;; -*-lisp-*-
;;
;; StumpWM configuration file
;; <https://stumpwm.github.io/>
;;
;; 2016 - 2022 (c) Marcel Kapfer <opensource@mmk2410.org>
;; MIT License

(in-package :stumpwm)

(defun mmk2410/work ()
  "Returns T if running my work machine"
  (string-equal
   (string-trim
    '(#\Space #\Newline #\Linefeed #\Return)
    (run-shell-command "hostname" t))
   "knuth"))

;; Other parameters
(defparameter *key-layout* "de" "Stores the current key layout")

;; Default applications
(defparameter *app-web-browser* "firefox" "Stores the web browser")
(defparameter *app-snd-web-browser* "qutebrowser" "Stores the 2nd web browser")
(defparameter *app-terminal* "alacritty" "Stores the terminal emulator")
(defparameter *app-editor* "es" "Stores the editor")
(defparameter *app-db-browser* "beekeeper" "Stores the DB browser")
(defparameter *app-password* "keepassxc" "Stores the password manager")
(defparameter *app-file-manager* "nautilus" "Stores the terminal emulator")
(defparameter *app-music-player* "spotify" "Stores the terminal emulator")

;; Host-specific default applications
(when (mmk2410/work)
  (defparameter *app-ide* "phpstorm" "Stores the IDE")
  (defparameter *app-api-builder* "postman" "Stores the API builder")
  (defparameter *app-communication* "teams" "Stores the chat application"))

;; set correct module directory
(set-module-dir "~/.stumpwm.d/modules")

;; creating or rename groups
(when *initializing*
  (grename "web")
  (gnewbg "emacs")
  (gnewbg "work")
  (gnewbg "misc")
  (gnewbg "music")
  (gnewbg "winkel"))

;; border style
(setf *window-border-style* :tight)
(set-focus-color "#b00045")
(set-win-bg-color "#b00045")
(set-unfocus-color "#333333")
(set-float-focus-color "#b00045")
(set-float-unfocus-color "#333333")

;; window gravity
(set-normal-gravity :center)
(set-maxsize-gravity :center)
(set-transient-gravity :center)
(gravity :center)

;; input bar position
(setf *input-window-gravity* :center)

;; message bar position
(setf *message-window-gravity* :center)

;; message timeout
(setf *timeout-wait* 3)

;; set the mouse focus
(setf *mouse-focus-policy* :click)

;; set DESKTOP_SESSION variable
(setf (getenv "DESKTOP_SESSION") "stumpwm")

;; bugfix for scrolling doesn't work with an external mouse in GTK+3 Apps
(setf (getenv "GDK_CORE_DEVICE_EVENTS") "1")

