gimputils.c 43.4 KB
Newer Older
1 2 3 4 5 6
/* LIBGIMP - The GIMP Library
 * Copyright (C) 1995-1997 Spencer Kimball and Peter Mattis
 *
 * gimputils.c
 * Copyright (C) 2003  Sven Neumann <sven@gimp.org>
 *
7
 * This library is free software: you can redistribute it and/or
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 3 of the License, or (at your option) any later version.
11
 *
12
 * This library is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
19
 * <https://www.gnu.org/licenses/>.
20 21 22 23
 */

#include "config.h"

24
#include <stdlib.h>
25
#include <string.h>
26
#include <stdio.h>
27

28 29 30 31
#ifdef PLATFORM_OSX
#include <AppKit/AppKit.h>
#endif

32 33 34 35 36
#ifdef HAVE_EXECINFO_H
/* Allowing backtrace() API. */
#include <execinfo.h>
#endif

37
#include <gio/gio.h>
38
#include <glib/gprintf.h>
39

40
#if defined(G_OS_WIN32)
41 42
# include <windows.h>
# include <shlobj.h>
43

44
#else /* G_OS_WIN32 */
45

46 47
/* For waitpid() */
#include <sys/wait.h>
48 49 50
#include <unistd.h>
#include <errno.h>

51 52 53 54
/* For thread IDs. */
#include <sys/types.h>
#include <sys/syscall.h>

55 56 57
#ifdef HAVE_SYS_PRCTL_H
#include <sys/prctl.h>
#endif
58

59 60 61 62
#ifdef HAVE_SYS_THR_H
#include <sys/thr.h>
#endif

63
#endif /* G_OS_WIN32 */
64

65
#include "gimpbasetypes.h"
66 67
#include "gimputils.h"

68 69
#include "libgimp/libgimp-intl.h"

70

71 72 73 74 75 76 77 78
/**
 * SECTION: gimputils
 * @title: gimputils
 * @short_description: Utilities of general interest
 *
 * Utilities of general interest
 **/

79 80 81 82 83
static gboolean gimp_utils_generic_available (const gchar *program,
                                              gint         major,
                                              gint         minor);
static gboolean gimp_utils_gdb_available     (gint         major,
                                              gint         minor);
84

85 86 87
/**
 * gimp_utf8_strtrim:
 * @str: an UTF-8 encoded string (or %NULL)
88 89
 * @max_chars: the maximum number of characters before the string get
 * trimmed
90
 *
91 92 93
 * Creates a (possibly trimmed) copy of @str. The string is cut if it
 * exceeds @max_chars characters or on the first newline. The fact
 * that the string was trimmed is indicated by appending an ellipsis.
94
 *
95 96
 * Returns: A (possibly trimmed) copy of @str which should be freed
 * using g_free() when it is not needed any longer.
97 98 99
 **/
gchar *
gimp_utf8_strtrim (const gchar *str,
Sven Neumann's avatar
Sven Neumann committed
100
                   gint         max_chars)
101 102
{
  /* FIXME: should we make this translatable? */
103
  const gchar ellipsis[] = "...";
Sven Neumann's avatar
Sven Neumann committed
104
  const gint  e_len      = strlen (ellipsis);
105 106 107 108 109 110 111 112

  if (str)
    {
      const gchar *p;
      const gchar *newline = NULL;
      gint         chars   = 0;
      gunichar     unichar;

Sven Neumann's avatar
Sven Neumann committed
113
      for (p = str; *p; p = g_utf8_next_char (p))
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
        {
          if (++chars > max_chars)
            break;

          unichar = g_utf8_get_char (p);

          switch (g_unichar_break_type (unichar))
            {
            case G_UNICODE_BREAK_MANDATORY:
            case G_UNICODE_BREAK_LINE_FEED:
              newline = p;
              break;
            default:
              continue;
            }

Sven Neumann's avatar
Sven Neumann committed
130
          break;
131 132
        }

133
      if (*p)
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        {
          gsize  len     = p - str;
          gchar *trimmed = g_new (gchar, len + e_len + 2);

          memcpy (trimmed, str, len);
          if (newline)
            trimmed[len++] = ' ';

          g_strlcpy (trimmed + len, ellipsis, e_len + 1);

          return trimmed;
        }

      return g_strdup (str);
    }

  return NULL;
}
152

153 154 155 156 157 158 159 160
/**
 * gimp_any_to_utf8:
 * @str:            The string to be converted to UTF-8.
 * @len:            The length of the string, or -1 if the string
 *                  is nul-terminated.
 * @warning_format: The message format for the warning message if conversion
 *                  to UTF-8 fails. See the <function>printf()</function>
 *                  documentation.
161
 * @...:            The parameters to insert into the format string.
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
 *
 * This function takes any string (UTF-8 or not) and always returns a valid
 * UTF-8 string.
 *
 * If @str is valid UTF-8, a copy of the string is returned.
 *
 * If UTF-8 validation fails, g_locale_to_utf8() is tried and if it
 * succeeds the resulting string is returned.
 *
 * Otherwise, the portion of @str that is UTF-8, concatenated
 * with "(invalid UTF-8 string)" is returned. If not even the start
 * of @str is valid UTF-8, only "(invalid UTF-8 string)" is returned.
 *
 * Return value: The UTF-8 string as described above.
 **/
