Fixed crashing bug on restart/exit/save session.
[wmaker-crm.git] / src / session.c
blob8208234ca5e34f703890831e59c69361b58c2507
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;
129 static proplist_t sDock;
131 static proplist_t sYes, sNo;
134 static void
135 make_keys()
137 if (sApplications!=NULL)
138 return;
140 sApplications = PLMakeString("Applications");
141 sCommand = PLMakeString("Command");
142 sName = PLMakeString("Name");
143 sHost = PLMakeString("Host");
144 sWorkspace = PLMakeString("Workspace");
145 sShaded = PLMakeString("Shaded");
146 sMiniaturized = PLMakeString("Miniaturized");
147 sHidden = PLMakeString("Hidden");
148 sGeometry = PLMakeString("Geometry");
149 sDock = PLMakeString("Dock");
151 sYes = PLMakeString("Yes");
152 sNo = PLMakeString("No");
157 static int
158 getBool(proplist_t value)
160 char *val;
162 if (!PLIsString(value)) {
163 return 0;
165 if (!(val = PLGetString(value))) {
166 return 0;
169 if ((val[1]=='\0' && (val[0]=='y' || val[0]=='Y'))
170 || strcasecmp(val, "YES")==0) {
172 return 1;
173 } else if ((val[1]=='\0' && (val[0]=='n' || val[0]=='N'))
174 || strcasecmp(val, "NO")==0) {
175 return 0;
176 } else {
177 int i;
178 if (sscanf(val, "%i", &i)==1) {
179 return (i!=0);
180 } else {
181 wwarning(_("can't convert \"%s\" to boolean"), val);
182 return 0;
189 static proplist_t
190 makeWindowState(WWindow *wwin, WApplication *wapp)
192 WScreen *scr = wwin->screen_ptr;
193 Window win;
194 int argc;
195 char **argv;
196 char *class, *instance, *command=NULL, buffer[256];
197 proplist_t win_state, cmd, name, workspace;
198 proplist_t shaded, miniaturized, hidden, geometry;
199 proplist_t dock;
201 if (wwin->main_window!=None && wwin->main_window!=wwin->client_win)
202 win = wwin->main_window;
203 else
204 win = wwin->client_win;
206 if (XGetCommand(dpy, win, &argv, &argc) && argc>0) {
207 command = FlattenStringList(argv, argc);
208 XFreeStringList(argv);
210 if (!command)
211 return NULL;
213 if (PropGetWMClass(win, &class, &instance)) {
214 if (class && instance)
215 sprintf(buffer, "%s.%s", instance, class);
216 else if (instance)
217 sprintf(buffer, "%s", instance);
218 else if (class)
219 sprintf(buffer, ".%s", class);
220 else
221 sprintf(buffer, ".");
223 name = PLMakeString(buffer);
224 cmd = PLMakeString(command);
225 /*sprintf(buffer, "%d", wwin->frame->workspace+1);
226 workspace = PLMakeString(buffer);*/
227 workspace = PLMakeString(scr->workspaces[wwin->frame->workspace]->name);
228 shaded = wwin->flags.shaded ? sYes : sNo;
229 miniaturized = wwin->flags.miniaturized ? sYes : sNo;
230 hidden = wwin->flags.hidden ? sYes : sNo;
231 sprintf(buffer, "%ix%i+%i+%i", wwin->client.width, wwin->client.height,
232 wwin->frame_x, wwin->frame_y);
233 geometry = PLMakeString(buffer);
235 win_state = PLMakeDictionaryFromEntries(sName, name,
236 sCommand, cmd,
237 sWorkspace, workspace,
238 sShaded, shaded,
239 sMiniaturized, miniaturized,
240 sHidden, hidden,
241 sGeometry, geometry,
242 NULL);
244 PLRelease(name);
245 PLRelease(cmd);
246 PLRelease(workspace);
247 PLRelease(geometry);
248 if (wapp && wapp->app_icon && wapp->app_icon->dock) {
249 int i;
250 char *name;
251 if (wapp->app_icon->dock == scr->dock) {
252 name="Dock";
253 } else {
254 for(i=0; i<scr->workspace_count; i++)
255 if(scr->workspaces[i]->clip == wapp->app_icon->dock)
256 break;
257 assert( i < scr->workspace_count);
258 /*n = i+1;*/
259 name = scr->workspaces[i]->name;
261 dock = PLMakeString(name);
262 PLInsertDictionaryEntry(win_state, sDock, dock);
263 PLRelease(dock);
265 } else {
266 win_state = NULL;
269 if (instance) XFree(instance);
270 if (class) XFree(class);
271 if (command) free(command);
273 return win_state;
277 void
278 wSessionSaveState(WScreen *scr)
280 WWindow *wwin = scr->focused_window;
281 proplist_t win_info, wks;
282 proplist_t list=NULL;
283 WMBag *wapp_list=NULL;
286 make_keys();
288 if (!scr->session_state) {
289 scr->session_state = PLMakeDictionaryFromEntries(NULL, NULL, NULL);
290 if (!scr->session_state)
291 return;
294 list = PLMakeArrayFromElements(NULL);
296 wapp_list = WMCreateBag(16);
298 while (wwin) {
299 WApplication *wapp=wApplicationOf(wwin->main_window);
301 if (wwin->transient_for==None && WMGetFirstInBag(wapp_list, wapp)<0
302 && !WFLAGP(wwin, dont_save_session)) {
303 /* A entry for this application was not yet saved. Save one. */
304 if ((win_info = makeWindowState(wwin, wapp))!=NULL) {
305 list = PLAppendArrayElement(list, win_info);
306 PLRelease(win_info);
307 /* If we were succesful in saving the info for this window
308 * add the application the window belongs to, to the
309 * application list, so no multiple entries for the same
310 * application are saved.
312 WMPutInBag(wapp_list, wapp);
315 wwin = wwin->prev;
317 PLRemoveDictionaryEntry(scr->session_state, sApplications);
318 PLInsertDictionaryEntry(scr->session_state, sApplications, list);
319 PLRelease(list);
321 wks = PLMakeString(scr->workspaces[scr->current_workspace]->name);
322 PLInsertDictionaryEntry(scr->session_state, sWorkspace, wks);
323 PLRelease(wks);
325 WMFreeBag(wapp_list);
329 void
330 wSessionClearState(WScreen *scr)
332 make_keys();
334 if (!scr->session_state)
335 return;
337 PLRemoveDictionaryEntry(scr->session_state, sApplications);
338 PLRemoveDictionaryEntry(scr->session_state, sWorkspace);
342 static pid_t
343 execCommand(WScreen *scr, char *command, char *host)
345 pid_t pid;
346 char **argv;
347 int argc;
349 ParseCommand(command, &argv, &argc);
351 if (argv==NULL) {
352 return 0;
355 if ((pid=fork())==0) {
356 char **args;
357 int i;
359 SetupEnvironment(scr);
361 args = malloc(sizeof(char*)*(argc+1));
362 if (!args)
363 exit(111);
364 for (i=0; i<argc; i++) {
365 args[i] = argv[i];
367 args[argc] = NULL;
368 execvp(argv[0], args);
369 exit(111);
371 while (argc > 0)
372 free(argv[--argc]);
373 free(argv);
374 return pid;
378 static WSavedState*
379 getWindowState(WScreen *scr, proplist_t win_state)
381 WSavedState *state = wmalloc(sizeof(WSavedState));
382 proplist_t value;
383 char *tmp;
384 int i;
386 memset(state, 0, sizeof(WSavedState));
387 state->workspace = -1;
388 value = PLGetDictionaryEntry(win_state, sWorkspace);
389 if (value && PLIsString(value)) {
390 tmp = PLGetString(value);
391 if (sscanf(tmp, "%i", &state->workspace)!=1) {
392 state->workspace = -1;
393 for (i=0; i < scr->workspace_count; i++) {
394 if (strcmp(scr->workspaces[i]->name, tmp)==0) {
395 state->workspace = i;
396 break;
399 } else {
400 state->workspace--;
403 if ((value = PLGetDictionaryEntry(win_state, sShaded))!=NULL)
404 state->shaded = getBool(value);
405 if ((value = PLGetDictionaryEntry(win_state, sMiniaturized))!=NULL)
406 state->miniaturized = getBool(value);
407 if ((value = PLGetDictionaryEntry(win_state, sHidden))!=NULL)
408 state->hidden = getBool(value);
410 value = PLGetDictionaryEntry(win_state, sGeometry);
411 if (value && PLIsString(value)) {
412 if (sscanf(PLGetString(value), "%ix%i+%i+%i",
413 &state->w, &state->h, &state->x, &state->y)==4 &&
414 (state->w>0 && state->h>0)) {
415 state->use_geometry = 1;
416 } else if (sscanf(PLGetString(value), "%i,%i,%i,%i",
417 &state->x, &state->y, &state->w, &state->h)==4 &&
418 (state->w>0 && state->h>0)) {
419 /* TODO: remove redundant sscanf() in version 0.20.x */
420 state->use_geometry = 1;
425 return state;
429 #define SAME(x, y) (((x) && (y) && !strcmp((x), (y))) || (!(x) && !(y)))
431 void
432 wSessionRestoreState(WScreen *scr)
434 WSavedState *state;
435 char *instance, *class, *command, *host;
436 proplist_t win_info, apps, cmd, value;
437 pid_t pid;
438 int i, count;
439 WDock *dock;
440 WAppIcon *btn=NULL;
441 int j, n, found;
442 char *tmp;
444 make_keys();
446 if (!scr->session_state)
447 return;
449 PLSetStringCmpHook(NULL);
451 apps = PLGetDictionaryEntry(scr->session_state, sApplications);
452 if (!apps)
453 return;
455 count = PLGetNumberOfElements(apps);
456 if (count==0)
457 return;
459 for (i=0; i<count; i++) {
460 win_info = PLGetArrayElement(apps, i);
462 cmd = PLGetDictionaryEntry(win_info, sCommand);
463 if (!cmd || !PLIsString(cmd) || !(command = PLGetString(cmd))) {
464 continue;
467 value = PLGetDictionaryEntry(win_info, sName);
468 if (!value)
469 continue;
471 ParseWindowName(value, &instance, &class, "session");
472 if (!instance && !class)
473 continue;
475 value = PLGetDictionaryEntry(win_info, sHost);
476 if (value && PLIsString(value))
477 host = PLGetString(value);
478 else
479 host = NULL;
481 state = getWindowState(scr, win_info);
483 dock = NULL;
484 value = PLGetDictionaryEntry(win_info, sDock);
485 if (value && PLIsString(value) && (tmp = PLGetString(value))!=NULL) {
486 if (sscanf(tmp, "%i", &n)!=1) {
487 if (!strcasecmp(tmp, "DOCK")) {
488 dock = scr->dock;
489 } else {
490 for (j=0; j < scr->workspace_count; j++) {
491 if (strcmp(scr->workspaces[j]->name, tmp)==0) {
492 dock = scr->workspaces[j]->clip;
493 break;
497 } else {
498 if (n == 0) {
499 dock = scr->dock;
500 } else if (n>0 && n<=scr->workspace_count) {
501 dock = scr->workspaces[n-1]->clip;
506 found = 0;
507 if (dock!=NULL) {
508 for (j=0; j<dock->max_icons; j++) {
509 btn = dock->icon_array[j];
510 if (btn && SAME(instance, btn->wm_instance) &&
511 SAME(class, btn->wm_class) &&
512 SAME(command, btn->command)) {
513 found = 1;
514 break;
519 if (found) {
520 wDockLaunchWithState(dock, btn, state);
521 } else if ((pid = execCommand(scr, command, host)) > 0) {
522 wWindowAddSavedState(instance, class, command, pid, state);
523 } else {
524 free(state);
527 if (instance) free(instance);
528 if (class) free(class);
530 /* clean up */
531 PLSetStringCmpHook(StringCompareHook);
535 void
536 wSessionRestoreLastWorkspace(WScreen *scr)
538 proplist_t wks;
539 int w, i;
540 char *tmp;
542 make_keys();
544 if (!scr->session_state)
545 return;
547 PLSetStringCmpHook(NULL);
549 wks = PLGetDictionaryEntry(scr->session_state, sWorkspace);
550 if (!wks || !PLIsString(wks))
551 return;
553 tmp = PLGetString(wks);
555 /* clean up */
556 PLSetStringCmpHook(StringCompareHook);
558 if (sscanf(tmp, "%i", &w)!=1) {
559 w = -1;
560 for (i=0; i < scr->workspace_count; i++) {
561 if (strcmp(scr->workspaces[i]->name, tmp)==0) {
562 w = i;
563 break;
566 } else {
567 w--;
570 if (w!=scr->current_workspace && w<scr->workspace_count) {
571 wWorkspaceChange(scr, w);
576 static void
577 clearWaitingAckState(WScreen *scr)
579 WWindow *wwin;
580 WApplication *wapp;
582 for (wwin = scr->focused_window; wwin != NULL; wwin = wwin->prev) {
583 wwin->flags.waiting_save_ack = 0;
584 if (wwin->main_window != None) {
585 wapp = wApplicationOf(wwin->main_window);
586 if (wapp)
587 wapp->main_window_desc->flags.waiting_save_ack = 0;
593 void
594 wSessionSaveClients(WScreen *scr)
601 * With XSMP, this job is done by smproxy
603 void
604 wSessionSendSaveYourself(WScreen *scr)
606 WWindow *wwin;
607 int count;
609 /* freeze client interaction with clients */
610 XGrabKeyboard(dpy, scr->root_win, False, GrabModeAsync, GrabModeAsync,
611 CurrentTime);
612 XGrabPointer(dpy, scr->root_win, False, ButtonPressMask|ButtonReleaseMask,
613 GrabModeAsync, GrabModeAsync, scr->root_win, None,
614 CurrentTime);
616 clearWaitingAckState(scr);
618 count = 0;
620 /* first send SAVE_YOURSELF for everybody */
621 for (wwin = scr->focused_window; wwin != NULL; wwin = wwin->prev) {
622 WWindow *mainWin;
624 mainWin = wWindowFor(wwin->main_window);
626 if (mainWin) {
627 /* if the client is a multi-window client, only send message
628 * to the main window */
629 wwin = mainWin;
632 /* make sure the SAVE_YOURSELF flag is up-to-date */
633 PropGetProtocols(wwin->client_win, &wwin->protocols);
635 if (wwin->protocols.SAVE_YOURSELF) {
636 if (!wwin->flags.waiting_save_ack) {
637 wClientSendProtocol(wwin, _XA_WM_SAVE_YOURSELF, LastTimestamp);
639 wwin->flags.waiting_save_ack = 1;
640 count++;
642 } else {
643 wwin->flags.waiting_save_ack = 0;
647 /* then wait for acknowledge */
648 while (count > 0) {
652 XUngrabPointer(dpy, CurrentTime);
653 XUngrabKeyboard(dpy, CurrentTime);
654 XFlush(dpy);
658 #ifdef XSMP_ENABLED
660 * With full session management support, the part of WMState
661 * that store client window state will become obsolete (maybe we can reuse
662 * the old code too),
663 * but we still need to store state info like the dock and workspaces.
664 * It is better to keep dock/wspace info in WMState because the user
665 * might want to keep the dock configuration while not wanting to
666 * resume a previously saved session.
667 * So, wmaker specific state info can be saved in
668 * ~/GNUstep/.AppInfo/WindowMaker/statename.state
669 * Its better to not put it in the defaults directory because:
670 * - its not a defaults file (having domain names like wmaker0089504baa
671 * in the defaults directory wouldn't be very neat)
672 * - this state file is not meant to be edited by users
674 * The old session code will become obsolete. When wmaker is
675 * compiled with R6 sm support compiled in, itll be better to
676 * use a totally rewritten state saving code, but we can keep
677 * the current code for when XSMP_ENABLED is not compiled in.
679 * This will be confusing to old users (well get lots of "SAVE_SESSION broke!"
680 * messages), but itll be better.
682 * -readme
686 static char*
687 getWindowRole(Window window)
689 XTextProperty prop;
690 static Atom atom = 0;
692 if (!atom)
693 atom = XInternAtom(dpy, "WM_WINDOW_ROLE", False);
695 if (XGetTextProperty(dpy, window, &prop, atom)) {
696 if (prop.encoding == XA_STRING && prop.format == 8 && prop.nitems > 0)
697 return prop.value;
700 return NULL;
706 * Saved Info:
708 * WM_WINDOW_ROLE
710 * WM_CLASS.instance
711 * WM_CLASS.class
712 * WM_NAME
713 * WM_COMMAND
715 * geometry
716 * state = (miniaturized, shaded, etc)
717 * attribute
718 * workspace #
719 * app state = (which dock, hidden)
720 * window shortcut #
723 static proplist_t
724 makeAppState(WWindow *wwin)
726 WApplication *wapp;
727 proplist_t state;
728 WScreen *scr = wwin->screen_ptr;
730 state = PLMakeArrayWithElements(NULL, NULL);
732 wapp = wApplicationOf(wwin->main_window);
734 if (wapp) {
735 if (wapp->app_icon && wapp->app_icon->dock) {
737 if (wapp->app_icon->dock == scr->dock) {
738 PLAppendArrayElement(state, PLMakeString("Dock"));
739 } else {
740 int i;
742 for(i=0; i<scr->workspace_count; i++)
743 if(scr->workspaces[i]->clip == wapp->app_icon->dock)
744 break;
746 assert(i < scr->workspace_count);
748 PLAppendArrayElement(state,
749 PLMakeString(scr->workspaces[i]->name));
753 PLAppendArrayElement(state, PLMakeString(wapp->hidden ? "1" : "0"));
756 return state;
761 Bool
762 wSessionGetStateFor(WWindow *wwin, WSessionData *state)
764 char *str;
765 proplist_t slist;
766 proplist_t elem;
767 proplist_t value;
768 int index = 0;
770 index = 3;
772 /* geometry */
773 value = PLGetArrayElement(slist, index++);
774 str = PLGetString(value);
776 sscanf(str, "%i %i %i %i %i %i", &state->x, &state->y,
777 &state->width, &state->height,
778 &state->user_changed_width, &state->user_changed_height);
781 /* state */
782 value = PLGetArrayElement(slist, index++);
783 str = PLGetString(value);
785 sscanf(str, "%i %i %i", &state->miniaturized, &state->shaded,
786 &state->maximized);
789 /* attributes */
790 value = PLGetArrayElement(slist, index++);
791 str = PLGetString(value);
793 getAttributeState(str, &state->mflags, &state->flags);
796 /* workspace */
797 value = PLGetArrayElement(slist, index++);
798 str = PLGetString(value);
800 sscanf(str, "%i", &state->workspace);
803 /* app state (repeated for all windows of the app) */
804 value = PLGetArrayElement(slist, index++);
805 str = PLGetString(value);
807 /* ???? */
809 /* shortcuts */
810 value = PLGetArrayElement(slist, index++);
811 str = PLGetString(value);
813 sscanf(str, "%i", &state->shortcuts);
818 static proplist_t
819 makeAttributeState(WWindow *wwin)
821 unsigned int data1, data2;
822 char buffer[256];
824 #define W_FLAG(wwin, FLAG) ((wwin)->defined_user_flags.FLAG \
825 ? (wwin)->user_flags.FLAG : -1)
827 sprintf(buffer,
828 "%i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i",
829 W_FLAG(no_titlebar),
830 W_FLAG(no_resizable),
831 W_FLAG(no_closable),
832 W_FLAG(no_miniaturizable),
833 W_FLAG(no_resizebar),
834 W_FLAG(no_close_button),
835 W_FLAG(no_miniaturize_button),
837 W_FLAG(broken_close),
838 W_FLAG(kill_close),
840 W_FLAG(no_shadeable),
841 W_FLAG(omnipresent),
842 W_FLAG(skip_window_list),
843 W_FLAG(floating),
844 W_FLAG(sunken),
845 W_FLAG(no_bind_keys),
846 W_FLAG(no_bind_mouse),
847 W_FLAG(no_hide_others),
848 W_FLAG(no_appicon),
849 W_FLAG(dont_move_off),
850 W_FLAG(no_focusable),
851 W_FLAG(always_user_icon),
852 W_FLAG(start_miniaturized),
853 W_FLAG(start_hidden),
854 W_FLAG(start_maximized),
855 W_FLAG(dont_save_session),
856 W_FLAG(emulate_appicon));
858 return PLMakeString(buffer);
862 static void
863 appendStringInArray(proplist_t array, char *str)
865 proplist_t val;
867 val = PLMakeString(str);
868 PLAppendArrayElement(array, val);
869 PLRelease(val);
873 static proplist_t
874 makeClientState(WWindow *wwin)
876 proplist_t state;
877 proplist_t tmp;
878 char *str;
879 char buffer[256];
880 int i;
881 unsigned shortcuts;
883 state = PLMakeArrayWithElements(NULL, NULL);
885 /* WM_WINDOW_ROLE */
886 str = getWindowRole(wwin->client_win);
887 if (!str)
888 appendStringInArray(state, "");
889 else {
890 appendStringInArray(state, str);
891 XFree(str);
894 /* WM_CLASS.instance */
895 appendStringInArray(state, wwin->wm_instance);
897 /* WM_CLASS.class */
898 appendStringInArray(state, wwin->wm_class);
900 /* WM_NAME */
901 if (wwin->flags.wm_name_changed)
902 appendStringInArray(state, "");
903 else
904 appendStringInArray(state, wwin->frame->name);
906 /* geometry */
907 sprintf(buffer, "%i %i %i %i %i %i", wwin->frame_x, wwin->frame_y,
908 wwin->client.width, wwin->client.height,
909 wwin->flags.user_changed_width, wwin->flags.user_changed_height);
910 appendStringInArray(state, buffer);
912 /* state */
913 sprintf(buffer, "%i %i %i", wwin->flags.miniaturized,
914 wwin->flags.shaded, wwin->flags.maximized);
915 appendStringInArray(state, buffer);
917 /* attributes */
918 tmp = makeAttributeState(wwin);
919 PLAppendArrayElement(state, tmp);
920 PLRelease(tmp);
922 /* workspace */
923 sprintf(buffer, "%i", wwin->frame->workspace);
924 appendStringInArray(state, buffer);
926 /* app state (repeated for all windows of the app) */
927 tmp = makeAppState(wwin);
928 PLAppendArrayElement(state, tmp);
929 PLRelease(tmp);
931 /* shortcuts */
932 shortcuts = 0;
933 for (i = 0; i < MAX_WINDOW_SHORTCUTS; i++) {
934 if (scr->shortcutWindow[i] == wwin) {
935 shortcuts |= 1 << i;
938 sprintf(buffer, "%ui", shortcuts);
939 appendStringInArray(tmp, buffer);
941 return state;
945 static void
946 smSaveYourselfPhase2Proc(SmcConn smc_conn, SmPointer client_data)
948 SmProp props[4];
949 SmPropValue prop1val, prop2val, prop3val, prop4val;
950 char **argv = (char**)client_data;
951 int argc;
952 int i, j;
953 Bool ok = False;
954 char *statefile = NULL;
955 char *prefix;
956 Bool gsPrefix = False;
957 char *discardCmd = NULL;
958 time_t t;
959 proplist_t state;
961 #ifdef DEBUG1
962 puts("received SaveYourselfPhase2 SM message");
963 #endif
965 /* save session state */
967 /* the file that will contain the state */
968 prefix = getenv("SM_SAVE_DIR");
969 if (!prefix) {
970 prefix = wusergnusteppath();
971 if (prefix)
972 gsPrefix = True;
974 if (!prefix) {
975 prefix = getenv("HOME");
977 if (!prefix)
978 prefix = ".";
980 statefile = malloc(strlen(prefix)+64);
981 if (!statefile) {
982 wwarning(_("out of memory while saving session state"));
983 goto fail;
986 t = time();
987 i = 0;
988 do {
989 if (gsPrefix)
990 sprintf(statefile, "%s/.AppInfo/WindowMaker/wmaker.%l%i.state",
991 prefix, t, i);
992 else
993 sprintf(statefile, "%s/wmaker.%l%i.state", prefix, t, i);
994 i++;
995 } while (access(F_OK, statefile)!=-1);
997 /* save the states of all windows we're managing */
998 state = PLMakeArrayFromElements(NULL, NULL);
1001 * Format:
1003 * state_file ::= dictionary with version_info ; state
1004 * version_info ::= 'version' = '1';
1005 * state ::= 'state' = array of screen_info
1006 * screen_info ::= array of (screen number, window_info, window_info, ...)
1007 * window_info ::=
1009 for (i=0; i<wScreenCount; i++) {
1010 WScreen *scr;
1011 WWindow *wwin;
1012 char buf[32];
1013 proplist_t pscreen;
1015 scr = wScreenWithNumber(i);
1017 sprintf(buf, "%i", scr->screen);
1018 pscreen = PLMakeArrayFromElements(PLMakeString(buf), NULL);
1020 wwin = scr->focused_window;
1021 while (wwin) {
1022 proplist_t pwindow;
1024 pwindow = makeClientState(wwin);
1025 PLAppendArrayElement(pscreen, pwindow);
1027 wwin = wwin->prev;
1030 PLAppendArrayElement(state, pscreen);
1034 proplist_t statefile;
1036 statefile = PLMakeDictionaryFromEntries(PLMakeString("Version"),
1037 PLMakeString("1.0"),
1039 PLMakeString("Screens"),
1040 state,
1042 NULL);
1044 PLSetFilename(statefile, PLMakeString(statefile));
1045 PLSave(statefile, NO);
1047 PLRelease(statefile);
1050 /* set the remaining properties that we didn't set at
1051 * startup time */
1053 for (argc=0, i=0; argv[i]!=NULL; i++) {
1054 if (strcmp(argv[i], "-clientid")==0
1055 || strcmp(argv[i], "-restore")==0) {
1056 i++;
1057 } else {
1058 argc++;
1062 prop[0].name = SmRestartCommand;
1063 prop[0].type = SmLISTofARRAY8;
1064 prop[0].vals = malloc(sizeof(SmPropValue)*(argc+4));
1065 prop[0].num_vals = argc+4;
1067 prop[1].name = SmCloneCommand;
1068 prop[1].type = SmLISTofARRAY8;
1069 prop[1].vals = malloc(sizeof(SmPropValue)*(argc));
1070 prop[1].num_vals = argc;
1072 if (!prop[0].vals || !prop[1].vals) {
1073 wwarning(_("end of memory while saving session state"));
1074 goto fail;
1077 for (j=0, i=0; i<argc+4; i++) {
1078 if (strcmp(argv[i], "-clientid")==0
1079 || strcmp(argv[i], "-restore")==0) {
1080 i++;
1081 } else {
1082 prop[0].vals[j].value = argv[i];
1083 prop[0].vals[j].length = strlen(argv[i]);
1084 prop[1].vals[j].value = argv[i];
1085 prop[1].vals[j].length = strlen(argv[i]);
1086 j++;
1089 prop[0].vals[j].value = "-clientid";
1090 prop[0].vals[j].length = 9;
1091 j++;
1092 prop[0].vals[j].value = sClientID;
1093 prop[0].vals[j].length = strlen(sClientID);
1094 j++;
1095 prop[0].vals[j].value = "-restore";
1096 prop[0].vals[j].length = 11;
1097 j++;
1098 prop[0].vals[j].value = statefile;
1099 prop[0].vals[j].length = strlen(statefile);
1101 discardCmd = malloc(strlen(statefile)+8);
1102 if (!discardCmd)
1103 goto fail;
1104 sprintf(discardCmd, "rm %s", statefile);
1105 prop[2].name = SmDiscardCommand;
1106 prop[2].type = SmARRAY8;
1107 prop[2].vals[0] = discardCmd;
1108 prop[2].num_vals = 1;
1110 SmcSetProperties(sSMCConn, 3, prop);
1112 ok = True;
1113 fail:
1114 SmcSaveYourselfDone(smc_conn, ok);
1116 if (prop[0].vals)
1117 free(prop[0].vals);
1118 if (prop[1].vals)
1119 free(prop[1].vals);
1120 if (discardCmd)
1121 free(discardCmd);
1123 if (!ok) {
1124 remove(statefile);
1126 if (statefile)
1127 free(statefile);
1131 static void
1132 smSaveYourselfProc(SmcConn smc_conn, SmPointer client_data, int save_type,
1133 Bool shutdown, int interact_style, Bool fast)
1135 #ifdef DEBUG1
1136 puts("received SaveYourself SM message");
1137 #endif
1139 if (!SmcRequestSaveYourselfPhase2(smc_conn, smSaveYourselfPhase2Proc,
1140 client_data)) {
1142 SmcSaveYourselfDone(smc_conn, False);
1143 sWaitingPhase2 = False;
1144 } else {
1145 #ifdef DEBUG1
1146 puts("successfull request of SYS phase 2");
1147 #endif
1148 sWaitingPhase2 = True;
1153 static void
1154 smDieProc(SmcConn smc_conn, SmPointer client_data)
1156 #ifdef DEBUG1
1157 puts("received Die SM message");
1158 #endif
1160 wSessionDisconnectManager();
1162 Shutdown(WSExitMode, True);
1167 static void
1168 smSaveCompleteProc(SmcConn smc_conn)
1170 /* it means that we can resume doing things that can change our state */
1171 #ifdef DEBUG1
1172 puts("received SaveComplete SM message");
1173 #endif
1177 static void
1178 smShutdownCancelledProc(SmcConn smc_conn, SmPointer client_data)
1180 if (sWaitingPhase2) {
1182 sWaitingPhase2 = False;
1184 SmcSaveYourselfDone(smc_conn, False);
1189 static void
1190 iceMessageProc(int fd, int mask, void *clientData)
1192 IceConn iceConn = (IceConn)clientData;
1194 IceProcessMessages(iceConn, NULL, NULL);
1198 static void
1199 iceIOErrorHandler(IceConnection ice_conn)
1201 /* This is not fatal but can mean the session manager exited.
1202 * If the session manager exited normally we would get a
1203 * Die message, so this probably means an abnormal exit.
1204 * If the sm was the last client of session, then we'll die
1205 * anyway, otherwise we can continue doing our stuff.
1207 wwarning(_("connection to the session manager was lost"));
1208 wSessionDisconnectManager();
1212 void
1213 wSessionConnectManager(char **argv, int argc)
1215 IceConn iceConn;
1216 char *previous_id = NULL;
1217 char buffer[256];
1218 SmcCallbacks callbacks;
1219 unsigned long mask;
1220 char uid[32];
1221 char pid[32];
1222 SmProp props[4];
1223 SmPropValue prop1val, prop2val, prop3val, prop4val;
1224 char restartStyle;
1225 int i;
1227 mask = SmcSaveYourselfProcMask|SmcDieProcMask|SmcSaveCompleteProcMask
1228 |SmcShutdownCancelledProcMask;
1230 callbacks.save_yourself.callback = smSaveYourselfProc;
1231 callbacks.save_yourself.client_data = argv;
1233 callbacks.die.callback = smDieProc;
1234 callbacks.die.client_data = NULL;
1236 callbacks.save_complete.callback = smSaveCompleteProc;
1237 callbacks.save_complete.client_data = NULL;
1239 callbacks.shutdown_cancelled.callback = smShutdownCancelledProc;
1240 callbacks.shutdown_cancelled.client_data = NULL;
1242 for (i=0; i<argc; i++) {
1243 if (strcmp(argv[i], "-clientid")==0) {
1244 previous_id = argv[i+1];
1245 break;
1249 /* connect to the session manager */
1250 sSMCConn = SmcOpenConnection(NULL, NULL, SmProtoMajor, SmProtoMinor,
1251 mask, &callbacks, previous_id,
1252 &sClientID, 255, buffer);
1253 if (!sSMCConn) {
1254 return;
1256 #ifdef DEBUG1
1257 puts("connected to the session manager");
1258 #endif
1260 /* IceSetIOErrorHandler(iceIOErrorHandler);*/
1262 /* check for session manager clients */
1263 iceConn = SmcGetIceConnection(smcConn);
1265 if (fcntl(IceConnectionNumber(iceConn), F_SETFD, FD_CLOEXEC) < 0) {
1266 wsyserror("error setting close-on-exec flag for ICE connection");
1269 sSMInputHandler = WMAddInputHandler(IceConnectionNumber(iceConn),
1270 WIReadMask, iceMessageProc, iceConn);
1272 /* setup information about ourselves */
1274 /* program name */
1275 prop1val.value = argv[0];
1276 prop1val.length = strlen(argv[0]);
1277 prop[0].name = SmProgram;
1278 prop[0].type = SmARRAY8;
1279 prop[0].num_vals = 1;
1280 prop[0].vals = &prop1val;
1282 /* The XSMP doc from X11R6.1 says it contains the user name,
1283 * but every client implementation I saw places the uid # */
1284 sprintf(uid, "%i", getuid());
1285 prop2val.value = uid;
1286 prop2val.length = strlen(uid);
1287 prop[1].name = SmUserID;
1288 prop[1].type = SmARRAY8;
1289 prop[1].num_vals = 1;
1290 prop[1].vals = &prop2val;
1292 /* Restart style. We should restart only if we were running when
1293 * the previous session finished. */
1294 restartStyle = SmRestartIfRunning;
1295 prop3val.value = &restartStyle;
1296 prop3val.length = 1;
1297 prop[2].name = SmRestartStyleHint;
1298 prop[2].type = SmCARD8;
1299 prop[2].num_vals = 1;
1300 prop[2].vals = &prop3val;
1302 /* Our PID. Not required but might be usefull */
1303 sprintf(pid, "%i", getpid());
1304 prop4val.value = pid;
1305 prop4val.length = strlen(pid);
1306 prop[3].name = SmProcessID;
1307 prop[3].type = SmARRAY8;
1308 prop[3].num_vals = 1;
1309 prop[3].vals = &prop4val;
1311 /* we'll set the rest of the hints later */
1313 SmcSetProperties(sSMCConn, 4, props);
1318 void
1319 wSessionDisconnectManager(void)
1321 if (sSMCConn) {
1322 WMDeleteInputHandler(sSMInputHandler);
1323 sSMInputHandler = NULL;
1325 SmcCloseConnection(sSMCConn, 0, NULL);
1326 sSMCConn = NULL;
1330 void
1331 wSessionRequestShutdown(void)
1333 /* request a shutdown to the session manager */
1334 if (sSMCConn)
1335 SmcRequestSaveYourself(sSMCConn, SmSaveBoth, True, SmInteractStyleAny,
1336 False, True);
1340 Bool
1341 wSessionIsManaged(void)
1343 return sSMCConn!=NULL;
1346 #endif /* !XSMP_ENABLED */