;; Add .local/bin to PATH
(setf (getenv "PATH") (concatenate 'string "~/.local/bin:" (getenv "PATH")))

;; style message windows
(set-bg-color "#333333")
(set-border-color "#b00045")

;; loading modeline modules
(load-module "battery-portable")
(load-module "stumptray")

;; mode-line style
(setf *mode-line-background-color* "#333333"
      *mode-line-foreground-color* "#cccccc"
      *time-modeline-string* "%a %b %e %k:%M"
      *mode-line-timeout* 5
      *mode-line-border-width* 0
      *mode-line-pad-x* 3
      *mode-line-pad-y* 3
      *screen-mode-line-format* (list " [%g] %w ^> [%B] [ %d ] %T"))

;; Gaps
(load-module "swm-gaps")
(setf swm-gaps:*inner-gaps-size* 5
      swm-gaps:*outer-gaps-size* 10
      swm-gaps:*head-gaps-size* 0)
(when *initializing*
  (swm-gaps:toggle-gaps))

;; customize texts
(setf *window-format* "^B %n ^b %20t "
      *group-format* "%t")

;; root keybindings
(set-prefix-key (kbd "C-q"))

;; Application keybindings
(define-key *root-map* (kbd "W") (concatenate 'string "exec " *app-web-browser*))
(define-key *root-map* (kbd "c") (concatenate 'string "exec " *app-terminal*))
(define-key *root-map* (kbd "e") (concatenate 'string "exec " *app-editor*))

(defvar *application-run-bindings*
  (let ((m (make-sparse-keymap)))
    (define-key m (kbd "m") (concatenate 'string "exec " *app-music-player*))
    (define-key m (kbd "e") (concatenate 'string "exec " *app-file-manager*))
    (define-key m (kbd "d") (concatenate 'string "exec " *app-db-browser*))
    (define-key m (kbd "w") (concatenate 'string "exec " *app-snd-web-browser*))
    (define-key m (kbd "p") (concatenate 'string "exec " *app-password*))
    (when (mmk2410/work)
      (define-key m (kbd "i") (concatenate 'string "exec " *app-ide*))
      (define-key m (kbd "a") (concatenate 'string "exec " *app-api-builder*))
      (define-key m (kbd "c") (concatenate 'string "exec " *app-communication*)))
    m))

(define-key *root-map* (kbd "RET") '*application-run-bindings*)

;;; bind keys for changing workspace
(define-key *top-map* (kbd "s-1") "gselect web")
(define-key *top-map* (kbd "s-2") "gselect emacs")
(define-key *top-map* (kbd "s-3") "gselect work")
(define-key *top-map* (kbd "s-4") "gselect misc")
(define-key *top-map* (kbd "s-9") "gselect music")
(define-key *top-map* (kbd "s-0") "gselect winkel")
(define-key *top-map* (kbd "s-p") "gother")

;; bind keys for moving the current window to another workspace
(define-key *top-map* (kbd "s-C-1") "gmove web")
(define-key *top-map* (kbd "s-C-2") "gmove emacs")
(define-key *top-map* (kbd "s-C-3") "gmove work")
(define-key *top-map* (kbd "s-C-4") "gmove misc")
(define-key *top-map* (kbd "s-C-9") "gmove music")
(define-key *top-map* (kbd "s-C-0") "gmove winkel")

;; bind keys for focus changing
(define-key *top-map* (kbd "s-h") "move-focus left")
(define-key *top-map* (kbd "s-j") "move-focus down")
(define-key *top-map* (kbd "s-k") "move-focus up")
(define-key *top-map* (kbd "s-l") "move-focus right")

;; bind keys for window moving
(define-key *top-map* (kbd "s-C-h") "move-window left")
(define-key *top-map* (kbd "s-C-j") "move-window down")
(define-key *top-map* (kbd "s-C-k") "move-window up")
(define-key *top-map* (kbd "s-C-l") "move-window right")

;;; mode-line key
(define-key *root-map* (kbd "Menu") "mode-line")

;; define volume control keys
(define-key *top-map* (kbd "XF86AudioLowerVolume") "exec amixer set Master 5%-")
(define-key *top-map* (kbd "XF86AudioRaiseVolume") "exec amixer set Master 5%+")
(define-key *top-map* (kbd "XF86AudioMute") "exec amixer set Master toggle")
(define-key *top-map* (kbd "XF86AudioMicMute") "exec amixer set Capture toggle")

;; webjump keys
(defvar *webjump-frame-bindings*
  (let  ((m (make-sparse-keymap)))
    (define-key m (kbd "g") "google")
    (define-key m (kbd "G") "googlede")
    (define-key m (kbd "d") "duckduckgo")
    (define-key m (kbd "D") "packages")
    (define-key m (kbd "w") "wikipedia")
    (define-key m (kbd "W") "wikipediade")
    m))

(define-key *root-map* (kbd "j") '*webjump-frame-bindings*)

;; computer power state keys
(defvar *powerstate-frame-bindings*
  (let ((m (make-sparse-keymap)))
    (define-key m (kbd "M-s") "exec systemctl suspend")
    (define-key m (kbd "M-p") "exec systemctl poweroff")
    (define-key m (kbd "M-r") "exec systemctl reboot")
    (define-key m (kbd "M-h") "exec systemctl hibernate")
    m))

(define-key *root-map* (kbd "C-F12") '*powerstate-frame-bindings*)

;; lockscreen
(define-key *root-map* (kbd "M-l") "exec blurlock")

;; battery status
(define-key *root-map* (kbd "b") "exec ~/scripts/rat/bat.sh")

;; xserver

(run-shell-command "xrdb -merge ~/.Xresources")
;;; HiDPI stuff.
;;; TODO: Only run if required
;; (run-shell-command "xrdb -merge ~/.Xresources-hidpi")

;; dunst notify server
(run-shell-command "dunst")

;; nitrogen (wallpaper)
(run-shell-command "~/.fehbg")

;; start compton (compositor)
(run-shell-command "picom -b")

;; start mode line
(if (not (head-mode-line (current-head)))
    (toggle-mode-line (current-screen) (current-head)))

(defparameter *backlight-sysfs* "/sys/class/backlight/intel_backlight/")

(defun get-max-backlight ()
  "Retrieve maximal backlight brightness from sysfs"
  (let ((max-backlight-file (concatenate 'string *backlight-sysfs* "max_brightness")))
    (if (probe-file max-backlight-file)
	(with-open-file (in max-backlight-file)
	  (parse-integer (read-line in))))))

(defun get-backlight ()
  "Retrieve current backlight brightness from sysfs"
  (let ((backlight-file (concatenate 'string *backlight-sysfs* "brightness")))
    (if (probe-file backlight-file)
	(with-open-file (in backlight-file)
	  (parse-integer (read-line in))))))

(defun get-backlight-rel ()
  "Retrieve current backlight brightness relative to maximum"
  (round (* 100
	    (float (/ (get-backlight)
		      (get-max-backlight))))))

(defun set-backlight (value)
  "Set backlight brightness to given value using sysfs"
  (let ((backlight-file (concatenate 'string *backlight-sysfs* "brightness")))
    (if (probe-file backlight-file)
	(progn (with-open-file (out backlight-file
				    :direction :output
				    :if-exists :overwrite)
		 (format out "~D" (truncate value)))
	       value))))

(defun set-backlight-rel (value)
  "Set backlight brightness relative to maximum"
  (let ((max-backlight (get-max-backlight)))
    (if max-backlight
	(set-backlight (* 0.01 value max-backlight)))))

(defcommand change-backlight (value)
  ((:number "Backlight in %: "))
  "Setting a new backlight value"
  (unless (set-backlight-rel value)
    (echo "Can't set backlight")))

(defcommand increase-backlight ()
  ()
  "Increase backlight by 5%"
  (let ((current (get-backlight-rel)))
    (if (> current 95)
	(set-backlight-rel 100)
	(set-backlight-rel (+ current 5)))))

(defcommand decrease-backlight ()
  ()
  "Decrease backlight by 5%"
  (let ((current (get-backlight-rel)))
    (if (< current 6)
	(set-backlight-rel 1)
	(set-backlight-rel (- current 5)))))

(define-key *root-map* (kbd "B") "change-backlight")

(define-key *top-map* (kbd "XF86MonBrightnessUp") "increase-backlight")
(define-key *top-map* (kbd "XF86MonBrightnessDown") "decrease-backlight")

;; switch key layout
(defun switch-layout-to (new-lang)
  "Switch the key layout to the given one"
  (setq *key-layout* new-lang)
  (run-shell-command (concatenate 'string "setxkbmap -layout " new-lang " && xmodmap ~/.Xmodmap"))
  (echo (concatenate 'string "Set keyboard layout to " new-lang)))

;; switch key leyout to german
(defcommand layout-de ()
  ()
  "Set the keyboard layout to de (german)"
  (switch-layout-to "de"))

;; switch key leyout to american english
(defcommand layout-en ()
  ()
  "Set the keyboard layout to US International AltGr"
  (switch-layout-to "us -variant altgr-intl"))

;; switch key layout automatically
(defcommand switch-layout ()
  ()
  "Switch the layout"
  (if (string= "us -variant altgr-intl" *key-layout*)
      (switch-layout-to "de")
      (switch-layout-to "us -variant altgr-intl")))

(define-key *top-map* (kbd "s-SPC" ) "switch-layout")

;; switch workspace with a message
(defcommand change-workspace (n)
  ((:string n))
  "Switch workspace"
  (run-commands (concatenate 'string "gselect " n))
  (echo (concatenate 'string "Switched to " n)))

;; toggle window floating
(defcommand toggle-float ()
  ()
  "Toggle weather window is floating or not"
  (if (typep (current-window) 'STUMPWM::FLOAT-WINDOW)
      (unfloat-this)
      (float-this)))

;; and the key for it
(define-key *root-map* (kbd "C-f") "toggle-float")

;; key for keeping window always on top
(define-key *root-map* (kbd "C-T") "toggle-always-on-top")

;; webjumps
(defmacro make-web-jump (name prefix)
  `(defcommand ,(intern name) (search) ((:rest ,(concatenate 'string name " search: ")))
    (substitute #\+ #\Space search)
    (run-shell-command (concatenate 'string *web-browser* " " ,prefix search))))

(make-web-jump "google" "http://www.google.com/search?q=")
(make-web-jump "googlede" "http://www.google.de/search?q=")
(make-web-jump "duckduckgo" "https://duckduckgo.com/?q=")
(make-web-jump "packages" "https://packages.debian.org/")
(make-web-jump "wikipedia" "https://en.wikipedia.org/w/index.php?search=")
(make-web-jump "wikipediade" "https://de.wikipedia.org/w/index.php?search=")

(defun list-screen-layouts ()
  "Return an alist of possible screen layouts. Those are the layouts saved in
~/.screenlayout.sh. First is the name of the layout and second the path to the
script."
  (loop
     for file
     in (mapcar 'namestring
		(directory "~/.screenlayout/*.sh"))
     collect `(,(subseq file
			(+ 1 (search "/" file :from-end t))
			(- (length file) 3))
		,file)))

(defcommand switch-screen-layout ()
  ()
  "Menu to switch the screen layout. Possible options are the scripts saved in
  ~/.screenlayout/"
  (labels
      ((pick (options)
	 (let ((selection
		(select-from-menu
		 (current-screen)
		 options
		 nil
		 0)))
	   (cond
	     ((null selection)
	      nil)
	     (t (stringp (second selection))
		(run-shell-command (second selection))
                (refresh-heads)
                (refresh-heads))))))
    (pick (list-screen-layouts))))

(define-key *root-map* (kbd "l") "switch-screen-layout")

;; font configuration
(load-module "ttf-fonts")
(set-font (make-instance 'xft:font :family "JetBrains Mono" :subfamily "Regular" :size 12))

;; window placement rules
(define-frame-preference "winkel"
  (0 nil t :class "keepassxc")
  (0 nil t :class "Nextcloud")
  (0 nil t :class "TelegramDesktop")
  (0 nil t :class "Microsoft Teams - Preview"))

(define-frame-preference "web"
  (0 nil t :class "qutebrowser")
  (0 nil t :class "Firefox"))

(define-frame-preference "music"
  (0 nil t :class "Spotify"))

;; Start NetworkManager systray applet
(run-shell-command "nm-applet")

;; last settings
(stumptray:stumptray)

(switch-layout-to *key-layout*)

(run-shell-command "xsetroot -cursor_name left_ptr")
(run-shell-command "xmodmap $HOME/.Xmodmap" t)

;; Local Variables:
;; mode: stumpwm
;; End: