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