gtkmountoperation-x11.c 26.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* GTK - The GIMP Toolkit
 * Copyright (C) David Zeuthen <davidz@redhat.com>
 * Copyright (C) 2001 Havoc Pennington
 * Copyright (C) 2005-2007 Vincent Untz
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
Javier Jardón's avatar
Javier Jardón committed
18
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
 */

/*
 * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
 * file for a list of people on the GTK+ Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
 */

#include "config.h"

#include <string.h>
#include <stdlib.h>
#include <gio/gio.h>
#include "x11/gdkx.h"
#include <X11/Xatom.h>
#include <gtk/gtkicontheme.h>
#include "gtkintl.h"

/* for the kill(2) system call and errno - POSIX.1-2001 and later */
#include <sys/types.h>
#include <signal.h>
#include <errno.h>

43 44 45 46
#if defined(__OpenBSD__)
#include <sys/sysctl.h>
#endif

47 48 49 50 51
#include "gtkmountoperationprivate.h"

/* ---------------------------------------------------------------------------------------------------- */
/* these functions are based on code from libwnck (LGPLv2) */

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
static gboolean get_window_list   (GdkDisplay *display,
                                   Window      xwindow,
                                   Atom        atom,
                                   Window    **windows,
                                   int        *len);

static char*    get_utf8_property (GdkDisplay *display,
                                   Window      xwindow,
                                   Atom        atom);

static gboolean get_cardinal      (GdkDisplay *display,
                                   Window      xwindow,
                                   Atom        atom,
                                   int        *val);

static gboolean read_rgb_icon     (GdkDisplay *display,
                                   Window      xwindow,
                                   int         ideal_width,
                                   int         ideal_height,
                                   int        *width,
                                   int        *height,
                                   guchar    **pixdata);
74 75 76


static gboolean
77 78 79 80
get_cardinal (GdkDisplay *display,
              Window      xwindow,
              Atom        atom,
              int        *val)
81 82 83 84 85 86 87 88 89 90
{
  Atom type;
  int format;
  gulong nitems;
  gulong bytes_after;
  gulong *num;
  int err, result;

  *val = 0;

91
  gdk_x11_display_error_trap_push (display);
92
  type = None;
93
  result = XGetWindowProperty (GDK_DISPLAY_XDISPLAY (display),
94 95 96 97 98
                               xwindow,
                               atom,
                               0, G_MAXLONG,
                               False, XA_CARDINAL, &type, &format, &nitems,
                               &bytes_after, (void*)&num);
99 100
  XSync (GDK_DISPLAY_XDISPLAY (display), False);
  err = gdk_x11_display_error_trap_pop (display);
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

  if (err != Success ||
      result != Success)
    return FALSE;

  if (type != XA_CARDINAL)
    {
      XFree (num);
      return FALSE;
    }

  *val = *num;

  XFree (num);

  return TRUE;
}

static char*
120 121 122
get_utf8_property (GdkDisplay *display,
                   Window      xwindow,
                   Atom        atom)
123 124 125 126 127 128 129 130 131 132 133 134
{
  Atom type;
  int format;
  gulong nitems;
  gulong bytes_after;
  gchar *val;
  int err, result;
  char *retval;
  Atom utf8_string;

  utf8_string = gdk_x11_get_xatom_by_name ("UTF8_STRING");

135
  gdk_x11_display_error_trap_push (display);
136 137
  type = None;
  val = NULL;
138
  result = XGetWindowProperty (GDK_DISPLAY_XDISPLAY (display),
139 140 141 142 143 144
                               xwindow,
                               atom,
                               0, G_MAXLONG,
                               False, utf8_string,
                               &type, &format, &nitems,
                               &bytes_after, (guchar **)&val);
145 146
  XSync (GDK_DISPLAY_XDISPLAY (display), False);
  err = gdk_x11_display_error_trap_pop (display);
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162

  if (err != Success ||
      result != Success)
    return NULL;

  if (type != utf8_string ||
      format != 8 ||
      nitems == 0)
    {
      if (val)
        XFree (val);
      return NULL;
    }

  if (!g_utf8_validate (val, nitems, NULL))
    {
163
      g_warning ("Property %s contained invalid UTF-8",
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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
                 gdk_x11_get_xatom_name (atom));
      XFree (val);
      return NULL;
    }

  retval = g_strndup (val, nitems);

  XFree (val);

  return retval;
}

