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