frameset.el 56 KB

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