static gboolean
find_largest_sizes (gulong *data,
                    gulong  nitems,
                    int    *width,
                    int    *height)
{
  *width = 0;
  *height = 0;

  while (nitems > 0)
    {
      int w, h;

      if (nitems < 3)
        return FALSE; /* no space for w, h */

      w = data[0];
      h = data[1];

      if (nitems < ((w * h) + 2))
        return FALSE; /* not enough data */

      *width = MAX (w, *width);
      *height = MAX (h, *height);

      data += (w * h) + 2;
      nitems -= (w * h) + 2;
    }

  return TRUE;
}

static gboolean
find_best_size (gulong  *data,
                gulong   nitems,
                int      ideal_width,
                int      ideal_height,
                int     *width,
                int     *height,
                gulong **start)
{
  int best_w;
  int best_h;
  gulong *best_start;
  int max_width, max_height;

  *width = 0;
  *height = 0;
  *start = NULL;

  if (!find_largest_sizes (data, nitems, &max_width, &max_height))
    return FALSE;

  if (ideal_width < 0)
    ideal_width = max_width;
  if (ideal_height < 0)
    ideal_height = max_height;

  best_w = 0;
  best_h = 0;
  best_start = NULL;

  while (nitems > 0)
    {
      int w, h;
      gboolean replace;

      replace = FALSE;

      if (nitems < 3)
        return FALSE; /* no space for w, h */

      w = data[0];
      h = data[1];

      if (nitems < ((w * h) + 2))
        break; /* not enough data */

      if (best_start == NULL)
        {
          replace = TRUE;
        }
      else
        {
          /* work with averages */
          const int ideal_size = (ideal_width + ideal_height) / 2;
          int best_size = (best_w + best_h) / 2;
          int this_size = (w + h) / 2;

          /* larger than desired is always better than smaller */
          if (best_size < ideal_size &&
              this_size >= ideal_size)
            replace = TRUE;
          /* if we have too small, pick anything bigger */
          else if (best_size < ideal_size &&
                   this_size > best_size)
            replace = TRUE;
          /* if we have too large, pick anything smaller
           * but still >= the ideal
           */
          else if (best_size > ideal_size &&
                   this_size >= ideal_size &&
                   this_size < best_size)
            replace = TRUE;
        }

      if (replace)
        {
          best_start = data + 2;
          best_w = w;
          best_h = h;
        }

      data += (w * h) + 2;
      nitems -= (w * h) + 2;
    }

  if (best_start)
    {
      *start = best_start;
      *width = best_w;
      *height = best_h;
      return TRUE;
    }
  else
    return FALSE;
}

static void
argbdata_to_pixdata (gulong  *argb_data,
                     int      len,
                     guchar **pixdata)
{
  guchar *p;
  int i;

  *pixdata = g_new (guchar, len * 4);
  p = *pixdata;

  /* One could speed this up a lot. */
  i = 0;
  while (i < len)
    {
      guint argb;
      guint rgba;

      argb = argb_data[i];
      rgba = (argb << 8) | (argb >> 24);

      *p = rgba >> 24;
      ++p;
      *p = (rgba >> 16) & 0xff;
      ++p;
      *p = (rgba >> 8) & 0xff;
      ++p;
      *p = rgba & 0xff;
      ++p;

      ++i;
    }
}

static gboolean
339 340 341 342 343 344 345
read_rgb_icon (GdkDisplay *display,
               Window      xwindow,
               int         ideal_width,
               int         ideal_height,
               int        *width,
               int        *height,
               guchar    **pixdata)
