- s/sprintf/snprintf
[wmaker-crm.git] / src / session.c
blob824ef6d411be5dabae1d745905c90520a0ebef3f
1 /* session.c - session state handling and R6 style session management
3 * Copyright (c) 1998 Dan Pascu
4 * Copyright (c) 1998, 1999 Alfredo Kojima
6 * Window Maker window manager
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
21 * USA.
27 * If defined(XSMP_ENABLED) and session manager is running then
28 * do normal stuff
29 * else
30 * do pre-R6 session management stuff (save window state and relaunch)
32 * When doing a checkpoint:
34 * = Without XSMP
35 * Open "Stop"/status Dialog
36 * Send SAVE_YOURSELF to clients and wait for reply
37 * Save restart info
38 * Save state of clients
40 * = With XSMP
41 * Send checkpoint request to sm
43 * When exiting:
44 * -------------
46 * = Without XSMP
48 * Open "Exit Now"/status Dialog
49 * Send SAVE_YOURSELF to clients and wait for reply
50 * Save restart info
51 * Save state of clients
52 * Send DELETE to all clients
53 * When no more clients are left or user hit "Exit Now", exit
55 * = With XSMP
57 * Send Shutdown request to session manager
58 * if SaveYourself message received, save state of clients
59 * if the Die message is received, exit.
62 #include "wconfig.h"
64 #include <X11/Xlib.h>
65 #include <X11/Xutil.h>
67 #ifdef XSMP_ENABLED
68 #include <X11/SM/SMlib.h>
69 #endif
71 #include <stdlib.h>
72 #include <stdio.h>
73 #include <string.h>
74 #include <unistd.h>
75 #include <time.h>
78 #include "WindowMaker.h"
79 #include "screen.h"
80 #include "window.h"
81 #include "client.h"
82 #include "session.h"
83 #include "wcore.h"
84 #include "framewin.h"
85 #include "workspace.h"
86 #include "funcs.h"
87 #include "properties.h"
88 #include "application.h"
89 #include "appicon.h"
92 #include "dock.h"
95 #include <proplist.h>
97 /** Global **/
99 extern Atom _XA_WM_SAVE_YOURSELF;
101 extern Time LastTimestamp;
103 #ifdef XSMP_ENABLED
105 extern int wScreenCount;
107 /* requested for SaveYourselfPhase2 */
108 static Bool sWaitingPhase2 = False;
110 static SmcConn sSMCConn = NULL;
112 static WMHandlerID sSMInputHandler = NULL;
114 /* our SM client ID */
115 static char *sClientID = NULL;
116 #endif
119 static proplist_t sApplications = NULL;
120 static proplist_t sCommand;
121 static proplist_t sName;
122 static proplist_t sHost;
123 static proplist_t sWorkspace;
124 static proplist_t sShaded;
125 static proplist_t sMiniaturized;
126 static proplist_t sHidden;
127 static proplist_t sGeometry;
128 static proplist_t sShortcutMask;
130 static proplist_t sDock;
132 static proplist_t sYes, sNo;
135 static void
136 make_keys()
138 if (sApplications!=NULL)
139 return;
141 sApplications = PLMakeString("Applications");
142 sCommand = PLMakeString("Command");
143 sName = PLMakeString("Name");
144 sHost = PLMakeString("Host");
145 sWorkspace = PLMakeString("Workspace");
146 sShaded = PLMakeString("Shaded");
147 sMiniaturized = PLMakeString("Miniaturized");
148 sHidden = PLMakeString("Hidden");
149 sGeometry = PLMakeString("Geometry");
150 sDock = PLMakeString("Dock");
151 sShortcutMask = PLMakeString("ShortcutMask");
153 sYes = PLMakeString("Yes");
154 sNo = PLMakeString("No");
159 static int
160 getBool(proplist_t value)
162 char *val;
164 if (!PLIsString(value)) {
165 return 0;
167 if (!(val = PLGetString(value))) {
168 return 0;
171 if ((val[1]=='\0' && (val[0]=='y' || val[0]=='Y'))
172 || strcasecmp(val, "YES")==0) {
174 return 1;
175 } else if ((val[1]=='\0' && (val[0]=='n' || val[0]=='N'))
176 || strcasecmp(val, "NO")==0) {
177 return 0;
178 } else {
179 int i;
180 if (sscanf(val, "%i", &i)==1) {
181 return (i!=0);
182 } else {
183 wwarning(_("can't convert \"%s\" to boolean"), val);
184 return 0;
190 static unsigned
191 getInt(proplist_t value)
193 char *val;
194 unsigned n;
196 if (!PLIsString(value))
197 return 0;
198 val = PLGetString(value);
199 if (!val)
200 return 0;
201 if (sscanf(val, "%u", &n) != 1)
202 return 0;
204 return n;
209 static proplist_t
210 makeWindowState(WWindow *wwin, WApplication *wapp)
212 WScreen *scr = wwin->screen_ptr;
213 Window win;
214 int argc;
215 char **argv;
216 int i;
217 unsigned mask;
218 char *class, *instance, *command=NULL, buffer[512];
219 proplist_t win_state, cmd, name, workspace;
220 proplist_t shaded, miniaturized, hidden, geometry;
221 proplist_t dock, shortcut;
223 if (wwin->main_window!=None && wwin->main_window!=wwin->client_win)
224 win = wwin->main_window;
225 else
226 win = wwin->client_win;
228 if (XGetCommand(dpy, win, &argv, &argc) && argc>0) {
229 command = wtokenjoin(argv, argc);
230 XFreeStringList(argv);
232 if (!command)
233 return NULL;
235 if (PropGetWMClass(win, &class, &instance)) {
236 if (class && instance)
237 snprintf(buffer, sizeof(buffer), "%s.%s", instance, class);
238 else if (instance)
239 snprintf(buffer, sizeof(buffer), "%s", instance);
240 else if (class)
241 snprintf(buffer, sizeof(buffer), ".%s", class);
242 else
243 snprintf(buffer, sizeof(buffer), ".");
245 name = PLMakeString(buffer);
246 cmd = PLMakeString(command);
247 /*sprintf(buffer, "%d", wwin->frame->workspace+1);
248 workspace = PLMakeString(buffer);*/
249 workspace = PLMakeString(scr->workspaces[wwin->frame->workspace]->name);
250 shaded = wwin->flags.shaded ? sYes : sNo;
251 miniaturized = wwin->flags.miniaturized ? sYes : sNo;
252 hidden = wwin->flags.hidden ? sYes : sNo;
253 snprintf(buffer, sizeof(buffer), "%ix%i+%i+%i",
254 wwin->client.width, wwin->client.height,
255 wwin->frame_x, wwin->frame_y);
256 geometry = PLMakeString(buffer);
258 for (mask = 0, i = 0; i < MAX_WINDOW_SHORTCUTS; i++) {
259 if (scr->shortcutWindows[i] != NULL &&
260 WMGetFirstInArray(scr->shortcutWindows[i], wwin) != WANotFound) {
261 mask |= 1<<i;
265 snprintf(buffer, sizeof(buffer), "%u", mask);
266 shortcut = PLMakeString(buffer);
268 win_state = PLMakeDictionaryFromEntries(sName, name,
269 sCommand, cmd,
270 sWorkspace, workspace,
271 sShaded, shaded,
272 sMiniaturized, miniaturized,
273 sHidden, hidden,
274 sShortcutMask, shortcut,
275 sGeometry, geometry,
276 NULL);
278 PLRelease(name);
279 PLRelease(cmd);
280 PLRelease(workspace);
281 PLRelease(geometry);
282 PLRelease(shortcut);
283 if (wapp && wapp->app_icon && wapp->app_icon->dock) {
284 int i;
285 char *name;
286 if (wapp->app_icon->dock == scr->dock) {
287 name="Dock";
288 } else {
289 for(i=0; i<scr->workspace_count; i++)
290 if(scr->workspaces[i]->clip == wapp->app_icon->dock)
291 break;
292 assert( i < scr->workspace_count);
293 /*n = i+1;*/
294 name = scr->workspaces[i]->name;
296 dock = PLMakeString(name);
297 PLInsertDictionaryEntry(win_state, sDock, dock);
298 PLRelease(dock);
300 } else {
301 win_state = NULL;
304 if (instance) XFree(instance);
305 if (class) XFree(class);
306 if (command) wfree(command);
308 return win_state;
312 void
313 wSessionSaveState(WScreen *scr)
315 WWindow *wwin = scr->focused_window;
316 proplist_t win_info, wks;
317 proplist_t list=NULL;
318 WMArray *wapp_list=NULL;
321 make_keys();
323 if (!scr->session_state) {
324 scr->session_state = PLMakeDictionaryFromEntries(NULL, NULL, NULL);
325 if (!scr->session_state)
326 return;
329 list = PLMakeArrayFromElements(NULL);
331 wapp_list = WMCreateArray(16);
333 while (wwin) {
334 WApplication *wapp=wApplicationOf(wwin->main_window);
336 if (wwin->transient_for==None
337 && WMGetFirstInArray(wapp_list, wapp)==WANotFound
338 && !WFLAGP(wwin, dont_save_session)) {
339 /* A entry for this application was not yet saved. Save one. */
340 if ((win_info = makeWindowState(wwin, wapp))!=NULL) {
341 list = PLAppendArrayElement(list, win_info);
342 PLRelease(win_info);
343 /* If we were succesful in saving the info for this window
344 * add the application the window belongs to, to the
345 * application list, so no multiple entries for the same
346 * application are saved.
348 WMAddToArray(wapp_list, wapp);
351 wwin = wwin->prev;
353 PLRemoveDictionaryEntry(scr->session_state, sApplications);
354 PLInsertDictionaryEntry(scr->session_state, sApplications, list);
355 PLRelease(list);
357 wks = PLMakeString(scr->workspaces[scr->current_workspace]->name);
358 PLInsertDictionaryEntry(scr->session_state, sWorkspace, wks);
359 PLRelease(wks);
361 WMFreeArray(wapp_list);
365 void
366 wSessionClearState(WScreen *scr)
368 make_keys();
370 if (!scr->session_state)
371 return;
373 PLRemoveDictionaryEntry(scr->session_state, sApplications);
374 PLRemoveDictionaryEntry(scr->session_state, sWorkspace);
378 static pid_t
379 execCommand(WScreen *scr, char *command, char *host)
381 pid_t pid;
382 char **argv;
383 int argc;
385 wtokensplit(command, &argv, &argc);
387 if (argv==NULL) {
388 return 0;
391 if ((pid=fork())==0) {
392 char **args;
393 int i;
395 SetupEnvironment(scr);
397 args = malloc(sizeof(char*)*(argc+1));
398 if (!args)
399 exit(111);
400 for (i=0; i<argc; i++) {
401 args[i] = argv[i];
403 args[argc] = NULL;
404 execvp(argv[0], args);
405 exit(111);
407 while (argc > 0)
408 wfree(argv[--argc]);
409 wfree(argv);
410 return pid;
414 static WSavedState*
415 getWindowState(WScreen *scr, proplist_t win_state)
417 WSavedState *state = wmalloc(sizeof(WSavedState));
418 proplist_t value;
419 char *tmp;
420 unsigned mask;
421 int i;
423 memset(state, 0, sizeof(WSavedState));
424 state->workspace = -1;
425 value = PLGetDictionaryEntry(win_state, sWorkspace);
426 if (value && PLIsString(value)) {
427 tmp = PLGetString(value);
428 if (sscanf(tmp, "%i", &state->workspace)!=1) {
429 state->workspace = -1;
430 for (i=0; i < scr->workspace_count; i++) {
431 if (strcmp(scr->workspaces[i]->name, tmp)==0) {
432 state->workspace = i;
433 break;
436 } else {
437 state->workspace--;
440 if ((value = PLGetDictionaryEntry(win_state, sShaded))!=NULL)
441 state->shaded = getBool(value);
442 if ((value = PLGetDictionaryEntry(win_state, sMiniaturized))!=NULL)
443 state->miniaturized = getBool(value);
444 if ((value = PLGetDictionaryEntry(win_state, sHidden))!=NULL)
445 state->hidden = getBool(value);
446 if ((value = PLGetDictionaryEntry(win_state, sShortcutMask))!=NULL) {
447 mask = getInt(value);
448 state->window_shortcuts = mask;
451 value = PLGetDictionaryEntry(win_state, sGeometry);
452 if (value && PLIsString(value)) {
453 if (!(sscanf(PLGetString(value), "%ix%i+%i+%i",
454 &state->w, &state->h, &state->x, &state->y)==4 &&
455 (state->w>0 && state->h>0))) {
456 state->w = 0;
457 state->h = 0;
461 return state;
465 #define SAME(x, y) (((x) && (y) && !strcmp((x), (y))) || (!(x) && !(y)))
467 void
468 wSessionRestoreState(WScreen *scr)
470 WSavedState *state;
471 char *instance, *class, *command, *host;
472 proplist_t win_info, apps, cmd, value;
473 pid_t pid;
474 int i, count;
475 WDock *dock;
476 WAppIcon *btn=NULL;
477 int j, n, found;
478 char *tmp;
480 make_keys();
482 if (!scr->session_state)
483 return;
485 PLSetStringCmpHook(NULL);
487 apps = PLGetDictionaryEntry(scr->session_state, sApplications);
488 if (!apps)
489 return;
491 count = PLGetNumberOfElements(apps);
492 if (count==0)
493 return;
495 for (i=0; i<count; i++) {
496 win_info = PLGetArrayElement(apps, i);
498 cmd = PLGetDictionaryEntry(win_info, sCommand);
499 if (!cmd || !PLIsString(cmd) || !(command = PLGetString(cmd))) {
500 continue;
503 value = PLGetDictionaryEntry(win_info, sName);
504 if (!value)
505 continue;
507 ParseWindowName(value, &instance, &class, "session");
508 if (!instance && !class)
509 continue;
511 value = PLGetDictionaryEntry(win_info, sHost);
512 if (value && PLIsString(value))
513 host = PLGetString(value);
514 else
515 host = NULL;
517 state = getWindowState(scr, win_info);
519 dock = NULL;
520 value = PLGetDictionaryEntry(win_info, sDock);
521 if (value && PLIsString(value) && (tmp = PLGetString(value))!=NULL) {
522 if (sscanf(tmp, "%i", &n)!=1) {
523 if (!strcasecmp(tmp, "DOCK")) {
524 dock = scr->dock;
525 } else {
526 for (j=0; j < scr->workspace_count; j++) {
527 if (strcmp(scr->workspaces[j]->name, tmp)==0) {
528 dock = scr->workspaces[j]->clip;
529 break;
533 } else {
534 if (n == 0) {
535 dock = scr->dock;
536 } else if (n>0 && n<=scr->workspace_count) {
537 dock = scr->workspaces[n-1]->clip;
542 found = 0;
543 if (dock!=NULL) {
544 for (j=0; j<dock->max_icons; j++) {
545 btn = dock->icon_array[j];
546 if (btn && SAME(instance, btn->wm_instance) &&
547 SAME(class, btn->wm_class) &&
548 SAME(command, btn->command) &&
549 !btn->launching) {
550 found = 1;
551 break;
556 if (found) {
557 wDockLaunchWithState(dock, btn, state);
558 } else if ((pid = execCommand(scr, command, host)) > 0) {
559 wWindowAddSavedState(instance, class, command, pid, state);
560 } else {
561 wfree(state);
564 if (instance) wfree(instance);
565 if (class) wfree(class);
567 /* clean up */
568 PLSetStringCmpHook(StringCompareHook);
572 void
573 wSessionRestoreLastWorkspace(WScreen *scr)
575 proplist_t wks;
576 int w, i;
577 char *tmp;
579 make_keys();
581 if (!scr->session_state)
582 return;
584 PLSetStringCmpHook(NULL);
586 wks = PLGetDictionaryEntry(scr->session_state, sWorkspace);
587 if (!wks || !PLIsString(wks))
588 return;
590 tmp = PLGetString(wks);
592 /* clean up */
593 PLSetStringCmpHook(StringCompareHook);
595 if (sscanf(tmp, "%i", &w)!=1) {
596 w = -1;
597 for (i=0; i < scr->workspace_count; i++) {
598 if (strcmp(scr->workspaces[i]->name, tmp)==0) {
599 w = i;
600 break;
603 } else {
604 w--;
607 if (w!=scr->current_workspace && w<scr->workspace_count) {
608 wWorkspaceChange(scr, w);
613 static void
614 clearWaitingAckState(WScreen *scr)
616 WWindow *wwin;
617 WApplication *wapp;
619 for (wwin = scr->focused_window; wwin != NULL; wwin = wwin->prev) {
620 wwin->flags.waiting_save_ack = 0;
621 if (wwin->main_window != None) {
622 wapp = wApplicationOf(wwin->main_window);
623 if (wapp)
624 wapp->main_window_desc->flags.waiting_save_ack = 0;
630 void
631 wSessionSaveClients(WScreen *scr)
638 * With XSMP, this job is done by smproxy
640 void
641 wSessionSendSaveYourself(WScreen *scr)
643 WWindow *wwin;
644 int count;
646 /* freeze client interaction with clients */
647 XGrabKeyboard(dpy, scr->root_win, False, GrabModeAsync, GrabModeAsync,
648 CurrentTime);
649 XGrabPointer(dpy, scr->root_win, False, ButtonPressMask|ButtonReleaseMask,
650 GrabModeAsync, GrabModeAsync, scr->root_win, None,
651 CurrentTime);
653 clearWaitingAckState(scr);
655 count = 0;
657 /* first send SAVE_YOURSELF for everybody */
658 for (wwin = scr->focused_window; wwin != NULL; wwin = wwin->prev) {
659 WWindow *mainWin;
661 mainWin = wWindowFor(wwin->main_window);
663 if (mainWin) {
664 /* if the client is a multi-window client, only send message
665 * to the main window */
666 wwin = mainWin;
669 /* make sure the SAVE_YOURSELF flag is up-to-date */
670 PropGetProtocols(wwin->client_win, &wwin->protocols);
672 if (wwin->protocols.SAVE_YOURSELF) {
673 if (!wwin->flags.waiting_save_ack) {
674 wClientSendProtocol(wwin, _XA_WM_SAVE_YOURSELF, LastTimestamp);
676 wwin->flags.waiting_save_ack = 1;
677 count++;
679 } else {
680 wwin->flags.waiting_save_ack = 0;
684 /* then wait for acknowledge */
685 while (count > 0) {
689 XUngrabPointer(dpy, CurrentTime);
690 XUngrabKeyboard(dpy, CurrentTime);
691 XFlush(dpy);
695 #ifdef XSMP_ENABLED
697 * With full session management support, the part of WMState
698 * that store client window state will become obsolete (maybe we can reuse
699 * the old code too),
700 * but we still need to store state info like the dock and workspaces.
701 * It is better to keep dock/wspace info in WMState because the user
702 * might want to keep the dock configuration while not wanting to
703 * resume a previously saved session.
704 * So, wmaker specific state info can be saved in
705 * ~/GNUstep/.AppInfo/WindowMaker/statename.state
706 * Its better to not put it in the defaults directory because:
707 * - its not a defaults file (having domain names like wmaker0089504baa
708 * in the defaults directory wouldn't be very neat)
709 * - this state file is not meant to be edited by users
711 * The old session code will become obsolete. When wmaker is
712 * compiled with R6 sm support compiled in, itll be better to
713 * use a totally rewritten state saving code, but we can keep
714 * the current code for when XSMP_ENABLED is not compiled in.
716 * This will be confusing to old users (well get lots of "SAVE_SESSION broke!"
717 * messages), but itll be better.
719 * -readme
723 static char*
724 getWindowRole(Window window)
726 XTextProperty prop;
727 static Atom atom = 0;
729 if (!atom)
730 atom = XInternAtom(dpy, "WM_WINDOW_ROLE", False);
732 if (XGetTextProperty(dpy, window, &prop, atom)) {
733 if (prop.encoding == XA_STRING && prop.format == 8 && prop.nitems > 0)
734 return prop.value;
737 return NULL;
743 * Saved Info:
745 * WM_WINDOW_ROLE
747 * WM_CLASS.instance
748 * WM_CLASS.class
749 * WM_NAME
750 * WM_COMMAND
752 * geometry
753 * state = (miniaturized, shaded, etc)
754 * attribute
755 * workspace #
756 * app state = (which dock, hidden)
757 * window shortcut #
760 static proplist_t
761 makeAppState(WWindow *wwin)
763 WApplication *wapp;
764 proplist_t state;
765 WScreen *scr = wwin->screen_ptr;
767 state = PLMakeArrayWithElements(NULL, NULL);
769 wapp = wApplicationOf(wwin->main_window);
771 if (wapp) {
772 if (wapp->app_icon && wapp->app_icon->dock) {
774 if (wapp->app_icon->dock == scr->dock) {
775 PLAppendArrayElement(state, PLMakeString("Dock"));
776 } else {
777 int i;
779 for(i=0; i<scr->workspace_count; i++)
780 if(scr->workspaces[i]->clip == wapp->app_icon->dock)
781 break;
783 assert(i < scr->workspace_count);
785 PLAppendArrayElement(state,
786 PLMakeString(scr->workspaces[i]->name));
790 PLAppendArrayElement(state, PLMakeString(wapp->hidden ? "1" : "0"));
793 return state;
798 Bool
799 wSessionGetStateFor(WWindow *wwin, WSessionData *state)
801 char *str;
802 proplist_t slist;
803 proplist_t elem;
804 proplist_t value;
805 int index = 0;
807 index = 3;
809 /* geometry */
810 value = PLGetArrayElement(slist, index++);
811 str = PLGetString(value);
813 sscanf(str, "%i %i %i %i %i %i", &state->x, &state->y,
814 &state->width, &state->height,
815 &state->user_changed_width, &state->user_changed_height);
818 /* state */
819 value = PLGetArrayElement(slist, index++);
820 str = PLGetString(value);
822 sscanf(str, "%i %i %i", &state->miniaturized, &state->shaded,
823 &state->maximized);
826 /* attributes */
827 value = PLGetArrayElement(slist, index++);
828 str = PLGetString(value);
830 getAttributeState(str, &state->mflags, &state->flags);
833 /* workspace */
834 value = PLGetArrayElement(slist, index++);
835 str = PLGetString(value);
837 sscanf(str, "%i", &state->workspace);
840 /* app state (repeated for all windows of the app) */
841 value = PLGetArrayElement(slist, index++);
842 str = PLGetString(value);
844 /* ???? */
846 /* shortcuts */
847 value = PLGetArrayElement(slist, index++);
848 str = PLGetString(value);
850 sscanf(str, "%i", &state->shortcuts);
855 static proplist_t
856 makeAttributeState(WWindow *wwin)
858 unsigned int data1, data2;
859 char buffer[256];
861 #define W_FLAG(wwin, FLAG) ((wwin)->defined_user_flags.FLAG \
862 ? (wwin)->user_flags.FLAG : -1)
864 snprintf(buffer, sizeof(buffer),
865 "%i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i",
866 W_FLAG(no_titlebar),
867 W_FLAG(no_resizable),
868 W_FLAG(no_closable),
869 W_FLAG(no_miniaturizable),
870 W_FLAG(no_resizebar),
871 W_FLAG(no_close_button),
872 W_FLAG(no_miniaturize_button),
874 W_FLAG(broken_close),
875 W_FLAG(kill_close),
877 W_FLAG(no_shadeable),
878 W_FLAG(omnipresent),
879 W_FLAG(skip_window_list),
880 W_FLAG(floating),
881 W_FLAG(sunken),
882 W_FLAG(no_bind_keys),
883 W_FLAG(no_bind_mouse),
884 W_FLAG(no_hide_others),
885 W_FLAG(no_appicon),
886 W_FLAG(dont_move_off),
887 W_FLAG(no_focusable),
888 W_FLAG(always_user_icon),
889 W_FLAG(start_miniaturized),
890 W_FLAG(start_hidden),
891 W_FLAG(start_maximized),
892 W_FLAG(dont_save_session),
893 W_FLAG(emulate_appicon));
895 return PLMakeString(buffer);
899 static void
900 appendStringInArray(proplist_t array, char *str)
902 proplist_t val;
904 val = PLMakeString(str);
905 PLAppendArrayElement(array, val);
906 PLRelease(val);
910 static proplist_t
911 makeClientState(WWindow *wwin)
913 proplist_t state;
914 proplist_t tmp;
915 char *str;
916 char buffer[512];
917 int i;
918 unsigned shortcuts;
920 state = PLMakeArrayWithElements(NULL, NULL);
922 /* WM_WINDOW_ROLE */
923 str = getWindowRole(wwin->client_win);
924 if (!str)
925 appendStringInArray(state, "");
926 else {
927 appendStringInArray(state, str);
928 XFree(str);
931 /* WM_CLASS.instance */
932 appendStringInArray(state, wwin->wm_instance);
934 /* WM_CLASS.class */
935 appendStringInArray(state, wwin->wm_class);
937 /* WM_NAME */
938 if (wwin->flags.wm_name_changed)
939 appendStringInArray(state, "");
940 else
941 appendStringInArray(state, wwin->frame->name);
943 /* geometry */
944 snprintf(buffer, sizeof(buffer), "%i %i %i %i %i %i", wwin->frame_x, wwin->frame_y,
945 wwin->client.width, wwin->client.height,
946 wwin->flags.user_changed_width, wwin->flags.user_changed_height);
947 appendStringInArray(state, buffer);
949 /* state */
950 snprintf(buffer, sizeof(buffer), "%i %i %i", wwin->flags.miniaturized,
951 wwin->flags.shaded, wwin->flags.maximized);
952 appendStringInArray(state, buffer);
954 /* attributes */
955 tmp = makeAttributeState(wwin);
956 PLAppendArrayElement(state, tmp);
957 PLRelease(tmp);
959 /* workspace */
960 snprintf(buffer, sizeof(buffer), "%i", wwin->frame->workspace);
961 appendStringInArray(state, buffer);
963 /* app state (repeated for all windows of the app) */
964 tmp = makeAppState(wwin);
965 PLAppendArrayElement(state, tmp);
966 PLRelease(tmp);
968 /* shortcuts */
969 shortcuts = 0;
970 for (i = 0; i < MAX_WINDOW_SHORTCUTS; i++) {
971 if (scr->shortcutWindow[i] == wwin) {
972 shortcuts |= 1 << i;
975 snprintf(buffer, sizeof(buffer), "%ui", shortcuts);
976 appendStringInArray(tmp, buffer);
978 return state;
982 static void
983 smSaveYourselfPhase2Proc(SmcConn smc_conn, SmPointer client_data)
985 SmProp props[4];
986 SmPropValue prop1val, prop2val, prop3val, prop4val;
987 char **argv = (char**)client_data;
988 int argc;
989 int i, j;
990 Bool ok = False;
991 char *statefile = NULL;
992 char *prefix;
993 Bool gsPrefix = False;
994 char *discardCmd = NULL;
995 time_t t;
996 proplist_t state;
997 int len;
999 #ifdef DEBUG1
1000 puts("received SaveYourselfPhase2 SM message");
1001 #endif
1003 /* save session state */
1005 /* the file that will contain the state */
1006 prefix = getenv("SM_SAVE_DIR");
1007 if (!prefix) {
1008 prefix = wusergnusteppath();
1009 if (prefix)
1010 gsPrefix = True;
1012 if (!prefix) {
1013 prefix = getenv("HOME");
1015 if (!prefix)
1016 prefix = ".";
1018 len = strlen(prefix)+64;
1019 statefile = malloc(len);
1020 if (!statefile) {
1021 wwarning(_("out of memory while saving session state"));
1022 goto fail;
1025 t = time();
1026 i = 0;
1027 do {
1028 if (gsPrefix)
1029 snprintf(statefile, len, "%s/.AppInfo/WindowMaker/wmaker.%l%i.state",
1030 prefix, t, i);
1031 else
1032 snprintf(statefile, len, "%s/wmaker.%l%i.state", prefix, t, i);
1033 i++;
1034 } while (access(F_OK, statefile)!=-1);
1036 /* save the states of all windows we're managing */
1037 state = PLMakeArrayFromElements(NULL, NULL);
1040 * Format:
1042 * state_file ::= dictionary with version_info ; state
1043 * version_info ::= 'version' = '1';
1044 * state ::= 'state' = array of screen_info
1045 * screen_info ::= array of (screen number, window_info, window_info, ...)
1046 * window_info ::=
1048 for (i=0; i<wScreenCount; i++) {
1049 WScreen *scr;
1050 WWindow *wwin;
1051 char buf[32];
1052 proplist_t pscreen;
1054 scr = wScreenWithNumber(i);
1056 snprintf(buf, sizeof(buf), "%i", scr->screen);
1057 pscreen = PLMakeArrayFromElements(PLMakeString(buf), NULL);
1059 wwin = scr->focused_window;
1060 while (wwin) {
1061 proplist_t pwindow;
1063 pwindow = makeClientState(wwin);
1064 PLAppendArrayElement(pscreen, pwindow);
1066 wwin = wwin->prev;
1069 PLAppendArrayElement(state, pscreen);
1073 proplist_t statefile;
1075 statefile = PLMakeDictionaryFromEntries(PLMakeString("Version"),
1076 PLMakeString("1.0"),
1078 PLMakeString("Screens"),
1079 state,
1081 NULL);
1083 PLSetFilename(statefile, PLMakeString(statefile));
1084 PLSave(statefile, NO);
1086 PLRelease(statefile);
1089 /* set the remaining properties that we didn't set at
1090 * startup time */
1092 for (argc=0, i=0; argv[i]!=NULL; i++) {
1093 if (strcmp(argv[i], "-clientid")==0
1094 || strcmp(argv[i], "-restore")==0) {
1095 i++;
1096 } else {
1097 argc++;
1101 prop[0].name = SmRestartCommand;
1102 prop[0].type = SmLISTofARRAY8;
1103 prop[0].vals = malloc(sizeof(SmPropValue)*(argc+4));
1104 prop[0].num_vals = argc+4;
1106 prop[1].name = SmCloneCommand;
1107 prop[1].type = SmLISTofARRAY8;
1108 prop[1].vals = malloc(sizeof(SmPropValue)*(argc));
1109 prop[1].num_vals = argc;
1111 if (!prop[0].vals || !prop[1].vals) {
1112 wwarning(_("end of memory while saving session state"));
1113 goto fail;
1116 for (j=0, i=0; i<argc+4; i++) {
1117 if (strcmp(argv[i], "-clientid")==0
1118 || strcmp(argv[i], "-restore")==0) {
1119 i++;
1120 } else {
1121 prop[0].vals[j].value = argv[i];
1122 prop[0].vals[j].length = strlen(argv[i]);
1123 prop[1].vals[j].value = argv[i];
1124 prop[1].vals[j].length = strlen(argv[i]);
1125 j++;
1128 prop[0].vals[j].value = "-clientid";
1129 prop[0].vals[j].length = 9;
1130 j++;
1131 prop[0].vals[j].value = sClientID;
1132 prop[0].vals[j].length = strlen(sClientID);
1133 j++;
1134 prop[0].vals[j].value = "-restore";
1135 prop[0].vals[j].length = 11;
1136 j++;
1137 prop[0].vals[j].value = statefile;
1138 prop[0].vals[j].length = strlen(statefile);
1141 int len = strlen(statefile)+8;
1143 discardCmd = malloc(len);
1144 if (!discardCmd)
1145 goto fail;
1146 snprintf(discardCmd, len, "rm %s", statefile);
1148 prop[2].name = SmDiscardCommand;
1149 prop[2].type = SmARRAY8;
1150 prop[2].vals[0] = discardCmd;
1151 prop[2].num_vals = 1;
1153 SmcSetProperties(sSMCConn, 3, prop);
1155 ok = True;
1156 fail:
1157 SmcSaveYourselfDone(smc_conn, ok);
1159 if (prop[0].vals)
1160 wfree(prop[0].vals);
1161 if (prop[1].vals)
1162 wfree(prop[1].vals);
1163 if (discardCmd)
1164 wfree(discardCmd);
1166 if (!ok) {
1167 remove(statefile);
1169 if (statefile)
1170 wfree(statefile);
1174 static void
1175 smSaveYourselfProc(SmcConn smc_conn, SmPointer client_data, int save_type,
1176 Bool shutdown, int interact_style, Bool fast)
1178 #ifdef DEBUG1
1179 puts("received SaveYourself SM message");
1180 #endif
1182 if (!SmcRequestSaveYourselfPhase2(smc_conn, smSaveYourselfPhase2Proc,
1183 client_data)) {
1185 SmcSaveYourselfDone(smc_conn, False);
1186 sWaitingPhase2 = False;
1187 } else {
1188 #ifdef DEBUG1
1189 puts("successfull request of SYS phase 2");
1190 #endif
1191 sWaitingPhase2 = True;
1196 static void
1197 smDieProc(SmcConn smc_conn, SmPointer client_data)
1199 #ifdef DEBUG1
1200 puts("received Die SM message");
1201 #endif
1203 wSessionDisconnectManager();
1205 Shutdown(WSExitMode, True);
1210 static void
1211 smSaveCompleteProc(SmcConn smc_conn)
1213 /* it means that we can resume doing things that can change our state */
1214 #ifdef DEBUG1
1215 puts("received SaveComplete SM message");
1216 #endif
1220 static void
1221 smShutdownCancelledProc(SmcConn smc_conn, SmPointer client_data)
1223 if (sWaitingPhase2) {
1225 sWaitingPhase2 = False;
1227 SmcSaveYourselfDone(smc_conn, False);
1232 static void
1233 iceMessageProc(int fd, int mask, void *clientData)
1235 IceConn iceConn = (IceConn)clientData;
1237 IceProcessMessages(iceConn, NULL, NULL);
1241 static void
1242 iceIOErrorHandler(IceConnection ice_conn)
1244 /* This is not fatal but can mean the session manager exited.
1245 * If the session manager exited normally we would get a
1246 * Die message, so this probably means an abnormal exit.
1247 * If the sm was the last client of session, then we'll die
1248 * anyway, otherwise we can continue doing our stuff.
1250 wwarning(_("connection to the session manager was lost"));
1251 wSessionDisconnectManager();
1255 void
1256 wSessionConnectManager(char **argv, int argc)
1258 IceConn iceConn;
1259 char *previous_id = NULL;
1260 char buffer[256];
1261 SmcCallbacks callbacks;
1262 unsigned long mask;
1263 char uid[32];
1264 char pid[32];
1265 SmProp props[4];
1266 SmPropValue prop1val, prop2val, prop3val, prop4val;
1267 char restartStyle;
1268 int i;
1270 mask = SmcSaveYourselfProcMask|SmcDieProcMask|SmcSaveCompleteProcMask
1271 |SmcShutdownCancelledProcMask;
1273 callbacks.save_yourself.callback = smSaveYourselfProc;
1274 callbacks.save_yourself.client_data = argv;
1276 callbacks.die.callback = smDieProc;
1277 callbacks.die.client_data = NULL;
1279 callbacks.save_complete.callback = smSaveCompleteProc;
1280 callbacks.save_complete.client_data = NULL;
1282 callbacks.shutdown_cancelled.callback = smShutdownCancelledProc;
1283 callbacks.shutdown_cancelled.client_data = NULL;
1285 for (i=0; i<argc; i++) {
1286 if (strcmp(argv[i], "-clientid")==0) {
1287 previous_id = argv[i+1];
1288 break;
1292 /* connect to the session manager */
1293 sSMCConn = SmcOpenConnection(NULL, NULL, SmProtoMajor, SmProtoMinor,
1294 mask, &callbacks, previous_id,
1295 &sClientID, 255, buffer);
1296 if (!sSMCConn) {
1297 return;
1299 #ifdef DEBUG1
1300 puts("connected to the session manager");
1301 #endif
1303 /* IceSetIOErrorHandler(iceIOErrorHandler);*/
1305 /* check for session manager clients */
1306 iceConn = SmcGetIceConnection(smcConn);
1308 if (fcntl(IceConnectionNumber(iceConn), F_SETFD, FD_CLOEXEC) < 0) {
1309 wsyserror("error setting close-on-exec flag for ICE connection");
1312 sSMInputHandler = WMAddInputHandler(IceConnectionNumber(iceConn),
1313 WIReadMask, iceMessageProc, iceConn);
1315 /* setup information about ourselves */
1317 /* program name */
1318 prop1val.value = argv[0];
1319 prop1val.length = strlen(argv[0]);
1320 prop[0].name = SmProgram;
1321 prop[0].type = SmARRAY8;
1322 prop[0].num_vals = 1;
1323 prop[0].vals = &prop1val;
1325 /* The XSMP doc from X11R6.1 says it contains the user name,
1326 * but every client implementation I saw places the uid # */
1327 snprintf(uid, sizeof(uid), "%i", getuid());
1328 prop2val.value = uid;
1329 prop2val.length = strlen(uid);
1330 prop[1].name = SmUserID;
1331 prop[1].type = SmARRAY8;
1332 prop[1].num_vals = 1;
1333 prop[1].vals = &prop2val;
1335 /* Restart style. We should restart only if we were running when
1336 * the previous session finished. */
1337 restartStyle = SmRestartIfRunning;
1338 prop3val.value = &restartStyle;
1339 prop3val.length = 1;
1340 prop[2].name = SmRestartStyleHint;
1341 prop[2].type = SmCARD8;
1342 prop[2].num_vals = 1;
1343 prop[2].vals = &prop3val;
1345 /* Our PID. Not required but might be usefull */
1346 snprintf(pid, sizeof(pid), "%i", getpid());
1347 prop4val.value = pid;
1348 prop4val.length = strlen(pid);
1349 prop[3].name = SmProcessID;
1350 prop[3].type = SmARRAY8;
1351 prop[3].num_vals = 1;
1352 prop[3].vals = &prop4val;
1354 /* we'll set the rest of the hints later */
1356 SmcSetProperties(sSMCConn, 4, props);
1361 void
1362 wSessionDisconnectManager(void)
1364 if (sSMCConn) {
1365 WMDeleteInputHandler(sSMInputHandler);
1366 sSMInputHandler = NULL;
1368 SmcCloseConnection(sSMCConn, 0, NULL);
1369 sSMCConn = NULL;
1373 void
1374 wSessionRequestShutdown(void)
1376 /* request a shutdown to the session manager */
1377 if (sSMCConn)
1378 SmcRequestSaveYourself(sSMCConn, SmSaveBoth, True, SmInteractStyleAny,
1379 False, True);
1383 Bool
1384 wSessionIsManaged(void)
1386 return sSMCConn!=NULL;
1389 #endif /* !XSMP_ENABLED */