gchar *
gimp_any_to_utf8 (const gchar  *str,
                  gssize        len,
                  const gchar  *warning_format,
                  ...)
{
  const gchar *start_invalid;
  gchar       *utf8;

  g_return_val_if_fail (str != NULL, NULL);

  if (g_utf8_validate (str, len, &start_invalid))
189 190 191 192 193 194
    {
      if (len < 0)
        utf8 = g_strdup (str);
      else
        utf8 = g_strndup (str, len);
    }
195
  else
196 197 198
    {
      utf8 = g_locale_to_utf8 (str, len, NULL, NULL, NULL);
    }
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218

  if (! utf8)
    {
      if (warning_format)
        {
          va_list warning_args;

          va_start (warning_args, warning_format);

          g_logv (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE,
                  warning_format, warning_args);

          va_end (warning_args);
        }

      if (start_invalid > str)
        {
          gchar *tmp;

          tmp = g_strndup (str, start_invalid - str);
219
          utf8 = g_strconcat (tmp, " ", _("(invalid UTF-8 string)"), NULL);
220 221 222 223 224 225 226 227 228 229 230
          g_free (tmp);
        }
      else
        {
          utf8 = g_strdup (_("(invalid UTF-8 string)"));
        }
    }

  return utf8;
}

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
/**
 * gimp_filename_to_utf8:
 * @filename: The filename to be converted to UTF-8.
 *
 * Convert a filename in the filesystem's encoding to UTF-8
 * temporarily.  The return value is a pointer to a string that is
 * guaranteed to be valid only during the current iteration of the
 * main loop or until the next call to gimp_filename_to_utf8().
 *
 * The only purpose of this function is to provide an easy way to pass
 * a filename in the filesystem encoding to a function that expects an
 * UTF-8 encoded filename.
 *
 * Return value: A temporarily valid UTF-8 representation of @filename.
 *               This string must not be changed or freed.
 **/
const gchar *
gimp_filename_to_utf8 (const gchar *filename)
{
  /* Simpleminded implementation, but at least allocates just one copy
   * of each translation. Could check if already UTF-8, and if so
   * return filename as is. Could perhaps (re)use a suitably large
   * cyclic buffer, but then would have to verify that all calls
   * really need the return value just for a "short" time.
   */

  static GHashTable *ht = NULL;
  gchar             *filename_utf8;

  if (! filename)
    return NULL;

  if (! ht)
    ht = g_hash_table_new (g_str_hash, g_str_equal);

  filename_utf8 = g_hash_table_lookup (ht, filename);

  if (! filename_utf8)
    {
270
      filename_utf8 = g_filename_display_name (filename);
271 272 273 274 275 276
      g_hash_table_insert (ht, g_strdup (filename), filename_utf8);
    }

  return filename_utf8;
}

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
/**
 * gimp_file_get_utf8_name:
 * @file: a #GFile
 *
 * This function works like gimp_filename_to_utf8() and returns
 * a UTF-8 encoded string that does not need to be freed.
 *
 * It converts a #GFile's path or uri to UTF-8 temporarily.  The
 * return value is a pointer to a string that is guaranteed to be
 * valid only during the current iteration of the main loop or until
 * the next call to gimp_file_get_utf8_name().
 *
 * The only purpose of this function is to provide an easy way to pass
 * a #GFile's name to a function that expects an UTF-8 encoded string.
 *
 * See g_file_get_parse_name().
 *
294
 * Since: 2.10
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
 *
 * Return value: A temporarily valid UTF-8 representation of @file's name.
 *               This string must not be changed or freed.
 **/
const gchar *
gimp_file_get_utf8_name (GFile *file)
{
  gchar *name;

  g_return_val_if_fail (G_IS_FILE (file), NULL);

  name = g_file_get_parse_name (file);

  g_object_set_data_full (G_OBJECT (file), "gimp-parse-name", name,
                          (GDestroyNotify) g_free);

  return name;
}
313

314 315 316 317 318 319 320 321 322
/**
 * gimp_file_has_extension:
 * @file:      a #GFile
 * @extension: an ASCII extension
 *
 * This function checks if @file's URI ends with @extension. It behaves
 * like g_str_has_suffix() on g_file_get_uri(), except that the string
 * comparison is done case-insensitively using g_ascii_strcasecmp().
 *
323
 * Since: 2.10
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
 *
 * Return value: %TRUE if @file's URI ends with @extension,
 *               %FALSE otherwise.
 **/
gboolean
gimp_file_has_extension (GFile       *file,
                         const gchar *extension)
{
  gchar    *uri;
  gint      uri_len;
  gint      ext_len;
  gboolean  result = FALSE;

  g_return_val_if_fail (G_IS_FILE (file), FALSE);
  g_return_val_if_fail (extension != NULL, FALSE);

  uri = g_file_get_uri (file);

  uri_len = strlen (uri);
  ext_len = strlen (extension);

  if (uri_len && ext_len && (uri_len > ext_len))
    {
      if (g_ascii_strcasecmp (uri + uri_len - ext_len, extension) == 0)
        result = TRUE;
    }

  g_free (uri);

  return result;
}

356 357 358 359 360 361 362
/**
 * gimp_file_show_in_file_manager:
 * @file:  a #GFile
 * @error: return location for a #GError
 *
 * Shows @file in the system file manager.
 *
363
 * Since: 2.10
364
 *
365
 * Return value: %TRUE on success, %FALSE otherwise. On %FALSE, @error
366 367 368 369 370 371 372 373 374 375 376 377
 *               is set.
 **/
gboolean
gimp_file_show_in_file_manager (GFile   *file,
                                GError **error)
{
  g_return_val_if_fail (G_IS_FILE (file), FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

#if defined(G_OS_WIN32)

  {
378 379 380 381 382 383 384
    gboolean ret;
    char *filename;
    int n;
    LPWSTR w_filename = NULL;
    ITEMIDLIST *pidl = NULL;

    ret = FALSE;
385

386
    /* Calling this function multiple times should do no harm, but it is
387 388 389 390 391 392 393
       easier to put this here as it needs linking against ole32. */
    CoInitialize (NULL);

    filename = g_file_get_path (file);
    if (!filename)
      {
        g_set_error_literal (error, G_FILE_ERROR, 0,
394
                             _("File path is NULL"));
395 396 397 398 399 400 401 402
        goto out;
      }

    n = MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
                             filename, -1, NULL, 0);
    if (n == 0)
      {
        g_set_error_literal (error, G_FILE_ERROR, 0,
403
                             _("Error converting UTF-8 filename to wide char"));
404 405 406 407 408 409 410 411 412 413
        goto out;
      }

    w_filename = g_malloc_n (n + 1, sizeof (wchar_t));
    n = MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
                             filename, -1,
                             w_filename, (n + 1) * sizeof (wchar_t));
    if (n == 0)
      {
        g_set_error_literal (error, G_FILE_ERROR, 0,
414
                             _("Error converting UTF-8 filename to wide char"));
415 416 417 418 419 420 421
        goto out;
      }

    pidl = ILCreateFromPathW (w_filename);
    if (!pidl)
      {
        g_set_error_literal (error, G_FILE_ERROR, 0,
422
                             _("ILCreateFromPath() failed"));
423 424 425 426 427 428 429 430 431 432 433 434 435
        goto out;
      }

    SHOpenFolderAndSelectItems (pidl, 0, NULL, 0);
    ret = TRUE;

  out:
    if (pidl)
      ILFree (pidl);
    g_free (w_filename);
    g_free (filename);

    return ret;
436 437 438 439 440
  }

