Subversion Repositories filter_foundry

Rev

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