Hammerspoon / hammerspoon

Staggeringly powerful macOS desktop automation with Lua
http://www.hammerspoon.org
MIT License
12.11k stars 582 forks source link

Significant delay when loading hs.window.filter #3712

Open avegetablechicken opened 1 week ago

avegetablechicken commented 1 week ago

I experienced significant delay when loading hammerspoon scripts. The delay happens when hammerspoon loads hs.window.filter module for the first time. The delay lasts for almost the same time as hs.window._timed_allWindows hangs. Considering that process "com.apple.WebKit.WebContent" accounts for major part of delay when executing hs.window._timed_allWindows, I add a line of code in function "startAppWatcher" in file "window_filter.lua". It seems that the unexpected delay disappears.

local function startAppWatcher(app,appname,retry,nologging,force)
  if not app or not appname then log.e('called startAppWatcher with no app') return end
  if apps[appname] then return not nologging and log.df('app %s already registered',appname) end
 + if app:bundleID() == "com.apple.WebKit.WebContent" then return end
  if app:kind()<0 or not windowfilter.isGuiApp(appname) then log.df('app %s has no GUI',appname) return end
  if not fnutils.contains(axuielement.applicationElement(app):attributeNames() or {}, "AXFocusedWindow") then
      log.df('app %s has no AXFocusedWindow element',appname)
      return
  end
  retry=(retry or 0)+1

  if app:focusedWindow() or force then
    pendingApps[appname]=nil --done
    local watcher = app:newWatcher(appWindowEvent,appname)
    watcher:start({uiwatcher.windowCreated,uiwatcher.focusedWindowChanged})
    App.new(app,appname,watcher)
  else
    -- apps that start with an open window will often fail to be detected by the watcher if we
    -- start it too early, so we try `app:focusedWindow()` MAX_RETRIES times before giving up
    pendingApps[appname] = timer.doAfter(retry*RETRY_DELAY,function()
        startAppWatcher(app,appname,retry,nologging, retry > MAX_RETRIES)
    end)
  end
end

I don't know whether this is a bug, but it does occur to both of my MBP. Have anyone else come into it?

franzbu commented 6 days ago

Thanks for that; it speeds up starting EnhancedSpaces (https://github.com/franzbu/EnhancedSpaces.spoon) and I haven't encountered any side effects.