Subversion Repositories filter_foundry

Rev

Rev 555 | 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.net
  4.     Copyright (C) 2018-2023 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. TCHAR *err[4];
  44. int errpos[4],errstart[4],nplanes,cnvused,chunksize,toprow;
  45. value_type cell[NUM_CELLS];
  46.  
  47. // this is the only memory area that keeps preserved by Photoshop:
  48. globals_t *gdata;
  49. FilterRecordPtr gpb;
  50.  
  51. #ifdef MAC_ENV
  52. #define HINSTANCE HANDLE
  53. #define hDllInstance NULL /* fake this Windows-only global */
  54. #endif
  55.  
  56. #ifdef WIN_ENV
  57. #include "manifest.h"
  58. #endif
  59.  
  60. extern struct sym_rec predefs[];
  61. extern int nplanes,varused[];
  62.  
  63. int checkandinitparams(Handle params);
  64.  
  65. // MPW MrC requires prototype
  66. DLLEXPORT MACPASCAL
  67. void ENTRYPOINT(short selector,FilterRecordPtr pb,intptr_t *data,short *result);
  68.  
  69. unsigned long parm_hash(PARM_T *parm) {
  70.         unsigned long hash;
  71.         int i;
  72.  
  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]);
  80.  
  81.         return hash;
  82. }
  83.  
  84. size_t get_temp_afs(LPTSTR outfilename, Boolean isStandalone, PARM_T *parm) {
  85.         char* atempdir;
  86.         int hash;
  87.         size_t i, j;
  88.         TCHAR out[MAX_PATH + 1];
  89.         char ahash[20];
  90.  
  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.  
  98.         #ifdef WIN_ENV
  99.         if (xstrlen(out) > 0) xstrcat(out, TEXT("\\"));
  100.         #else
  101.         if (xstrlen(out) > 0) xstrcat(out, TEXT("/"));
  102.         #endif
  103.  
  104.         hash = (isStandalone) ? parm_hash(parm) : 0;
  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);
  119. }
  120.  
  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];
  138.         if (GetModuleFileNameA(hinst, exename, MAX_PATH) == 0) return false;
  139.         return stristr(exename, "rundll32") != NULL;
  140. }
  141.  
  142. void CALLBACK FakeRundll32(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow) {
  143.         UNREFERENCED_PARAMETER(hwnd);
  144.         UNREFERENCED_PARAMETER(hinst);
  145.         UNREFERENCED_PARAMETER(lpszCmdLine);
  146.         UNREFERENCED_PARAMETER(nCmdShow);
  147.  
  148.         /*
  149.         char* tmp = (char*)malloc(512);
  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.         }
  155.         */
  156.  
  157.         simplealert_id(MSG_RUNDLL_ERR_ID);
  158.  
  159.         return;
  160. }
  161.  
  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:
  170.  
  171.         // (Method 1)
  172.         // 1. The deprecated Standard Buffer Suite (pb->bufferProcs) - works fine!
  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.         */
  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?
  188.         //    Also, the buffer suite is only available on the Adobe Photoshop host application.
  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.         */
  195.  
  196.         // (Method 3)
  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.
  200.         /*
  201.         *data = (intptr_t)malloc(sizeof(globals_t));
  202.         if (*data) memset((void*)*data, 0, sizeof(globals_t));
  203.         */
  204.  
  205.         // (Method 4)
  206.         // 4. Using PLUGIN.DLL:NewPtr(). This does FilterFactory 3.0.4, but requires an Adobe host.
  207.         //    In Plugin.dll, the function NewPtr() and NewPtrClear() are implemented as GlobalAlloc/GlobalLock.
  208.         //    Nothing special.
  209.  
  210.         // (Method 5)
  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).
  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.
  218.         *data = (intptr_t)NewPtrClear(sizeof(globals_t));
  219. }
  220.  
  221. DLLEXPORT MACPASCAL
  222. void ENTRYPOINT(short selector, FilterRecordPtr pb, intptr_t *data, short *result){
  223.         static Boolean wantdialog = false;
  224.         static Boolean premiereWarnedOnce = false;
  225.  
  226.         #ifdef SHOW_HOST_DEBUG
  227.         char* tmp;
  228.         #endif
  229.  
  230.         #ifdef WIN_ENV
  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;
  236.         #endif
  237.  
  238.         // ---------------------------------------------------------------------
  239.  
  240.         EnterCodeResource();
  241.  
  242.         #ifdef WIN_ENV
  243.         activationContextUsed = ActivateManifest((HMODULE)hDllInstance, 1, &manifestVars);
  244.         #endif
  245.  
  246.         #ifdef WIN_ENV
  247.         if ((intptr_t)result == SW_SHOWDEFAULT && CalledFromRunDLL32((HINSTANCE)pb)) {
  248.                 // When the 8BF file is analyzed with VirusTotal.com, it will invoke each
  249.                 // exported function by calling
  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.                 //
  254.                 // But RunDLL32 requires the following signature:
  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);
  258.                 //
  259.                 // Obviously, this will cause an Exception. (It crashes at *result=e because result is 0xA, which is SW_SHOWDEFAULT)
  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!
  265.                 // Even actions from processes like "MicrosoftEdgeUpdate.exe" and "SpeechRuntime.exe" are reported to be our
  266.                 // actions, although they have nothing to do with us!
  267.                 // See https://www.virustotal.com/gui/file/1f1012c567208186be455b81afc1ee407ae6476c197d633c70cc70929113223a/behavior
  268.                 //
  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.  
  272.                 FakeRundll32((HWND)(intptr_t)selector, (HINSTANCE)pb, (LPSTR)data, (int)(intptr_t)result);
  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.  
  275.                 goto endmain;
  276.         }
  277.         else {
  278.                 // will be changed if an error happens
  279.                 *result = noErr;
  280.         }
  281.         #endif
  282.  
  283.         #ifdef SHOW_HOST_DEBUG
  284.         tmp = (char*)malloc(512);
  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);
  286.         simplealert(tmp);
  287.         free(tmp);
  288.         #endif
  289.  
  290.         if (pb->hostSig == HOSTSIG_ADOBE_PREMIERE) {
  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!),
  293.                 // but it crashes in evalpixel() where there is write-access to the "outp".
  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)...
  296.                 // Maybe the canvas structure is different (maybe it contains frames to achieve transitions?)
  297.                 // TODO: make Filter Foundry compatible with Premiere!
  298.                 if (!premiereWarnedOnce) {
  299.                         simplealert_id(MSG_PREMIERE_COMPAT_ID);
  300.                 }
  301.                 premiereWarnedOnce = true;
  302.                 *result = errPlugInHostInsufficient;
  303.                 goto endmain;
  304.         }
  305.  
  306.         #ifdef DEBUG_SIMULATE_GIMP
  307.         *data = 0;
  308.         pb->parameters = pb->handleProcs->newProc(1);
  309.         #endif
  310.  
  311.         gpb = pb; // required for CreateDataPointer()
  312.  
  313.         if (selector != filterSelectorAbout && !*data) {
  314.                 // The filter was never called before. We allocate (zeroed) memory now.
  315.                 CreateDataPointer(data);
  316.                 if (!*data) {
  317.                         *result = memFullErr;
  318.                         goto endmain;
  319.                 }
  320.         }
  321.  
  322.         gdata = (globals_t*)*data;
  323.  
  324.         nplanes = MIN(pb->planes,4);
  325.  
  326.         switch (selector){
  327.         case filterSelectorAbout:
  328.                 if (!gdata) {
  329.                         Boolean parmReadOk;
  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).
  332.                         gdata = (globals_t*)malloc(sizeof(globals_t));
  333.                         if (!gdata) break;
  334.                         gdata->hWndMainDlg = (HWND)((PlatformData*)((AboutRecordPtr)pb)->platformData)->hwnd; // so that simplealert() works
  335.                         parmReadOk = (LOADING_OK == readPARMresource((HMODULE)hDllInstance));
  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);
  339.                                 if (gdata->obfusc) {
  340.                                         simplealert_id(MSG_INCOMPATIBLE_OBFUSCATION_ID);
  341.                                 }
  342.                                 else {
  343.                                         simplealert_id(MSG_INVALID_PARAMETER_DATA_ID);
  344.                                 }
  345.                         }
  346.                         else {
  347.                                 DoAbout((AboutRecordPtr)pb);
  348.                         }
  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:
  359.                 gdata->hWndMainDlg = 0;
  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.  
  376.                 if (!pb->parameters) {
  377.                         *result = memFullErr;
  378.                 }
  379.                 else
  380.                 {
  381.                         wantdialog |= checkandinitparams(pb->parameters);
  382.  
  383.                         /* wantdialog = false means that we never got a Parameters call, so we're not supposed to ask user */
  384.                         if (wantdialog && (!gdata->parm.standalone || gdata->parm.popDialog)) {
  385.                                 if (maindialog(pb)) {
  386.                                         if (!host_preserves_parameters()) {
  387.                                                 /* Workaround for GIMP/PSPI, to avoid that formulas vanish when you re-open the main window.
  388.                                                    The reason is a bug in PSPI: The host should preserve the value of pb->parameters, which PSPI does not do.
  389.                                                    Also, all global variables are unloaded, so the plugin cannot preserve any data.
  390.                                                    Workaround in FF 1.7: If the host GIMP is detected, then a special mode will be activated.
  391.                                                    This mode saves the filter data into a temporary file "FilterFoundryXX.afs" and loads it
  392.                                                    when the window is opened again. */
  393.                                                    // Workaround: Save settings in "FilterFoundryXX.afs" if the host does not preserve pb->parameters
  394.                                                 TCHAR outfilename[MAX_PATH + 1];
  395.                                                 StandardFileReply sfr;
  396.                                                 InternalState tmpState;
  397.                                                 FFSavingResult saveres;
  398.  
  399.                                                 sfr.sfGood = true;
  400.                                                 sfr.sfReplacing = true;
  401.                                                 sfr.sfType = PS_FILTER_FILETYPE;
  402.  
  403.                                                 get_temp_afs(&outfilename[0], gdata->parm.standalone, &gdata->parm);
  404.  
  405.                                                 xstrcpy(sfr.sfFile.szName, outfilename);
  406.                                                 #ifdef WIN_ENV
  407.                                                 sfr.nFileExtension = (WORD)(xstrlen(outfilename) - strlen(".afs") + 1);
  408.                                                 #endif
  409.                                                 sfr.sfScript = smSystemScript;
  410.  
  411.                                                 // We only want the parameters (ctl,map) in the temporary .afs file
  412.                                                 // It is important to remove the expressions, otherwise they would be
  413.                                                 // revealed in the temporary files (That might be bad for obfuscated filters).
  414.                                                 if (gdata->parm.standalone) {
  415.                                                         tmpState = saveInternalState();
  416.                                                         parm_reset(false, false, false, true);
  417.                                                 }
  418.  
  419.                                                 saveres = savefile_afs_pff_picotxt_guf(&sfr);
  420.  
  421.                                                 if (gdata->parm.standalone) {
  422.                                                         restoreInternalState(tmpState);
  423.                                                 }
  424.  
  425.                                                 if (saveres != SAVING_OK) {
  426.                                                         TCHAR* reason = FF_GetMsg_Cpy(saveres);
  427.                                                         alertuser_id(MSG_CANNOT_SAVE_SETTINGS_ID, reason);
  428.                                                         FF_GetMsg_Free(reason);
  429.                                                         *result = filterBadParameters;
  430.                                                 }
  431.                                         }
  432.                                         else {
  433.                                                 /* update stored parameters from new user settings */
  434.                                                 if (pb->parameters)
  435.                                                         saveparams_afs_pff(pb->parameters, false);
  436.                                         }
  437.                                 }
  438.                                 else
  439.                                         *result = userCanceledErr;
  440.                         }
  441.                         wantdialog = false;
  442.                 }
  443.  
  444.                 if(*result == noErr){
  445.                         if(setup(pb)){
  446.                                 DoStart(pb);
  447.                         }else{
  448.                                 simplealert_id(MSG_SAVED_EXPR_ERR_ID);
  449.                                 *result = filterBadParameters;
  450.                         }
  451.                 }
  452.                 break;
  453.         case filterSelectorContinue:
  454.                 *result = DoContinue(pb);
  455.                 break;
  456.         case filterSelectorFinish:
  457.                 DoFinish(pb);
  458.                 break;
  459.         default:
  460.                 *result = filterBadParameters;
  461.         }
  462.  
  463. endmain:
  464.  
  465.         // TODO: Question: Is that OK to call this every invocation, or should it be only around UI stuff?
  466.         #ifdef WIN_ENV
  467.         if (activationContextUsed) DeactivateManifest(&manifestVars);
  468.         #endif
  469.  
  470.         ExitCodeResource();
  471. }
  472.  
  473. void parm_reset(Boolean resetMetadata, Boolean resetSliderValues, Boolean resetSliderNames, Boolean resetFormulas) {
  474.         gdata->parm.cbSize = PARM_SIZE;
  475.         if (resetMetadata) {
  476.                 strcpy(gdata->parm.szCategory, "Filter Foundry");
  477.                 strcpy(gdata->parm.szTitle, "Untitled");
  478.                 strcpy(gdata->parm.szCopyright, ""); //"Filter Foundry Copyright (C) 2003-2009 Toby Thain, 2018-" RELEASE_YEAR " Daniel Marschall"
  479.                 strcpy(gdata->parm.szAuthor, "Anonymous");
  480.         }
  481.         if (resetSliderValues) {
  482.                 int i;
  483.                 for (i = 0; i < 8; ++i) {
  484.                         gdata->parm.val[i] = (uint8_t)(i * 10 + 100);
  485.                 }
  486.         }
  487.         if (resetSliderNames) {
  488.                 int i;
  489.                 for (i = 0; i < 8; ++i) {
  490.                         strcpy(gdata->parm.szCtl[i], "ctl(X)");
  491.                         gdata->parm.szCtl[i][4] = '0' + i;
  492.                 }
  493.                 for (i = 0; i < 4; ++i) {
  494.                         strcpy(gdata->parm.szMap[i], "Map X");
  495.                         gdata->parm.szMap[i][4] = '0' + i;
  496.                 }
  497.         }
  498.         if (resetFormulas) {
  499.                 if (gpb->imageMode == plugInModeRGBColor) {
  500.                         strcpy(gdata->parm.szFormula[0], "r");
  501.                         strcpy(gdata->parm.szFormula[1], "g");
  502.                         strcpy(gdata->parm.szFormula[2], "b");
  503.                         strcpy(gdata->parm.szFormula[3], "a");
  504.                 }
  505.                 else {
  506.                         strcpy(gdata->parm.szFormula[0], "c");
  507.                         strcpy(gdata->parm.szFormula[1], "c");
  508.                         strcpy(gdata->parm.szFormula[2], "c");
  509.                         strcpy(gdata->parm.szFormula[3], "c");
  510.                 }
  511.         }
  512. }
  513.  
  514. void parm_cleanup() {
  515.         // Cleanup "PARM" resource by removing stuff after the null terminators, to avoid that parts of confidential formulas are leaked
  516.         int i;
  517.  
  518.         {
  519.                 char tmp[256];
  520.  
  521.                 strcpy(tmp, gdata->parm.szCategory);
  522.                 memset(gdata->parm.szCategory, 0, sizeof(gdata->parm.szCategory));
  523.                 strcpy(gdata->parm.szCategory, tmp);
  524.  
  525.                 strcpy(tmp, gdata->parm.szTitle);
  526.                 memset(gdata->parm.szTitle, 0, sizeof(gdata->parm.szTitle));
  527.                 strcpy(gdata->parm.szTitle, tmp);
  528.  
  529.                 strcpy(tmp, gdata->parm.szCopyright);
  530.                 memset(gdata->parm.szCopyright, 0, sizeof(gdata->parm.szCopyright));
  531.                 strcpy(gdata->parm.szCopyright, tmp);
  532.  
  533.                 strcpy(tmp, gdata->parm.szAuthor);
  534.                 memset(gdata->parm.szAuthor, 0, sizeof(gdata->parm.szAuthor));
  535.                 strcpy(gdata->parm.szAuthor, tmp);
  536.         }
  537.  
  538.         for (i = 0; i < 4; i++) {
  539.                 char tmp[256];
  540.                 strcpy(tmp, gdata->parm.szMap[i]);
  541.                 memset(gdata->parm.szMap[i], 0, sizeof(gdata->parm.szMap[i]));
  542.                 strcpy(gdata->parm.szMap[i], tmp);
  543.         }
  544.  
  545.         for (i = 0; i < 8; i++) {
  546.                 char tmp[256];
  547.                 strcpy(tmp, gdata->parm.szCtl[i]);
  548.                 memset(gdata->parm.szCtl[i], 0, sizeof(gdata->parm.szCtl[i]));
  549.                 strcpy(gdata->parm.szCtl[i], tmp);
  550.         }
  551.  
  552.         for (i = 0; i < 4; i++) {
  553.                 char tmp[1024];
  554.                 strcpy(tmp, gdata->parm.szFormula[i]);
  555.                 memset(gdata->parm.szFormula[i], 0, sizeof(gdata->parm.szFormula[i]));
  556.                 strcpy(gdata->parm.szFormula[i], tmp);
  557.         }
  558. }
  559.  
  560. int checkandinitparams(Handle params){
  561.         int i;
  562.         Boolean bUninitializedParams;
  563.         Boolean showdialog;
  564.         InternalState tmpState;
  565.  
  566.         if (!host_preserves_parameters()) {
  567.                 // Workaround: Load settings in "FilterFoundryXX.afs" if host does not preserve pb->parameters
  568.                 TCHAR outfilename[MAX_PATH + 1];
  569.                 Boolean parmReadOk;
  570.                 StandardFileReply sfr;
  571.                 char bakexpr[4][MAXEXPR];
  572.  
  573.                 sfr.sfGood = true;
  574.                 sfr.sfReplacing = true;
  575.                 sfr.sfType = PS_FILTER_FILETYPE;
  576.  
  577.                 parmReadOk = (LOADING_OK == readPARMresource((HMODULE)hDllInstance));
  578.                 if (!parmReadOk) gdata->parm.standalone = false;
  579.                 if (parmReadOk && (gdata->parm.cbSize != PARM_SIZE) && (gdata->parm.cbSize != PARM_SIZE_PREMIERE) && (gdata->parm.cbSize != PARM_SIG_MAC)) {
  580.                         parm_reset(true, true, true, true);
  581.                         if (gdata->obfusc) {
  582.                                 simplealert_id(MSG_INCOMPATIBLE_OBFUSCATION_ID);
  583.                         }
  584.                         else {
  585.                                 simplealert_id(MSG_INVALID_PARAMETER_DATA_ID);
  586.                         }
  587.                         return false;
  588.                 }
  589.  
  590.                 get_temp_afs(&outfilename[0], parmReadOk, &gdata->parm);
  591.  
  592.                 xstrcpy(sfr.sfFile.szName, outfilename);
  593.                 #ifdef WIN_ENV
  594.                 sfr.nFileExtension = (WORD)(xstrlen(outfilename) - strlen(".afs") + 1);
  595.                 #endif
  596.                 sfr.sfScript = smSystemScript;
  597.  
  598.                 if (parmReadOk) {
  599.                         tmpState = saveInternalState();
  600.                 }
  601.  
  602.                 if (LOADING_OK == loadfile(&sfr)) {
  603.                         if (parmReadOk) {
  604.                                 // In the standalone filter, we only want the parameters (ctl,map) in the temporary .afs file, not the formulas
  605.                                 // We do not need to care about the metadata, because the AFS does not touch the metadata anyway
  606.                                 for (i = 0; i < 4; i++) {
  607.                                         strcpy(bakexpr[i], gdata->parm.szFormula[i]);
  608.                                 }
  609.                                 restoreInternalState(tmpState);
  610.                                 for (i = 0; i < 4; i++) {
  611.                                         strcpy(gdata->parm.szFormula[i],bakexpr[i]);
  612.                                 }
  613.                         }
  614.  
  615.                         return true;
  616.                 }
  617.         }
  618.  
  619.         if( (bUninitializedParams = !(params && (LOADING_OK == readparams_afs_pff(params, false)))) ){
  620.                 /* either the parameter handle was uninitialised,
  621.                    or the parameter data couldn't be read; set default values */
  622.  
  623.                 Boolean parmReadOk;
  624.  
  625.                 // see if saved parameters exist
  626.                 parmReadOk = (LOADING_OK == readPARMresource((HMODULE)hDllInstance));
  627.                 if (!parmReadOk) gdata->parm.standalone = false;
  628.                 if (parmReadOk && (gdata->parm.cbSize != PARM_SIZE) && (gdata->parm.cbSize != PARM_SIZE_PREMIERE) && (gdata->parm.cbSize != PARM_SIG_MAC)) {
  629.                         parm_reset(true, true, true, true);
  630.                         if (gdata->obfusc) {
  631.                                 simplealert_id(MSG_INCOMPATIBLE_OBFUSCATION_ID);
  632.                         }
  633.                         else {
  634.                                 simplealert_id(MSG_INVALID_PARAMETER_DATA_ID);
  635.                         }
  636.                         return false;
  637.                 }
  638.  
  639.                 if(!gdata->parm.standalone){
  640.                         // no saved settings (not standalone)
  641.                         parm_reset(true, true, true, true);
  642.                 }
  643.         }
  644.  
  645.         // let scripting system change parameters, if we're scripted;
  646.         // user may want to force display of dialog during scripting playback
  647.         switch (ReadScriptParamsOnRead()) {
  648.         case SCR_SHOW_DIALOG:
  649.                 showdialog = true;
  650.                 break;
  651.         case SCR_HIDE_DIALOG:
  652.                 showdialog = false;
  653.                 break;
  654.         default:
  655.         case SCR_NO_SCRIPT:
  656.                 showdialog = bUninitializedParams;
  657.                 break;
  658.         }
  659.  
  660.         if (params) saveparams_afs_pff(params, false);
  661.  
  662.         return showdialog;
  663. }
  664.  
  665. Boolean host_preserves_parameters(void) {
  666.         #ifdef DEBUG_SIMULATE_GIMP
  667.         return false;
  668.         #endif
  669.  
  670.         if (gpb->hostSig == HOSTSIG_GIMP) return false;
  671.         if (gpb->hostSig == HOSTSIG_IRFANVIEW) return false;
  672.  
  673.         // We just assume the other hosts preserve the parameters
  674.         return true;
  675. }
  676.  
  677. int64_t maxspace(void){
  678.         // Please see "Hosts.md" for details about the MaxSpace implementations of tested plugins
  679.  
  680.         // Plugins that don't support MaxSpace64 shall set the field to zero; then we will use MaxSpace instead.
  681.         // Also check "gpb->bufferProcs->numBufferProcs" to see if 64 bit API is available
  682.         if ((gpb->bufferProcs->numBufferProcs >= 8) && (gpb->maxSpace64 > 0)) {
  683.                 uint64_t maxSpace64 = gpb->maxSpace64;
  684.  
  685.                 return maxSpace64;
  686.         } else {
  687.                 // 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.
  688.                 unsigned int maxSpace32 = (unsigned int) gpb->maxSpace;
  689.                 uint64_t maxSpace64 = maxSpace32;
  690.  
  691.                 if (gpb->hostSig == HOSTSIG_IRFANVIEW) maxSpace64 *= 1024; // IrfanView is giving Kilobytes instead of Bytes
  692.                 //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???
  693.  
  694.                 return maxSpace64;
  695.         }
  696. }
  697.  
  698. Boolean maxspace_available(void) {
  699.         // Please see "Hosts.md" for details about the MaxSpace implementations of tested plugins
  700.  
  701.         // GIMP PSPI sets MaxSpace to hardcoded 100 MB
  702.         if (gpb->hostSig == HOSTSIG_GIMP) return false;
  703.  
  704.         // HOSTSIG_PAINT_NET sets MaxSpace to hardcoded 1 GB, see https://github.com/0xC0000054/PSFilterPdn/issues/5
  705.         // Comment by the host author "This was done to avoid any compatibility issues with plugins handling 2 GB - 1"
  706.         if (gpb->hostSig == HOSTSIG_PAINT_NET) return false;
  707.  
  708.         return true;
  709. }
  710.  
  711. void DoPrepare(FilterRecordPtr pb){
  712.         int i;
  713.  
  714.         for(i = 4; i--;){
  715.                 tree[i] = NULL;
  716.                 err[i] = NULL;
  717.         }
  718.  
  719.         // Commented out by DM, 18 Dec 2018:
  720.         // This code did not work on systems with 8 GB RAM:
  721.         /*
  722.         long space = (pb->maxSpace*9)/10; // don't ask for more than 90% of available memory
  723.  
  724.         maxSpace = 512L<<10; // this is a wild guess, actually
  725.         if(maxSpace > space)
  726.                         maxSpace = space;
  727.         pb->maxSpace = maxSpace;
  728.         */
  729.  
  730.         // New variant:
  731.         if (maxspace_available()) {
  732.                 // don't ask for more than 90% of available memory
  733.                 int64 ninetyPercent = (int64)ceil((maxspace() / 10.) * 9);
  734.                 if ((gpb->bufferProcs->numBufferProcs >= 8) && (gpb->maxSpace64 > 0)) {
  735.                         pb->maxSpace64 = ninetyPercent;
  736.                 }
  737.                 if (ninetyPercent <= 0x7FFFFFFF) {
  738.                         pb->maxSpace = (int32)ninetyPercent;
  739.                 }
  740.         }
  741. }
  742.  
  743. void RequestNext(FilterRecordPtr pb){
  744.         /* Request next block of the image */
  745.  
  746.         pb->inLoPlane = pb->outLoPlane = 0;
  747.         pb->inHiPlane = pb->outHiPlane = nplanes-1;
  748.  
  749.         if (HAS_BIG_DOC(pb)) {
  750.                 // if any of the formulae involve random access to image pixels,
  751.                 // ask for the entire image
  752.                 if (needall) {
  753.                         SETRECT(BIGDOC_IN_RECT(pb), 0, 0, BIGDOC_IMAGE_SIZE(pb).h, BIGDOC_IMAGE_SIZE(pb).v);
  754.                 } else {
  755.                         // TODO: This does not work with GIMP. So, if we are using GIMP, we should
  756.                         //       somehow always use "needall=true", and/or find out why this doesn't work
  757.                         //       with GIMP.
  758.  
  759.                         // otherwise, process the filtered area, by chunksize parts
  760.                         BIGDOC_IN_RECT(pb).left = BIGDOC_FILTER_RECT(pb).left;
  761.                         BIGDOC_IN_RECT(pb).right = BIGDOC_FILTER_RECT(pb).right;
  762.                         BIGDOC_IN_RECT(pb).top = (int32)toprow;
  763.                         BIGDOC_IN_RECT(pb).bottom = (int32)MIN(toprow + chunksize, BIGDOC_FILTER_RECT(pb).bottom);
  764.  
  765.                         if (cnvused) {
  766.                                 // cnv() needs one extra pixel in each direction
  767.                                 if (BIGDOC_IN_RECT(pb).left > 0)
  768.                                         --BIGDOC_IN_RECT(pb).left;
  769.                                 if (BIGDOC_IN_RECT(pb).right < BIGDOC_IMAGE_SIZE(pb).h)
  770.                                         ++BIGDOC_IN_RECT(pb).right;
  771.                                 if (BIGDOC_IN_RECT(pb).top > 0)
  772.                                         --BIGDOC_IN_RECT(pb).top;
  773.                                 if (BIGDOC_IN_RECT(pb).bottom < BIGDOC_IMAGE_SIZE(pb).v)
  774.                                         ++BIGDOC_IN_RECT(pb).bottom;
  775.                         }
  776.                 }
  777.                 BIGDOC_OUT_RECT(pb) = BIGDOC_FILTER_RECT(pb);
  778.                 /*
  779.                 {char s[0x100];sprintf(s,"RequestNext needall=%d inRect=(%d,%d,%d,%d) filterRect=(%d,%d,%d,%d)",
  780.                                 needall,
  781.                                 BIGDOC_IN_RECT(pb).left,BIGDOC_IN_RECT(pb).top,BIGDOC_IN_RECT(pb).right,BIGDOC_IN_RECT(pb).bottom,
  782.                                 BIGDOC_FILTER_RECT(pb).left,BIGDOC_FILTER_RECT(pb).top,BIGDOC_FILTER_RECT(pb).right,BIGDOC_FILTER_RECT(pb).bottom);dbg(s);}
  783.                 */
  784.         } else {
  785.                 // if any of the formulae involve random access to image pixels,
  786.                 // ask for the entire image
  787.                 if (needall) {
  788.                         SETRECT(IN_RECT(pb), 0, 0, IMAGE_SIZE(pb).h, IMAGE_SIZE(pb).v);
  789.                 }
  790.                 else {
  791.                         // TODO: This does not work with GIMP. So, if we are using GIMP, we should
  792.                         //       somehow always use "needall=true", and/or find out why this doesn't work
  793.                         //       with GIMP.
  794.  
  795.                         // otherwise, process the filtered area, by chunksize parts
  796.                         IN_RECT(pb).left = FILTER_RECT(pb).left;
  797.                         IN_RECT(pb).right = FILTER_RECT(pb).right;
  798.                         IN_RECT(pb).top = (int16)toprow;
  799.                         IN_RECT(pb).bottom = (int16)MIN(toprow + chunksize, FILTER_RECT(pb).bottom);
  800.  
  801.                         if (cnvused) {
  802.                                 // cnv() needs one extra pixel in each direction
  803.                                 if (IN_RECT(pb).left > 0)
  804.                                         --IN_RECT(pb).left;
  805.                                 if (IN_RECT(pb).right < IMAGE_SIZE(pb).h)
  806.                                         ++IN_RECT(pb).right;
  807.                                 if (IN_RECT(pb).top > 0)
  808.                                         --IN_RECT(pb).top;
  809.                                 if (IN_RECT(pb).bottom < IMAGE_SIZE(pb).v)
  810.                                         ++IN_RECT(pb).bottom;
  811.                         }
  812.                 }
  813.                 OUT_RECT(pb) = FILTER_RECT(pb);
  814.                 /*
  815.                 {char s[0x100];sprintf(s,"RequestNext needall=%d inRect=(%d,%d,%d,%d) filterRect=(%d,%d,%d,%d)",
  816.                                 needall,
  817.                                 IN_RECT(pb).left,IN_RECT(pb).top,IN_RECT(pb).right,IN_RECT(pb).bottom,
  818.                                 FILTER_RECT(pb).left,FILTER_RECT(pb).top,FILTER_RECT(pb).right,FILTER_RECT(pb).bottom);dbg(s);}
  819.                 */
  820.         }
  821. }
  822.  
  823. void DoStart(FilterRecordPtr pb){
  824.         /* Global variable "needall": if src() or rad() functions are used, random access to the image data is required,
  825.            so we must request the entire image in a single chunk, otherwise we will use chunksize "CHUNK_ROWS". */
  826.         if (HAS_BIG_DOC(pb)) {
  827.                 chunksize = needall ? (BIGDOC_FILTER_RECT(pb).bottom - BIGDOC_FILTER_RECT(pb).top) : CHUNK_ROWS;
  828.                 toprow = BIGDOC_FILTER_RECT(pb).top;
  829.         } else {
  830.                 chunksize = needall ? (FILTER_RECT(pb).bottom - FILTER_RECT(pb).top) : CHUNK_ROWS;
  831.                 toprow = FILTER_RECT(pb).top;
  832.         }
  833.         RequestNext(pb);
  834. }
  835.  
  836. OSErr DoContinue(FilterRecordPtr pb){
  837.         OSErr e = noErr;
  838.         long outoffset;
  839.  
  840.         if (HAS_BIG_DOC(pb)) {
  841.                 VRect fr;
  842.                 if (needall) {
  843.                         fr = BIGDOC_FILTER_RECT(pb);  // filter whole selection at once
  844.                 } else if (cnvused) {
  845.                         // we've requested one pixel extra all around
  846.                         // (see RequestNext()), just for access purposes. But filter
  847.                         // original selection only.
  848.                         fr.left = BIGDOC_FILTER_RECT(pb).left;
  849.                         fr.right = BIGDOC_FILTER_RECT(pb).right;
  850.                         fr.top = toprow;
  851.                         fr.bottom = MIN(toprow + chunksize, BIGDOC_FILTER_RECT(pb).bottom);
  852.                 } else {  // filter whatever portion we've been given
  853.                         fr = BIGDOC_IN_RECT(pb);
  854.                 }
  855.  
  856.                 outoffset = (long)pb->outRowBytes * (fr.top - BIGDOC_OUT_RECT(pb).top)
  857.                         + (long)nplanes * (fr.left - BIGDOC_OUT_RECT(pb).left);
  858.  
  859.                 if (!(e = process_scaled_bigdoc(pb, true, fr, fr,
  860.                         (Ptr)pb->outData + outoffset, pb->outRowBytes, 1.)))
  861.                 {
  862.                         toprow += chunksize;
  863.                         if (toprow < BIGDOC_FILTER_RECT(pb).bottom)
  864.                                 RequestNext(pb);
  865.                         else {
  866.                                 SETRECT(BIGDOC_IN_RECT(pb), 0, 0, 0, 0);
  867.                                 BIGDOC_OUT_RECT(pb) = BIGDOC_MASK_RECT(pb) = BIGDOC_IN_RECT(pb);
  868.                         }
  869.                 }
  870.         } else {
  871.                 Rect fr;
  872.                 if (needall) {
  873.                         fr = FILTER_RECT(pb);  // filter whole selection at once
  874.                 } else if (cnvused) {
  875.                         // we've requested one pixel extra all around
  876.                         // (see RequestNext()), just for access purposes. But filter
  877.                         // original selection only.
  878.                         fr.left = FILTER_RECT(pb).left;
  879.                         fr.right = FILTER_RECT(pb).right;
  880.                         fr.top = toprow;
  881.                         fr.bottom = MIN(toprow + chunksize, FILTER_RECT(pb).bottom);
  882.                 } else {  // filter whatever portion we've been given
  883.                         fr = IN_RECT(pb);
  884.                 }
  885.  
  886.                 outoffset = (long)pb->outRowBytes*(fr.top - OUT_RECT(pb).top)
  887.                         + (long)nplanes*(fr.left - OUT_RECT(pb).left);
  888.  
  889.                 if(!(e = process_scaled_olddoc(pb, true, fr, fr,
  890.                         (Ptr)pb->outData+outoffset, pb->outRowBytes, 1.)))
  891.                 {
  892.                         toprow += chunksize;
  893.                         if(toprow < FILTER_RECT(pb).bottom)
  894.                                 RequestNext(pb);
  895.                         else{
  896.                                 SETRECT(IN_RECT(pb),0,0,0,0);
  897.                                 OUT_RECT(pb) = MASK_RECT(pb) = IN_RECT(pb);
  898.                         }
  899.                 }
  900.         }
  901.         return e;
  902. }
  903.  
  904. void DoFinish(FilterRecordPtr pb){
  905.         int i;
  906.  
  907.         UNREFERENCED_PARAMETER(pb);
  908.  
  909.         WriteScriptParamsOnRead();
  910.  
  911.         for(i = 4; i--;){
  912.                 freetree(tree[i]);
  913.         }
  914. }
  915.  
  916. InternalState saveInternalState(void) {
  917.         InternalState ret;
  918.         ret.bak_obfusc = gdata->obfusc;
  919.         memcpy(&ret.bak_parm, &gdata->parm, sizeof(PARM_T));
  920.  
  921.         return ret;
  922. }
  923.  
  924. void restoreInternalState(InternalState state) {
  925.         gdata->obfusc = state.bak_obfusc;
  926.         memcpy(&gdata->parm, &state.bak_parm, sizeof(PARM_T));
  927. }
  928.