#elif defined(PLATFORM_OSX)

  {
441 442 443 444
    gchar    *uri;
    NSString *filename;
    NSURL    *url;
    gboolean  retval = TRUE;
445

446 447
    uri = g_file_get_uri (file);
    filename = [NSString stringWithUTF8String:uri];
448

449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    url = [NSURL URLWithString:filename];
    if (url)
      {
        NSArray *url_array = [NSArray arrayWithObject:url];

        [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:url_array];
      }
    else
      {
        g_set_error (error, G_FILE_ERROR, 0,
                     _("Cannot convert '%s' into a valid NSURL."), uri);
        retval = FALSE;
      }

    g_free (uri);

    return retval;
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
  }

#else /* UNIX */

  {
    GDBusProxy      *proxy;
    GVariant        *retval;
    GVariantBuilder *builder;
    gchar           *uri;

    proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION,
                                           G_DBUS_PROXY_FLAGS_NONE,
                                           NULL,
                                           "org.freedesktop.FileManager1",
                                           "/org/freedesktop/FileManager1",
                                           "org.freedesktop.FileManager1",
                                           NULL, error);

    if (! proxy)
      {
        g_prefix_error (error,
                        _("Connecting to org.freedesktop.FileManager1 failed: "));
        return FALSE;
      }

    uri = g_file_get_uri (file);

    builder = g_variant_builder_new (G_VARIANT_TYPE ("as"));
    g_variant_builder_add (builder, "s", uri);

    g_free (uri);

    retval = g_dbus_proxy_call_sync (proxy,
                                     "ShowItems",
                                     g_variant_new ("(ass)",
                                                    builder,
                                                    ""),
                                     G_DBUS_CALL_FLAGS_NONE,
                                     -1, NULL, error);

    g_variant_builder_unref (builder);
    g_object_unref (proxy);

    if (! retval)
      {
        g_prefix_error (error, _("Calling ShowItems failed: "));
        return FALSE;
      }

    g_variant_unref (retval);

    return TRUE;
  }

#endif
}

523 524
/**
 * gimp_strip_uline:
525
 * @str: underline infested string (or %NULL)
526 527 528 529 530
 *
 * This function returns a copy of @str stripped of underline
 * characters. This comes in handy when needing to strip mnemonics
 * from menu paths etc.
 *
531 532 533
 * In some languages, mnemonics are handled by adding the mnemonic
 * character in brackets (like "File (_F)"). This function recognizes
 * this construct and removes the whole bracket construction to get
534
 * rid of the mnemonic (see bug 157561).
535
 *
536
 * Return value: A (possibly stripped) copy of @str which should be
537
 *               freed using g_free() when it is not needed any longer.
538 539 540 541
 **/
gchar *
gimp_strip_uline (const gchar *str)
{
542 543 544
  gchar    *escaped;
  gchar    *p;
  gboolean  past_bracket = FALSE;
545 546 547 548 549 550 551 552 553 554 555 556

  if (! str)
    return NULL;

  p = escaped = g_strdup (str);

  while (*str)
    {
      if (*str == '_')
        {
          /*  "__" means a literal "_" in the menu path  */
          if (str[1] == '_')
557 558
            {
             *p++ = *str++;
559 560
             str++;
             continue;
561
            }
562

563 564 565 566 567 568 569 570 571 572
          /*  find the "(_X)" construct and remove it entirely  */
          if (past_bracket && str[1] && *(g_utf8_next_char (str + 1)) == ')')
            {
              str = g_utf8_next_char (str + 1) + 1;
              p--;
            }
          else
            {
              str++;
            }
573 574 575
        }
      else
        {
576 577
          past_bracket = (*str == '(');

578 579 580 581 582 583 584 585
          *p++ = *str++;
        }
    }

  *p = '\0';

  return escaped;
}
586 587 588 589 590 591 592 593 594 595 596 597

/**
 * gimp_escape_uline:
 * @str: Underline infested string (or %NULL)
 *
 * This function returns a copy of @str with all underline converted
 * to two adjacent underlines. This comes in handy when needing to display
 * strings with underlines (like filenames) in a place that would convert
 * them to mnemonics.
 *
 * Return value: A (possibly escaped) copy of @str which should be
 * freed using g_free() when it is not needed any longer.
Michael Natterer's avatar
Michael Natterer committed
598
 *
599
 * Since: 2.2
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
 **/
gchar *
gimp_escape_uline (const gchar *str)
{
  gchar *escaped;
  gchar *p;
  gint   n_ulines = 0;

  if (! str)
    return NULL;

  for (p = (gchar *) str; *p; p++)
    if (*p == '_')
      n_ulines++;

  p = escaped = g_malloc (strlen (str) + n_ulines + 1);

  while (*str)
    {
      if (*str == '_')
        *p++ = '_';

      *p++ = *str++;
    }

  *p = '\0';

  return escaped;
}
629

630 631 632 633 634 635 636
/**
 * gimp_canonicalize_identifier:
 * @identifier: The identifier string to canonicalize.
 *
 * Turns any input string into a canonicalized string.
 *
 * Canonical identifiers are e.g. expected by the PDB for procedure
637 638
 * and parameter names. Every character of the input string that is
 * not either '-', 'a-z', 'A-Z' or '0-9' will be replaced by a '-'.
639 640 641 642
 *
 * Return value: The canonicalized identifier. This is a newly
 *               allocated string that should be freed with g_free()
 *               when no longer needed.
643
 *
644
 * Since: 2.4
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
 **/
gchar *
gimp_canonicalize_identifier (const gchar *identifier)
{
  gchar *canonicalized = NULL;

  if (identifier)
    {
      gchar *p;

      canonicalized = g_strdup (identifier);

      for (p = canonicalized; *p != 0; p++)
        {
          gchar c = *p;

          if (c != '-' &&
              (c < '0' || c > '9') &&
              (c < 'A' || c > 'Z') &&
              (c < 'a' || c > 'z'))
            *p = '-';
        }
    }

  return canonicalized;
}

