HideIfDef mode bug fixes and enhancements. This is #2 of 3 patches based
[bpt/emacs.git] / lisp / frameset.el
CommitLineData
9421876d
JB
1;;; frameset.el --- save and restore frame and window setup -*- lexical-binding: t -*-
2
ba318903 3;; Copyright (C) 2013-2014 Free Software Foundation, Inc.
9421876d
JB
4
5;; Author: Juanma Barranquero <lekktu@gmail.com>
6;; Keywords: convenience
7
8;; This file is part of GNU Emacs.
9
10;; GNU Emacs is free software: you can redistribute it and/or modify
11;; it under the terms of the GNU General Public License as published by
12;; the Free Software Foundation, either version 3 of the License, or
13;; (at your option) any later version.
14
15;; GNU Emacs is distributed in the hope that it will be useful,
16;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18;; GNU General Public License for more details.
19
20;; You should have received a copy of the GNU General Public License
21;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22
23;;; Commentary:
24
25;; This file provides a set of operations to save a frameset (the state
26;; of all or a subset of the existing frames and windows), both
27;; in-session and persistently, and restore it at some point in the
28;; future.
29;;
30;; It should be noted that restoring the frames' windows depends on
31;; the buffers they are displaying, but this package does not provide
32;; any way to save and restore sets of buffers (see desktop.el for
33;; that). So, it's up to the user of frameset.el to make sure that
34;; any relevant buffer is loaded before trying to restore a frameset.
35;; When a window is restored and a buffer is missing, the window will
36;; be deleted unless it is the last one in the frame, in which case
37;; some previous buffer will be shown instead.
38
39;;; Code:
40
41(require 'cl-lib)
42
43\f
a912c016 44(cl-defstruct (frameset (:type vector) :named
1f585e65 45 (:constructor frameset--make)
76c5e5ab
JB
46 ;; Copier is defined below.
47 (:copier nil))
063233c3
JB
48
49 "A frameset encapsulates a serializable view of a set of frames and windows.
50
51It contains the following slots, which can be accessed with
52\(frameset-SLOT fs) and set with (setf (frameset-SLOT fs) VALUE):
53
a912c016
JB
54 version A read-only version number, identifying the format
55 of the frameset struct. Currently its value is 1.
56 timestamp A read-only timestamp, the output of `current-time'.
57 app A symbol, or a list whose first element is a symbol, which
3677ffeb
JB
58 identifies the creator of the frameset and related info;
59 for example, desktop.el sets this slot to a list
60 `(desktop . ,desktop-file-version).
a912c016
JB
61 name A string, the name of the frameset instance.
62 description A string, a description for user consumption (to show in
3677ffeb 63 menus, messages, etc).
063233c3 64 properties A property list, to store both frameset-specific and
a912c016
JB
65 user-defined serializable data.
66 states A list of items (FRAME-PARAMETERS . WINDOW-STATE), in no
67 particular order. Each item represents a frame to be
024b38fc 68 restored. FRAME-PARAMETERS is a frame's parameter alist,
a912c016 69 extracted with (frame-parameters FRAME) and filtered
3677ffeb 70 through `frameset-filter-params'.
a912c016 71 WINDOW-STATE is the output of `window-state-get' applied
3677ffeb 72 to the root window of the frame.
063233c3 73
024b38fc
JB
74To avoid collisions, it is recommended that applications wanting to add
75private serializable data to `properties' either store all info under a
76single, distinctive name, or use property names with a well-chosen prefix.
77
063233c3
JB
78A frameset is intended to be used through the following simple API:
79
024b38fc
JB
80 - `frameset-save', the type's constructor, captures all or a subset of the
81 live frames, and returns a serializable snapshot of them (a frameset).
063233c3
JB
82 - `frameset-restore' takes a frameset, and restores the frames and windows
83 it describes, as faithfully as possible.
76c5e5ab
JB
84 - `frameset-p' is the predicate for the frameset type.
85 - `frameset-valid-p' checks a frameset's validity.
063233c3
JB
86 - `frameset-copy' returns a deep copy of a frameset.
87 - `frameset-prop' is a `setf'able accessor for the contents of the
88 `properties' slot.
89 - The `frameset-SLOT' accessors described above."
90
a912c016
JB
91 (version 1 :read-only t)
92 (timestamp (current-time) :read-only t)
93 (app nil)
94 (name nil)
95 (description nil)
96 (properties nil)
97 (states nil))
063233c3 98
76c5e5ab
JB
99;; Add nicer docstrings for built-in predicate and accessors.
100(put 'frameset-p 'function-documentation
101 "Return non-nil if OBJECT is a frameset, nil otherwise.\n\n(fn OBJECT)")
102(put 'frameset-version 'function-documentation
103 "Return the version number of FRAMESET.\n
104It is an integer that identifies the format of the frameset struct.
105This slot cannot be modified.\n\n(fn FRAMESET)")
106(put 'frameset-timestamp 'function-documentation
107 "Return the creation timestamp of FRAMESET.\n
108The value is in the format returned by `current-time'.
109This slot cannot be modified.\n\n(fn FRAMESET)")
110(put 'frameset-app 'function-documentation
111 "Return the application identifier for FRAMESET.\n
112The value is either a symbol, like `my-app', or a list
113\(my-app ADDITIONAL-DATA...).\n\n(fn FRAMESET)")
114(put 'frameset-name 'function-documentation
115 "Return the name of FRAMESET (a string).\n\n(fn FRAMESET)")
116(put 'frameset-description 'function-documentation
117 "Return the description of FRAMESET (a string).\n\n(fn FRAMESET)")
118(put 'frameset-properties 'function-documentation
119 "Return the property list of FRAMESET.\n
120This list is useful to store both frameset-specific and user-defined
121serializable data. The simplest way to access and modify it is
122through `frameset-prop' (which see).\n\n(fn FRAMESET)")
123(put 'frameset-states 'function-documentation
124 "Return the list of frame states of FRAMESET.\n
125A frame state is a pair (FRAME-PARAMETERS . WINDOW-STATE), where
126FRAME-PARAMETERS is a frame's parameter alist, extracted with
127\(frame-parameters FRAME) and filtered through `frameset-filter-params',
128and WINDOW-STATE is the output of `window-state-get' applied to the
129root window of the frame.\n
130IMPORTANT: Modifying this slot may cause frameset functions to fail,
131unless the type constraints defined above are respected.\n\n(fn FRAMESET)")
132
1f585e65
SM
133;; We autoloaded this for use in register.el, but now that we use registerv
134;; objects, this autoload is not useful any more.
135;; ;;;###autoload (autoload 'frameset-p "frameset"
136;; ;;;###autoload "Return non-nil if OBJECT is a frameset, nil otherwise." nil)
77187e6f 137
063233c3 138(defun frameset-copy (frameset)
a912c016
JB
139 "Return a deep copy of FRAMESET.
140FRAMESET is copied with `copy-tree'."
9421876d
JB
141 (copy-tree frameset t))
142
76c5e5ab 143(defun frameset-valid-p (object)
1f585e65
SM
144 "Return non-nil if OBJECT is a valid frameset, nil otherwise."
145 (and (frameset-p object)
146 (integerp (frameset-version object))
147 (consp (frameset-timestamp object))
148 (let ((app (frameset-app object)))
76c5e5ab
JB
149 (or (null app) ; APP is nil
150 (symbolp app) ; or a symbol
151 (and (consp app) ; or a list
152 (symbolp (car app))))) ; starting with a symbol
1f585e65
SM
153 (stringp (or (frameset-name object) ""))
154 (stringp (or (frameset-description object) ""))
155 (listp (frameset-properties object))
156 (let ((states (frameset-states object)))
157 (and (listp states)
158 (cl-every #'consp (frameset-states object))))
62f33bae
JB
159 (frameset-version object))) ; And VERSION is non-nil.
160
161(defun frameset--prop-setter (frameset property value)
162 "Setter function for `frameset-prop'. Internal use only."
163 (setf (frameset-properties frameset)
164 (plist-put (frameset-properties frameset) property value))
165 value)
9421876d 166
2613dea2 167;; A setf'able accessor to the frameset's properties
a912c016
JB
168(defun frameset-prop (frameset property)
169 "Return the value for FRAMESET of PROPERTY.
2613dea2 170
063233c3 171Properties can be set with
2613dea2 172
bd0c3c0b 173 (setf (frameset-prop FRAMESET PROPERTY) NEW-VALUE)"
62f33bae 174 (declare (gv-setter frameset--prop-setter))
a912c016 175 (plist-get (frameset-properties frameset) property))
2613dea2 176
9421876d
JB
177\f
178;; Filtering
179
a912c016
JB
180;; What's the deal with these "filter alists"?
181;;
182;; Let's say that Emacs' frame parameters were never designed as a tool to
183;; precisely record (or restore) a frame's state. They grew organically,
184;; and their uses and behaviors reflect their history. In using them to
526e5233 185;; implement framesets, the unwary implementer, or the prospective package
a912c016
JB
186;; writer willing to use framesets in their code, might fall victim of some
187;; unexpected... oddities.
188;;
189;; You can find frame parameters that:
190;;
191;; - can be used to get and set some data from the frame's current state
192;; (`height', `width')
193;; - can be set at creation time, and setting them afterwards has no effect
194;; (`window-state', `minibuffer')
195;; - can be set at creation time, and setting them afterwards will fail with
196;; an error, *unless* you set it to the same value, a noop (`border-width')
197;; - act differently when passed at frame creation time, and when set
198;; afterwards (`height')
199;; - affect the value of other parameters (`name', `visibility')
200;; - can be ignored by window managers (most positional args, like `height',
201;; `width', `left' and `top', and others, like `auto-raise', `auto-lower')
202;; - can be set externally in X resources or Window registry (again, most
203;; positional parameters, and also `toolbar-lines', `menu-bar-lines' etc.)
204;, - can contain references to live objects (`buffer-list', `minibuffer') or
205;; code (`buffer-predicate')
206;; - are set automatically, and cannot be changed (`window-id', `parent-id'),
207;; but setting them produces no error
208;; - have a noticeable effect in some window managers, and are ignored in
209;; others (`menu-bar-lines')
210;; - can not be safely set in a tty session and then copied back to a GUI
211;; session (`font', `background-color', `foreground-color')
212;;
213;; etc etc.
214;;
215;; Which means that, in order to save a parameter alist to disk and read it
216;; back later to reconstruct a frame, some processing must be done. That's
217;; what `frameset-filter-params' and the `frameset-*-filter-alist' variables
218;; are for.
219;;
76c5e5ab 220;; First, a clarification. The word "filter" in these names refers to both
a912c016
JB
221;; common meanings of filter: to filter out (i.e., to remove), and to pass
222;; through a transformation function (think `filter-buffer-substring').
223;;
224;; `frameset-filter-params' takes a parameter alist PARAMETERS, a filtering
225;; alist FILTER-ALIST, and a flag SAVING to indicate whether we are filtering
226;; parameters with the intent of saving a frame or restoring it. It then
76c5e5ab 227;; accumulates an output alist, FILTERED, by checking each parameter in
a912c016
JB
228;; PARAMETERS against FILTER-ALIST and obeying any rule found there. The
229;; absence of a rule just means the parameter/value pair (called CURRENT in
230;; filtering functions) is copied to FILTERED as is. Keyword values :save,
231;; :restore and :never tell the function to copy CURRENT to FILTERED in the
232;; respective situations, that is, when saving, restoring, or never at all.
233;; Values :save and :restore are not used in this package, because usually if
234;; you don't want to save a parameter, you don't want to restore it either.
235;; But they can be useful, for example, if you already have a saved frameset
236;; created with some intent, and want to reuse it for a different objective
237;; where the expected parameter list has different requirements.
238;;
239;; Finally, the value can also be a filtering function, or a filtering
240;; function plus some arguments. The function is called for each matching
241;; parameter, and receives CURRENT (the parameter/value pair being processed),
242;; FILTERED (the output alist so far), PARAMETERS (the full parameter alist),
243;; SAVING (the save/restore flag), plus any additional ARGS set along the
244;; function in the `frameset-*-filter-alist' entry. The filtering function
245;; then has the possibility to pass along CURRENT, or reject it altogether,
246;; or pass back a (NEW-PARAM . NEW-VALUE) pair, which does not even need to
247;; refer to the same parameter (so you can filter `width' and return `height'
248;; and vice versa, if you're feeling silly and want to mess with the user's
249;; mind). As a help in deciding what to do, the filtering function has
250;; access to PARAMETERS, but must not change it in any way. It also has
251;; access to FILTERED, which can be modified at will. This allows two or
252;; more filters to coordinate themselves, because in general there's no way
253;; to predict the order in which they will be run.
254;;
255;; So, which parameters are filtered by default, and why? Let's see.
256;;
257;; - `buffer-list', `buried-buffer-list', `buffer-predicate': They contain
258;; references to live objects, or in the case of `buffer-predicate', it
259;; could also contain an fbound symbol (a predicate function) that could
260;; not be defined in a later session.
261;;
262;; - `window-id', `outer-window-id', `parent-id': They are assigned
263;; automatically and cannot be set, so keeping them is harmless, but they
264;; add clutter. `window-system' is similar: it's assigned at frame
265;; creation, and does not serve any useful purpose later.
266;;
267;; - `left', `top': Only problematic when saving an iconified frame, because
268;; when the frame is iconified they are set to (- 32000), which doesn't
269;; really help in restoring the frame. Better to remove them and let the
270;; window manager choose a default position for the frame.
271;;
272;; - `background-color', `foreground-color': In tty frames they can be set
273;; to "unspecified-bg" and "unspecified-fg", which aren't understood on
274;; GUI sessions. They have to be filtered out when switching from tty to
275;; a graphical display.
276;;
277;; - `tty', `tty-type': These are tty-specific. When switching to a GUI
76c5e5ab 278;; display they do no harm, but they clutter the parameter alist.
a912c016
JB
279;;
280;; - `minibuffer': It can contain a reference to a live window, which cannot
281;; be serialized. Because of Emacs' idiosyncratic treatment of this
282;; parameter, frames created with (minibuffer . t) have a parameter
283;; (minibuffer . #<window...>), while frames created with
284;; (minibuffer . #<window...>) have (minibuffer . nil), which is madness
285;; but helps to differentiate between minibufferless and "normal" frames.
286;; So, changing (minibuffer . #<window...>) to (minibuffer . t) allows
287;; Emacs to set up the new frame correctly. Nice, uh?
288;;
289;; - `name': If this parameter is directly set, `explicit-name' is
290;; automatically set to t, and then `name' no longer changes dynamically.
291;; So, in general, not saving `name' is the right thing to do, though
292;; surely there are applications that will want to override this filter.
293;;
294;; - `font', `fullscreen', `height' and `width': These parameters suffer
76c5e5ab 295;; from the fact that they are badly mangled when going through a
a912c016
JB
296;; tty session, though not all in the same way. When saving a GUI frame
297;; and restoring it in a tty, the height and width of the new frame are
298;; those of the tty screen (let's say 80x25, for example); going back
299;; to a GUI session means getting frames of the tty screen size (so all
300;; your frames are 80 cols x 25 rows). For `fullscreen' there's a
301;; similar problem, because a tty frame cannot really be fullscreen or
302;; maximized, so the state is lost. The problem with `font' is a bit
303;; different, because a valid GUI font spec in `font' turns into
304;; (font . "tty") in a tty frame, and when read back into a GUI session
305;; it fails because `font's value is no longer a valid font spec.
306;;
307;; In most cases, the filtering functions just do the obvious thing: remove
308;; CURRENT when it is meaningless to keep it, or pass a modified copy if
309;; that helps (as in the case of `minibuffer').
310;;
311;; The exception are the parameters in the last set, which should survive
312;; the roundtrip though tty-land. The answer is to add "stashing
313;; parameters", working in pairs, to shelve the GUI-specific contents and
314;; restore it once we're back in pixel country. That's what functions
c03c02ee 315;; `frameset-filter-shelve-param' and `frameset-filter-unshelve-param' do.
a912c016
JB
316;;
317;; Basically, if you set `frameset-filter-shelve-param' as the filter for
318;; a parameter P, it will detect when it is restoring a GUI frame into a
319;; tty session, and save P's value in the custom parameter X:P, but only
320;; if X:P does not exist already (so it is not overwritten if you enter
321;; the tty session more than once). If you're not switching to a tty
322;; frame, the filter just passes CURRENT along.
323;;
324;; The parameter X:P, on the other hand, must have been setup to be
325;; filtered by `frameset-filter-unshelve-param', which unshelves the
326;; value: if we're entering a GUI session, returns P instead of CURRENT,
327;; while in other cases it just passes it along.
328;;
329;; The only additional trick is that `frameset-filter-shelve-param' does
330;; not set P if switching back to GUI and P already has a value, because
331;; it assumes that `frameset-filter-unshelve-param' did set it up. And
332;; `frameset-filter-unshelve-param', when unshelving P, must look into
333;; FILTERED to determine if P has already been set and if so, modify it;
334;; else just returns P.
335;;
336;; Currently, the value of X in X:P is `GUI', but you can use any prefix,
337;; by passing its symbol as argument in the filter:
338;;
339;; (my-parameter frameset-filter-shelve-param MYPREFIX)
340;;
341;; instead of
342;;
343;; (my-parameter . frameset-filter-shelve-param)
344;;
345;; Note that `frameset-filter-unshelve-param' does not need MYPREFIX
346;; because it is available from the parameter name in CURRENT. Also note
347;; that the colon between the prefix and the parameter name is hardcoded.
348;; The reason is that X:P is quite readable, and that the colon is a
349;; very unusual character in symbol names, other than in initial position
350;; in keywords (emacs -Q has only two such symbols, and one of them is a
351;; URL). So the probability of a collision with existing or future
352;; symbols is quite insignificant.
353;;
c03c02ee
JB
354;; Now, what about the filter alist variables? There are three of them,
355;; though only two sets of parameters:
a912c016
JB
356;;
357;; - `frameset-session-filter-alist' contains these filters that allow to
358;; save and restore framesets in-session, without the need to serialize
359;; the frameset or save it to disk (for example, to save a frameset in a
360;; register and restore it later). Filters in this list do not remove
361;; live objects, except in `minibuffer', which is dealt especially by
362;; `frameset-save' / `frameset-restore'.
363;;
364;; - `frameset-persistent-filter-alist' is the whole deal. It does all
365;; the filtering described above, and the result is ready to be saved on
366;; disk without loss of information. That's the format used by the
367;; desktop.el package, for example.
368;;
c03c02ee 369;; IMPORTANT: These variables share structure and should NEVER be modified.
a912c016
JB
370;;
371;; - `frameset-filter-alist': The value of this variable is the default
372;; value for the FILTERS arguments of `frameset-save' and
373;; `frameset-restore'. It is set to `frameset-persistent-filter-alist',
374;; though it can be changed by specific applications.
375;;
376;; How to use them?
377;;
378;; The simplest way is just do nothing. The default should work
379;; reasonably and sensibly enough. But, what if you really need a
380;; customized filter alist? Then you can create your own variable
381;;
382;; (defvar my-filter-alist
383;; '((my-param1 . :never)
384;; (my-param2 . :save)
385;; (my-param3 . :restore)
386;; (my-param4 . my-filtering-function-without-args)
387;; (my-param5 my-filtering-function-with arg1 arg2)
388;; ;;; many other parameters
389;; )
390;; "My customized parameter filter alist.")
391;;
392;; or, if you're only changing a few items,
393;;
394;; (defvar my-filter-alist
395;; (nconc '((my-param1 . :never)
396;; (my-param2 . my-filtering-function))
397;; frameset-filter-alist)
398;; "My brief customized parameter filter alist.")
399;;
400;; and pass it to the FILTER arg of the save/restore functions,
401;; ALWAYS taking care of not modifying the original lists; if you're
402;; going to do any modifying of my-filter-alist, please use
403;;
404;; (nconc '((my-param1 . :never) ...)
405;; (copy-sequence frameset-filter-alist))
406;;
407;; One thing you shouldn't forget is that they are alists, so searching
408;; in them is sequential. If you just want to change the default of
409;; `name' to allow it to be saved, you can set (name . nil) in your
410;; customized filter alist; it will take precedence over the latter
411;; setting. In case you decide that you *always* want to save `name',
412;; you can add it to `frameset-filter-alist':
413;;
414;; (push '(name . nil) frameset-filter-alist)
415;;
416;; In certain applications, having a parameter filtering function like
417;; `frameset-filter-params' can be useful, even if you're not using
418;; framesets. The interface of `frameset-filter-params' is generic
419;; and does not depend of global state, with one exception: it uses
baf8d0ac
JB
420;; the dynamically bound variable `frameset--target-display' to decide
421;; if, and how, to modify the `display' parameter of FILTERED. That
422;; should not represent a problem, because it's only meaningful when
423;; restoring, and customized uses of `frameset-filter-params' are
424;; likely to use their own filter alist and just call
a912c016
JB
425;;
426;; (setq my-filtered (frameset-filter-params my-params my-filters t))
427;;
428;; In case you want to use it with the standard filters, you can
429;; wrap the call to `frameset-filter-params' in a let form to bind
430;; `frameset--target-display' to nil or the desired value.
431;;
432
d5671a82 433;;;###autoload
a912c016 434(defvar frameset-session-filter-alist
76c5e5ab 435 '((name . :never)
307764cc 436 (left . frameset-filter-iconified)
76c5e5ab
JB
437 (minibuffer . frameset-filter-minibuffer)
438 (top . frameset-filter-iconified))
d5671a82 439 "Minimum set of parameters to filter for live (on-session) framesets.
f9dbf1cb 440DO NOT MODIFY. See `frameset-filter-alist' for a full description.")
d5671a82
JB
441
442;;;###autoload
443(defvar frameset-persistent-filter-alist
444 (nconc
76c5e5ab
JB
445 '((background-color . frameset-filter-sanitize-color)
446 (buffer-list . :never)
447 (buffer-predicate . :never)
063233c3 448 (buried-buffer-list . :never)
76c5e5ab
JB
449 (font . frameset-filter-shelve-param)
450 (foreground-color . frameset-filter-sanitize-color)
451 (fullscreen . frameset-filter-shelve-param)
452 (GUI:font . frameset-filter-unshelve-param)
453 (GUI:fullscreen . frameset-filter-unshelve-param)
454 (GUI:height . frameset-filter-unshelve-param)
455 (GUI:width . frameset-filter-unshelve-param)
456 (height . frameset-filter-shelve-param)
457 (outer-window-id . :never)
458 (parent-id . :never)
459 (tty . frameset-filter-tty-to-GUI)
460 (tty-type . frameset-filter-tty-to-GUI)
461 (width . frameset-filter-shelve-param)
462 (window-id . :never)
463 (window-system . :never))
a912c016
JB
464 frameset-session-filter-alist)
465 "Parameters to filter for persistent framesets.
f9dbf1cb 466DO NOT MODIFY. See `frameset-filter-alist' for a full description.")
d5671a82
JB
467
468;;;###autoload
469(defvar frameset-filter-alist frameset-persistent-filter-alist
9421876d
JB
470 "Alist of frame parameters and filtering functions.
471
a912c016
JB
472This alist is the default value of the FILTERS argument of
473`frameset-save' and `frameset-restore' (which see).
474
f9dbf1cb
JB
475Initially, `frameset-filter-alist' is set to, and shares the value of,
476`frameset-persistent-filter-alist'. You can override any item in
477this alist by `push'ing a new item onto it. If, for some reason, you
478intend to modify existing values, do
479
480 (setq frameset-filter-alist (copy-tree frameset-filter-alist))
481
482before changing anything.
483
a912c016
JB
484On saving, PARAMETERS is the parameter alist of each frame processed,
485and FILTERED is the parameter alist that gets saved to the frameset.
486
024b38fc
JB
487On restoring, PARAMETERS is the parameter alist extracted from the
488frameset, and FILTERED is the resulting frame parameter alist used
063233c3
JB
489to restore the frame.
490
024b38fc
JB
491Elements of `frameset-filter-alist' are conses (PARAM . ACTION),
492where PARAM is a parameter name (a symbol identifying a frame
493parameter), and ACTION can be:
063233c3
JB
494
495 nil The parameter is copied to FILTERED.
496 :never The parameter is never copied to FILTERED.
76c5e5ab 497 :save The parameter is copied only when saving the frame.
063233c3 498 :restore The parameter is copied only when restoring the frame.
76c5e5ab 499 FILTER A filter function.
9421876d
JB
500
501FILTER can be a symbol FILTER-FUN, or a list (FILTER-FUN ARGS...).
024b38fc
JB
502FILTER-FUN is invoked with
503
504 (apply FILTER-FUN CURRENT FILTERED PARAMETERS SAVING ARGS)
505
506where
9421876d
JB
507
508 CURRENT A cons (PARAM . VALUE), where PARAM is the one being
d5671a82 509 filtered and VALUE is its current value.
063233c3 510 FILTERED The resulting alist (so far).
9421876d 511 PARAMETERS The complete alist of parameters being filtered,
76c5e5ab 512 SAVING Non-nil if filtering before saving state, nil if filtering
a912c016 513 before restoring it.
024b38fc 514 ARGS Any additional arguments specified in the ACTION.
9421876d 515
307764cc
JB
516FILTER-FUN is allowed to modify items in FILTERED, but no other arguments.
517It must return:
76c5e5ab
JB
518 nil Skip CURRENT (do not add it to FILTERED).
519 t Add CURRENT to FILTERED as is.
063233c3
JB
520 (NEW-PARAM . NEW-VALUE) Add this to FILTERED instead of CURRENT.
521
522Frame parameters not on this alist are passed intact, as if they were
523defined with ACTION = nil.")
9421876d 524
baf8d0ac
JB
525;; Dynamically bound in `frameset-save', `frameset-restore'.
526(defvar frameset--target-display)
527;; Either (display . VALUE) or nil.
528;; This refers to the current frame config being processed with
529;; `frameset-filter-params' and its auxiliary filtering functions.
530;; If nil, there is no need to change the display.
531;; If non-nil, display parameter to use when creating the frame.
9421876d
JB
532
533(defun frameset-switch-to-gui-p (parameters)
534 "True when switching to a graphic display.
a912c016
JB
535Return non-nil if the parameter alist PARAMETERS describes a frame on a
536text-only terminal, and the frame is being restored on a graphic display;
537otherwise return nil. Only meaningful when called from a filtering
538function in `frameset-filter-alist'."
76c5e5ab
JB
539 (and frameset--target-display ; we're switching
540 (null (cdr (assq 'display parameters))) ; from a tty
541 (cdr frameset--target-display))) ; to a GUI display
9421876d
JB
542
543(defun frameset-switch-to-tty-p (parameters)
544 "True when switching to a text-only terminal.
a912c016
JB
545Return non-nil if the parameter alist PARAMETERS describes a frame on a
546graphic display, and the frame is being restored on a text-only terminal;
547otherwise return nil. Only meaningful when called from a filtering
548function in `frameset-filter-alist'."
76c5e5ab
JB
549 (and frameset--target-display ; we're switching
550 (cdr (assq 'display parameters)) ; from a GUI display
551 (null (cdr frameset--target-display)))) ; to a tty
9421876d 552
d5671a82 553(defun frameset-filter-tty-to-GUI (_current _filtered parameters saving)
063233c3
JB
554 "Remove CURRENT when switching from tty to a graphic display.
555
556For the meaning of CURRENT, FILTERED, PARAMETERS and SAVING,
a912c016 557see `frameset-filter-alist'."
d5671a82
JB
558 (or saving
559 (not (frameset-switch-to-gui-p parameters))))
560
9421876d
JB
561(defun frameset-filter-sanitize-color (current _filtered parameters saving)
562 "When switching to a GUI frame, remove \"unspecified\" colors.
063233c3
JB
563Useful as a filter function for tty-specific parameters.
564
565For the meaning of CURRENT, FILTERED, PARAMETERS and SAVING,
a912c016 566see `frameset-filter-alist'."
9421876d
JB
567 (or saving
568 (not (frameset-switch-to-gui-p parameters))
569 (not (stringp (cdr current)))
570 (not (string-match-p "^unspecified-[fb]g$" (cdr current)))))
571
14d1e463
JB
572(defun frameset-filter-minibuffer (current filtered _parameters saving)
573 "Force the minibuffer parameter to have a sensible value.
574
575When saving, convert (minibuffer . #<window>) to (minibuffer . t).
576When restoring, if there are two copies, keep the one pointing to
577a live window.
063233c3
JB
578
579For the meaning of CURRENT, FILTERED, PARAMETERS and SAVING,
a912c016 580see `frameset-filter-alist'."
14d1e463
JB
581 (let ((value (cdr current)) mini)
582 (cond (saving
583 (if (windowp value) '(minibuffer . t) t))
584 ((setq mini (assq 'minibuffer filtered))
585 (when (windowp value) (setcdr mini value))
586 nil)
587 (t t))))
9421876d 588
a912c016
JB
589(defun frameset-filter-shelve-param (current _filtered parameters saving
590 &optional prefix)
9421876d 591 "When switching to a tty frame, save parameter P as PREFIX:P.
a912c016 592The parameter can be later restored with `frameset-filter-unshelve-param'.
063233c3
JB
593PREFIX defaults to `GUI'.
594
595For the meaning of CURRENT, FILTERED, PARAMETERS and SAVING,
a912c016 596see `frameset-filter-alist'."
9421876d
JB
597 (unless prefix (setq prefix 'GUI))
598 (cond (saving t)
599 ((frameset-switch-to-tty-p parameters)
600 (let ((prefix:p (intern (format "%s:%s" prefix (car current)))))
601 (if (assq prefix:p parameters)
602 nil
603 (cons prefix:p (cdr current)))))
604 ((frameset-switch-to-gui-p parameters)
605 (not (assq (intern (format "%s:%s" prefix (car current))) parameters)))
606 (t t)))
607
a912c016 608(defun frameset-filter-unshelve-param (current filtered parameters saving)
9421876d 609 "When switching to a GUI frame, restore PREFIX:P parameter as P.
063233c3
JB
610CURRENT must be of the form (PREFIX:P . value).
611
612For the meaning of CURRENT, FILTERED, PARAMETERS and SAVING,
a912c016 613see `frameset-filter-alist'."
9421876d
JB
614 (or saving
615 (not (frameset-switch-to-gui-p parameters))
616 (let* ((prefix:p (symbol-name (car current)))
617 (p (intern (substring prefix:p
618 (1+ (string-match-p ":" prefix:p)))))
619 (val (cdr current))
620 (found (assq p filtered)))
621 (if (not found)
622 (cons p val)
623 (setcdr found val)
624 nil))))
625
626(defun frameset-filter-iconified (_current _filtered parameters saving)
627 "Remove CURRENT when saving an iconified frame.
063233c3 628This is used for positional parameters `left' and `top', which are
9421876d 629meaningless in an iconified frame, so the frame is restored in a
063233c3
JB
630default position.
631
632For the meaning of CURRENT, FILTERED, PARAMETERS and SAVING,
a912c016 633see `frameset-filter-alist'."
9421876d
JB
634 (not (and saving (eq (cdr (assq 'visibility parameters)) 'icon))))
635
9421876d 636(defun frameset-filter-params (parameters filter-alist saving)
024b38fc 637 "Filter parameter alist PARAMETERS and return a filtered alist.
9421876d
JB
638FILTER-ALIST is an alist of parameter filters, in the format of
639`frameset-filter-alist' (which see).
640SAVING is non-nil while filtering parameters to save a frameset,
641nil while the filtering is done to restore it."
642 (let ((filtered nil))
643 (dolist (current parameters)
024b38fc
JB
644 ;; When saving, the parameter alist is temporary, so modifying it
645 ;; is not a problem. When restoring, the parameter alist is part
307764cc
JB
646 ;; of a frameset, so we must copy parameters to avoid inadvertent
647 ;; modifications.
9421876d
JB
648 (pcase (cdr (assq (car current) filter-alist))
649 (`nil
307764cc 650 (push (if saving current (copy-tree current)) filtered))
063233c3 651 (:never
9421876d 652 nil)
9421876d 653 (:restore
307764cc 654 (unless saving (push (copy-tree current) filtered)))
063233c3 655 (:save
9421876d
JB
656 (when saving (push current filtered)))
657 ((or `(,fun . ,args) (and fun (pred fboundp)))
307764cc
JB
658 (let* ((this (apply fun current filtered parameters saving args))
659 (val (if (eq this t) current this)))
660 (when val
661 (push (if saving val (copy-tree val)) filtered))))
9421876d
JB
662 (other
663 (delay-warning 'frameset (format "Unknown filter %S" other) :error))))
664 ;; Set the display parameter after filtering, so that filter functions
665 ;; have access to its original value.
666 (when frameset--target-display
667 (let ((display (assq 'display filtered)))
668 (if display
669 (setcdr display (cdr frameset--target-display))
670 (push frameset--target-display filtered))))
671 filtered))
672
673\f
38276e01 674;; Frame ids
9421876d
JB
675
676(defun frameset--set-id (frame)
38276e01 677 "Set FRAME's id if not yet set.
9421876d 678Internal use only."
d5671a82 679 (unless (frame-parameter frame 'frameset--id)
9421876d 680 (set-frame-parameter frame
d5671a82 681 'frameset--id
9421876d
JB
682 (mapconcat (lambda (n) (format "%04X" n))
683 (cl-loop repeat 4 collect (random 65536))
684 "-"))))
c6463340
JB
685
686(defun frameset-cfg-id (frame-cfg)
687 "Return the frame id for frame configuration FRAME-CFG."
688 (cdr (assq 'frameset--id frame-cfg)))
689
38276e01
JB
690;;;###autoload
691(defun frameset-frame-id (frame)
692 "Return the frame id of FRAME, if it has one; else, return nil.
693A frame id is a string that uniquely identifies a frame.
694It is persistent across `frameset-save' / `frameset-restore'
695invocations, and once assigned is never changed unless the same
696frame is duplicated (via `frameset-restore'), in which case the
697newest frame keeps the id and the old frame's is set to nil."
698 (frame-parameter frame 'frameset--id))
699
700;;;###autoload
701(defun frameset-frame-id-equal-p (frame id)
702 "Return non-nil if FRAME's id matches ID."
703 (string= (frameset-frame-id frame) id))
704
705;;;###autoload
a912c016 706(defun frameset-frame-with-id (id &optional frame-list)
38276e01
JB
707 "Return the live frame with id ID, if exists; else nil.
708If FRAME-LIST is a list of frames, check these frames only.
709If nil, check all live frames."
710 (cl-find-if (lambda (f)
711 (and (frame-live-p f)
712 (frameset-frame-id-equal-p f id)))
713 (or frame-list (frame-list))))
714
715\f
716;; Saving framesets
9421876d 717
a912c016 718(defun frameset--record-minibuffer-relationships (frame-list)
9421876d 719 "Process FRAME-LIST and record minibuffer relationships.
d5671a82 720FRAME-LIST is a list of frames. Internal use only."
9421876d
JB
721 ;; Record frames with their own minibuffer
722 (dolist (frame (minibuffer-frame-list))
723 (when (memq frame frame-list)
724 (frameset--set-id frame)
725 ;; For minibuffer-owning frames, frameset--mini is a cons
726 ;; (t . DEFAULT?), where DEFAULT? is a boolean indicating whether
727 ;; the frame is the one pointed out by `default-minibuffer-frame'.
728 (set-frame-parameter frame
729 'frameset--mini
730 (cons t (eq frame default-minibuffer-frame)))))
731 ;; Now link minibufferless frames with their minibuffer frames
732 (dolist (frame frame-list)
733 (unless (frame-parameter frame 'frameset--mini)
734 (frameset--set-id frame)
14d1e463
JB
735 (let ((mb-frame (window-frame (minibuffer-window frame))))
736 ;; For minibufferless frames, frameset--mini is a cons
737 ;; (nil . FRAME-ID), where FRAME-ID is the frameset--id of
738 ;; the frame containing its minibuffer window.
739 ;; FRAME-ID can be set to nil, if FRAME-LIST doesn't contain
740 ;; the minibuffer frame of a minibufferless frame; we allow
741 ;; it without trying to second-guess the user.
742 (set-frame-parameter frame
743 'frameset--mini
744 (cons nil
745 (and mb-frame
746 (frameset-frame-id mb-frame))))))))
9421876d 747
51d30f2c 748;;;###autoload
a912c016
JB
749(cl-defun frameset-save (frame-list
750 &key app name description
751 filters predicate properties)
752 "Return a frameset for FRAME-LIST, a list of frames.
307764cc
JB
753Dead frames and non-frame objects are silently removed from the list.
754If nil, FRAME-LIST defaults to the output of `frame-list' (all live frames).
a912c016
JB
755APP, NAME and DESCRIPTION are optional data; see the docstring of the
756`frameset' defstruct for details.
757FILTERS is an alist of parameter filters; if nil, the value of the variable
758`frameset-filter-alist' is used instead.
9421876d 759PREDICATE is a predicate function, which must return non-nil for frames that
024b38fc 760should be saved; if PREDICATE is nil, all frames from FRAME-LIST are saved.
9421876d 761PROPERTIES is a user-defined property list to add to the frameset."
063233c3 762 (let* ((list (or (copy-sequence frame-list) (frame-list)))
baf8d0ac 763 (frameset--target-display nil)
063233c3
JB
764 (frames (cl-delete-if-not #'frame-live-p
765 (if predicate
766 (cl-delete-if-not predicate list)
c03c02ee
JB
767 list)))
768 fs)
a912c016 769 (frameset--record-minibuffer-relationships frames)
1f585e65 770 (setq fs (frameset--make
c03c02ee
JB
771 :app app
772 :name name
773 :description description
774 :properties properties
775 :states (mapcar
776 (lambda (frame)
777 (cons
778 (frameset-filter-params (frame-parameters frame)
779 (or filters
780 frameset-filter-alist)
781 t)
782 (window-state-get (frame-root-window frame) t)))
783 frames)))
784 (cl-assert (frameset-valid-p fs))
785 fs))
9421876d
JB
786
787\f
788;; Restoring framesets
789
4538c058
JB
790;; Dynamically bound in `frameset-restore'.
791(defvar frameset--reuse-list)
792(defvar frameset--action-map)
9421876d 793
024b38fc
JB
794(defun frameset-compute-pos (value left/top right/bottom)
795 "Return an absolute positioning value for a frame.
796VALUE is the value of a positional frame parameter (`left' or `top').
797If VALUE is relative to the screen edges (like (+ -35) or (-200), it is
798converted to absolute by adding it to the corresponding edge; if it is
799an absolute position, it is returned unmodified.
800LEFT/TOP and RIGHT/BOTTOM indicate the dimensions of the screen in
801pixels along the relevant direction: either the position of the left
802and right edges for a `left' positional parameter, or the position of
803the top and bottom edges for a `top' parameter."
9421876d
JB
804 (pcase value
805 (`(+ ,val) (+ left/top val))
806 (`(- ,val) (+ right/bottom val))
807 (val val)))
808
307764cc 809(defun frameset-move-onscreen (frame force-onscreen)
9421876d
JB
810 "If FRAME is offscreen, move it back onscreen and, if necessary, resize it.
811For the description of FORCE-ONSCREEN, see `frameset-restore'.
812When forced onscreen, frames wider than the monitor's workarea are converted
813to fullwidth, and frames taller than the workarea are converted to fullheight.
307764cc 814NOTE: This only works for non-iconified frames."
9421876d 815 (pcase-let* ((`(,left ,top ,width ,height) (cl-cdadr (frame-monitor-attributes frame)))
d5671a82
JB
816 (right (+ left width -1))
817 (bottom (+ top height -1))
024b38fc
JB
818 (fr-left (frameset-compute-pos (frame-parameter frame 'left) left right))
819 (fr-top (frameset-compute-pos (frame-parameter frame 'top) top bottom))
9421876d
JB
820 (ch-width (frame-char-width frame))
821 (ch-height (frame-char-height frame))
d5671a82
JB
822 (fr-width (max (frame-pixel-width frame) (* ch-width (frame-width frame))))
823 (fr-height (max (frame-pixel-height frame) (* ch-height (frame-height frame))))
824 (fr-right (+ fr-left fr-width -1))
825 (fr-bottom (+ fr-top fr-height -1)))
9421876d 826 (when (pcase force-onscreen
d5671a82
JB
827 ;; A predicate.
828 ((pred functionp)
829 (funcall force-onscreen
830 frame
831 (list fr-left fr-top fr-width fr-height)
832 (list left top width height)))
9421876d 833 ;; Any corner is outside the screen.
76c5e5ab 834 (:all (or (< fr-bottom top) (> fr-bottom bottom)
9421876d
JB
835 (< fr-left left) (> fr-left right)
836 (< fr-right left) (> fr-right right)
76c5e5ab 837 (< fr-top top) (> fr-top bottom)))
9421876d 838 ;; Displaced to the left, right, above or below the screen.
76c5e5ab 839 (`t (or (> fr-left right)
9421876d 840 (< fr-right left)
76c5e5ab 841 (> fr-top bottom)
9421876d
JB
842 (< fr-bottom top)))
843 ;; Fully inside, no need to do anything.
844 (_ nil))
845 (let ((fullwidth (> fr-width width))
846 (fullheight (> fr-height height))
847 (params nil))
848 ;; Position frame horizontally.
849 (cond (fullwidth
850 (push `(left . ,left) params))
851 ((> fr-right right)
852 (push `(left . ,(+ left (- width fr-width))) params))
853 ((< fr-left left)
854 (push `(left . ,left) params)))
855 ;; Position frame vertically.
856 (cond (fullheight
857 (push `(top . ,top) params))
858 ((> fr-bottom bottom)
859 (push `(top . ,(+ top (- height fr-height))) params))
860 ((< fr-top top)
861 (push `(top . ,top) params)))
862 ;; Compute fullscreen state, if required.
863 (when (or fullwidth fullheight)
864 (push (cons 'fullscreen
865 (cond ((not fullwidth) 'fullheight)
866 ((not fullheight) 'fullwidth)
867 (t 'maximized)))
868 params))
869 ;; Finally, move the frame back onscreen.
870 (when params
871 (modify-frame-parameters frame params))))))
872
a912c016 873(defun frameset--find-frame-if (predicate display &rest args)
4538c058 874 "Find a reusable frame satisfying PREDICATE.
9421876d
JB
875Look through available frames whose display property matches DISPLAY
876and return the first one for which (PREDICATE frame ARGS) returns t.
877If PREDICATE is nil, it is always satisfied. Internal use only."
878 (cl-find-if (lambda (frame)
879 (and (equal (frame-parameter frame 'display) display)
880 (or (null predicate)
881 (apply predicate frame args))))
882 frameset--reuse-list))
883
a912c016
JB
884(defun frameset--reuse-frame (display parameters)
885 "Return an existing frame to reuse, or nil if none found.
886DISPLAY is the display where the frame will be shown, and PARAMETERS
024b38fc 887is the parameter alist of the frame being restored. Internal use only."
9421876d
JB
888 (let ((frame nil)
889 mini)
890 ;; There are no fancy heuristics there. We could implement some
891 ;; based on frame size and/or position, etc., but it is not clear
892 ;; that any "gain" (in the sense of reduced flickering, etc.) is
893 ;; worth the added complexity. In fact, the code below mainly
894 ;; tries to work nicely when M-x desktop-read is used after a
895 ;; desktop session has already been loaded. The other main use
896 ;; case, which is the initial desktop-read upon starting Emacs,
897 ;; will usually have only one frame, and should already work.
898 (cond ((null display)
899 ;; When the target is tty, every existing frame is reusable.
a912c016
JB
900 (setq frame (frameset--find-frame-if nil display)))
901 ((car (setq mini (cdr (assq 'frameset--mini parameters))))
9421876d
JB
902 ;; If the frame has its own minibuffer, let's see whether
903 ;; that frame has already been loaded (which can happen after
904 ;; M-x desktop-read).
a912c016 905 (setq frame (frameset--find-frame-if
9421876d 906 (lambda (f id)
38276e01 907 (frameset-frame-id-equal-p f id))
c6463340 908 display (frameset-cfg-id parameters)))
9421876d
JB
909 ;; If it has not been loaded, and it is not a minibuffer-only frame,
910 ;; let's look for an existing non-minibuffer-only frame to reuse.
a912c016
JB
911 (unless (or frame (eq (cdr (assq 'minibuffer parameters)) 'only))
912 (setq frame (frameset--find-frame-if
9421876d
JB
913 (lambda (f)
914 (let ((w (frame-parameter f 'minibuffer)))
915 (and (window-live-p w)
916 (window-minibuffer-p w)
917 (eq (window-frame w) f))))
918 display))))
919 (mini
920 ;; For minibufferless frames, check whether they already exist,
921 ;; and that they are linked to the right minibuffer frame.
a912c016 922 (setq frame (frameset--find-frame-if
a04d36a0 923 (lambda (f id mini-id)
38276e01 924 (and (frameset-frame-id-equal-p f id)
14d1e463
JB
925 (or (null mini-id) ; minibuffer frame not saved
926 (frameset-frame-id-equal-p
927 (window-frame (minibuffer-window f))
928 mini-id))))
c6463340 929 display (frameset-cfg-id parameters) (cdr mini))))
9421876d
JB
930 (t
931 ;; Default to just finding a frame in the same display.
a912c016 932 (setq frame (frameset--find-frame-if nil display))))
9421876d
JB
933 ;; If found, remove from the list.
934 (when frame
f097a3d2 935 (setq frameset--reuse-list (delq frame frameset--reuse-list)))
9421876d
JB
936 frame))
937
a912c016
JB
938(defun frameset--initial-params (parameters)
939 "Return a list of PARAMETERS that must be set when creating the frame.
d5671a82 940Setting position and size parameters as soon as possible helps reducing
a912c016
JB
941flickering; other parameters, like `minibuffer' and `border-width', can
942not be changed once the frame has been created. Internal use only."
c3561529 943 (cl-loop for param in '(left top width height border-width minibuffer)
9284000e 944 when (assq param parameters) collect it))
d5671a82 945
a912c016 946(defun frameset--restore-frame (parameters window-state filters force-onscreen)
9421876d
JB
947 "Set up and return a frame according to its saved state.
948That means either reusing an existing frame or creating one anew.
a912c016 949PARAMETERS is the frame's parameter alist; WINDOW-STATE is its window state.
063233c3 950For the meaning of FILTERS and FORCE-ONSCREEN, see `frameset-restore'.
d5671a82 951Internal use only."
a912c016 952 (let* ((fullscreen (cdr (assq 'fullscreen parameters)))
a912c016 953 (filtered-cfg (frameset-filter-params parameters filters nil))
9421876d
JB
954 (display (cdr (assq 'display filtered-cfg))) ;; post-filtering
955 alt-cfg frame)
956
9421876d
JB
957 (when fullscreen
958 ;; Currently Emacs has the limitation that it does not record the size
959 ;; and position of a frame before maximizing it, so we cannot save &
960 ;; restore that info. Instead, when restoring, we resort to creating
961 ;; invisible "fullscreen" frames of default size and then maximizing them
962 ;; (and making them visible) which at least is somewhat user-friendly
963 ;; when these frames are later de-maximized.
964 (let ((width (and (eq fullscreen 'fullheight) (cdr (assq 'width filtered-cfg))))
965 (height (and (eq fullscreen 'fullwidth) (cdr (assq 'height filtered-cfg))))
966 (visible (assq 'visibility filtered-cfg)))
967 (setq filtered-cfg (cl-delete-if (lambda (p)
968 (memq p '(visibility fullscreen width height)))
969 filtered-cfg :key #'car))
970 (when width
971 (setq filtered-cfg (append `((user-size . t) (width . ,width))
972 filtered-cfg)))
973 (when height
974 (setq filtered-cfg (append `((user-size . t) (height . ,height))
975 filtered-cfg)))
976 ;; These are parameters to apply after creating/setting the frame.
977 (push visible alt-cfg)
978 (push (cons 'fullscreen fullscreen) alt-cfg)))
979
4538c058
JB
980 ;; Time to find or create a frame and apply the big bunch of parameters.
981 (setq frame (and frameset--reuse-list
982 (frameset--reuse-frame display filtered-cfg)))
983 (if frame
984 (puthash frame :reused frameset--action-map)
985 ;; If a frame needs to be created and it falls partially or fully offscreen,
986 ;; sometimes it gets "pushed back" onscreen; however, moving it afterwards is
987 ;; allowed. So we create the frame as invisible and then reapply the full
988 ;; parameter alist (including position and size parameters).
989 (setq frame (make-frame-on-display display
990 (cons '(visibility)
991 (frameset--initial-params filtered-cfg))))
992 (puthash frame :created frameset--action-map))
993
9421876d
JB
994 (modify-frame-parameters frame
995 (if (eq (frame-parameter frame 'fullscreen) fullscreen)
996 ;; Workaround for bug#14949
997 (assq-delete-all 'fullscreen filtered-cfg)
998 filtered-cfg))
999
1000 ;; If requested, force frames to be onscreen.
1001 (when (and force-onscreen
1002 ;; FIXME: iconified frames should be checked too,
1003 ;; but it is impossible without deiconifying them.
1004 (not (eq (frame-parameter frame 'visibility) 'icon)))
307764cc 1005 (frameset-move-onscreen frame force-onscreen))
9421876d 1006
857ba6ec 1007 ;; Let's give the finishing touches (visibility, maximization).
9421876d
JB
1008 (when alt-cfg (modify-frame-parameters frame alt-cfg))
1009 ;; Now restore window state.
a912c016 1010 (window-state-put window-state (frame-root-window frame) 'safe)
9421876d
JB
1011 frame))
1012
063233c3 1013(defun frameset--minibufferless-last-p (state1 state2)
307764cc 1014 "Predicate to sort frame states in an order suitable for creating frames.
024b38fc
JB
1015It sorts minibuffer-owning frames before minibufferless ones.
1016Internal use only."
9421876d
JB
1017 (pcase-let ((`(,hasmini1 ,id-def1) (assq 'frameset--mini (car state1)))
1018 (`(,hasmini2 ,id-def2) (assq 'frameset--mini (car state2))))
1019 (cond ((eq id-def1 t) t)
1020 ((eq id-def2 t) nil)
1021 ((not (eq hasmini1 hasmini2)) (eq hasmini1 t))
14d1e463 1022 ((eq hasmini1 nil) (or id-def1 id-def2))
9421876d
JB
1023 (t t))))
1024
d5671a82 1025(defun frameset-keep-original-display-p (force-display)
a912c016
JB
1026 "True if saved frames' displays should be honored.
1027For the meaning of FORCE-DISPLAY, see `frameset-restore'."
d5671a82 1028 (cond ((daemonp) t)
307764cc 1029 ((eq system-type 'windows-nt) nil) ;; Does ns support more than one display?
d5671a82
JB
1030 (t (not force-display))))
1031
063233c3
JB
1032(defun frameset-minibufferless-first-p (frame1 _frame2)
1033 "Predicate to sort minibufferless frames before other frames."
9421876d
JB
1034 (not (frame-parameter frame1 'minibuffer)))
1035
51d30f2c 1036;;;###autoload
d5671a82 1037(cl-defun frameset-restore (frameset
a912c016 1038 &key predicate filters reuse-frames
4538c058
JB
1039 force-display force-onscreen
1040 cleanup-frames)
9421876d
JB
1041 "Restore a FRAMESET into the current display(s).
1042
a912c016
JB
1043PREDICATE is a function called with two arguments, the parameter alist
1044and the window-state of the frame being restored, in that order (see
1045the docstring of the `frameset' defstruct for additional details).
1046If PREDICATE returns nil, the frame described by that parameter alist
1047and window-state is not restored.
1048
1049FILTERS is an alist of parameter filters; if nil, the value of
1050`frameset-filter-alist' is used instead.
9421876d 1051
4538c058
JB
1052REUSE-FRAMES selects the policy to reuse frames when restoring:
1053 t All existing frames can be reused.
1054 nil No existing frame can be reused.
1055 match Only frames with matching frame ids can be reused.
1056 PRED A predicate function; it receives as argument a live frame,
1057 and must return non-nil to allow reusing it, nil otherwise.
9421876d
JB
1058
1059FORCE-DISPLAY can be:
76c5e5ab
JB
1060 t Frames are restored in the current display.
1061 nil Frames are restored, if possible, in their original displays.
4538c058 1062 delete Frames in other displays are deleted instead of restored.
76c5e5ab 1063 PRED A function called with two arguments, the parameter alist and
a912c016 1064 the window state (in that order). It must return t, nil or
4538c058 1065 `delete', as above but affecting only the frame that will
a912c016 1066 be created from that parameter alist.
9421876d
JB
1067
1068FORCE-ONSCREEN can be:
76c5e5ab
JB
1069 t Force onscreen only those frames that are fully offscreen.
1070 nil Do not force any frame back onscreen.
4538c058 1071 all Force onscreen any frame fully or partially offscreen.
76c5e5ab 1072 PRED A function called with three arguments,
d5671a82
JB
1073 - the live frame just restored,
1074 - a list (LEFT TOP WIDTH HEIGHT), describing the frame,
063233c3
JB
1075 - a list (LEFT TOP WIDTH HEIGHT), describing the workarea.
1076 It must return non-nil to force the frame onscreen, nil otherwise.
d5671a82 1077
4538c058
JB
1078CLEANUP-FRAMES allows to \"clean up\" the frame list after restoring a frameset:
1079 t Delete all frames that were not created or restored upon.
1080 nil Keep all frames.
1081 FUNC A function called with two arguments:
1082 - FRAME, a live frame.
1083 - ACTION, which can be one of
1084 :rejected Frame existed, but was not a candidate for reuse.
1085 :ignored Frame existed, was a candidate, but wasn't reused.
1086 :reused Frame existed, was a candidate, and restored upon.
1087 :created Frame didn't exist, was created and restored upon.
1088 Return value is ignored.
1089
d5671a82 1090Note the timing and scope of the operations described above: REUSE-FRAMES
3677ffeb 1091affects existing frames; PREDICATE, FILTERS and FORCE-DISPLAY affect the frame
4538c058
JB
1092being restored before that happens; FORCE-ONSCREEN affects the frame once
1093it has been restored; and CLEANUP-FRAMES affects all frames alive after the
1094restoration, including those that have been reused or created anew.
9421876d 1095
a912c016 1096All keyword parameters default to nil."
9421876d 1097
76c5e5ab 1098 (cl-assert (frameset-valid-p frameset))
9421876d 1099
4538c058
JB
1100 (let* ((frames (frame-list))
1101 (frameset--action-map (make-hash-table :test #'eq))
1102 ;; frameset--reuse-list is a list of frames potentially reusable. Later we
1103 ;; will decide which ones can be reused, and how to deal with any leftover.
1104 (frameset--reuse-list
1105 (pcase reuse-frames
1106 (`t
1107 frames)
1108 (`nil
1109 nil)
1110 (`match
1111 (cl-loop for (state) in (frameset-states frameset)
1112 when (frameset-frame-with-id (frameset-cfg-id state) frames)
1113 collect it))
1114 ((pred functionp)
1115 (cl-remove-if-not reuse-frames frames))
1116 (_
1117 (error "Invalid arg :reuse-frames %s" reuse-frames)))))
1118
1119 ;; Mark existing frames in the map; candidates to reuse are marked as :ignored;
1120 ;; they will be reassigned later, if chosen.
1121 (dolist (frame frames)
1122 (puthash frame
1123 (if (memq frame frameset--reuse-list) :ignored :rejected)
1124 frameset--action-map))
9421876d
JB
1125
1126 ;; Sort saved states to guarantee that minibufferless frames will be created
1127 ;; after the frames that contain their minibuffer windows.
1128 (dolist (state (sort (copy-sequence (frameset-states frameset))
063233c3 1129 #'frameset--minibufferless-last-p))
a912c016
JB
1130 (pcase-let ((`(,frame-cfg . ,window-cfg) state))
1131 (when (or (null predicate) (funcall predicate frame-cfg window-cfg))
1132 (condition-case-unless-debug err
1133 (let* ((d-mini (cdr (assq 'frameset--mini frame-cfg)))
1134 (mb-id (cdr d-mini))
14d1e463 1135 (default (and (car d-mini) mb-id))
a912c016
JB
1136 (force-display (if (functionp force-display)
1137 (funcall force-display frame-cfg window-cfg)
1138 force-display))
baf8d0ac 1139 (frameset--target-display nil)
94e5e202 1140 frame to-tty duplicate)
a912c016 1141 ;; Only set target if forcing displays and the target display is different.
baf8d0ac 1142 (unless (or (frameset-keep-original-display-p force-display)
ee79b33f
JB
1143 (equal (frame-parameter nil 'display)
1144 (cdr (assq 'display frame-cfg))))
baf8d0ac
JB
1145 (setq frameset--target-display (cons 'display
1146 (frame-parameter nil 'display))
1147 to-tty (null (cdr frameset--target-display))))
a912c016
JB
1148 ;; Time to restore frames and set up their minibuffers as they were.
1149 ;; We only skip a frame (thus deleting it) if either:
1150 ;; - we're switching displays, and the user chose the option to delete, or
1151 ;; - we're switching to tty, and the frame to restore is minibuffer-only.
1152 (unless (and frameset--target-display
4538c058 1153 (or (eq force-display 'delete)
a912c016
JB
1154 (and to-tty
1155 (eq (cdr (assq 'minibuffer frame-cfg)) 'only))))
94e5e202
JB
1156 ;; To avoid duplicating frame ids after restoration, we note any
1157 ;; existing frame whose id matches a frame configuration in the
1158 ;; frameset. Once the frame config is properly restored, we can
1159 ;; reset the old frame's id to nil.
4538c058
JB
1160 (setq duplicate (frameset-frame-with-id (frameset-cfg-id frame-cfg)
1161 frames))
a912c016
JB
1162 ;; Restore minibuffers. Some of this stuff could be done in a filter
1163 ;; function, but it would be messy because restoring minibuffers affects
1164 ;; global state; it's best to do it here than add a bunch of global
1165 ;; variables to pass info back-and-forth to/from the filter function.
1166 (cond
1167 ((null d-mini)) ;; No frameset--mini. Process as normal frame.
1168 (to-tty) ;; Ignore minibuffer stuff and process as normal frame.
1169 ((car d-mini) ;; Frame has minibuffer (or it is minibuffer-only).
1170 (when (eq (cdr (assq 'minibuffer frame-cfg)) 'only)
1171 (setq frame-cfg (append '((tool-bar-lines . 0) (menu-bar-lines . 0))
1172 frame-cfg))))
1173 (t ;; Frame depends on other frame's minibuffer window.
14d1e463
JB
1174 (when mb-id
1175 (let ((mb-frame (frameset-frame-with-id mb-id))
1176 (mb-window nil))
1177 (if (not mb-frame)
1178 (delay-warning 'frameset
1179 (format "Minibuffer frame %S not found" mb-id)
1180 :warning)
1181 (setq mb-window (minibuffer-window mb-frame))
1182 (unless (and (window-live-p mb-window)
1183 (window-minibuffer-p mb-window))
1184 (delay-warning 'frameset
1185 (format "Not a minibuffer window %s" mb-window)
1186 :warning)
1187 (setq mb-window nil)))
1188 (when mb-window
1189 (push (cons 'minibuffer mb-window) frame-cfg))))))
a912c016
JB
1190 ;; OK, we're ready at last to create (or reuse) a frame and
1191 ;; restore the window config.
1192 (setq frame (frameset--restore-frame frame-cfg window-cfg
1193 (or filters frameset-filter-alist)
1194 force-onscreen))
94e5e202
JB
1195 ;; Now reset any duplicate frameset--id
1196 (when (and duplicate (not (eq frame duplicate)))
1197 (set-frame-parameter duplicate 'frameset--id nil))
a912c016
JB
1198 ;; Set default-minibuffer if required.
1199 (when default (setq default-minibuffer-frame frame))))
1200 (error
1201 (delay-warning 'frameset (error-message-string err) :error))))))
9421876d
JB
1202
1203 ;; In case we try to delete the initial frame, we want to make sure that
1204 ;; other frames are already visible (discussed in thread for bug#14841).
1205 (sit-for 0 t)
1206
4538c058
JB
1207 ;; Clean up the frame list
1208 (when cleanup-frames
1209 (let ((map nil)
1210 (cleanup (if (eq cleanup-frames t)
1211 (lambda (frame action)
1212 (when (memq action '(:rejected :ignored))
1213 (delete-frame frame)))
1214 cleanup-frames)))
1215 (maphash (lambda (frame _action) (push frame map)) frameset--action-map)
1216 (dolist (frame (sort map
1217 ;; Minibufferless frames must go first to avoid
1218 ;; errors when attempting to delete a frame whose
1219 ;; minibuffer window is used by another frame.
1220 #'frameset-minibufferless-first-p))
1221 (condition-case-unless-debug err
1222 (funcall cleanup frame (gethash frame frameset--action-map))
1223 (error
1224 (delay-warning 'frameset (error-message-string err) :warning))))))
9421876d
JB
1225
1226 ;; Make sure there's at least one visible frame.
d27a1a7b
JB
1227 (unless (or (daemonp)
1228 (catch 'visible
1229 (maphash (lambda (frame _)
1230 (and (frame-live-p frame) (frame-visible-p frame)
1231 (throw 'visible t)))
1232 frameset--action-map)))
e7db5447 1233 (make-frame-visible (selected-frame)))))
9421876d 1234
77187e6f
JB
1235\f
1236;; Register support
1237
13c00cf0 1238;;;###autoload
77187e6f
JB
1239(defun frameset--jump-to-register (data)
1240 "Restore frameset from DATA stored in register.
1241Called from `jump-to-register'. Internal use only."
4538c058
JB
1242 (frameset-restore
1243 (aref data 0)
1244 :filters frameset-session-filter-alist
1245 :reuse-frames (if current-prefix-arg t 'match)
1246 :cleanup-frames (if current-prefix-arg
1247 ;; delete frames
1248 nil
1249 ;; iconify frames
1250 (lambda (frame action)
1251 (pcase action
1252 (`rejected (iconify-frame frame))
1253 ;; In the unexpected case that a frame was a candidate
1254 ;; (matching frame id) and yet not restored, remove it
1255 ;; because it is in fact a duplicate.
1256 (`ignored (delete-frame frame))))))
c6463340
JB
1257
1258 ;; Restore selected frame, buffer and point.
1259 (let ((frame (frameset-frame-with-id (aref data 1)))
1260 buffer window)
1261 (when frame
1262 (select-frame-set-input-focus frame)
1263 (when (and (buffer-live-p (setq buffer (marker-buffer (aref data 2))))
1264 (window-live-p (setq window (get-buffer-window buffer frame))))
1265 (set-frame-selected-window frame window)
1266 (with-current-buffer buffer (goto-char (aref data 2)))))))
77187e6f
JB
1267
1268;;;###autoload
7bcbca40 1269(defun frameset-to-register (register)
77187e6f
JB
1270 "Store the current frameset in register REGISTER.
1271Use \\[jump-to-register] to restore the frameset.
6a6b8e40
GM
1272Argument is a character, naming the register.
1273
1274Interactively, reads the register using `register-read-with-preview'."
7bcbca40 1275 (interactive (list (register-read-with-preview "Frameset to register: ")))
77187e6f
JB
1276 (set-register register
1277 (registerv-make
1278 (vector (frameset-save nil
1279 :app 'register
1280 :filters frameset-session-filter-alist)
1281 ;; frameset-save does not include the value of point
1282 ;; in the current buffer, so record that separately.
1283 (frameset-frame-id nil)
1284 (point-marker))
1285 :print-func (lambda (_data) (princ "a frameset."))
1286 :jump-func #'frameset--jump-to-register)))
1287
9421876d
JB
1288(provide 'frameset)
1289
1290;;; frameset.el ends here