fix compiling without session manager support
[dana/openbox.git] / openbox / session.c
1 /* -*- indent-tabs-mode: nil; tab-width: 4; c-basic-offset: 4; -*-
2
3    session.c for the Openbox window manager
4    Copyright (c) 2003        Ben Jansens
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    See the COPYING file for a copy of the GNU General Public License.
17 */
18
19 /* This session code is largely inspired by metacity code. */
20
21 #ifndef USE_SM
22
23 #include "session.h"
24 #include "client.h"
25
26 GList *session_saved_state;
27
28 void session_startup(gint argc, gchar **argv) {}
29 void session_shutdown(gboolean permanent) {}
30 GList* session_state_find(ObClient *c) { return NULL; }
31 gboolean session_state_cmp(ObSessionState *s, ObClient *c) { return FALSE; }
32 void session_state_free(ObSessionState *state) {}
33
34 #else
35
36 #include "debug.h"
37 #include "openbox.h"
38 #include "session.h"
39 #include "client.h"
40 #include "prop.h"
41 #include "gettext.h"
42 #include "parser/parse.h"
43
44 #include <time.h>
45 #include <errno.h>
46 #include <stdio.h>
47
48 #ifdef HAVE_UNISTD_H
49 #  include <sys/types.h>
50 #  include <unistd.h>
51 #endif
52
53 #include <X11/SM/SMlib.h>
54
55 GList *session_saved_state;
56
57 static gboolean    sm_disable;
58 static SmcConn     sm_conn;
59 static gchar      *save_file;
60 static gchar      *sm_id;
61 static gint        sm_argc;
62 static gchar     **sm_argv;
63 static gchar      *sm_sessions_path;
64
65 static void session_load(gchar *path);
66 static gboolean session_save();
67
68 static void sm_save_yourself(SmcConn conn, SmPointer data, gint save_type,
69                              Bool shutdown, gint interact_style, Bool fast);
70 static void sm_die(SmcConn conn, SmPointer data);
71 static void sm_save_complete(SmcConn conn, SmPointer data);
72 static void sm_shutdown_cancelled(SmcConn conn, SmPointer data);
73
74 static void save_commands()
75 {
76     SmProp *props[2];
77     SmProp prop_cmd = { SmCloneCommand, SmLISTofARRAY8, 1, };
78     SmProp prop_res = { SmRestartCommand, SmLISTofARRAY8, };
79     gint i;
80
81     prop_cmd.vals = g_new(SmPropValue, sm_argc);
82     prop_cmd.num_vals = sm_argc;
83     for (i = 0; i < sm_argc; ++i) {
84         prop_cmd.vals[i].value = sm_argv[i];
85         prop_cmd.vals[i].length = strlen(sm_argv[i]);
86     }
87
88     prop_res.vals = g_new(SmPropValue, sm_argc + 2);
89     prop_res.num_vals = sm_argc + 2;
90     for (i = 0; i < sm_argc; ++i) { 
91         prop_res.vals[i].value = sm_argv[i];
92         prop_res.vals[i].length = strlen(sm_argv[i]);
93     }
94
95     prop_res.vals[i].value = "--sm-save-file";
96     prop_res.vals[i++].length = strlen("--sm-save-file");
97     prop_res.vals[i].value = save_file;
98     prop_res.vals[i++].length = strlen(save_file);
99
100     props[0] = &prop_res;
101     props[1] = &prop_cmd;
102     SmcSetProperties(sm_conn, 2, props);
103
104     g_free(prop_res.vals);
105     g_free(prop_cmd.vals);
106 }
107
108 static void remove_args(gint *argc, gchar ***argv, gint index, gint num)
109 {
110     gint i;
111
112     for (i = index; i < index + num; ++i)
113         (*argv)[i] = (*argv)[i+num];
114     *argc -= num;
115 }
116
117 static void parse_args(gint *argc, gchar ***argv)
118 {
119     gint i;
120
121     for (i = 1; i < *argc; ++i) {
122         if (!strcmp((*argv)[i], "--sm-client-id")) {
123             if (i == *argc - 1) /* no args left */
124                 g_printerr(_("--sm-client-id requires an argument\n"));
125             else {
126                 sm_id = g_strdup((*argv)[i+1]);
127                 remove_args(argc, argv, i, 2);
128                 ++i;
129             }
130         } else if (!strcmp((*argv)[i], "--sm-save-file")) {
131             if (i == *argc - 1) /* no args left */
132                 g_printerr(_("--sm-save-file requires an argument\n"));
133             else {
134                 save_file = g_strdup((*argv)[i+1]);
135                 remove_args(argc, argv, i, 2);
136                 ++i;
137             }
138         } else if (!strcmp((*argv)[i], "--sm-disable")) {
139             sm_disable = TRUE;
140             remove_args(argc, argv, i, 1);
141         }
142     }
143 }
144
145 void session_startup(gint argc, gchar **argv)
146 {
147 #define SM_ERR_LEN 1024
148
149     SmcCallbacks cb;
150     gchar sm_err[SM_ERR_LEN];
151     gint i;
152
153     sm_argc = argc;
154     sm_argv = g_new(gchar*, argc);
155     for (i = 0; i < argc; ++i)
156         sm_argv[i] = argv[i];
157
158     parse_args(&sm_argc, &sm_argv);
159
160     if (sm_disable) {
161         g_free(sm_argv);
162         return;
163     }
164
165     sm_sessions_path = g_build_filename(parse_xdg_data_home_path(),
166                                         "openbox", "sessions", NULL);
167     if (!parse_mkdir_path(sm_sessions_path, 0700))
168         g_warning(_("Unable to make directory '%s': %s"),
169                   sm_sessions_path, g_strerror(errno));
170
171     if (save_file)
172         session_load(save_file);
173     else {
174         gchar *filename;
175
176         /* this algo is from metacity */
177         filename = g_strdup_printf("%d-%d-%u.obs",
178                                    (gint) time(NULL),
179                                    (gint) getpid(),
180                                    g_random_int());
181         save_file = g_build_filename(sm_sessions_path, filename, NULL);
182         g_free(filename);
183     }
184
185     cb.save_yourself.callback = sm_save_yourself;
186     cb.save_yourself.client_data = NULL;
187
188     cb.die.callback = sm_die;
189     cb.die.client_data = NULL;
190
191     cb.save_complete.callback = sm_save_complete;
192     cb.save_complete.client_data = NULL;
193
194     cb.shutdown_cancelled.callback = sm_shutdown_cancelled;
195     cb.shutdown_cancelled.client_data = NULL;
196
197     sm_conn = SmcOpenConnection(NULL, NULL, 1, 0,
198                                 SmcSaveYourselfProcMask |
199                                 SmcDieProcMask |
200                                 SmcSaveCompleteProcMask |
201                                 SmcShutdownCancelledProcMask,
202                                 &cb, sm_id, &sm_id,
203                                 SM_ERR_LEN, sm_err);
204     if (sm_conn == NULL)
205         ob_debug("Failed to connect to session manager: %s\n", sm_err);
206     else {
207         SmPropValue val_prog;
208         SmPropValue val_uid;
209         SmPropValue val_hint; 
210         SmPropValue val_pri;
211         SmPropValue val_pid;
212         SmProp prop_prog = { SmProgram, SmARRAY8, 1, };
213         SmProp prop_uid = { SmUserID, SmARRAY8, 1, };
214         SmProp prop_hint = { SmRestartStyleHint, SmCARD8, 1, };
215         SmProp prop_pid = { SmProcessID, SmARRAY8, 1, };
216         SmProp prop_pri = { "_GSM_Priority", SmCARD8, 1, };
217         SmProp *props[6];
218         gchar hint, pri;
219         gchar pid[32];
220
221         val_prog.value = sm_argv[0];
222         val_prog.length = strlen(sm_argv[0]);
223
224         val_uid.value = g_strdup(g_get_user_name());
225         val_uid.length = strlen(val_uid.value);
226
227         hint = SmRestartImmediately;
228         val_hint.value = &hint;
229         val_hint.length = 1;
230
231         g_snprintf(pid, sizeof(pid), "%ld", (glong) getpid());
232         val_pid.value = pid;
233         val_pid.length = strlen(pid);
234
235         /* priority with gnome-session-manager, low to run before other apps */
236         pri = 20;
237         val_pri.value = &pri;
238         val_pri.length = 1;
239
240         prop_prog.vals = &val_prog;
241         prop_uid.vals = &val_uid;
242         prop_hint.vals = &val_hint;
243         prop_pid.vals = &val_pid;
244         prop_pri.vals = &val_pri;
245
246         props[0] = &prop_prog;
247         props[1] = &prop_uid;
248         props[2] = &prop_hint;
249         props[3] = &prop_pid;
250         props[4] = &prop_pri;
251
252         SmcSetProperties(sm_conn, 5, props);
253
254         g_free(val_uid.value);
255
256         save_commands();
257     }
258 }
259
260 void session_shutdown(gboolean permanent)
261 {
262     if (sm_disable)
263         return;
264
265     g_free(sm_sessions_path);
266     g_free(save_file);
267     g_free(sm_id);
268     g_free(sm_argv);
269
270     if (sm_conn) {
271         /* if permanent is true then we will change our session state so that
272            the SM won't run us again */
273         if (permanent) {
274             SmPropValue val_hint;
275             SmProp prop_hint = { SmRestartStyleHint, SmCARD8, 1, };
276             SmProp *props[1];
277             gulong hint;
278
279             /* when we exit, we want to reset this to a more friendly state */
280             hint = SmRestartIfRunning;
281             val_hint.value = &hint;
282             val_hint.length = 1;
283
284             prop_hint.vals = &val_hint;
285
286             props[0] = &prop_hint;
287
288             SmcSetProperties(sm_conn, 1, props);
289         }
290
291         SmcCloseConnection(sm_conn, 0, NULL);
292
293         while (session_saved_state) {
294             session_state_free(session_saved_state->data);
295             session_saved_state = g_list_delete_link(session_saved_state,
296                                                      session_saved_state);
297         }
298     }
299 }
300
301 static void sm_save_yourself_phase2(SmcConn conn, SmPointer data)
302 {
303     gboolean success;
304
305     success = session_save();
306     save_commands();
307
308     SmcSaveYourselfDone(conn, success);
309 }
310
311 static void sm_save_yourself(SmcConn conn, SmPointer data, gint save_type,
312                              Bool shutdown, gint interact_style, Bool fast)
313 {
314     if (!SmcRequestSaveYourselfPhase2(conn, sm_save_yourself_phase2, data)) {
315         ob_debug("SAVE YOURSELF PHASE 2 failed\n");
316         SmcSaveYourselfDone(conn, FALSE);
317     }
318 }
319
320 static void sm_die(SmcConn conn, SmPointer data)
321 {
322     ob_exit(0);
323 }
324
325 static void sm_save_complete(SmcConn conn, SmPointer data)
326 {
327 }
328
329 static void sm_shutdown_cancelled(SmcConn conn, SmPointer data)
330 {
331 }
332
333 static gboolean session_save()
334 {
335     FILE *f;
336     GList *it;
337     gboolean success = TRUE;
338
339     f = fopen(save_file, "w");
340     if (!f) {
341         success = FALSE;
342         g_warning("unable to save the session to %s: %s",
343                   save_file, g_strerror(errno));
344     } else {
345         guint stack_pos = 0;
346
347         fprintf(f, "<?xml version=\"1.0\"?>\n\n");
348         fprintf(f, "<openbox_session id=\"%s\">\n\n", sm_id);
349
350         for (it = stacking_list; it; it = g_list_next(it)) {
351             gint prex, prey, prew, preh;
352             ObClient *c;
353             gchar *t;
354
355             if (WINDOW_IS_CLIENT(it->data))
356                 c = WINDOW_AS_CLIENT(it->data);
357             else
358                 continue;
359
360             if (!client_normal(c))
361                 continue;
362
363             if (!c->sm_client_id)
364                 continue;
365
366             prex = c->area.x;
367             prey = c->area.y;
368             prew = c->area.width;
369             preh = c->area.height;
370             if (c->fullscreen) {
371                 prex = c->pre_fullscreen_area.x;
372                 prey = c->pre_fullscreen_area.x;
373                 prew = c->pre_fullscreen_area.width;
374                 preh = c->pre_fullscreen_area.height;
375             }
376             if (c->max_horz) {
377                 prex = c->pre_max_area.x;
378                 prew = c->pre_max_area.width;
379             }
380             if (c->max_vert) {
381                 prey = c->pre_max_area.y;
382                 preh = c->pre_max_area.height;
383             }
384
385             fprintf(f, "<window id=\"%s\">\n", c->sm_client_id);
386
387             t = g_markup_escape_text(c->name, -1);
388             fprintf(f, "\t<name>%s</name>\n", t);
389             g_free(t);
390
391             t = g_markup_escape_text(c->class, -1);
392             fprintf(f, "\t<class>%s</class>\n", t);
393             g_free(t);
394
395             t = g_markup_escape_text(c->role, -1);
396             fprintf(f, "\t<role>%s</role>\n", t);
397             g_free(t);
398
399             fprintf(f, "\t<desktop>%d</desktop>\n", c->desktop);
400             fprintf(f, "\t<stacking>%d</stacking>\n", stack_pos);
401             fprintf(f, "\t<x>%d</x>\n", prex);
402             fprintf(f, "\t<y>%d</y>\n", prey);
403             fprintf(f, "\t<width>%d</width>\n", prew);
404             fprintf(f, "\t<height>%d</height>\n", preh);
405             if (c->shaded)
406                 fprintf(f, "\t<shaded />\n");
407             if (c->iconic)
408                 fprintf(f, "\t<iconic />\n");
409             if (c->skip_pager)
410                 fprintf(f, "\t<skip_pager />\n");
411             if (c->skip_taskbar)
412                 fprintf(f, "\t<skip_taskbar />\n");
413             if (c->fullscreen)
414                 fprintf(f, "\t<fullscreen />\n");
415             if (c->above)
416                 fprintf(f, "\t<above />\n");
417             if (c->below)
418                 fprintf(f, "\t<below />\n");
419             if (c->max_horz)
420                 fprintf(f, "\t<max_horz />\n");
421             if (c->max_vert)
422                 fprintf(f, "\t<max_vert />\n");
423             fprintf(f, "</window>\n\n");
424
425             ++stack_pos;
426         }
427
428         fprintf(f, "</openbox_session>\n");
429
430         if (fflush(f)) {
431             success = FALSE;
432             g_warning("error while saving the session to %s: %s",
433                       save_file, g_strerror(errno));
434         }
435         fclose(f);
436     }
437
438     return success;
439 }
440
441 void session_state_free(ObSessionState *state)
442 {
443     if (state) {
444         g_free(state->id);
445         g_free(state->name);
446         g_free(state->class);
447         g_free(state->role);
448
449         g_free(state);
450     }
451 }
452
453 gboolean session_state_cmp(ObSessionState *s, ObClient *c)
454 {
455     return (c->sm_client_id &&
456             !strcmp(s->id, c->sm_client_id) &&
457             !strcmp(s->name, c->name) &&
458             !strcmp(s->class, c->class) &&
459             !strcmp(s->role, c->role));
460 }
461
462 GList* session_state_find(ObClient *c)
463 {
464     GList *it;
465
466     for (it = session_saved_state; it; it = g_list_next(it)) {
467         ObSessionState *s = it->data;
468         if (!s->matched && session_state_cmp(s, c)) {
469             s->matched = TRUE;
470             break;
471         }
472     }
473     return it;
474 }
475
476 static gint stack_sort(const ObSessionState *s1, const ObSessionState *s2)
477 {
478     return s1->stacking - s2->stacking;
479 }
480
481 static void session_load(gchar *path)
482 {
483     xmlDocPtr doc;
484     xmlNodePtr node, n;
485     gchar *id;
486
487     if (!parse_load(path, "openbox_session", &doc, &node))
488         return;
489
490     if (!parse_attr_string("id", node, &id))
491         return;
492     g_free(sm_id);
493     sm_id = id;
494
495     node = parse_find_node("window", node->children);
496     while (node) {
497         ObSessionState *state;
498
499         state = g_new0(ObSessionState, 1);
500
501         if (!parse_attr_string("id", node, &state->id))
502             goto session_load_bail;
503         if (!(n = parse_find_node("name", node->children)))
504             goto session_load_bail;
505         state->name = parse_string(doc, n);
506         if (!(n = parse_find_node("class", node->children)))
507             goto session_load_bail;
508         state->class = parse_string(doc, n);
509         if (!(n = parse_find_node("role", node->children)))
510             goto session_load_bail;
511         state->role = parse_string(doc, n);
512         if (!(n = parse_find_node("stacking", node->children)))
513             goto session_load_bail;
514         state->stacking = parse_int(doc, n);
515         if (!(n = parse_find_node("desktop", node->children)))
516             goto session_load_bail;
517         state->desktop = parse_int(doc, n);
518         if (!(n = parse_find_node("x", node->children)))
519             goto session_load_bail;
520         state->x = parse_int(doc, n);
521         if (!(n = parse_find_node("y", node->children)))
522             goto session_load_bail;
523         state->y = parse_int(doc, n);
524         if (!(n = parse_find_node("width", node->children)))
525             goto session_load_bail;
526         state->w = parse_int(doc, n);
527         if (!(n = parse_find_node("height", node->children)))
528             goto session_load_bail;
529         state->h = parse_int(doc, n);
530
531         state->shaded =
532             parse_find_node("shaded", node->children) != NULL;
533         state->iconic =
534             parse_find_node("iconic", node->children) != NULL;
535         state->skip_pager =
536             parse_find_node("skip_pager", node->children) != NULL;
537         state->skip_taskbar =
538             parse_find_node("skip_taskbar", node->children) != NULL;
539         state->fullscreen =
540             parse_find_node("fullscreen", node->children) != NULL;
541         state->above =
542             parse_find_node("above", node->children) != NULL;
543         state->below =
544             parse_find_node("below", node->children) != NULL;
545         state->max_horz =
546             parse_find_node("max_horz", node->children) != NULL;
547         state->max_vert =
548             parse_find_node("max_vert", node->children) != NULL;
549         
550         /* save this */
551         session_saved_state = g_list_prepend(session_saved_state, state);
552         goto session_load_ok;
553
554     session_load_bail:
555         session_state_free(state);
556
557     session_load_ok:
558
559         node = parse_find_node("window", node->next);
560     }
561
562     /* sort them by their stacking order */
563     session_saved_state = g_list_sort(session_saved_state,
564                                       (GCompareFunc)stack_sort);
565
566     xmlFreeDoc(doc);
567 }
568
569 #endif