lisp/frameset.el (frameset-save): Check validity of the resulting frameset.
[bpt/emacs.git] / lisp / frameset.el
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
44 (cl-defstruct (frameset (:type vector) :named
45 ;; Copier is defined below.
46 (:copier nil))
47
48 "A frameset encapsulates a serializable view of a set of frames and windows.
49
50 It contains the following slots, which can be accessed with
51 \(frameset-SLOT fs) and set with (setf (frameset-SLOT fs) VALUE):
52
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
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).
60 name A string, the name of the frameset instance.
61 description A string, a description for user consumption (to show in
62 menus, messages, etc).
63 properties A property list, to store both frameset-specific and
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
67 restored. FRAME-PARAMETERS is a frame's parameter alist,
68 extracted with (frame-parameters FRAME) and filtered
69 through `frameset-filter-params'.
70 WINDOW-STATE is the output of `window-state-get' applied
71 to the root window of the frame.
72
73 To avoid collisions, it is recommended that applications wanting to add
74 private serializable data to `properties' either store all info under a
75 single, distinctive name, or use property names with a well-chosen prefix.
76
77 A frameset is intended to be used through the following simple API:
78
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).
81 - `frameset-restore' takes a frameset, and restores the frames and windows
82 it describes, as faithfully as possible.
83 - `frameset-p' is the predicate for the frameset type.
84 - `frameset-valid-p' checks a frameset's validity.
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
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))
97
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
103 It is an integer that identifies the format of the frameset struct.
104 This slot cannot be modified.\n\n(fn FRAMESET)")
105 (put 'frameset-timestamp 'function-documentation
106 "Return the creation timestamp of FRAMESET.\n
107 The value is in the format returned by `current-time'.
108 This slot cannot be modified.\n\n(fn FRAMESET)")
109 (put 'frameset-app 'function-documentation
110 "Return the application identifier for FRAMESET.\n
111 The 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
119 This list is useful to store both frameset-specific and user-defined
120 serializable data. The simplest way to access and modify it is
121 through `frameset-prop' (which see).\n\n(fn FRAMESET)")
122 (put 'frameset-states 'function-documentation
123 "Return the list of frame states of FRAMESET.\n
124 A frame state is a pair (FRAME-PARAMETERS . WINDOW-STATE), where
125 FRAME-PARAMETERS is a frame's parameter alist, extracted with
126 \(frame-parameters FRAME) and filtered through `frameset-filter-params',
127 and WINDOW-STATE is the output of `window-state-get' applied to the
128 root window of the frame.\n
129 IMPORTANT: Modifying this slot may cause frameset functions to fail,
130 unless the type constraints defined above are respected.\n\n(fn FRAMESET)")
131
132 (defun frameset-copy (frameset)
133 "Return a deep copy of FRAMESET.
134 FRAMESET is copied with `copy-tree'."
135 (copy-tree frameset t))
136
137 ;;;###autoload
138 (defun frameset-valid-p (object)
139 "Return non-nil if OBJECT is a valid frameset, nil otherwise.
140
141 The return value is nil if OBJECT is not a frameset, or not
142 a valid one, and the frameset version if it is valid."
143 (and (vectorp object) ; a vector
144 (>= (length object) 8) ; of the right length (future-proof)
145 (eq (aref object 0) 'frameset) ; tagged as `frameset'
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
159
160 ;; A setf'able accessor to the frameset's properties
161 (defun frameset-prop (frameset property)
162 "Return the value for FRAMESET of PROPERTY.
163
164 Properties can be set with
165
166 (setf (frameset-prop FRAMESET PROPERTY) NEW-VALUE)"
167 (plist-get (frameset-properties frameset) property))
168
169 (gv-define-setter frameset-prop (val fs prop)
170 (macroexp-let2 nil v val
171 `(progn
172 (setf (frameset-properties ,fs)
173 (plist-put (frameset-properties ,fs) ,prop ,v))
174 ,v)))
175
176 \f
177 ;; Filtering
178
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 ;;
219 ;; First, a clarification. The word "filter" in these names refers to both
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
226 ;; accumulates an output alist, FILTERED, by checking each parameter in
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
277 ;; display they do no harm, but they clutter the parameter alist.
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
294 ;; from the fact that they are badly mangled when going through a
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
314 ;; `frameset-filter-shelve-param' and `frameset-filter-unshelve-param' do.
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 ;;
353 ;; Now, what about the filter alist variables? There are three of them,
354 ;; though only two sets of parameters:
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 ;;
368 ;; IMPORTANT: These variables share structure and should NEVER be modified.
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
432 ;;;###autoload
433 (defvar frameset-session-filter-alist
434 '((name . :never)
435 (left . frameset-filter-iconified)
436 (minibuffer . frameset-filter-minibuffer)
437 (top . frameset-filter-iconified))
438 "Minimum set of parameters to filter for live (on-session) framesets.
439 DO NOT MODIFY. See `frameset-filter-alist' for a full description.")
440
441 ;;;###autoload
442 (defvar frameset-persistent-filter-alist
443 (nconc
444 '((background-color . frameset-filter-sanitize-color)
445 (buffer-list . :never)
446 (buffer-predicate . :never)
447 (buried-buffer-list . :never)
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))
463 frameset-session-filter-alist)
464 "Parameters to filter for persistent framesets.
465 DO NOT MODIFY. See `frameset-filter-alist' for a full description.")
466
467 ;;;###autoload
468 (defvar frameset-filter-alist frameset-persistent-filter-alist
469 "Alist of frame parameters and filtering functions.
470
471 This alist is the default value of the FILTERS argument of
472 `frameset-save' and `frameset-restore' (which see).
473
474 Initially, `frameset-filter-alist' is set to, and shares the value of,
475 `frameset-persistent-filter-alist'. You can override any item in
476 this alist by `push'ing a new item onto it. If, for some reason, you
477 intend to modify existing values, do
478
479 (setq frameset-filter-alist (copy-tree frameset-filter-alist))
480
481 before changing anything.
482
483 On saving, PARAMETERS is the parameter alist of each frame processed,
484 and FILTERED is the parameter alist that gets saved to the frameset.
485
486 On restoring, PARAMETERS is the parameter alist extracted from the
487 frameset, and FILTERED is the resulting frame parameter alist used
488 to restore the frame.
489
490 Elements of `frameset-filter-alist' are conses (PARAM . ACTION),
491 where PARAM is a parameter name (a symbol identifying a frame
492 parameter), and ACTION can be:
493
494 nil The parameter is copied to FILTERED.
495 :never The parameter is never copied to FILTERED.
496 :save The parameter is copied only when saving the frame.
497 :restore The parameter is copied only when restoring the frame.
498 FILTER A filter function.
499
500 FILTER can be a symbol FILTER-FUN, or a list (FILTER-FUN ARGS...).
501 FILTER-FUN is invoked with
502
503 (apply FILTER-FUN CURRENT FILTERED PARAMETERS SAVING ARGS)
504
505 where
506
507 CURRENT A cons (PARAM . VALUE), where PARAM is the one being
508 filtered and VALUE is its current value.
509 FILTERED The resulting alist (so far).
510 PARAMETERS The complete alist of parameters being filtered,
511 SAVING Non-nil if filtering before saving state, nil if filtering
512 before restoring it.
513 ARGS Any additional arguments specified in the ACTION.
514
515 FILTER-FUN is allowed to modify items in FILTERED, but no other arguments.
516 It must return:
517 nil Skip CURRENT (do not add it to FILTERED).
518 t Add CURRENT to FILTERED as is.
519 (NEW-PARAM . NEW-VALUE) Add this to FILTERED instead of CURRENT.
520
521 Frame parameters not on this alist are passed intact, as if they were
522 defined with ACTION = nil.")
523
524
525 (defvar frameset--target-display nil
526 ;; Either (minibuffer . VALUE) or nil.
527 ;; This refers to the current frame config being processed inside
528 ;; `frameset-restore' and its auxiliary functions (like filtering).
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.
535 Return non-nil if the parameter alist PARAMETERS describes a frame on a
536 text-only terminal, and the frame is being restored on a graphic display;
537 otherwise return nil. Only meaningful when called from a filtering
538 function in `frameset-filter-alist'."
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
542
543 (defun frameset-switch-to-tty-p (parameters)
544 "True when switching to a text-only terminal.
545 Return non-nil if the parameter alist PARAMETERS describes a frame on a
546 graphic display, and the frame is being restored on a text-only terminal;
547 otherwise return nil. Only meaningful when called from a filtering
548 function in `frameset-filter-alist'."
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
552
553 (defun frameset-filter-tty-to-GUI (_current _filtered parameters saving)
554 "Remove CURRENT when switching from tty to a graphic display.
555
556 For the meaning of CURRENT, FILTERED, PARAMETERS and SAVING,
557 see `frameset-filter-alist'."
558 (or saving
559 (not (frameset-switch-to-gui-p parameters))))
560
561 (defun frameset-filter-sanitize-color (current _filtered parameters saving)
562 "When switching to a GUI frame, remove \"unspecified\" colors.
563 Useful as a filter function for tty-specific parameters.
564
565 For the meaning of CURRENT, FILTERED, PARAMETERS and SAVING,
566 see `frameset-filter-alist'."
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)
573 "When saving, convert (minibuffer . #<window>) to (minibuffer . t).
574
575 For the meaning of CURRENT, FILTERED, PARAMETERS and SAVING,
576 see `frameset-filter-alist'."
577 (or (not saving)
578 (if (windowp (cdr current))
579 '(minibuffer . t)
580 t)))
581
582 (defun frameset-filter-shelve-param (current _filtered parameters saving
583 &optional prefix)
584 "When switching to a tty frame, save parameter P as PREFIX:P.
585 The parameter can be later restored with `frameset-filter-unshelve-param'.
586 PREFIX defaults to `GUI'.
587
588 For the meaning of CURRENT, FILTERED, PARAMETERS and SAVING,
589 see `frameset-filter-alist'."
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
601 (defun frameset-filter-unshelve-param (current filtered parameters saving)
602 "When switching to a GUI frame, restore PREFIX:P parameter as P.
603 CURRENT must be of the form (PREFIX:P . value).
604
605 For the meaning of CURRENT, FILTERED, PARAMETERS and SAVING,
606 see `frameset-filter-alist'."
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.
621 This is used for positional parameters `left' and `top', which are
622 meaningless in an iconified frame, so the frame is restored in a
623 default position.
624
625 For the meaning of CURRENT, FILTERED, PARAMETERS and SAVING,
626 see `frameset-filter-alist'."
627 (not (and saving (eq (cdr (assq 'visibility parameters)) 'icon))))
628
629 (defun frameset-filter-params (parameters filter-alist saving)
630 "Filter parameter alist PARAMETERS and return a filtered alist.
631 FILTER-ALIST is an alist of parameter filters, in the format of
632 `frameset-filter-alist' (which see).
633 SAVING is non-nil while filtering parameters to save a frameset,
634 nil while the filtering is done to restore it."
635 (let ((filtered nil))
636 (dolist (current parameters)
637 ;; When saving, the parameter alist is temporary, so modifying it
638 ;; is not a problem. When restoring, the parameter alist is part
639 ;; of a frameset, so we must copy parameters to avoid inadvertent
640 ;; modifications.
641 (pcase (cdr (assq (car current) filter-alist))
642 (`nil
643 (push (if saving current (copy-tree current)) filtered))
644 (:never
645 nil)
646 (:restore
647 (unless saving (push (copy-tree current) filtered)))
648 (:save
649 (when saving (push current filtered)))
650 ((or `(,fun . ,args) (and fun (pred fboundp)))
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))))
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
667 ;; Frame ids
668
669 (defun frameset--set-id (frame)
670 "Set FRAME's id if not yet set.
671 Internal use only."
672 (unless (frame-parameter frame 'frameset--id)
673 (set-frame-parameter frame
674 'frameset--id
675 (mapconcat (lambda (n) (format "%04X" n))
676 (cl-loop repeat 4 collect (random 65536))
677 "-"))))
678 ;;;###autoload
679 (defun frameset-frame-id (frame)
680 "Return the frame id of FRAME, if it has one; else, return nil.
681 A frame id is a string that uniquely identifies a frame.
682 It is persistent across `frameset-save' / `frameset-restore'
683 invocations, and once assigned is never changed unless the same
684 frame is duplicated (via `frameset-restore'), in which case the
685 newest 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
694 (defun frameset-frame-with-id (id &optional frame-list)
695 "Return the live frame with id ID, if exists; else nil.
696 If FRAME-LIST is a list of frames, check these frames only.
697 If 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
705
706 (defun frameset--record-minibuffer-relationships (frame-list)
707 "Process FRAME-LIST and record minibuffer relationships.
708 FRAME-LIST is a list of frames. Internal use only."
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)))
724 (id (and mb-frame (frameset-frame-id mb-frame))))
725 (if (null id)
726 (error "Minibuffer frame %S for %S is not being saved" mb-frame frame)
727 ;; For minibufferless frames, frameset--mini is a cons
728 ;; (nil . FRAME-ID), where FRAME-ID is the frameset--id
729 ;; of the frame containing its minibuffer window.
730 (set-frame-parameter frame
731 'frameset--mini
732 (cons nil id)))))))
733
734 ;;;###autoload
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.
739 Dead frames and non-frame objects are silently removed from the list.
740 If nil, FRAME-LIST defaults to the output of `frame-list' (all live frames).
741 APP, NAME and DESCRIPTION are optional data; see the docstring of the
742 `frameset' defstruct for details.
743 FILTERS is an alist of parameter filters; if nil, the value of the variable
744 `frameset-filter-alist' is used instead.
745 PREDICATE is a predicate function, which must return non-nil for frames that
746 should be saved; if PREDICATE is nil, all frames from FRAME-LIST are saved.
747 PROPERTIES is a user-defined property list to add to the frameset."
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)
752 list)))
753 fs)
754 (frameset--record-minibuffer-relationships frames)
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))
771
772 \f
773 ;; Restoring framesets
774
775 (defvar frameset--reuse-list nil
776 "The list of frames potentially reusable.
777 Its value is only meaningful during execution of `frameset-restore'.
778 Internal use only.")
779
780 (defun frameset-compute-pos (value left/top right/bottom)
781 "Return an absolute positioning value for a frame.
782 VALUE is the value of a positional frame parameter (`left' or `top').
783 If VALUE is relative to the screen edges (like (+ -35) or (-200), it is
784 converted to absolute by adding it to the corresponding edge; if it is
785 an absolute position, it is returned unmodified.
786 LEFT/TOP and RIGHT/BOTTOM indicate the dimensions of the screen in
787 pixels along the relevant direction: either the position of the left
788 and right edges for a `left' positional parameter, or the position of
789 the top and bottom edges for a `top' parameter."
790 (pcase value
791 (`(+ ,val) (+ left/top val))
792 (`(- ,val) (+ right/bottom val))
793 (val val)))
794
795 (defun frameset-move-onscreen (frame force-onscreen)
796 "If FRAME is offscreen, move it back onscreen and, if necessary, resize it.
797 For the description of FORCE-ONSCREEN, see `frameset-restore'.
798 When forced onscreen, frames wider than the monitor's workarea are converted
799 to fullwidth, and frames taller than the workarea are converted to fullheight.
800 NOTE: This only works for non-iconified frames."
801 (pcase-let* ((`(,left ,top ,width ,height) (cl-cdadr (frame-monitor-attributes frame)))
802 (right (+ left width -1))
803 (bottom (+ top height -1))
804 (fr-left (frameset-compute-pos (frame-parameter frame 'left) left right))
805 (fr-top (frameset-compute-pos (frame-parameter frame 'top) top bottom))
806 (ch-width (frame-char-width frame))
807 (ch-height (frame-char-height frame))
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)))
812 (when (pcase force-onscreen
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)))
819 ;; Any corner is outside the screen.
820 (:all (or (< fr-bottom top) (> fr-bottom bottom)
821 (< fr-left left) (> fr-left right)
822 (< fr-right left) (> fr-right right)
823 (< fr-top top) (> fr-top bottom)))
824 ;; Displaced to the left, right, above or below the screen.
825 (`t (or (> fr-left right)
826 (< fr-right left)
827 (> fr-top bottom)
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
859 (defun frameset--find-frame-if (predicate display &rest args)
860 "Find a frame in `frameset--reuse-list' satisfying PREDICATE.
861 Look through available frames whose display property matches DISPLAY
862 and return the first one for which (PREDICATE frame ARGS) returns t.
863 If 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
870 (defun frameset--reuse-frame (display parameters)
871 "Return an existing frame to reuse, or nil if none found.
872 DISPLAY is the display where the frame will be shown, and PARAMETERS
873 is the parameter alist of the frame being restored. Internal use only."
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.
886 (setq frame (frameset--find-frame-if nil display)))
887 ((car (setq mini (cdr (assq 'frameset--mini parameters))))
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).
891 (setq frame (frameset--find-frame-if
892 (lambda (f id)
893 (frameset-frame-id-equal-p f id))
894 display (cdr (assq 'frameset--id parameters))))
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.
897 (unless (or frame (eq (cdr (assq 'minibuffer parameters)) 'only))
898 (setq frame (frameset--find-frame-if
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.
908 (setq frame (frameset--find-frame-if
909 (lambda (f id mini-id)
910 (and (frameset-frame-id-equal-p f id)
911 (frameset-frame-id-equal-p (window-frame
912 (minibuffer-window f))
913 mini-id)))
914 display (cdr (assq 'frameset--id parameters)) (cdr mini))))
915 (t
916 ;; Default to just finding a frame in the same display.
917 (setq frame (frameset--find-frame-if nil display))))
918 ;; If found, remove from the list.
919 (when frame
920 (setq frameset--reuse-list (delq frame frameset--reuse-list)))
921 frame))
922
923 (defun frameset--initial-params (parameters)
924 "Return a list of PARAMETERS that must be set when creating the frame.
925 Setting position and size parameters as soon as possible helps reducing
926 flickering; other parameters, like `minibuffer' and `border-width', can
927 not be changed once the frame has been created. Internal use only."
928 (cl-loop for param in '(left top with height border-width minibuffer)
929 collect (assq param parameters)))
930
931 (defun frameset--restore-frame (parameters window-state filters force-onscreen)
932 "Set up and return a frame according to its saved state.
933 That means either reusing an existing frame or creating one anew.
934 PARAMETERS is the frame's parameter alist; WINDOW-STATE is its window state.
935 For the meaning of FILTERS and FORCE-ONSCREEN, see `frameset-restore'.
936 Internal use only."
937 (let* ((fullscreen (cdr (assq 'fullscreen parameters)))
938 (lines (assq 'tool-bar-lines parameters))
939 (filtered-cfg (frameset-filter-params parameters filters nil))
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
974 ;; parameter alist (including position and size parameters).
975 (setq frame (or (and frameset--reuse-list
976 (frameset--reuse-frame display filtered-cfg))
977 (make-frame-on-display display
978 (cons '(visibility)
979 (frameset--initial-params filtered-cfg)))))
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)))
991 (frameset-move-onscreen frame force-onscreen))
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.
997 (window-state-put window-state (frame-root-window frame) 'safe)
998 frame))
999
1000 (defun frameset--minibufferless-last-p (state1 state2)
1001 "Predicate to sort frame states in an order suitable for creating frames.
1002 It sorts minibuffer-owning frames before minibufferless ones.
1003 Internal use only."
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
1012 (defun frameset-keep-original-display-p (force-display)
1013 "True if saved frames' displays should be honored.
1014 For the meaning of FORCE-DISPLAY, see `frameset-restore'."
1015 (cond ((daemonp) t)
1016 ((eq system-type 'windows-nt) nil) ;; Does ns support more than one display?
1017 (t (not force-display))))
1018
1019 (defun frameset-minibufferless-first-p (frame1 _frame2)
1020 "Predicate to sort minibufferless frames before other frames."
1021 (not (frame-parameter frame1 'minibuffer)))
1022
1023 ;;;###autoload
1024 (cl-defun frameset-restore (frameset
1025 &key predicate filters reuse-frames
1026 force-display force-onscreen)
1027 "Restore a FRAMESET into the current display(s).
1028
1029 PREDICATE is a function called with two arguments, the parameter alist
1030 and the window-state of the frame being restored, in that order (see
1031 the docstring of the `frameset' defstruct for additional details).
1032 If PREDICATE returns nil, the frame described by that parameter alist
1033 and window-state is not restored.
1034
1035 FILTERS is an alist of parameter filters; if nil, the value of
1036 `frameset-filter-alist' is used instead.
1037
1038 REUSE-FRAMES selects the policy to use to reuse frames when restoring:
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).
1043 Remaining frames in this list are deleted; other frames not
1044 included on the list are left untouched.
1045
1046 FORCE-DISPLAY can be:
1047 t Frames are restored in the current display.
1048 nil Frames are restored, if possible, in their original displays.
1049 :delete Frames in other displays are deleted instead of restored.
1050 PRED A function called with two arguments, the parameter alist and
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.
1054
1055 FORCE-ONSCREEN can be:
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,
1060 - the live frame just restored,
1061 - a list (LEFT TOP WIDTH HEIGHT), describing the frame,
1062 - a list (LEFT TOP WIDTH HEIGHT), describing the workarea.
1063 It must return non-nil to force the frame onscreen, nil otherwise.
1064
1065 Note the timing and scope of the operations described above: REUSE-FRAMES
1066 affects existing frames; PREDICATE, FILTERS and FORCE-DISPLAY affect the frame
1067 being restored before that happens; and FORCE-ONSCREEN affects the frame once
1068 it has been restored.
1069
1070 All keyword parameters default to nil."
1071
1072 (cl-assert (frameset-valid-p frameset))
1073
1074 (let (other-frames)
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
1079 ((or `nil `:keep)
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)
1085 (memq frame frameset--reuse-list))
1086 (frame-list))))
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))
1094 #'frameset--minibufferless-last-p))
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))))))
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.
1169 (unless (eq reuse-frames :keep)
1170 (dolist (frame (sort (nconc (if (listp reuse-frames) nil other-frames)
1171 frameset--reuse-list)
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))
1176 (condition-case err
1177 (delete-frame frame)
1178 (error
1179 (delay-warning 'frameset (error-message-string err))))))
1180 (setq frameset--reuse-list nil
1181 frameset--target-display nil)
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