672 673 674 675 676 677 678 679 680
/**
 * gimp_enum_get_desc:
 * @enum_class: a #GEnumClass
 * @value:      a value from @enum_class
 *
 * Retrieves #GimpEnumDesc associated with the given value, or %NULL.
 *
 * Return value: the value's #GimpEnumDesc.
 *
681
 * Since: 2.2
682
 **/
683 684 685 686 687 688 689 690
GimpEnumDesc *
gimp_enum_get_desc (GEnumClass *enum_class,
                    gint        value)
{
  const GimpEnumDesc *value_desc;

  g_return_val_if_fail (G_IS_ENUM_CLASS (enum_class), NULL);

691 692
  value_desc =
    gimp_enum_get_value_descriptions (G_TYPE_FROM_CLASS (enum_class));
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707

  if (value_desc)
    {
      while (value_desc->value_desc)
        {
          if (value_desc->value == value)
            return (GimpEnumDesc *) value_desc;

          value_desc++;
        }
    }

  return NULL;
}

708 709 710 711
/**
 * gimp_enum_get_value:
 * @enum_type:  the #GType of a registered enum
 * @value:      an integer value
712
 * @value_name: return location for the value's name (or %NULL)
713
 * @value_nick: return location for the value's nick (or %NULL)
Sven Neumann's avatar
Sven Neumann committed
714
 * @value_desc: return location for the value's translated description (or %NULL)
715
 * @value_help: return location for the value's translated help (or %NULL)
716 717
 *
 * Checks if @value is valid for the enum registered as @enum_type.
718
 * If the value exists in that enum, its name, nick and its translated
Sven Neumann's avatar
Sven Neumann committed
719 720
 * description and help are returned (if @value_name, @value_nick,
 * @value_desc and @value_help are not %NULL).
721 722 723 724
 *
 * Return value: %TRUE if @value is valid for the @enum_type,
 *               %FALSE otherwise
 *
725
 * Since: 2.2
726 727 728 729
 **/
gboolean
gimp_enum_get_value (GType         enum_type,
                     gint          value,
730
                     const gchar **value_name,
731
                     const gchar **value_nick,
732 733
                     const gchar **value_desc,
                     const gchar **value_help)
734 735 736
{
  GEnumClass *enum_class;
  GEnumValue *enum_value;
737
  gboolean    success = FALSE;
738 739 740

  g_return_val_if_fail (G_TYPE_IS_ENUM (enum_type), FALSE);

741
  enum_class = g_type_class_ref (enum_type);
742 743 744 745
  enum_value = g_enum_get_value (enum_class, value);

  if (enum_value)
    {
746 747 748
      if (value_name)
        *value_name = enum_value->value_name;

749 750 751
      if (value_nick)
        *value_nick = enum_value->value_nick;

752 753 754 755 756 757
      if (value_desc || value_help)
        {
          GimpEnumDesc *enum_desc;

          enum_desc = gimp_enum_get_desc (enum_class, value);

758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
          if (value_desc)
            {
              if (enum_desc && enum_desc->value_desc)
                {
                  const gchar *context;

                  context = gimp_type_get_translation_context (enum_type);

                  if (context)  /*  the new way, using NC_()    */
                    *value_desc = g_dpgettext2 (gimp_type_get_translation_domain (enum_type),
                                                context,
                                                enum_desc->value_desc);
                  else          /*  for backward compatibility  */
                    *value_desc = g_strip_context (enum_desc->value_desc,
                                                   dgettext (gimp_type_get_translation_domain (enum_type),
                                                             enum_desc->value_desc));
                }
              else
                {
                  *value_desc = NULL;
                }
            }
780 781

          if (value_help)
782 783 784 785 786 787
            {
              *value_help = ((enum_desc && enum_desc->value_help) ?
                             dgettext (gimp_type_get_translation_domain (enum_type),
                                       enum_desc->value_help) :
                             NULL);
            }
788 789
        }

790
      success = TRUE;
791 792
    }

793 794 795
  g_type_class_unref (enum_class);

  return success;
796 797 798
}

/**
799 800 801 802
 * gimp_enum_value_get_desc:
 * @enum_class: a #GEnumClass
 * @enum_value: a #GEnumValue from @enum_class
 *
803
 * Retrieves the translated description for a given @enum_value.
804
 *
805
 * Return value: the translated description of the enum value
806
 *
807
 * Since: 2.2
808 809 810 811 812 813 814 815 816 817
 **/
const gchar *
gimp_enum_value_get_desc (GEnumClass *enum_class,
                          GEnumValue *enum_value)
{
  GType         type = G_TYPE_FROM_CLASS (enum_class);
  GimpEnumDesc *enum_desc;

  enum_desc = gimp_enum_get_desc (enum_class, enum_value->value);

818
  if (enum_desc && enum_desc->value_desc)
819 820 821 822 823 824 825 826 827 828 829 830 831 832
    {
      const gchar *context;

      context = gimp_type_get_translation_context (type);

      if (context)  /*  the new way, using NC_()    */
        return g_dpgettext2 (gimp_type_get_translation_domain (type),
                             context,
                             enum_desc->value_desc);
      else          /*  for backward compatibility  */
        return g_strip_context (enum_desc->value_desc,
                                dgettext (gimp_type_get_translation_domain (type),
                                          enum_desc->value_desc));
    }
833 834 835 836 837 838 839 840 841 842 843 844 845

  return enum_value->value_name;
}

/**
 * gimp_enum_value_get_help:
 * @enum_class: a #GEnumClass
 * @enum_value: a #GEnumValue from @enum_class
 *
 * Retrieves the translated help for a given @enum_value.
 *
 * Return value: the translated help of the enum value
 *
846
 * Since: 2.2
847 848 849 850 851 852 853 854 855 856
 **/
