updated code to use new bags
[wmaker-crm.git] / src / session.c
blobd13fca6334a3be7b333ced0145460dbd895efb4e
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 sShortcut;
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 sShortcut = PLMakeString("Shortcut");
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[256];
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 = FlattenStringList(argv, argc);
230 XFreeStringList(argv);
232 if (!command)
233 return NULL;
235 if (PropGetWMClass(win, &class, &instance)) {
236 if (class && instance)
237 sprintf(buffer, "%s.%s", instance, class);
238 else if (instance)
239 sprintf(buffer, "%s", instance);
240 else if (class)
241 sprintf(buffer, ".%s", class);
242 else
243 sprintf(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 sprintf(buffer, "%ix%i+%i+%i", wwin->client.width, wwin->client.height,
254 wwin->frame_x, wwin->frame_y);
255 geometry = PLMakeString(buffer);
257 for (mask = 0, i = 0; i < MAX_WINDOW_SHORTCUTS; i++) {
258 if (WMGetFirstInBag(scr->shortcutWindows[i], wwin)) {
259 mask |= 1<<i;
263 sprintf(buffer, "%u", mask);
264 shortcut = PLMakeString(buffer);
266 win_state = PLMakeDictionaryFromEntries(sName, name,
267 sCommand, cmd,
268 sWorkspace, workspace,
269 sShaded, shaded,
270 sMiniaturized, miniaturized,
271 sHidden, hidden,
272 sShortcut, shortcut,
273 sGeometry, geometry,
274 NULL);
276 PLRelease(name);
277 PLRelease(cmd);
278 PLRelease(workspace);
279 PLRelease(geometry);
280 PLRelease(shortcut);
281 if (wapp && wapp->app_icon && wapp->app_icon->dock) {
282 int i;
283 char *name;
284 if (wapp->app_icon->dock == scr->dock) {
285 name="Dock";
286 } else {
287 for(i=0; i<scr->workspace_count; i++)
288 if(scr->workspaces[i]->clip == wapp->app_icon->dock)
289 break;
290 assert( i < scr->workspace_count);
291 /*n = i+1;*/
292 name = scr->workspaces[i]->name;
294 dock = PLMakeString(name);
295 PLInsertDictionaryEntry(win_state, sDock, dock);
296 PLRelease(dock);
298 } else {
299 win_state = NULL;
302 if (instance) XFree(instance);
303 if (class) XFree(class);
304 if (command) free(command);
306 return win_state;
310 void
311 wSessionSaveState(WScreen *scr)
313 WWindow *wwin = scr->focused_window;
314 proplist_t win_info, wks;
315 proplist_t list=NULL;
316 WMBag *wapp_list=NULL;
319 make_keys();
321 if (!scr->session_state) {
322 scr->session_state = PLMakeDictionaryFromEntries(NULL, NULL, NULL);
323 if (!scr->session_state)
324 return;
327 list = PLMakeArrayFromElements(NULL);
329 wapp_list = WMCreateBag(16);
331 while (wwin) {
332 WApplication *wapp=wApplicationOf(wwin->main_window);
334 if (wwin->transient_for==None && WMGetFirstInBag(wapp_list, wapp)<0
335 && !WFLAGP(wwin, dont_save_session)) {
336 /* A entry for this application was not yet saved. Save one. */
337 if ((win_info = makeWindowState(wwin, wapp))!=NULL) {
338 list = PLAppendArrayElement(list, win_info);
339 PLRelease(win_info);
340 /* If we were succesful in saving the info for this window
341 * add the application the window belongs to, to the
342 * application list, so no multiple entries for the same
343 * application are saved.
345 WMPutInBag(wapp_list, wapp);
348 wwin = wwin->prev;
350 PLRemoveDictionaryEntry(scr->session_state, sApplications);
351 PLInsertDictionaryEntry(scr->session_state, sApplications, list);
352 PLRelease(list);
354 wks = PLMakeString(scr->workspaces[scr->current_workspace]->name);
355 PLInsertDictionaryEntry(scr->session_state, sWorkspace, wks);
356 PLRelease(wks);
358 WMFreeBag(wapp_list);
362 void
363 wSessionClearState(WScreen *scr)
365 make_keys();
367 if (!scr->session_state)
368 return;
370 PLRemoveDictionaryEntry(scr->session_state, sApplications);
371 PLRemoveDictionaryEntry(scr->session_state, sWorkspace);
375 static pid_t
376 execCommand(WScreen *scr, char *command, char *host)
378 pid_t pid;
379 char **argv;
380 int argc;
382 ParseCommand(command, &argv, &argc);
384 if (argv==NULL) {
385 return 0;
388 if ((pid=fork())==0) {
389 char **args;
390 int i;
392 SetupEnvironment(scr);
394 args = malloc(sizeof(char*)*(argc+1));
395 if (!args)
396 exit(111);
397 for (i=0; i<argc; i++) {
398 args[i] = argv[i];
400 args[argc] = NULL;
401 execvp(argv[0], args);
402 exit(111);
404 while (argc > 0)
405 free(argv[--argc]);
406 free(argv);
407 return pid;
411 static WSavedState*
412 getWindowState(WScreen *scr, proplist_t win_state)
414 WSavedState *state = wmalloc(sizeof(WSavedState));
415 proplist_t value;
416 char *tmp;
417 unsigned mask;
418 int i;
420 memset(state, 0, sizeof(WSavedState));
421 state->workspace = -1;
422 value = PLGetDictionaryEntry(win_state, sWorkspace);
423 if (value && PLIsString(value)) {
424 tmp = PLGetString(value);
425 if (sscanf(tmp, "%i", &state->workspace)!=1) {
426 state->workspace = -1;
427 for (i=0; i < scr->workspace_count; i++) {
428 if (strcmp(scr->workspaces[i]->name, tmp)==0) {
429 state->workspace = i;
430 break;
433 } else {
434 state->workspace--;
437 if ((value = PLGetDictionaryEntry(win_state, sShaded))!=NULL)
438 state->shaded = getBool(value);
439 if ((value = PLGetDictionaryEntry(win_state, sMiniaturized))!=NULL)
440 state->miniaturized = getBool(value);
441 if ((value = PLGetDictionaryEntry(win_state, sHidden))!=NULL)
442 state->hidden = getBool(value);
443 if ((value = PLGetDictionaryEntry(win_state, sHidden))!=NULL) {
444 mask = getInt(value);
445 state->window_shortcuts = mask;
448 value = PLGetDictionaryEntry(win_state, sGeometry);
449 if (value && PLIsString(value)) {
450 if (sscanf(PLGetString(value), "%ix%i+%i+%i",
451 &state->w, &state->h, &state->x, &state->y)==4 &&
452 (state->w>0 && state->h>0)) {
453 state->use_geometry = 1;
454 } else if (sscanf(PLGetString(value), "%i,%i,%i,%i",
455 &state->x, &state->y, &state->w, &state->h)==4 &&
456 (state->w>0 && state->h>0)) {
457 /* TODO: remove redundant sscanf() in version 0.20.x */
458 state->use_geometry = 1;
463 return state;
467 #define SAME(x, y) (((x) && (y) && !strcmp((x), (y))) || (!(x) && !(y)))
469 void
470 wSessionRestoreState(WScreen *scr)
472 WSavedState *state;
473 char *instance, *class, *command, *host;
474 proplist_t win_info, apps, cmd, value;
475 pid_t pid;
476 int i, count;
477 WDock *dock;
478 WAppIcon *btn=NULL;
479 int j, n, found;
480 char *tmp;
482 make_keys();
484 if (!scr->session_state)
485 return;
487 PLSetStringCmpHook(NULL);
489 apps = PLGetDictionaryEntry(scr->session_state, sApplications);
490 if (!apps)
491 return;
493 count = PLGetNumberOfElements(apps);
494 if (count==0)
495 return;
497 for (i=0; i<count; i++) {
498 win_info = PLGetArrayElement(apps, i);
500 cmd = PLGetDictionaryEntry(win_info, sCommand);
501 if (!cmd || !PLIsString(cmd) || !(command = PLGetString(cmd))) {
502 continue;
505 value = PLGetDictionaryEntry(win_info, sName);
506 if (!value)
507 continue;
509 ParseWindowName(value, &instance, &class, "session");
510 if (!instance && !class)
511 continue;
513 value = PLGetDictionaryEntry(win_info, sHost);
514 if (value && PLIsString(value))
515 host = PLGetString(value);
516 else
517 host = NULL;
519 state = getWindowState(scr, win_info);
521 dock = NULL;
522 value = PLGetDictionaryEntry(win_info, sDock);
523 if (value && PLIsString(value) && (tmp = PLGetString(value))!=NULL) {
524 if (sscanf(tmp, "%i", &n)!=1) {
525 if (!strcasecmp(tmp, "DOCK")) {
526 dock = scr->dock;
527 } else {
528 for (j=0; j < scr->workspace_count; j++) {
529 if (strcmp(scr->workspaces[j]->name, tmp)==0) {
530 dock = scr->workspaces[j]->clip;
531 break;
535 } else {
536 if (n == 0) {
537 dock = scr->dock;
538 } else if (n>0 && n<=scr->workspace_count) {
539 dock = scr->workspaces[n-1]->clip;
544 found = 0;
545 if (dock!=NULL) {
546 for (j=0; j<dock->max_icons; j++) {
547 btn = dock->icon_array[j];
548 if (btn && SAME(instance, btn->wm_instance) &&
549 SAME(class, btn->wm_class) &&
550 SAME(command, btn->command) &&
551 !btn->launching) {
552 found = 1;
553 break;
558 if (found) {
559 wDockLaunchWithState(dock, btn, state);
560 } else if ((pid = execCommand(scr, command, host)) > 0) {
561 wWindowAddSavedState(instance, class, command, pid, state);
562 } else {
563 free(state);
566 if (instance) free(instance);
567 if (class) free(class);
569 /* clean up */
570 PLSetStringCmpHook(StringCompareHook);
574 void
575 wSessionRestoreLastWorkspace(WScreen *scr)
577 proplist_t wks;
578 int w, i;
579 char *tmp;
581 make_keys();
583 if (!scr->session_state)
584 return;
586 PLSetStringCmpHook(NULL);
588 wks = PLGetDictionaryEntry(scr->session_state, sWorkspace);
589 if (!wks || !PLIsString(wks))
590 return;
592 tmp = PLGetString(wks);
594 /* clean up */
595 PLSetStringCmpHook(StringCompareHook);
597 if (sscanf(tmp, "%i", &w)!=1) {
598 w = -1;
599 for (i=0; i < scr->workspace_count; i++) {
600 if (strcmp(scr->workspaces[i]->name, tmp)==0) {
601 w = i;
602 break;
605 } else {
606 w--;
609 if (w!=scr->current_workspace && w<scr->workspace_count) {
610 wWorkspaceChange(scr, w);
615 static void
616 clearWaitingAckState(WScreen *scr)
618 WWindow *wwin;
619 WApplication *wapp;
621 for (wwin = scr->focused_window; wwin != NULL; wwin = wwin->prev) {
622 wwin->flags.waiting_save_ack = 0;
623 if (wwin->main_window != None) {
624 wapp = wApplicationOf(wwin->main_window);
625 if (wapp)
626 wapp->main_window_desc->flags.waiting_save_ack = 0;
632 void
633 wSessionSaveClients(WScreen *scr)
640 * With XSMP, this job is done by smproxy
642 void
643 wSessionSendSaveYourself(WScreen *scr)
645 WWindow *wwin;
646 int count;
648 /* freeze client interaction with clients */
649 XGrabKeyboard(dpy, scr->root_win, False, GrabModeAsync, GrabModeAsync,
650 CurrentTime);
651 XGrabPointer(dpy, scr->root_win, False, ButtonPressMask|ButtonReleaseMask,
652 GrabModeAsync, GrabModeAsync, scr->root_win, None,
653 CurrentTime);
655 clearWaitingAckState(scr);
657 count = 0;
659 /* first send SAVE_YOURSELF for everybody */
660 for (wwin = scr->focused_window; wwin != NULL; wwin = wwin->prev) {
661 WWindow *mainWin;
663 mainWin = wWindowFor(wwin->main_window);
665 if (mainWin) {
666 /* if the client is a multi-window client, only send message
667 * to the main window */
668 wwin = mainWin;
671 /* make sure the SAVE_YOURSELF flag is up-to-date */
672 PropGetProtocols(wwin->client_win, &wwin->protocols);
674 if (wwin->protocols.SAVE_YOURSELF) {
675 if (!wwin->flags.waiting_save_ack) {
676 wClientSendProtocol(wwin, _XA_WM_SAVE_YOURSELF, LastTimestamp);
678 wwin->flags.waiting_save_ack = 1;
679 count++;
681 } else {
682 wwin->flags.waiting_save_ack = 0;
686 /* then wait for acknowledge */
687 while (count > 0) {
691 XUngrabPointer(dpy, CurrentTime);
692 XUngrabKeyboard(dpy, CurrentTime);
693 XFlush(dpy);
697 #ifdef XSMP_ENABLED
699 * With full session management support, the part of WMState
700 * that store client window state will become obsolete (maybe we can reuse
701 * the old code too),
702 * but we still need to store state info like the dock and workspaces.
703 * It is better to keep dock/wspace info in WMState because the user
704 * might want to keep the dock configuration while not wanting to
705 * resume a previously saved session.
706 * So, wmaker specific state info can be saved in
707 * ~/GNUstep/.AppInfo/WindowMaker/statename.state
708 * Its better to not put it in the defaults directory because:
709 * - its not a defaults file (having domain names like wmaker0089504baa
710 * in the defaults directory wouldn't be very neat)
711 * - this state file is not meant to be edited by users
713 * The old session code will become obsolete. When wmaker is
714 * compiled with R6 sm support compiled in, itll be better to
715 * use a totally rewritten state saving code, but we can keep
716 * the current code for when XSMP_ENABLED is not compiled in.
718 * This will be confusing to old users (well get lots of "SAVE_SESSION broke!"
719 * messages), but itll be better.
721 * -readme
725 static char*
726 getWindowRole(Window window)
728 XTextProperty prop;
729 static Atom atom = 0;
731 if (!atom)
732 atom = XInternAtom(dpy, "WM_WINDOW_ROLE", False);
734 if (XGetTextProperty(dpy, window, &prop, atom)) {
735 if (prop.encoding == XA_STRING && prop.format == 8 && prop.nitems > 0)
736 return prop.value;
739 return NULL;
745 * Saved Info:
747 * WM_WINDOW_ROLE
749 * WM_CLASS.instance
750 * WM_CLASS.class
751 * WM_NAME
752 * WM_COMMAND
754 * geometry
755 * state = (miniaturized, shaded, etc)
756 * attribute
757 * workspace #
758 * app state = (which dock, hidden)
759 * window shortcut #
762 static proplist_t
763 makeAppState(WWindow *wwin)
765 WApplication *wapp;
766 proplist_t state;
767 WScreen *scr = wwin->screen_ptr;
769 state = PLMakeArrayWithElements(NULL, NULL);
771 wapp = wApplicationOf(wwin->main_window);
773 if (wapp) {
774 if (wapp->app_icon && wapp->app_icon->dock) {
776 if (wapp->app_icon->dock == scr->dock) {
777 PLAppendArrayElement(state, PLMakeString("Dock"));
778 } else {
779 int i;
781 for(i=0; i<scr->workspace_count; i++)
782 if(scr->workspaces[i]->clip == wapp->app_icon->dock)
783 break;
785 assert(i < scr->workspace_count);
787 PLAppendArrayElement(state,
788 PLMakeString(scr->workspaces[i]->name));
792 PLAppendArrayElement(state, PLMakeString(wapp->hidden ? "1" : "0"));
795 return state;
800 Bool
801 wSessionGetStateFor(WWindow *wwin, WSessionData *state)
803 char *str;
804 proplist_t slist;
805 proplist_t elem;
806 proplist_t value;
807 int index = 0;
809 index = 3;
811 /* geometry */
812 value = PLGetArrayElement(slist, index++);
813 str = PLGetString(value);
815 sscanf(str, "%i %i %i %i %i %i", &state->x, &state->y,
816 &state->width, &state->height,
817 &state->user_changed_width, &state->user_changed_height);
820 /* state */
821 value = PLGetArrayElement(slist, index++);
822 str = PLGetString(value);
824 sscanf(str, "%i %i %i", &state->miniaturized, &state->shaded,
825 &state->maximized);
828 /* attributes */
829 value = PLGetArrayElement(slist, index++);
830 str = PLGetString(value);
832 getAttributeState(str, &state->mflags, &state->flags);
835 /* workspace */
836 value = PLGetArrayElement(slist, index++);
837 str = PLGetString(value);
839 sscanf(str, "%i", &state->workspace);
842 /* app state (repeated for all windows of the app) */
843 value = PLGetArrayElement(slist, index++);
844 str = PLGetString(value);
846 /* ???? */
848 /* shortcuts */
849 value = PLGetArrayElement(slist, index++);
850 str = PLGetString(value);
852 sscanf(str, "%i", &state->shortcuts);
857 static proplist_t
858 makeAttributeState(WWindow *wwin)
860 unsigned int data1, data2;
861 char buffer[256];
863 #define W_FLAG(wwin, FLAG) ((wwin)->defined_user_flags.FLAG \
864 ? (wwin)->user_flags.FLAG : -1)
866 sprintf(buffer,
867 "%i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i",
868 W_FLAG(no_titlebar),
869 W_FLAG(no_resizable),
870 W_FLAG(no_closable),
871 W_FLAG(no_miniaturizable),
872 W_FLAG(no_resizebar),
873 W_FLAG(no_close_button),
874 W_FLAG(no_miniaturize_button),
876 W_FLAG(broken_close),
877 W_FLAG(kill_close),
879 W_FLAG(no_shadeable),
880 W_FLAG(omnipresent),
881 W_FLAG(skip_window_list),
882 W_FLAG(floating),
883 W_FLAG(sunken),
884 W_FLAG(no_bind_keys),
885 W_FLAG(no_bind_mouse),
886 W_FLAG(no_hide_others),
887 W_FLAG(no_appicon),
888 W_FLAG(dont_move_off),
889 W_FLAG(no_focusable),
890 W_FLAG(always_user_icon),
891 W_FLAG(start_miniaturized),
892 W_FLAG(start_hidden),
893 W_FLAG(start_maximized),
894 W_FLAG(dont_save_session),
895 W_FLAG(emulate_appicon));
897 return PLMakeString(buffer);
901 static void
902 appendStringInArray(proplist_t array, char *str)
904 proplist_t val;
906 val = PLMakeString(str);
907 PLAppendArrayElement(array, val);
908 PLRelease(val);
912 static proplist_t
913 makeClientState(WWindow *wwin)
915 proplist_t state;
916 proplist_t tmp;
917 char *str;
918 char buffer[256];
919 int i;
920 unsigned shortcuts;
922 state = PLMakeArrayWithElements(NULL, NULL);
924 /* WM_WINDOW_ROLE */
925 str = getWindowRole(wwin->client_win);
926 if (!str)
927 appendStringInArray(state, "");
928 else {
929 appendStringInArray(state, str);
930 XFree(str);
933 /* WM_CLASS.instance */
934 appendStringInArray(state, wwin->wm_instance);
936 /* WM_CLASS.class */
937 appendStringInArray(state, wwin->wm_class);
939 /* WM_NAME */
940 if (wwin->flags.wm_name_changed)
941 appendStringInArray(state, "");
942 else
943 appendStringInArray(state, wwin->frame->name);
945 /* geometry */
946 sprintf(buffer, "%i %i %i %i %i %i", wwin->frame_x, wwin->frame_y,
947 wwin->client.width, wwin->client.height,
948 wwin->flags.user_changed_width, wwin->flags.user_changed_height);
949 appendStringInArray(state, buffer);
951 /* state */
952 sprintf(buffer, "%i %i %i", wwin->flags.miniaturized,
953 wwin->flags.shaded, wwin->flags.maximized);
954 appendStringInArray(state, buffer);
956 /* attributes */
957 tmp = makeAttributeState(wwin);
958 PLAppendArrayElement(state, tmp);
959 PLRelease(tmp);
961 /* workspace */
962 sprintf(buffer, "%i", wwin->frame->workspace);
963 appendStringInArray(state, buffer);
965 /* app state (repeated for all windows of the app) */
966 tmp = makeAppState(wwin);
967 PLAppendArrayElement(state, tmp);
968 PLRelease(tmp);
970 /* shortcuts */
971 shortcuts = 0;
972 for (i = 0; i < MAX_WINDOW_SHORTCUTS; i++) {
973 if (scr->shortcutWindow[i] == wwin) {
974 shortcuts |= 1 << i;
977 sprintf(buffer, "%ui", shortcuts);
978 appendStringInArray(tmp, buffer);
980 return state;
984 static void
985 smSaveYourselfPhase2Proc(SmcConn smc_conn, SmPointer client_data)
987 SmProp props[4];
988 SmPropValue prop1val, prop2val, prop3val, prop4val;
989 char **argv = (char**)client_data;
990 int argc;
991 int i, j;
992 Bool ok = False;
993 char *statefile = NULL;
994 char *prefix;
995 Bool gsPrefix = False;
996 char *discardCmd = NULL;
997 time_t t;
998 proplist_t state;
1000 #ifdef DEBUG1
1001 puts("received SaveYourselfPhase2 SM message");
1002 #endif
1004 /* save session state */
1006 /* the file that will contain the state */
1007 prefix = getenv("SM_SAVE_DIR");
1008 if (!prefix) {
1009 prefix = wusergnusteppath();
1010 if (prefix)
1011 gsPrefix = True;
1013 if (!prefix) {
1014 prefix = getenv("HOME");
1016 if (!prefix)
1017 prefix = ".";
1019 statefile = malloc(strlen(prefix)+64);
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 sprintf(statefile, "%s/.AppInfo/WindowMaker/wmaker.%l%i.state",
1030 prefix, t, i);
1031 else
1032 sprintf(statefile, "%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 sprintf(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);
1140 discardCmd = malloc(strlen(statefile)+8);
1141 if (!discardCmd)
1142 goto fail;
1143 sprintf(discardCmd, "rm %s", statefile);
1144 prop[2].name = SmDiscardCommand;
1145 prop[2].type = SmARRAY8;
1146 prop[2].vals[0] = discardCmd;
1147 prop[2].num_vals = 1;
1149 SmcSetProperties(sSMCConn, 3, prop);
1151 ok = True;
1152 fail:
1153 SmcSaveYourselfDone(smc_conn, ok);
1155 if (prop[0].vals)
1156 free(prop[0].vals);
1157 if (prop[1].vals)
1158 free(prop[1].vals);
1159 if (discardCmd)
1160 free(discardCmd);
1162 if (!ok) {
1163 remove(statefile);
1165 if (statefile)
1166 free(statefile);
1170 static void
1171 smSaveYourselfProc(SmcConn smc_conn, SmPointer client_data, int save_type,
1172 Bool shutdown, int interact_style, Bool fast)
1174 #ifdef DEBUG1
1175 puts("received SaveYourself SM message");
1176 #endif
1178 if (!SmcRequestSaveYourselfPhase2(smc_conn, smSaveYourselfPhase2Proc,
1179 client_data)) {
1181 SmcSaveYourselfDone(smc_conn, False);
1182 sWaitingPhase2 = False;
1183 } else {
1184 #ifdef DEBUG1
1185 puts("successfull request of SYS phase 2");
1186 #endif
1187 sWaitingPhase2 = True;
1192 static void
1193 smDieProc(SmcConn smc_conn, SmPointer client_data)
1195 #ifdef DEBUG1
1196 puts("received Die SM message");
1197 #endif
1199 wSessionDisconnectManager();
1201 Shutdown(WSExitMode, True);
1206 static void
1207 smSaveCompleteProc(SmcConn smc_conn)
1209 /* it means that we can resume doing things that can change our state */
1210 #ifdef DEBUG1
1211 puts("received SaveComplete SM message");
1212 #endif
1216 static void
1217 smShutdownCancelledProc(SmcConn smc_conn, SmPointer client_data)
1219 if (sWaitingPhase2) {
1221 sWaitingPhase2 = False;
1223 SmcSaveYourselfDone(smc_conn, False);
1228 static void
1229 iceMessageProc(int fd, int mask, void *clientData)
1231 IceConn iceConn = (IceConn)clientData;
1233 IceProcessMessages(iceConn, NULL, NULL);
1237 static void
1238 iceIOErrorHandler(IceConnection ice_conn)
1240 /* This is not fatal but can mean the session manager exited.
1241 * If the session manager exited normally we would get a
1242 * Die message, so this probably means an abnormal exit.
1243 * If the sm was the last client of session, then we'll die
1244 * anyway, otherwise we can continue doing our stuff.
1246 wwarning(_("connection to the session manager was lost"));
1247 wSessionDisconnectManager();
1251 void
1252 wSessionConnectManager(char **argv, int argc)
1254 IceConn iceConn;
1255 char *previous_id = NULL;
1256 char buffer[256];
1257 SmcCallbacks callbacks;
1258 unsigned long mask;
1259 char uid[32];
1260 char pid[32];
1261 SmProp props[4];
1262 SmPropValue prop1val, prop2val, prop3val, prop4val;
1263 char restartStyle;
1264 int i;
1266 mask = SmcSaveYourselfProcMask|SmcDieProcMask|SmcSaveCompleteProcMask
1267 |SmcShutdownCancelledProcMask;
1269 callbacks.save_yourself.callback = smSaveYourselfProc;
1270 callbacks.save_yourself.client_data = argv;
1272 callbacks.die.callback = smDieProc;
1273 callbacks.die.client_data = NULL;
1275 callbacks.save_complete.callback = smSaveCompleteProc;
1276 callbacks.save_complete.client_data = NULL;
1278 callbacks.shutdown_cancelled.callback = smShutdownCancelledProc;
1279 callbacks.shutdown_cancelled.client_data = NULL;
1281 for (i=0; i<argc; i++) {
1282 if (strcmp(argv[i], "-clientid")==0) {
1283 previous_id = argv[i+1];
1284 break;
1288 /* connect to the session manager */
1289 sSMCConn = SmcOpenConnection(NULL, NULL, SmProtoMajor, SmProtoMinor,
1290 mask, &callbacks, previous_id,
1291 &sClientID, 255, buffer);
1292 if (!sSMCConn) {
1293 return;
1295 #ifdef DEBUG1
1296 puts("connected to the session manager");
1297 #endif
1299 /* IceSetIOErrorHandler(iceIOErrorHandler);*/
1301 /* check for session manager clients */
1302 iceConn = SmcGetIceConnection(smcConn);
1304 if (fcntl(IceConnectionNumber(iceConn), F_SETFD, FD_CLOEXEC) < 0) {
1305 wsyserror("error setting close-on-exec flag for ICE connection");
1308 sSMInputHandler = WMAddInputHandler(IceConnectionNumber(iceConn),
1309 WIReadMask, iceMessageProc, iceConn);
1311 /* setup information about ourselves */
1313 /* program name */
1314 prop1val.value = argv[0];
1315 prop1val.length = strlen(argv[0]);
1316 prop[0].name = SmProgram;
1317 prop[0].type = SmARRAY8;
1318 prop[0].num_vals = 1;
1319 prop[0].vals = &prop1val;
1321 /* The XSMP doc from X11R6.1 says it contains the user name,
1322 * but every client implementation I saw places the uid # */
1323 sprintf(uid, "%i", getuid());
1324 prop2val.value = uid;
1325 prop2val.length = strlen(uid);
1326 prop[1].name = SmUserID;
1327 prop[1].type = SmARRAY8;
1328 prop[1].num_vals = 1;
1329 prop[1].vals = &prop2val;
1331 /* Restart style. We should restart only if we were running when
1332 * the previous session finished. */
1333 restartStyle = SmRestartIfRunning;
1334 prop3val.value = &restartStyle;
1335 prop3val.length = 1;
1336 prop[2].name = SmRestartStyleHint;
1337 prop[2].type = SmCARD8;
1338 prop[2].num_vals = 1;
1339 prop[2].vals = &prop3val;
1341 /* Our PID. Not required but might be usefull */
1342 sprintf(pid, "%i", getpid());
1343 prop4val.value = pid;
1344 prop4val.length = strlen(pid);
1345 prop[3].name = SmProcessID;
1346 prop[3].type = SmARRAY8;
1347 prop[3].num_vals = 1;
1348 prop[3].vals = &prop4val;
1350 /* we'll set the rest of the hints later */
1352 SmcSetProperties(sSMCConn, 4, props);
1357 void
1358 wSessionDisconnectManager(void)
1360 if (sSMCConn) {
1361 WMDeleteInputHandler(sSMInputHandler);
1362 sSMInputHandler = NULL;
1364 SmcCloseConnection(sSMCConn, 0, NULL);
1365 sSMCConn = NULL;
1369 void
1370 wSessionRequestShutdown(void)
1372 /* request a shutdown to the session manager */
1373 if (sSMCConn)
1374 SmcRequestSaveYourself(sSMCConn, SmSaveBoth, True, SmInteractStyleAny,
1375 False, True);
1379 Bool
1380 wSessionIsManaged(void)
1382 return sSMCConn!=NULL;
1385 #endif /* !XSMP_ENABLED */