help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Ignore spurious focus events for ‘after-focus-change-function’


From: Andrea Greselin
Subject: Re: Ignore spurious focus events for ‘after-focus-change-function’
Date: Mon, 18 Jan 2021 20:09:44 +0100

I've settled with these home-made remakes of the obsoleted hooks:

  ;; Set up hooks to be run on focus in and focus out

  ;; Mutter sends spurious focus events, including sending focus out
  ;; events when Emacs never really was unfocused.
  ;; The timer filters out these false focus out events, while
  ;; checking the ‘last-focus-state’ allows ignoring repeated events
  ;; of the same kind.
  ;; REVIEW: false focus out events are still received sometimes when
  ;; using the menu bar.
  ;; Adapted from a suggestion by DasEwigeLicht on
  ;;
https://www.reddit.com/r/emacs/comments/kxsgtn/ignore_spurious_focus_events_for/

  (defvar focus-events-timer nil)

  (defvar last-focus-state (frame-focus-state))

  (defvar my-focus-in-hook nil
    "Normal hook run when all frames lose input focus.")

  (defvar my-focus-out-hook nil
    "Normal hook run when a frame gains focus.")

  (defun change-of-focus-functions ()
    (unless (equal last-focus-state (frame-focus-state))
      (if (frame-focus-state)
          (run-hooks 'my-focus-in-hook)
        (run-hooks 'my-focus-out-hook)))
    (setq focus-events-timer nil)
    (setq last-focus-state (frame-focus-state)))

  (defun run-change-of-focus-functions-with-timer ()
    (setq focus-events-timer
          (unless (timerp focus-events-timer)
            (run-at-time "0.05 sec" nil ; Found by trial and error.
                         #'change-of-focus-functions))))

  (add-function :after after-focus-change-function
                #'run-change-of-focus-functions-with-timer)

  ;; Test

  (defun focus-in-test ()
    (message "focus-in"))

  (defun focus-out-test ()
    (message "focus-out"))

  (add-hook 'my-focus-in-hook #'focus-in-test)
  (add-hook 'my-focus-out-hook #'focus-out-test)

  ;; Actual use

  (add-hook 'my-focus-out-hook #'do-auto-save)

Please reply with suggestions if there's something wrong or
less-than-optimal.

Andrea


reply via email to

[Prev in Thread] Current Thread [Next in Thread]