346 347 348 349 350 351 352 353 354 355
{
  Atom type;
  int format;
  gulong nitems;
  gulong bytes_after;
  int result, err;
  gulong *data;
  gulong *best;
  int w, h;

356
  gdk_x11_display_error_trap_push (display);
357 358
  type = None;
  data = NULL;
359
  result = XGetWindowProperty (GDK_DISPLAY_XDISPLAY (display),
360 361 362 363 364
                               xwindow,
                               gdk_x11_get_xatom_by_name ("_NET_WM_ICON"),
                               0, G_MAXLONG,
                               False, XA_CARDINAL, &type, &format, &nitems,
                               &bytes_after, (void*)&data);
365 366
  XSync (GDK_DISPLAY_XDISPLAY (display), False);
  err = gdk_x11_display_error_trap_pop (display);
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458

  if (err != Success ||
      result != Success)
    return FALSE;

  if (type != XA_CARDINAL)
    {
      XFree (data);
      return FALSE;
    }

  if (!find_best_size (data, nitems,
                       ideal_width, ideal_height,
                       &w, &h, &best))
    {
      XFree (data);
      return FALSE;
    }

  *width = w;
  *height = h;

  argbdata_to_pixdata (best, w * h, pixdata);

  XFree (data);

  return TRUE;
}

static void
free_pixels (guchar *pixels, gpointer data)
{
  g_free (pixels);
}

static GdkPixbuf*
scaled_from_pixdata (guchar *pixdata,
                     int     w,
                     int     h,
                     int     new_w,
                     int     new_h)
{
  GdkPixbuf *src;
  GdkPixbuf *dest;

  src = gdk_pixbuf_new_from_data (pixdata,
                                  GDK_COLORSPACE_RGB,
                                  TRUE,
                                  8,
                                  w, h, w * 4,
                                  free_pixels,
                                  NULL);

  if (src == NULL)
    return NULL;

  if (w != h)
    {
      GdkPixbuf *tmp;
      int size;

      size = MAX (w, h);

      tmp = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8, size, size);

      if (tmp != NULL)
        {
          gdk_pixbuf_fill (tmp, 0);
          gdk_pixbuf_copy_area (src, 0, 0, w, h,
                                tmp,
                                (size - w) / 2, (size - h) / 2);

          g_object_unref (src);
          src = tmp;
        }
    }

  if (w != new_w || h != new_h)
    {
      dest = gdk_pixbuf_scale_simple (src, new_w, new_h, GDK_INTERP_BILINEAR);

      g_object_unref (G_OBJECT (src));
    }
  else
    {
      dest = src;
    }

  return dest;
}

static gboolean
459 460 461 462 463
get_window_list (GdkDisplay *display,
                 Window      xwindow,
                 Atom        atom,
                 Window    **windows,
                 int        *len)
464 465 466 467 468 469 470 471 472 473 474
{
  Atom type;
  int format;
  gulong nitems;
  gulong bytes_after;
  Window *data;
  int err, result;

  *windows = NULL;
  *len = 0;

475
  gdk_x11_display_error_trap_push (display);
476
  type = None;
477
  result = XGetWindowProperty (GDK_DISPLAY_XDISPLAY (display),
478 479 480 481 482
                               xwindow,
                               atom,
                               0, G_MAXLONG,
                               False, XA_WINDOW, &type, &format, &nitems,
                               &bytes_after, (void*)&data);
483 484
  XSync (GDK_DISPLAY_XDISPLAY (display), False);
  err = gdk_x11_display_error_trap_pop (display);
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 523 524 525 526 527 528 529 530 531 532 533

  if (err != Success ||
      result != Success)
    return FALSE;

  if (type != XA_WINDOW)
    {
      XFree (data);
      return FALSE;
    }

  *windows = g_new (Window, nitems);
  memcpy (*windows, data, sizeof (Window) * nitems);
  *len = nitems;

  XFree (data);

  return TRUE;
}


