Subversion Repositories filter_foundry

Rev

Rev 283 | Rev 301 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
259 daniel-mar 1
/*
268 daniel-mar 2
    This file is part of "Filter Foundry", a filter plugin for Adobe Photoshop
259 daniel-mar 3
        Copyright (C) 2003-2009 Toby Thain, toby@telegraphics.com.au
4
        Copyright (C) 2018-2021 Daniel Marschall, ViaThinkSoft
5
 
6
        This program is free software; you can redistribute it and/or modify
7
        it under the terms of the GNU General Public License as published by
8
        the Free Software Foundation; either version 2 of the License, or
9
        (at your option) any later version.
10
 
11
        This program is distributed in the hope that it will be useful,
12
        but WITHOUT ANY WARRANTY; without even the implied warranty of
13
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
        GNU General Public License for more details.
15
 
16
        You should have received a copy of the GNU General Public License
17
        along with this program; if not, write to the Free Software
18
        Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
*/
20
 
21
//#include <stdio.h>
22
//#include <sound.h>
23
 
24
#include "ff.h"
25
 
26
#include "node.h"
27
#include "funcs.h"
28
#include "y.tab.h"
29
#include "scripting.h"
30
#include <math.h>
31
#include "PIBufferSuite.h"
32
 
33
// GIMP (PSPI) and IrfanView preserve neither *data(gdata), nor pb->parameters between invocations!
34
// For debugging, we can simulate it here
35
//#define DEBUG_SIMULATE_GIMP
36
 
264 daniel-mar 37
// Used to find out which host signatures and memory settings a plugin host has
38
//#define SHOW_HOST_DEBUG
39
 
259 daniel-mar 40
struct node *tree[4];
41
char *err[4];
42
int errpos[4],errstart[4],nplanes,cnvused,chunksize,toprow;
43
value_type slider[8],cell[NUM_CELLS],map[4][0x100];
44
char *expr[4];
45
// long maxSpace;
46
globals_t *gdata;
47
FilterRecordPtr gpb;
48
 
49
#ifdef MAC_ENV
50
        #define HINSTANCE HANDLE
51
        #define hDllInstance NULL /* fake this Windows-only global */
52
#endif
53
 
54
#ifdef WIN_ENV
55
#include "manifest.h"
56
#endif
57
 
58
extern struct sym_rec predefs[];
59
extern int nplanes,varused[];
60
 
61
int checkandinitparams(Handle params);
62
 
63
// MPW MrC requires prototype
64
DLLEXPORT MACPASCAL
65
void ENTRYPOINT(short selector,FilterRecordPtr pb,intptr_t *data,short *result);
66
 
276 daniel-mar 67
unsigned long get_parm_hash(PARM_T *parm) {
259 daniel-mar 68
        unsigned long hash;
69
        int i;
70
 
276 daniel-mar 71
        hash = djb2((char*)parm->category);
72
        hash += djb2((char*)parm->title);
73
        hash += djb2((char*)parm->copyright);
74
        hash += djb2((char*)parm->author);
75
        for (i = 0; i < 4; i++) hash += hash += djb2((char*)parm->map[i]);
76
        for (i = 0; i < 8; i++) hash += hash += djb2((char*)parm->ctl[i]);
77
        for (i = 0; i < 4; i++) hash += hash += djb2((char*)parm->formula[i]);
259 daniel-mar 78
 
79
        return hash;
80
}
81
 
