aboutsummaryrefslogtreecommitdiff
path: root/src/state.lisp
diff options
context:
space:
mode:
Diffstat (limited to 'src/state.lisp')
-rw-r--r--src/state.lisp41
1 files changed, 41 insertions, 0 deletions
diff --git a/src/state.lisp b/src/state.lisp
new file mode 100644
index 0000000..43b643e
--- /dev/null
+++ b/src/state.lisp
@@ -0,0 +1,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)))))