/* ---------------------------------------------------------------------------------------------------- */

struct _GtkMountOperationLookupContext
{
  /* Hash from pid (gint) -> XID (gint)
   *
   * Note that XIDs are at most 27 bits - however, also note that sizeof(XID) == 8 on
   * x86_64 - that's just xlib brokenness. So it's safe to stuff the XID into a pointer.
   */
  GHashTable *pid_to_window;
  GdkDisplay *display;
};

GtkMountOperationLookupContext *
_gtk_mount_operation_lookup_context_get (GdkDisplay *display)
{
  GtkMountOperationLookupContext *context;
  Window *mapping;
  gint mapping_length;
  gint n;

  context = g_new0 (GtkMountOperationLookupContext, 1);

  context->pid_to_window = g_hash_table_new (g_direct_hash, g_direct_equal);
  context->display = display;

  mapping = NULL;
  mapping_length = 0;
534
  get_window_list (context->display,
535 536 537 538 539 540 541 542 543
                   GDK_ROOT_WINDOW(),
                   gdk_x11_get_xatom_by_name_for_display (context->display,
                                                          "_NET_CLIENT_LIST"),
                   &mapping,
                   &mapping_length);
  for (n = 0; n < mapping_length; n++)
    {
      gint pid;

544
      if (!get_cardinal (context->display,
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 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 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
                         mapping[n],
                         gdk_x11_get_xatom_by_name_for_display (context->display,
                                                                "_NET_WM_PID"),
                         &pid))
        continue;

      g_hash_table_insert (context->pid_to_window,
                           GINT_TO_POINTER (pid),
                           GINT_TO_POINTER ((gint) mapping[n]));
    }
  g_free (mapping);

  return context;
}

void
_gtk_mount_operation_lookup_context_free (GtkMountOperationLookupContext *context)
{
  g_hash_table_unref (context->pid_to_window);
  g_free (context);
}

/* ---------------------------------------------------------------------------------------------------- */

#ifdef __linux__

static GPid
pid_get_parent (GPid pid)
{
  GPid ppid;
  gchar **tokens;
  gchar *stat_filename;
  gchar *stat_contents;
  gsize stat_len;

  ppid = 0;
  tokens = NULL;
  stat_contents = NULL;
  stat_filename = NULL;

  /* fail if trying to get the parent of the init process (no such thing) */
  if (pid == 1)
      goto out;

  stat_filename = g_strdup_printf ("/proc/%d/status", pid);
  if (g_file_get_contents (stat_filename,
                           &stat_contents,
                           &stat_len,
                           NULL))
    {
      guint n;

      tokens = g_strsplit (stat_contents, "\n", 0);

      for (n = 0; tokens[n] != NULL; n++)
        {
          if (g_str_has_prefix (tokens[n], "PPid:"))
            {
              gchar *endp;

              endp = NULL;
              ppid = strtoll (tokens[n] + sizeof "PPid:" - 1, &endp, 10);
              if (endp == NULL || *endp != '\0')
                {
                  g_warning ("Error parsing contents of `%s'. Parent pid is malformed.",
                             stat_filename);
                  ppid = 0;
                  goto out;
                }

              break;
            }
        }
    }

 out:
  g_strfreev (tokens);
  g_free (stat_contents);
  g_free (stat_filename);

  return ppid;
}