82
DLLEXPORT MACPASCAL
83
void ENTRYPOINT(short selector, FilterRecordPtr pb, intptr_t *data, short *result){
84
        static Boolean wantdialog = false;
85
        static Boolean premiereWarnedOnce = false;
86
        OSErr e = noErr;
87
        char *reason;
284 daniel-mar 88
 
89
        #ifdef SHOW_HOST_DEBUG
90
        char* tmp;
91
        #endif
268 daniel-mar 92
 
93
        #ifdef WIN_ENV
259 daniel-mar 94
        // For Windows, we use an activation context to enforce that our Manifest resource will
95
        // be used. This allows us to use Visual Styles, even if the host application does not
96
        // support it.
97
        ManifestActivationCtx manifestVars;
98
        BOOL activationContextUsed;
268 daniel-mar 99
        #endif
259 daniel-mar 100
 
284 daniel-mar 101
        // ---------------------------------------------------------------------
102
 
103
        EnterCodeResource();
104
 
283 daniel-mar 105
        #ifdef WIN_ENV
106
        // The first 64KB of address space is always invalid
107
        if ((intptr_t)result <= 0xffff) {
108
                // When the 8BF file is analyzed with VirusTotal.com, it will invoke each
109
                // exported function by calling
110
                //    C:\Windows\System32\rundll32.exe rundll32.exe FilterFoundry.8bf,PluginMain
111
                // But RunDLL32 requires following signature:
112
                //    void CALLBACK EntryPoint(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow);
113
                // Obviously, this will cause an Exception. (It crashes at *result=e because result is 0xA)
114
                // Here is the problem: The crash will be handled by WerFault.exe inside the
115
                // VirusTotal virtual machine. WerFault connects to various servers (9 DNS resolutions!) and does
116
                // a lot of weird things, but VirusTotal thinks that our plugin does all that stuff,
117
                // and so they mark our plugin as "malware"!
118
                // This is a problem with VirusTotal! It shall not assume that WerFault.exe actions are our actions!
119
                // Even processes like "MicrosoftEdgeUpdate.exe" and "SpeechRuntime.exe" are reported to be our
120
                // actions, although they have nothing to do with us!
121
                // See https://www.virustotal.com/gui/file/1f1012c567208186be455b81afc1ee407ae6476c197d633c70cc70929113223a/behavior
122
                // 
123
                // TODO: Not 100% sure if the calling convention is correct...
124
                //       are we corrupting the stack? At least WER isn't triggered...
125
                return;
126
        }
127
        #endif
284 daniel-mar 128
 
264 daniel-mar 129
        #ifdef SHOW_HOST_DEBUG
284 daniel-mar 130
        tmp = (char*)malloc(512);
131
        sprintf(tmp, "Host signature: '%c%c%c%c' (%d)\nMaxSpace32 = %d\nMaxSpace64 = %lld\nNum buffer procs: %d", (pb->hostSig >> 24) & 0xFF, (pb->hostSig >> 16) & 0xFF, (pb->hostSig >> 8) & 0xFF, pb->hostSig & 0xFF, pb->hostSig, pb->maxSpace, pb->maxSpace64, pb->bufferProcs->numBufferProcs);
132
        simplealert(tmp);
264 daniel-mar 133
        #endif
259 daniel-mar 134
 
135
        if (pb->hostSig == HOSTSIG_ADOBE_PREMIERE) {
136
                // DM 19.07.2021 : Tried running the 8BF file in Adobe Premiere 5 (yes, that's possible,
137
                // and there is even a FilterFactory for Premeire!),
138
                // but it crashes in evalpixel() where there is write-access to the "outp".
139
                // Probably the canvas structure is different (maybe it contains frames to achieve transitions?)
140
                if (!premiereWarnedOnce) {
141
                        simplealert(_strdup("This version of Filter Foundry is not compatible with Adobe Premiere!"));
142
                }
143
                premiereWarnedOnce = true;
144
                *result = errPlugInHostInsufficient;
145
                return;
146
        }
147
 
148
        #ifdef DEBUG_SIMULATE_GIMP
149
        *data = 0;
150
        pb->parameters = pb->handleProcs->newProc(1);
151
        #endif
152
 
153
        // Register "gdata" that contains the PARM information and other things which need to be persistant
154
        // and preserve then in *data
155
        // TODO: memory leak? where is the stuff freed?
156
        if (selector != filterSelectorAbout && !*data) {
157
                /*
158
                PSBufferSuite1* pSBufferSuite32 = NULL;
159
 
160
                if ((pb->sSPBasic == 0) ||
161
                        (pb->sSPBasic->AcquireSuite(kPSBufferSuite, kPSBufferSuiteVersion1, (const void**)&pSBufferSuite32)) ||
162
                        (pSBufferSuite32 == NULL))
163
                {
164
                                // Old deprecated buffer suite
165
                                BufferID tempId;
166
                                if ((*result = pb->bufferProcs->allocateProc(sizeof(globals_t), &tempId))) return;
167
                                *data = (intptr_t)pb->bufferProcs->lockProc(tempId, true);
168
                                gdata = (globals_t*)*data;
169
                }
170
                else
171
                {
172
                                // New buffer suite (but only 32-bit version 1, because version 2 has problems with old Photoshop versions)
173
                                // Windows Photoshop 7 and CS 2 accepts kPSBufferSuiteVersion2, but doesn't correctly implement it:
174
                                // The symbols "New" and "GetSpace64" point to memory memory addresses outside the Photoshop.exe address range.
175
                                // (Other Photoshop versions were not tested.)
176
                                // 64-bit support for Windows was established in Photoshop CS 4,
177
                                // and PSBufferSuite2 was first documented in SDK CS 6.
178
                                // So, kPSBufferSuiteVersion2 probably was partically implemented as hidden "Work in progress" version
179
                                // before it was publicly documented.
180
                                // Side note:  pb->bufferSpace64/pb->maxSpace64 was documented in SDK CC 2017.
181
                                //             pb->bufferProcs->allocateProc64/spaceProc64 was documented in SDK CS 6.
182
                                unsigned32 siz = sizeof(globals_t);
183
                                *data = (intptr_t)pSBufferSuite32->New(&siz, siz);
184
                                if ((*data == 0) || (siz == 0)) {
185
                                                *result = errPlugInHostInsufficient; // TODO: what is the correct error code for "out of memory"?
186
                                                return;
187
                                }
188
                                gdata = (globals_t*)*data;
189
                                pb->sSPBasic->ReleaseSuite(kPSBufferSuite, kPSBufferSuiteVersion1);
190
                }
191
                gdata->standalone = gdata->parmloaded = false;
192
                */
193
 
194
                // We have 3 options:
195
                // - The deprecated buffer suite (pb->bufferProcs), works fine
196
                // - The recommended buffer suite (kPSBufferSuite), does NOT work (causes memory corruption?) and is not available on some hosts!
197
                //   Either I do something wrong, or maybe it cannot be used to store data between invocations?
198
                // - Using malloc(), which works also fine and is more independent from the host and easier
199
                *data = (intptr_t)malloc(sizeof(globals_t));
200
                if (*data == 0) return;
201
                gdata = (globals_t*)*data;
202
                gdata->standalone = gdata->parmloaded = false; // they will be set later
203
        }
204
        else {
205
                // We have data from the previous invocation. Use it instead
206
                gdata = (globals_t*)*data;
207
        }
208
 
209
        #ifdef WIN_ENV
210
        activationContextUsed = ActivateManifest((HMODULE)hDllInstance, 1, &manifestVars);
211
        #endif
212
 
213
        gpb = pb;
214
 
215
        nplanes = MIN(pb->planes,4);
216
 
217
        switch (selector){
218
        case filterSelectorAbout:
219
                if (!gdata) {
220
                        gdata = (globals_t*)malloc(sizeof(globals_t));
221
                        if (!gdata) break;
222
                        gdata->standalone = gdata->parmloaded = readPARMresource((HMODULE)hDllInstance,&reason,READ_OBFUSC);
223
                        DoAbout((AboutRecordPtr)pb);
224
                        free(gdata);
225
                        gdata = NULL;
226
                } else {
227
                        DoAbout((AboutRecordPtr)pb);
228
                }
229
                break;
230
        case filterSelectorParameters:
231
                wantdialog = true;
232
                break;
233
        case filterSelectorPrepare:
234
                DoPrepare(pb);
235
                init_symtab(predefs); // ready for parser calls
236
                init_trigtab();
237
                break;
238
        case filterSelectorStart:
239
                if (HAS_BIG_DOC(pb)) {
240
                        // The BigDocument structure is required if the document is larger than 30,000 pixels
241
                        // It deprecates imageSize, filterRect, inRect, outRect, maskRect, floatCoord, and wholeSize.
242
                        // By setting it to nonzero, we communicate to Photoshop that we support the BigDocument structure.
243
                        pb->bigDocumentData->PluginUsing32BitCoordinates = true;
244
                }
245
 
246
                /* initialise the parameter handle that Photoshop keeps for us */
247
                if(!pb->parameters)
248
                        pb->parameters = PINEWHANDLE(1); // don't set initial size to 0, since some hosts (e.g. GIMP/PSPI) are incompatible with that.
249
 
250
                wantdialog |= checkandinitparams(pb->parameters);
251
 
252
                /* wantdialog = false means that we never got a Parameters call, so we're not supposed to ask user */
253
                if( wantdialog && (!gdata->standalone || gdata->parm.popDialog) ){
254
                        if( maindialog(pb) ){
255
                                if (!host_preserves_parameters()) {
264 daniel-mar 256
                                        /* Workaround for GIMP/PSPI, to avoid that formulas vanish when you re-open the main window.
257
                                           The reason is a bug in PSPI: The host should preserve the value of pb->parameters, which PSPI does not do.
258
                                           Also, all global variables are unloaded, so the plugin cannot preserve any data.
259
                                           Workaround in FF 1.7: If the host GIMP is detected, then a special mode will be activated.
260
                                           This mode saves the filter data into a temporary file "FilterFoundryXX.afs" and loads it
261
                                           when the window is opened again. */
262
                                        // Workaround: Save settings in "FilterFoundryXX.afs" if the host does not preserve pb->parameters
263
                                        char outfilename[255];
264
                                        char* tempdir;
265
                                        int hash;
266
                                        StandardFileReply sfr;
267
                                        char* bakexpr[4];
259 daniel-mar 268
 
264 daniel-mar 269
                                        sfr.sfGood = true;
270
                                        sfr.sfReplacing = true;
271
                                        sfr.sfType = PS_FILTER_FILETYPE;
259 daniel-mar 272
 
264 daniel-mar 273
                                        tempdir = getenv("TMP");
274
                                        #ifdef WIN_ENV
275
                                        if (strlen(tempdir) > 0) strcat(tempdir, "\\");
276
                                        #else
277
                                        if (strlen(tempdir) > 0) strcat(tempdir, "/");
278
                                        #endif
259 daniel-mar 279
 
276 daniel-mar 280
                                        hash = (gdata->standalone) ? get_parm_hash(&gdata->parm) : 0;
264 daniel-mar 281
                                        sprintf(outfilename, "%sFilterFoundry%d.afs", tempdir, hash);
282
 
283
                                        myc2pstrcpy(sfr.sfFile.name, outfilename);
284
                                        #ifdef WIN_ENV
285
                                        sfr.nFileExtension = (WORD)(strlen(outfilename) - strlen(".afs") + 1);
286
                                        #endif
287
                                        sfr.sfScript = 0; // FIXME: is that ok?
288
 
289
                                        // We only want the parameters (ctl,map) in the temporary .afs file
290
                                        // It is important to remove the expressions, otherwise they would be
291
                                        // revealed in the temporary files.
272 daniel-mar 292
                                        bakexpr[0] = expr[0]; // moved out of the if-definition to make the compiler happy
293
                                        bakexpr[1] = expr[1];
294
                                        bakexpr[2] = expr[2];
295
                                        bakexpr[3] = expr[3];
264 daniel-mar 296
                                        if (gdata->standalone) {
297
                                                expr[0] = _strdup("r");
298
                                                expr[1] = _strdup("g");
299
                                                expr[2] = _strdup("b");
300
                                                expr[3] = _strdup("a");
259 daniel-mar 301
                                        }
264 daniel-mar 302
 
303
                                        savefile(&sfr);
304
 
305
                                        if (gdata->standalone) {
306
                                                free(expr[0]); expr[0] = bakexpr[0];
307
                                                free(expr[1]); expr[1] = bakexpr[1];
308
                                                free(expr[2]); expr[2] = bakexpr[2];
309
                                                free(expr[3]); expr[3] = bakexpr[3];
310
                                        }
311
                                } else {
312
                                        /* update stored parameters from new user settings */
313
                                        saveparams(pb->parameters);
259 daniel-mar 314
                                }
315
                        }else
316
                                e = userCanceledErr;
317
                }
318
                wantdialog = false;
319
 
320
                if(!e){
321
                        if(setup(pb)){
322
                                DoStart(pb);
323
                        }else{
324
                                SYSBEEP(1);
325
                                e = filterBadParameters;
326
                        }
327
                }
328
                break;
329
        case filterSelectorContinue:
330
                e = DoContinue(pb);
331
                break;
332
        case filterSelectorFinish:
333
                DoFinish(pb);
334
                break;
335
        default:
336
                e = filterBadParameters;
337
        }
338
 
339
        *result = e;
340
 
341
        #ifdef WIN_ENV
342
        if (activationContextUsed) DeactivateManifest(&manifestVars);
343
        #endif
344
 
345
        ExitCodeResource();
346
}
347
 