const gchar *
gimp_enum_value_get_help (GEnumClass *enum_class,
                          GEnumValue *enum_value)
{
  GType         type = G_TYPE_FROM_CLASS (enum_class);
  GimpEnumDesc *enum_desc;

  enum_desc = gimp_enum_get_desc (enum_class, enum_value->value);

Sven Neumann's avatar
Sven Neumann committed
857
  if (enum_desc && enum_desc->value_help)
858 859 860 861 862 863
    return dgettext (gimp_type_get_translation_domain (type),
                     enum_desc->value_help);

  return NULL;
}

864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
/**
 * gimp_enum_value_get_abbrev:
 * @enum_class: a #GEnumClass
 * @enum_value: a #GEnumValue from @enum_class
 *
 * Retrieves the translated abbreviation for a given @enum_value.
 *
 * Return value: the translated abbreviation of the enum value
 *
 * Since: 2.10
 **/
const gchar *
gimp_enum_value_get_abbrev (GEnumClass *enum_class,
                            GEnumValue *enum_value)
{
  GType         type = G_TYPE_FROM_CLASS (enum_class);
  GimpEnumDesc *enum_desc;

  enum_desc = gimp_enum_get_desc (enum_class, enum_value->value);

  if (enum_desc                              &&
      enum_desc[1].value == enum_desc->value &&
      enum_desc[1].value_desc)
    {
888 889 890
      return g_dpgettext2 (gimp_type_get_translation_domain (type),
                           gimp_type_get_translation_context (type),
                           enum_desc[1].value_desc);
891 892 893 894 895
    }

  return NULL;
}

896 897 898 899 900 901 902 903 904
/**
 * gimp_flags_get_first_desc:
 * @flags_class: a #GFlagsClass
 * @value:       a value from @flags_class
 *
 * Retrieves the first #GimpFlagsDesc that matches the given value, or %NULL.
 *
 * Return value: the value's #GimpFlagsDesc.
 *
905
 * Since: 2.2
906 907 908 909 910 911 912 913 914
 **/
GimpFlagsDesc *
gimp_flags_get_first_desc (GFlagsClass *flags_class,
                           guint        value)
{
  const GimpFlagsDesc *value_desc;

  g_return_val_if_fail (G_IS_FLAGS_CLASS (flags_class), NULL);

915 916
  value_desc =
    gimp_flags_get_value_descriptions (G_TYPE_FROM_CLASS (flags_class));
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933

  if (value_desc)
    {
      while (value_desc->value_desc)
        {
          if ((value_desc->value & value) == value_desc->value)
            return (GimpFlagsDesc *) value_desc;

          value_desc++;
        }
    }

  return NULL;
}

/**
 * gimp_flags_get_first_value:
934 935 936 937
 * @flags_type: the #GType of registered flags
 * @value:      an integer value
 * @value_name: return location for the value's name (or %NULL)
 * @value_nick: return location for the value's nick (or %NULL)
Sven Neumann's avatar
Sven Neumann committed
938
 * @value_desc: return location for the value's translated description (or %NULL)
939 940 941
 * @value_help: return location for the value's translated help (or %NULL)
 *
 * Checks if @value is valid for the flags registered as @flags_type.
Sven Neumann's avatar
Sven Neumann committed
942 943 944
 * If the value exists in that flags, its name, nick and its
 * translated description and help are returned (if @value_name,
 * @value_nick, @value_desc and @value_help are not %NULL).
945 946 947 948
 *
 * Return value: %TRUE if @value is valid for the @flags_type,
 *               %FALSE otherwise
 *
949
 * Since: 2.2
950 951
 **/
gboolean
952 953 954 955 956 957
gimp_flags_get_first_value (GType         flags_type,
                            guint         value,
                            const gchar **value_name,
                            const gchar **value_nick,
                            const gchar **value_desc,
                            const gchar **value_help)
958 959 960 961 962 963 964 965 966 967 968
{
  GFlagsClass *flags_class;
  GFlagsValue *flags_value;

  g_return_val_if_fail (G_TYPE_IS_FLAGS (flags_type), FALSE);

  flags_class = g_type_class_peek (flags_type);
  flags_value = g_flags_get_first_value (flags_class, value);

  if (flags_value)
    {
969
      if (value_name)
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
        *value_name = flags_value->value_name;

      if (value_nick)
        *value_nick = flags_value->value_nick;

      if (value_desc || value_help)
        {
          GimpFlagsDesc *flags_desc;

          flags_desc = gimp_flags_get_first_desc (flags_class, value);

          if (value_desc)
            *value_desc = ((flags_desc && flags_desc->value_desc) ?
                           dgettext (gimp_type_get_translation_domain (flags_type),
                                     flags_desc->value_desc) :
                           NULL);

          if (value_help)
            *value_help = ((flags_desc && flags_desc->value_desc) ?
                           dgettext (gimp_type_get_translation_domain (flags_type),
                                     flags_desc->value_help) :
                           NULL);
        }
993 994 995 996 997 998 999

      return TRUE;
    }

  return FALSE;
}

1000 1001 1002 1003 1004
/**
 * gimp_flags_value_get_desc:
 * @flags_class: a #GFlagsClass
 * @flags_value: a #GFlagsValue from @flags_class
 *
1005
 * Retrieves the translated description for a given @flags_value.
1006
 *
1007
 * Return value: the translated description of the flags value
1008
 *
1009
 * Since: 2.2
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
 **/
const gchar *
gimp_flags_value_get_desc (GFlagsClass *flags_class,
                           GFlagsValue *flags_value)
{
  GType         type = G_TYPE_FROM_CLASS (flags_class);
  GimpFlagsDesc *flags_desc;

  flags_desc = gimp_flags_get_first_desc (flags_class, flags_value->value);

  if (flags_desc->value_desc)
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
    {
      const gchar *context;

      context = gimp_type_get_translation_context (type);

      if (context)  /*  the new way, using NC_()    */
        return g_dpgettext2 (gimp_type_get_translation_domain (type),
                             context,
                             flags_desc->value_desc);
      else          /*  for backward compatibility  */
        return g_strip_context (flags_desc->value_desc,
                                dgettext (gimp_type_get_translation_domain (type),
                                          flags_desc->value_desc));
    }
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

  return flags_value->value_name;
}

