Subversion Repositories filter_foundry

Rev

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