static gchar *
pid_get_env (GPid         pid,
             const gchar *key)
{
  gchar *ret;
  gchar *env_filename;
  gchar *env;
  gsize env_len;
  gsize key_len;
  gchar *end;

  ret = NULL;

  key_len = strlen (key);

  env_filename = g_strdup_printf ("/proc/%d/environ", pid);
  if (g_file_get_contents (env_filename,
                           &env,
                           &env_len,
                           NULL))
    {
      guint n;

      /* /proc/<pid>/environ in Linux is split at '\0' points, g_strsplit() can't handle that... */
      n = 0;
      while (TRUE)
        {
655
          if (n >= env_len || env[n] == '\0')
656 657 658 659 660 661 662
            break;

          if (g_str_has_prefix (env + n, key) && (*(env + n + key_len) == '='))
            {
              ret = g_strdup (env + n + key_len + 1);

              /* skip invalid UTF-8 */
663
              if (!g_utf8_validate (ret, -1, (const gchar **) &end))
664 665 666 667
                *end = '\0';
              break;
            }

668
          for (; n < env_len && env[n] != '\0'; n++)
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
            ;
          n++;
        }
      g_free (env);
    }
  g_free (env_filename);

  return ret;
}

static gchar *
pid_get_command_line (GPid pid)
{
  gchar *cmdline_filename;
  gchar *cmdline_contents;
  gsize cmdline_len;
  guint n;
  gchar *end;

  cmdline_contents = NULL;

  cmdline_filename = g_strdup_printf ("/proc/%d/cmdline", pid);
  if (!g_file_get_contents (cmdline_filename,
                            &cmdline_contents,
                            &cmdline_len,
                            NULL))
    goto out;

  /* /proc/<pid>/cmdline separates args by NUL-bytes - replace with spaces */
  for (n = 0; n < cmdline_len - 1; n++)
    {
      if (cmdline_contents[n] == '\0')
        cmdline_contents[n] = ' ';
    }

  /* skip invalid UTF-8 */
705
  if (!g_utf8_validate (cmdline_contents, -1, (const gchar **) &end))
706 707 708 709 710 711 712 713 714
      *end = '\0';

 out:
  g_free (cmdline_filename);

  return cmdline_contents;
}

/* ---------------------------------------------------------------------------------------------------- */
715 716 717 718 719 720 721 722

#elif defined(__OpenBSD__)

/* ---------------------------------------------------------------------------------------------------- */

static GPid
pid_get_parent (GPid pid)
{
723 724 725 726 727 728
  struct kinfo_proc kp;
  size_t len;
  GPid ppid;

  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid,
                sizeof(struct kinfo_proc), 0 };
729

730
  if (sysctl (mib, G_N_ELEMENTS (mib), NULL, &len, NULL, 0) == -1)
731 732
      return (-1);
  mib[5] = (len / sizeof(struct kinfo_proc));
733

734
  if (sysctl (mib, G_N_ELEMENTS (mib), &kp, &len, NULL, 0) < 0)
735 736 737
      return -1;

  ppid = kp.p_ppid;
738 739 740 741 742 743 744

  return ppid;
}

static gchar *
pid_get_env (GPid pid, const gchar *key)
{
745 746 747
  size_t len;
  char **strs;
  char *ret = NULL;
748 749 750 751
  char *end;
  int key_len;
  int i;

752 753
  int mib[] = { CTL_KERN, KERN_PROC_ARGS, pid, KERN_PROC_ENV };

754 755 756 757
  if (sysctl (mib, G_N_ELEMENTS (mib), NULL, &len, NULL, 0) == -1)
    return ret;

  strs = g_malloc0 (len);
758 759 760

  key_len = strlen (key);

761
  if (sysctl (mib, G_N_ELEMENTS (mib), strs, &len, NULL, 0) != -1)
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
    {
      for (i = 0; strs[i] != NULL; i++)
	{
	  if (g_str_has_prefix (strs[i], key) && (*(strs[i] + key_len) == '='))
	    {
	      ret = g_strdup (strs[i] + key_len + 1);

	      /* skip invalid UTF-8 */
	      if (!g_utf8_validate (ret, -1, (const gchar **) &end))
		*end = '\0';
	      break;
	    }
	}
    }

777
  g_free (strs);
778 779 780 781 782 783
  return ret;
}