/**
 * gimp_flags_value_get_help:
 * @flags_class: a #GFlagsClass
 * @flags_value: a #GFlagsValue from @flags_class
 *
 * Retrieves the translated help for a given @flags_value.
 *
 * Return value: the translated help of the flags value
 *
1048
 * Since: 2.2
1049 1050 1051 1052 1053 1054 1055 1056 1057
 **/
const gchar *
gimp_flags_value_get_help (GFlagsClass *flags_class,
                           GFlagsValue *flags_value)
{
  GType         type = G_TYPE_FROM_CLASS (flags_class);
  GimpFlagsDesc *flags_desc;

  flags_desc = gimp_flags_get_first_desc (flags_class, flags_value->value);
1058

1059
  if (flags_desc->value_help)
1060
    return dgettext (gimp_type_get_translation_domain (type),
1061
                     flags_desc->value_help);
1062 1063 1064

  return NULL;
}
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089

/**
 * gimp_flags_value_get_abbrev:
 * @flags_class: a #GFlagsClass
 * @flags_value: a #GFlagsValue from @flags_class
 *
 * Retrieves the translated abbreviation for a given @flags_value.
 *
 * Return value: the translated abbreviation of the flags value
 *
 * Since: 2.10
 **/
const gchar *
gimp_flags_value_get_abbrev (GFlagsClass *flags_class,
                             GFlagsValue *flags_value)
{
  GType          type = G_TYPE_FROM_CLASS (flags_class);
  GimpFlagsDesc *flags_desc;

  flags_desc = gimp_flags_get_first_desc (flags_class, flags_value->value);

  if (flags_desc                               &&
      flags_desc[1].value == flags_desc->value &&
      flags_desc[1].value_desc)
    {
1090 1091 1092
      return g_dpgettext2 (gimp_type_get_translation_domain (type),
                           gimp_type_get_translation_context (type),
                           flags_desc[1].value_desc);
1093 1094 1095 1096
    }

  return NULL;
}
1097 1098

/**
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
 * gimp_stack_trace_available:
 * @optimal: whether we get optimal traces.
 *
 * Returns #TRUE if we have dependencies to generate backtraces. If
 * @optimal is #TRUE, the function will return #TRUE only when we
 * are able to generate optimal traces (i.e. with GDB or LLDB);
 * otherwise we return #TRUE even if only backtrace() API is available.
 *
 * On Win32, we return TRUE if Dr. Mingw is built-in, FALSE otherwise.
 *
1109 1110 1111 1112 1113
 * Note: this function is not crash-safe, i.e. you should not try to use
 * it in a callback when the program is already crashing. In such a
 * case, call gimp_stack_trace_print() or gimp_stack_trace_query()
 * directly.
 *
1114 1115 1116 1117 1118 1119
 * Since: 2.10
 **/
gboolean
gimp_stack_trace_available (gboolean optimal)
{
#ifndef G_OS_WIN32
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
  gchar    *lld_path = NULL;
  gboolean  has_lldb = FALSE;

  /* Similarly to gdb, we could check for lldb by calling:
   * gimp_utils_generic_available ("lldb", major, minor).
   * We don't do so on purpose because on macOS, when lldb is absent, it
   * triggers a popup asking to install Xcode. So instead, we just
   * search for the executable in path.
   * This is the reason why this function is not crash-safe, since
   * g_find_program_in_path() allocates memory.
   * See issue #1999.
   */
  lld_path = g_find_program_in_path ("lldb");
  if (lld_path)
    {
      has_lldb = TRUE;
      g_free (lld_path);
    }

  if (gimp_utils_gdb_available (7, 0) || has_lldb)
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
    return TRUE;
#ifdef HAVE_EXECINFO_H
  if (! optimal)
    return TRUE;
#endif
#else /* G_OS_WIN32 */
#ifdef HAVE_EXCHNDL
  return TRUE;
#endif
#endif /* G_OS_WIN32 */
  return FALSE;
}

/**
 * gimp_stack_trace_print:
1155
 * @prog_name: the program to attach to.
1156
 * @stream: a #FILE * stream.
1157 1158 1159
 * @trace: location to store a newly allocated string of the trace.
 *
 * Attempts to generate a stack trace at current code position in
1160 1161 1162 1163
 * @prog_name. @prog_name is mostly a helper and can be set to NULL.
 * Nevertheless if set, it has to be the current program name (argv[0]).
 * This function is not meant to generate stack trace for third-party
 * programs, and will attach the current process id only.
1164 1165 1166 1167
 * Internally, this function uses `gdb` or `lldb` if they are available,
 * or the stacktrace() API on platforms where it is available. It always
 * fails on Win32.
 *
1168
 * The stack trace, once generated, will either be printed to @stream or
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
 * returned as a newly allocated string in @trace, if not #NULL.
 *
 * In some error cases (e.g. segmentation fault), trying to allocate
 * more memory will trigger more segmentation faults and therefore loop
 * our error handling (which is just wrong). Therefore printing to a
 * file description is an implementation without any memory allocation.

 * Return value: #TRUE if a stack trace could be generated, #FALSE
 * otherwise.
 *
 * Since: 2.10
 **/
gboolean
1182 1183 1184
gimp_stack_trace_print (const gchar   *prog_name,
                        gpointer      stream,
                        gchar       **trace)
