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