348
int checkandinitparams(Handle params){
349
        char *reasonstr,*reason;
350
        int i,bUninitializedParams;
351
        Boolean showdialog;
352
 
353
        if (!host_preserves_parameters()) {
354
                // Workaround: Load settings in "FilterFoundryXX.afs" if host does not preserve pb->parameters
355
                char outfilename[255];
356
                char* tempdir;
357
                int hash;
358
                Boolean isStandalone;
359
                StandardFileReply sfr;
264 daniel-mar 360
                char* bakexpr[4];
361
 
259 daniel-mar 362
                sfr.sfGood = true;
363
                sfr.sfReplacing = true;
364
                sfr.sfType = PS_FILTER_FILETYPE;
365
 
366
                // We need to set gdata->standalone after loadfile(), but we must call readPARMresource() before loadfile()
367
                // Reason: readPARMresource() reads parameters from the DLL while loadfile() reads parameters from the AFS file
368
                // But loadfile() will reset gdata->standalone ...
369
                isStandalone = readPARMresource((HMODULE)hDllInstance, &reason, READ_OBFUSC);
370
 
264 daniel-mar 371
                tempdir = getenv("TMP");
372
                #ifdef WIN_ENV
373
                if (strlen(tempdir) > 0) strcat(tempdir, "\\");
374
                #else
375
                if (strlen(tempdir) > 0) strcat(tempdir, "/");
376
                #endif
259 daniel-mar 377
 
276 daniel-mar 378
                hash = (isStandalone) ? get_parm_hash(&gdata->parm) : 0;
264 daniel-mar 379
                sprintf(outfilename, "%sFilterFoundry%d.afs", tempdir, hash);
259 daniel-mar 380
 
264 daniel-mar 381
                myc2pstrcpy(sfr.sfFile.name, outfilename);
382
                #ifdef WIN_ENV
383
                sfr.nFileExtension = (WORD)(strlen(outfilename) - strlen(".afs") + 1);
384
                #endif
385
                sfr.sfScript = 0; // FIXME: is that ok?
259 daniel-mar 386
 
264 daniel-mar 387
                // We only want the parameters (ctl,map) in the temporary .afs file
388
                if (isStandalone) {
389
                        bakexpr[0] = my_strdup(expr[0]);
390
                        bakexpr[1] = my_strdup(expr[1]);
391
                        bakexpr[2] = my_strdup(expr[2]);
392
                        bakexpr[3] = my_strdup(expr[3]);
393
                }
394
 
395
                if (loadfile(&sfr, &reason)) {
396
                        gdata->standalone = gdata->parmloaded = isStandalone;
397
 
398
                        if (isStandalone) {
399
                                free(expr[0]); expr[0] = bakexpr[0];
400
                                free(expr[1]); expr[1] = bakexpr[1];
401
                                free(expr[2]); expr[2] = bakexpr[2];
402
                                free(expr[3]); expr[3] = bakexpr[3];
259 daniel-mar 403
                        }
264 daniel-mar 404
 
405
                        return true;
259 daniel-mar 406
                }
407
        }
408
 
409
        if( (bUninitializedParams = !(params && readparams(params,false,&reasonstr))) ){
410
                /* either the parameter handle was uninitialised,
411
                   or the parameter data couldn't be read; set default values */
412
 
413
                // see if saved parameters exist
414
                gdata->standalone = gdata->parmloaded = readPARMresource((HMODULE)hDllInstance,&reason,READ_OBFUSC);
415
 
416
 
417
                if(!gdata->standalone){
418
                        // no saved settings (not standalone)
419
                        for(i = 0; i < 8; ++i)
420
                                slider[i] = i*10+100;
421
                        for(i = 0; i < 4; ++i)
422
                                if(expr[i])
423
                                        free(expr[i]);
424
                        if(gpb->imageMode == plugInModeRGBColor){
425
                                expr[0] = _strdup("r");
426
                                expr[1] = _strdup("g");
427
                                expr[2] = _strdup("b");
428
                                expr[3] = _strdup("a");
429
                        }else{
430
                                expr[0] = _strdup("c");
431
                                expr[1] = _strdup("c");
432
                                expr[2] = _strdup("c");
433
                                expr[3] = _strdup("c");
434
                        }
435
                }
436
        }
437
 
438
        // let scripting system change parameters, if we're scripted;
439
        // user may want to force display of dialog during scripting playback
440
        switch (ReadScriptParamsOnRead()) {
441
        case SCR_SHOW_DIALOG:
442
                showdialog = true;
443
                break;
444
        case SCR_HIDE_DIALOG:
445
                showdialog = false;
446
                break;
447
        default:
448
        case SCR_NO_SCRIPT:
449
                showdialog = bUninitializedParams;
450
                break;
451
        }
452
 
453
        saveparams(params);
454
 
455
        return showdialog;
456
}
457
 
