r3768: Updated years.
[rox-filer.git] / ROX-Filer / src / main.c
blobf0ea95f893c1cab4786b3d60784b89cdedb319d4
1 /*
2 * $Id$
4 * ROX-Filer, filer for the ROX desktop project
5 * Copyright (C) 2005, the ROX-Filer team.
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the Free
9 * Software Foundation; either version 2 of the License, or (at your option)
10 * any later version.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * more details.
17 * You should have received a copy of the GNU General Public License along with
18 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
19 * Place, Suite 330, Boston, MA 02111-1307 USA
22 /* main.c - parses command-line options and parameters, plus some global
23 * housekeeping.
25 * New to the code and feeling lost? Read global.h now.
28 #include "config.h"
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <sys/types.h>
33 #include <signal.h>
34 #include <string.h>
35 #include <sys/wait.h>
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <pwd.h>
39 #include <grp.h>
40 #include <libxml/parser.h>
42 #ifdef HAVE_GETOPT_LONG
43 # include <getopt.h>
44 #endif
46 #include <gtk/gtk.h>
47 #include <gdk/gdkx.h> /* For rox_x_error */
49 #include "global.h"
51 #include "main.h"
52 #include "support.h"
53 #include "gui_support.h"
54 #include "filer.h"
55 #include "display.h"
56 #include "mount.h"
57 #include "menu.h"
58 #include "dnd.h"
59 #include "options.h"
60 #include "choices.h"
61 #include "type.h"
62 #include "pixmaps.h"
63 #include "dir.h"
64 #include "diritem.h"
65 #include "action.h"
66 #include "i18n.h"
67 #include "remote.h"
68 #include "pinboard.h"
69 #include "run.h"
70 #include "toolbar.h"
71 #include "bind.h"
72 #include "panel.h"
73 #include "session.h"
74 #include "minibuffer.h"
75 #include "xtypes.h"
77 int number_of_windows = 0; /* Quit when this reaches 0 again... */
78 int to_wakeup_pipe = -1; /* Write here to get noticed */
80 /* Information about the ROX-Filer process */
81 uid_t euid;
82 gid_t egid;
83 int ngroups; /* Number of supplemental groups */
84 gid_t *supplemental_groups = NULL;
86 /* Message to display at the top of each filer window */
87 const gchar *show_user_message = NULL;
89 int home_dir_len;
90 const char *home_dir, *app_dir;
92 GtkTooltips *tooltips = NULL;
94 #define COPYING \
95 N_("Copyright (C) 2005 Thomas Leonard.\n" \
96 "ROX-Filer comes with ABSOLUTELY NO WARRANTY,\n" \
97 "to the extent permitted by law.\n" \
98 "You may redistribute copies of ROX-Filer\n" \
99 "under the terms of the GNU General Public License.\n" \
100 "For more information about these matters, " \
101 "see the file named COPYING.\n")
103 #ifdef HAVE_GETOPT_LONG
104 # define USAGE N_("Try `ROX-Filer/AppRun --help' for more information.\n")
105 # define SHORT_ONLY_WARNING ""
106 #else
107 # define USAGE N_("Try `ROX-Filer/AppRun -h' for more information.\n")
108 # define SHORT_ONLY_WARNING \
109 _("NOTE: Your system does not support long options - \n" \
110 "you must use the short versions instead.\n\n")
111 #endif
113 #define BUGS_TO "<rox-devel@lists.sourceforge.net>"
115 #define HELP N_("Usage: ROX-Filer/AppRun [OPTION]... [FILE]...\n" \
116 "Open each directory or file listed, or the current working\n" \
117 "directory if no arguments are given.\n\n" \
118 " -b, --bottom=PANEL open PAN as a bottom-edge panel\n" \
119 " -c, --client-id=ID used for session management\n" \
120 " -d, --dir=DIR open DIR as directory (not application)\n" \
121 " -D, --close=DIR close DIR and its subdirectories\n" \
122 " -h, --help display this help and exit\n" \
123 " -l, --left=PANEL open PAN as a left-edge panel\n" \
124 " -m, --mime-type=FILE print MIME type of FILE and exit\n" \
125 " -n, --new start new copy; for debugging the filer\n" \
126 " -p, --pinboard=PIN use pinboard PIN as the pinboard\n" \
127 " -r, --right=PANEL open PAN as a right-edge panel\n" \
128 " -R, --RPC invoke method call read from stdin\n" \
129 " -s, --show=FILE open a directory showing FILE\n" \
130 " -t, --top=PANEL open PANEL as a top-edge panel\n" \
131 " -u, --user show user name in each window \n" \
132 " -v, --version display the version information and exit\n" \
133 " -x, --examine=FILE FILE has changed - re-examine it\n" \
134 "\nReport bugs to " BUGS_TO ".\n" \
135 "Home page (including updated versions): http://rox.sourceforge.net/\n")
137 #define SHORT_OPS "c:d:t:b:l:r:op:s:hvnux:m:D:R"
139 #ifdef HAVE_GETOPT_LONG
140 static struct option long_opts[] =
142 {"dir", 1, NULL, 'd'},
143 {"top", 1, NULL, 't'},
144 {"bottom", 1, NULL, 'b'},
145 {"left", 1, NULL, 'l'},
146 {"override", 0, NULL, 'o'},
147 {"pinboard", 1, NULL, 'p'},
148 {"right", 1, NULL, 'r'},
149 {"help", 0, NULL, 'h'},
150 {"version", 0, NULL, 'v'},
151 {"user", 0, NULL, 'u'},
152 {"new", 0, NULL, 'n'},
153 {"RPC", 0, NULL, 'R'},
154 {"show", 1, NULL, 's'},
155 {"examine", 1, NULL, 'x'},
156 {"close", 1, NULL, 'D'},
157 {"mime-type", 1, NULL, 'm'},
158 {"client-id", 1, NULL, 'c'},
159 {NULL, 0, NULL, 0},
161 #endif
163 /* Take control of panels away from WM? */
164 Option o_override_redirect;
166 /* Always start a new filer, even if one seems to be already running */
167 gboolean new_copy = FALSE;
169 /* Maps child PIDs to Callback pointers */
170 static GHashTable *death_callbacks = NULL;
171 static gboolean child_died_flag = FALSE;
173 Option o_dnd_no_hostnames;
175 /* Static prototypes */
176 static void show_features(void);
177 static void soap_add(xmlNodePtr body,
178 xmlChar *function,
179 const xmlChar *arg1_name, const xmlChar *arg1_value,
180 const xmlChar *arg2_name, const xmlChar *arg2_value);
181 static void child_died(int signum);
182 static void child_died_callback(void);
183 static void wake_up_cb(gpointer data, gint source, GdkInputCondition condition);
184 static void xrandr_size_change(GdkScreen *screen, gpointer user_data);
186 /****************************************************************
187 * EXTERNAL INTERFACE *
188 ****************************************************************/
190 /* The value that goes with an option */
191 #define VALUE (*optarg == '=' ? optarg + 1 : optarg)
193 static int rox_x_error(Display *display, XErrorEvent *error)
195 gchar buf[64];
197 XGetErrorText(display, error->error_code, buf, 63);
199 g_warning ("The program '%s' received an X Window System error.\n"
200 "This probably reflects a bug in the program.\n"
201 "The error was '%s'.\n"
202 " (Details: serial %ld error_code %d request_code %d minor_code %d)\n"
203 " (Note to programmers: normally, X errors are reported asynchronously;\n"
204 " that is, you will receive the error a while after causing it.\n"
205 " To debug your program, run it with the --sync command line\n"
206 " option to change this behavior. You can then get a meaningful\n"
207 " backtrace from your debugger.)",
208 g_get_prgname (),
209 buf,
210 error->serial,
211 error->error_code,
212 error->request_code,
213 error->minor_code);
215 abort();
218 /* Parses the command-line to work out what the user wants to do.
219 * Tries to send the request to an already-running copy of the filer.
220 * If that fails, it initialises all the other modules and executes the
221 * request itself.
223 int main(int argc, char **argv)
225 int wakeup_pipe[2];
226 int i;
227 struct sigaction act;
228 guchar *tmp, *dir;
229 gchar *client_id = NULL;
230 gboolean show_user = FALSE;
231 xmlDocPtr rpc, soap_rpc = NULL, reply;
232 xmlNodePtr body;
234 home_dir = g_get_home_dir();
235 home_dir_len = strlen(home_dir);
236 app_dir = g_strdup(getenv("APP_DIR"));
238 /* Get internationalisation up and running. This requires the
239 * choices system, to discover the user's preferred language.
241 choices_init();
242 options_init();
243 i18n_init();
244 xtype_init();
246 #ifdef HAVE_GNOME_VFS
247 if (!gnome_vfs_init())
248 g_warning("Failed to init gnomevfs!");
249 #endif
251 if (!app_dir)
253 g_warning("APP_DIR environment variable was unset!\n"
254 "Use the AppRun script to invoke ROX-Filer...\n");
255 app_dir = g_get_current_dir();
257 #ifdef HAVE_UNSETENV
258 else
260 /* Don't pass it on to our child processes... */
261 unsetenv("APP_DIR");
263 #endif
265 /* Sometimes we want to take special action when a child
266 * process exits. This hash table is used to convert the
267 * child's PID to the callback function.
269 death_callbacks = g_hash_table_new(NULL, NULL);
271 /* Find out some information about ourself */
272 euid = geteuid();
273 egid = getegid();
274 ngroups = getgroups(0, NULL);
275 if (ngroups < 0)
276 ngroups = 0;
277 else if (ngroups > 0)
279 supplemental_groups = g_malloc(sizeof(gid_t) * ngroups);
280 getgroups(ngroups, supplemental_groups);
283 if (argc == 2 && strcmp(argv[1], "-v") == 0)
285 /* This is used by install.sh to test if the filer
286 * compiled OK. Do this test before gtk_init so that
287 * we don't need an X server to install.
289 g_print("ROX-Filer %s\n", VERSION);
290 g_print(_(COPYING));
291 show_features();
292 return EXIT_SUCCESS;
295 option_add_int(&o_override_redirect, "override_redirect", FALSE);
297 /* The idea here is to convert the command-line arguments
298 * into a SOAP RPC.
299 * We attempt to invoke the call on an already-running copy of
300 * the filer if possible, or execute it ourselves if not.
302 rpc = soap_new(&body);
304 /* Note: must do this before checking our options,
305 * otherwise we report an error for Gtk's options.
307 gtk_init(&argc, &argv);
308 /* Set a default style for the collection widget */
309 gtk_rc_parse_string("style \"rox-default-collection-style\" {\n"
310 " bg[NORMAL] = \"#f3f3f3\"\n"
311 " fg[NORMAL] = \"#000000\"\n"
312 " bg[INSENSITIVE] = \"#bfbfbf\"\n"
313 " fg[INSENSITIVE] = \"#000000\"\n"
314 "}\n"
315 "style \"rox-default-pinboard-style\" {\n"
316 " bg[NORMAL] = \"#666666\"\n"
317 "}\n"
318 "widget \"rox-pinboard\" style : gtk "
319 "\"rox-default-pinboard-style\"\n"
321 "class \"Collection\" style : gtk "
322 "\"rox-default-collection-style\"\n");
324 g_signal_connect(gdk_screen_get_default(), "size-changed",
325 G_CALLBACK(xrandr_size_change), NULL);
327 /* Process each option in turn */
328 while (1)
330 int c;
331 #ifdef HAVE_GETOPT_LONG
332 int long_index;
333 c = getopt_long(argc, argv, SHORT_OPS,
334 long_opts, &long_index);
335 #else
336 c = getopt(argc, argv, SHORT_OPS);
337 #endif
339 if (c == EOF)
340 break; /* No more options */
342 switch (c)
344 case 'n':
345 new_copy = TRUE;
346 break;
347 case 'o':
348 info_message(_("The -o argument is no longer "
349 "used. You can turn on override "
350 "redirect from the Options box "
351 "instead."));
352 break;
353 case 'v':
354 g_print("ROX-Filer %s\n", VERSION);
355 g_print("%s", _(COPYING));
356 show_features();
357 return EXIT_SUCCESS;
358 case 'h':
359 g_print("%s", _(HELP));
360 g_print("%s", _(SHORT_ONLY_WARNING));
361 return EXIT_SUCCESS;
362 case 'D':
363 case 'd':
364 case 'x':
365 /* Argument is a path */
366 if (c == 'd' && VALUE[0] == '/')
367 tmp = g_strdup(VALUE);
368 else
369 tmp = pathdup(VALUE);
370 soap_add(body,
371 c == 'D' ? "CloseDir" :
372 c == 'd' ? "OpenDir" :
373 c == 'x' ? "Examine" : "Unknown",
374 "Filename", tmp,
375 NULL, NULL);
376 g_free(tmp);
377 break;
378 case 's':
379 tmp = g_path_get_dirname(VALUE);
381 if (tmp[0] == '/')
382 dir = NULL;
383 else
384 dir = pathdup(tmp);
386 soap_add(body, "Show",
387 "Directory", dir ? dir : tmp,
388 "Leafname", g_basename(VALUE));
389 g_free(tmp);
390 g_free(dir);
391 break;
392 case 'l':
393 case 'r':
394 case 't':
395 case 'b':
396 /* Argument is a leaf (or starts with /) */
397 soap_add(body, "Panel", "Name", VALUE,
398 "Side", c == 'l' ? "Left" :
399 c == 'r' ? "Right" :
400 c == 't' ? "Top" :
401 c == 'b' ? "Bottom" :
402 "Unkown");
403 break;
404 case 'p':
405 soap_add(body, "Pinboard",
406 "Name", VALUE, NULL, NULL);
407 break;
408 case 'u':
409 show_user = TRUE;
410 break;
411 case 'm':
413 MIME_type *type;
414 type_init();
415 diritem_init();
416 pixmaps_init();
417 type = type_get_type(VALUE);
418 printf("%s/%s\n", type->media_type,
419 type->subtype);
420 return EXIT_SUCCESS;
422 case 'c':
423 client_id = g_strdup(VALUE);
424 break;
425 case 'R':
426 soap_rpc = xmlParseFile("-");
427 if (!soap_rpc)
428 g_error("Invalid XML in RPC");
429 break;
430 default:
431 printf(_(USAGE));
432 return EXIT_FAILURE;
436 tooltips = gtk_tooltips_new();
438 if (euid == 0 || show_user)
439 show_user_message = g_strdup_printf(_("Running as user '%s'"),
440 user_name(euid));
442 /* Add each remaining (non-option) argument to the list of files
443 * to run.
445 i = optind;
446 while (i < argc)
448 tmp = pathdup(argv[i++]);
450 soap_add(body, "Run", "Filename", tmp, NULL, NULL);
452 g_free(tmp);
455 if (soap_rpc)
457 if (body->xmlChildrenNode)
458 g_error("Can't use -R with other options - sorry!");
459 xmlFreeDoc(rpc);
460 body = NULL;
461 rpc = soap_rpc;
463 else if (!body->xmlChildrenNode)
465 /* The user didn't request any action. Open the current
466 * directory.
468 guchar *dir;
470 dir = g_get_current_dir();
471 soap_add(body, "OpenDir", "Filename", dir, NULL, NULL);
472 g_free(dir);
475 option_add_int(&o_dnd_no_hostnames, "dnd_no_hostnames", 1);
477 /* Try to send the request to an already-running copy of the filer */
478 gui_support_init();
479 if (remote_init(rpc, new_copy))
480 return EXIT_SUCCESS; /* It worked - exit */
482 /* Put ourselves into the background (so 'rox' always works the
483 * same, whether we're already running or not).
484 * Not for -n, though (helps when debugging).
486 if (!new_copy)
488 int fd;
489 pid_t child;
491 child = fork();
492 if (child > 0)
493 _exit(0); /* Parent exits */
494 /* Otherwise we're the child (or an error occurred - ignore
495 * it!).
498 /* Close stdin. We don't need it, and it can cause problems if
499 * a child process wants a password, etc...
501 fd = open("/dev/null", O_RDONLY);
502 if (fd > 0)
504 close(0);
505 dup2(fd, 0);
506 close(fd);
510 /* Initialize the rest of the filer... */
512 pixmaps_init();
514 dnd_init();
515 bind_init();
516 dir_init();
517 diritem_init();
518 menu_init();
519 minibuffer_init();
520 filer_init();
521 toolbar_init();
522 display_init();
523 mount_init();
524 type_init();
525 action_init();
527 pinboard_init();
528 panel_init();
530 /* Let everyone update */
531 options_notify();
533 /* When we get a signal, we can't do much right then. Instead,
534 * we send a char down this pipe, which causes the main loop to
535 * deal with the event next time we're idle.
537 pipe(wakeup_pipe);
538 close_on_exec(wakeup_pipe[0], TRUE);
539 close_on_exec(wakeup_pipe[1], TRUE);
540 gdk_input_add_full(wakeup_pipe[0], GDK_INPUT_READ, wake_up_cb,
541 NULL, NULL);
542 to_wakeup_pipe = wakeup_pipe[1];
544 /* If the pipe is full then we're going to get woken up anyway... */
545 set_blocking(to_wakeup_pipe, FALSE);
547 /* Let child processes die */
548 act.sa_handler = child_died;
549 sigemptyset(&act.sa_mask);
550 act.sa_flags = SA_NOCLDSTOP;
551 sigaction(SIGCHLD, &act, NULL);
553 /* Ignore SIGPIPE - check for EPIPE errors instead */
554 act.sa_handler = SIG_IGN;
555 sigemptyset(&act.sa_mask);
556 act.sa_flags = 0;
557 sigaction(SIGPIPE, &act, NULL);
559 /* Set up session managament if available */
560 session_init(client_id);
561 g_free(client_id);
563 /* Finally, execute the request */
564 reply = run_soap(rpc);
565 xmlFreeDoc(rpc);
566 if (reply)
568 /* Write the result, if any, to stdout */
569 save_xml_file(reply, "-");
570 xmlFreeDoc(reply);
573 /* Try to find out why we crash with GTK 2.4 */
574 XSetErrorHandler(rox_x_error);
576 /* Enter the main loop, processing events until all our windows
577 * are closed.
579 if (number_of_windows > 0)
580 gtk_main();
582 return EXIT_SUCCESS;
585 /* Register a function to be called when process number 'child' dies. */
586 void on_child_death(gint child, CallbackFn callback, gpointer data)
588 Callback *cb;
590 g_return_if_fail(callback != NULL);
592 cb = g_new(Callback, 1);
594 cb->callback = callback;
595 cb->data = data;
597 g_hash_table_insert(death_callbacks, GINT_TO_POINTER(child), cb);
600 void one_less_window(void)
602 if (--number_of_windows < 1)
603 gtk_main_quit();
606 /****************************************************************
607 * INTERNAL FUNCTIONS *
608 ****************************************************************/
610 static void show_features(void)
612 g_print("\n");
613 g_print(_("Compiled with GTK version %s\n"), GTK_VERSION);
614 g_print(_("Running with GTK version %d.%d.%d\n"),
615 gtk_major_version,
616 gtk_minor_version,
617 gtk_micro_version);
618 g_print("\n-- %s --\n\n", _("features set at compile time"));
619 g_print("%s... %s\n", _("Large File Support"),
620 #ifdef LARGE_FILE_SUPPORT
621 _("Yes")
622 #else
623 _("No")
624 #endif
626 g_print("%s... %s\n", _("GNOME-VFS library"),
627 # ifdef HAVE_GNOME_VFS
628 _("Yes")
629 # else
630 _("No (need 2.8.0 or later)")
631 # endif
633 g_print("%s... %s\n", _("Dnotify support"),
634 #ifdef USE_DNOTIFY
635 _("Yes")
636 #else
637 _("No")
638 #endif
640 g_print("%s... %s\n", _("Binary compatibility"),
641 #if defined(HAVE_APSYMBOLS_H) || defined(HAVE_APBUILD_APSYMBOLS_H)
642 _("Yes (can run with older glibc versions)")
643 #else
644 _("No (apsymbols.h not found)")
645 #endif
649 static void soap_add(xmlNodePtr body,
650 xmlChar *function,
651 const xmlChar *arg1_name, const xmlChar *arg1_value,
652 const xmlChar *arg2_name, const xmlChar *arg2_value)
654 xmlNodePtr node;
655 xmlNs *rox;
657 rox = xmlSearchNsByHref(body->doc, body, ROX_NS);
659 node = xmlNewChild(body, rox, function, NULL);
661 if (arg1_name)
663 xmlNewTextChild(node, rox, arg1_name, arg1_value);
664 if (arg2_name)
665 xmlNewTextChild(node, rox, arg2_name, arg2_value);
669 /* This is called as a signal handler; simply ensures that
670 * child_died_callback() will get called later.
672 static void child_died(int signum)
674 child_died_flag = TRUE;
675 write(to_wakeup_pipe, "\0", 1); /* Wake up! */
678 static void child_died_callback(void)
680 int status;
681 gint child;
683 child_died_flag = FALSE;
685 /* Find out which children exited and allow them to die */
688 Callback *cb;
690 child = waitpid(-1, &status, WNOHANG);
692 if (child == 0 || child == -1)
693 return;
695 cb = g_hash_table_lookup(death_callbacks,
696 GINT_TO_POINTER(child));
697 if (cb)
699 cb->callback(cb->data);
700 g_hash_table_remove(death_callbacks,
701 GINT_TO_POINTER(child));
704 } while (1);
707 #define BUFLEN 40
708 /* When data is written to_wakeup_pipe, this gets called from the event
709 * loop some time later. Useful for getting out of signal handlers, etc.
711 static void wake_up_cb(gpointer data, gint source, GdkInputCondition condition)
713 char buf[BUFLEN];
715 read(source, buf, BUFLEN);
717 if (child_died_flag)
718 child_died_callback();
719 #ifdef USE_DNOTIFY
720 if (dnotify_wakeup)
721 dnotify_wakeup();
722 #endif
725 static void xrandr_size_change(GdkScreen *screen, gpointer user_data)
727 gui_store_screen_geometry(screen);
729 panel_update_size();
730 pinboard_update_size();