remove the use of the BINARY define. kill a compiler warning.
[mikachu/openbox.git] / openbox / openbox.c
1 #include "openbox.h"
2 #include "dock.h"
3 #include "event.h"
4 #include "menu.h"
5 #include "client.h"
6 #include "dispatch.h"
7 #include "xerror.h"
8 #include "prop.h"
9 #include "startup.h"
10 #include "screen.h"
11 #include "focus.h"
12 #include "moveresize.h"
13 #include "frame.h"
14 #include "extensions.h"
15 #include "grab.h"
16 #include "plugin.h"
17 #include "timer.h"
18 #include "group.h"
19 #include "config.h"
20 #include "gettext.h"
21 #include "parser/parse.h"
22 #include "render/render.h"
23 #include "render/theme.h"
24
25 #ifdef HAVE_FCNTL_H
26 #  include <fcntl.h>
27 #endif
28 #ifdef HAVE_SIGNAL_H
29 #define __USE_UNIX98
30 #  include <signal.h>
31 #endif
32 #ifdef HAVE_STDLIB_H
33 #  include <stdlib.h>
34 #endif
35 #ifdef HAVE_LOCALE_H
36 #  include <locale.h>
37 #endif
38 #ifdef HAVE_UNISTD_H
39 #  include <unistd.h>
40 #endif
41 #ifdef HAVE_SYS_STAT_H
42 #  include <sys/stat.h>
43 #  include <sys/types.h>
44 #endif
45
46 #ifdef USE_SM
47 #include <X11/SM/SMlib.h>
48 #endif
49
50 #include <X11/cursorfont.h>
51
52 #ifdef USE_SM
53 gboolean    ob_sm_use = TRUE;
54 SmcConn     ob_sm_conn;
55 gchar      *ob_sm_id = NULL;
56 #endif
57
58 RrInstance *ob_rr_inst = NULL;
59 RrTheme    *ob_rr_theme = NULL;
60 Display    *ob_display = NULL;
61 int         ob_screen;
62 Window      ob_root;
63 State       ob_state;
64 gboolean    ob_shutdown = FALSE;
65 gboolean    ob_restart  = FALSE;
66 char       *ob_restart_path = NULL;
67 gboolean    ob_remote   = TRUE;
68 gboolean    ob_sync     = FALSE;
69 Cursors     ob_cursors;
70 char       *ob_rc_path  = NULL;
71
72 static void signal_handler(const ObEvent *e, void *data);
73 static void parse_args(int argc, char **argv);
74
75 static void sm_startup(int argc, char **argv);
76 static void sm_shutdown();
77
78 #ifdef USE_SM
79 static void sm_save_yourself(SmcConn conn, SmPointer data, int save_type,
80                              Bool shutdown, int interact_style, Bool fast);
81 static void sm_die(SmcConn conn, SmPointer data);
82 static void sm_save_complete(SmcConn conn, SmPointer data);
83 static void sm_shutdown_cancelled(SmcConn conn, SmPointer data);
84 #endif
85 static void exit_with_error(gchar *msg);
86
87 int main(int argc, char **argv)
88 {
89     struct sigaction action;
90     sigset_t sigset;
91     char *path;
92     xmlDocPtr doc;
93     xmlNodePtr node;
94
95     ob_state = State_Starting;
96
97     /* initialize the locale */
98     if (!setlocale(LC_ALL, ""))
99         g_warning("Couldn't set locale from environment.\n");
100     bindtextdomain(PACKAGE_NAME, LOCALEDIR);
101     bind_textdomain_codeset(PACKAGE_NAME, "UTF-8");
102     textdomain(PACKAGE_NAME);
103
104     /* start our event dispatcher and register for signals */
105     dispatch_startup();
106     dispatch_register(Event_Signal, signal_handler, NULL);
107
108     /* set up signal handler */
109     sigemptyset(&sigset);
110     action.sa_handler = dispatch_signal;
111     action.sa_mask = sigset;
112     action.sa_flags = SA_NOCLDSTOP | SA_NODEFER;
113     sigaction(SIGUSR1, &action, (struct sigaction *) NULL);
114     sigaction(SIGPIPE, &action, (struct sigaction *) NULL);
115 /*    sigaction(SIGSEGV, &action, (struct sigaction *) NULL);*/
116     sigaction(SIGFPE, &action, (struct sigaction *) NULL);
117     sigaction(SIGTERM, &action, (struct sigaction *) NULL);
118     sigaction(SIGINT, &action, (struct sigaction *) NULL);
119     sigaction(SIGHUP, &action, (struct sigaction *) NULL);
120
121     /* create the ~/.openbox dir */
122     path = g_build_filename(g_get_home_dir(), ".openbox", NULL);
123     mkdir(path, (S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP |
124                  S_IROTH | S_IWOTH | S_IXOTH));
125     g_free(path);
126     /* create the ~/.openbox/themes dir */
127     path = g_build_filename(g_get_home_dir(), ".openbox", "themes", NULL);
128     mkdir(path, (S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP |
129                  S_IROTH | S_IWOTH | S_IXOTH));
130     g_free(path);
131
132     g_set_prgname(argv[0]);
133      
134     /* parse out command line args */
135     parse_args(argc, argv);
136
137     ob_display = XOpenDisplay(NULL);
138     if (ob_display == NULL)
139         exit_with_error("Failed to open the display.");
140     if (fcntl(ConnectionNumber(ob_display), F_SETFD, 1) == -1)
141         exit_with_error("Failed to set display as close-on-exec.");
142
143     sm_startup(argc, argv);
144
145 #ifdef USE_LIBSN
146     ob_sn_display = sn_display_new(ob_display, NULL, NULL);
147 #endif
148
149     ob_screen = DefaultScreen(ob_display);
150     ob_root = RootWindow(ob_display, ob_screen);
151
152     ob_rr_inst = RrInstanceNew(ob_display, ob_screen);
153     if (ob_rr_inst == NULL)
154         exit_with_error("Failed to initialize the render library.");
155
156     /* XXX fork self onto other screens */
157      
158     XSynchronize(ob_display, ob_sync);
159
160     /* check for locale support */
161     if (!XSupportsLocale())
162         g_warning("X server does not support locale.");
163     if (!XSetLocaleModifiers(""))
164         g_warning("Cannot set locale modifiers for the X server.");
165
166     /* set our error handler */
167     XSetErrorHandler(xerror_handler);
168
169     /* set the DISPLAY environment variable for any lauched children, to the
170        display we're using, so they open in the right place. */
171     putenv(g_strdup_printf("DISPLAY=%s", DisplayString(ob_display)));
172
173     ob_cursors.ptr = XCreateFontCursor(ob_display, XC_left_ptr);
174     ob_cursors.busy = XCreateFontCursor(ob_display, XC_watch);
175     ob_cursors.move = XCreateFontCursor(ob_display, XC_fleur);
176     ob_cursors.tl = XCreateFontCursor(ob_display, XC_top_left_corner);
177     ob_cursors.tr = XCreateFontCursor(ob_display, XC_top_right_corner);
178     ob_cursors.bl = XCreateFontCursor(ob_display, XC_bottom_left_corner);
179     ob_cursors.br = XCreateFontCursor(ob_display, XC_bottom_right_corner);
180     ob_cursors.t = XCreateFontCursor(ob_display, XC_top_side);
181     ob_cursors.r = XCreateFontCursor(ob_display, XC_right_side);
182     ob_cursors.b = XCreateFontCursor(ob_display, XC_bottom_side);
183     ob_cursors.l = XCreateFontCursor(ob_display, XC_left_side);
184
185     prop_startup(); /* get atoms values for the display */
186     extensions_query_all(); /* find which extensions are present */
187
188     /* save stuff that we can use to restore state */
189     startup_save();
190
191     if (screen_annex()) { /* it will be ours! */
192         /* startup the parsing so everything can register sections of the rc */
193         parse_startup();
194
195         /* anything that is going to read data from the rc file needs to be 
196            in this group */
197         timer_startup();
198         event_startup();
199         grab_startup();
200         /* focus_backup is used for stacking, so this needs to come before
201            anything that calls stacking_add */
202         focus_startup();
203         window_startup();
204         plugin_startup();
205         /* load the plugins specified in the pluginrc */
206         plugin_loadall();
207
208         /* set up the kernel config shit */
209         config_startup();
210         menu_startup();
211         /* parse/load user options */
212         if (parse_load_rc(&doc, &node))
213             parse_tree(doc, node->xmlChildrenNode, NULL);
214         /* we're done with parsing now, kill it */
215         parse_shutdown();
216
217         /* load the theme specified in the rc file */
218         ob_rr_theme = RrThemeNew(ob_rr_inst, config_theme);
219         if (ob_rr_theme == NULL)
220             exit_with_error("Unable to load a theme.");
221
222         frame_startup();
223         moveresize_startup();
224         screen_startup();
225         group_startup();
226         client_startup();
227         dock_startup();
228
229         /* call startup for all the plugins */
230         plugin_startall();
231
232         /* get all the existing windows */
233         client_manage_all();
234
235         ob_state = State_Running;
236         while (!ob_shutdown)
237             event_loop();
238         ob_state = State_Exiting;
239
240         dock_remove_all();
241         client_unmanage_all();
242
243         plugin_shutdown(); /* calls all the plugins' shutdown functions */
244         dock_shutdown();
245         client_shutdown();
246         group_shutdown();
247         screen_shutdown();
248         focus_shutdown();
249         moveresize_shutdown();
250         frame_shutdown();
251         menu_shutdown();
252         window_shutdown();
253         grab_shutdown();
254         event_shutdown();
255         timer_shutdown();
256         config_shutdown();
257     }
258
259     dispatch_shutdown();
260
261     RrThemeFree(ob_rr_theme);
262     RrInstanceFree(ob_rr_inst);
263
264     sm_shutdown();
265
266     XCloseDisplay(ob_display);
267
268     if (ob_restart) {
269         if (ob_restart_path != NULL) {
270             int argcp;
271             char **argvp;
272             GError *err = NULL;
273
274             /* run other shit */
275             if (g_shell_parse_argv(ob_restart_path, &argcp, &argvp, &err)) {
276                 execvp(argvp[0], argvp);
277                 g_strfreev(argvp);
278             } else {
279                 g_warning("failed to execute '%s': %s", ob_restart_path,
280                           err->message);
281             }
282         }
283
284         /* re-run me */
285         execvp(argv[0], argv); /* try how we were run */
286     }
287      
288     return 0;
289 }
290
291 static void sm_startup(int argc, char **argv)
292 {
293 #ifdef USE_SM
294
295 #define SM_ERR_LEN 1024
296
297     SmcCallbacks cb;
298     char sm_err[SM_ERR_LEN];
299
300     cb.save_yourself.callback = sm_save_yourself;
301     cb.save_yourself.client_data = NULL;
302
303     cb.die.callback = sm_die;
304     cb.die.client_data = NULL;
305
306     cb.save_complete.callback = sm_save_complete;
307     cb.save_complete.client_data = NULL;
308
309     cb.shutdown_cancelled.callback = sm_shutdown_cancelled;
310     cb.shutdown_cancelled.client_data = NULL;
311
312     ob_sm_conn = SmcOpenConnection(NULL, NULL, 1, 0,
313                                    SmcSaveYourselfProcMask |
314                                    SmcDieProcMask |
315                                    SmcSaveCompleteProcMask |
316                                    SmcShutdownCancelledProcMask,
317                                    &cb, ob_sm_id, &ob_sm_id,
318                                    SM_ERR_LEN, sm_err);
319     if (ob_sm_conn == NULL)
320         g_warning("Failed to connect to session manager: %s", sm_err);
321     else {
322         SmPropValue val_prog;
323         SmPropValue val_uid;
324         SmPropValue val_hint; 
325         SmPropValue val_pri;
326         SmPropValue val_pid;
327         SmProp prop_cmd = { SmCloneCommand, SmLISTofARRAY8, 1, };
328         SmProp prop_res = { SmRestartCommand, SmLISTofARRAY8, };
329         SmProp prop_prog = { SmProgram, SmARRAY8, 1, };
330         SmProp prop_uid = { SmUserID, SmARRAY8, 1, };
331         SmProp prop_hint = { SmRestartStyleHint, SmCARD8, 1, };
332         SmProp prop_pid = { SmProcessID, SmARRAY8, 1, };
333         SmProp prop_pri = { "_GSM_Priority", SmCARD8, 1, };
334         SmProp *props[7];
335         gulong hint, pri;
336         gchar pid[32];
337         gint i, j;
338         gboolean has_id;
339
340         for (i = 1; i < argc - 1; ++i)
341             if (strcmp(argv[i], "--sm-client-id") == 0)
342                 break;
343         has_id = (i < argc - 1);
344
345         prop_cmd.vals = g_new(SmPropValue, (has_id ? argc-2 : argc));
346         prop_cmd.num_vals = (has_id ? argc-2 : argc);
347         for (i = 0, j = 0; i < argc; ++i, ++j) {
348             if (strcmp (argv[i], "--sm-client-id") == 0) {
349                 ++i, --j; /* skip the next as well, keep j where it is */
350             } else {
351                 prop_cmd.vals[j].value = argv[i];
352                 prop_cmd.vals[j].length = strlen(argv[i]);
353             }
354         }
355
356         prop_res.vals = g_new(SmPropValue, (has_id ? argc : argc+2));
357         prop_res.num_vals = (has_id ? argc : argc+2);
358         for (i = 0, j = 0; i < argc; ++i, ++j) { 
359             if (strcmp (argv[i], "--sm-client-id") == 0) {
360                 ++i, --j; /* skip the next as well, keep j where it is */
361             } else {
362                 prop_res.vals[j].value = argv[i];
363                 prop_res.vals[j].length = strlen(argv[i]);
364             }
365         }
366         prop_res.vals[j].value = "--sm-client-id";
367         prop_res.vals[j++].length = strlen("--sm-client-id");
368         prop_res.vals[j].value = ob_sm_id;
369         prop_res.vals[j++].length = strlen(ob_sm_id);
370
371         val_prog.value = argv[0];
372         val_prog.length = strlen(argv[0]);
373
374         val_uid.value = g_strdup(g_get_user_name());
375         val_uid.length = strlen(val_uid.value);
376
377         hint = SmRestartImmediately;
378         val_hint.value = &hint;
379         val_hint.length = 1;
380
381         sprintf(pid, "%ld", (long)getpid());
382         val_pid.value = pid;
383         val_pid.length = strlen(pid);
384
385         /* priority with gnome-session-manager, low to run before other apps */
386         pri = 20;
387         val_pri.value = &pri;
388         val_pri.length = 1;
389
390         prop_prog.vals = &val_prog;
391         prop_uid.vals = &val_uid;
392         prop_hint.vals = &val_hint;
393         prop_pid.vals = &val_pid;
394         prop_pri.vals = &val_pri;
395
396         props[0] = &prop_prog;
397         props[1] = &prop_cmd;
398         props[2] = &prop_res;
399         props[3] = &prop_uid;
400         props[4] = &prop_hint;
401         props[5] = &prop_pid;
402         props[6] = &prop_pri;
403
404         SmcSetProperties(ob_sm_conn, 7, props);
405
406         g_free(val_uid.value);
407         g_free(prop_cmd.vals);
408         g_free(prop_res.vals);
409
410         g_message("Connected to session manager with id %s", ob_sm_id);
411     }
412     g_free (ob_sm_id);
413 #endif
414 }
415
416 static void sm_shutdown()
417 {
418 #ifdef USE_SM
419     if (ob_sm_conn) {
420         SmPropValue val_hint;
421         SmProp prop_hint = { SmRestartStyleHint, SmCARD8, 1, };
422         SmProp *props[1];
423         gulong hint;
424
425         /* when we exit, we want to reset this to a more friendly state */
426         hint = SmRestartIfRunning;
427         val_hint.value = &hint;
428         val_hint.length = 1;
429
430         prop_hint.vals = &val_hint;
431
432         props[0] = &prop_hint;
433
434         SmcSetProperties(ob_sm_conn, 1, props);
435
436         SmcCloseConnection(ob_sm_conn, 0, NULL);
437     }
438 #endif
439 }
440
441 static void signal_handler(const ObEvent *e, void *data)
442 {
443     int s;
444
445     s = e->data.s.signal;
446     switch (s) {
447     case SIGUSR1:
448         fprintf(stderr, "Caught SIGUSR1 signal. Restarting.");
449         ob_shutdown = ob_restart = TRUE;
450         break;
451
452     case SIGHUP:
453     case SIGINT:
454     case SIGTERM:
455     case SIGPIPE:
456         fprintf(stderr, "Caught signal %d. Exiting.", s);
457         ob_shutdown = TRUE;
458         break;
459
460     case SIGFPE:
461     case SIGSEGV:
462         fprintf(stderr, "Caught signal %d. Aborting and dumping core.", s);
463         abort();
464     }
465 }
466
467 static void print_version()
468 {
469     g_print("Openbox %s\n\n", PACKAGE_VERSION);
470     g_print("This program comes with ABSOLUTELY NO WARRANTY.\n");
471     g_print("This is free software, and you are welcome to redistribute it\n");
472     g_print("under certain conditions. See the file COPYING for details.\n\n");
473 }
474
475 static void print_help()
476 {
477     print_version();
478     g_print("Syntax: openbox [options]\n\n");
479     g_print("Options:\n\n");
480     g_print("  --rc PATH          Specify the path to the rc file to use\n");
481 #ifdef USE_SM
482     g_print("  --sm-client-id ID  Specify session management ID\n");
483     g_print("  --sm-disable       Disable connection to session manager\n");
484 #endif
485     g_print("  --help             Display this help and exit\n");
486     g_print("  --version          Display the version and exit\n");
487     g_print("  --sync             Run in synchronous mode (this is slow and\n"
488             "                     meant for debugging X routines)\n");
489     g_print("\nPlease report bugs at %s\n", PACKAGE_BUGREPORT);
490 }
491
492 static void parse_args(int argc, char **argv)
493 {
494     int i;
495
496     for (i = 1; i < argc; ++i) {
497         if (!strcmp(argv[i], "--version")) {
498             print_version();
499             exit(0);
500         } else if (!strcmp(argv[i], "--help")) {
501             print_help();
502             exit(0);
503         } else if (!strcmp(argv[i], "--sync")) {
504             ob_sync = TRUE;
505         } else if (!strcmp(argv[i], "--rc")) {
506             if (i == argc - 1) /* no args left */
507                 g_printerr(_("--rc requires an argument\n"));
508             else
509                 ob_rc_path = argv[++i];
510 #ifdef USE_SM
511         } else if (!strcmp(argv[i], "--sm-client-id")) {
512             if (i == argc - 1) /* no args left */
513                 g_printerr(_("--sm-client-id requires an argument\n"));
514             else
515                 ob_sm_id = argv[++i];
516         } else if (!strcmp(argv[i], "--sm-disable")) {
517             ob_sm_use = FALSE;
518 #endif
519         } else {
520             g_printerr("Invalid option: '%s'\n\n", argv[i]);
521             print_help();
522             exit(1);
523         }
524     }
525 }
526
527 gboolean ob_pointer_pos(int *x, int *y)
528 {
529     Window w;
530     int i;
531     guint u;
532
533     return !!XQueryPointer(ob_display, ob_root, &w, &w, x, y, &i, &i, &u);
534 }
535
536 #ifdef USE_SM
537 static void sm_save_yourself(SmcConn conn, SmPointer data, int save_type,
538                              Bool shutdown, int interact_style, Bool fast)
539 {
540     g_message("got SAVE YOURSELF from session manager");
541     SmcSaveYourselfDone(conn, TRUE);
542 }
543
544 static void sm_die(SmcConn conn, SmPointer data)
545 {
546     ob_shutdown = TRUE;
547     g_message("got DIE from session manager");
548 }
549
550 static void sm_save_complete(SmcConn conn, SmPointer data)
551 {
552     g_message("got SAVE COMPLETE from session manager");
553 }
554
555 static void sm_shutdown_cancelled(SmcConn conn, SmPointer data)
556 {
557     g_message("got SHUTDOWN CANCELLED from session manager");
558 }
559 #endif
560
561 static void exit_with_error(gchar *msg)
562 {
563     g_critical(msg);
564     sm_shutdown();
565     exit(EXIT_FAILURE);
566 }