458
Boolean host_preserves_parameters() {
459
        #ifdef DEBUG_SIMULATE_GIMP
460
        return false;
461
        #endif
462
 
463
        if (gpb->hostSig == HOSTSIG_GIMP) return false;
464
        if (gpb->hostSig == HOSTSIG_IRFANVIEW) return false;
465
 
466
        // We just assume the other hosts preserve the parameters
467
        return true;
468
}
469
 
470
int64_t maxspace(){
471
        // Please see "Hosts.md" for details about the MaxSpace implementations of tested plugins
472
 
473
        // Plugins that don't support MaxSpace64 shall set the field to zero; then we will use MaxSpace instead.
474
        // Also check "gpb->bufferProcs->numBufferProcs" to see if 64 bit API is available
475
        if ((gpb->bufferProcs->numBufferProcs >= 8) && (gpb->maxSpace64 > 0)) {
476
                uint64_t maxSpace64 = gpb->maxSpace64;
477
 
478
                return maxSpace64;
479
        } else {
480
                // Note: If maxSpace gets converted from Int32 to unsigned int, we can reach up to 4 GB RAM. However, after this, there will be a wrap to 0 GB again.
481
                unsigned int maxSpace32 = (unsigned int) gpb->maxSpace;
482
                uint64_t maxSpace64 = maxSpace32;
483
 
484
                if (gpb->hostSig == HOSTSIG_IRFANVIEW) maxSpace64 *= 1024; // IrfanView is giving Kilobytes instead of Bytes
485
                //if (gpb->hostSig == HOSTSIG_SERIF_PHOTOPLUS) maxSpace64 *= 1024; // TODO: Serif PhotoPlus also gives Kilobytes instead of bytes. But since it uses not a unique host signature, there is nothing we can do???
486
 
487
                return maxSpace64;
488
        }
489
}
490
 