1185
{
1186
  gboolean stack_printed = FALSE;
1187 1188 1189 1190 1191 1192 1193

  /* This works only on UNIX systems. */
#ifndef G_OS_WIN32
  GString *gtrace = NULL;
  gchar    gimp_pid[16];
  gchar    buffer[256];
  ssize_t  read_n;
1194
  int      sync_fd[2];
1195
  int      out_fd[2];
1196 1197
  pid_t    fork_pid;
  pid_t    pid = getpid();
1198
  gint     eintr_count = 0;
1199 1200
#if defined(G_OS_WIN32)
  DWORD    tid = GetCurrentThreadId ();
1201 1202
#elif defined(PLATFORM_OSX)
  uint64   tid64;
1203 1204
  long     tid;

1205
  pthread_threadid_np (NULL, &tid64);
1206
  tid = (long) tid64;
1207
#elif defined(SYS_gettid)
1208
  long     tid = syscall (SYS_gettid);
1209 1210 1211
#elif defined(HAVE_THR_SELF)
  long     tid = 0;
  thr_self (&tid);
1212
#endif
1213

1214
  g_snprintf (gimp_pid, 16, "%u", (guint) pid);
1215

1216 1217 1218 1219 1220
  if (pipe (sync_fd) == -1)
    {
      return FALSE;
    }

1221 1222
  if (pipe (out_fd) == -1)
    {
1223 1224 1225
      close (sync_fd[0]);
      close (sync_fd[1]);

1226 1227 1228
      return FALSE;
    }

1229 1230
  fork_pid = fork ();
  if (fork_pid == 0)
1231 1232
    {
      /* Child process. */
1233 1234 1235
      gchar *args[9] = { "gdb", "-batch",
                         "-ex", "info threads",
                         "-ex", "thread apply all backtrace full",
1236 1237
                         (gchar *) prog_name, NULL, NULL };

1238
      if (prog_name == NULL)
1239
        args[6] = "-p";
1240

1241
      args[7] = gimp_pid;
1242

1243 1244 1245 1246 1247 1248 1249 1250 1251
      /* Wait until the parent enabled us to ptrace it. */
      {
        gchar dummy;

        close (sync_fd[1]);
        while (read (sync_fd[0], &dummy, 1) < 0 && errno == EINTR);
        close (sync_fd[0]);
      }

1252 1253 1254 1255 1256
      /* Redirect the debugger output. */
      dup2 (out_fd[1], STDOUT_FILENO);
      close (out_fd[0]);
      close (out_fd[1]);

1257 1258 1259 1260 1261 1262 1263 1264
      /* Run GDB if version 7.0 or over. Why I do such a check is that
       * it turns out older versions may not only fail, but also have
       * very undesirable side effects like terminating the debugged
       * program, at least on FreeBSD where GDB 6.1 is apparently
       * installed by default on the stable release at day of writing.
       * See bug 793514. */
      if (! gimp_utils_gdb_available (7, 0) ||
          execvp (args[0], args) == -1)
1265
        {
1266 1267
          /* LLDB as alternative if the GDB call failed or if it was in
           * a too-old version. */
1268 1269 1270 1271
          gchar *args_lldb[15] = { "lldb", "--attach-pid", NULL, "--batch",
                                   "--one-line", "thread list",
                                   "--one-line", "thread backtrace all",
                                   "--one-line", "bt all",
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
                                   "--one-line-on-crash", "bt",
                                   "--one-line-on-crash", "quit", NULL };

          args_lldb[2] = gimp_pid;

          execvp (args_lldb[0], args_lldb);
        }

      _exit (0);
    }
1282
  else if (fork_pid > 0)
1283 1284 1285 1286
    {
      /* Main process */
      int status;

1287 1288 1289
      /* Allow the child to ptrace us, and signal it to start. */
      close (sync_fd[0]);
#ifdef PR_SET_PTRACER
1290
      prctl (PR_SET_PTRACER, fork_pid, 0, 0, 0);
1291 1292
#endif
      close (sync_fd[1]);
1293 1294 1295 1296 1297 1298 1299

      /* It is important to close the writing side of the pipe, otherwise
       * the read() will wait forever without getting the information that
       * writing is finished.
       */
      close (out_fd[1]);

1300
      while ((read_n = read (out_fd[0], buffer, 256)) != 0)
1301
        {
1302 1303
          if (read_n < 0)
            {
1304 1305 1306 1307 1308 1309 1310
              /* LLDB on macOS seems to trigger a few EINTR error (see
               * !13), though read() finally ends up working later. So
               * let's not make this error fatal, and instead try again.
               * Yet to avoid infinite loop (in case the error really
               * happens at every call), we abandon after a few
               * consecutive errors.
               */
1311 1312 1313 1314 1315 1316 1317
              if (errno == EINTR && eintr_count <= 5)
                {
                  eintr_count++;
                  continue;
                }
              break;
            }
1318
          eintr_count = 0;
1319 1320
          if (! stack_printed)
            {
1321 1322 1323 1324 1325 1326
#if defined(PLATFORM_OSX)
              if (stream)
                g_fprintf (stream,
                           "\n# Stack traces obtained from PID %d - Thread 0x%lx #\n\n",
                           pid, tid);
#elif defined(G_OS_WIN32) || defined(SYS_gettid) || defined(HAVE_THR_SELF)
1327 1328 1329 1330
              if (stream)
                g_fprintf (stream,
                           "\n# Stack traces obtained from PID %d - Thread %lu #\n\n",
                           pid, tid);
1331
#endif
1332 1333 1334
              if (trace)
                {
                  gtrace = g_string_new (NULL);
1335 1336 1337 1338 1339
#if defined(PLATFORM_OSX)
                  g_string_printf (gtrace,
                                   "\n# Stack traces obtained from PID %d - Thread 0x%lx #\n\n",
                                   pid, tid);
#elif defined(G_OS_WIN32) || defined(SYS_gettid) || defined(HAVE_THR_SELF)
1340 1341 1342
                  g_string_printf (gtrace,
                                   "\n# Stack traces obtained from PID %d - Thread %lu #\n\n",
                                   pid, tid);
1343
#endif
1344 1345
                }
            }
1346 1347 1348 1349 1350 1351 1352
          /* It's hard to know if the debugger was found since it
           * happened in the child. Let's just assume that any output
           * means it succeeded.
           */
          stack_printed = TRUE;

          buffer[read_n] = '\0';
1353 1354
          if (stream)
            g_fprintf (stream, "%s", buffer);
1355
          if (trace)
1356
            g_string_append (gtrace, (const gchar *) buffer);
1357 1358
        }
      close (out_fd[0]);
1359 1360 1361 1362 1363 1364

#ifdef PR_SET_PTRACER
      /* Clear ptrace permission set above */
      prctl (PR_SET_PTRACER, 0, 0, 0, 0);
#endif

1365
      waitpid (fork_pid, &status, 0);
1366
    }
1367
  /* else if (fork_pid == (pid_t) -1)
1368 1369 1370
   * Fork failed!
   * Just continue, maybe the backtrace() API will succeed.
   */
1371 1372 1373 1374 1375 1376 1377

#ifdef HAVE_EXECINFO_H
  if (! stack_printed)
    {
      /* As a last resort, try using the backtrace() Linux API. It is a bit
       * less fancy than gdb or lldb, which is why it is not given priority.
       */
1378 1379
      void *bt_buf[100];
      int   n_symbols;
1380 1381

      n_symbols = backtrace (bt_buf, 100);
1382
      if (trace && n_symbols)
1383
        {
1384 1385
          char **symbols;
          int    i;
1386

1387 1388
          symbols = backtrace_symbols (bt_buf, n_symbols);
          if (symbols)
1389
            {
1390
              for (i = 0; i < n_symbols; i++)
1391
                {
1392 1393
                  if (stream)
                    g_fprintf (stream, "%s\n", (const gchar *) symbols[i]);
1394 1395 1396 1397 1398 1399 1400 1401
                  if (trace)
                    {
                      if (! gtrace)
                        gtrace = g_string_new (NULL);
                      g_string_append (gtrace,
                                       (const gchar *) symbols[i]);
                      g_string_append_c (gtrace, '\n');
                    }
1402
                }
1403
              free (symbols);
1404 1405
            }
        }
1406 1407 1408 1409 1410 1411
      else if (n_symbols)
        {
          /* This allows to generate traces without memory allocation.
           * In some cases, this is necessary, especially during
           * segfault-type crashes.
           */
1412
          backtrace_symbols_fd (bt_buf, n_symbols, fileno ((FILE *) stream));
1413 1414
        }
      stack_printed = (n_symbols > 0);
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
    }
#endif /* HAVE_EXECINFO_H */

  if (trace)
    {
      if (gtrace)
        *trace = g_string_free (gtrace, FALSE);
      else
        *trace = NULL;
    }
#endif /* G_OS_WIN32 */

  return stack_printed;
}

