1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* GTK - The GIMP Toolkit
3 * Copyright (C) David Zeuthen <davidz@redhat.com>
4 * Copyright (C) 2001 Havoc Pennington
5 * Copyright (C) 2005-2007 Vincent Untz
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
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 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
22 * Modified by the GTK+ Team and others 1997-2000. See the AUTHORS
23 * file for a list of people on the GTK+ Team. See the ChangeLog
24 * files for a list of changes. These files are distributed with
25 * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
34 #include <X11/Xatom.h>
35 #include <gtk/gtkicontheme.h>
38 /* for the kill(2) system call and errno - POSIX.1-2001 and later */
39 #include <sys/types.h>
43 #if defined(__OpenBSD__)
45 #include <sys/param.h>
47 #include <sys/sysctl.h>
50 #include "gtkmountoperationprivate.h"
52 /* ---------------------------------------------------------------------------------------------------- */
53 /* these functions are based on code from libwnck (LGPLv2) */
55 static gboolean get_window_list (Display *xdisplay,
61 static char* get_utf8_property (Display *xdisplay,
65 static gboolean get_cardinal (Display *xdisplay,
70 static gboolean read_rgb_icon (Display *xdisplay,
80 get_cardinal (Display *xdisplay,
94 gdk_error_trap_push ();
96 result = XGetWindowProperty (xdisplay,
100 False, XA_CARDINAL, &type, &format, &nitems,
101 &bytes_after, (void*)&num);
102 XSync (xdisplay, False);
103 err = gdk_error_trap_pop ();
105 if (err != Success ||
109 if (type != XA_CARDINAL)
123 get_utf8_property (Display *xdisplay,
136 utf8_string = gdk_x11_get_xatom_by_name ("UTF8_STRING");
138 gdk_error_trap_push ();
141 result = XGetWindowProperty (xdisplay,
146 &type, &format, &nitems,
147 &bytes_after, (guchar **)&val);
148 XSync (xdisplay, False);
149 err = gdk_error_trap_pop ();
151 if (err != Success ||
155 if (type != utf8_string ||
164 if (!g_utf8_validate (val, nitems, NULL))
166 g_warning ("Property %s contained invalid UTF-8\n",
167 gdk_x11_get_xatom_name (atom));
172 retval = g_strndup (val, nitems);
180 find_largest_sizes (gulong *data,
193 return FALSE; /* no space for w, h */
198 if (nitems < ((w * h) + 2))
199 return FALSE; /* not enough data */
201 *width = MAX (w, *width);
202 *height = MAX (h, *height);
205 nitems -= (w * h) + 2;
212 find_best_size (gulong *data,
223 int max_width, max_height;
229 if (!find_largest_sizes (data, nitems, &max_width, &max_height))
233 ideal_width = max_width;
234 if (ideal_height < 0)
235 ideal_height = max_height;
249 return FALSE; /* no space for w, h */
254 if (nitems < ((w * h) + 2))
255 break; /* not enough data */
257 if (best_start == NULL)
263 /* work with averages */
264 const int ideal_size = (ideal_width + ideal_height) / 2;
265 int best_size = (best_w + best_h) / 2;
266 int this_size = (w + h) / 2;
268 /* larger than desired is always better than smaller */
269 if (best_size < ideal_size &&
270 this_size >= ideal_size)
272 /* if we have too small, pick anything bigger */
273 else if (best_size < ideal_size &&
274 this_size > best_size)
276 /* if we have too large, pick anything smaller
277 * but still >= the ideal
279 else if (best_size > ideal_size &&
280 this_size >= ideal_size &&
281 this_size < best_size)
287 best_start = data + 2;
293 nitems -= (w * h) + 2;
308 argbdata_to_pixdata (gulong *argb_data,
315 *pixdata = g_new (guchar, len * 4);
318 /* One could speed this up a lot. */
326 rgba = (argb << 8) | (argb >> 24);
330 *p = (rgba >> 16) & 0xff;
332 *p = (rgba >> 8) & 0xff;
342 read_rgb_icon (Display *xdisplay,
359 gdk_error_trap_push ();
362 result = XGetWindowProperty (xdisplay,
364 gdk_x11_get_xatom_by_name ("_NET_WM_ICON"),
366 False, XA_CARDINAL, &type, &format, &nitems,
367 &bytes_after, (void*)&data);
369 XSync (xdisplay, False);
370 err = gdk_error_trap_pop ();
372 if (err != Success ||
376 if (type != XA_CARDINAL)
382 if (!find_best_size (data, nitems,
383 ideal_width, ideal_height,
393 argbdata_to_pixdata (best, w * h, pixdata);
401 free_pixels (guchar *pixels, gpointer data)
407 scaled_from_pixdata (guchar *pixdata,
416 src = gdk_pixbuf_new_from_data (pixdata,
434 tmp = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8, size, size);
438 gdk_pixbuf_fill (tmp, 0);
439 gdk_pixbuf_copy_area (src, 0, 0, w, h,
441 (size - w) / 2, (size - h) / 2);
443 g_object_unref (src);
448 if (w != new_w || h != new_h)
450 dest = gdk_pixbuf_scale_simple (src, new_w, new_h, GDK_INTERP_BILINEAR);
452 g_object_unref (G_OBJECT (src));
463 get_window_list (Display *xdisplay,
479 gdk_error_trap_push ();
481 result = XGetWindowProperty (xdisplay,
485 False, XA_WINDOW, &type, &format, &nitems,
486 &bytes_after, (void*)&data);
487 XSync (xdisplay, False);
488 err = gdk_error_trap_pop ();
490 if (err != Success ||
494 if (type != XA_WINDOW)
500 *windows = g_new (Window, nitems);
501 memcpy (*windows, data, sizeof (Window) * nitems);
510 /* ---------------------------------------------------------------------------------------------------- */
512 struct _GtkMountOperationLookupContext
514 /* Hash from pid (gint) -> XID (gint)
516 * Note that XIDs are at most 27 bits - however, also note that sizeof(XID) == 8 on
517 * x86_64 - that's just xlib brokenness. So it's safe to stuff the XID into a pointer.
519 GHashTable *pid_to_window;
523 GtkMountOperationLookupContext *
524 _gtk_mount_operation_lookup_context_get (GdkDisplay *display)
526 GtkMountOperationLookupContext *context;
531 context = g_new0 (GtkMountOperationLookupContext, 1);
533 context->pid_to_window = g_hash_table_new (g_direct_hash, g_direct_equal);
534 context->display = display;
538 get_window_list (GDK_DISPLAY_XDISPLAY (context->display),
540 gdk_x11_get_xatom_by_name_for_display (context->display,
544 for (n = 0; n < mapping_length; n++)
548 if (!get_cardinal (GDK_DISPLAY_XDISPLAY (context->display),
550 gdk_x11_get_xatom_by_name_for_display (context->display,
555 g_hash_table_insert (context->pid_to_window,
556 GINT_TO_POINTER (pid),
557 GINT_TO_POINTER ((gint) mapping[n]));
565 _gtk_mount_operation_lookup_context_free (GtkMountOperationLookupContext *context)
567 g_hash_table_unref (context->pid_to_window);
571 /* ---------------------------------------------------------------------------------------------------- */
576 pid_get_parent (GPid pid)
580 gchar *stat_filename;
581 gchar *stat_contents;
586 stat_contents = NULL;
587 stat_filename = NULL;
589 /* fail if trying to get the parent of the init process (no such thing) */
593 stat_filename = g_strdup_printf ("/proc/%d/status", pid);
594 if (g_file_get_contents (stat_filename,
601 tokens = g_strsplit (stat_contents, "\n", 0);
603 for (n = 0; tokens[n] != NULL; n++)
605 if (g_str_has_prefix (tokens[n], "PPid:"))
610 ppid = strtoll (tokens[n] + sizeof "PPid:" - 1, &endp, 10);
611 if (endp == NULL || *endp != '\0')
613 g_warning ("Error parsing contents of `%s'. Parent pid is malformed.",
626 g_free (stat_contents);
627 g_free (stat_filename);
633 pid_get_env (GPid pid,
645 key_len = strlen (key);
647 env_filename = g_strdup_printf ("/proc/%d/environ", pid);
648 if (g_file_get_contents (env_filename,
655 /* /proc/<pid>/environ in Linux is split at '\0' points, g_strsplit() can't handle that... */
659 if (env[n] == '\0' || n >= env_len)
662 if (g_str_has_prefix (env + n, key) && (*(env + n + key_len) == '='))
664 ret = g_strdup (env + n + key_len + 1);
666 /* skip invalid UTF-8 */
667 if (!g_utf8_validate (ret, -1, (const gchar **) &end))
672 for (; env[n] != '\0' && n < env_len; n++)
678 g_free (env_filename);
684 pid_get_command_line (GPid pid)
686 gchar *cmdline_filename;
687 gchar *cmdline_contents;
692 cmdline_contents = NULL;
694 cmdline_filename = g_strdup_printf ("/proc/%d/cmdline", pid);
695 if (!g_file_get_contents (cmdline_filename,
701 /* /proc/<pid>/cmdline separates args by NUL-bytes - replace with spaces */
702 for (n = 0; n < cmdline_len - 1; n++)
704 if (cmdline_contents[n] == '\0')
705 cmdline_contents[n] = ' ';
708 /* skip invalid UTF-8 */
709 if (!g_utf8_validate (cmdline_contents, -1, (const gchar **) &end))
713 g_free (cmdline_filename);
715 return cmdline_contents;
718 /* ---------------------------------------------------------------------------------------------------- */
720 #elif defined(__OpenBSD__)
722 /* ---------------------------------------------------------------------------------------------------- */
725 pid_get_parent (GPid pid)
727 struct kinfo_proc kp;
731 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid,
732 sizeof(struct kinfo_proc), 0 };
734 if (sysctl(mib, G_N_ELEMENTS (mib), NULL, &len, NULL, 0) == -1)
736 mib[5] = (len / sizeof(struct kinfo_proc));
738 if (sysctl(mib, G_N_ELEMENTS (mib), &kp, &len, NULL, 0) < 0)
747 pid_get_env (GPid pid, const gchar *key)
749 size_t len = PATH_MAX;
756 int mib[] = { CTL_KERN, KERN_PROC_ARGS, pid, KERN_PROC_ENV };
758 strs = (char **)realloc(strs, len);
760 key_len = strlen (key);
763 if (sysctl(mib, G_N_ELEMENTS (mib), strs, &len, NULL, 0) != -1)
765 for (i = 0; strs[i] != NULL; i++)
767 if (g_str_has_prefix (strs[i], key) && (*(strs[i] + key_len) == '='))
769 ret = g_strdup (strs[i] + key_len + 1);
771 /* skip invalid UTF-8 */
772 if (!g_utf8_validate (ret, -1, (const gchar **) &end))
784 pid_get_command_line (GPid pid)
786 size_t len = PATH_MAX;
791 int mib[] = { CTL_KERN, KERN_PROC_ARGS, pid, KERN_PROC_ARGV };
793 strs = (char **)realloc(strs, len);
795 if (sysctl(mib, G_N_ELEMENTS (mib), strs, &len, NULL, 0) == -1) {
800 ret = g_strjoinv (" ", strs);
801 /* skip invalid UTF-8 */
802 if (!g_utf8_validate (ret, -1, (const gchar **) &end))
811 /* TODO: please implement for your OS - must return valid UTF-8 */
814 pid_get_parent (GPid pid)
820 pid_get_env (GPid pid,
827 pid_get_command_line (GPid pid)
834 /* ---------------------------------------------------------------------------------------------------- */
837 get_name_for_window_with_pid (GtkMountOperationLookupContext *context,
841 Window windowid_window;
846 window = GPOINTER_TO_INT (g_hash_table_lookup (context->pid_to_window, GINT_TO_POINTER (pid)));
849 gchar *windowid_value;
851 /* check for $WINDOWID (set by terminals) and see if we can get the title that way */
852 windowid_value = pid_get_env (pid, "WINDOWID");
853 if (windowid_value != NULL)
858 windowid_window = (Window) g_ascii_strtoll (windowid_value, &endp, 10);
859 if (endp != NULL || *endp == '\0')
861 window = windowid_window;
863 g_free (windowid_value);
866 /* otherwise, check for parents */
871 pid = pid_get_parent (pid);
875 window = GPOINTER_TO_INT (g_hash_table_lookup (context->pid_to_window, GINT_TO_POINTER (pid)));
885 ret = get_utf8_property (GDK_DISPLAY_XDISPLAY (context->display),
887 gdk_x11_get_xatom_by_name_for_display (context->display,
890 ret = get_utf8_property (GDK_DISPLAY_XDISPLAY (context->display),
891 window, gdk_x11_get_xatom_by_name_for_display (context->display,
892 "_NET_WM_ICON_NAME"));
898 /* ---------------------------------------------------------------------------------------------------- */
901 get_pixbuf_for_window_with_pid (GtkMountOperationLookupContext *context,
910 window = GPOINTER_TO_INT (g_hash_table_lookup (context->pid_to_window, GINT_TO_POINTER (pid)));
913 /* otherwise, check for parents */
916 pid = pid_get_parent (pid);
920 window = GPOINTER_TO_INT (g_hash_table_lookup (context->pid_to_window, GINT_TO_POINTER (pid)));
933 if (read_rgb_icon (GDK_DISPLAY_XDISPLAY (context->display),
935 size_pixels, size_pixels,
940 ret = scaled_from_pixdata (pixdata,
942 size_pixels, size_pixels);
949 /* ---------------------------------------------------------------------------------------------------- */
951 static const gchar *well_known_commands[] =
953 /* translators: this string is a name for the 'less' command */
954 "less", N_("Terminal Pager"),
955 "top", N_("Top Command"),
956 "bash", N_("Bourne Again Shell"),
957 "sh", N_("Bourne Shell"),
958 "zsh", N_("Z Shell"),
963 _gtk_mount_operation_lookup_info (GtkMountOperationLookupContext *context,
967 gchar **out_command_line,
968 GdkPixbuf **out_pixbuf)
970 g_return_val_if_fail (out_name != NULL && *out_name == NULL, FALSE);
971 g_return_val_if_fail (out_command_line != NULL && *out_command_line == NULL, FALSE);
972 g_return_val_if_fail (out_pixbuf != NULL && *out_pixbuf == NULL, FALSE);
974 /* We perform two different lookups for name and icon size.. this is
975 * because we want the name from the window with WINDOWID and this
976 * normally does not give you an icon
978 * (the canonical example is a tab in gnome-terminal - the shell/command running
979 * in the shell will have WINDOWID set - but this window won't have an icon - so
980 * we want to continue up until the gnome-terminal window so we can get that icon)
983 *out_command_line = pid_get_command_line (pid);
985 *out_name = get_name_for_window_with_pid (context, pid);
987 *out_pixbuf = get_pixbuf_for_window_with_pid (context, pid, size_pixels);
989 /* if we didn't manage to find the name via X, fall back to the basename
990 * of the first element of the command line and, for maximum geek-comfort,
991 * map a few well-known commands to proper translated names
993 if (*out_name == NULL && *out_command_line != NULL &&
994 strlen (*out_command_line) > 0 && (*out_command_line)[0] != ' ')
1000 /* find the first character after the first argument */
1001 s = strchr (*out_command_line, ' ');
1003 s = *out_command_line + strlen (*out_command_line);
1005 for (p = s; p > *out_command_line; p--)
1014 *out_name = g_strndup (p, s - p);
1016 for (n = 0; well_known_commands[n] != NULL; n += 2)
1018 /* sometimes the command is prefixed with a -, e.g. '-bash' instead
1019 * of 'bash' - handle that as well
1021 if ((strcmp (well_known_commands[n], *out_name) == 0) ||
1022 ((*out_name)[0] == '-' && (strcmp (well_known_commands[n], (*out_name) + 1) == 0)))
1025 *out_name = g_strdup (_(well_known_commands[n+1]));
1035 _gtk_mount_operation_kill_process (GPid pid,
1042 if (kill ((pid_t) pid, SIGTERM) != 0)
1046 /* TODO: On EPERM, we could use a setuid helper using polkit (very easy to implement
1047 * via pkexec(1)) to allow the user to e.g. authenticate to gain the authorization
1048 * to kill the process. But that's not how things currently work.
1054 g_io_error_from_errno (errsv),
1055 _("Cannot end process with PID %d: %s"),
1057 g_strerror (errsv));