491
Boolean maxspace_available() {
492
        // Please see "Hosts.md" for details about the MaxSpace implementations of tested plugins
493
 
494
        // GIMP PSPI sets MaxSpace to hardcoded 100 MB
495
        if (gpb->hostSig == HOSTSIG_GIMP) return false;
496
 
497
        // HOSTSIG_PAINT_NET sets MaxSpace to hardcoded 1 GB, see https://github.com/0xC0000054/PSFilterPdn/issues/5
498
        // Comment by the host author "This was done to avoid any compatibility issues with plugins handling 2 GB - 1"
499
        if (gpb->hostSig == HOSTSIG_PAINT_NET) return false;
500
 
501
        return true;
502
}
503
 
504
void DoPrepare(FilterRecordPtr pb){
505
        int i;
506
 
507
        for(i = 4; i--;){
508
                if(expr[i]||tree[i]) DBG("expr[] or tree[] non-NULL in Prepare!");
509
                expr[i] = NULL;
510
                tree[i] = NULL;
511
        }
512
 
513
        // Commented out by DM, 18 Dec 2018:
514
        // This code did not work on systems with 8 GB RAM:
515
        /*
516
        long space = (pb->maxSpace*9)/10; // don't ask for more than 90% of available memory
517
 
518
        maxSpace = 512L<<10; // this is a wild guess, actually
519
        if(maxSpace > space)
520
                        maxSpace = space;
521
        pb->maxSpace = maxSpace;
522
        */
523
 
524
        // New variant:
525
        if (maxspace_available()) {
526
                pb->maxSpace = (int32)ceil((maxspace()/10.)*9); // don't ask for more than 90% of available memory
527
                // FIXME: Also maxSpace64
528
        }
529
}
530
 
