Subversion Repositories filter_foundry

Rev

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