static gchar *
pid_get_command_line (GPid pid)
{
784 785 786
  size_t len;
  char **strs;
  char *ret, *end;
787

788
  int mib[] = { CTL_KERN, KERN_PROC_ARGS, pid, KERN_PROC_ARGV };
789

790 791 792 793
  if (sysctl (mib, G_N_ELEMENTS (mib), NULL, &len, NULL, 0) == -1)
    return NULL;

  strs = g_malloc0 (len);
794

795
  if (sysctl (mib, G_N_ELEMENTS (mib), strs, &len, NULL, 0) == -1) {
796
    g_free (strs);
797
    return NULL;
798
  }
799 800 801 802 803 804

  ret = g_strjoinv (" ", strs);
  /* skip invalid UTF-8 */
  if (!g_utf8_validate (ret, -1, (const gchar **) &end))
    *end = '\0';

805
  g_free (strs);
806 807 808
  return ret;
}

809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
#else

/* TODO: please implement for your OS - must return valid UTF-8 */

static GPid
pid_get_parent (GPid pid)
{
  return 0;
}

static gchar *
pid_get_env (GPid         pid,
             const gchar *key)
{
  return NULL;
}

static gchar *
pid_get_command_line (GPid pid)
{
  return NULL;
}

#endif

/* ---------------------------------------------------------------------------------------------------- */

static gchar *
get_name_for_window_with_pid (GtkMountOperationLookupContext *context,
                              GPid                            pid)
{
  Window window;
  Window windowid_window;
  gchar *ret;

  ret = NULL;

  window = GPOINTER_TO_INT (g_hash_table_lookup (context->pid_to_window, GINT_TO_POINTER (pid)));
  if (window == None)
    {
      gchar *windowid_value;

      /* check for $WINDOWID (set by terminals) and see if we can get the title that way */
      windowid_value = pid_get_env (pid, "WINDOWID");
      if (windowid_value != NULL)
        {
          gchar *endp;

          endp = NULL;
          windowid_window = (Window) g_ascii_strtoll (windowid_value, &endp, 10);
          if (endp != NULL || *endp == '\0')
            {
              window = windowid_window;
            }
          g_free (windowid_value);
        }

      /* otherwise, check for parents */
      if (window == None)
        {
          do
            {
              pid = pid_get_parent (pid);
              if (pid == 0)
                break;

              window = GPOINTER_TO_INT (g_hash_table_lookup (context->pid_to_window, GINT_TO_POINTER (pid)));
              if (window != None)
                break;
            }
          while (TRUE);
        }
    }

  if (window != None)
    {
885
      ret = get_utf8_property (context->display,
886 887 888 889
                               window,
                               gdk_x11_get_xatom_by_name_for_display (context->display,
                                                                      "_NET_WM_NAME"));
      if (ret == NULL)
890
        ret = get_utf8_property (context->display,
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
                                 window, gdk_x11_get_xatom_by_name_for_display (context->display,
                                                                                "_NET_WM_ICON_NAME"));
    }

  return ret;
}

/* ---------------------------------------------------------------------------------------------------- */

static GdkPixbuf *
get_pixbuf_for_window_with_pid (GtkMountOperationLookupContext *context,
                                GPid                            pid,
                                gint                            size_pixels)
{
  Window window;
  GdkPixbuf *ret;

  ret = NULL;

  window = GPOINTER_TO_INT (g_hash_table_lookup (context->pid_to_window, GINT_TO_POINTER (pid)));
  if (window == None)
    {
      /* otherwise, check for parents */
      do
        {
          pid = pid_get_parent (pid);
          if (pid == 0)
            break;

          window = GPOINTER_TO_INT (g_hash_table_lookup (context->pid_to_window, GINT_TO_POINTER (pid)));
          if (window != None)
            break;
        }
      while (TRUE);
    }

  if (window != None)
    {
      gint    width;
      gint    height;
      guchar *pixdata;

933
      if (read_rgb_icon (context->display,
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
                         window,
                         size_pixels, size_pixels,
                         &width, &height,
                         &pixdata))
        {
          /* steals pixdata */
          ret = scaled_from_pixdata (pixdata,
                                     width, height,
                                     size_pixels, size_pixels);
        }
    }

  return ret;
}

