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, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * Modified by the GTK+ Team and others 1997-2000. See the AUTHORS
25 * file for a list of people on the GTK+ Team. See the ChangeLog
26 * files for a list of changes. These files are distributed with
27 * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
36 #include <X11/Xatom.h>
37 #include <gtk/gtkicontheme.h>
40 /* for the kill(2) system call and errno - POSIX.1-2001 and later */
41 #include <sys/types.h>
45 #if defined(__OpenBSD__)
46 #include <sys/param.h>
49 #include <sys/sysctl.h>
52 #include "gtkmountoperationprivate.h"
54 /* ---------------------------------------------------------------------------------------------------- */
55 /* these functions are based on code from libwnck (LGPLv2) */
57 static gboolean get_window_list (Display *xdisplay,
63 static char* get_utf8_property (Display *xdisplay,
67 static gboolean get_cardinal (Display *xdisplay,
72 static gboolean read_rgb_icon (Display *xdisplay,
82 get_cardinal (Display *xdisplay,
96 gdk_error_trap_push ();
98 result = XGetWindowProperty (xdisplay,
102 False, XA_CARDINAL, &type, &format, &nitems,
103 &bytes_after, (void*)&num);
104 XSync (xdisplay, False);
105 err = gdk_error_trap_pop ();
107 if (err != Success ||
111 if (type != XA_CARDINAL)
125 get_utf8_property (Display *xdisplay,
138 utf8_string = gdk_x11_get_xatom_by_name ("UTF8_STRING");
140 gdk_error_trap_push ();
143 result = XGetWindowProperty (xdisplay,
148 &type, &format, &nitems,
149 &bytes_after, (guchar **)&val);
150 XSync (xdisplay, False);
151 err = gdk_error_trap_pop ();
153 if (err != Success ||
157 if (type != utf8_string ||
166 if (!g_utf8_validate (val, nitems, NULL))
168 g_warning ("Property %s contained invalid UTF-8\n",
169 gdk_x11_get_xatom_name (atom));
174 retval = g_strndup (val, nitems);
182 find_largest_sizes (gulong *data,
195 return FALSE; /* no space for w, h */
200 if (nitems < ((w * h) + 2))
201 return FALSE; /* not enough data */
203 *width = MAX (w, *width);
204 *height = MAX (h, *height);
207 nitems -= (w * h) + 2;
214 find_best_size (gulong *data,
225 int max_width, max_height;
231 if (!find_largest_sizes (data, nitems, &max_width, &max_height))
235 ideal_width = max_width;
236 if (ideal_height < 0)
237 ideal_height = max_height;
251 return FALSE; /* no space for w, h */
256 if (nitems < ((w * h) + 2))
257 break; /* not enough data */
259 if (best_start == NULL)
265 /* work with averages */
266 const int ideal_size = (ideal_width + ideal_height) / 2;
267 int best_size = (best_w + best_h) / 2;
268 int this_size = (w + h) / 2;
270 /* larger than desired is always better than smaller */
271 if (best_size < ideal_size &&
272 this_size >= ideal_size)
274 /* if we have too small, pick anything bigger */
275 else if (best_size < ideal_size &&
276 this_size > best_size)
278 /* if we have too large, pick anything smaller
279 * but still >= the ideal
281 else if (best_size > ideal_size &&
282 this_size >= ideal_size &&
283 this_size < best_size)
289 best_start = data + 2;
295 nitems -= (w * h) + 2;
310 argbdata_to_pixdata (gulong *argb_data,
317 *pixdata = g_new (guchar, len * 4);
320 /* One could speed this up a lot. */
328 rgba = (argb << 8) | (argb >> 24);
332 *p = (rgba >> 16) & 0xff;
334 *p = (rgba >> 8) & 0xff;
344 read_rgb_icon (Display *xdisplay,
361 gdk_error_trap_push ();
364 result = XGetWindowProperty (xdisplay,
366 gdk_x11_get_xatom_by_name ("_NET_WM_ICON"),
368 False, XA_CARDINAL, &type, &format, &nitems,
369 &bytes_after, (void*)&data);
371 XSync (xdisplay, False);
372 err = gdk_error_trap_pop ();
374 if (err != Success ||
378 if (type != XA_CARDINAL)
384 if (!find_best_size (data, nitems,
385 ideal_width, ideal_height,
395 argbdata_to_pixdata (best, w * h, pixdata);
403 free_pixels (guchar *pixels, gpointer data)
409 scaled_from_pixdata (guchar *pixdata,
418 src = gdk_pixbuf_new_from_data (pixdata,
436 tmp = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8, size, size);
440 gdk_pixbuf_fill (tmp, 0);
441 gdk_pixbuf_copy_area (src, 0, 0, w, h,
443 (size - w) / 2, (size - h) / 2);
445 g_object_unref (src);
450 if (w != new_w || h != new_h)
452 dest = gdk_pixbuf_scale_simple (src, new_w, new_h, GDK_INTERP_BILINEAR);
454 g_object_unref (G_OBJECT (src));
465 get_window_list (Display *xdisplay,
481 gdk_error_trap_push ();
483 result = XGetWindowProperty (xdisplay,
487 False, XA_WINDOW, &type, &format, &nitems,
488 &bytes_after, (void*)&data);
489 XSync (xdisplay, False);
490 err = gdk_error_trap_pop ();
492 if (err != Success ||
496 if (type != XA_WINDOW)
502 *windows = g_new (Window, nitems);
503 memcpy (*windows, data, sizeof (Window) * nitems);
512 /* ---------------------------------------------------------------------------------------------------- */
514 struct _GtkMountOperationLookupContext
516 /* Hash from pid (gint) -> XID (gint)
518 * Note that XIDs are at most 27 bits - however, also note that sizeof(XID) == 8 on
519 * x86_64 - that's just xlib brokenness. So it's safe to stuff the XID into a pointer.
521 GHashTable *pid_to_window;
525 GtkMountOperationLookupContext *
526 _gtk_mount_operation_lookup_context_get (GdkDisplay *display)
528 GtkMountOperationLookupContext *context;
533 context = g_new0 (GtkMountOperationLookupContext, 1);
535 context->pid_to_window = g_hash_table_new (g_direct_hash, g_direct_equal);
536 context->display = display;
540 get_window_list (GDK_DISPLAY_XDISPLAY (context->display),
542 gdk_x11_get_xatom_by_name_for_display (context->display,
546 for (n = 0; n < mapping_length; n++)
550 if (!get_cardinal (GDK_DISPLAY_XDISPLAY (context->display),
552 gdk_x11_get_xatom_by_name_for_display (context->display,
557 g_hash_table_insert (context->pid_to_window,
558 GINT_TO_POINTER (pid),
559 GINT_TO_POINTER ((gint) mapping[n]));
567 _gtk_mount_operation_lookup_context_free (GtkMountOperationLookupContext *context)
569 g_hash_table_unref (context->pid_to_window);
573 /* ---------------------------------------------------------------------------------------------------- */
578 pid_get_parent (GPid pid)
582 gchar *stat_filename;
583 gchar *stat_contents;
588 stat_contents = NULL;
589 stat_filename = NULL;
591 /* fail if trying to get the parent of the init process (no such thing) */
595 stat_filename = g_strdup_printf ("/proc/%d/status", pid);
596 if (g_file_get_contents (stat_filename,
603 tokens = g_strsplit (stat_contents, "\n", 0);
605 for (n = 0; tokens[n] != NULL; n++)
607 if (g_str_has_prefix (tokens[n], "PPid:"))
612 ppid = strtoll (tokens[n] + sizeof "PPid:" - 1, &endp, 10);
613 if (endp == NULL || *endp != '\0')
615 g_warning ("Error parsing contents of `%s'. Parent pid is malformed.",
628 g_free (stat_contents);
629 g_free (stat_filename);
635 pid_get_env (GPid pid,
647 key_len = strlen (key);
649 env_filename = g_strdup_printf ("/proc/%d/environ", pid);
650 if (g_file_get_contents (env_filename,
657 /* /proc/<pid>/environ in Linux is split at '\0' points, g_strsplit() can't handle that... */
661 if (env[n] == '\0' || n >= env_len)
664 if (g_str_has_prefix (env + n, key) && (*(env + n + key_len) == '='))
666 ret = g_strdup (env + n + key_len + 1);
668 /* skip invalid UTF-8 */
669 if (!g_utf8_validate (ret, -1, (const gchar **) &end))
674 for (; env[n] != '\0' && n < env_len; n++)
680 g_free (env_filename);
686 pid_get_command_line (GPid pid)
688 gchar *cmdline_filename;
689 gchar *cmdline_contents;
694 cmdline_contents = NULL;
696 cmdline_filename = g_strdup_printf ("/proc/%d/cmdline", pid);
697 if (!g_file_get_contents (cmdline_filename,
703 /* /proc/<pid>/cmdline separates args by NUL-bytes - replace with spaces */
704 for (n = 0; n < cmdline_len - 1; n++)
706 if (cmdline_contents[n] == '\0')
707 cmdline_contents[n] = ' ';
710 /* skip invalid UTF-8 */
711 if (!g_utf8_validate (cmdline_contents, -1, (const gchar **) &end))
715 g_free (cmdline_filename);
717 return cmdline_contents;
720 /* ---------------------------------------------------------------------------------------------------- */
722 #elif defined(__OpenBSD__)
724 /* ---------------------------------------------------------------------------------------------------- */
727 pid_get_parent (GPid pid)
729 struct kinfo_proc *proc;
734 kvm = kvm_openfiles (NULL, NULL, NULL, KVM_NO_FILES, NULL);
738 proc = kvm_getprocs (kvm, KERN_PROC_PID, pid, sizeof(struct kinfo_proc), &count);
747 pid_get_env (GPid pid, const gchar *key)
750 struct kinfo_proc *proc;
758 kvm = kvm_openfiles (NULL, NULL, NULL, KVM_NO_FILES, NULL);
762 key_len = strlen (key);
765 proc = kvm_getprocs (kvm, KERN_PROC_PID, pid, sizeof(struct kinfo_proc), &count);
768 strs = kvm_getenvv (kvm, proc, 0);
769 for (i = 0; strs[i] != NULL; i++)
771 if (g_str_has_prefix (strs[i], key) && (*(strs[i] + key_len) == '='))
773 ret = g_strdup (strs[i] + key_len + 1);
775 /* skip invalid UTF-8 */
776 if (!g_utf8_validate (ret, -1, (const gchar **) &end))
788 pid_get_command_line (GPid pid)
791 struct kinfo_proc *proc;
797 kvm = kvm_openfiles (NULL, NULL, NULL, KVM_NO_FILES, NULL);
801 proc = kvm_getprocs (kvm, KERN_PROC_PID, pid, sizeof (struct kinfo_proc), &count);
805 strs = kvm_getargv (kvm, proc, 0);
806 ret = g_strjoinv (" ", strs);
807 /* skip invalid UTF-8 */
808 if (!g_utf8_validate (ret, -1, (const gchar **) &end))
817 /* TODO: please implement for your OS - must return valid UTF-8 */
820 pid_get_parent (GPid pid)
826 pid_get_env (GPid pid,
833 pid_get_command_line (GPid pid)
840 /* ---------------------------------------------------------------------------------------------------- */
843 get_name_for_window_with_pid (GtkMountOperationLookupContext *context,
847 Window windowid_window;
852 window = GPOINTER_TO_INT (g_hash_table_lookup (context->pid_to_window, GINT_TO_POINTER (pid)));
855 gchar *windowid_value;
857 /* check for $WINDOWID (set by terminals) and see if we can get the title that way */
858 windowid_value = pid_get_env (pid, "WINDOWID");
859 if (windowid_value != NULL)
864 windowid_window = (Window) g_ascii_strtoll (windowid_value, &endp, 10);
865 if (endp != NULL || *endp == '\0')
867 window = windowid_window;
869 g_free (windowid_value);
872 /* otherwise, check for parents */
877 pid = pid_get_parent (pid);
881 window = GPOINTER_TO_INT (g_hash_table_lookup (context->pid_to_window, GINT_TO_POINTER (pid)));
891 ret = get_utf8_property (GDK_DISPLAY_XDISPLAY (context->display),
893 gdk_x11_get_xatom_by_name_for_display (context->display,
896 ret = get_utf8_property (GDK_DISPLAY_XDISPLAY (context->display),
897 window, gdk_x11_get_xatom_by_name_for_display (context->display,
898 "_NET_WM_ICON_NAME"));
904 /* ---------------------------------------------------------------------------------------------------- */
907 get_pixbuf_for_window_with_pid (GtkMountOperationLookupContext *context,
916 window = GPOINTER_TO_INT (g_hash_table_lookup (context->pid_to_window, GINT_TO_POINTER (pid)));
919 /* otherwise, check for parents */
922 pid = pid_get_parent (pid);
926 window = GPOINTER_TO_INT (g_hash_table_lookup (context->pid_to_window, GINT_TO_POINTER (pid)));
939 if (read_rgb_icon (GDK_DISPLAY_XDISPLAY (context->display),
941 size_pixels, size_pixels,
946 ret = scaled_from_pixdata (pixdata,
948 size_pixels, size_pixels);
955 /* ---------------------------------------------------------------------------------------------------- */
957 static const gchar *well_known_commands[] =
959 /* translators: this string is a name for the 'less' command */
960 "less", N_("Terminal Pager"),
961 "top", N_("Top Command"),
962 "bash", N_("Bourne Again Shell"),
963 "sh", N_("Bourne Shell"),
964 "zsh", N_("Z Shell"),
969 _gtk_mount_operation_lookup_info (GtkMountOperationLookupContext *context,
973 gchar **out_command_line,
974 GdkPixbuf **out_pixbuf)
976 g_return_val_if_fail (out_name != NULL && *out_name == NULL, FALSE);
977 g_return_val_if_fail (out_command_line != NULL && *out_command_line == NULL, FALSE);
978 g_return_val_if_fail (out_pixbuf != NULL && *out_pixbuf == NULL, FALSE);
980 /* We perform two different lookups for name and icon size.. this is
981 * because we want the name from the window with WINDOWID and this
982 * normally does not give you an icon
984 * (the canonical example is a tab in gnome-terminal - the shell/command running
985 * in the shell will have WINDOWID set - but this window won't have an icon - so
986 * we want to continue up until the gnome-terminal window so we can get that icon)
989 *out_command_line = pid_get_command_line (pid);
991 *out_name = get_name_for_window_with_pid (context, pid);
993 *out_pixbuf = get_pixbuf_for_window_with_pid (context, pid, size_pixels);
995 /* if we didn't manage to find the name via X, fall back to the basename
996 * of the first element of the command line and, for maximum geek-comfort,
997 * map a few well-known commands to proper translated names
999 if (*out_name == NULL && *out_command_line != NULL &&
1000 strlen (*out_command_line) > 0 && (*out_command_line)[0] != ' ')
1006 /* find the first character after the first argument */
1007 s = strchr (*out_command_line, ' ');
1009 s = *out_command_line + strlen (*out_command_line);
1011 for (p = s; p > *out_command_line; p--)
1020 *out_name = g_strndup (p, s - p);
1022 for (n = 0; well_known_commands[n] != NULL; n += 2)
1024 /* sometimes the command is prefixed with a -, e.g. '-bash' instead
1025 * of 'bash' - handle that as well
1027 if ((strcmp (well_known_commands[n], *out_name) == 0) ||
1028 ((*out_name)[0] == '-' && (strcmp (well_known_commands[n], (*out_name) + 1) == 0)))
1031 *out_name = g_strdup (_(well_known_commands[n+1]));
1041 _gtk_mount_operation_kill_process (GPid pid,
1048 if (kill ((pid_t) pid, SIGTERM) != 0)
1052 /* TODO: On EPERM, we could use a setuid helper using polkit (very easy to implement
1053 * via pkexec(1)) to allow the user to e.g. authenticate to gain the authorization
1054 * to kill the process. But that's not how things currently work.
1060 g_io_error_from_errno (errsv),
1061 _("Cannot end process with PID %d: %s"),
1063 g_strerror (errsv));