aboutsummaryrefslogtreecommitdiff
path: root/src/state.lisp
blob: 43b643e1ef1b5a0856b6876cb1954c510294e920 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
(in-package #:wallpaper-switcher)

;;; Remembering the current wallpaper
;;;
;;; The path of the last wallpaper set is kept in
;;; $XDG_STATE_HOME/wallpaper-switcher/current (by default
;;; ~/.local/state/wallpaper-switcher/current) as a single line, so
;;; `--restore` can set it again at login.

(defvar *state-file* nil
  "Overrides the state file location when non-NIL (used by the tests).")

(defun state-file-path ()
  (or *state-file*
      (let ((base (uiop:getenv-absolute-directory "XDG_STATE_HOME")))
        (merge-pathnames "wallpaper-switcher/current"
                         (or base (merge-pathnames ".local/state/"
                                                   (user-homedir-pathname)))))))

(defun write-state (pathname)
  "Save PATHNAME as the current wallpaper.  Writes a temporary file and
renames it over the old one, so a crash never leaves a half-written file.
The temporary file differs by name, not extension: RENAME-FILE fills a
missing extension in from the source, so renaming current.tmp to current
would land back on current.tmp."
  (let* ((path (state-file-path))
         (tmp (make-pathname :name (format nil "~A-tmp" (pathname-name path))
                             :defaults path)))
    (ensure-directories-exist path)
    (with-open-file (out tmp :direction :output :if-exists :supersede)
      (write-line (uiop:native-namestring pathname) out))
    (uiop:rename-file-overwriting-target tmp path)
    path))

(defun read-state ()
  "The saved wallpaper path as a string, or NIL if none has been saved."
  (let ((path (state-file-path)))
    (when (probe-file path)
      (let ((line (string-trim '(#\Space #\Tab #\Newline #\Return)
                               (uiop:read-file-string path))))
        (unless (string= line "") line)))))