531
void RequestNext(FilterRecordPtr pb,long toprow){
532
        /* Request next block of the image */
533
 
534
        pb->inLoPlane = pb->outLoPlane = 0;
535
        pb->inHiPlane = pb->outHiPlane = nplanes-1;
536
 
537
        if (HAS_BIG_DOC(pb)) {
538
                // if any of the formulae involve random access to image pixels,
539
                // ask for the entire image
540
                if (needall) {
541
                        SETRECT(BIGDOC_IN_RECT(pb), 0, 0, BIGDOC_IMAGE_SIZE(pb).h, BIGDOC_IMAGE_SIZE(pb).v);
542
                } else {
543
                        // TODO: This does not work with GIMP. So, if we are using GIMP, we should
544
                        //       somehow always use "needall=true", and/or find out why this doesn't work
545
                        //       with GIMP.
546
 
547
                        // otherwise, process the filtered area, by chunksize parts
548
                        BIGDOC_IN_RECT(pb).left = BIGDOC_FILTER_RECT(pb).left;
549
                        BIGDOC_IN_RECT(pb).right = BIGDOC_FILTER_RECT(pb).right;
550
                        BIGDOC_IN_RECT(pb).top = (int32)toprow;
551
                        BIGDOC_IN_RECT(pb).bottom = (int32)MIN(toprow + chunksize, BIGDOC_FILTER_RECT(pb).bottom);
552
 
553
                        if (cnvused) {
554
                                // cnv() needs one extra pixel in each direction
555
                                if (BIGDOC_IN_RECT(pb).left > 0)
556
                                        --BIGDOC_IN_RECT(pb).left;
557
                                if (BIGDOC_IN_RECT(pb).right < BIGDOC_IMAGE_SIZE(pb).h)
558
                                        ++BIGDOC_IN_RECT(pb).right;
559
                                if (BIGDOC_IN_RECT(pb).top > 0)
560
                                        --BIGDOC_IN_RECT(pb).top;
561
                                if (BIGDOC_IN_RECT(pb).bottom < BIGDOC_IMAGE_SIZE(pb).v)
562
                                        ++BIGDOC_IN_RECT(pb).bottom;
563
                        }
564
                }
565
                BIGDOC_OUT_RECT(pb) = BIGDOC_FILTER_RECT(pb);
566
                /*
567
                {char s[0x100];sprintf(s,"RequestNext needall=%d inRect=(%d,%d,%d,%d) filterRect=(%d,%d,%d,%d)",
568
                                needall,
569
                                BIGDOC_IN_RECT(pb).left,BIGDOC_IN_RECT(pb).top,BIGDOC_IN_RECT(pb).right,BIGDOC_IN_RECT(pb).bottom,
570
                                BIGDOC_FILTER_RECT(pb).left,BIGDOC_FILTER_RECT(pb).top,BIGDOC_FILTER_RECT(pb).right,BIGDOC_FILTER_RECT(pb).bottom);dbg(s);}
571
                */
572
        } else {
573
                // if any of the formulae involve random access to image pixels,
574
                // ask for the entire image
575
                if (needall) {
576
                        SETRECT(IN_RECT(pb), 0, 0, IMAGE_SIZE(pb).h, IMAGE_SIZE(pb).v);
577
                }
578
                else {
579
                        // TODO: This does not work with GIMP. So, if we are using GIMP, we should
580
                        //       somehow always use "needall=true", and/or find out why this doesn't work
581
                        //       with GIMP.
582
 
583
                        // otherwise, process the filtered area, by chunksize parts
584
                        IN_RECT(pb).left = FILTER_RECT(pb).left;
585
                        IN_RECT(pb).right = FILTER_RECT(pb).right;
586
                        IN_RECT(pb).top = (int16)toprow;
587
                        IN_RECT(pb).bottom = (int16)MIN(toprow + chunksize, FILTER_RECT(pb).bottom);
588
 
589
                        if (cnvused) {
590
                                // cnv() needs one extra pixel in each direction
591
                                if (IN_RECT(pb).left > 0)
592
                                        --IN_RECT(pb).left;
593
                                if (IN_RECT(pb).right < IMAGE_SIZE(pb).h)
594
                                        ++IN_RECT(pb).right;
595
                                if (IN_RECT(pb).top > 0)
596
                                        --IN_RECT(pb).top;
597
                                if (IN_RECT(pb).bottom < IMAGE_SIZE(pb).v)
598
                                        ++IN_RECT(pb).bottom;
599
                        }
600
                }
601
                OUT_RECT(pb) = FILTER_RECT(pb);
602
                /*
603
                {char s[0x100];sprintf(s,"RequestNext needall=%d inRect=(%d,%d,%d,%d) filterRect=(%d,%d,%d,%d)",
604
                                needall,
605
                                IN_RECT(pb).left,IN_RECT(pb).top,IN_RECT(pb).right,IN_RECT(pb).bottom,
606
                                FILTER_RECT(pb).left,FILTER_RECT(pb).top,FILTER_RECT(pb).right,FILTER_RECT(pb).bottom);dbg(s);}
607
                */
608
        }
609
}
610
 