/**
1431
 * gimp_stack_trace_query:
1432 1433 1434 1435
 * @prog_name: the program to attach to.
 *
 * This is mostly the same as g_on_error_query() except that we use our
 * own backtrace function, much more complete.
1436
 * @prog_name must be the current program name (argv[0]).
1437 1438 1439 1440 1441
 * It does nothing on Win32.
 *
 * Since: 2.10
 **/
void
1442
gimp_stack_trace_query (const gchar *prog_name)
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
{
#ifndef G_OS_WIN32
  gchar buf[16];

 retry:

  g_fprintf (stdout,
             "%s (pid:%u): %s: ",
             prog_name,
             (guint) getpid (),
             "[E]xit, show [S]tack trace or [P]roceed");
  fflush (stdout);

  if (isatty(0) && isatty(1))
    fgets (buf, 8, stdin);
  else
    strcpy (buf, "E\n");

  if ((buf[0] == 'E' || buf[0] == 'e')
      && buf[1] == '\n')
    _exit (0);
  else if ((buf[0] == 'P' || buf[0] == 'p')
           && buf[1] == '\n')
    return;
  else if ((buf[0] == 'S' || buf[0] == 's')
           && buf[1] == '\n')
    {
1470
      if (! gimp_stack_trace_print (prog_name, stdout, NULL))
1471 1472 1473 1474 1475 1476 1477
        g_fprintf (stderr, "%s\n", "Stack trace not available on your system.");
      goto retry;
    }
  else
    goto retry;
#endif
}
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603


/* Private functions. */

static gboolean
gimp_utils_generic_available (const gchar *program,
                              gint         major,
                              gint         minor)
{
#ifndef G_OS_WIN32
  pid_t pid;
  int   out_fd[2];

  if (pipe (out_fd) == -1)
    {
      return FALSE;
    }

  /* XXX: I don't use g_spawn_sync() or similar glib functions because
   * to read the contents of the stdout, these functions would allocate
   * memory dynamically. As we know, when debugging crashes, this is a
   * definite blocker. So instead I simply use a buffer on the stack
   * with a lower level fork() call.
   */
  pid = fork ();
  if (pid == 0)
    {
      /* Child process. */
      gchar *args[3] = { (gchar *) program, "--version", NULL };

      /* Redirect the debugger output. */
      dup2 (out_fd[1], STDOUT_FILENO);
      close (out_fd[0]);
      close (out_fd[1]);

      /* Run version check. */
      execvp (args[0], args);
      _exit (-1);
    }
  else if (pid > 0)
    {
      /* Main process */
      gchar    buffer[256];
      ssize_t  read_n;
      int      status;
      gint     installed_major = 0;
      gint     installed_minor = 0;
      gboolean major_reading = FALSE;
      gboolean minor_reading = FALSE;
      gint     i;
      gchar    c;

      waitpid (pid, &status, 0);

      if (! WIFEXITED (status) || WEXITSTATUS (status) != 0)
        return FALSE;

      /* It is important to close the writing side of the pipe, otherwise
       * the read() will wait forever without getting the information that
       * writing is finished.
       */
      close (out_fd[1]);

      /* I could loop forever until EOL, but I am pretty sure the
       * version information is stored on the first line and one call to
       * read() with 256 characters should be more than enough.
       */
      read_n = read (out_fd[0], buffer, 256);

      /* This is quite a very stupid parser. I only look for the first
       * numbers and consider them as version information. This works
       * fine for both GDB and LLDB as far as I can see for the output
       * of `${program} --version` but this should obviously not be
       * considered as a *really* generic version test.
       */
      for (i = 0; i < read_n; i++)
        {
          c = buffer[i];
          if (c >= '0' && c <= '9')
            {
              if (minor_reading)
                {
                  installed_minor = 10 * installed_minor + (c - '0');
                }
              else
                {
                  major_reading = TRUE;
                  installed_major = 10 * installed_major + (c - '0');
                }
            }
          else if (c == '.')
            {
              if (major_reading)
                {
                  minor_reading = TRUE;
                  major_reading = FALSE;
                }
              else if (minor_reading)
                {
                  break;
                }
            }
          else if (c == '\n')
            {
              /* Version information should be in the first line. */
              break;
            }
        }
      close (out_fd[0]);

      return (installed_major > 0 &&
              (installed_major > major ||
               (installed_major == major && installed_minor >= minor)));
    }
#endif

  /* Fork failed, or Win32. */
  return FALSE;
}

static gboolean
gimp_utils_gdb_available (gint major,
                          gint minor)
{
  return gimp_utils_generic_available ("gdb", major, minor);
}