;;; dclock.el --- DigitalClock on Emacs -*- lexical-binding: nil -*-
;;;
;;; Version: 2026/05/01
;;;
;;; Install
;;;  copy dclock.el to /usr/share/emacs/site-lisp/.
;;;
;;; Setting
;;;  add to .emacs
;;;  ----
;;;  (require 'dclock)
;;;  (setq dclock-font-scale 9)  ;;example
;;;  (setq dclock-font-faces     ;;example
;;;        '(:family "DSEG7 Modern" :foundry "outline" :slant italic :weight bold))
;;;  ----
;;;
;;; Start and Stop
;;;  M-x dclock-start
;;;  M-x dclock-stop
;;;

;;; Code:

(defcustom dclock-font-scale 8
  "Font scale for DigitalClock"
  :group 'dclock
  :type 'integer)

(defcustom dclock-font-faces nil
  "Font-faces for DigitalClock"
  :group 'dclock
  :type 'face-properties)

(defcustom dclock-format-time-string "%H:%M %S"
  "Display format for DigitalClock"
  :group 'dclock
  :type 'string)

(defcustom dclock-display-properties
  '(lambda () ""
     (progn
       (add-text-properties (- (point-max) 3) (point-max) '(face (:height 0.5)))
       ))
  "Function of tweak display text properties for DigitalClock"
  :group 'dclock
  :type 'function)

(defvar dclock-buffername "*DigitalClock*"
  "dclock buffer name")

(defvar dclock-timer nil
  "dclock timer")

(defvar dclock-mode-line-format
  '("    "
    mode-line-frame-identification
    mode-line-buffer-identification))

(defvar dclock-local-map nil)

(defun dclock-start (&optional othwin)
  "start dclock"
  (interactive)
  (if (eq (window-system) nil)
      (message "Warning: FontSize and FontFace can't be changed in no-window-system"))
  (progn
    (if dclock-timer (cancel-timer dclock-timer))
    (setq dclock-timer (run-with-timer t 1.0 'dclock))
    (let ((selected))
      (setq selected (selected-window))
      (if othwin
          (switch-to-buffer-other-window dclock-buffername)
        (switch-to-buffer dclock-buffername))
      (if (and dclock-font-faces (eq (not (window-system)) nil))
          (buffer-face-set (list dclock-font-faces)))
      (text-scale-set 0)
      (text-scale-set dclock-font-scale)
      (setq dclock-local-map (make-keymap))
      (define-key dclock-local-map "q"  'dclock-stop)
      (use-local-map dclock-local-map)
      (select-window selected))))

(defun dclock-start-other-window ()
  "start dclock"
  (interactive)
  (dclock-start t))

(defun dclock-stop ()
  "stop dclock"
  (interactive)
  (if dclock-timer
      (progn
        (cancel-timer dclock-timer)
        (setq dclock-timer nil)
        (kill-buffer dclock-buffername))))

(defun dclock ()
  (with-current-buffer (get-buffer-create dclock-buffername)
    (setq truncate-lines t)
    (setq cursor-type nil)
    (read-only-mode 0)
    (buffer-disable-undo)
    (erase-buffer)

    (insert (format-time-string dclock-format-time-string))
    (funcall dclock-display-properties)

    (setq mode-line-format dclock-mode-line-format)
    (read-only-mode 1)
    ))

(provide 'dclock)