611
void DoStart(FilterRecordPtr pb){
264 daniel-mar 612
        /* Global variable "needall": if src() or rad() functions are used, random access to the image data is required,
613
           so we must request the entire image in a single chunk, otherwise we will use chunksize "CHUNK_ROWS". */
259 daniel-mar 614
        if (HAS_BIG_DOC(pb)) {
615
                chunksize = needall ? (BIGDOC_FILTER_RECT(pb).bottom - BIGDOC_FILTER_RECT(pb).top) : CHUNK_ROWS;
616
                toprow = BIGDOC_FILTER_RECT(pb).top;
617
        } else {
618
                chunksize = needall ? (FILTER_RECT(pb).bottom - FILTER_RECT(pb).top) : CHUNK_ROWS;
619
                toprow = FILTER_RECT(pb).top;
620
        }
621
        RequestNext(pb, toprow);
622
}
623
 
624
OSErr DoContinue(FilterRecordPtr pb){
625
        OSErr e = noErr;
626
        long outoffset;
627
 
628
        if (HAS_BIG_DOC(pb)) {
629
                VRect fr;
630
                if (needall) {
631
                        fr = BIGDOC_FILTER_RECT(pb);  // filter whole selection at once
632
                } else if (cnvused) {
633
                        // we've requested one pixel extra all around
634
                        // (see RequestNext()), just for access purposes. But filter
635
                        // original selection only.
636
                        fr.left = BIGDOC_FILTER_RECT(pb).left;
637
                        fr.right = BIGDOC_FILTER_RECT(pb).right;
638
                        fr.top = toprow;
639
                        fr.bottom = MIN(toprow + chunksize, BIGDOC_FILTER_RECT(pb).bottom);
640
                } else {  // filter whatever portion we've been given
641
                        fr = BIGDOC_IN_RECT(pb);
642
                }
643
 
644
                outoffset = (long)pb->outRowBytes * (fr.top - BIGDOC_OUT_RECT(pb).top)
645
                        + (long)nplanes * (fr.left - BIGDOC_OUT_RECT(pb).left);
646
 
647
                if (!(e = process_scaled_bigdoc(pb, true, fr, fr,
648
                        (Ptr)pb->outData + outoffset, pb->outRowBytes, 1.)))
649
                {
650
                        toprow += chunksize;
651
                        if (toprow < BIGDOC_FILTER_RECT(pb).bottom)
652
                                RequestNext(pb, toprow);
653
                        else {
654
                                SETRECT(BIGDOC_IN_RECT(pb), 0, 0, 0, 0);
655
                                BIGDOC_OUT_RECT(pb) = BIGDOC_MASK_RECT(pb) = BIGDOC_IN_RECT(pb);
656
                        }
657
                }
658
        } else {
659
                Rect fr;
660
                if (needall) {
661
                        fr = FILTER_RECT(pb);  // filter whole selection at once
662
                } else if (cnvused) {
663
                        // we've requested one pixel extra all around
664
                        // (see RequestNext()), just for access purposes. But filter
665
                        // original selection only.
666
                        fr.left = FILTER_RECT(pb).left;
667
                        fr.right = FILTER_RECT(pb).right;
668
                        fr.top = toprow;
669
                        fr.bottom = MIN(toprow + chunksize, FILTER_RECT(pb).bottom);
670
                } else {  // filter whatever portion we've been given
671
                        fr = IN_RECT(pb);
672
                }
673
 
674
                outoffset = (long)pb->outRowBytes*(fr.top - OUT_RECT(pb).top)
675
                        + (long)nplanes*(fr.left - OUT_RECT(pb).left);
676
 
677
                if(!(e = process_scaled_olddoc(pb, true, fr, fr,
678
                        (Ptr)pb->outData+outoffset, pb->outRowBytes, 1.)))
679
                {
680
                        toprow += chunksize;
681
                        if(toprow < FILTER_RECT(pb).bottom)
682
                                RequestNext(pb,toprow);
683
                        else{
684
                                SETRECT(IN_RECT(pb),0,0,0,0);
685
                                OUT_RECT(pb) = MASK_RECT(pb) = IN_RECT(pb);
686
                        }
687
                }
688
        }
689
        return e;
690
}
691
 
692
void DoFinish(FilterRecordPtr pb){
693
        int i;
694
 
695
        WriteScriptParamsOnRead();
696
 
697
        for(i = 4; i--;){
698
                freetree(tree[i]);
699
                if(expr[i]) free(expr[i]);
700
        }
701
}