restore saved session data for applications
[mikachu/openbox.git] / openbox / session.c
1 /* This session code is largely inspired by metacity code. */
2
3 #ifndef USE_SM
4
5 void session_load(char *path) {}
6 void session_startup(int argc, char **argv) {}
7 void session_shutdown() {}
8
9 #else
10
11 #include "debug.h"
12 #include "openbox.h"
13 #include "session.h"
14 #include "client.h"
15 #include "prop.h"
16 #include "parser/parse.h"
17
18 #include <time.h>
19 #include <errno.h>
20 #include <stdio.h>
21
22 #ifdef HAVE_UNISTD_H
23 #  include <sys/types.h>
24 #  include <unistd.h>
25 #endif
26
27 #include <X11/SM/SMlib.h>
28
29 static SmcConn     sm_conn;
30 static gchar      *save_file;
31 static gint        sm_argc;
32 static gchar     **sm_argv;
33 static GSList     *sm_saved_state;
34
35 static gboolean session_save();
36
37 static void sm_save_yourself(SmcConn conn, SmPointer data, int save_type,
38                              Bool shutdown, int interact_style, Bool fast);
39 static void sm_die(SmcConn conn, SmPointer data);
40 static void sm_save_complete(SmcConn conn, SmPointer data);
41 static void sm_shutdown_cancelled(SmcConn conn, SmPointer data);
42
43 static void save_commands()
44 {
45     SmProp *props[2];
46     SmProp prop_cmd = { SmCloneCommand, SmLISTofARRAY8, 1, };
47     SmProp prop_res = { SmRestartCommand, SmLISTofARRAY8, };
48     gint i, j, n;
49     gboolean has_id = FALSE, has_file = FALSE;
50
51     for (i = 1; !has_id && !has_file && i < sm_argc - 1; ++i) {
52         if (!has_id && strcmp(sm_argv[i], "--sm-client-id") == 0)
53             has_id = TRUE;
54         if (!has_file && strcmp(sm_argv[i], "--sm-save-file") == 0)
55             has_file = TRUE;
56     }
57
58     n = (has_file ? sm_argc-2 : sm_argc);
59     n = (has_id ? n-2 : n);
60     prop_cmd.vals = g_new(SmPropValue, n);
61     prop_cmd.num_vals = n;
62     for (i = 0, j = 0; i < sm_argc; ++i, ++j) {
63         if (strcmp (sm_argv[i], "--sm-client-id") == 0 ||
64             strcmp (sm_argv[i], "--sm-save-file") == 0) {
65             ++i, --j; /* skip the next as well, keep j where it is */
66         } else {
67             prop_cmd.vals[j].value = sm_argv[i];
68             prop_cmd.vals[j].length = strlen(sm_argv[i]);
69         }
70     }
71
72     n = (has_file ? sm_argc : sm_argc+2);
73     n = (has_id ? n-2 : n);
74     prop_res.vals = g_new(SmPropValue, n);
75     prop_res.num_vals = n;
76     for (i = 0, j = 0; i < sm_argc; ++i, ++j) { 
77         if (strcmp (sm_argv[i], "--sm-client-id") == 0 ||
78             strcmp (sm_argv[i], "--sm-save-file") == 0) {
79             ++i, --j; /* skip the next as well, keep j where it is */
80         } else {
81             prop_res.vals[j].value = sm_argv[i];
82             prop_res.vals[j].length = strlen(sm_argv[i]);
83         }
84     }
85
86     if (save_file) {
87         prop_res.vals[j].value = "--sm-save-file";
88         prop_res.vals[j++].length = strlen("--sm-save-file");
89         prop_res.vals[j].value = save_file;
90         prop_res.vals[j++].length = strlen(save_file);
91     } else {
92         prop_res.vals[j].value = "--sm-client-id";
93         prop_res.vals[j++].length = strlen("--sm-client-id");
94         prop_res.vals[j].value = ob_sm_id;
95         prop_res.vals[j++].length = strlen(ob_sm_id);
96     }
97
98     props[0] = &prop_res;
99     props[1] = &prop_cmd;
100     SmcSetProperties(sm_conn, 2, props);
101
102     g_free(prop_res.vals);
103     g_free(prop_cmd.vals);
104 }
105
106 void session_startup(int argc, char **argv)
107 {
108 #define SM_ERR_LEN 1024
109
110     SmcCallbacks cb;
111     char sm_err[SM_ERR_LEN];
112
113     sm_argc = argc;
114     sm_argv = argv;
115
116     cb.save_yourself.callback = sm_save_yourself;
117     cb.save_yourself.client_data = NULL;
118
119     cb.die.callback = sm_die;
120     cb.die.client_data = NULL;
121
122     cb.save_complete.callback = sm_save_complete;
123     cb.save_complete.client_data = NULL;
124
125     cb.shutdown_cancelled.callback = sm_shutdown_cancelled;
126     cb.shutdown_cancelled.client_data = NULL;
127
128     sm_conn = SmcOpenConnection(NULL, NULL, 1, 0,
129                                 SmcSaveYourselfProcMask |
130                                 SmcDieProcMask |
131                                 SmcSaveCompleteProcMask |
132                                 SmcShutdownCancelledProcMask,
133                                 &cb, ob_sm_id, &ob_sm_id,
134                                 SM_ERR_LEN, sm_err);
135     if (sm_conn == NULL)
136         g_warning("Failed to connect to session manager: %s", sm_err);
137     else {
138         SmPropValue val_prog;
139         SmPropValue val_uid;
140         SmPropValue val_hint; 
141         SmPropValue val_pri;
142         SmPropValue val_pid;
143         SmProp prop_prog = { SmProgram, SmARRAY8, 1, };
144         SmProp prop_uid = { SmUserID, SmARRAY8, 1, };
145         SmProp prop_hint = { SmRestartStyleHint, SmCARD8, 1, };
146         SmProp prop_pid = { SmProcessID, SmARRAY8, 1, };
147         SmProp prop_pri = { "_GSM_Priority", SmCARD8, 1, };
148         SmProp *props[6];
149         gchar hint, pri;
150         gchar pid[32];
151
152         val_prog.value = argv[0];
153         val_prog.length = strlen(argv[0]);
154
155         val_uid.value = g_strdup(g_get_user_name());
156         val_uid.length = strlen(val_uid.value);
157
158         hint = SmRestartImmediately;
159         val_hint.value = &hint;
160         val_hint.length = 1;
161
162         sprintf(pid, "%ld", (long)getpid());
163         val_pid.value = pid;
164         val_pid.length = strlen(pid);
165
166         /* priority with gnome-session-manager, low to run before other apps */
167         pri = 20;
168         val_pri.value = &pri;
169         val_pri.length = 1;
170
171         prop_prog.vals = &val_prog;
172         prop_uid.vals = &val_uid;
173         prop_hint.vals = &val_hint;
174         prop_pid.vals = &val_pid;
175         prop_pri.vals = &val_pri;
176
177         props[0] = &prop_prog;
178         props[1] = &prop_uid;
179         props[2] = &prop_hint;
180         props[3] = &prop_pid;
181         props[4] = &prop_pri;
182
183         SmcSetProperties(sm_conn, 5, props);
184
185         g_free(val_uid.value);
186
187         save_commands();
188
189         ob_debug("Connected to session manager with id %s\n", ob_sm_id);
190     }
191 }
192
193 void session_shutdown()
194 {
195     g_free(save_file);
196
197     if (sm_conn) {
198         SmPropValue val_hint;
199         SmProp prop_hint = { SmRestartStyleHint, SmCARD8, 1, };
200         SmProp *props[1];
201         gulong hint;
202
203         /* when we exit, we want to reset this to a more friendly state */
204         hint = SmRestartIfRunning;
205         val_hint.value = &hint;
206         val_hint.length = 1;
207
208         prop_hint.vals = &val_hint;
209
210         props[0] = &prop_hint;
211
212         SmcSetProperties(sm_conn, 1, props);
213
214         SmcCloseConnection(sm_conn, 0, NULL);
215     }
216 }
217
218 static void sm_save_yourself_phase2(SmcConn conn, SmPointer data)
219 {
220     gboolean success;
221
222     ob_debug("got SAVE YOURSELF PHASE 2 from session manager\n");
223
224     success = session_save();
225     save_commands();
226
227     SmcSaveYourselfDone(conn, success);
228 }
229
230 static void sm_save_yourself(SmcConn conn, SmPointer data, int save_type,
231                              Bool shutdown, int interact_style, Bool fast)
232 {
233     ob_debug("got SAVE YOURSELF from session manager\n");
234
235     if (!SmcRequestSaveYourselfPhase2(conn, sm_save_yourself_phase2, data)) {
236         ob_debug("SAVE YOURSELF PHASE 2 failed\n");
237         SmcSaveYourselfDone(conn, FALSE);
238     }
239 }
240
241 static void sm_die(SmcConn conn, SmPointer data)
242 {
243     ob_exit();
244     ob_debug("got DIE from session manager\n");
245 }
246
247 static void sm_save_complete(SmcConn conn, SmPointer data)
248 {
249     ob_debug("got SAVE COMPLETE from session manager\n");
250 }
251
252 static void sm_shutdown_cancelled(SmcConn conn, SmPointer data)
253 {
254     ob_debug("got SHUTDOWN CANCELLED from session manager\n");
255 }
256
257 static gboolean session_save()
258 {
259     gchar *filename;
260     FILE *f;
261     GList *it;
262     gboolean success = TRUE;
263
264     /* this algo is from metacity */
265     filename = g_strdup_printf("%d-%d-%u.obs",
266                                (int) time(NULL),
267                                (int) getpid(),
268                                g_random_int());
269     save_file = g_build_filename(g_get_home_dir(), ".openbox", "sessions",
270                                  filename, NULL);
271     g_free(filename);
272
273     f = fopen(save_file, "w");
274     if (!f) {
275         success = FALSE;
276         g_warning("unable to save the session to %s: %s",
277                   save_file, strerror(errno));
278     } else {
279         fprintf(f, "<?xml version=\"1.0\"?>\n\n");
280         fprintf(f, "<openbox_session id=\"%s\">\n\n", ob_sm_id);
281
282         for (it = client_list; it; it = g_list_next(it)) {
283             guint num;
284             gint32 *dimensions;
285             gint prex, prey, prew, preh;
286             ObClient *c = it->data;
287             gchar *client_id, *t;
288
289             if (!client_normal(c))
290                 continue;
291
292             if (!PROP_GETS(c->window, sm_client_id, locale, &client_id))
293                 continue;
294
295             prex = c->area.x;
296             prey = c->area.y;
297             prew = c->area.width;
298             preh = c->area.height;
299             if (PROP_GETA32(c->window, openbox_premax, cardinal,
300                             (guint32**)&dimensions, &num)) {
301                 if (num == 4) {
302                     prex = dimensions[0];
303                     prey = dimensions[1];
304                     prew = dimensions[2];
305                     preh = dimensions[3];
306                 }
307                 g_free(dimensions);
308             }
309
310             fprintf(f, "<window id=\"%s\">\n", client_id);
311
312             t = g_markup_escape_text(c->name, -1);
313             fprintf(f, "\t<name>%s</name>\n", t);
314             g_free(t);
315
316             t = g_markup_escape_text(c->class, -1);
317             fprintf(f, "\t<class>%s</class>\n", t);
318             g_free(t);
319
320             t = g_markup_escape_text(c->role, -1);
321             fprintf(f, "\t<role>%s</role>\n", t);
322             g_free(t);
323
324             fprintf(f, "\t<desktop>%d</desktop>\n", c->desktop);
325             fprintf(f, "\t<x>%d</x>\n", prex);
326             fprintf(f, "\t<y>%d</y>\n", prey);
327             fprintf(f, "\t<width>%d</width>\n", prew);
328             fprintf(f, "\t<height>%d</height>\n", preh);
329             if (c->shaded)
330                 fprintf(f, "\t<shaded />\n");
331             if (c->iconic)
332                 fprintf(f, "\t<iconic />\n");
333             if (c->skip_pager)
334                 fprintf(f, "\t<skip_pager />\n");
335             if (c->skip_taskbar)
336                 fprintf(f, "\t<skip_taskbar />\n");
337             if (c->fullscreen)
338                 fprintf(f, "\t<fullscreen />\n");
339             if (c->above)
340                 fprintf(f, "\t<above />\n");
341             if (c->below)
342                 fprintf(f, "\t<below />\n");
343             if (c->max_horz)
344                 fprintf(f, "\t<max_horz />\n");
345             if (c->max_vert)
346                 fprintf(f, "\t<max_vert />\n");
347             fprintf(f, "</window>\n\n");
348
349             g_free(client_id);
350         }
351
352         fprintf(f, "</openbox_session>\n");
353
354         if (fflush(f)) {
355             success = FALSE;
356             g_warning("error while saving the session to %s: %s",
357                       save_file, strerror(errno));
358         }
359         fclose(f);
360     }
361
362     return success;
363 }
364
365 void session_state_free(ObSessionState *state)
366 {
367     if (state) {
368         g_free(state->id);
369         g_free(state->name);
370         g_free(state->class);
371         g_free(state->role);
372
373         g_free(state);
374     }
375 }
376
377 static gboolean session_state_cmp(const ObSessionState *s, const ObClient *c)
378 {
379     gchar *client_id;
380
381     if (!PROP_GETS(c->window, sm_client_id, locale, &client_id))
382         return FALSE;
383     g_print("\nsaved %s\nnow %s\n", s->id, client_id);
384     if (strcmp(s->id, client_id)) {
385         g_free(client_id);
386         return FALSE;
387     }
388     g_free(client_id);
389     g_print("\nsaved %s\nnow %s\n", s->name, c->name);
390     if (strcmp(s->name, c->name))
391         return FALSE;
392     g_print("\nsaved %s\nnow %s\n", s->class, c->class);
393     if (strcmp(s->class, c->class))
394         return FALSE;
395     g_print("\nsaved %s\nnow %s\n", s->role, c->role);
396     if (strcmp(s->role, c->role))
397         return FALSE;
398     return TRUE;
399 }
400
401 ObSessionState* session_state_find(ObClient *c)
402 {
403     GSList *it;
404
405     for (it = sm_saved_state; it; it = g_slist_next(it))
406         if (session_state_cmp(it->data, c)) {
407             ObSessionState *s = it->data;
408             sm_saved_state = g_slist_remove(sm_saved_state, s);
409             return s;
410         }
411     return NULL;
412 }
413
414 void session_load(char *path)
415 {
416     xmlDocPtr doc;
417     xmlNodePtr node, n;
418     gchar *sm_id;
419
420     if (!parse_load(path, "openbox_session", &doc, &node))
421         return;
422
423     if (!parse_attr_string("id", node, &sm_id))
424         return;
425     ob_sm_id = g_strdup(sm_id);
426
427     node = parse_find_node("window", node->xmlChildrenNode);
428     while (node) {
429         ObSessionState *state;
430
431         state = g_new0(ObSessionState, 1);
432
433         if (!parse_attr_string("id", node, &state->id))
434             goto session_load_bail;
435         if (!(n = parse_find_node("name", node->xmlChildrenNode)))
436             goto session_load_bail;
437         state->name = parse_string(doc, n);
438         if (!(n = parse_find_node("class", node->xmlChildrenNode)))
439             goto session_load_bail;
440         state->class = parse_string(doc, n);
441         if (!(n = parse_find_node("role", node->xmlChildrenNode)))
442             goto session_load_bail;
443         state->role = parse_string(doc, n);
444         if (!(n = parse_find_node("desktop", node->xmlChildrenNode)))
445             goto session_load_bail;
446         state->desktop = parse_int(doc, n);
447         if (!(n = parse_find_node("x", node->xmlChildrenNode)))
448             goto session_load_bail;
449         state->x = parse_int(doc, n);
450         if (!(n = parse_find_node("y", node->xmlChildrenNode)))
451             goto session_load_bail;
452         state->y = parse_int(doc, n);
453         if (!(n = parse_find_node("width", node->xmlChildrenNode)))
454             goto session_load_bail;
455         state->w = parse_int(doc, n);
456         if (!(n = parse_find_node("height", node->xmlChildrenNode)))
457             goto session_load_bail;
458         state->h = parse_int(doc, n);
459
460         state->shaded =
461             parse_find_node("shaded", node->xmlChildrenNode) != NULL;
462         state->iconic =
463             parse_find_node("iconic", node->xmlChildrenNode) != NULL;
464         state->skip_pager =
465             parse_find_node("skip_pager", node->xmlChildrenNode) != NULL;
466         state->skip_taskbar =
467             parse_find_node("skip_taskbar", node->xmlChildrenNode) != NULL;
468         state->fullscreen =
469             parse_find_node("fullscreen", node->xmlChildrenNode) != NULL;
470         state->above =
471             parse_find_node("above", node->xmlChildrenNode) != NULL;
472         state->below =
473             parse_find_node("below", node->xmlChildrenNode) != NULL;
474         state->max_horz =
475             parse_find_node("max_horz", node->xmlChildrenNode) != NULL;
476         state->max_vert =
477             parse_find_node("max_vert", node->xmlChildrenNode) != NULL;
478         
479         g_message("read session window %s", state->name);
480
481         /* save this */
482         g_message("saved state for %s %s", state->name, state->id);
483         sm_saved_state = g_slist_prepend(sm_saved_state, state);
484         goto session_load_ok;
485
486     session_load_bail:
487         session_state_free(state);
488
489     session_load_ok:
490
491         node = parse_find_node("window", node->next);
492     }
493
494     xmlFreeDoc(doc);
495 }
496
497 #endif