Subversion Repositories filter_foundry

Rev

Rev 483 | Rev 491 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

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