/* ---------------------------------------------------------------------------------------------------- */

static const gchar *well_known_commands[] =
{
953
  /* translators: this string is a name for the 'less' command */
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
  "less", N_("Terminal Pager"),
  "top", N_("Top Command"),
  "bash", N_("Bourne Again Shell"),
  "sh", N_("Bourne Shell"),
  "zsh", N_("Z Shell"),
  NULL,
};

gboolean
_gtk_mount_operation_lookup_info (GtkMountOperationLookupContext *context,
                                  GPid                            pid,
                                  gint                            size_pixels,
                                  gchar                         **out_name,
                                  gchar                         **out_command_line,
                                  GdkPixbuf                     **out_pixbuf)
{
  g_return_val_if_fail (out_name != NULL && *out_name == NULL, FALSE);
  g_return_val_if_fail (out_command_line != NULL && *out_command_line == NULL, FALSE);
  g_return_val_if_fail (out_pixbuf != NULL && *out_pixbuf == NULL, FALSE);

  /* We perform two different lookups for name and icon size.. this is
   * because we want the name from the window with WINDOWID and this
   * normally does not give you an icon
   *
   * (the canonical example is a tab in gnome-terminal - the shell/command running
   *  in the shell will have WINDOWID set - but this window won't have an icon - so
   *  we want to continue up until the gnome-terminal window so we can get that icon)
   */

  *out_command_line = pid_get_command_line (pid);

  *out_name = get_name_for_window_with_pid (context, pid);

  *out_pixbuf = get_pixbuf_for_window_with_pid (context, pid, size_pixels);

  /* if we didn't manage to find the name via X, fall back to the basename
   * of the first element of the command line and, for maximum geek-comfort,
   * map a few well-known commands to proper translated names
   */
  if (*out_name == NULL && *out_command_line != NULL &&
      strlen (*out_command_line) > 0 && (*out_command_line)[0] != ' ')
    {
      guint n;
      gchar *s;
      gchar *p;

      /* find the first character after the first argument */
      s = strchr (*out_command_line, ' ');
      if (s == NULL)
        s = *out_command_line + strlen (*out_command_line);

      for (p = s; p > *out_command_line; p--)
        {
          if (*p == '/')
            {
              p++;
              break;
            }
        }

      *out_name = g_strndup (p, s - p);

      for (n = 0; well_known_commands[n] != NULL; n += 2)
        {
          /* sometimes the command is prefixed with a -, e.g. '-bash' instead
           * of 'bash' - handle that as well
           */
          if ((strcmp (well_known_commands[n], *out_name) == 0) ||
              ((*out_name)[0] == '-' && (strcmp (well_known_commands[n], (*out_name) + 1) == 0)))
            {
              g_free (*out_name);
              *out_name = g_strdup (_(well_known_commands[n+1]));
              break;
            }
        }
    }

  return TRUE;
}

gboolean
_gtk_mount_operation_kill_process (GPid      pid,
                                   GError  **error)
{
  gboolean ret;

  ret = TRUE;

  if (kill ((pid_t) pid, SIGTERM) != 0)
    {
1044 1045
      int errsv = errno;

1046 1047 1048 1049 1050 1051 1052 1053
      /* TODO: On EPERM, we could use a setuid helper using polkit (very easy to implement
       *       via pkexec(1)) to allow the user to e.g. authenticate to gain the authorization
       *       to kill the process. But that's not how things currently work.
       */

      ret = FALSE;
      g_set_error (error,
                   G_IO_ERROR,
1054
                   g_io_error_from_errno (errsv),
1055
                   _("Cannot end process with PID %d: %s"),
1056
                   pid,
1057
                   g_strerror (errsv));
1058 1059 1060 1061
    }

  return ret;
}