Subversion Repositories filter_foundry

Rev

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