fixed many bugs, removed linked list
[wmaker-crm.git] / src / session.c
blobd990312352e6cf1ae074fcc6d919d9f304109ad1
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 while (wwin) {
297 WApplication *wapp=wApplicationOf(wwin->main_window);
299 if (wwin->transient_for==None && WMGetFirstInBag(wapp_list, wapp)<0
300 && !WFLAGP(wwin, dont_save_session)) {
301 /* A entry for this application was not yet saved. Save one. */
302 if ((win_info = makeWindowState(wwin, wapp))!=NULL) {
303 list = PLAppendArrayElement(list, win_info);
304 PLRelease(win_info);
305 /* If we were succesful in saving the info for this window
306 * add the application the window belongs to, to the
307 * application list, so no multiple entries for the same
308 * application are saved.
310 WMPutInBag(wapp_list, wapp);
313 wwin = wwin->prev;
315 PLRemoveDictionaryEntry(scr->session_state, sApplications);
316 PLInsertDictionaryEntry(scr->session_state, sApplications, list);
317 PLRelease(list);
319 wks = PLMakeString(scr->workspaces[scr->current_workspace]->name);
320 PLInsertDictionaryEntry(scr->session_state, sWorkspace, wks);
321 PLRelease(wks);
323 WMFreeBag(wapp_list);
327 void
328 wSessionClearState(WScreen *scr)
330 make_keys();
332 if (!scr->session_state)
333 return;
335 PLRemoveDictionaryEntry(scr->session_state, sApplications);
336 PLRemoveDictionaryEntry(scr->session_state, sWorkspace);
340 static pid_t
341 execCommand(WScreen *scr, char *command, char *host)
343 pid_t pid;
344 char **argv;
345 int argc;
347 ParseCommand(command, &argv, &argc);
349 if (argv==NULL) {
350 return 0;
353 if ((pid=fork())==0) {
354 char **args;
355 int i;
357 SetupEnvironment(scr);
359 args = malloc(sizeof(char*)*(argc+1));
360 if (!args)
361 exit(111);
362 for (i=0; i<argc; i++) {
363 args[i] = argv[i];
365 args[argc] = NULL;
366 execvp(argv[0], args);
367 exit(111);
369 while (argc > 0)
370 free(argv[--argc]);
371 free(argv);
372 return pid;
376 static WSavedState*
377 getWindowState(WScreen *scr, proplist_t win_state)
379 WSavedState *state = wmalloc(sizeof(WSavedState));
380 proplist_t value;
381 char *tmp;
382 int i;
384 memset(state, 0, sizeof(WSavedState));
385 state->workspace = -1;
386 value = PLGetDictionaryEntry(win_state, sWorkspace);
387 if (value && PLIsString(value)) {
388 tmp = PLGetString(value);
389 if (sscanf(tmp, "%i", &state->workspace)!=1) {
390 state->workspace = -1;
391 for (i=0; i < scr->workspace_count; i++) {
392 if (strcmp(scr->workspaces[i]->name, tmp)==0) {
393 state->workspace = i;
394 break;
397 } else {
398 state->workspace--;
401 if ((value = PLGetDictionaryEntry(win_state, sShaded))!=NULL)
402 state->shaded = getBool(value);
403 if ((value = PLGetDictionaryEntry(win_state, sMiniaturized))!=NULL)
404 state->miniaturized = getBool(value);
405 if ((value = PLGetDictionaryEntry(win_state, sHidden))!=NULL)
406 state->hidden = getBool(value);
408 value = PLGetDictionaryEntry(win_state, sGeometry);
409 if (value && PLIsString(value)) {
410 if (sscanf(PLGetString(value), "%ix%i+%i+%i",
411 &state->w, &state->h, &state->x, &state->y)==4 &&
412 (state->w>0 && state->h>0)) {
413 state->use_geometry = 1;
414 } else if (sscanf(PLGetString(value), "%i,%i,%i,%i",
415 &state->x, &state->y, &state->w, &state->h)==4 &&
416 (state->w>0 && state->h>0)) {
417 /* TODO: remove redundant sscanf() in version 0.20.x */
418 state->use_geometry = 1;
423 return state;
427 #define SAME(x, y) (((x) && (y) && !strcmp((x), (y))) || (!(x) && !(y)))
429 void
430 wSessionRestoreState(WScreen *scr)
432 WSavedState *state;
433 char *instance, *class, *command, *host;
434 proplist_t win_info, apps, cmd, value;
435 pid_t pid;
436 int i, count;
437 WDock *dock;
438 WAppIcon *btn=NULL;
439 int j, n, found;
440 char *tmp;
442 make_keys();
444 if (!scr->session_state)
445 return;
447 PLSetStringCmpHook(NULL);
449 apps = PLGetDictionaryEntry(scr->session_state, sApplications);
450 if (!apps)
451 return;
453 count = PLGetNumberOfElements(apps);
454 if (count==0)
455 return;
457 for (i=0; i<count; i++) {
458 win_info = PLGetArrayElement(apps, i);
460 cmd = PLGetDictionaryEntry(win_info, sCommand);
461 if (!cmd || !PLIsString(cmd) || !(command = PLGetString(cmd))) {
462 continue;
465 value = PLGetDictionaryEntry(win_info, sName);
466 if (!value)
467 continue;
469 ParseWindowName(value, &instance, &class, "session");
470 if (!instance && !class)
471 continue;
473 value = PLGetDictionaryEntry(win_info, sHost);
474 if (value && PLIsString(value))
475 host = PLGetString(value);
476 else
477 host = NULL;
479 state = getWindowState(scr, win_info);
481 dock = NULL;
482 value = PLGetDictionaryEntry(win_info, sDock);
483 if (value && PLIsString(value) && (tmp = PLGetString(value))!=NULL) {
484 if (sscanf(tmp, "%i", &n)!=1) {
485 if (!strcasecmp(tmp, "DOCK")) {
486 dock = scr->dock;
487 } else {
488 for (j=0; j < scr->workspace_count; j++) {
489 if (strcmp(scr->workspaces[j]->name, tmp)==0) {
490 dock = scr->workspaces[j]->clip;
491 break;
495 } else {
496 if (n == 0) {
497 dock = scr->dock;
498 } else if (n>0 && n<=scr->workspace_count) {
499 dock = scr->workspaces[n-1]->clip;
504 found = 0;
505 if (dock!=NULL) {
506 for (j=0; j<dock->max_icons; j++) {
507 btn = dock->icon_array[j];
508 if (btn && SAME(instance, btn->wm_instance) &&
509 SAME(class, btn->wm_class) &&
510 SAME(command, btn->command)) {
511 found = 1;
512 break;
517 if (found) {
518 wDockLaunchWithState(dock, btn, state);
519 } else if ((pid = execCommand(scr, command, host)) > 0) {
520 wWindowAddSavedState(instance, class, command, pid, state);
521 } else {
522 free(state);
525 if (instance) free(instance);
526 if (class) free(class);
528 /* clean up */
529 PLSetStringCmpHook(StringCompareHook);
533 void
534 wSessionRestoreLastWorkspace(WScreen *scr)
536 proplist_t wks;
537 int w, i;
538 char *tmp;
540 make_keys();
542 if (!scr->session_state)
543 return;
545 PLSetStringCmpHook(NULL);
547 wks = PLGetDictionaryEntry(scr->session_state, sWorkspace);
548 if (!wks || !PLIsString(wks))
549 return;
551 tmp = PLGetString(wks);
553 /* clean up */
554 PLSetStringCmpHook(StringCompareHook);
556 if (sscanf(tmp, "%i", &w)!=1) {
557 w = -1;
558 for (i=0; i < scr->workspace_count; i++) {
559 if (strcmp(scr->workspaces[i]->name, tmp)==0) {
560 w = i;
561 break;
564 } else {
565 w--;
568 if (w!=scr->current_workspace && w<scr->workspace_count) {
569 wWorkspaceChange(scr, w);
574 static void
575 clearWaitingAckState(WScreen *scr)
577 WWindow *wwin;
578 WApplication *wapp;
580 for (wwin = scr->focused_window; wwin != NULL; wwin = wwin->prev) {
581 wwin->flags.waiting_save_ack = 0;
582 if (wwin->main_window != None) {
583 wapp = wApplicationOf(wwin->main_window);
584 if (wapp)
585 wapp->main_window_desc->flags.waiting_save_ack = 0;
591 void
592 wSessionSaveClients(WScreen *scr)
599 * With XSMP, this job is done by smproxy
601 void
602 wSessionSendSaveYourself(WScreen *scr)
604 WWindow *wwin;
605 int count;
607 /* freeze client interaction with clients */
608 XGrabKeyboard(dpy, scr->root_win, False, GrabModeAsync, GrabModeAsync,
609 CurrentTime);
610 XGrabPointer(dpy, scr->root_win, False, ButtonPressMask|ButtonReleaseMask,
611 GrabModeAsync, GrabModeAsync, scr->root_win, None,
612 CurrentTime);
614 clearWaitingAckState(scr);
616 count = 0;
618 /* first send SAVE_YOURSELF for everybody */
619 for (wwin = scr->focused_window; wwin != NULL; wwin = wwin->prev) {
620 WWindow *mainWin;
622 mainWin = wWindowFor(wwin->main_window);
624 if (mainWin) {
625 /* if the client is a multi-window client, only send message
626 * to the main window */
627 wwin = mainWin;
630 /* make sure the SAVE_YOURSELF flag is up-to-date */
631 PropGetProtocols(wwin->client_win, &wwin->protocols);
633 if (wwin->protocols.SAVE_YOURSELF) {
634 if (!wwin->flags.waiting_save_ack) {
635 wClientSendProtocol(wwin, _XA_WM_SAVE_YOURSELF, LastTimestamp);
637 wwin->flags.waiting_save_ack = 1;
638 count++;
640 } else {
641 wwin->flags.waiting_save_ack = 0;
645 /* then wait for acknowledge */
646 while (count > 0) {
650 XUngrabPointer(dpy, CurrentTime);
651 XUngrabKeyboard(dpy, CurrentTime);
652 XFlush(dpy);
656 #ifdef XSMP_ENABLED
658 * With full session management support, the part of WMState
659 * that store client window state will become obsolete (maybe we can reuse
660 * the old code too),
661 * but we still need to store state info like the dock and workspaces.
662 * It is better to keep dock/wspace info in WMState because the user
663 * might want to keep the dock configuration while not wanting to
664 * resume a previously saved session.
665 * So, wmaker specific state info can be saved in
666 * ~/GNUstep/.AppInfo/WindowMaker/statename.state
667 * Its better to not put it in the defaults directory because:
668 * - its not a defaults file (having domain names like wmaker0089504baa
669 * in the defaults directory wouldn't be very neat)
670 * - this state file is not meant to be edited by users
672 * The old session code will become obsolete. When wmaker is
673 * compiled with R6 sm support compiled in, itll be better to
674 * use a totally rewritten state saving code, but we can keep
675 * the current code for when XSMP_ENABLED is not compiled in.
677 * This will be confusing to old users (well get lots of "SAVE_SESSION broke!"
678 * messages), but itll be better.
680 * -readme
684 static char*
685 getWindowRole(Window window)
687 XTextProperty prop;
688 static Atom atom = 0;
690 if (!atom)
691 atom = XInternAtom(dpy, "WM_WINDOW_ROLE", False);
693 if (XGetTextProperty(dpy, window, &prop, atom)) {
694 if (prop.encoding == XA_STRING && prop.format == 8 && prop.nitems > 0)
695 return prop.value;
698 return NULL;
704 * Saved Info:
706 * WM_WINDOW_ROLE
708 * WM_CLASS.instance
709 * WM_CLASS.class
710 * WM_NAME
711 * WM_COMMAND
713 * geometry
714 * state = (miniaturized, shaded, etc)
715 * attribute
716 * workspace #
717 * app state = (which dock, hidden)
718 * window shortcut #
721 static proplist_t
722 makeAppState(WWindow *wwin)
724 WApplication *wapp;
725 proplist_t state;
726 WScreen *scr = wwin->screen_ptr;
728 state = PLMakeArrayWithElements(NULL, NULL);
730 wapp = wApplicationOf(wwin->main_window);
732 if (wapp) {
733 if (wapp->app_icon && wapp->app_icon->dock) {
735 if (wapp->app_icon->dock == scr->dock) {
736 PLAppendArrayElement(state, PLMakeString("Dock"));
737 } else {
738 int i;
740 for(i=0; i<scr->workspace_count; i++)
741 if(scr->workspaces[i]->clip == wapp->app_icon->dock)
742 break;
744 assert(i < scr->workspace_count);
746 PLAppendArrayElement(state,
747 PLMakeString(scr->workspaces[i]->name));
751 PLAppendArrayElement(state, PLMakeString(wapp->hidden ? "1" : "0"));
754 return state;
759 Bool
760 wSessionGetStateFor(WWindow *wwin, WSessionData *state)
762 char *str;
763 proplist_t slist;
764 proplist_t elem;
765 proplist_t value;
766 int index = 0;
768 index = 3;
770 /* geometry */
771 value = PLGetArrayElement(slist, index++);
772 str = PLGetString(value);
774 sscanf(str, "%i %i %i %i %i %i", &state->x, &state->y,
775 &state->width, &state->height,
776 &state->user_changed_width, &state->user_changed_height);
779 /* state */
780 value = PLGetArrayElement(slist, index++);
781 str = PLGetString(value);
783 sscanf(str, "%i %i %i", &state->miniaturized, &state->shaded,
784 &state->maximized);
787 /* attributes */
788 value = PLGetArrayElement(slist, index++);
789 str = PLGetString(value);
791 getAttributeState(str, &state->mflags, &state->flags);
794 /* workspace */
795 value = PLGetArrayElement(slist, index++);
796 str = PLGetString(value);
798 sscanf(str, "%i", &state->workspace);
801 /* app state (repeated for all windows of the app) */
802 value = PLGetArrayElement(slist, index++);
803 str = PLGetString(value);
805 /* ???? */
807 /* shortcuts */
808 value = PLGetArrayElement(slist, index++);
809 str = PLGetString(value);
811 sscanf(str, "%i", &state->shortcuts);
816 static proplist_t
817 makeAttributeState(WWindow *wwin)
819 unsigned int data1, data2;
820 char buffer[256];
822 #define W_FLAG(wwin, FLAG) ((wwin)->defined_user_flags.FLAG \
823 ? (wwin)->user_flags.FLAG : -1)
825 sprintf(buffer,
826 "%i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i",
827 W_FLAG(no_titlebar),
828 W_FLAG(no_resizable),
829 W_FLAG(no_closable),
830 W_FLAG(no_miniaturizable),
831 W_FLAG(no_resizebar),
832 W_FLAG(no_close_button),
833 W_FLAG(no_miniaturize_button),
835 W_FLAG(broken_close),
836 W_FLAG(kill_close),
838 W_FLAG(no_shadeable),
839 W_FLAG(omnipresent),
840 W_FLAG(skip_window_list),
841 W_FLAG(floating),
842 W_FLAG(sunken),
843 W_FLAG(no_bind_keys),
844 W_FLAG(no_bind_mouse),
845 W_FLAG(no_hide_others),
846 W_FLAG(no_appicon),
847 W_FLAG(dont_move_off),
848 W_FLAG(no_focusable),
849 W_FLAG(always_user_icon),
850 W_FLAG(start_miniaturized),
851 W_FLAG(start_hidden),
852 W_FLAG(start_maximized),
853 W_FLAG(dont_save_session),
854 W_FLAG(emulate_appicon));
856 return PLMakeString(buffer);
860 static void
861 appendStringInArray(proplist_t array, char *str)
863 proplist_t val;
865 val = PLMakeString(str);
866 PLAppendArrayElement(array, val);
867 PLRelease(val);
871 static proplist_t
872 makeClientState(WWindow *wwin)
874 proplist_t state;
875 proplist_t tmp;
876 char *str;
877 char buffer[256];
878 int i;
879 unsigned shortcuts;
881 state = PLMakeArrayWithElements(NULL, NULL);
883 /* WM_WINDOW_ROLE */
884 str = getWindowRole(wwin->client_win);
885 if (!str)
886 appendStringInArray(state, "");
887 else {
888 appendStringInArray(state, str);
889 XFree(str);
892 /* WM_CLASS.instance */
893 appendStringInArray(state, wwin->wm_instance);
895 /* WM_CLASS.class */
896 appendStringInArray(state, wwin->wm_class);
898 /* WM_NAME */
899 if (wwin->flags.wm_name_changed)
900 appendStringInArray(state, "");
901 else
902 appendStringInArray(state, wwin->frame->name);
904 /* geometry */
905 sprintf(buffer, "%i %i %i %i %i %i", wwin->frame_x, wwin->frame_y,
906 wwin->client.width, wwin->client.height,
907 wwin->flags.user_changed_width, wwin->flags.user_changed_height);
908 appendStringInArray(state, buffer);
910 /* state */
911 sprintf(buffer, "%i %i %i", wwin->flags.miniaturized,
912 wwin->flags.shaded, wwin->flags.maximized);
913 appendStringInArray(state, buffer);
915 /* attributes */
916 tmp = makeAttributeState(wwin);
917 PLAppendArrayElement(state, tmp);
918 PLRelease(tmp);
920 /* workspace */
921 sprintf(buffer, "%i", wwin->frame->workspace);
922 appendStringInArray(state, buffer);
924 /* app state (repeated for all windows of the app) */
925 tmp = makeAppState(wwin);
926 PLAppendArrayElement(state, tmp);
927 PLRelease(tmp);
929 /* shortcuts */
930 shortcuts = 0;
931 for (i = 0; i < MAX_WINDOW_SHORTCUTS; i++) {
932 if (scr->shortcutWindow[i] == wwin) {
933 shortcuts |= 1 << i;
936 sprintf(buffer, "%ui", shortcuts);
937 appendStringInArray(tmp, buffer);
939 return state;
943 static void
944 smSaveYourselfPhase2Proc(SmcConn smc_conn, SmPointer client_data)
946 SmProp props[4];
947 SmPropValue prop1val, prop2val, prop3val, prop4val;
948 char **argv = (char**)client_data;
949 int argc;
950 int i, j;
951 Bool ok = False;
952 char *statefile = NULL;
953 char *prefix;
954 Bool gsPrefix = False;
955 char *discardCmd = NULL;
956 time_t t;
957 proplist_t state;
959 #ifdef DEBUG1
960 puts("received SaveYourselfPhase2 SM message");
961 #endif
963 /* save session state */
965 /* the file that will contain the state */
966 prefix = getenv("SM_SAVE_DIR");
967 if (!prefix) {
968 prefix = wusergnusteppath();
969 if (prefix)
970 gsPrefix = True;
972 if (!prefix) {
973 prefix = getenv("HOME");
975 if (!prefix)
976 prefix = ".";
978 statefile = malloc(strlen(prefix)+64);
979 if (!statefile) {
980 wwarning(_("out of memory while saving session state"));
981 goto fail;
984 t = time();
985 i = 0;
986 do {
987 if (gsPrefix)
988 sprintf(statefile, "%s/.AppInfo/WindowMaker/wmaker.%l%i.state",
989 prefix, t, i);
990 else
991 sprintf(statefile, "%s/wmaker.%l%i.state", prefix, t, i);
992 i++;
993 } while (access(F_OK, statefile)!=-1);
995 /* save the states of all windows we're managing */
996 state = PLMakeArrayFromElements(NULL, NULL);
999 * Format:
1001 * state_file ::= dictionary with version_info ; state
1002 * version_info ::= 'version' = '1';
1003 * state ::= 'state' = array of screen_info
1004 * screen_info ::= array of (screen number, window_info, window_info, ...)
1005 * window_info ::=
1007 for (i=0; i<wScreenCount; i++) {
1008 WScreen *scr;
1009 WWindow *wwin;
1010 char buf[32];
1011 proplist_t pscreen;
1013 scr = wScreenWithNumber(i);
1015 sprintf(buf, "%i", scr->screen);
1016 pscreen = PLMakeArrayFromElements(PLMakeString(buf), NULL);
1018 wwin = scr->focused_window;
1019 while (wwin) {
1020 proplist_t pwindow;
1022 pwindow = makeClientState(wwin);
1023 PLAppendArrayElement(pscreen, pwindow);
1025 wwin = wwin->prev;
1028 PLAppendArrayElement(state, pscreen);
1032 proplist_t statefile;
1034 statefile = PLMakeDictionaryFromEntries(PLMakeString("Version"),
1035 PLMakeString("1.0"),
1037 PLMakeString("Screens"),
1038 state,
1040 NULL);
1042 PLSetFilename(statefile, PLMakeString(statefile));
1043 PLSave(statefile, NO);
1045 PLRelease(statefile);
1048 /* set the remaining properties that we didn't set at
1049 * startup time */
1051 for (argc=0, i=0; argv[i]!=NULL; i++) {
1052 if (strcmp(argv[i], "-clientid")==0
1053 || strcmp(argv[i], "-restore")==0) {
1054 i++;
1055 } else {
1056 argc++;
1060 prop[0].name = SmRestartCommand;
1061 prop[0].type = SmLISTofARRAY8;
1062 prop[0].vals = malloc(sizeof(SmPropValue)*(argc+4));
1063 prop[0].num_vals = argc+4;
1065 prop[1].name = SmCloneCommand;
1066 prop[1].type = SmLISTofARRAY8;
1067 prop[1].vals = malloc(sizeof(SmPropValue)*(argc));
1068 prop[1].num_vals = argc;
1070 if (!prop[0].vals || !prop[1].vals) {
1071 wwarning(_("end of memory while saving session state"));
1072 goto fail;
1075 for (j=0, i=0; i<argc+4; i++) {
1076 if (strcmp(argv[i], "-clientid")==0
1077 || strcmp(argv[i], "-restore")==0) {
1078 i++;
1079 } else {
1080 prop[0].vals[j].value = argv[i];
1081 prop[0].vals[j].length = strlen(argv[i]);
1082 prop[1].vals[j].value = argv[i];
1083 prop[1].vals[j].length = strlen(argv[i]);
1084 j++;
1087 prop[0].vals[j].value = "-clientid";
1088 prop[0].vals[j].length = 9;
1089 j++;
1090 prop[0].vals[j].value = sClientID;
1091 prop[0].vals[j].length = strlen(sClientID);
1092 j++;
1093 prop[0].vals[j].value = "-restore";
1094 prop[0].vals[j].length = 11;
1095 j++;
1096 prop[0].vals[j].value = statefile;
1097 prop[0].vals[j].length = strlen(statefile);
1099 discardCmd = malloc(strlen(statefile)+8);
1100 if (!discardCmd)
1101 goto fail;
1102 sprintf(discardCmd, "rm %s", statefile);
1103 prop[2].name = SmDiscardCommand;
1104 prop[2].type = SmARRAY8;
1105 prop[2].vals[0] = discardCmd;
1106 prop[2].num_vals = 1;
1108 SmcSetProperties(sSMCConn, 3, prop);
1110 ok = True;
1111 fail:
1112 SmcSaveYourselfDone(smc_conn, ok);
1114 if (prop[0].vals)
1115 free(prop[0].vals);
1116 if (prop[1].vals)
1117 free(prop[1].vals);
1118 if (discardCmd)
1119 free(discardCmd);
1121 if (!ok) {
1122 remove(statefile);
1124 if (statefile)
1125 free(statefile);
1129 static void
1130 smSaveYourselfProc(SmcConn smc_conn, SmPointer client_data, int save_type,
1131 Bool shutdown, int interact_style, Bool fast)
1133 #ifdef DEBUG1
1134 puts("received SaveYourself SM message");
1135 #endif
1137 if (!SmcRequestSaveYourselfPhase2(smc_conn, smSaveYourselfPhase2Proc,
1138 client_data)) {
1140 SmcSaveYourselfDone(smc_conn, False);
1141 sWaitingPhase2 = False;
1142 } else {
1143 #ifdef DEBUG1
1144 puts("successfull request of SYS phase 2");
1145 #endif
1146 sWaitingPhase2 = True;
1151 static void
1152 smDieProc(SmcConn smc_conn, SmPointer client_data)
1154 #ifdef DEBUG1
1155 puts("received Die SM message");
1156 #endif
1158 wSessionDisconnectManager();
1160 Shutdown(WSExitMode, True);
1165 static void
1166 smSaveCompleteProc(SmcConn smc_conn)
1168 /* it means that we can resume doing things that can change our state */
1169 #ifdef DEBUG1
1170 puts("received SaveComplete SM message");
1171 #endif
1175 static void
1176 smShutdownCancelledProc(SmcConn smc_conn, SmPointer client_data)
1178 if (sWaitingPhase2) {
1180 sWaitingPhase2 = False;
1182 SmcSaveYourselfDone(smc_conn, False);
1187 static void
1188 iceMessageProc(int fd, int mask, void *clientData)
1190 IceConn iceConn = (IceConn)clientData;
1192 IceProcessMessages(iceConn, NULL, NULL);
1196 static void
1197 iceIOErrorHandler(IceConnection ice_conn)
1199 /* This is not fatal but can mean the session manager exited.
1200 * If the session manager exited normally we would get a
1201 * Die message, so this probably means an abnormal exit.
1202 * If the sm was the last client of session, then we'll die
1203 * anyway, otherwise we can continue doing our stuff.
1205 wwarning(_("connection to the session manager was lost"));
1206 wSessionDisconnectManager();
1210 void
1211 wSessionConnectManager(char **argv, int argc)
1213 IceConn iceConn;
1214 char *previous_id = NULL;
1215 char buffer[256];
1216 SmcCallbacks callbacks;
1217 unsigned long mask;
1218 char uid[32];
1219 char pid[32];
1220 SmProp props[4];
1221 SmPropValue prop1val, prop2val, prop3val, prop4val;
1222 char restartStyle;
1223 int i;
1225 mask = SmcSaveYourselfProcMask|SmcDieProcMask|SmcSaveCompleteProcMask
1226 |SmcShutdownCancelledProcMask;
1228 callbacks.save_yourself.callback = smSaveYourselfProc;
1229 callbacks.save_yourself.client_data = argv;
1231 callbacks.die.callback = smDieProc;
1232 callbacks.die.client_data = NULL;
1234 callbacks.save_complete.callback = smSaveCompleteProc;
1235 callbacks.save_complete.client_data = NULL;
1237 callbacks.shutdown_cancelled.callback = smShutdownCancelledProc;
1238 callbacks.shutdown_cancelled.client_data = NULL;
1240 for (i=0; i<argc; i++) {
1241 if (strcmp(argv[i], "-clientid")==0) {
1242 previous_id = argv[i+1];
1243 break;
1247 /* connect to the session manager */
1248 sSMCConn = SmcOpenConnection(NULL, NULL, SmProtoMajor, SmProtoMinor,
1249 mask, &callbacks, previous_id,
1250 &sClientID, 255, buffer);
1251 if (!sSMCConn) {
1252 return;
1254 #ifdef DEBUG1
1255 puts("connected to the session manager");
1256 #endif
1258 /* IceSetIOErrorHandler(iceIOErrorHandler);*/
1260 /* check for session manager clients */
1261 iceConn = SmcGetIceConnection(smcConn);
1263 if (fcntl(IceConnectionNumber(iceConn), F_SETFD, FD_CLOEXEC) < 0) {
1264 wsyserror("error setting close-on-exec flag for ICE connection");
1267 sSMInputHandler = WMAddInputHandler(IceConnectionNumber(iceConn),
1268 WIReadMask, iceMessageProc, iceConn);
1270 /* setup information about ourselves */
1272 /* program name */
1273 prop1val.value = argv[0];
1274 prop1val.length = strlen(argv[0]);
1275 prop[0].name = SmProgram;
1276 prop[0].type = SmARRAY8;
1277 prop[0].num_vals = 1;
1278 prop[0].vals = &prop1val;
1280 /* The XSMP doc from X11R6.1 says it contains the user name,
1281 * but every client implementation I saw places the uid # */
1282 sprintf(uid, "%i", getuid());
1283 prop2val.value = uid;
1284 prop2val.length = strlen(uid);
1285 prop[1].name = SmUserID;
1286 prop[1].type = SmARRAY8;
1287 prop[1].num_vals = 1;
1288 prop[1].vals = &prop2val;
1290 /* Restart style. We should restart only if we were running when
1291 * the previous session finished. */
1292 restartStyle = SmRestartIfRunning;
1293 prop3val.value = &restartStyle;
1294 prop3val.length = 1;
1295 prop[2].name = SmRestartStyleHint;
1296 prop[2].type = SmCARD8;
1297 prop[2].num_vals = 1;
1298 prop[2].vals = &prop3val;
1300 /* Our PID. Not required but might be usefull */
1301 sprintf(pid, "%i", getpid());
1302 prop4val.value = pid;
1303 prop4val.length = strlen(pid);
1304 prop[3].name = SmProcessID;
1305 prop[3].type = SmARRAY8;
1306 prop[3].num_vals = 1;
1307 prop[3].vals = &prop4val;
1309 /* we'll set the rest of the hints later */
1311 SmcSetProperties(sSMCConn, 4, props);
1316 void
1317 wSessionDisconnectManager(void)
1319 if (sSMCConn) {
1320 WMDeleteInputHandler(sSMInputHandler);
1321 sSMInputHandler = NULL;
1323 SmcCloseConnection(sSMCConn, 0, NULL);
1324 sSMCConn = NULL;
1328 void
1329 wSessionRequestShutdown(void)
1331 /* request a shutdown to the session manager */
1332 if (sSMCConn)
1333 SmcRequestSaveYourself(sSMCConn, SmSaveBoth, True, SmInteractStyleAny,
1334 False, True);
1338 Bool
1339 wSessionIsManaged(void)
1341 return sSMCConn!=NULL;
1344 #endif /* !XSMP_ENABLED */