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