Subversion Repositories filter_foundry

Rev

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