1 /* LIBGIMP - The GIMP Library
2  * Copyright (C) 1995-1997 Peter Mattis and Spencer Kimball
3  *
4  * gimp.c
5  *
6  * This library is free software: you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 3 of the License, or (at your option) any later version.
10  *
11  * This library 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 GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library.  If not, see
18  * <https://www.gnu.org/licenses/>.
19  */
20 
21 #include "config.h"
22 
23 #define _GNU_SOURCE  /* for the sigaction stuff */
24 
25 #include <errno.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #include <floatingpoint.h>
32 
33 #ifdef HAVE_SYS_TIME_H
34 #include <sys/time.h>
35 #endif
36 
37 #ifdef HAVE_SYS_PARAM_H
38 #include <sys/param.h>
39 #endif
40 
41 #ifdef HAVE_SYS_WAIT_H
42 #include <sys/wait.h>
43 #endif
44 
45 #ifdef HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48 
49 #ifndef WAIT_ANY
50 #define WAIT_ANY -1
51 #endif
52 
53 #include <gtk/gtk.h> /* need GDK_WINDOWING_FOO defines */
54 
55 #ifndef G_OS_WIN32
56 #include "libgimpbase/gimpsignal.h"
57 
58 #else
59 
60 #ifdef HAVE_EXCHNDL
61 #include <time.h>
62 #include <exchndl.h>
63 #endif
64 
65 #include <signal.h>
66 #endif
67 
68 #ifdef HAVE_SYS_SELECT_H
69 #include <sys/select.h>
70 #endif
71 
72 #if defined(USE_SYSV_SHM)
73 
74 #ifdef HAVE_IPC_H
75 #include <sys/ipc.h>
76 #endif
77 
78 #ifdef HAVE_SHM_H
79 #include <sys/shm.h>
80 #endif
81 
82 #elif defined(USE_POSIX_SHM)
83 
84 #ifdef HAVE_UNISTD_H
85 #include <unistd.h>
86 #endif
87 
88 #include <fcntl.h>
89 #include <sys/mman.h>
90 
91 #endif /* USE_POSIX_SHM */
92 
93 #ifdef GDK_WINDOWING_QUARTZ
94 #include <Cocoa/Cocoa.h>
95 #endif
96 
97 #if defined(G_OS_WIN32) || defined(G_WITH_CYGWIN)
98 #  ifdef STRICT
99 #  undef STRICT
100 #  endif
101 #  define STRICT
102 
103 #  ifdef _WIN32_WINNT
104 #  undef _WIN32_WINNT
105 #  endif
106 #  define _WIN32_WINNT 0x0601
107 
108 #  include <windows.h>
109 #  include <tlhelp32.h>
110 #  undef RGB
111 #  define USE_WIN32_SHM 1
112 #endif
113 
114 #include <locale.h>
115 
116 #include "libgimpbase/gimpbase.h"
117 #include "libgimpbase/gimpbase-private.h"
118 #include "libgimpbase/gimpprotocol.h"
119 #include "libgimpbase/gimpwire.h"
120 
121 #include "gimp.h"
122 #include "gimpunitcache.h"
123 
124 #include "libgimp-intl.h"
125 
126 
127 /**
128  * SECTION: gimp
129  * @title: Gimp
130  * @short_description: Main functions needed for building a GIMP plug-in.
131  *                     This header includes all other GIMP Library headers.
132  *
133  * Main functions needed for building a GIMP plug-in. This header
134  * includes all other GIMP Library headers.
135  **/
136 
137 
138 #define TILE_MAP_SIZE (_tile_width * _tile_height * 32)
139 
140 #define ERRMSG_SHM_FAILED "Could not attach to gimp shared memory segment"
141 
142 /* Maybe this should go in a public header if we add other things to it */
143 typedef enum
144 {
145   GIMP_DEBUG_PID            = 1 << 0,
146   GIMP_DEBUG_FATAL_WARNINGS = 1 << 1,
147   GIMP_DEBUG_QUERY          = 1 << 2,
148   GIMP_DEBUG_INIT           = 1 << 3,
149   GIMP_DEBUG_RUN            = 1 << 4,
150   GIMP_DEBUG_QUIT           = 1 << 5,
151 
152   GIMP_DEBUG_DEFAULT        = (GIMP_DEBUG_RUN | GIMP_DEBUG_FATAL_WARNINGS)
153 } GimpDebugFlag;
154 
155 #define WRITE_BUFFER_SIZE  1024
156 
157 void gimp_read_expect_msg   (GimpWireMessage *msg,
158                              gint             type);
159 
160 
161 static void       gimp_close                   (void);
162 static void       gimp_debug_stop              (void);
163 static void       gimp_message_func            (const gchar    *log_domain,
164                                                 GLogLevelFlags  log_level,
165                                                 const gchar    *message,
166                                                 gpointer        data);
167 static void       gimp_fatal_func              (const gchar    *log_domain,
168                                                 GLogLevelFlags  flags,
169                                                 const gchar    *message,
170                                                 gpointer        data);
171 #ifdef G_OS_WIN32
172 #ifdef HAVE_EXCHNDL
173 static LONG WINAPI gimp_plugin_sigfatal_handler (PEXCEPTION_POINTERS pExceptionInfo);
174 #endif
175 #else
176 static void       gimp_plugin_sigfatal_handler (gint            sig_num);
177 #endif
178 static gboolean   gimp_plugin_io_error_handler (GIOChannel      *channel,
179                                                 GIOCondition     cond,
180                                                 gpointer         data);
181 static gboolean   gimp_write                   (GIOChannel      *channel,
182                                                 const guint8    *buf,
183                                                 gulong           count,
184                                                 gpointer         user_data);
185 static gboolean   gimp_flush                   (GIOChannel      *channel,
186                                                 gpointer         user_data);
187 static void       gimp_loop                    (void);
188 static void       gimp_config                  (GPConfig        *config);
189 static void       gimp_proc_run                (GPProcRun       *proc_run);
190 static void       gimp_temp_proc_run           (GPProcRun       *proc_run);
191 static void       gimp_process_message         (GimpWireMessage *msg);
192 static void       gimp_single_message          (void);
193 static gboolean   gimp_extension_read          (GIOChannel      *channel,
194                                                 GIOCondition     condition,
195                                                 gpointer         data);
196 
197 static void       gimp_set_pdb_error           (const GimpParam *return_vals,
198                                                 gint             n_return_vals);
199 
200 
201 #if defined G_OS_WIN32 && defined HAVE_EXCHNDL
202 static LPTOP_LEVEL_EXCEPTION_FILTER  _prevExceptionFilter    = NULL;
203 static gchar                         *plug_in_backtrace_path = NULL;
204 #endif
205 
206 static GIOChannel                   *_readchannel            = NULL;
207 GIOChannel                          *_writechannel           = NULL;
208 
209 #ifdef USE_WIN32_SHM
210 static HANDLE shm_handle;
211 #endif
212 
213 static gint           _tile_width        = -1;
214 static gint           _tile_height       = -1;
215 static gint           _shm_ID            = -1;
216 static guchar        *_shm_addr          = NULL;
217 static gboolean       _show_tool_tips    = TRUE;
218 static gboolean       _show_help_button  = TRUE;
219 static gboolean       _export_profile    = FALSE;
220 static gboolean       _export_exif       = FALSE;
221 static gboolean       _export_xmp        = FALSE;
222 static gboolean       _export_iptc       = FALSE;
223 static GimpCheckSize  _check_size        = GIMP_CHECK_SIZE_MEDIUM_CHECKS;
224 static GimpCheckType  _check_type        = GIMP_CHECK_TYPE_GRAY_CHECKS;
225 static gint           _min_colors        = 144;
226 static gint           _gdisp_ID          = -1;
227 static gchar         *_wm_class          = NULL;
228 static gchar         *_display_name      = NULL;
229 static gint           _monitor_number    = 0;
230 static guint32        _timestamp         = 0;
231 static gchar         *_icon_theme_dir    = NULL;
232 static const gchar   *progname           = NULL;
233 
234 static gchar          write_buffer[WRITE_BUFFER_SIZE];
235 static gulong         write_buffer_index = 0;
236 
237 static GimpStackTraceMode stack_trace_mode = GIMP_STACK_TRACE_NEVER;
238 
239 static GHashTable    *temp_proc_ht       = NULL;
240 
241 static guint          gimp_debug_flags   = 0;
242 
243 static const GDebugKey gimp_debug_keys[] =
244 {
245   { "pid",            GIMP_DEBUG_PID            },
246   { "fatal-warnings", GIMP_DEBUG_FATAL_WARNINGS },
247   { "fw",             GIMP_DEBUG_FATAL_WARNINGS },
248   { "query",          GIMP_DEBUG_QUERY          },
249   { "init",           GIMP_DEBUG_INIT           },
250   { "run",            GIMP_DEBUG_RUN            },
251   { "quit",           GIMP_DEBUG_QUIT           },
252   { "on",             GIMP_DEBUG_DEFAULT        }
253 };
254 
255 static GimpPlugInInfo PLUG_IN_INFO;
256 
257 
258 static GimpPDBStatusType  pdb_error_status   = GIMP_PDB_SUCCESS;
259 static gchar             *pdb_error_message  = NULL;
260 
261 
262 /**
263  * gimp_main:
264  * @info: the PLUG_IN_INFO structure
265  * @argc: the number of arguments
266  * @argv: the arguments
267  *
268  * The main procedure that must be called with the PLUG_IN_INFO structure
269  * and the 'argc' and 'argv' that are passed to "main".
270  *
271  * Returns: an exit status as defined by the C library,
272  *          on success EXIT_SUCCESS.
273  **/
274 gint
gimp_main(const GimpPlugInInfo * info,gint argc,gchar * argv[])275 gimp_main (const GimpPlugInInfo *info,
276            gint                  argc,
277            gchar                *argv[])
278 {
279   enum
280   {
281     ARG_PROGNAME,
282     ARG_GIMP,
283     ARG_READ_FD,
284     ARG_WRITE_FD,
285     ARG_MODE,
286     ARG_STACK_TRACE_MODE,
287 
288     N_ARGS
289   };
290 
291   gchar       *basename;
292   const gchar *env_string;
293   gchar       *debug_string;
294 
295 #ifdef G_OS_WIN32
296   gint i, j, k;
297 
298   /* Reduce risks */
299   {
300     typedef BOOL (WINAPI *t_SetDllDirectoryA) (LPCSTR lpPathName);
301     t_SetDllDirectoryA p_SetDllDirectoryA;
302 
303     p_SetDllDirectoryA = (t_SetDllDirectoryA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
304                                                               "SetDllDirectoryA");
305     if (p_SetDllDirectoryA)
306       (*p_SetDllDirectoryA) ("");
307   }
308 
309   /* On Windows, set DLL search path to $INSTALLDIR/bin so that GEGL
310      file operations can find their respective file library DLLs (such
311      as jasper, etc.) without needing to set external PATH. */
312   {
313     const gchar *install_dir;
314     gchar       *bin_dir;
315     LPWSTR       w_bin_dir;
316     int          n;
317 
318     w_bin_dir = NULL;
319     install_dir = gimp_installation_directory ();
320     bin_dir = g_build_filename (install_dir, "bin", NULL);
321 
322     n = MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
323                              bin_dir, -1, NULL, 0);
324     if (n == 0)
325       goto out;
326 
327     w_bin_dir = g_malloc_n (n + 1, sizeof (wchar_t));
328     n = MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
329                              bin_dir, -1,
330                              w_bin_dir, (n + 1) * sizeof (wchar_t));
331     if (n == 0)
332       goto out;
333 
334     SetDllDirectoryW (w_bin_dir);
335 
336   out:
337     if (w_bin_dir)
338       g_free (w_bin_dir);
339     g_free (bin_dir);
340   }
341 
342 #ifdef HAVE_EXCHNDL
343   /* Use Dr. Mingw (dumps backtrace on crash) if it is available. */
344   {
345     time_t  t;
346     gchar  *filename;
347     gchar  *dir;
348 
349     /* This has to be the non-roaming directory (i.e., the local
350        directory) as backtraces correspond to the binaries on this
351        system. */
352     dir = g_build_filename (g_get_user_data_dir (),
353                             GIMPDIR, GIMP_USER_VERSION, "CrashLog",
354                             NULL);
355     /* Ensure the path exists. */
356     g_mkdir_with_parents (dir, 0700);
357 
358     time (&t);
359     filename = g_strdup_printf ("%s-crash-%" G_GUINT64_FORMAT ".txt",
360                                 g_get_prgname(), t);
361     plug_in_backtrace_path = g_build_filename (dir, filename, NULL);
362     g_free (filename);
363     g_free (dir);
364 
365     /* Similar to core crash handling in app/signals.c, the order here
366      * is very important!
367      */
368     if (! _prevExceptionFilter)
369       _prevExceptionFilter = SetUnhandledExceptionFilter (gimp_plugin_sigfatal_handler);
370 
371     ExcHndlInit ();
372     ExcHndlSetLogFileNameA (plug_in_backtrace_path);
373   }
374 #endif
375 
376 #ifndef _WIN64
377   {
378     typedef BOOL (WINAPI *t_SetProcessDEPPolicy) (DWORD dwFlags);
379     t_SetProcessDEPPolicy p_SetProcessDEPPolicy;
380 
381     p_SetProcessDEPPolicy = GetProcAddress (GetModuleHandle ("kernel32.dll"),
382                                             "SetProcessDEPPolicy");
383     if (p_SetProcessDEPPolicy)
384       (*p_SetProcessDEPPolicy) (PROCESS_DEP_ENABLE|PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION);
385   }
386 #endif
387 
388   /* Group all our windows together on the taskbar */
389   {
390     typedef HRESULT (WINAPI *t_SetCurrentProcessExplicitAppUserModelID) (PCWSTR lpPathName);
391     t_SetCurrentProcessExplicitAppUserModelID p_SetCurrentProcessExplicitAppUserModelID;
392 
393     p_SetCurrentProcessExplicitAppUserModelID = (t_SetCurrentProcessExplicitAppUserModelID) GetProcAddress (GetModuleHandle ("shell32.dll"),
394                                                                                                             "SetCurrentProcessExplicitAppUserModelID");
395     if (p_SetCurrentProcessExplicitAppUserModelID)
396       (*p_SetCurrentProcessExplicitAppUserModelID) (L"gimp.GimpApplication");
397   }
398 
399   /* Check for exe file name with spaces in the path having been split up
400    * by buggy NT C runtime, or something. I don't know why this happens
401    * on NT (including w2k), but not on w95/98.
402    */
403 
404   for (i = 1; i < argc; i++)
405     {
406       k = strlen (argv[i]);
407 
408       if (k > 10)
409         {
410           if (g_ascii_strcasecmp (argv[i] + k - 4, ".exe") == 0)
411             {
412               /* Found the end of the executable name, most probably.
413                * Splice the parts of the name back together.
414                */
415               GString *s;
416 
417               s = g_string_new (argv[ARG_PROGNAME]);
418 
419               for (j = 1; j <= i; j++)
420                 {
421                   s = g_string_append_c (s, ' ');
422                   s = g_string_append (s, argv[j]);
423                 }
424 
425               argv[ARG_PROGNAME] = s->str;
426 
427               /* Move rest of argv down */
428               for (j = 1; j < argc - i; j++)
429                 argv[j] = argv[j + i];
430 
431               argv[argc - i] = NULL;
432               argc -= i;
433 
434               break;
435           }
436        }
437     }
438 #endif
439 
440   g_assert (info != NULL);
441 
442   PLUG_IN_INFO = *info;
443 
444   if ((argc != N_ARGS) || (strcmp (argv[ARG_GIMP], "-gimp") != 0))
445     {
446       g_printerr ("%s is a GIMP plug-in and must be run by GIMP to be used\n",
447                   argv[ARG_PROGNAME]);
448       return 1;
449     }
450 
451   gimp_env_init (TRUE);
452 
453   progname = argv[ARG_PROGNAME];
454 
455   /* Ignore floating point exceptions */
456   fpsetmask(0);
457 
458   basename = g_path_get_basename (progname);
459 
460   g_set_prgname (basename);
461 
462   env_string = g_getenv ("GIMP_PLUGIN_DEBUG");
463 
464   if (env_string)
465     {
466       const gchar *debug_messages;
467 
468       debug_string = strchr (env_string, ',');
469 
470       if (debug_string)
471         {
472           gint len = debug_string - env_string;
473 
474           if ((strlen (basename) == len) &&
475               (strncmp (basename, env_string, len) == 0))
476             {
477               gimp_debug_flags =
478                 g_parse_debug_string (debug_string + 1,
479                                       gimp_debug_keys,
480                                       G_N_ELEMENTS (gimp_debug_keys));
481             }
482         }
483       else if (strcmp (env_string, basename) == 0)
484         {
485           gimp_debug_flags = GIMP_DEBUG_DEFAULT;
486         }
487 
488       /*  make debug output visible by setting G_MESSAGES_DEBUG  */
489       debug_messages = g_getenv ("G_MESSAGES_DEBUG");
490 
491       if (debug_messages)
492         {
493           gchar *tmp = g_strconcat (debug_messages, ",LibGimp", NULL);
494           g_setenv ("G_MESSAGES_DEBUG", tmp, TRUE);
495           g_free (tmp);
496         }
497       else
498         {
499           g_setenv ("G_MESSAGES_DEBUG", "LibGimp", TRUE);
500         }
501     }
502 
503   g_free (basename);
504 
505   stack_trace_mode = (GimpStackTraceMode) CLAMP (atoi (argv[ARG_STACK_TRACE_MODE]),
506                                                  GIMP_STACK_TRACE_NEVER,
507                                                  GIMP_STACK_TRACE_ALWAYS);
508 
509 #ifndef G_OS_WIN32
510   /* No use catching these on Win32, the user won't get any meaningful
511    * stack trace from glib anyhow. It's better to let Windows inform
512    * about the program error, and offer debugging if the plug-in
513    * has been built with MSVC, and the user has MSVC installed.
514    */
515   gimp_signal_private (SIGHUP,  gimp_plugin_sigfatal_handler, 0);
516   gimp_signal_private (SIGINT,  gimp_plugin_sigfatal_handler, 0);
517   gimp_signal_private (SIGQUIT, gimp_plugin_sigfatal_handler, 0);
518   gimp_signal_private (SIGTERM, gimp_plugin_sigfatal_handler, 0);
519 
520   gimp_signal_private (SIGABRT, gimp_plugin_sigfatal_handler, 0);
521   gimp_signal_private (SIGBUS,  gimp_plugin_sigfatal_handler, 0);
522   gimp_signal_private (SIGSEGV, gimp_plugin_sigfatal_handler, 0);
523   gimp_signal_private (SIGFPE,  gimp_plugin_sigfatal_handler, 0);
524 
525   /* Ignore SIGPIPE from crashing Gimp */
526   gimp_signal_private (SIGPIPE, SIG_IGN, 0);
527 
528   /* Restart syscalls interrupted by SIGCHLD */
529   gimp_signal_private (SIGCHLD, SIG_DFL, SA_RESTART);
530 #endif
531 
532 #ifdef G_OS_WIN32
533   _readchannel  = g_io_channel_win32_new_fd (atoi (argv[ARG_READ_FD]));
534   _writechannel = g_io_channel_win32_new_fd (atoi (argv[ARG_WRITE_FD]));
535 #else
536   _readchannel  = g_io_channel_unix_new (atoi (argv[ARG_READ_FD]));
537   _writechannel = g_io_channel_unix_new (atoi (argv[ARG_WRITE_FD]));
538 #endif
539 
540   g_io_channel_set_encoding (_readchannel, NULL, NULL);
541   g_io_channel_set_encoding (_writechannel, NULL, NULL);
542 
543   g_io_channel_set_buffered (_readchannel, FALSE);
544   g_io_channel_set_buffered (_writechannel, FALSE);
545 
546   g_io_channel_set_close_on_unref (_readchannel, TRUE);
547   g_io_channel_set_close_on_unref (_writechannel, TRUE);
548 
549   gp_init ();
550 
551   gimp_wire_set_writer (gimp_write);
552   gimp_wire_set_flusher (gimp_flush);
553 
554   gimp_enums_init ();
555 
556   /*  initialize units  */
557   {
558     GimpUnitVtable vtable;
559 
560     vtable.unit_get_number_of_units = _gimp_unit_cache_get_number_of_units;
561     vtable.unit_get_number_of_built_in_units =
562       _gimp_unit_cache_get_number_of_built_in_units;
563     vtable.unit_new                 = _gimp_unit_cache_new;
564     vtable.unit_get_deletion_flag   = _gimp_unit_cache_get_deletion_flag;
565     vtable.unit_set_deletion_flag   = _gimp_unit_cache_set_deletion_flag;
566     vtable.unit_get_factor          = _gimp_unit_cache_get_factor;
567     vtable.unit_get_digits          = _gimp_unit_cache_get_digits;
568     vtable.unit_get_identifier      = _gimp_unit_cache_get_identifier;
569     vtable.unit_get_symbol          = _gimp_unit_cache_get_symbol;
570     vtable.unit_get_abbreviation    = _gimp_unit_cache_get_abbreviation;
571     vtable.unit_get_singular        = _gimp_unit_cache_get_singular;
572     vtable.unit_get_plural          = _gimp_unit_cache_get_plural;
573 
574     gimp_base_init (&vtable);
575   }
576 
577   /* initialize i18n support */
578 
579   setlocale (LC_ALL, "");
580 
581   bindtextdomain (GETTEXT_PACKAGE"-libgimp", gimp_locale_directory ());
582 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
583   bind_textdomain_codeset (GETTEXT_PACKAGE"-libgimp", "UTF-8");
584 #endif
585 
586 
587   /* set handler both for the "LibGimp" and "" domains */
588   {
589     const gchar * const log_domains[] =
590     {
591       "LibGimp",
592       "LibGimpBase",
593       "LibGimpColor",
594       "LibGimpConfig",
595       "LibGimpMath",
596       "LibGimpModule",
597       "LibGimpThumb",
598       "LibGimpWidgets"
599     };
600     gint i;
601 
602     for (i = 0; i < G_N_ELEMENTS (log_domains); i++)
603       g_log_set_handler (log_domains[i],
604                          G_LOG_LEVEL_MESSAGE,
605                          gimp_message_func,
606                          NULL);
607 
608     g_log_set_handler (NULL,
609                        G_LOG_LEVEL_MESSAGE,
610                        gimp_message_func,
611                        NULL);
612   }
613 
614   if (gimp_debug_flags & GIMP_DEBUG_FATAL_WARNINGS)
615     {
616       GLogLevelFlags fatal_mask;
617 
618       fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK);
619       fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL;
620       g_log_set_always_fatal (fatal_mask);
621 
622       g_log_set_handler (NULL,
623                          G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL |
624                          G_LOG_LEVEL_ERROR | G_LOG_FLAG_FATAL,
625                          gimp_fatal_func, NULL);
626     }
627   else
628     {
629       g_log_set_handler (NULL,
630                          G_LOG_LEVEL_ERROR | G_LOG_FLAG_FATAL,
631                          gimp_fatal_func, NULL);
632     }
633 
634   if (strcmp (argv[ARG_MODE], "-query") == 0)
635     {
636       if (PLUG_IN_INFO.init_proc)
637         gp_has_init_write (_writechannel, NULL);
638 
639       if (gimp_debug_flags & GIMP_DEBUG_QUERY)
640         gimp_debug_stop ();
641 
642       if (PLUG_IN_INFO.query_proc)
643         (* PLUG_IN_INFO.query_proc) ();
644 
645       gimp_close ();
646 
647       return EXIT_SUCCESS;
648     }
649 
650   if (strcmp (argv[ARG_MODE], "-init") == 0)
651     {
652       if (gimp_debug_flags & GIMP_DEBUG_INIT)
653         gimp_debug_stop ();
654 
655       if (PLUG_IN_INFO.init_proc)
656         (* PLUG_IN_INFO.init_proc) ();
657 
658       gimp_close ();
659 
660       return EXIT_SUCCESS;
661     }
662 
663   if (gimp_debug_flags & GIMP_DEBUG_RUN)
664     gimp_debug_stop ();
665   else if (gimp_debug_flags & GIMP_DEBUG_PID)
666     g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "Here I am!");
667 
668   temp_proc_ht = g_hash_table_new (g_str_hash, g_str_equal);
669 
670   g_io_add_watch (_readchannel,
671                   G_IO_ERR | G_IO_HUP,
672                   gimp_plugin_io_error_handler,
673                   NULL);
674 
675   gimp_loop ();
676 
677   return EXIT_SUCCESS;
678 }
679 
680 /**
681  * gimp_quit:
682  *
683  * Forcefully causes the GIMP library to exit and close down its
684  * connection to main gimp application. This function never returns.
685  **/
686 void
gimp_quit(void)687 gimp_quit (void)
688 {
689   gimp_close ();
690 
691 #if defined G_OS_WIN32 && defined HAVE_EXCHNDL
692   if (plug_in_backtrace_path)
693     g_free (plug_in_backtrace_path);
694 #endif
695 
696   exit (EXIT_SUCCESS);
697 }
698 
699 /**
700  * gimp_install_procedure:
701  * @name:          the procedure's name.
702  * @blurb:         a short text describing what the procedure does.
703  * @help:          the help text for the procedure (usually considerably
704  *                 longer than @blurb).
705  * @author:        the procedure's author(s).
706  * @copyright:     the procedure's copyright.
707  * @date:          the date the procedure was added.
708  * @menu_label:    the label to use for the procedure's menu entry,
709  *                 or #NULL if the procedure has no menu entry.
710  * @image_types:   the drawable types the procedure can handle.
711  * @type:          the type of the procedure.
712  * @n_params:      the number of parameters the procedure takes.
713  * @n_return_vals: the number of return values the procedure returns.
714  * @params:        the procedure's parameters.
715  * @return_vals:   the procedure's return values.
716  *
717  * Installs a new procedure with the PDB (procedural database).
718  *
719  * Call this function from within your plug-in's query() function for
720  * each procedure your plug-in implements.
721  *
722  * The @name parameter is mandatory and should be unique, or it will
723  * overwrite an already existing procedure (overwrite procedures only
724  * if you know what you're doing).
725  *
726  * The @blurb, @help, @author, @copyright and @date parameters are
727  * optional but then you shouldn't write procedures without proper
728  * documentation, should you.
729  *
730  * @menu_label defines the label that should be used for the
731  * procedure's menu entry. The position where to register in the menu
732  * hierarchy is chosen using gimp_plugin_menu_register().  This
733  * function also still accepts the old (pre-2.2) way of registering a
734  * menu entry and takes a string in the form
735  * "&lt;Domain&gt;/Path/To/My/Menu"
736  * (e.g. "&lt;Image&gt;/Filters/Render/Useless").
737  *
738  * Note that registering a full (pre-2.2-style) menu path is
739  * deprecated and will cause a failure in GIMP 3.0 and newer.
740  *
741  * It is possible to register a procedure only for keyboard-shortcut
742  * activation by passing a @menu_label to gimp_install_procedure() but
743  * not registering any menu path with gimp_plugin_menu_register(). In
744  * this case, the given @menu_label will only be used as the
745  * procedure's user-visible name in the keyboard shortcut editor.
746  *
747  * @image_types is a comma separated list of image types, or actually
748  * drawable types, that this procedure can deal with. Wildcards are
749  * possible here, so you could say "RGB*" instead of "RGB, RGBA" or
750  * "*" for all image types. If the procedure doesn't need an image to
751  * run, use the empty string.
752  *
753  * @type must be one of %GIMP_PLUGIN or %GIMP_EXTENSION. Note that
754  * temporary procedures must be installed using
755  * gimp_install_temp_proc().
756  *
757  * NOTE: Unlike the GIMP 1.2 API, %GIMP_EXTENSION no longer means
758  * that the procedure's menu prefix is &lt;Toolbox&gt;, but that
759  * it will install temporary procedures. Therefore, the GIMP core
760  * will wait until the %GIMP_EXTENSION procedure has called
761  * gimp_extension_ack(), which means that the procedure has done
762  * its initialization, installed its temporary procedures and is
763  * ready to run.
764  *
765  * <emphasis>Not calling gimp_extension_ack() from a %GIMP_EXTENSION
766  * procedure will cause the GIMP core to lock up.</emphasis>
767  *
768  * Additionally, a %GIMP_EXTENSION procedure with no parameters
769  * (@n_params == 0 and @params == #NULL) is an "automatic" extension
770  * that will be automatically started on each GIMP startup.
771  **/
772 void
gimp_install_procedure(const gchar * name,const gchar * blurb,const gchar * help,const gchar * author,const gchar * copyright,const gchar * date,const gchar * menu_label,const gchar * image_types,GimpPDBProcType type,gint n_params,gint n_return_vals,const GimpParamDef * params,const GimpParamDef * return_vals)773 gimp_install_procedure (const gchar        *name,
774                         const gchar        *blurb,
775                         const gchar        *help,
776                         const gchar        *author,
777                         const gchar        *copyright,
778                         const gchar        *date,
779                         const gchar        *menu_label,
780                         const gchar        *image_types,
781                         GimpPDBProcType     type,
782                         gint                n_params,
783                         gint                n_return_vals,
784                         const GimpParamDef *params,
785                         const GimpParamDef *return_vals)
786 {
787   GPProcInstall proc_install;
788 
789   g_return_if_fail (name != NULL);
790   g_return_if_fail (type != GIMP_INTERNAL);
791   g_return_if_fail ((n_params == 0 && params == NULL) ||
792                     (n_params > 0  && params != NULL));
793   g_return_if_fail ((n_return_vals == 0 && return_vals == NULL) ||
794                     (n_return_vals > 0  && return_vals != NULL));
795 
796   proc_install.name         = (gchar *) name;
797   proc_install.blurb        = (gchar *) blurb;
798   proc_install.help         = (gchar *) help;
799   proc_install.author       = (gchar *) author;
800   proc_install.copyright    = (gchar *) copyright;
801   proc_install.date         = (gchar *) date;
802   proc_install.menu_path    = (gchar *) menu_label;
803   proc_install.image_types  = (gchar *) image_types;
804   proc_install.type         = type;
805   proc_install.nparams      = n_params;
806   proc_install.nreturn_vals = n_return_vals;
807   proc_install.params       = (GPParamDef *) params;
808   proc_install.return_vals  = (GPParamDef *) return_vals;
809 
810   if (! gp_proc_install_write (_writechannel, &proc_install, NULL))
811     gimp_quit ();
812 }
813 
814 /**
815  * gimp_install_temp_proc:
816  * @name:          the procedure's name.
817  * @blurb:         a short text describing what the procedure does.
818  * @help:          the help text for the procedure (usually considerably
819  *                 longer than @blurb).
820  * @author:        the procedure's author(s).
821  * @copyright:     the procedure's copyright.
822  * @date:          the date the procedure was added.
823  * @menu_label:    the procedure's menu label, or #NULL if the procedure has
824  *                 no menu entry.
825  * @image_types:   the drawable types the procedure can handle.
826  * @type:          the type of the procedure.
827  * @n_params:      the number of parameters the procedure takes.
828  * @n_return_vals: the number of return values the procedure returns.
829  * @params:        the procedure's parameters.
830  * @return_vals:   the procedure's return values.
831  * @run_proc:      the function to call for executing the procedure.
832  *
833  * Installs a new temporary procedure with the PDB (procedural database).
834  *
835  * A temporary procedure is a procedure which is only available while
836  * one of your plug-in's "real" procedures is running.
837  *
838  * See gimp_install_procedure() for most details.
839  *
840  * @type <emphasis>must</emphasis> be %GIMP_TEMPORARY or the function
841  * will fail.
842  *
843  * @run_proc is the function which will be called to execute the
844  * procedure.
845  *
846  * NOTE: Normally, plug-in communication is triggered by the plug-in
847  * and the GIMP core only responds to the plug-in's requests. You must
848  * explicitly enable receiving of temporary procedure run requests
849  * using either gimp_extension_enable() or
850  * gimp_extension_process(). See this functions' documentation for
851  * details.
852  **/
853 void
gimp_install_temp_proc(const gchar * name,const gchar * blurb,const gchar * help,const gchar * author,const gchar * copyright,const gchar * date,const gchar * menu_label,const gchar * image_types,GimpPDBProcType type,gint n_params,gint n_return_vals,const GimpParamDef * params,const GimpParamDef * return_vals,GimpRunProc run_proc)854 gimp_install_temp_proc (const gchar        *name,
855                         const gchar        *blurb,
856                         const gchar        *help,
857                         const gchar        *author,
858                         const gchar        *copyright,
859                         const gchar        *date,
860                         const gchar        *menu_label,
861                         const gchar        *image_types,
862                         GimpPDBProcType     type,
863                         gint                n_params,
864                         gint                n_return_vals,
865                         const GimpParamDef *params,
866                         const GimpParamDef *return_vals,
867                         GimpRunProc         run_proc)
868 {
869   g_return_if_fail (name != NULL);
870   g_return_if_fail ((n_params == 0 && params == NULL) ||
871                     (n_params > 0  && params != NULL));
872   g_return_if_fail ((n_return_vals == 0 && return_vals == NULL) ||
873                     (n_return_vals > 0  && return_vals != NULL));
874   g_return_if_fail (type == GIMP_TEMPORARY);
875   g_return_if_fail (run_proc != NULL);
876 
877   gimp_install_procedure (name,
878                           blurb, help,
879                           author, copyright, date,
880                           menu_label,
881                           image_types,
882                           type,
883                           n_params, n_return_vals,
884                           params, return_vals);
885 
886   /*  Insert the temp proc run function into the hash table  */
887   g_hash_table_insert (temp_proc_ht, g_strdup (name), (gpointer) run_proc);
888 }
889 
890 /**
891  * gimp_uninstall_temp_proc:
892  * @name: the procedure's name
893  *
894  * Uninstalls a temporary procedure which has previously been
895  * installed using gimp_install_temp_proc().
896  **/
897 void
gimp_uninstall_temp_proc(const gchar * name)898 gimp_uninstall_temp_proc (const gchar *name)
899 {
900   GPProcUninstall proc_uninstall;
901   gpointer        hash_name;
902   gboolean        found;
903 
904   g_return_if_fail (name != NULL);
905 
906   proc_uninstall.name = (gchar *) name;
907 
908   if (! gp_proc_uninstall_write (_writechannel, &proc_uninstall, NULL))
909     gimp_quit ();
910 
911   found = g_hash_table_lookup_extended (temp_proc_ht, name, &hash_name, NULL);
912   if (found)
913     {
914       g_hash_table_remove (temp_proc_ht, (gpointer) name);
915       g_free (hash_name);
916     }
917 }
918 
919 /**
920  * gimp_run_procedure:
921  * @name:          the name of the procedure to run
922  * @n_return_vals: return location for the number of return values
923  * @...:           list of procedure parameters
924  *
925  * This function calls a GIMP procedure and returns its return values.
926  *
927  * The procedure's parameters are given by a va_list in the format
928  * (type, value, type, value) and must be terminated by %GIMP_PDB_END.
929  *
930  * This function converts the va_list of parameters into an array and
931  * passes them to gimp_run_procedure2(). Please look there for further
932  * information.
933  *
934  * Return value: the procedure's return values unless there was an error,
935  * in which case the zero-th return value will be the error status, and
936  * the first return value will be a string detailing the error.
937  **/
938 GimpParam *
gimp_run_procedure(const gchar * name,gint * n_return_vals,...)939 gimp_run_procedure (const gchar *name,
940                     gint        *n_return_vals,
941                     ...)
942 {
943   GimpPDBArgType  param_type;
944   GimpParam      *return_vals;
945   GimpParam      *params   = NULL;
946   gint            n_params = 0;
947   va_list         args;
948   gint            i;
949 
950   g_return_val_if_fail (name != NULL, NULL);
951   g_return_val_if_fail (n_return_vals != NULL, NULL);
952 
953   va_start (args, n_return_vals);
954   param_type = va_arg (args, GimpPDBArgType);
955 
956   while (param_type != GIMP_PDB_END)
957     {
958       switch (param_type)
959         {
960         case GIMP_PDB_INT32:
961         case GIMP_PDB_DISPLAY:
962         case GIMP_PDB_IMAGE:
963         case GIMP_PDB_ITEM:
964         case GIMP_PDB_LAYER:
965         case GIMP_PDB_CHANNEL:
966         case GIMP_PDB_DRAWABLE:
967         case GIMP_PDB_SELECTION:
968         case GIMP_PDB_VECTORS:
969         case GIMP_PDB_STATUS:
970           (void) va_arg (args, gint);
971           break;
972         case GIMP_PDB_INT16:
973           (void) va_arg (args, gint);
974           break;
975         case GIMP_PDB_INT8:
976           (void) va_arg (args, gint);
977           break;
978         case GIMP_PDB_FLOAT:
979           (void) va_arg (args, gdouble);
980           break;
981         case GIMP_PDB_STRING:
982           (void) va_arg (args, gchar *);
983           break;
984         case GIMP_PDB_INT32ARRAY:
985           (void) va_arg (args, gint32 *);
986           break;
987         case GIMP_PDB_INT16ARRAY:
988           (void) va_arg (args, gint16 *);
989           break;
990         case GIMP_PDB_INT8ARRAY:
991           (void) va_arg (args, gint8 *);
992           break;
993         case GIMP_PDB_FLOATARRAY:
994           (void) va_arg (args, gdouble *);
995           break;
996         case GIMP_PDB_STRINGARRAY:
997           (void) va_arg (args, gchar **);
998           break;
999         case GIMP_PDB_COLOR:
1000         case GIMP_PDB_COLORARRAY:
1001           (void) va_arg (args, GimpRGB *);
1002           break;
1003         case GIMP_PDB_PARASITE:
1004           (void) va_arg (args, GimpParasite *);
1005           break;
1006         case GIMP_PDB_END:
1007           break;
1008         }
1009 
1010       n_params++;
1011 
1012       param_type = va_arg (args, GimpPDBArgType);
1013     }
1014 
1015   va_end (args);
1016 
1017   params = g_new0 (GimpParam, n_params);
1018 
1019   va_start (args, n_return_vals);
1020 
1021   for (i = 0; i < n_params; i++)
1022     {
1023       params[i].type = va_arg (args, GimpPDBArgType);
1024 
1025       switch (params[i].type)
1026         {
1027         case GIMP_PDB_INT32:
1028           params[i].data.d_int32 = (gint32) va_arg (args, gint);
1029           break;
1030         case GIMP_PDB_INT16:
1031           params[i].data.d_int16 = (gint16) va_arg (args, gint);
1032           break;
1033         case GIMP_PDB_INT8:
1034           params[i].data.d_int8 = (guint8) va_arg (args, gint);
1035           break;
1036         case GIMP_PDB_FLOAT:
1037           params[i].data.d_float = (gdouble) va_arg (args, gdouble);
1038           break;
1039         case GIMP_PDB_STRING:
1040           params[i].data.d_string = va_arg (args, gchar *);
1041           break;
1042         case GIMP_PDB_INT32ARRAY:
1043           params[i].data.d_int32array = va_arg (args, gint32 *);
1044           break;
1045         case GIMP_PDB_INT16ARRAY:
1046           params[i].data.d_int16array = va_arg (args, gint16 *);
1047           break;
1048         case GIMP_PDB_INT8ARRAY:
1049           params[i].data.d_int8array = va_arg (args, guint8 *);
1050           break;
1051         case GIMP_PDB_FLOATARRAY:
1052           params[i].data.d_floatarray = va_arg (args, gdouble *);
1053           break;
1054         case GIMP_PDB_STRINGARRAY:
1055           params[i].data.d_stringarray = va_arg (args, gchar **);
1056           break;
1057         case GIMP_PDB_COLOR:
1058           params[i].data.d_color = *va_arg (args, GimpRGB *);
1059           break;
1060         case GIMP_PDB_ITEM:
1061           params[i].data.d_item = va_arg (args, gint32);
1062           break;
1063         case GIMP_PDB_DISPLAY:
1064           params[i].data.d_display = va_arg (args, gint32);
1065           break;
1066         case GIMP_PDB_IMAGE:
1067           params[i].data.d_image = va_arg (args, gint32);
1068           break;
1069         case GIMP_PDB_LAYER:
1070           params[i].data.d_layer = va_arg (args, gint32);
1071           break;
1072         case GIMP_PDB_CHANNEL:
1073           params[i].data.d_channel = va_arg (args, gint32);
1074           break;
1075         case GIMP_PDB_DRAWABLE:
1076           params[i].data.d_drawable = va_arg (args, gint32);
1077           break;
1078         case GIMP_PDB_SELECTION:
1079           params[i].data.d_selection = va_arg (args, gint32);
1080           break;
1081         case GIMP_PDB_COLORARRAY:
1082           params[i].data.d_colorarray = va_arg (args, GimpRGB *);
1083           break;
1084         case GIMP_PDB_VECTORS:
1085           params[i].data.d_vectors = va_arg (args, gint32);
1086           break;
1087         case GIMP_PDB_PARASITE:
1088           {
1089             GimpParasite *parasite = va_arg (args, GimpParasite *);
1090 
1091             if (parasite == NULL)
1092               {
1093                 params[i].data.d_parasite.name = NULL;
1094                 params[i].data.d_parasite.data = NULL;
1095               }
1096             else
1097               {
1098                 params[i].data.d_parasite.name  = parasite->name;
1099                 params[i].data.d_parasite.flags = parasite->flags;
1100                 params[i].data.d_parasite.size  = parasite->size;
1101                 params[i].data.d_parasite.data  = parasite->data;
1102               }
1103           }
1104           break;
1105         case GIMP_PDB_STATUS:
1106           params[i].data.d_status = va_arg (args, gint32);
1107           break;
1108         case GIMP_PDB_END:
1109           break;
1110         }
1111     }
1112 
1113   va_end (args);
1114 
1115   return_vals = gimp_run_procedure2 (name, n_return_vals, n_params, params);
1116 
1117   g_free (params);
1118 
1119   return return_vals;
1120 }
1121 
1122 void
gimp_read_expect_msg(GimpWireMessage * msg,gint type)1123 gimp_read_expect_msg (GimpWireMessage *msg,
1124                       gint             type)
1125 {
1126   while (TRUE)
1127     {
1128       if (! gimp_wire_read_msg (_readchannel, msg, NULL))
1129         gimp_quit ();
1130 
1131       if (msg->type == type)
1132         return; /* up to the caller to call wire_destroy() */
1133 
1134       if (msg->type == GP_TEMP_PROC_RUN || msg->type == GP_QUIT)
1135         {
1136           gimp_process_message (msg);
1137         }
1138       else
1139         {
1140           g_error ("unexpected message: %d", msg->type);
1141         }
1142 
1143       gimp_wire_destroy (msg);
1144     }
1145 }
1146 
1147 /**
1148  * gimp_run_procedure2:
1149  * @name:          the name of the procedure to run
1150  * @n_return_vals: return location for the number of return values
1151  * @n_params:      the number of parameters the procedure takes.
1152  * @params:        the procedure's parameters array.
1153  *
1154  * This function calls a GIMP procedure and returns its return values.
1155  * To get more information about the available procedures and the
1156  * parameters they expect, please have a look at the Procedure Browser
1157  * as found in the Xtns menu in GIMP's toolbox.
1158  *
1159  * As soon as you don't need the return values any longer, you should
1160  * free them using gimp_destroy_params().
1161  *
1162  * Return value: the procedure's return values unless there was an error,
1163  * in which case the zero-th return value will be the error status, and
1164  * if there are two values returned, the other return value will be a
1165  * string detailing the error.
1166  **/
1167 GimpParam *
gimp_run_procedure2(const gchar * name,gint * n_return_vals,gint n_params,const GimpParam * params)1168 gimp_run_procedure2 (const gchar     *name,
1169                      gint            *n_return_vals,
1170                      gint             n_params,
1171                      const GimpParam *params)
1172 {
1173   GPProcRun        proc_run;
1174   GPProcReturn    *proc_return;
1175   GimpWireMessage  msg;
1176   GimpParam       *return_vals;
1177 
1178   g_return_val_if_fail (name != NULL, NULL);
1179   g_return_val_if_fail (n_return_vals != NULL, NULL);
1180 
1181   proc_run.name    = (gchar *) name;
1182   proc_run.nparams = n_params;
1183   proc_run.params  = (GPParam *) params;
1184 
1185   if (! gp_proc_run_write (_writechannel, &proc_run, NULL))
1186     gimp_quit ();
1187 
1188   gimp_read_expect_msg (&msg, GP_PROC_RETURN);
1189 
1190   proc_return = msg.data;
1191 
1192   *n_return_vals = proc_return->nparams;
1193   return_vals    = (GimpParam *) proc_return->params;
1194 
1195   proc_return->nparams = 0;
1196   proc_return->params  = NULL;
1197 
1198   gimp_wire_destroy (&msg);
1199 
1200   gimp_set_pdb_error (return_vals, *n_return_vals);
1201 
1202   return return_vals;
1203 }
1204 
1205 /**
1206  * gimp_destroy_params:
1207  * @params:   the #GimpParam array to destroy
1208  * @n_params: the number of elements in the array
1209  *
1210  * Destroys a #GimpParam array as returned by gimp_run_procedure() or
1211  * gimp_run_procedure2().
1212  **/
1213 void
gimp_destroy_params(GimpParam * params,gint n_params)1214 gimp_destroy_params (GimpParam *params,
1215                      gint       n_params)
1216 {
1217   gp_params_destroy ((GPParam *) params, n_params);
1218 }
1219 
1220 /**
1221  * gimp_destroy_paramdefs:
1222  * @paramdefs: the #GimpParamDef array to destroy
1223  * @n_params:  the number of elements in the array
1224  *
1225  * Destroys a #GimpParamDef array as returned by
1226  * gimp_procedural_db_proc_info().
1227  **/
1228 void
gimp_destroy_paramdefs(GimpParamDef * paramdefs,gint n_params)1229 gimp_destroy_paramdefs (GimpParamDef *paramdefs,
1230                         gint          n_params)
1231 {
1232   while (n_params--)
1233     {
1234       g_free (paramdefs[n_params].name);
1235       g_free (paramdefs[n_params].description);
1236     }
1237 
1238   g_free (paramdefs);
1239 }
1240 
1241 /**
1242  * gimp_get_pdb_error:
1243  *
1244  * Retrieves the error message from the last procedure call.
1245  *
1246  * If a procedure call fails, then it might pass an error message with
1247  * the return values. Plug-ins that are using the libgimp C wrappers
1248  * don't access the procedure return values directly. Thus libgimp
1249  * stores the error message and makes it available with this
1250  * function. The next procedure call unsets the error message again.
1251  *
1252  * The returned string is owned by libgimp and must not be freed or
1253  * modified.
1254  *
1255  * Return value: the error message
1256  *
1257  * Since: 2.6
1258  **/
1259 const gchar *
gimp_get_pdb_error(void)1260 gimp_get_pdb_error (void)
1261 {
1262   if (pdb_error_message && strlen (pdb_error_message))
1263     return pdb_error_message;
1264 
1265   switch (pdb_error_status)
1266     {
1267     case GIMP_PDB_SUCCESS:
1268       /*  procedure executed successfully  */
1269       return _("success");
1270 
1271     case GIMP_PDB_EXECUTION_ERROR:
1272       /*  procedure execution failed       */
1273       return _("execution error");
1274 
1275     case GIMP_PDB_CALLING_ERROR:
1276       /*  procedure called incorrectly     */
1277       return _("calling error");
1278 
1279     case GIMP_PDB_CANCEL:
1280       /*  procedure execution cancelled    */
1281       return _("cancelled");
1282 
1283     default:
1284       return "invalid return status";
1285     }
1286 }
1287 
1288 /**
1289  * gimp_get_pdb_status:
1290  *
1291  * Retrieves the status from the last procedure call.
1292  *
1293  * Return value: the #GimpPDBStatusType.
1294  *
1295  * Since: 2.10
1296  **/
1297 GimpPDBStatusType
gimp_get_pdb_status(void)1298 gimp_get_pdb_status (void)
1299 {
1300   return pdb_error_status;
1301 }
1302 
1303 /**
1304  * gimp_tile_width:
1305  *
1306  * Returns the tile width GIMP is using.
1307  *
1308  * This is a constant value given at plug-in configuration time.
1309  *
1310  * Return value: the tile_width
1311  **/
1312 guint
gimp_tile_width(void)1313 gimp_tile_width (void)
1314 {
1315   return _tile_width;
1316 }
1317 
1318 /**
1319  * gimp_tile_height:
1320  *
1321  * Returns the tile height GIMP is using.
1322  *
1323  * This is a constant value given at plug-in configuration time.
1324  *
1325  * Return value: the tile_height
1326  **/
1327 guint
gimp_tile_height(void)1328 gimp_tile_height (void)
1329 {
1330   return _tile_height;
1331 }
1332 
1333 /**
1334  * gimp_shm_ID:
1335  *
1336  * Returns the shared memory ID used for passing tile data between the
1337  * GIMP core and the plug-in.
1338  *
1339  * This is a constant value given at plug-in configuration time.
1340  *
1341  * Return value: the shared memory ID
1342  **/
1343 gint
gimp_shm_ID(void)1344 gimp_shm_ID (void)
1345 {
1346   return _shm_ID;
1347 }
1348 
1349 /**
1350  * gimp_shm_addr:
1351  *
1352  * Returns the address of the shared memory segment used for passing
1353  * tile data between the GIMP core and the plug-in.
1354  *
1355  * This is a constant value given at plug-in configuration time.
1356  *
1357  * Return value: the shared memory address
1358  **/
1359 guchar *
gimp_shm_addr(void)1360 gimp_shm_addr (void)
1361 {
1362   return _shm_addr;
1363 }
1364 
1365 /**
1366  * gimp_gamma:
1367  *
1368  * Returns the global gamma value GIMP and all its plug-ins should
1369  * use.
1370  *
1371  * This is a constant value.
1372  *
1373  * NOTE: This function will always return 2.2, the gamma value for
1374  * sRGB. If you need the actual gamma value of a drawable, look at its
1375  * format.
1376  *
1377  * See also: gimp_drawable_get_format().
1378  *
1379  * @Deprecated: 2.8.4
1380  *
1381  * Return value: the gamma value
1382  **/
1383 gdouble
gimp_gamma(void)1384 gimp_gamma (void)
1385 {
1386   return 2.2;
1387 }
1388 
1389 /**
1390  * gimp_install_cmap:
1391  *
1392  * Returns whether or not the plug-in should allocate an own colormap
1393  * when running on an 8 bit display. See also: gimp_min_colors().
1394  *
1395  * This is a constant value given at plug-in configuration time.
1396  *
1397  * @Deprecated: 2.8
1398  *
1399  * Return value: the install_cmap boolean
1400  **/
1401 gboolean
gimp_install_cmap(void)1402 gimp_install_cmap (void)
1403 {
1404   return FALSE;
1405 }
1406 
1407 /**
1408  * gimp_min_colors:
1409  *
1410  * Returns the minimum number of colors to use when allocating an own
1411  * colormap on 8 bit displays.
1412  *
1413  * This is a constant value given at plug-in configuration time.
1414  *
1415  * See also: gimp_install_cmap()
1416  *
1417  * @Deprecated: 2.8
1418  *
1419  * Return value: the minimum number of colors to allocate
1420  **/
1421 gint
gimp_min_colors(void)1422 gimp_min_colors (void)
1423 {
1424   return _min_colors;
1425 }
1426 
1427 /**
1428  * gimp_show_tool_tips:
1429  *
1430  * Returns whether or not the plug-in should show tool-tips.
1431  *
1432  * This is a constant value given at plug-in configuration time.
1433  *
1434  * Return value: the show_tool_tips boolean
1435  **/
1436 gboolean
gimp_show_tool_tips(void)1437 gimp_show_tool_tips (void)
1438 {
1439   return _show_tool_tips;
1440 }
1441 
1442 /**
1443  * gimp_show_help_button:
1444  *
1445  * Returns whether or not GimpDialog should automatically add a help
1446  * button if help_func and help_id are given.
1447  *
1448  * This is a constant value given at plug-in configuration time.
1449  *
1450  * Return value: the show_help_button boolean
1451  *
1452  * Since: 2.2
1453  **/
1454 gboolean
gimp_show_help_button(void)1455 gimp_show_help_button (void)
1456 {
1457   return _show_help_button;
1458 }
1459 
1460 /**
1461  * gimp_export_color_profile:
1462  *
1463  * Returns whether file plug-ins should default to exporting the
1464  * image's color profile.
1465  *
1466  * Return value: TRUE if preferences are set to export the color profile.
1467  *
1468  * Since: 2.10.4
1469  **/
1470 gboolean
gimp_export_color_profile(void)1471 gimp_export_color_profile (void)
1472 {
1473   return _export_profile;
1474 }
1475 
1476 /**
1477  * gimp_export_exif:
1478  *
1479  * Returns whether file plug-ins should default to exporting Exif
1480  * metadata, according preferences (original settings is #FALSE since
1481  * metadata can contain sensitive information).
1482  *
1483  * Return value: TRUE if preferences are set to export Exif.
1484  *
1485  * Since: 2.10
1486  **/
1487 gboolean
gimp_export_exif(void)1488 gimp_export_exif (void)
1489 {
1490   return _export_exif;
1491 }
1492 
1493 /**
1494  * gimp_export_xmp:
1495  *
1496  * Returns whether file plug-ins should default to exporting XMP
1497  * metadata, according preferences (original settings is #FALSE since
1498  * metadata can contain sensitive information).
1499  *
1500  * Return value: TRUE if preferences are set to export XMP.
1501  *
1502  * Since: 2.10
1503  **/
1504 gboolean
gimp_export_xmp(void)1505 gimp_export_xmp (void)
1506 {
1507   return _export_xmp;
1508 }
1509 
1510 /**
1511  * gimp_export_iptc:
1512  *
1513  * Returns whether file plug-ins should default to exporting IPTC
1514  * metadata, according preferences (original settings is #FALSE since
1515  * metadata can contain sensitive information).
1516  *
1517  * Return value: TRUE if preferences are set to export IPTC.
1518  *
1519  * Since: 2.10
1520  **/
1521 gboolean
gimp_export_iptc(void)1522 gimp_export_iptc (void)
1523 {
1524   return _export_iptc;
1525 }
1526 
1527 /**
1528  * gimp_check_size:
1529  *
1530  * Returns the size of the checkerboard to be used in previews.
1531  *
1532  * This is a constant value given at plug-in configuration time.
1533  *
1534  * Return value: the check_size value
1535  *
1536  * Since: 2.2
1537  **/
1538 GimpCheckSize
gimp_check_size(void)1539 gimp_check_size (void)
1540 {
1541   return _check_size;
1542 }
1543 
1544 /**
1545  * gimp_check_type:
1546  *
1547  * Returns the type of the checkerboard to be used in previews.
1548  *
1549  * This is a constant value given at plug-in configuration time.
1550  *
1551  * Return value: the check_type value
1552  *
1553  * Since: 2.2
1554  **/
1555 GimpCheckType
gimp_check_type(void)1556 gimp_check_type (void)
1557 {
1558   return _check_type;
1559 }
1560 
1561 /**
1562  * gimp_default_display:
1563  *
1564  * Returns the default display ID. This corresponds to the display the
1565  * running procedure's menu entry was invoked from.
1566  *
1567  * This is a constant value given at plug-in configuration time.
1568  *
1569  * Return value: the default display ID
1570  **/
1571 gint32
gimp_default_display(void)1572 gimp_default_display (void)
1573 {
1574   return _gdisp_ID;
1575 }
1576 
1577 /**
1578  * gimp_wm_class:
1579  *
1580  * Returns the window manager class to be used for plug-in windows.
1581  *
1582  * This is a constant value given at plug-in configuration time.
1583  *
1584  * Return value: the window manager class
1585  **/
1586 const gchar *
gimp_wm_class(void)1587 gimp_wm_class (void)
1588 {
1589   return _wm_class;
1590 }
1591 
1592 /**
1593  * gimp_display_name:
1594  *
1595  * Returns the display to be used for plug-in windows.
1596  *
1597  * This is a constant value given at plug-in configuration time.
1598  * Will return #NULL if GIMP has been started with no GUI, either
1599  * via "--no-interface" flag, or a console build.
1600  *
1601  * Return value: the display name
1602  **/
1603 const gchar *
gimp_display_name(void)1604 gimp_display_name (void)
1605 {
1606   return _display_name;
1607 }
1608 
1609 /**
1610  * gimp_monitor_number:
1611  *
1612  * Returns the monitor number to be used for plug-in windows.
1613  *
1614  * This is a constant value given at plug-in configuration time.
1615  *
1616  * Return value: the monitor number
1617  **/
1618 gint
gimp_monitor_number(void)1619 gimp_monitor_number (void)
1620 {
1621   return _monitor_number;
1622 }
1623 
1624 /**
1625  * gimp_user_time:
1626  *
1627  * Returns the timestamp of the user interaction that should be set on
1628  * the plug-in window. This is handled transparently, plug-in authors
1629  * do not have to care about it.
1630  *
1631  * This is a constant value given at plug-in configuration time.
1632  *
1633  * Return value: timestamp for plug-in window
1634  *
1635  * Since: 2.6
1636  **/
1637 guint32
gimp_user_time(void)1638 gimp_user_time (void)
1639 {
1640   return _timestamp;
1641 }
1642 
1643 /**
1644  * gimp_get_icon_theme_dir:
1645  *
1646  * Returns the directory of the current icon theme.
1647  *
1648  * This is a constant value given at plug-in configuration time.
1649  *
1650  * Return value: the icon theme directory
1651  *
1652  * Since: 2.10.4
1653  **/
1654 const gchar *
gimp_icon_theme_dir(void)1655 gimp_icon_theme_dir (void)
1656 {
1657   return _icon_theme_dir;
1658 }
1659 
1660 /**
1661  * gimp_get_progname:
1662  *
1663  * Returns the plug-in's executable name.
1664  *
1665  * Return value: the executable name
1666  **/
1667 const gchar *
gimp_get_progname(void)1668 gimp_get_progname (void)
1669 {
1670   return progname;
1671 }
1672 
1673 /**
1674  * gimp_extension_ack:
1675  *
1676  * Notify the main GIMP application that the extension has been properly
1677  * initialized and is ready to run.
1678  *
1679  * This function <emphasis>must</emphasis> be called from every
1680  * procedure that was registered as #GIMP_EXTENSION.
1681  *
1682  * Subsequently, extensions can process temporary procedure run
1683  * requests using either gimp_extension_enable() or
1684  * gimp_extension_process().
1685  *
1686  * See also: gimp_install_procedure(), gimp_install_temp_proc()
1687  **/
1688 void
gimp_extension_ack(void)1689 gimp_extension_ack (void)
1690 {
1691   if (! gp_extension_ack_write (_writechannel, NULL))
1692     gimp_quit ();
1693 }
1694 
1695 /**
1696  * gimp_extension_enable:
1697  *
1698  * Enables asynchronous processing of messages from the main GIMP
1699  * application.
1700  *
1701  * Normally, a plug-in is not called by GIMP except for the call to
1702  * the procedure it implements. All subsequent communication is
1703  * triggered by the plug-in and all messages sent from GIMP to the
1704  * plug-in are just answers to requests the plug-in made.
1705  *
1706  * If the plug-in however registered temporary procedures using
1707  * gimp_install_temp_proc(), it needs to be able to receive requests
1708  * to execute them. Usually this will be done by running
1709  * gimp_extension_process() in an endless loop.
1710  *
1711  * If the plug-in cannot use gimp_extension_process(), i.e. if it has
1712  * a GUI and is hanging around in a #GMainLoop, it must call
1713  * gimp_extension_enable().
1714  *
1715  * Note that the plug-in does not need to be a #GIMP_EXTENSION to
1716  * register temporary procedures.
1717  *
1718  * See also: gimp_install_procedure(), gimp_install_temp_proc()
1719  **/
1720 void
gimp_extension_enable(void)1721 gimp_extension_enable (void)
1722 {
1723   static gboolean callback_added = FALSE;
1724 
1725   if (! callback_added)
1726     {
1727       g_io_add_watch (_readchannel, G_IO_IN | G_IO_PRI, gimp_extension_read,
1728                       NULL);
1729 
1730       callback_added = TRUE;
1731     }
1732 }
1733 
1734 /**
1735  * gimp_extension_process:
1736  * @timeout: The timeout (in ms) to use for the select() call.
1737  *
1738  * Processes one message sent by GIMP and returns.
1739  *
1740  * Call this function in an endless loop after calling
1741  * gimp_extension_ack() to process requests for running temporary
1742  * procedures.
1743  *
1744  * See gimp_extension_enable() for an asynchronous way of doing the
1745  * same if running an endless loop is not an option.
1746  *
1747  * See also: gimp_install_procedure(), gimp_install_temp_proc()
1748  **/
1749 void
gimp_extension_process(guint timeout)1750 gimp_extension_process (guint timeout)
1751 {
1752 #ifndef G_OS_WIN32
1753   gint select_val;
1754 
1755   do
1756     {
1757       fd_set readfds;
1758       struct timeval  tv;
1759       struct timeval *tvp;
1760 
1761       if (timeout)
1762         {
1763           tv.tv_sec  = timeout / 1000;
1764           tv.tv_usec = (timeout % 1000) * 1000;
1765           tvp = &tv;
1766         }
1767       else
1768         tvp = NULL;
1769 
1770       FD_ZERO (&readfds);
1771       FD_SET (g_io_channel_unix_get_fd (_readchannel), &readfds);
1772 
1773       if ((select_val = select (FD_SETSIZE, &readfds, NULL, NULL, tvp)) > 0)
1774         {
1775           gimp_single_message ();
1776         }
1777       else if (select_val == -1 && errno != EINTR)
1778         {
1779           perror ("gimp_extension_process");
1780           gimp_quit ();
1781         }
1782     }
1783   while (select_val == -1 && errno == EINTR);
1784 #else
1785   /* Zero means infinite wait for us, but g_poll and
1786    * g_io_channel_win32_poll use -1 to indicate
1787    * infinite wait.
1788    */
1789   GPollFD pollfd;
1790 
1791   if (timeout == 0)
1792     timeout = -1;
1793 
1794   g_io_channel_win32_make_pollfd (_readchannel, G_IO_IN, &pollfd);
1795 
1796   if (g_io_channel_win32_poll (&pollfd, 1, timeout) == 1)
1797     gimp_single_message ();
1798 #endif
1799 }
1800 
1801 /**
1802  * gimp_parasite_find:
1803  * @name: The name of the parasite to find.
1804  *
1805  * Deprecated: Use gimp_get_parasite() instead.
1806  *
1807  * Returns: The found parasite.
1808  **/
1809 GimpParasite *
gimp_parasite_find(const gchar * name)1810 gimp_parasite_find (const gchar *name)
1811 {
1812   return gimp_get_parasite (name);
1813 }
1814 
1815 /**
1816  * gimp_parasite_attach:
1817  * @parasite: The parasite to attach.
1818  *
1819  * Deprecated: Use gimp_attach_parasite() instead.
1820  *
1821  * Returns: TRUE on success.
1822  **/
1823 gboolean
gimp_parasite_attach(const GimpParasite * parasite)1824 gimp_parasite_attach (const GimpParasite *parasite)
1825 {
1826   return gimp_attach_parasite (parasite);
1827 }
1828 
1829 /**
1830  * gimp_parasite_detach:
1831  * @name: The name of the parasite to detach.
1832  *
1833  * Deprecated: Use gimp_detach_parasite() instead.
1834  *
1835  * Returns: TRUE on success.
1836  **/
1837 gboolean
gimp_parasite_detach(const gchar * name)1838 gimp_parasite_detach (const gchar *name)
1839 {
1840   return gimp_detach_parasite (name);
1841 }
1842 
1843 /**
1844  * gimp_parasite_list:
1845  * @num_parasites: The number of attached parasites.
1846  * @parasites: The names of currently attached parasites.
1847  *
1848  * Deprecated: Use gimp_get_parasite_list() instead.
1849  *
1850  * Returns: TRUE on success.
1851  **/
1852 gboolean
gimp_parasite_list(gint * num_parasites,gchar *** parasites)1853 gimp_parasite_list (gint    *num_parasites,
1854                     gchar ***parasites)
1855 {
1856   *parasites = gimp_get_parasite_list (num_parasites);
1857 
1858   return *parasites != NULL;
1859 }
1860 
1861 /**
1862  * gimp_attach_new_parasite:
1863  * @name: the name of the #GimpParasite to create and attach.
1864  * @flags: the flags set on the #GimpParasite.
1865  * @size: the size of the parasite data in bytes.
1866  * @data: a pointer to the data attached with the #GimpParasite.
1867  *
1868  * Convenience function that creates a parasite and attaches it
1869  * to GIMP.
1870  *
1871  * Deprecated: Use gimp_attach_parasite() instead.
1872  *
1873  * Return value: TRUE on successful creation and attachment of
1874  * the new parasite.
1875  *
1876  * See Also: gimp_attach_parasite()
1877  */
1878 gboolean
gimp_attach_new_parasite(const gchar * name,gint flags,gint size,gconstpointer data)1879 gimp_attach_new_parasite (const gchar   *name,
1880                           gint           flags,
1881                           gint           size,
1882                           gconstpointer  data)
1883 {
1884   GimpParasite *parasite = gimp_parasite_new (name, flags, size, data);
1885   gboolean      success;
1886 
1887   success = gimp_attach_parasite (parasite);
1888 
1889   gimp_parasite_free (parasite);
1890 
1891   return success;
1892 }
1893 
1894 
1895 /*  private functions  */
1896 
1897 static void
gimp_close(void)1898 gimp_close (void)
1899 {
1900   if (gimp_debug_flags & GIMP_DEBUG_QUIT)
1901     gimp_debug_stop ();
1902 
1903   if (PLUG_IN_INFO.quit_proc)
1904     (* PLUG_IN_INFO.quit_proc) ();
1905 
1906 #if defined(USE_SYSV_SHM)
1907 
1908   if ((_shm_ID != -1) && _shm_addr)
1909     shmdt ((char *) _shm_addr);
1910 
1911 #elif defined(USE_WIN32_SHM)
1912 
1913   if (shm_handle)
1914     CloseHandle (shm_handle);
1915 
1916 #elif defined(USE_POSIX_SHM)
1917 
1918   if ((_shm_ID != -1) && (_shm_addr != MAP_FAILED))
1919     munmap (_shm_addr, TILE_MAP_SIZE);
1920 
1921 #endif
1922 
1923   gp_quit_write (_writechannel, NULL);
1924 }
1925 
1926 static void
gimp_debug_stop(void)1927 gimp_debug_stop (void)
1928 {
1929 #ifndef G_OS_WIN32
1930 
1931   g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "Waiting for debugger...");
1932   raise (SIGSTOP);
1933 
1934 #else
1935 
1936   HANDLE        hThreadSnap = NULL;
1937   THREADENTRY32 te32        = { 0 };
1938   pid_t         opid        = getpid ();
1939 
1940   g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
1941          "Debugging (restart externally): %ld",
1942          (long int) opid);
1943 
1944   hThreadSnap = CreateToolhelp32Snapshot (TH32CS_SNAPTHREAD, 0);
1945   if (hThreadSnap == INVALID_HANDLE_VALUE)
1946     {
1947       g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
1948              "error getting threadsnap - debugging impossible");
1949       return;
1950     }
1951 
1952   te32.dwSize = sizeof (THREADENTRY32);
1953 
1954   if (Thread32First (hThreadSnap, &te32))
1955     {
1956       do
1957         {
1958           if (te32.th32OwnerProcessID == opid)
1959             {
1960               HANDLE hThread = OpenThread (THREAD_SUSPEND_RESUME, FALSE,
1961                                            te32.th32ThreadID);
1962               SuspendThread (hThread);
1963               CloseHandle (hThread);
1964             }
1965         }
1966       while (Thread32Next (hThreadSnap, &te32));
1967     }
1968   else
1969     {
1970       g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "error getting threads");
1971     }
1972 
1973   CloseHandle (hThreadSnap);
1974 
1975 #endif
1976 }
1977 
1978 static void
gimp_message_func(const gchar * log_domain,GLogLevelFlags log_level,const gchar * message,gpointer data)1979 gimp_message_func (const gchar    *log_domain,
1980                    GLogLevelFlags  log_level,
1981                    const gchar    *message,
1982                    gpointer        data)
1983 {
1984   gimp_message (message);
1985 }
1986 
1987 static void
gimp_fatal_func(const gchar * log_domain,GLogLevelFlags flags,const gchar * message,gpointer data)1988 gimp_fatal_func (const gchar    *log_domain,
1989                  GLogLevelFlags  flags,
1990                  const gchar    *message,
1991                  gpointer        data)
1992 {
1993   const gchar *level;
1994 
1995   switch (flags & G_LOG_LEVEL_MASK)
1996     {
1997     case G_LOG_LEVEL_WARNING:
1998       level = "WARNING";
1999       break;
2000     case G_LOG_LEVEL_CRITICAL:
2001       level = "CRITICAL";
2002       break;
2003     case G_LOG_LEVEL_ERROR:
2004       level = "ERROR";
2005       break;
2006     default:
2007       level = "FATAL";
2008       break;
2009     }
2010 
2011   g_printerr ("%s: %s: %s\n",
2012               progname, level, message);
2013 
2014 #ifndef G_OS_WIN32
2015   switch (stack_trace_mode)
2016     {
2017     case GIMP_STACK_TRACE_NEVER:
2018       break;
2019 
2020     case GIMP_STACK_TRACE_QUERY:
2021         {
2022           sigset_t sigset;
2023 
2024           sigemptyset (&sigset);
2025           sigprocmask (SIG_SETMASK, &sigset, NULL);
2026           gimp_stack_trace_query (progname);
2027         }
2028       break;
2029 
2030     case GIMP_STACK_TRACE_ALWAYS:
2031         {
2032           sigset_t sigset;
2033 
2034           sigemptyset (&sigset);
2035           sigprocmask (SIG_SETMASK, &sigset, NULL);
2036           gimp_stack_trace_print (progname, stdout, NULL);
2037         }
2038       break;
2039     }
2040 #endif
2041 
2042   /* Do not end with gimp_quit().
2043    * We want the plug-in to continue its normal crash course, otherwise
2044    * we won't get the "Plug-in crashed" error in GIMP.
2045    */
2046   exit (EXIT_FAILURE);
2047 }
2048 
2049 #ifdef G_OS_WIN32
2050 
2051 #ifdef HAVE_EXCHNDL
2052 static LONG WINAPI
gimp_plugin_sigfatal_handler(PEXCEPTION_POINTERS pExceptionInfo)2053 gimp_plugin_sigfatal_handler (PEXCEPTION_POINTERS pExceptionInfo)
2054 {
2055   g_printerr ("%s: fatal error\n", progname);
2056 
2057   SetUnhandledExceptionFilter (_prevExceptionFilter);
2058 
2059   /* For simplicity, do not make a difference between QUERY and ALWAYS
2060    * on Windows (at least not for now).
2061    */
2062   if (stack_trace_mode != GIMP_STACK_TRACE_NEVER &&
2063       g_file_test (plug_in_backtrace_path, G_FILE_TEST_IS_REGULAR))
2064     {
2065       FILE   *stream;
2066       guchar  buffer[256];
2067       size_t  read_len;
2068 
2069       stream = fopen (plug_in_backtrace_path, "r");
2070       do
2071         {
2072           /* Just read and output directly the file content. */
2073           read_len = fread (buffer, 1, sizeof (buffer) - 1, stream);
2074           buffer[read_len] = '\0';
2075           g_printerr ("%s", buffer);
2076         }
2077       while (read_len);
2078       fclose (stream);
2079     }
2080 
2081   if (_prevExceptionFilter && _prevExceptionFilter != gimp_plugin_sigfatal_handler)
2082     return _prevExceptionFilter (pExceptionInfo);
2083   else
2084     return EXCEPTION_CONTINUE_SEARCH;
2085 }
2086 #endif
2087 
2088 #else
2089 static void
gimp_plugin_sigfatal_handler(gint sig_num)2090 gimp_plugin_sigfatal_handler (gint sig_num)
2091 {
2092   switch (sig_num)
2093     {
2094     case SIGHUP:
2095     case SIGINT:
2096     case SIGQUIT:
2097     case SIGTERM:
2098       g_printerr ("%s terminated: %s\n", progname, g_strsignal (sig_num));
2099       break;
2100 
2101     case SIGABRT:
2102     case SIGBUS:
2103     case SIGSEGV:
2104     case SIGFPE:
2105     case SIGPIPE:
2106     default:
2107       g_printerr ("%s: fatal error: %s\n", progname, g_strsignal (sig_num));
2108       switch (stack_trace_mode)
2109         {
2110         case GIMP_STACK_TRACE_NEVER:
2111           break;
2112 
2113         case GIMP_STACK_TRACE_QUERY:
2114           {
2115             sigset_t sigset;
2116 
2117             sigemptyset (&sigset);
2118             sigprocmask (SIG_SETMASK, &sigset, NULL);
2119             gimp_stack_trace_query (progname);
2120           }
2121           break;
2122 
2123         case GIMP_STACK_TRACE_ALWAYS:
2124           {
2125             sigset_t sigset;
2126 
2127             sigemptyset (&sigset);
2128             sigprocmask (SIG_SETMASK, &sigset, NULL);
2129             gimp_stack_trace_print (progname, stdout, NULL);
2130           }
2131           break;
2132         }
2133       break;
2134     }
2135 
2136   /* Do not end with gimp_quit().
2137    * We want the plug-in to continue its normal crash course, otherwise
2138    * we won't get the "Plug-in crashed" error in GIMP.
2139    */
2140   exit (EXIT_FAILURE);
2141 }
2142 #endif
2143 
2144 static gboolean
gimp_plugin_io_error_handler(GIOChannel * channel,GIOCondition cond,gpointer data)2145 gimp_plugin_io_error_handler (GIOChannel   *channel,
2146                               GIOCondition  cond,
2147                               gpointer      data)
2148 {
2149   g_printerr ("%s: fatal error: GIMP crashed\n", progname);
2150   gimp_quit ();
2151 
2152   /* never reached */
2153   return TRUE;
2154 }
2155 
2156 static gboolean
gimp_write(GIOChannel * channel,const guint8 * buf,gulong count,gpointer user_data)2157 gimp_write (GIOChannel   *channel,
2158             const guint8 *buf,
2159             gulong        count,
2160             gpointer      user_data)
2161 {
2162   gulong bytes;
2163 
2164   while (count > 0)
2165     {
2166       if ((write_buffer_index + count) >= WRITE_BUFFER_SIZE)
2167         {
2168           bytes = WRITE_BUFFER_SIZE - write_buffer_index;
2169           memcpy (&write_buffer[write_buffer_index], buf, bytes);
2170           write_buffer_index += bytes;
2171           if (! gimp_wire_flush (channel, NULL))
2172             return FALSE;
2173         }
2174       else
2175         {
2176           bytes = count;
2177           memcpy (&write_buffer[write_buffer_index], buf, bytes);
2178           write_buffer_index += bytes;
2179         }
2180 
2181       buf += bytes;
2182       count -= bytes;
2183     }
2184 
2185   return TRUE;
2186 }
2187 
2188 static gboolean
gimp_flush(GIOChannel * channel,gpointer user_data)2189 gimp_flush (GIOChannel *channel,
2190             gpointer    user_data)
2191 {
2192   GIOStatus  status;
2193   GError    *error = NULL;
2194   gsize      count;
2195   gsize      bytes;
2196 
2197   if (write_buffer_index > 0)
2198     {
2199       count = 0;
2200       while (count != write_buffer_index)
2201         {
2202           do
2203             {
2204               bytes = 0;
2205               status = g_io_channel_write_chars (channel,
2206                                                  &write_buffer[count],
2207                                                  (write_buffer_index - count),
2208                                                  &bytes,
2209                                                  &error);
2210             }
2211           while (status == G_IO_STATUS_AGAIN);
2212 
2213           if (status != G_IO_STATUS_NORMAL)
2214             {
2215               if (error)
2216                 {
2217                   g_warning ("%s: gimp_flush(): error: %s",
2218                              g_get_prgname (), error->message);
2219                   g_error_free (error);
2220                 }
2221               else
2222                 {
2223                   g_warning ("%s: gimp_flush(): error", g_get_prgname ());
2224                 }
2225 
2226               return FALSE;
2227             }
2228 
2229           count += bytes;
2230         }
2231 
2232       write_buffer_index = 0;
2233     }
2234 
2235   return TRUE;
2236 }
2237 
2238 static void
gimp_loop(void)2239 gimp_loop (void)
2240 {
2241   GimpWireMessage msg;
2242 
2243   while (TRUE)
2244     {
2245       if (! gimp_wire_read_msg (_readchannel, &msg, NULL))
2246         {
2247           gimp_close ();
2248           return;
2249         }
2250 
2251       switch (msg.type)
2252         {
2253         case GP_QUIT:
2254           gimp_wire_destroy (&msg);
2255           gimp_close ();
2256           return;
2257 
2258         case GP_CONFIG:
2259           gimp_config (msg.data);
2260           break;
2261 
2262         case GP_TILE_REQ:
2263         case GP_TILE_ACK:
2264         case GP_TILE_DATA:
2265           g_warning ("unexpected tile message received (should not happen)");
2266           break;
2267 
2268         case GP_PROC_RUN:
2269           gimp_proc_run (msg.data);
2270           gimp_wire_destroy (&msg);
2271           gimp_close ();
2272           return;
2273 
2274         case GP_PROC_RETURN:
2275           g_warning ("unexpected proc return message received (should not happen)");
2276           break;
2277 
2278         case GP_TEMP_PROC_RUN:
2279           g_warning ("unexpected temp proc run message received (should not happen");
2280           break;
2281 
2282         case GP_TEMP_PROC_RETURN:
2283           g_warning ("unexpected temp proc return message received (should not happen");
2284           break;
2285 
2286         case GP_PROC_INSTALL:
2287           g_warning ("unexpected proc install message received (should not happen)");
2288           break;
2289 
2290         case GP_HAS_INIT:
2291           g_warning ("unexpected has init message received (should not happen)");
2292           break;
2293         }
2294 
2295       gimp_wire_destroy (&msg);
2296     }
2297 }
2298 
2299 static void
gimp_config(GPConfig * config)2300 gimp_config (GPConfig *config)
2301 {
2302   GFile *file;
2303   gchar *path;
2304 
2305   if (config->version < GIMP_PROTOCOL_VERSION)
2306     {
2307       g_message ("Could not execute plug-in \"%s\"\n(%s)\n"
2308                  "because GIMP is using an older version of the "
2309                  "plug-in protocol.",
2310                  gimp_filename_to_utf8 (g_get_prgname ()),
2311                  gimp_filename_to_utf8 (progname));
2312       gimp_quit ();
2313     }
2314   else if (config->version > GIMP_PROTOCOL_VERSION)
2315     {
2316       g_message ("Could not execute plug-in \"%s\"\n(%s)\n"
2317                  "because it uses an obsolete version of the "
2318                  "plug-in protocol.",
2319                  gimp_filename_to_utf8 (g_get_prgname ()),
2320                  gimp_filename_to_utf8 (progname));
2321       gimp_quit ();
2322     }
2323 
2324   _tile_width       = config->tile_width;
2325   _tile_height      = config->tile_height;
2326   _shm_ID           = config->shm_ID;
2327   _check_size       = config->check_size;
2328   _check_type       = config->check_type;
2329   _show_tool_tips   = config->show_tooltips    ? TRUE : FALSE;
2330   _show_help_button = config->show_help_button ? TRUE : FALSE;
2331   _export_profile   = config->export_profile   ? TRUE : FALSE;
2332   _export_exif      = config->export_exif      ? TRUE : FALSE;
2333   _export_xmp       = config->export_xmp       ? TRUE : FALSE;
2334   _export_iptc      = config->export_iptc      ? TRUE : FALSE;
2335   _min_colors       = config->min_colors;
2336   _gdisp_ID         = config->gdisp_ID;
2337   _wm_class         = g_strdup (config->wm_class);
2338   _display_name     = g_strdup (config->display_name);
2339   _monitor_number   = config->monitor_number;
2340   _timestamp        = config->timestamp;
2341   _icon_theme_dir   = g_strdup (config->icon_theme_dir);
2342 
2343   if (config->app_name)
2344     g_set_application_name (config->app_name);
2345 
2346   gimp_cpu_accel_set_use (config->use_cpu_accel);
2347 
2348   file = gimp_file_new_for_config_path (config->swap_path, NULL);
2349   path = g_file_get_path (file);
2350 
2351   g_object_set (gegl_config (),
2352                 "tile-cache-size",     config->tile_cache_size,
2353                 "swap",                path,
2354                 "swap-compression",    config->swap_compression,
2355                 "threads",             (gint) config->num_processors,
2356                 "use-opencl",          config->use_opencl,
2357                 "application-license", "GPL3",
2358                 NULL);
2359 
2360   g_free (path);
2361   g_object_unref (file);
2362 
2363   if (_shm_ID != -1)
2364     {
2365 #if defined(USE_SYSV_SHM)
2366 
2367       /* Use SysV shared memory mechanisms for transferring tile data. */
2368 
2369       _shm_addr = (guchar *) shmat (_shm_ID, NULL, 0);
2370 
2371       if (_shm_addr == (guchar *) -1)
2372         {
2373           g_error ("shmat() failed: %s\n" ERRMSG_SHM_FAILED,
2374                    g_strerror (errno));
2375         }
2376 
2377 #elif defined(USE_WIN32_SHM)
2378 
2379       /* Use Win32 shared memory mechanisms for transferring tile data. */
2380 
2381       gchar fileMapName[128];
2382 
2383       /* From the id, derive the file map name */
2384       g_snprintf (fileMapName, sizeof (fileMapName), "GIMP%d.SHM", _shm_ID);
2385 
2386       /* Open the file mapping */
2387       shm_handle = OpenFileMapping (FILE_MAP_ALL_ACCESS,
2388                                     0, fileMapName);
2389       if (shm_handle)
2390         {
2391           /* Map the shared memory into our address space for use */
2392           _shm_addr = (guchar *) MapViewOfFile (shm_handle,
2393                                                 FILE_MAP_ALL_ACCESS,
2394                                                 0, 0, TILE_MAP_SIZE);
2395 
2396           /* Verify that we mapped our view */
2397           if (!_shm_addr)
2398             {
2399               g_error ("MapViewOfFile error: %lu... " ERRMSG_SHM_FAILED,
2400                        GetLastError ());
2401             }
2402         }
2403       else
2404         {
2405           g_error ("OpenFileMapping error: %lu... " ERRMSG_SHM_FAILED,
2406                    GetLastError ());
2407         }
2408 
2409 #elif defined(USE_POSIX_SHM)
2410 
2411       /* Use POSIX shared memory mechanisms for transferring tile data. */
2412 
2413       gchar map_file[32];
2414       gint  shm_fd;
2415 
2416       /* From the id, derive the file map name */
2417       g_snprintf (map_file, sizeof (map_file), "/gimp-shm-%d", _shm_ID);
2418 
2419       /* Open the file mapping */
2420       shm_fd = shm_open (map_file, O_RDWR, 0600);
2421 
2422       if (shm_fd != -1)
2423         {
2424           /* Map the shared memory into our address space for use */
2425           _shm_addr = (guchar *) mmap (NULL, TILE_MAP_SIZE,
2426                                        PROT_READ | PROT_WRITE, MAP_SHARED,
2427                                        shm_fd, 0);
2428 
2429           /* Verify that we mapped our view */
2430           if (_shm_addr == MAP_FAILED)
2431             {
2432               g_error ("mmap() failed: %s\n" ERRMSG_SHM_FAILED,
2433                        g_strerror (errno));
2434             }
2435 
2436           close (shm_fd);
2437         }
2438       else
2439         {
2440           g_error ("shm_open() failed: %s\n" ERRMSG_SHM_FAILED,
2441                    g_strerror (errno));
2442         }
2443 
2444 #endif
2445     }
2446 }
2447 
2448 static void
gimp_proc_run(GPProcRun * proc_run)2449 gimp_proc_run (GPProcRun *proc_run)
2450 {
2451   if (PLUG_IN_INFO.run_proc)
2452     {
2453       GPProcReturn  proc_return;
2454       GimpParam    *return_vals;
2455       gint          n_return_vals;
2456 
2457       (* PLUG_IN_INFO.run_proc) (proc_run->name,
2458                                  proc_run->nparams,
2459                                  (GimpParam *) proc_run->params,
2460                                  &n_return_vals, &return_vals);
2461 
2462       proc_return.name    = proc_run->name;
2463       proc_return.nparams = n_return_vals;
2464       proc_return.params  = (GPParam *) return_vals;
2465 
2466       if (! gp_proc_return_write (_writechannel, &proc_return, NULL))
2467         gimp_quit ();
2468     }
2469 }
2470 
2471 static void
gimp_temp_proc_run(GPProcRun * proc_run)2472 gimp_temp_proc_run (GPProcRun *proc_run)
2473 {
2474   GimpRunProc run_proc = g_hash_table_lookup (temp_proc_ht, proc_run->name);
2475 
2476   if (run_proc)
2477     {
2478       GPProcReturn  proc_return;
2479       GimpParam    *return_vals;
2480       gint          n_return_vals;
2481 
2482 #ifdef GDK_WINDOWING_QUARTZ
2483       if (proc_run->params &&
2484           proc_run->params[0].data.d_int32 == GIMP_RUN_INTERACTIVE)
2485         {
2486           [NSApp activateIgnoringOtherApps: YES];
2487         }
2488 #endif
2489 
2490       (* run_proc) (proc_run->name,
2491                     proc_run->nparams,
2492                     (GimpParam *) proc_run->params,
2493                     &n_return_vals, &return_vals);
2494 
2495       proc_return.name    = proc_run->name;
2496       proc_return.nparams = n_return_vals;
2497       proc_return.params  = (GPParam *) return_vals;
2498 
2499       if (! gp_temp_proc_return_write (_writechannel, &proc_return, NULL))
2500         gimp_quit ();
2501     }
2502 }
2503 
2504 static void
gimp_process_message(GimpWireMessage * msg)2505 gimp_process_message (GimpWireMessage *msg)
2506 {
2507   switch (msg->type)
2508     {
2509     case GP_QUIT:
2510       gimp_quit ();
2511       break;
2512     case GP_CONFIG:
2513       gimp_config (msg->data);
2514       break;
2515     case GP_TILE_REQ:
2516     case GP_TILE_ACK:
2517     case GP_TILE_DATA:
2518       g_warning ("unexpected tile message received (should not happen)");
2519       break;
2520     case GP_PROC_RUN:
2521       g_warning ("unexpected proc run message received (should not happen)");
2522       break;
2523     case GP_PROC_RETURN:
2524       g_warning ("unexpected proc return message received (should not happen)");
2525       break;
2526     case GP_TEMP_PROC_RUN:
2527       gimp_temp_proc_run (msg->data);
2528       break;
2529     case GP_TEMP_PROC_RETURN:
2530       g_warning ("unexpected temp proc return message received (should not happen)");
2531       break;
2532     case GP_PROC_INSTALL:
2533       g_warning ("unexpected proc install message received (should not happen)");
2534       break;
2535     case GP_HAS_INIT:
2536       g_warning ("unexpected has init message received (should not happen)");
2537       break;
2538     }
2539 }
2540 
2541 static void
gimp_single_message(void)2542 gimp_single_message (void)
2543 {
2544   GimpWireMessage msg;
2545 
2546   /* Run a temp function */
2547   if (! gimp_wire_read_msg (_readchannel, &msg, NULL))
2548     gimp_quit ();
2549 
2550   gimp_process_message (&msg);
2551 
2552   gimp_wire_destroy (&msg);
2553 }
2554 
2555 static gboolean
gimp_extension_read(GIOChannel * channel,GIOCondition condition,gpointer data)2556 gimp_extension_read (GIOChannel  *channel,
2557                      GIOCondition condition,
2558                      gpointer     data)
2559 {
2560   gimp_single_message ();
2561 
2562   return TRUE;
2563 }
2564 
2565 static void
gimp_set_pdb_error(const GimpParam * return_vals,gint n_return_vals)2566 gimp_set_pdb_error (const GimpParam *return_vals,
2567                     gint             n_return_vals)
2568 {
2569   if (pdb_error_message)
2570     {
2571       g_free (pdb_error_message);
2572       pdb_error_message = NULL;
2573     }
2574 
2575   pdb_error_status = return_vals[0].data.d_status;
2576 
2577   switch (pdb_error_status)
2578     {
2579     case GIMP_PDB_SUCCESS:
2580     case GIMP_PDB_PASS_THROUGH:
2581       break;
2582 
2583     case GIMP_PDB_EXECUTION_ERROR:
2584     case GIMP_PDB_CALLING_ERROR:
2585     case GIMP_PDB_CANCEL:
2586       if (n_return_vals > 1 && return_vals[1].type == GIMP_PDB_STRING)
2587         {
2588           pdb_error_message = g_strdup (return_vals[1].data.d_string);
2589         }
2590       break;
2591     }
2592 }
2593