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