use EXIT_SUCCESS. it's the same thing, but more correct.
[mikachu/openbox.git] / openbox / openbox.c
1 /* -*- indent-tabs-mode: nil; tab-width: 4; c-basic-offset: 4; -*-
2
3    openbox.c for the Openbox window manager
4    Copyright (c) 2006        Mikael Magnusson
5    Copyright (c) 2003        Ben Jansens
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program 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
15    GNU General Public License for more details.
16
17    See the COPYING file for a copy of the GNU General Public License.
18 */
19
20 #include "debug.h"
21 #include "openbox.h"
22 #include "session.h"
23 #include "dock.h"
24 #include "event.h"
25 #include "menu.h"
26 #include "client.h"
27 #include "xerror.h"
28 #include "prop.h"
29 #include "screen.h"
30 #include "startupnotify.h"
31 #include "focus.h"
32 #include "moveresize.h"
33 #include "frame.h"
34 #include "keyboard.h"
35 #include "mouse.h"
36 #include "extensions.h"
37 #include "menuframe.h"
38 #include "grab.h"
39 #include "group.h"
40 #include "config.h"
41 #include "mainloop.h"
42 #include "gettext.h"
43 #include "parser/parse.h"
44 #include "render/render.h"
45 #include "render/theme.h"
46
47 #ifdef HAVE_FCNTL_H
48 #  include <fcntl.h>
49 #endif
50 #ifdef HAVE_SIGNAL_H
51 #  include <signal.h>
52 #endif
53 #ifdef HAVE_STDLIB_H
54 #  include <stdlib.h>
55 #endif
56 #ifdef HAVE_LOCALE_H
57 #  include <locale.h>
58 #endif
59 #ifdef HAVE_SYS_STAT_H
60 #  include <sys/stat.h>
61 #  include <sys/types.h>
62 #endif
63 #ifdef HAVE_SYS_WAIT_H
64 #  include <sys/types.h>
65 #  include <sys/wait.h>
66 #endif
67 #ifdef HAVE_UNISTD_H
68 #  include <unistd.h>
69 #endif
70 #include <errno.h>
71
72 #include <X11/cursorfont.h>
73
74 RrInstance *ob_rr_inst;
75 RrTheme    *ob_rr_theme;
76 ObMainLoop *ob_main_loop;
77 Display    *ob_display;
78 gint        ob_screen;
79 gboolean    ob_replace_wm = FALSE;
80
81 static ObState   state;
82 static gboolean  xsync = FALSE;
83 static gboolean  reconfigure = FALSE;
84 static gboolean  restart = FALSE;
85 static gchar    *restart_path = NULL;
86 static Cursor    cursors[OB_NUM_CURSORS];
87 static KeyCode   keys[OB_NUM_KEYS];
88 static gint      exitcode = 0;
89 static guint     remote_control = 0;
90 static gboolean  being_replaced = FALSE;
91
92 static void signal_handler(gint signal, gpointer data);
93 static void parse_args(gint argc, gchar **argv);
94
95 gint main(gint argc, gchar **argv)
96 {
97 #ifdef DEBUG
98     ob_debug_show_output(TRUE);
99 #endif
100
101     state = OB_STATE_STARTING;
102
103     /* initialize the locale */
104     if (!setlocale(LC_ALL, ""))
105         g_warning("Couldn't set locale from environment.\n");
106     bindtextdomain(PACKAGE_NAME, LOCALEDIR);
107     bind_textdomain_codeset(PACKAGE_NAME, "UTF-8");
108     textdomain(PACKAGE_NAME);
109
110     g_set_prgname(argv[0]);
111
112     if (chdir(g_get_home_dir()) == -1)
113         g_warning("Unable to change to home directory (%s): %s",
114                   g_get_home_dir(), g_strerror(errno));
115      
116     /* parse out command line args */
117     parse_args(argc, argv);
118
119     if (!remote_control) {
120         parse_paths_startup();
121
122         session_startup(argc, argv);
123     }
124
125     ob_display = XOpenDisplay(NULL);
126     if (ob_display == NULL)
127         ob_exit_with_error("Failed to open the display.");
128     if (fcntl(ConnectionNumber(ob_display), F_SETFD, 1) == -1)
129         ob_exit_with_error("Failed to set display as close-on-exec.");
130
131     if (remote_control) {
132         prop_startup();
133
134         /* Send client message telling the OB process to:
135          * remote_control = 1 -> reconfigure 
136          * remote_control = 2 -> restart */
137         PROP_MSG(RootWindow(ob_display, ob_screen),
138                  ob_control, remote_control, 0, 0, 0);
139         XCloseDisplay(ob_display);
140         exit(EXIT_SUCCESS);
141     }
142
143     ob_main_loop = ob_main_loop_new(ob_display);
144
145     /* set up signal handler */
146     ob_main_loop_signal_add(ob_main_loop, SIGUSR1, signal_handler, NULL, NULL);
147     ob_main_loop_signal_add(ob_main_loop, SIGUSR2, signal_handler, NULL, NULL);
148     ob_main_loop_signal_add(ob_main_loop, SIGTERM, signal_handler, NULL, NULL);
149     ob_main_loop_signal_add(ob_main_loop, SIGINT, signal_handler, NULL, NULL);
150     ob_main_loop_signal_add(ob_main_loop, SIGHUP, signal_handler, NULL, NULL);
151     ob_main_loop_signal_add(ob_main_loop, SIGPIPE, signal_handler, NULL, NULL);
152     ob_main_loop_signal_add(ob_main_loop, SIGCHLD, signal_handler, NULL, NULL);
153
154     ob_screen = DefaultScreen(ob_display);
155
156     ob_rr_inst = RrInstanceNew(ob_display, ob_screen);
157     if (ob_rr_inst == NULL)
158         ob_exit_with_error("Failed to initialize the render library.");
159
160     XSynchronize(ob_display, xsync);
161
162     /* check for locale support */
163     if (!XSupportsLocale())
164         g_warning("X server does not support locale.");
165     if (!XSetLocaleModifiers(""))
166         g_warning("Cannot set locale modifiers for the X server.");
167
168     /* set our error handler */
169     XSetErrorHandler(xerror_handler);
170
171     /* set the DISPLAY environment variable for any lauched children, to the
172        display we're using, so they open in the right place. */
173     putenv(g_strdup_printf("DISPLAY=%s", DisplayString(ob_display)));
174
175     /* create available cursors */
176     cursors[OB_CURSOR_NONE] = None;
177     cursors[OB_CURSOR_POINTER] =
178         XCreateFontCursor(ob_display, XC_left_ptr);
179     cursors[OB_CURSOR_BUSY] =
180         XCreateFontCursor(ob_display, XC_watch);
181     cursors[OB_CURSOR_MOVE] =
182         XCreateFontCursor(ob_display, XC_fleur);
183     cursors[OB_CURSOR_NORTH] =
184         XCreateFontCursor(ob_display, XC_top_side);
185     cursors[OB_CURSOR_NORTHEAST] =
186         XCreateFontCursor(ob_display, XC_top_right_corner);
187     cursors[OB_CURSOR_EAST] =
188         XCreateFontCursor(ob_display, XC_right_side);
189     cursors[OB_CURSOR_SOUTHEAST] =
190         XCreateFontCursor(ob_display, XC_bottom_right_corner);
191     cursors[OB_CURSOR_SOUTH] =
192         XCreateFontCursor(ob_display, XC_bottom_side);
193     cursors[OB_CURSOR_SOUTHWEST] =
194         XCreateFontCursor(ob_display, XC_bottom_left_corner);
195     cursors[OB_CURSOR_WEST] =
196         XCreateFontCursor(ob_display, XC_left_side);
197     cursors[OB_CURSOR_NORTHWEST] =
198         XCreateFontCursor(ob_display, XC_top_left_corner);
199
200     /* create available keycodes */
201     keys[OB_KEY_RETURN] =
202         XKeysymToKeycode(ob_display, XStringToKeysym("Return"));
203     keys[OB_KEY_ESCAPE] =
204         XKeysymToKeycode(ob_display, XStringToKeysym("Escape"));
205     keys[OB_KEY_LEFT] =
206         XKeysymToKeycode(ob_display, XStringToKeysym("Left"));
207     keys[OB_KEY_RIGHT] =
208         XKeysymToKeycode(ob_display, XStringToKeysym("Right"));
209     keys[OB_KEY_UP] =
210         XKeysymToKeycode(ob_display, XStringToKeysym("Up"));
211     keys[OB_KEY_DOWN] =
212         XKeysymToKeycode(ob_display, XStringToKeysym("Down"));
213
214     prop_startup(); /* get atoms values for the display */
215     extensions_query_all(); /* find which extensions are present */
216
217     if (screen_annex()) { /* it will be ours! */
218         do {
219             {
220                 ObParseInst *i;
221                 xmlDocPtr doc;
222                 xmlNodePtr node;
223
224                 /* startup the parsing so everything can register sections
225                    of the rc */
226                 i = parse_startup();
227
228                 config_startup(i);
229                 /* parse/load user options */
230                 if (parse_load_rc(&doc, &node))
231                     parse_tree(i, doc, node->xmlChildrenNode);
232                 /* we're done with parsing now, kill it */
233                 parse_close(doc);
234                 parse_shutdown(i);
235             }
236
237             /* load the theme specified in the rc file */
238             {
239                 RrTheme *theme;
240                 if ((theme = RrThemeNew(ob_rr_inst, config_theme,
241                                         config_font_activewindow,
242                                         config_font_inactivewindow,
243                                         config_font_menutitle,
244                                         config_font_menuitem)))
245                 {
246                     RrThemeFree(ob_rr_theme);
247                     ob_rr_theme = theme;
248                 }
249                 if (ob_rr_theme == NULL)
250                     ob_exit_with_error("Unable to load a theme.");
251             }
252
253             if (reconfigure) {
254                 GList *it;
255
256                 /* update all existing windows for the new theme */
257                 for (it = client_list; it; it = g_list_next(it)) {
258                     ObClient *c = it->data;
259                     frame_adjust_theme(c->frame);
260                 }
261             }
262             event_startup(reconfigure);
263             /* focus_backup is used for stacking, so this needs to come before
264                anything that calls stacking_add */
265             focus_startup(reconfigure);
266             window_startup(reconfigure);
267             sn_startup(reconfigure);
268             screen_startup(reconfigure);
269             grab_startup(reconfigure);
270             group_startup(reconfigure);
271             client_startup(reconfigure);
272             dock_startup(reconfigure);
273             moveresize_startup(reconfigure);
274             keyboard_startup(reconfigure);
275             mouse_startup(reconfigure);
276             menu_startup(reconfigure);
277
278             if (!reconfigure) {
279                 /* get all the existing windows */
280                 client_manage_all();
281                 focus_fallback(OB_FOCUS_FALLBACK_NOFOCUS);
282             } else {
283                 GList *it;
284
285                 /* redecorate all existing windows */
286                 for (it = client_list; it; it = g_list_next(it)) {
287                     ObClient *c = it->data;
288                     /* the new config can change the window's decorations */
289                     client_setup_decor_and_functions(c);
290                     /* redraw the frames */
291                     frame_adjust_area(c->frame, TRUE, TRUE, FALSE);
292                 }
293             }
294
295             reconfigure = FALSE;
296
297             state = OB_STATE_RUNNING;
298             ob_main_loop_run(ob_main_loop);
299             state = OB_STATE_EXITING;
300
301             if (!reconfigure) {
302                 dock_remove_all();
303                 client_unmanage_all();
304             }
305
306             menu_shutdown(reconfigure);
307             mouse_shutdown(reconfigure);
308             keyboard_shutdown(reconfigure);
309             moveresize_shutdown(reconfigure);
310             dock_shutdown(reconfigure);
311             client_shutdown(reconfigure);
312             group_shutdown(reconfigure);
313             grab_shutdown(reconfigure);
314             screen_shutdown(reconfigure);
315             focus_shutdown(reconfigure);
316             sn_shutdown(reconfigure);
317             window_shutdown(reconfigure);
318             event_shutdown(reconfigure);
319             config_shutdown();
320         } while (reconfigure);
321     }
322
323     XSync(ob_display, FALSE);
324
325     RrThemeFree(ob_rr_theme);
326     RrInstanceFree(ob_rr_inst);
327
328     session_shutdown(being_replaced);
329
330     XCloseDisplay(ob_display);
331
332     parse_paths_shutdown();
333
334     if (restart) {
335         if (restart_path != NULL) {
336             gint argcp;
337             gchar **argvp;
338             GError *err = NULL;
339
340             /* run other window manager */
341             if (g_shell_parse_argv(restart_path, &argcp, &argvp, &err)) {
342                 execvp(argvp[0], argvp);
343                 g_strfreev(argvp);
344             } else {
345                 g_warning("failed to execute '%s': %s", restart_path,
346                           err->message);
347                 g_error_free(err);
348             }
349         }
350
351         /* re-run me */
352         execvp(argv[0], argv); /* try how we were run */
353         execlp(argv[0], g_path_get_basename(argv[0]),
354                (char *)NULL); /* last resort */
355     }
356      
357     return exitcode;
358 }
359
360 static void signal_handler(gint signal, gpointer data)
361 {
362     switch (signal) {
363     case SIGUSR1:
364         ob_debug("Caught signal %d. Restarting.\n", signal);
365         ob_restart();
366         break;
367     case SIGUSR2:
368         ob_debug("Caught signal %d. Reconfiguring.\n", signal);
369         ob_reconfigure(); 
370         break;
371     case SIGCHLD:
372         /* reap children */
373         while (waitpid(-1, NULL, WNOHANG) > 0);
374         break;
375     default:
376         ob_debug("Caught signal %d. Exiting.\n", signal);
377         /* TERM and INT return a 0 code */
378         ob_exit(!(signal == SIGTERM || signal == SIGINT));
379     }
380 }
381
382 static void print_version()
383 {
384     g_print("Openbox %s\n", PACKAGE_VERSION);
385     g_print("Copyright (c) 2006 Mikael Magnusson\n");
386     g_print("Copyright (c) 2003 Ben Jansens\n\n");
387     g_print("This program comes with ABSOLUTELY NO WARRANTY.\n");
388     g_print("This is free software, and you are welcome to redistribute it\n");
389     g_print("under certain conditions. See the file COPYING for details.\n\n");
390 }
391
392 static void print_help()
393 {
394     g_print("Syntax: openbox [options]\n\n");
395     g_print("Options:\n\n");
396     g_print("  --reconfigure       Tell the currently running instance of "
397             "Openbox to\n"
398             "                      reconfigure (and then exit immediately)\n");
399 #ifdef USE_SM
400     g_print("  --sm-disable        Disable connection to session manager\n");
401     g_print("  --sm-client-id ID   Specify session management ID\n");
402     g_print("  --sm-save-file FILE Specify file to load a saved session"
403             "from\n");
404 #endif
405     g_print("  --replace           Replace the currently running window "
406             "manager\n");
407     g_print("  --help              Display this help and exit\n");
408     g_print("  --version           Display the version and exit\n");
409     g_print("  --sync              Run in synchronous mode (this is slow and "
410             "meant for\n"
411             "                      debugging X routines)\n");
412     g_print("  --debug             Display debugging output\n");
413     g_print("\nPlease report bugs at %s\n\n", PACKAGE_BUGREPORT);
414 }
415
416 static void parse_args(gint argc, gchar **argv)
417 {
418     gint i;
419
420     for (i = 1; i < argc; ++i) {
421         if (!strcmp(argv[i], "--version")) {
422             print_version();
423             exit(0);
424         } else if (!strcmp(argv[i], "--help")) {
425             print_help();
426             exit(0);
427         } else if (!strcmp(argv[i], "--g-fatal-warnings")) {
428             g_log_set_always_fatal(G_LOG_LEVEL_CRITICAL);
429         } else if (!strcmp(argv[i], "--replace")) {
430             ob_replace_wm = TRUE;
431         } else if (!strcmp(argv[i], "--sync")) {
432             xsync = TRUE;
433         } else if (!strcmp(argv[i], "--debug")) {
434             ob_debug_show_output(TRUE);
435         } else if (!strcmp(argv[i], "--reconfigure")) {
436             remote_control = 1;
437         } else if (!strcmp(argv[i], "--restart")) {
438             remote_control = 2;
439         }
440     }
441 }
442
443 void ob_exit_with_error(gchar *msg)
444 {
445     g_critical(msg);
446     session_shutdown(TRUE);
447     exit(EXIT_FAILURE);
448 }
449
450 void ob_restart_other(const gchar *path)
451 {
452     restart_path = g_strdup(path);
453     ob_restart();
454 }
455
456 void ob_restart()
457 {
458     restart = TRUE;
459     ob_exit(0);
460 }
461
462 void ob_reconfigure()
463 {
464     reconfigure = TRUE;
465     ob_exit(0);
466 }
467
468 void ob_exit(gint code)
469 {
470     exitcode = code;
471     ob_main_loop_exit(ob_main_loop);
472 }
473
474 void ob_exit_replace()
475 {
476     exitcode = 0;
477     being_replaced = TRUE;
478     ob_main_loop_exit(ob_main_loop);
479 }
480
481 Cursor ob_cursor(ObCursor cursor)
482 {
483     g_assert(cursor < OB_NUM_CURSORS);
484     return cursors[cursor];
485 }
486
487 KeyCode ob_keycode(ObKey key)
488 {
489     g_assert(key < OB_NUM_KEYS);
490     return keys[key];
491 }
492
493 ObState ob_state()
494 {
495     return state;
496 }