Subversion Repositories filter_foundry

Rev

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