move focus cycling into its own file
[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-2007   Dana 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 "modkeys.h"
25 #include "event.h"
26 #include "menu.h"
27 #include "client.h"
28 #include "xerror.h"
29 #include "prop.h"
30 #include "screen.h"
31 #include "startupnotify.h"
32 #include "focus.h"
33 #include "focus_cycle.h"
34 #include "moveresize.h"
35 #include "frame.h"
36 #include "keyboard.h"
37 #include "mouse.h"
38 #include "extensions.h"
39 #include "menuframe.h"
40 #include "grab.h"
41 #include "group.h"
42 #include "propwin.h"
43 #include "config.h"
44 #include "mainloop.h"
45 #include "gettext.h"
46 #include "parser/parse.h"
47 #include "render/render.h"
48 #include "render/theme.h"
49
50 #ifdef HAVE_FCNTL_H
51 #  include <fcntl.h>
52 #endif
53 #ifdef HAVE_SIGNAL_H
54 #  include <signal.h>
55 #endif
56 #ifdef HAVE_STDLIB_H
57 #  include <stdlib.h>
58 #endif
59 #ifdef HAVE_LOCALE_H
60 #  include <locale.h>
61 #endif
62 #ifdef HAVE_SYS_STAT_H
63 #  include <sys/stat.h>
64 #  include <sys/types.h>
65 #endif
66 #ifdef HAVE_SYS_WAIT_H
67 #  include <sys/types.h>
68 #  include <sys/wait.h>
69 #endif
70 #ifdef HAVE_UNISTD_H
71 #  include <unistd.h>
72 #endif
73 #include <errno.h>
74
75 #include <X11/cursorfont.h>
76 #if USE_XCURSOR
77 #include <X11/Xcursor/Xcursor.h>
78 #endif
79
80 #include <X11/Xlib.h>
81 #include <X11/keysym.h>
82
83
84 RrInstance *ob_rr_inst;
85 RrTheme    *ob_rr_theme;
86 ObMainLoop *ob_main_loop;
87 Display    *ob_display;
88 gint        ob_screen;
89 gboolean    ob_replace_wm = FALSE;
90 gboolean    ob_sm_use = TRUE;
91 gchar      *ob_sm_id = NULL;
92 gchar      *ob_sm_save_file = NULL;
93 gboolean    ob_debug_xinerama = FALSE;
94
95 static ObState   state;
96 static gboolean  xsync = FALSE;
97 static gboolean  reconfigure = FALSE;
98 static gboolean  restart = FALSE;
99 static gchar    *restart_path = NULL;
100 static Cursor    cursors[OB_NUM_CURSORS];
101 static KeyCode   keys[OB_NUM_KEYS];
102 static gint      exitcode = 0;
103 static guint     remote_control = 0;
104 static gboolean  being_replaced = FALSE;
105
106 static void signal_handler(gint signal, gpointer data);
107 static void remove_args(gint *argc, gchar **argv, gint index, gint num);
108 static void parse_env();
109 static void parse_args(gint *argc, gchar **argv);
110 static Cursor load_cursor(const gchar *name, guint fontval);
111
112 gint main(gint argc, gchar **argv)
113 {
114     gchar *program_name;
115
116     state = OB_STATE_STARTING;
117
118     /* initialize the locale */
119     if (!setlocale(LC_ALL, ""))
120         g_message("Couldn't set locale from environment.");
121     bindtextdomain(PACKAGE_NAME, LOCALEDIR);
122     bind_textdomain_codeset(PACKAGE_NAME, "UTF-8");
123     textdomain(PACKAGE_NAME);
124
125     if (chdir(g_get_home_dir()) == -1)
126         g_message(_("Unable to change to home directory '%s': %s"),
127                   g_get_home_dir(), g_strerror(errno));
128      
129     /* parse the command line args, which can change the argv[0] */
130     parse_args(&argc, argv);
131     /* parse the environment variables */
132     parse_env();
133
134     program_name = g_path_get_basename(argv[0]);
135     g_set_prgname(program_name);
136
137     if (!remote_control) {
138         parse_paths_startup();
139
140         session_startup(argc, argv);
141     }
142
143
144     ob_display = XOpenDisplay(NULL);
145     if (ob_display == NULL)
146         ob_exit_with_error(_("Failed to open the display from the DISPLAY environment variable."));
147     if (fcntl(ConnectionNumber(ob_display), F_SETFD, 1) == -1)
148         ob_exit_with_error("Failed to set display as close-on-exec");
149
150     if (remote_control) {
151         prop_startup();
152
153         /* Send client message telling the OB process to:
154          * remote_control = 1 -> reconfigure 
155          * remote_control = 2 -> restart */
156         PROP_MSG(RootWindow(ob_display, ob_screen),
157                  ob_control, remote_control, 0, 0, 0);
158         XCloseDisplay(ob_display);
159         exit(EXIT_SUCCESS);
160     }
161
162     ob_main_loop = ob_main_loop_new(ob_display);
163
164     /* set up signal handler */
165     ob_main_loop_signal_add(ob_main_loop, SIGUSR1, signal_handler, NULL, NULL);
166     ob_main_loop_signal_add(ob_main_loop, SIGUSR2, signal_handler, NULL, NULL);
167     ob_main_loop_signal_add(ob_main_loop, SIGTERM, signal_handler, NULL, NULL);
168     ob_main_loop_signal_add(ob_main_loop, SIGINT, signal_handler, NULL, NULL);
169     ob_main_loop_signal_add(ob_main_loop, SIGHUP, signal_handler, NULL, NULL);
170     ob_main_loop_signal_add(ob_main_loop, SIGPIPE, signal_handler, NULL, NULL);
171     ob_main_loop_signal_add(ob_main_loop, SIGCHLD, signal_handler, NULL, NULL);
172
173     ob_screen = DefaultScreen(ob_display);
174
175     ob_rr_inst = RrInstanceNew(ob_display, ob_screen);
176     if (ob_rr_inst == NULL)
177         ob_exit_with_error(_("Failed to initialize the render library."));
178
179     XSynchronize(ob_display, xsync);
180
181     /* check for locale support */
182     if (!XSupportsLocale())
183         g_message(_("X server does not support locale."));
184     if (!XSetLocaleModifiers(""))
185         g_message(_("Cannot set locale modifiers for the X server."));
186
187     /* set our error handler */
188     XSetErrorHandler(xerror_handler);
189
190     /* set the DISPLAY environment variable for any lauched children, to the
191        display we're using, so they open in the right place. */
192     putenv(g_strdup_printf("DISPLAY=%s", DisplayString(ob_display)));
193
194     /* create available cursors */
195     cursors[OB_CURSOR_NONE] = None;
196     cursors[OB_CURSOR_POINTER] = load_cursor("left_ptr", XC_left_ptr);
197     cursors[OB_CURSOR_BUSY] = load_cursor("left_ptr_watch", XC_watch);
198     cursors[OB_CURSOR_MOVE] = load_cursor("fleur", XC_fleur);
199     cursors[OB_CURSOR_NORTH] = load_cursor("top_side", XC_top_side);
200     cursors[OB_CURSOR_NORTHEAST] = load_cursor("top_right_corner",
201                                                XC_top_right_corner);
202     cursors[OB_CURSOR_EAST] = load_cursor("right_side", XC_right_side);
203     cursors[OB_CURSOR_SOUTHEAST] = load_cursor("bottom_right_corner",
204                                                XC_bottom_right_corner);
205     cursors[OB_CURSOR_SOUTH] = load_cursor("bottom_side", XC_bottom_side);
206     cursors[OB_CURSOR_SOUTHWEST] = load_cursor("bottom_left_corner",
207                                                XC_bottom_left_corner);
208     cursors[OB_CURSOR_WEST] = load_cursor("left_side", XC_left_side);
209     cursors[OB_CURSOR_NORTHWEST] = load_cursor("top_left_corner",
210                                                XC_top_left_corner);
211
212
213     prop_startup(); /* get atoms values for the display */
214     extensions_query_all(); /* find which extensions are present */
215
216     if (screen_annex()) { /* it will be ours! */
217         do {
218             modkeys_startup(reconfigure);
219
220             /* get the keycodes for keys we use */
221             keys[OB_KEY_RETURN] = modkeys_sym_to_code(XK_Return);
222             keys[OB_KEY_ESCAPE] = modkeys_sym_to_code(XK_Escape);
223             keys[OB_KEY_LEFT] = modkeys_sym_to_code(XK_Left);
224             keys[OB_KEY_RIGHT] = modkeys_sym_to_code(XK_Right);
225             keys[OB_KEY_UP] = modkeys_sym_to_code(XK_Up);
226             keys[OB_KEY_DOWN] = modkeys_sym_to_code(XK_Down);
227
228             {
229                 ObParseInst *i;
230                 xmlDocPtr doc;
231                 xmlNodePtr node;
232
233                 /* startup the parsing so everything can register sections
234                    of the rc */
235                 i = parse_startup();
236
237                 /* start up config which sets up with the parser */
238                 config_startup(i);
239
240                 /* parse/load user options */
241                 if (parse_load_rc(NULL, &doc, &node)) {
242                     parse_tree(i, doc, node->xmlChildrenNode);
243                     parse_close(doc);
244                 } else
245                     g_message(_("Unable to find a valid config file, using some simple defaults"));
246
247 /*
248                 if (config_type != NULL)
249                     PROP_SETS(RootWindow(ob_display, ob_screen),
250                               ob_config, config_type);
251 */
252
253                 /* we're done with parsing now, kill it */
254                 parse_shutdown(i);
255             }
256
257             /* load the theme specified in the rc file */
258             {
259                 RrTheme *theme;
260                 if ((theme = RrThemeNew(ob_rr_inst, config_theme,
261                                         config_font_activewindow,
262                                         config_font_inactivewindow,
263                                         config_font_menutitle,
264                                         config_font_menuitem,
265                                         config_font_osd)))
266                 {
267                     RrThemeFree(ob_rr_theme);
268                     ob_rr_theme = theme;
269                 }
270                 if (ob_rr_theme == NULL)
271                     ob_exit_with_error(_("Unable to load a theme."));
272             }
273
274             if (reconfigure) {
275                 GList *it;
276
277                 /* update all existing windows for the new theme */
278                 for (it = client_list; it; it = g_list_next(it)) {
279                     ObClient *c = it->data;
280                     frame_adjust_theme(c->frame);
281                 }
282             }
283             event_startup(reconfigure);
284             /* focus_backup is used for stacking, so this needs to come before
285                anything that calls stacking_add */
286             focus_startup(reconfigure);
287             focus_cycle_startup(reconfigure);
288             window_startup(reconfigure);
289             sn_startup(reconfigure);
290             screen_startup(reconfigure);
291             grab_startup(reconfigure);
292             propwin_startup(reconfigure);
293             group_startup(reconfigure);
294             client_startup(reconfigure);
295             dock_startup(reconfigure);
296             moveresize_startup(reconfigure);
297             keyboard_startup(reconfigure);
298             mouse_startup(reconfigure);
299             menu_startup(reconfigure);
300             menu_frame_startup(reconfigure);
301
302             if (!reconfigure) {
303                 guint32 xid;
304                 ObWindow *w;
305
306                 /* get all the existing windows */
307                 client_manage_all();
308                 focus_nothing();
309
310                 /* focus what was focused if a wm was already running */
311                 if (PROP_GET32(RootWindow(ob_display, ob_screen),
312                                net_active_window, window, &xid) &&
313                     (w = g_hash_table_lookup(window_map, &xid)) &&
314                     WINDOW_IS_CLIENT(w))
315                 {
316                     client_focus(WINDOW_AS_CLIENT(w));
317                 }
318             } else {
319                 GList *it;
320
321                 /* redecorate all existing windows */
322                 for (it = client_list; it; it = g_list_next(it)) {
323                     ObClient *c = it->data;
324                     /* the new config can change the window's decorations */
325                     client_setup_decor_and_functions(c);
326                     /* redraw the frames */
327                     frame_adjust_area(c->frame, TRUE, TRUE, FALSE);
328                 }
329             }
330
331             reconfigure = FALSE;
332
333             state = OB_STATE_RUNNING;
334             ob_main_loop_run(ob_main_loop);
335             state = OB_STATE_EXITING;
336
337             if (!reconfigure) {
338                 dock_remove_all();
339                 client_unmanage_all();
340             }
341
342             menu_frame_shutdown(reconfigure);
343             menu_shutdown(reconfigure);
344             mouse_shutdown(reconfigure);
345             keyboard_shutdown(reconfigure);
346             moveresize_shutdown(reconfigure);
347             dock_shutdown(reconfigure);
348             client_shutdown(reconfigure);
349             group_shutdown(reconfigure);
350             propwin_shutdown(reconfigure);
351             grab_shutdown(reconfigure);
352             screen_shutdown(reconfigure);
353             focus_cycle_shutdown(reconfigure);
354             focus_shutdown(reconfigure);
355             sn_shutdown(reconfigure);
356             window_shutdown(reconfigure);
357             event_shutdown(reconfigure);
358             config_shutdown();
359             modkeys_shutdown(reconfigure);
360         } while (reconfigure);
361     }
362
363     XSync(ob_display, FALSE);
364
365     RrThemeFree(ob_rr_theme);
366     RrInstanceFree(ob_rr_inst);
367
368     session_shutdown(being_replaced);
369
370     XCloseDisplay(ob_display);
371
372     parse_paths_shutdown();
373
374     if (restart) {
375         if (restart_path != NULL) {
376             gint argcp;
377             gchar **argvp;
378             GError *err = NULL;
379
380             /* run other window manager */
381             if (g_shell_parse_argv(restart_path, &argcp, &argvp, &err)) {
382                 execvp(argvp[0], argvp);
383                 g_strfreev(argvp);
384             } else {
385                 g_message(
386                     _("Restart failed to execute new executable '%s': %s"),
387                     restart_path, err->message);
388                 g_error_free(err);
389             }
390         }
391
392         /* we remove the session arguments from argv, so put them back */
393         if (ob_sm_save_file != NULL || ob_sm_id != NULL) {
394             gchar **nargv;
395             gint i, l;
396
397             l = argc +
398                 (ob_sm_save_file != NULL ? 2 : 0) +
399                 (ob_sm_id != NULL ? 2 : 0);
400             nargv = g_new0(gchar*, l+1);
401             for (i = 0; i < argc; ++i)
402                 nargv[i] = argv[i];
403
404             if (ob_sm_save_file != NULL) {
405                 nargv[i++] = g_strdup("--sm-save-file");
406                 nargv[i++] = ob_sm_save_file;
407             }
408             if (ob_sm_id != NULL) {
409                 nargv[i++] = g_strdup("--sm-client-id");
410                 nargv[i++] = ob_sm_id;
411             }
412             g_assert(i == l);
413             argv = nargv;
414         }
415
416         /* re-run me */
417         execvp(argv[0], argv); /* try how we were run */
418         execlp(argv[0], program_name, (gchar*)NULL); /* last resort */
419     }
420
421     /* free stuff passed in from the command line or environment */
422     g_free(ob_sm_save_file);
423     g_free(ob_sm_id);
424     g_free(program_name);
425      
426     return exitcode;
427 }
428
429 static void signal_handler(gint signal, gpointer data)
430 {
431     switch (signal) {
432     case SIGUSR1:
433         ob_debug("Caught signal %d. Restarting.\n", signal);
434         ob_restart();
435         break;
436     case SIGUSR2:
437         ob_debug("Caught signal %d. Reconfiguring.\n", signal);
438         ob_reconfigure(); 
439         break;
440     case SIGCHLD:
441         /* reap children */
442         while (waitpid(-1, NULL, WNOHANG) > 0);
443         break;
444     default:
445         ob_debug("Caught signal %d. Exiting.\n", signal);
446         /* TERM and INT return a 0 code */
447         ob_exit(!(signal == SIGTERM || signal == SIGINT));
448     }
449 }
450
451 static void print_version()
452 {
453     g_print("Openbox %s\n", PACKAGE_VERSION);
454     g_print(_("Copyright (c)"));
455     g_print(" 2007        Mikael Magnusson\n");
456     g_print(_("Copyright (c)"));
457     g_print(" 2003-2007   Dana Jansens\n\n");
458     g_print("This program comes with ABSOLUTELY NO WARRANTY.\n");
459     g_print("This is free software, and you are welcome to redistribute it\n");
460     g_print("under certain conditions. See the file COPYING for details.\n\n");
461 }
462
463 static void print_help()
464 {
465     g_print(_("Syntax: openbox [options]\n"));
466     g_print(_("\nOptions:\n"));
467     g_print(_("  --help              Display this help and exit\n"));
468     g_print(_("  --version           Display the version and exit\n"));
469     g_print(_("  --replace           Replace the currently running window manager\n"));
470     g_print(_("  --sm-disable        Disable connection to the session manager\n"));
471     g_print(_("\nPassing messages to a running Openbox instance:\n"));
472     g_print(_("  --reconfigure       Reload Openbox's configuration\n"));
473     g_print(_("\nDebugging options:\n"));
474     g_print(_("  --sync              Run in synchronous mode\n"));
475     g_print(_("  --debug             Display debugging output\n"));
476     g_print(_("  --debug-focus       Display debugging output for focus handling\n"));
477     g_print(_("  --debug-xinerama    Split the display into fake xinerama screens\n"));
478     g_print(_("\nPlease report bugs at %s\n"), PACKAGE_BUGREPORT);
479 }
480
481 static void remove_args(gint *argc, gchar **argv, gint index, gint num)
482 {
483     gint i;
484
485     for (i = index; i < *argc - num; ++i)
486         argv[i] = argv[i+num];
487     for (; i < *argc; ++i)
488         argv[i] = NULL;
489     *argc -= num;
490 }
491
492 static void parse_env()
493 {
494     /* unset this so we don't pass it on unknowingly */
495     unsetenv("DESKTOP_STARTUP_ID");
496 }
497
498 static void parse_args(gint *argc, gchar **argv)
499 {
500     gint i;
501
502     for (i = 1; i < *argc; ++i) {
503         if (!strcmp(argv[i], "--version")) {
504             print_version();
505             exit(0);
506         }
507         else if (!strcmp(argv[i], "--help")) {
508             print_help();
509             exit(0);
510         }
511         else if (!strcmp(argv[i], "--g-fatal-warnings")) {
512             g_log_set_always_fatal(G_LOG_LEVEL_CRITICAL);
513         }
514         else if (!strcmp(argv[i], "--replace")) {
515             ob_replace_wm = TRUE;
516             remove_args(argc, argv, i, 1);
517             --i; /* this arg was removed so go back */
518         }
519         else if (!strcmp(argv[i], "--sync")) {
520             xsync = TRUE;
521         }
522         else if (!strcmp(argv[i], "--debug")) {
523             ob_debug_show_output(TRUE);
524             ob_debug_enable(OB_DEBUG_SM, TRUE);
525             ob_debug_enable(OB_DEBUG_APP_BUGS, TRUE);
526         }
527         else if (!strcmp(argv[i], "--debug-focus")) {
528             ob_debug_show_output(TRUE);
529             ob_debug_enable(OB_DEBUG_SM, TRUE);
530             ob_debug_enable(OB_DEBUG_APP_BUGS, TRUE);
531             ob_debug_enable(OB_DEBUG_FOCUS, TRUE);
532         }
533         else if (!strcmp(argv[i], "--debug-xinerama")) {
534             ob_debug_xinerama = TRUE;
535         }
536         else if (!strcmp(argv[i], "--reconfigure")) {
537             remote_control = 1;
538 /* don't make this do anything if it's not in --help ..
539         } else if (!strcmp(argv[i], "--restart")) {
540             remote_control = 2;
541 */
542         }
543         else if (!strcmp(argv[i], "--sm-save-file")) {
544             if (i == *argc - 1) /* no args left */
545                 /* not translated cuz it's sekret */
546                 g_printerr("--sm-save-file requires an argument\n");
547             else {
548                 ob_sm_save_file = g_strdup(argv[i+1]);
549                 remove_args(argc, argv, i, 2);
550                 --i; /* this arg was removed so go back */
551                 ob_debug_type(OB_DEBUG_SM, "--sm-save-file %s\n",
552                               ob_sm_save_file);
553             }
554         }
555         else if (!strcmp(argv[i], "--sm-client-id")) {
556             if (i == *argc - 1) /* no args left */
557                 /* not translated cuz it's sekret */
558                 g_printerr("--sm-client-id requires an argument\n");
559             else {
560                 ob_sm_id = g_strdup(argv[i+1]);
561                 remove_args(argc, argv, i, 2);
562                 --i; /* this arg was removed so go back */
563                 ob_debug_type(OB_DEBUG_SM, "--sm-client-id %s\n", ob_sm_id);
564             }
565         }
566         else if (!strcmp(argv[i], "--sm-disable")) {
567             ob_sm_use = FALSE;
568         }
569         else {
570             /* this is a memleak.. oh well.. heh */
571             gchar *err = g_strdup_printf
572                 (_("Invalid command line argument '%s'\n"), argv[i]);
573             ob_exit_with_error(err);
574         }
575     }
576 }
577
578 static Cursor load_cursor(const gchar *name, guint fontval)
579 {
580     Cursor c = None;
581
582 #if USE_XCURSOR
583     c = XcursorLibraryLoadCursor(ob_display, name);
584 #endif
585     if (c == None)
586         c = XCreateFontCursor(ob_display, fontval);
587     return c;
588 }
589
590 void ob_exit_with_error(const gchar *msg)
591 {
592     g_message(msg);
593     session_shutdown(TRUE);
594     exit(EXIT_FAILURE);
595 }
596
597 void ob_restart_other(const gchar *path)
598 {
599     restart_path = g_strdup(path);
600     ob_restart();
601 }
602
603 void ob_restart()
604 {
605     restart = TRUE;
606     ob_exit(0);
607 }
608
609 void ob_reconfigure()
610 {
611     reconfigure = TRUE;
612     ob_exit(0);
613 }
614
615 void ob_exit(gint code)
616 {
617     exitcode = code;
618     ob_main_loop_exit(ob_main_loop);
619 }
620
621 void ob_exit_replace()
622 {
623     exitcode = 0;
624     being_replaced = TRUE;
625     ob_main_loop_exit(ob_main_loop);
626 }
627
628 Cursor ob_cursor(ObCursor cursor)
629 {
630     g_assert(cursor < OB_NUM_CURSORS);
631     return cursors[cursor];
632 }
633
634 KeyCode ob_keycode(ObKey key)
635 {
636     g_assert(key < OB_NUM_KEYS);
637     return keys[key];
638 }
639
640 ObState ob_state()
641 {
642     return state;
643 }