much improved functions for maknig directories, props to Logan
[mikachu/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() {}
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     if (save_file) {
96         prop_res.vals[i].value = "--sm-save-file";
97         prop_res.vals[i++].length = strlen("--sm-save-file");
98         prop_res.vals[i].value = save_file;
99         prop_res.vals[i++].length = strlen(save_file);
100     } else {
101         prop_res.vals[i].value = "--sm-client-id";
102         prop_res.vals[i++].length = strlen("--sm-client-id");
103         prop_res.vals[i].value = sm_id;
104         prop_res.vals[i++].length = strlen(sm_id);
105     }
106
107     props[0] = &prop_res;
108     props[1] = &prop_cmd;
109     SmcSetProperties(sm_conn, 2, props);
110
111     g_free(prop_res.vals);
112     g_free(prop_cmd.vals);
113 }
114
115 static void remove_args(gint *argc, gchar ***argv, gint index, gint num)
116 {
117     gint i;
118
119     for (i = index; i < index + num; ++i)
120         (*argv)[i] = (*argv)[i+num];
121     *argc -= num;
122 }
123
124 static void parse_args(gint *argc, gchar ***argv)
125 {
126     gint i;
127
128     for (i = 1; i < *argc; ++i) {
129         if (!strcmp((*argv)[i], "--sm-client-id")) {
130             if (i == *argc - 1) /* no args left */
131                 g_printerr(_("--sm-client-id requires an argument\n"));
132             else {
133                 sm_id = g_strdup((*argv)[i+1]);
134                 remove_args(argc, argv, i, 2);
135                 ++i;
136             }
137         } else if (!strcmp((*argv)[i], "--sm-save-file")) {
138             if (i == *argc - 1) /* no args left */
139                 g_printerr(_("--sm-save-file requires an argument\n"));
140             else {
141                 save_file = g_strdup((*argv)[i+1]);
142                 remove_args(argc, argv, i, 2);
143                 ++i;
144             }
145         } else if (!strcmp((*argv)[i], "--sm-disable")) {
146             sm_disable = TRUE;
147             remove_args(argc, argv, i, 1);
148         }
149     }
150 }
151
152 void session_startup(gint *argc, gchar ***argv)
153 {
154 #define SM_ERR_LEN 1024
155
156     SmcCallbacks cb;
157     gchar sm_err[SM_ERR_LEN];
158
159     parse_args(argc, argv);
160
161     if (sm_disable)
162         return;
163
164     sm_sessions_path = g_build_filename(parse_xdg_data_home_path(),
165                                         "openbox", "sessions", NULL);
166     if (!parse_mkdir_path(sm_sessions_path, 0700))
167         g_warning(_("unable to make directory '%s': %s"),
168                   sm_sessions_path, g_strerror(errno));
169
170     if (save_file)
171         session_load(save_file);
172
173     sm_argc = *argc;
174     sm_argv = *argv;
175
176     cb.save_yourself.callback = sm_save_yourself;
177     cb.save_yourself.client_data = NULL;
178
179     cb.die.callback = sm_die;
180     cb.die.client_data = NULL;
181
182     cb.save_complete.callback = sm_save_complete;
183     cb.save_complete.client_data = NULL;
184
185     cb.shutdown_cancelled.callback = sm_shutdown_cancelled;
186     cb.shutdown_cancelled.client_data = NULL;
187
188     sm_conn = SmcOpenConnection(NULL, NULL, 1, 0,
189                                 SmcSaveYourselfProcMask |
190                                 SmcDieProcMask |
191                                 SmcSaveCompleteProcMask |
192                                 SmcShutdownCancelledProcMask,
193                                 &cb, sm_id, &sm_id,
194                                 SM_ERR_LEN, sm_err);
195     if (sm_conn == NULL)
196         ob_debug("Failed to connect to session manager: %s\n", sm_err);
197     else {
198         SmPropValue val_prog;
199         SmPropValue val_uid;
200         SmPropValue val_hint; 
201         SmPropValue val_pri;
202         SmPropValue val_pid;
203         SmProp prop_prog = { SmProgram, SmARRAY8, 1, };
204         SmProp prop_uid = { SmUserID, SmARRAY8, 1, };
205         SmProp prop_hint = { SmRestartStyleHint, SmCARD8, 1, };
206         SmProp prop_pid = { SmProcessID, SmARRAY8, 1, };
207         SmProp prop_pri = { "_GSM_Priority", SmCARD8, 1, };
208         SmProp *props[6];
209         gchar hint, pri;
210         gchar pid[32];
211
212         val_prog.value = sm_argv[0];
213         val_prog.length = strlen(sm_argv[0]);
214
215         val_uid.value = g_strdup(g_get_user_name());
216         val_uid.length = strlen(val_uid.value);
217
218         hint = SmRestartImmediately;
219         val_hint.value = &hint;
220         val_hint.length = 1;
221
222         sprintf(pid, "%ld", (glong)getpid());
223         val_pid.value = pid;
224         val_pid.length = strlen(pid);
225
226         /* priority with gnome-session-manager, low to run before other apps */
227         pri = 20;
228         val_pri.value = &pri;
229         val_pri.length = 1;
230
231         prop_prog.vals = &val_prog;
232         prop_uid.vals = &val_uid;
233         prop_hint.vals = &val_hint;
234         prop_pid.vals = &val_pid;
235         prop_pri.vals = &val_pri;
236
237         props[0] = &prop_prog;
238         props[1] = &prop_uid;
239         props[2] = &prop_hint;
240         props[3] = &prop_pid;
241         props[4] = &prop_pri;
242
243         SmcSetProperties(sm_conn, 5, props);
244
245         g_free(val_uid.value);
246
247         save_commands();
248     }
249 }
250
251 void session_shutdown()
252 {
253     g_free(sm_sessions_path);
254     g_free(save_file);
255     g_free(sm_id);
256
257     if (sm_conn) {
258         SmPropValue val_hint;
259         SmProp prop_hint = { SmRestartStyleHint, SmCARD8, 1, };
260         SmProp *props[1];
261         gulong hint;
262
263         /* when we exit, we want to reset this to a more friendly state */
264         hint = SmRestartIfRunning;
265         val_hint.value = &hint;
266         val_hint.length = 1;
267
268         prop_hint.vals = &val_hint;
269
270         props[0] = &prop_hint;
271
272         SmcSetProperties(sm_conn, 1, props);
273
274         SmcCloseConnection(sm_conn, 0, NULL);
275
276         while (session_saved_state) {
277             session_state_free(session_saved_state->data);
278             session_saved_state = g_list_delete_link(session_saved_state,
279                                                      session_saved_state);
280         }
281     }
282 }
283
284 static void sm_save_yourself_phase2(SmcConn conn, SmPointer data)
285 {
286     gboolean success;
287
288     success = session_save();
289     save_commands();
290
291     SmcSaveYourselfDone(conn, success);
292 }
293
294 static void sm_save_yourself(SmcConn conn, SmPointer data, gint save_type,
295                              Bool shutdown, gint interact_style, Bool fast)
296 {
297     if (!SmcRequestSaveYourselfPhase2(conn, sm_save_yourself_phase2, data)) {
298         ob_debug("SAVE YOURSELF PHASE 2 failed\n");
299         SmcSaveYourselfDone(conn, FALSE);
300     }
301 }
302
303 static void sm_die(SmcConn conn, SmPointer data)
304 {
305     ob_exit(0);
306 }
307
308 static void sm_save_complete(SmcConn conn, SmPointer data)
309 {
310 }
311
312 static void sm_shutdown_cancelled(SmcConn conn, SmPointer data)
313 {
314 }
315
316 static gboolean session_save()
317 {
318     gchar *filename;
319     FILE *f;
320     GList *it;
321     gboolean success = TRUE;
322
323     if (save_file)
324         unlink(save_file);
325
326     /* this algo is from metacity */
327     filename = g_strdup_printf("%d-%d-%u.obs",
328                                (gint) time(NULL),
329                                (gint) getpid(),
330                                g_random_int());
331     save_file = g_build_filename(sm_sessions_path, filename, NULL);
332     g_free(filename);
333
334     f = fopen(save_file, "w");
335     if (!f) {
336         success = FALSE;
337         g_warning("unable to save the session to %s: %s",
338                   save_file, strerror(errno));
339     } else {
340         guint stack_pos = 0;
341
342         fprintf(f, "<?xml version=\"1.0\"?>\n\n");
343         fprintf(f, "<openbox_session id=\"%s\">\n\n", sm_id);
344
345         for (it = stacking_list; it; it = g_list_next(it)) {
346             gint prex, prey, prew, preh;
347             ObClient *c;
348             gchar *t;
349
350             if (WINDOW_IS_CLIENT(it->data))
351                 c = WINDOW_AS_CLIENT(it->data);
352             else
353                 continue;
354
355             if (!client_normal(c))
356                 continue;
357
358             if (!c->sm_client_id)
359                 continue;
360
361             prex = c->area.x;
362             prey = c->area.y;
363             prew = c->area.width;
364             preh = c->area.height;
365             if (c->fullscreen) {
366                 prex = c->pre_fullscreen_area.x;
367                 prey = c->pre_fullscreen_area.x;
368                 prew = c->pre_fullscreen_area.width;
369                 preh = c->pre_fullscreen_area.height;
370             }
371             if (c->max_horz) {
372                 prex = c->pre_max_area.x;
373                 prew = c->pre_max_area.width;
374             }
375             if (c->max_vert) {
376                 prey = c->pre_max_area.y;
377                 preh = c->pre_max_area.height;
378             }
379
380             fprintf(f, "<window id=\"%s\">\n", c->sm_client_id);
381
382             t = g_markup_escape_text(c->name, -1);
383             fprintf(f, "\t<name>%s</name>\n", t);
384             g_free(t);
385
386             t = g_markup_escape_text(c->class, -1);
387             fprintf(f, "\t<class>%s</class>\n", t);
388             g_free(t);
389
390             t = g_markup_escape_text(c->role, -1);
391             fprintf(f, "\t<role>%s</role>\n", t);
392             g_free(t);
393
394             fprintf(f, "\t<desktop>%d</desktop>\n", c->desktop);
395             fprintf(f, "\t<stacking>%d</stacking>\n", stack_pos);
396             fprintf(f, "\t<x>%d</x>\n", prex);
397             fprintf(f, "\t<y>%d</y>\n", prey);
398             fprintf(f, "\t<width>%d</width>\n", prew);
399             fprintf(f, "\t<height>%d</height>\n", preh);
400             if (c->shaded)
401                 fprintf(f, "\t<shaded />\n");
402             if (c->iconic)
403                 fprintf(f, "\t<iconic />\n");
404             if (c->skip_pager)
405                 fprintf(f, "\t<skip_pager />\n");
406             if (c->skip_taskbar)
407                 fprintf(f, "\t<skip_taskbar />\n");
408             if (c->fullscreen)
409                 fprintf(f, "\t<fullscreen />\n");
410             if (c->above)
411                 fprintf(f, "\t<above />\n");
412             if (c->below)
413                 fprintf(f, "\t<below />\n");
414             if (c->max_horz)
415                 fprintf(f, "\t<max_horz />\n");
416             if (c->max_vert)
417                 fprintf(f, "\t<max_vert />\n");
418             fprintf(f, "</window>\n\n");
419
420             ++stack_pos;
421         }
422
423         fprintf(f, "</openbox_session>\n");
424
425         if (fflush(f)) {
426             success = FALSE;
427             g_warning("error while saving the session to %s: %s",
428                       save_file, strerror(errno));
429         }
430         fclose(f);
431     }
432
433     return success;
434 }
435
436 void session_state_free(ObSessionState *state)
437 {
438     if (state) {
439         g_free(state->id);
440         g_free(state->name);
441         g_free(state->class);
442         g_free(state->role);
443
444         g_free(state);
445     }
446 }
447
448 gboolean session_state_cmp(ObSessionState *s, ObClient *c)
449 {
450     return (c->sm_client_id &&
451             !strcmp(s->id, c->sm_client_id) &&
452             !strcmp(s->name, c->name) &&
453             !strcmp(s->class, c->class) &&
454             !strcmp(s->role, c->role));
455 }
456
457 GList* session_state_find(ObClient *c)
458 {
459     GList *it;
460
461     for (it = session_saved_state; it; it = g_list_next(it)) {
462         ObSessionState *s = it->data;
463         if (!s->matched && session_state_cmp(s, c)) {
464             s->matched = TRUE;
465             break;
466         }
467     }
468     return it;
469 }
470
471 static gint stack_sort(const ObSessionState *s1, const ObSessionState *s2)
472 {
473     return s1->stacking - s2->stacking;
474 }
475
476 static void session_load(gchar *path)
477 {
478     xmlDocPtr doc;
479     xmlNodePtr node, n;
480     gchar *id;
481
482     if (!parse_load(path, "openbox_session", &doc, &node))
483         return;
484
485     if (!parse_attr_string("id", node, &id))
486         return;
487     g_free(sm_id);
488     sm_id = id;
489
490     node = parse_find_node("window", node->children);
491     while (node) {
492         ObSessionState *state;
493
494         state = g_new0(ObSessionState, 1);
495
496         if (!parse_attr_string("id", node, &state->id))
497             goto session_load_bail;
498         if (!(n = parse_find_node("name", node->children)))
499             goto session_load_bail;
500         state->name = parse_string(doc, n);
501         if (!(n = parse_find_node("class", node->children)))
502             goto session_load_bail;
503         state->class = parse_string(doc, n);
504         if (!(n = parse_find_node("role", node->children)))
505             goto session_load_bail;
506         state->role = parse_string(doc, n);
507         if (!(n = parse_find_node("stacking", node->children)))
508             goto session_load_bail;
509         state->stacking = parse_int(doc, n);
510         if (!(n = parse_find_node("desktop", node->children)))
511             goto session_load_bail;
512         state->desktop = parse_int(doc, n);
513         if (!(n = parse_find_node("x", node->children)))
514             goto session_load_bail;
515         state->x = parse_int(doc, n);
516         if (!(n = parse_find_node("y", node->children)))
517             goto session_load_bail;
518         state->y = parse_int(doc, n);
519         if (!(n = parse_find_node("width", node->children)))
520             goto session_load_bail;
521         state->w = parse_int(doc, n);
522         if (!(n = parse_find_node("height", node->children)))
523             goto session_load_bail;
524         state->h = parse_int(doc, n);
525
526         state->shaded =
527             parse_find_node("shaded", node->children) != NULL;
528         state->iconic =
529             parse_find_node("iconic", node->children) != NULL;
530         state->skip_pager =
531             parse_find_node("skip_pager", node->children) != NULL;
532         state->skip_taskbar =
533             parse_find_node("skip_taskbar", node->children) != NULL;
534         state->fullscreen =
535             parse_find_node("fullscreen", node->children) != NULL;
536         state->above =
537             parse_find_node("above", node->children) != NULL;
538         state->below =
539             parse_find_node("below", node->children) != NULL;
540         state->max_horz =
541             parse_find_node("max_horz", node->children) != NULL;
542         state->max_vert =
543             parse_find_node("max_vert", node->children) != NULL;
544         
545         /* save this */
546         session_saved_state = g_list_prepend(session_saved_state, state);
547         goto session_load_ok;
548
549     session_load_bail:
550         session_state_free(state);
551
552     session_load_ok:
553
554         node = parse_find_node("window", node->next);
555     }
556
557     /* sort them by their stacking order */
558     session_saved_state = g_list_sort(session_saved_state,
559                                       (GCompareFunc)stack_sort);
560
561     xmlFreeDoc(doc);
562 }
563
564 #endif