Subversion Repositories filter_foundry

Rev

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