Fixed splitviews regarding index access (first element was never accesible)
[wmaker-crm.git] / src / session.c
blob59296f196f6794812567bd350d94a121f8f3bfae
1 /* session.c - session state handling and R6 style session management
3 * Copyright (c) 1998 Dan Pascu
4 * Copyright (c) 1998, 1999 Alfredo Kojima
6 * Window Maker window manager
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
21 * USA.
27 * If defined(XSMP_ENABLED) and session manager is running then
28 * do normal stuff
29 * else
30 * do pre-R6 session management stuff (save window state and relaunch)
32 * When doing a checkpoint:
34 * = Without XSMP
35 * Open "Stop"/status Dialog
36 * Send SAVE_YOURSELF to clients and wait for reply
37 * Save restart info
38 * Save state of clients
40 * = With XSMP
41 * Send checkpoint request to sm
43 * When exiting:
44 * -------------
46 * = Without XSMP
48 * Open "Exit Now"/status Dialog
49 * Send SAVE_YOURSELF to clients and wait for reply
50 * Save restart info
51 * Save state of clients
52 * Send DELETE to all clients
53 * When no more clients are left or user hit "Exit Now", exit
55 * = With XSMP
57 * Send Shutdown request to session manager
58 * if SaveYourself message received, save state of clients
59 * if the Die message is received, exit.
62 #include "wconfig.h"
64 #include <X11/Xlib.h>
65 #include <X11/Xutil.h>
67 #ifdef XSMP_ENABLED
68 #include <X11/SM/SMlib.h>
69 #endif
71 #include <stdlib.h>
72 #include <stdio.h>
73 #include <string.h>
74 #include <unistd.h>
75 #include <time.h>
78 #include "WindowMaker.h"
79 #include "screen.h"
80 #include "window.h"
81 #include "client.h"
82 #include "session.h"
83 #include "wcore.h"
84 #include "framewin.h"
85 #include "workspace.h"
86 #include "funcs.h"
87 #include "properties.h"
88 #include "application.h"
89 #include "appicon.h"
92 #include "dock.h"
95 #include <proplist.h>
97 /** Global **/
99 extern Atom _XA_WM_SAVE_YOURSELF;
101 extern Time LastTimestamp;
103 #ifdef XSMP_ENABLED
105 extern int wScreenCount;
107 /* requested for SaveYourselfPhase2 */
108 static Bool sWaitingPhase2 = False;
110 static SmcConn sSMCConn = NULL;
112 static WMHandlerID sSMInputHandler = NULL;
114 /* our SM client ID */
115 static char *sClientID = NULL;
116 #endif
119 static proplist_t sApplications = NULL;
120 static proplist_t sCommand;
121 static proplist_t sName;
122 static proplist_t sHost;
123 static proplist_t sWorkspace;
124 static proplist_t sShaded;
125 static proplist_t sMiniaturized;
126 static proplist_t sHidden;
127 static proplist_t sGeometry;
128 static proplist_t sShortcutMask;
130 static proplist_t sDock;
132 static proplist_t sYes, sNo;
135 static void
136 make_keys()
138 if (sApplications!=NULL)
139 return;
141 sApplications = PLMakeString("Applications");
142 sCommand = PLMakeString("Command");
143 sName = PLMakeString("Name");
144 sHost = PLMakeString("Host");
145 sWorkspace = PLMakeString("Workspace");
146 sShaded = PLMakeString("Shaded");
147 sMiniaturized = PLMakeString("Miniaturized");
148 sHidden = PLMakeString("Hidden");
149 sGeometry = PLMakeString("Geometry");
150 sDock = PLMakeString("Dock");
151 sShortcutMask = PLMakeString("ShortcutMask");
153 sYes = PLMakeString("Yes");
154 sNo = PLMakeString("No");
159 static int
160 getBool(proplist_t value)
162 char *val;
164 if (!PLIsString(value)) {
165 return 0;
167 if (!(val = PLGetString(value))) {
168 return 0;
171 if ((val[1]=='\0' && (val[0]=='y' || val[0]=='Y'))
172 || strcasecmp(val, "YES")==0) {
174 return 1;
175 } else if ((val[1]=='\0' && (val[0]=='n' || val[0]=='N'))
176 || strcasecmp(val, "NO")==0) {
177 return 0;
178 } else {
179 int i;
180 if (sscanf(val, "%i", &i)==1) {
181 return (i!=0);
182 } else {
183 wwarning(_("can't convert \"%s\" to boolean"), val);
184 return 0;
190 static unsigned
191 getInt(proplist_t value)
193 char *val;
194 unsigned n;
196 if (!PLIsString(value))
197 return 0;
198 val = PLGetString(value);
199 if (!val)
200 return 0;
201 if (sscanf(val, "%u", &n) != 1)
202 return 0;
204 return n;
209 static proplist_t
210 makeWindowState(WWindow *wwin, WApplication *wapp)
212 WScreen *scr = wwin->screen_ptr;
213 Window win;
214 int argc;
215 char **argv;
216 int i;
217 unsigned mask;
218 char *class, *instance, *command=NULL, buffer[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 = wtokenjoin(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 (scr->shortcutWindows[i] != NULL &&
259 WMGetFirstInBag(scr->shortcutWindows[i], wwin) != WBNotFound) {
260 mask |= 1<<i;
264 sprintf(buffer, "%u", mask);
265 shortcut = PLMakeString(buffer);
267 win_state = PLMakeDictionaryFromEntries(sName, name,
268 sCommand, cmd,
269 sWorkspace, workspace,
270 sShaded, shaded,
271 sMiniaturized, miniaturized,
272 sHidden, hidden,
273 sShortcutMask, shortcut,
274 sGeometry, geometry,
275 NULL);
277 PLRelease(name);
278 PLRelease(cmd);
279 PLRelease(workspace);
280 PLRelease(geometry);
281 PLRelease(shortcut);
282 if (wapp && wapp->app_icon && wapp->app_icon->dock) {
283 int i;
284 char *name;
285 if (wapp->app_icon->dock == scr->dock) {
286 name="Dock";
287 } else {
288 for(i=0; i<scr->workspace_count; i++)
289 if(scr->workspaces[i]->clip == wapp->app_icon->dock)
290 break;
291 assert( i < scr->workspace_count);
292 /*n = i+1;*/
293 name = scr->workspaces[i]->name;
295 dock = PLMakeString(name);
296 PLInsertDictionaryEntry(win_state, sDock, dock);
297 PLRelease(dock);
299 } else {
300 win_state = NULL;
303 if (instance) XFree(instance);
304 if (class) XFree(class);
305 if (command) wfree(command);
307 return win_state;
311 void
312 wSessionSaveState(WScreen *scr)
314 WWindow *wwin = scr->focused_window;
315 proplist_t win_info, wks;
316 proplist_t list=NULL;
317 WMBag *wapp_list=NULL;
320 make_keys();
322 if (!scr->session_state) {
323 scr->session_state = PLMakeDictionaryFromEntries(NULL, NULL, NULL);
324 if (!scr->session_state)
325 return;
328 list = PLMakeArrayFromElements(NULL);
330 wapp_list = WMCreateBag(16);
332 while (wwin) {
333 WApplication *wapp=wApplicationOf(wwin->main_window);
335 if (wwin->transient_for==None
336 && WMGetFirstInBag(wapp_list, wapp)==WBNotFound
337 && !WFLAGP(wwin, dont_save_session)) {
338 /* A entry for this application was not yet saved. Save one. */
339 if ((win_info = makeWindowState(wwin, wapp))!=NULL) {
340 list = PLAppendArrayElement(list, win_info);
341 PLRelease(win_info);
342 /* If we were succesful in saving the info for this window
343 * add the application the window belongs to, to the
344 * application list, so no multiple entries for the same
345 * application are saved.
347 WMPutInBag(wapp_list, wapp);
350 wwin = wwin->prev;
352 PLRemoveDictionaryEntry(scr->session_state, sApplications);
353 PLInsertDictionaryEntry(scr->session_state, sApplications, list);
354 PLRelease(list);
356 wks = PLMakeString(scr->workspaces[scr->current_workspace]->name);
357 PLInsertDictionaryEntry(scr->session_state, sWorkspace, wks);
358 PLRelease(wks);
360 WMFreeBag(wapp_list);
364 void
365 wSessionClearState(WScreen *scr)
367 make_keys();
369 if (!scr->session_state)
370 return;
372 PLRemoveDictionaryEntry(scr->session_state, sApplications);
373 PLRemoveDictionaryEntry(scr->session_state, sWorkspace);
377 static pid_t
378 execCommand(WScreen *scr, char *command, char *host)
380 pid_t pid;
381 char **argv;
382 int argc;
384 wtokensplit(command, &argv, &argc);
386 if (argv==NULL) {
387 return 0;
390 if ((pid=fork())==0) {
391 char **args;
392 int i;
394 SetupEnvironment(scr);
396 args = malloc(sizeof(char*)*(argc+1));
397 if (!args)
398 exit(111);
399 for (i=0; i<argc; i++) {
400 args[i] = argv[i];
402 args[argc] = NULL;
403 execvp(argv[0], args);
404 exit(111);
406 while (argc > 0)
407 wfree(argv[--argc]);
408 wfree(argv);
409 return pid;
413 static WSavedState*
414 getWindowState(WScreen *scr, proplist_t win_state)
416 WSavedState *state = wmalloc(sizeof(WSavedState));
417 proplist_t value;
418 char *tmp;
419 unsigned mask;
420 int i;
422 memset(state, 0, sizeof(WSavedState));
423 state->workspace = -1;
424 value = PLGetDictionaryEntry(win_state, sWorkspace);
425 if (value && PLIsString(value)) {
426 tmp = PLGetString(value);
427 if (sscanf(tmp, "%i", &state->workspace)!=1) {
428 state->workspace = -1;
429 for (i=0; i < scr->workspace_count; i++) {
430 if (strcmp(scr->workspaces[i]->name, tmp)==0) {
431 state->workspace = i;
432 break;
435 } else {
436 state->workspace--;
439 if ((value = PLGetDictionaryEntry(win_state, sShaded))!=NULL)
440 state->shaded = getBool(value);
441 if ((value = PLGetDictionaryEntry(win_state, sMiniaturized))!=NULL)
442 state->miniaturized = getBool(value);
443 if ((value = PLGetDictionaryEntry(win_state, sHidden))!=NULL)
444 state->hidden = getBool(value);
445 if ((value = PLGetDictionaryEntry(win_state, sShortcutMask))!=NULL) {
446 mask = getInt(value);
447 state->window_shortcuts = mask;
450 value = PLGetDictionaryEntry(win_state, sGeometry);
451 if (value && PLIsString(value)) {
452 if (!(sscanf(PLGetString(value), "%ix%i+%i+%i",
453 &state->w, &state->h, &state->x, &state->y)==4 &&
454 (state->w>0 && state->h>0))) {
455 state->w = 0;
456 state->h = 0;
460 return state;
464 #define SAME(x, y) (((x) && (y) && !strcmp((x), (y))) || (!(x) && !(y)))
466 void
467 wSessionRestoreState(WScreen *scr)
469 WSavedState *state;
470 char *instance, *class, *command, *host;
471 proplist_t win_info, apps, cmd, value;
472 pid_t pid;
473 int i, count;
474 WDock *dock;
475 WAppIcon *btn=NULL;
476 int j, n, found;
477 char *tmp;
479 make_keys();
481 if (!scr->session_state)
482 return;
484 PLSetStringCmpHook(NULL);
486 apps = PLGetDictionaryEntry(scr->session_state, sApplications);
487 if (!apps)
488 return;
490 count = PLGetNumberOfElements(apps);
491 if (count==0)
492 return;
494 for (i=0; i<count; i++) {
495 win_info = PLGetArrayElement(apps, i);
497 cmd = PLGetDictionaryEntry(win_info, sCommand);
498 if (!cmd || !PLIsString(cmd) || !(command = PLGetString(cmd))) {
499 continue;
502 value = PLGetDictionaryEntry(win_info, sName);
503 if (!value)
504 continue;
506 ParseWindowName(value, &instance, &class, "session");
507 if (!instance && !class)
508 continue;
510 value = PLGetDictionaryEntry(win_info, sHost);
511 if (value && PLIsString(value))
512 host = PLGetString(value);
513 else
514 host = NULL;
516 state = getWindowState(scr, win_info);
518 dock = NULL;
519 value = PLGetDictionaryEntry(win_info, sDock);
520 if (value && PLIsString(value) && (tmp = PLGetString(value))!=NULL) {
521 if (sscanf(tmp, "%i", &n)!=1) {
522 if (!strcasecmp(tmp, "DOCK")) {
523 dock = scr->dock;
524 } else {
525 for (j=0; j < scr->workspace_count; j++) {
526 if (strcmp(scr->workspaces[j]->name, tmp)==0) {
527 dock = scr->workspaces[j]->clip;
528 break;
532 } else {
533 if (n == 0) {
534 dock = scr->dock;
535 } else if (n>0 && n<=scr->workspace_count) {
536 dock = scr->workspaces[n-1]->clip;
541 found = 0;
542 if (dock!=NULL) {
543 for (j=0; j<dock->max_icons; j++) {
544 btn = dock->icon_array[j];
545 if (btn && SAME(instance, btn->wm_instance) &&
546 SAME(class, btn->wm_class) &&
547 SAME(command, btn->command) &&
548 !btn->launching) {
549 found = 1;
550 break;
555 if (found) {
556 wDockLaunchWithState(dock, btn, state);
557 } else if ((pid = execCommand(scr, command, host)) > 0) {
558 wWindowAddSavedState(instance, class, command, pid, state);
559 } else {
560 wfree(state);
563 if (instance) wfree(instance);
564 if (class) wfree(class);
566 /* clean up */
567 PLSetStringCmpHook(StringCompareHook);
571 void
572 wSessionRestoreLastWorkspace(WScreen *scr)
574 proplist_t wks;
575 int w, i;
576 char *tmp;
578 make_keys();
580 if (!scr->session_state)
581 return;
583 PLSetStringCmpHook(NULL);
585 wks = PLGetDictionaryEntry(scr->session_state, sWorkspace);
586 if (!wks || !PLIsString(wks))
587 return;
589 tmp = PLGetString(wks);
591 /* clean up */
592 PLSetStringCmpHook(StringCompareHook);
594 if (sscanf(tmp, "%i", &w)!=1) {
595 w = -1;
596 for (i=0; i < scr->workspace_count; i++) {
597 if (strcmp(scr->workspaces[i]->name, tmp)==0) {
598 w = i;
599 break;
602 } else {
603 w--;
606 if (w!=scr->current_workspace && w<scr->workspace_count) {
607 wWorkspaceChange(scr, w);
612 static void
613 clearWaitingAckState(WScreen *scr)
615 WWindow *wwin;
616 WApplication *wapp;
618 for (wwin = scr->focused_window; wwin != NULL; wwin = wwin->prev) {
619 wwin->flags.waiting_save_ack = 0;
620 if (wwin->main_window != None) {
621 wapp = wApplicationOf(wwin->main_window);
622 if (wapp)
623 wapp->main_window_desc->flags.waiting_save_ack = 0;
629 void
630 wSessionSaveClients(WScreen *scr)
637 * With XSMP, this job is done by smproxy
639 void
640 wSessionSendSaveYourself(WScreen *scr)
642 WWindow *wwin;
643 int count;
645 /* freeze client interaction with clients */
646 XGrabKeyboard(dpy, scr->root_win, False, GrabModeAsync, GrabModeAsync,
647 CurrentTime);
648 XGrabPointer(dpy, scr->root_win, False, ButtonPressMask|ButtonReleaseMask,
649 GrabModeAsync, GrabModeAsync, scr->root_win, None,
650 CurrentTime);
652 clearWaitingAckState(scr);
654 count = 0;
656 /* first send SAVE_YOURSELF for everybody */
657 for (wwin = scr->focused_window; wwin != NULL; wwin = wwin->prev) {
658 WWindow *mainWin;
660 mainWin = wWindowFor(wwin->main_window);
662 if (mainWin) {
663 /* if the client is a multi-window client, only send message
664 * to the main window */
665 wwin = mainWin;
668 /* make sure the SAVE_YOURSELF flag is up-to-date */
669 PropGetProtocols(wwin->client_win, &wwin->protocols);
671 if (wwin->protocols.SAVE_YOURSELF) {
672 if (!wwin->flags.waiting_save_ack) {
673 wClientSendProtocol(wwin, _XA_WM_SAVE_YOURSELF, LastTimestamp);
675 wwin->flags.waiting_save_ack = 1;
676 count++;
678 } else {
679 wwin->flags.waiting_save_ack = 0;
683 /* then wait for acknowledge */
684 while (count > 0) {
688 XUngrabPointer(dpy, CurrentTime);
689 XUngrabKeyboard(dpy, CurrentTime);
690 XFlush(dpy);
694 #ifdef XSMP_ENABLED
696 * With full session management support, the part of WMState
697 * that store client window state will become obsolete (maybe we can reuse
698 * the old code too),
699 * but we still need to store state info like the dock and workspaces.
700 * It is better to keep dock/wspace info in WMState because the user
701 * might want to keep the dock configuration while not wanting to
702 * resume a previously saved session.
703 * So, wmaker specific state info can be saved in
704 * ~/GNUstep/.AppInfo/WindowMaker/statename.state
705 * Its better to not put it in the defaults directory because:
706 * - its not a defaults file (having domain names like wmaker0089504baa
707 * in the defaults directory wouldn't be very neat)
708 * - this state file is not meant to be edited by users
710 * The old session code will become obsolete. When wmaker is
711 * compiled with R6 sm support compiled in, itll be better to
712 * use a totally rewritten state saving code, but we can keep
713 * the current code for when XSMP_ENABLED is not compiled in.
715 * This will be confusing to old users (well get lots of "SAVE_SESSION broke!"
716 * messages), but itll be better.
718 * -readme
722 static char*
723 getWindowRole(Window window)
725 XTextProperty prop;
726 static Atom atom = 0;
728 if (!atom)
729 atom = XInternAtom(dpy, "WM_WINDOW_ROLE", False);
731 if (XGetTextProperty(dpy, window, &prop, atom)) {
732 if (prop.encoding == XA_STRING && prop.format == 8 && prop.nitems > 0)
733 return prop.value;
736 return NULL;
742 * Saved Info:
744 * WM_WINDOW_ROLE
746 * WM_CLASS.instance
747 * WM_CLASS.class
748 * WM_NAME
749 * WM_COMMAND
751 * geometry
752 * state = (miniaturized, shaded, etc)
753 * attribute
754 * workspace #
755 * app state = (which dock, hidden)
756 * window shortcut #
759 static proplist_t
760 makeAppState(WWindow *wwin)
762 WApplication *wapp;
763 proplist_t state;
764 WScreen *scr = wwin->screen_ptr;
766 state = PLMakeArrayWithElements(NULL, NULL);
768 wapp = wApplicationOf(wwin->main_window);
770 if (wapp) {
771 if (wapp->app_icon && wapp->app_icon->dock) {
773 if (wapp->app_icon->dock == scr->dock) {
774 PLAppendArrayElement(state, PLMakeString("Dock"));
775 } else {
776 int i;
778 for(i=0; i<scr->workspace_count; i++)
779 if(scr->workspaces[i]->clip == wapp->app_icon->dock)
780 break;
782 assert(i < scr->workspace_count);
784 PLAppendArrayElement(state,
785 PLMakeString(scr->workspaces[i]->name));
789 PLAppendArrayElement(state, PLMakeString(wapp->hidden ? "1" : "0"));
792 return state;
797 Bool
798 wSessionGetStateFor(WWindow *wwin, WSessionData *state)
800 char *str;
801 proplist_t slist;
802 proplist_t elem;
803 proplist_t value;
804 int index = 0;
806 index = 3;
808 /* geometry */
809 value = PLGetArrayElement(slist, index++);
810 str = PLGetString(value);
812 sscanf(str, "%i %i %i %i %i %i", &state->x, &state->y,
813 &state->width, &state->height,
814 &state->user_changed_width, &state->user_changed_height);
817 /* state */
818 value = PLGetArrayElement(slist, index++);
819 str = PLGetString(value);
821 sscanf(str, "%i %i %i", &state->miniaturized, &state->shaded,
822 &state->maximized);
825 /* attributes */
826 value = PLGetArrayElement(slist, index++);
827 str = PLGetString(value);
829 getAttributeState(str, &state->mflags, &state->flags);
832 /* workspace */
833 value = PLGetArrayElement(slist, index++);
834 str = PLGetString(value);
836 sscanf(str, "%i", &state->workspace);
839 /* app state (repeated for all windows of the app) */
840 value = PLGetArrayElement(slist, index++);
841 str = PLGetString(value);
843 /* ???? */
845 /* shortcuts */
846 value = PLGetArrayElement(slist, index++);
847 str = PLGetString(value);
849 sscanf(str, "%i", &state->shortcuts);
854 static proplist_t
855 makeAttributeState(WWindow *wwin)
857 unsigned int data1, data2;
858 char buffer[256];
860 #define W_FLAG(wwin, FLAG) ((wwin)->defined_user_flags.FLAG \
861 ? (wwin)->user_flags.FLAG : -1)
863 sprintf(buffer,
864 "%i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i",
865 W_FLAG(no_titlebar),
866 W_FLAG(no_resizable),
867 W_FLAG(no_closable),
868 W_FLAG(no_miniaturizable),
869 W_FLAG(no_resizebar),
870 W_FLAG(no_close_button),
871 W_FLAG(no_miniaturize_button),
873 W_FLAG(broken_close),
874 W_FLAG(kill_close),
876 W_FLAG(no_shadeable),
877 W_FLAG(omnipresent),
878 W_FLAG(skip_window_list),
879 W_FLAG(floating),
880 W_FLAG(sunken),
881 W_FLAG(no_bind_keys),
882 W_FLAG(no_bind_mouse),
883 W_FLAG(no_hide_others),
884 W_FLAG(no_appicon),
885 W_FLAG(dont_move_off),
886 W_FLAG(no_focusable),
887 W_FLAG(always_user_icon),
888 W_FLAG(start_miniaturized),
889 W_FLAG(start_hidden),
890 W_FLAG(start_maximized),
891 W_FLAG(dont_save_session),
892 W_FLAG(emulate_appicon));
894 return PLMakeString(buffer);
898 static void
899 appendStringInArray(proplist_t array, char *str)
901 proplist_t val;
903 val = PLMakeString(str);
904 PLAppendArrayElement(array, val);
905 PLRelease(val);
909 static proplist_t
910 makeClientState(WWindow *wwin)
912 proplist_t state;
913 proplist_t tmp;
914 char *str;
915 char buffer[256];
916 int i;
917 unsigned shortcuts;
919 state = PLMakeArrayWithElements(NULL, NULL);
921 /* WM_WINDOW_ROLE */
922 str = getWindowRole(wwin->client_win);
923 if (!str)
924 appendStringInArray(state, "");
925 else {
926 appendStringInArray(state, str);
927 XFree(str);
930 /* WM_CLASS.instance */
931 appendStringInArray(state, wwin->wm_instance);
933 /* WM_CLASS.class */
934 appendStringInArray(state, wwin->wm_class);
936 /* WM_NAME */
937 if (wwin->flags.wm_name_changed)
938 appendStringInArray(state, "");
939 else
940 appendStringInArray(state, wwin->frame->name);
942 /* geometry */
943 sprintf(buffer, "%i %i %i %i %i %i", wwin->frame_x, wwin->frame_y,
944 wwin->client.width, wwin->client.height,
945 wwin->flags.user_changed_width, wwin->flags.user_changed_height);
946 appendStringInArray(state, buffer);
948 /* state */
949 sprintf(buffer, "%i %i %i", wwin->flags.miniaturized,
950 wwin->flags.shaded, wwin->flags.maximized);
951 appendStringInArray(state, buffer);
953 /* attributes */
954 tmp = makeAttributeState(wwin);
955 PLAppendArrayElement(state, tmp);
956 PLRelease(tmp);
958 /* workspace */
959 sprintf(buffer, "%i", wwin->frame->workspace);
960 appendStringInArray(state, buffer);
962 /* app state (repeated for all windows of the app) */
963 tmp = makeAppState(wwin);
964 PLAppendArrayElement(state, tmp);
965 PLRelease(tmp);
967 /* shortcuts */
968 shortcuts = 0;
969 for (i = 0; i < MAX_WINDOW_SHORTCUTS; i++) {
970 if (scr->shortcutWindow[i] == wwin) {
971 shortcuts |= 1 << i;
974 sprintf(buffer, "%ui", shortcuts);
975 appendStringInArray(tmp, buffer);
977 return state;
981 static void
982 smSaveYourselfPhase2Proc(SmcConn smc_conn, SmPointer client_data)
984 SmProp props[4];
985 SmPropValue prop1val, prop2val, prop3val, prop4val;
986 char **argv = (char**)client_data;
987 int argc;
988 int i, j;
989 Bool ok = False;
990 char *statefile = NULL;
991 char *prefix;
992 Bool gsPrefix = False;
993 char *discardCmd = NULL;
994 time_t t;
995 proplist_t state;
997 #ifdef DEBUG1
998 puts("received SaveYourselfPhase2 SM message");
999 #endif
1001 /* save session state */
1003 /* the file that will contain the state */
1004 prefix = getenv("SM_SAVE_DIR");
1005 if (!prefix) {
1006 prefix = wusergnusteppath();
1007 if (prefix)
1008 gsPrefix = True;
1010 if (!prefix) {
1011 prefix = getenv("HOME");
1013 if (!prefix)
1014 prefix = ".";
1016 statefile = malloc(strlen(prefix)+64);
1017 if (!statefile) {
1018 wwarning(_("out of memory while saving session state"));
1019 goto fail;
1022 t = time();
1023 i = 0;
1024 do {
1025 if (gsPrefix)
1026 sprintf(statefile, "%s/.AppInfo/WindowMaker/wmaker.%l%i.state",
1027 prefix, t, i);
1028 else
1029 sprintf(statefile, "%s/wmaker.%l%i.state", prefix, t, i);
1030 i++;
1031 } while (access(F_OK, statefile)!=-1);
1033 /* save the states of all windows we're managing */
1034 state = PLMakeArrayFromElements(NULL, NULL);
1037 * Format:
1039 * state_file ::= dictionary with version_info ; state
1040 * version_info ::= 'version' = '1';
1041 * state ::= 'state' = array of screen_info
1042 * screen_info ::= array of (screen number, window_info, window_info, ...)
1043 * window_info ::=
1045 for (i=0; i<wScreenCount; i++) {
1046 WScreen *scr;
1047 WWindow *wwin;
1048 char buf[32];
1049 proplist_t pscreen;
1051 scr = wScreenWithNumber(i);
1053 sprintf(buf, "%i", scr->screen);
1054 pscreen = PLMakeArrayFromElements(PLMakeString(buf), NULL);
1056 wwin = scr->focused_window;
1057 while (wwin) {
1058 proplist_t pwindow;
1060 pwindow = makeClientState(wwin);
1061 PLAppendArrayElement(pscreen, pwindow);
1063 wwin = wwin->prev;
1066 PLAppendArrayElement(state, pscreen);
1070 proplist_t statefile;
1072 statefile = PLMakeDictionaryFromEntries(PLMakeString("Version"),
1073 PLMakeString("1.0"),
1075 PLMakeString("Screens"),
1076 state,
1078 NULL);
1080 PLSetFilename(statefile, PLMakeString(statefile));
1081 PLSave(statefile, NO);
1083 PLRelease(statefile);
1086 /* set the remaining properties that we didn't set at
1087 * startup time */
1089 for (argc=0, i=0; argv[i]!=NULL; i++) {
1090 if (strcmp(argv[i], "-clientid")==0
1091 || strcmp(argv[i], "-restore")==0) {
1092 i++;
1093 } else {
1094 argc++;
1098 prop[0].name = SmRestartCommand;
1099 prop[0].type = SmLISTofARRAY8;
1100 prop[0].vals = malloc(sizeof(SmPropValue)*(argc+4));
1101 prop[0].num_vals = argc+4;
1103 prop[1].name = SmCloneCommand;
1104 prop[1].type = SmLISTofARRAY8;
1105 prop[1].vals = malloc(sizeof(SmPropValue)*(argc));
1106 prop[1].num_vals = argc;
1108 if (!prop[0].vals || !prop[1].vals) {
1109 wwarning(_("end of memory while saving session state"));
1110 goto fail;
1113 for (j=0, i=0; i<argc+4; i++) {
1114 if (strcmp(argv[i], "-clientid")==0
1115 || strcmp(argv[i], "-restore")==0) {
1116 i++;
1117 } else {
1118 prop[0].vals[j].value = argv[i];
1119 prop[0].vals[j].length = strlen(argv[i]);
1120 prop[1].vals[j].value = argv[i];
1121 prop[1].vals[j].length = strlen(argv[i]);
1122 j++;
1125 prop[0].vals[j].value = "-clientid";
1126 prop[0].vals[j].length = 9;
1127 j++;
1128 prop[0].vals[j].value = sClientID;
1129 prop[0].vals[j].length = strlen(sClientID);
1130 j++;
1131 prop[0].vals[j].value = "-restore";
1132 prop[0].vals[j].length = 11;
1133 j++;
1134 prop[0].vals[j].value = statefile;
1135 prop[0].vals[j].length = strlen(statefile);
1137 discardCmd = malloc(strlen(statefile)+8);
1138 if (!discardCmd)
1139 goto fail;
1140 sprintf(discardCmd, "rm %s", statefile);
1141 prop[2].name = SmDiscardCommand;
1142 prop[2].type = SmARRAY8;
1143 prop[2].vals[0] = discardCmd;
1144 prop[2].num_vals = 1;
1146 SmcSetProperties(sSMCConn, 3, prop);
1148 ok = True;
1149 fail:
1150 SmcSaveYourselfDone(smc_conn, ok);
1152 if (prop[0].vals)
1153 wfree(prop[0].vals);
1154 if (prop[1].vals)
1155 wfree(prop[1].vals);
1156 if (discardCmd)
1157 wfree(discardCmd);
1159 if (!ok) {
1160 remove(statefile);
1162 if (statefile)
1163 wfree(statefile);
1167 static void
1168 smSaveYourselfProc(SmcConn smc_conn, SmPointer client_data, int save_type,
1169 Bool shutdown, int interact_style, Bool fast)
1171 #ifdef DEBUG1
1172 puts("received SaveYourself SM message");
1173 #endif
1175 if (!SmcRequestSaveYourselfPhase2(smc_conn, smSaveYourselfPhase2Proc,
1176 client_data)) {
1178 SmcSaveYourselfDone(smc_conn, False);
1179 sWaitingPhase2 = False;
1180 } else {
1181 #ifdef DEBUG1
1182 puts("successfull request of SYS phase 2");
1183 #endif
1184 sWaitingPhase2 = True;
1189 static void
1190 smDieProc(SmcConn smc_conn, SmPointer client_data)
1192 #ifdef DEBUG1
1193 puts("received Die SM message");
1194 #endif
1196 wSessionDisconnectManager();
1198 Shutdown(WSExitMode, True);
1203 static void
1204 smSaveCompleteProc(SmcConn smc_conn)
1206 /* it means that we can resume doing things that can change our state */
1207 #ifdef DEBUG1
1208 puts("received SaveComplete SM message");
1209 #endif
1213 static void
1214 smShutdownCancelledProc(SmcConn smc_conn, SmPointer client_data)
1216 if (sWaitingPhase2) {
1218 sWaitingPhase2 = False;
1220 SmcSaveYourselfDone(smc_conn, False);
1225 static void
1226 iceMessageProc(int fd, int mask, void *clientData)
1228 IceConn iceConn = (IceConn)clientData;
1230 IceProcessMessages(iceConn, NULL, NULL);
1234 static void
1235 iceIOErrorHandler(IceConnection ice_conn)
1237 /* This is not fatal but can mean the session manager exited.
1238 * If the session manager exited normally we would get a
1239 * Die message, so this probably means an abnormal exit.
1240 * If the sm was the last client of session, then we'll die
1241 * anyway, otherwise we can continue doing our stuff.
1243 wwarning(_("connection to the session manager was lost"));
1244 wSessionDisconnectManager();
1248 void
1249 wSessionConnectManager(char **argv, int argc)
1251 IceConn iceConn;
1252 char *previous_id = NULL;
1253 char buffer[256];
1254 SmcCallbacks callbacks;
1255 unsigned long mask;
1256 char uid[32];
1257 char pid[32];
1258 SmProp props[4];
1259 SmPropValue prop1val, prop2val, prop3val, prop4val;
1260 char restartStyle;
1261 int i;
1263 mask = SmcSaveYourselfProcMask|SmcDieProcMask|SmcSaveCompleteProcMask
1264 |SmcShutdownCancelledProcMask;
1266 callbacks.save_yourself.callback = smSaveYourselfProc;
1267 callbacks.save_yourself.client_data = argv;
1269 callbacks.die.callback = smDieProc;
1270 callbacks.die.client_data = NULL;
1272 callbacks.save_complete.callback = smSaveCompleteProc;
1273 callbacks.save_complete.client_data = NULL;
1275 callbacks.shutdown_cancelled.callback = smShutdownCancelledProc;
1276 callbacks.shutdown_cancelled.client_data = NULL;
1278 for (i=0; i<argc; i++) {
1279 if (strcmp(argv[i], "-clientid")==0) {
1280 previous_id = argv[i+1];
1281 break;
1285 /* connect to the session manager */
1286 sSMCConn = SmcOpenConnection(NULL, NULL, SmProtoMajor, SmProtoMinor,
1287 mask, &callbacks, previous_id,
1288 &sClientID, 255, buffer);
1289 if (!sSMCConn) {
1290 return;
1292 #ifdef DEBUG1
1293 puts("connected to the session manager");
1294 #endif
1296 /* IceSetIOErrorHandler(iceIOErrorHandler);*/
1298 /* check for session manager clients */
1299 iceConn = SmcGetIceConnection(smcConn);
1301 if (fcntl(IceConnectionNumber(iceConn), F_SETFD, FD_CLOEXEC) < 0) {
1302 wsyserror("error setting close-on-exec flag for ICE connection");
1305 sSMInputHandler = WMAddInputHandler(IceConnectionNumber(iceConn),
1306 WIReadMask, iceMessageProc, iceConn);
1308 /* setup information about ourselves */
1310 /* program name */
1311 prop1val.value = argv[0];
1312 prop1val.length = strlen(argv[0]);
1313 prop[0].name = SmProgram;
1314 prop[0].type = SmARRAY8;
1315 prop[0].num_vals = 1;
1316 prop[0].vals = &prop1val;
1318 /* The XSMP doc from X11R6.1 says it contains the user name,
1319 * but every client implementation I saw places the uid # */
1320 sprintf(uid, "%i", getuid());
1321 prop2val.value = uid;
1322 prop2val.length = strlen(uid);
1323 prop[1].name = SmUserID;
1324 prop[1].type = SmARRAY8;
1325 prop[1].num_vals = 1;
1326 prop[1].vals = &prop2val;
1328 /* Restart style. We should restart only if we were running when
1329 * the previous session finished. */
1330 restartStyle = SmRestartIfRunning;
1331 prop3val.value = &restartStyle;
1332 prop3val.length = 1;
1333 prop[2].name = SmRestartStyleHint;
1334 prop[2].type = SmCARD8;
1335 prop[2].num_vals = 1;
1336 prop[2].vals = &prop3val;
1338 /* Our PID. Not required but might be usefull */
1339 sprintf(pid, "%i", getpid());
1340 prop4val.value = pid;
1341 prop4val.length = strlen(pid);
1342 prop[3].name = SmProcessID;
1343 prop[3].type = SmARRAY8;
1344 prop[3].num_vals = 1;
1345 prop[3].vals = &prop4val;
1347 /* we'll set the rest of the hints later */
1349 SmcSetProperties(sSMCConn, 4, props);
1354 void
1355 wSessionDisconnectManager(void)
1357 if (sSMCConn) {
1358 WMDeleteInputHandler(sSMInputHandler);
1359 sSMInputHandler = NULL;
1361 SmcCloseConnection(sSMCConn, 0, NULL);
1362 sSMCConn = NULL;
1366 void
1367 wSessionRequestShutdown(void)
1369 /* request a shutdown to the session manager */
1370 if (sSMCConn)
1371 SmcRequestSaveYourself(sSMCConn, SmSaveBoth, True, SmInteractStyleAny,
1372 False, True);
1376 Bool
1377 wSessionIsManaged(void)
1379 return sSMCConn!=NULL;
1382 #endif /* !XSMP_ENABLED */