Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions shell/plugins/menu/Menu.qml
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,17 @@ Item {
else root.loadProviderForMenu(root.activeMenu)
}
}
// A route that fell back to root before both menu files had answered
// gets one more try once they have, so it sees the user's overrides too.
var pending = root.pendingInitialMenu
if (pending && root.menuFilesAnswered()) {
root.pendingInitialMenu = ""
if (root.opened && !root.dmenuActive && root.item(root.resolveRoute(pending))) root.openRoute(pending)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Startup checks run twice

Replaying a pending submenu runs the guard batch twice. rebuildItemsFromSources() already calls evaluateGuards() before this line. Calling openRoute(pending) then reaches openExistingMenu(), which calls it again. The first batch is still running, so the second call sets guardsPending and queues another full batch.

This adds avoidable work during startup. Skip the second evaluation when replaying a route from this rebuild.

}
}

function menuFilesAnswered() {
return root.defaultMenuSettled && root.userMenuSettled
}

// Each known provider is a tiny bash one-liner that enumerates a list and
Expand Down Expand Up @@ -813,12 +824,15 @@ Item {
root.selectedIndex = 0
root.cursorActive = root.mode !== "input"
root.disarmPointer()
// Typing or moving to another menu drops a route still waiting to open.
root.pendingInitialMenu = ""
if (!root.dmenuActive && root.filterText.trim()) root.loadProvidersForSearch()
root.rebuildDisplay()
}

function setActiveMenu(id, pushHistory, fromPointer) {
panel.freezeCardTop()
root.pendingInitialMenu = ""
if (!root.item(id)) id = "root"
if (pushHistory && id !== root.activeMenu) root.navStack = root.navStack.concat([root.activeMenu])
root.activeMenu = id
Expand Down Expand Up @@ -947,6 +961,8 @@ Item {
selectionFile = ""
doneFile = ""
activeMenu = root.item(initialMenu) ? initialMenu : "root"
// Only a route that fell back to root while the menu files load waits.
if (activeMenu === initialMenu || root.menuFilesAnswered()) pendingInitialMenu = ""
navStack = []
filterText = ""
selectedIndex = 0
Expand Down Expand Up @@ -1142,8 +1158,9 @@ Item {
watchChanges: true
printErrors: false
onLoaded: { root.defaultMenuItems = root.parseMenuJsonc(text()); root.defaultMenuSettled = true; root.rebuildItemsFromSources() }
// A user file that loaded first held its evaluation for this one.
onLoadFailed: { root.defaultMenuSettled = true; if (root.userMenuSettled) root.evaluateGuards() }
// A user file that answered first held its guard evaluation and any
// startup route for this one, so a failure rebuilds too.
onLoadFailed: { root.defaultMenuSettled = true; root.rebuildItemsFromSources() }
onFileChanged: reload()
}

Expand Down
242 changes: 242 additions & 0 deletions test/shell.d/menu-startup-route-test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
#!/bin/bash

set -euo pipefail

source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh"

# The shell hands a summon queued during startup to the menu as soon as the
# plugin loads, before either FileView has read its JSONC file. These checks
# run Menu.qml's own open, navigation and FileView handler code in a vm
# context and load the two files in either order around the summon.
run_node_test <<'JS'
const fs = require('fs')
const vm = require('vm')

const MenuModel = requireFromRoot('shell/plugins/menu/MenuModel.js')
const menuQml = fs.readFileSync(path.join(root, 'shell/plugins/menu/Menu.qml'), 'utf8')
const defaultJsonc = fs.readFileSync(path.join(root, 'default/omarchy/omarchy-menu.jsonc'), 'utf8')
const stockUserJsonc = fs.readFileSync(path.join(root, 'config/omarchy/extensions/omarchy-menu.jsonc'), 'utf8')
const personalJsonc = '{ "personal": {"label":"Personal"}, "personal.notes": {"label":"Notes","action":"notes"} }'
const aboutOverrideJsonc = '{ "about": {"label":"About","action":"my-about"} }'

const qmlFunctions = ['open', 'close', 'openRoute', 'resolveRoute', 'item', 'openExistingMenu', 'openDmenu', 'cancel',
'parseMenuJsonc', 'menuFilesAnswered', 'rebuildItemsFromSources', 'setFilter', 'setActiveMenu', 'goBack'].map(name => {
const fn = menuQml.match(new RegExp(` function ${name}\\([^]*?\\n }`))
if (!fn) fail(`Menu.qml provides ${name}`)
return fn[0]
})

function handler(fileId, signal) {
const found = menuQml.match(new RegExp(`id: ${fileId}\\n[^]*?${signal}: (\\{[^\\n]*\\})`))
if (!found) fail(`Menu.qml ${fileId} handles ${signal}`)
return found[1]
}
const defaultLoaded = handler('defaultMenuFile', 'onLoaded')
const userLoaded = handler('userMenuFile', 'onLoaded')
const userLoadFailed = handler('userMenuFile', 'onLoadFailed')
const defaultLoadFailed = handler('defaultMenuFile', 'onLoadFailed')

// The menu's own initial values for the properties this path reads.
function initial(name) {
const found = menuQml.match(new RegExp(`property (?:string|var|bool) ${name}: ([^\\n]*)`))
if (!found) fail(`Menu.qml declares ${name}`)
return vm.runInNewContext(found[1])
}

// A freshly loaded plugin: no rows yet, nothing open. Display, guards and
// providers are QML-side effects outside this path, so they are no-ops here.
function startMenu() {
const menu = vm.createContext({
MenuModel,
Qt: { callLater() {} },
keyCatcher: { forceActiveFocus() {} },
panel: { freezeCardTop() {} },
pointerGate: { allowInitialSample() {} },
appLibrary: null,
pendingInitialMenu: initial('pendingInitialMenu'),
defaultMenuItems: initial('defaultMenuItems'),
userMenuItems: initial('userMenuItems'),
defaultMenuSettled: initial('defaultMenuSettled'),
userMenuSettled: initial('userMenuSettled'),
menuCatalog: initial('menuCatalog'),
items: ({}),
itemOrder: [],
opened: false,
mode: 'menu',
rowsLoaded: false,
activeMenu: 'root',
filterText: '',
selectedIndex: 0,
cursorActive: false,
requestSerial: 0,
requestActive: false,
selectionFile: '',
doneFile: '',
navStack: [],
providerRevision: 0,
providersLoaded: ({}),
providerQueue: [],
actions: [],
evaluateGuards() {},
rebuildDisplay() {},
loadProvidersForSearch() {},
loadProviderForMenu() {},
invalidateVolatileProvider() {},
disarmPointer() {},
finishRequest() { menu.opened = false },
runAction(action) { menu.actions.push(action) }
})
menu.root = menu
Object.defineProperty(menu, 'dmenuActive', { get: () => menu.mode === 'select' || menu.mode === 'input' })
for (const fn of qmlFunctions) vm.runInContext(fn, menu)
return menu
}

function load(menu, signal, raw) {
menu.text = () => raw
vm.runInContext(signal, menu)
}

const summon = (menu, payload) => menu.open(JSON.stringify(payload))
const loadDefault = menu => load(menu, defaultLoaded, defaultJsonc)
const loadUser = (menu, raw) => load(menu, userLoaded, raw)
const noUserFile = menu => load(menu, userLoadFailed, '')
const noDefaultFile = menu => load(menu, defaultLoadFailed, '')

let menu = startMenu()
summon(menu, { menu: 'system' })
loadDefault(menu)
assertEqual(menu.activeMenu, 'root', 'a route summoned during startup waits for the user file as well')
noUserFile(menu)
assertEqual(menu.activeMenu, 'system', 'a route summoned during startup opens once the default file loads and the user file is found missing')
menu.setActiveMenu('style', true)
loadDefault(menu)
assertEqual(menu.activeMenu, 'style', 'a replayed route is not replayed again by a later reload')

menu = startMenu()
summon(menu, { menu: 'system' })
noUserFile(menu)
assertEqual(menu.activeMenu, 'root', 'with only the missing user file read, the route has nothing to resolve against yet')
loadDefault(menu)
assertEqual(menu.activeMenu, 'system', 'a route summoned during startup opens when the default file loads after the user file fails')

menu = startMenu()
summon(menu, { menu: 'power-menu' })
loadUser(menu, stockUserJsonc)
loadDefault(menu)
assertEqual(menu.activeMenu, 'system', 'an alias summoned during startup opens when the default file loads after the stock user file')

menu = startMenu()
summon(menu, { menu: 'personal' })
loadDefault(menu)
assertEqual(menu.activeMenu, 'root', 'a user-defined menu cannot resolve from the default file alone')
loadUser(menu, personalJsonc)
assertEqual(menu.activeMenu, 'personal', 'a user-defined menu summoned during startup opens when the user file loads after the default file')

menu = startMenu()
summon(menu, { menu: 'personal' })
loadUser(menu, personalJsonc)
loadDefault(menu)
assertEqual(menu.activeMenu, 'personal', 'a user-defined menu summoned during startup opens when the user file loads first')

menu = startMenu()
summon(menu, { menu: 'personal.notes' })
loadUser(menu, personalJsonc)
noDefaultFile(menu)
assertDeepEqual(menu.actions, ['notes'], 'a route summoned during startup gets its one try when the default file fails after the user file loads')

menu = startMenu()
summon(menu, { menu: 'system' })
loadUser(menu, personalJsonc)
noDefaultFile(menu)
assertEqual(menu.activeMenu, 'root', 'a route the failed default file would have defined stays on root')
menu.rebuildItemsFromSources(true)
loadDefault(menu)
assertEqual(menu.activeMenu, 'root', 'a route already tried is not opened by a catalog load or a default file that reappears')

menu = startMenu()
summon(menu, { menu: 'reminder-set' })
loadDefault(menu)
noUserFile(menu)
assertDeepEqual(menu.actions, ['omarchy-reminder -i'], 'an action alias summoned during startup runs its action once the files load')
assertEqual(menu.opened, false, 'running a replayed action alias closes the menu')

menu = startMenu()
summon(menu, { menu: 'about' })
loadDefault(menu)
assertDeepEqual(menu.actions, [], 'an action summoned during startup does not run before the user file has answered')
loadUser(menu, aboutOverrideJsonc)
assertDeepEqual(menu.actions, ['my-about'], 'an action summoned during startup runs the user override, not the default command')

menu = startMenu()
summon(menu, {})
const opens = menu.requestSerial
loadDefault(menu)
noUserFile(menu)
assertEqual(menu.activeMenu, 'root', 'a summon without a route opens root')
assertEqual(menu.requestSerial, opens, 'a summon without a route is not reopened when the files load')

menu = startMenu()
summon(menu, { menu: 'no-such-menu' })
const missingOpens = menu.requestSerial
loadDefault(menu)
noUserFile(menu)
assertEqual(menu.activeMenu, 'root', 'a route to a missing menu still falls back to root')
assertEqual(menu.requestSerial, missingOpens, 'a route to a missing menu does not reopen root when the files load')
loadUser(menu, '{ "no-such-menu": {"label":"Added later"} }')
assertEqual(menu.requestSerial, missingOpens, 'a route to a missing menu is not opened by a later edit that adds it')

menu = startMenu()
loadDefault(menu)
noUserFile(menu)
summon(menu, { menu: 'personal' })
assertEqual(menu.activeMenu, 'root', 'a summon after startup for a menu nobody defines falls back to root')
loadUser(menu, personalJsonc)
assertEqual(menu.activeMenu, 'root', 'a live edit that adds the menu later does not open it')

menu = startMenu()
summon(menu, { menu: 'personal' })
loadDefault(menu)
menu.setActiveMenu('style', true)
loadUser(menu, personalJsonc)
assertEqual(menu.activeMenu, 'style', 'a pending route does not pull the user out of a menu they opened')

menu = startMenu()
summon(menu, { menu: 'personal' })
loadDefault(menu)
menu.setActiveMenu('style', true)
menu.goBack()
loadUser(menu, personalJsonc)
assertEqual(menu.activeMenu, 'root', 'a pending route does not replace the root the user navigated back to')

menu = startMenu()
summon(menu, { menu: 'personal' })
loadDefault(menu)
menu.setFilter('not')
menu.setFilter('')
loadUser(menu, personalJsonc)
assertEqual(menu.activeMenu, 'root', 'a pending route does not open after the user typed into the menu')

menu = startMenu()
summon(menu, { menu: 'system' })
menu.close()
loadDefault(menu)
noUserFile(menu)
assertEqual(menu.opened, false, 'a route summoned and dismissed during startup stays closed')

menu = startMenu()
summon(menu, { menu: 'system' })
summon(menu, { mode: 'select', prompt: 'Pick', options: ['a', 'b'] })
loadDefault(menu)
noUserFile(menu)
assertEqual(menu.mode, 'select', 'a select prompt that replaced an early route summon is not replaced by it')

menu = startMenu()
loadDefault(menu)
noUserFile(menu)
summon(menu, { menu: 'system' })
assertEqual(menu.activeMenu, 'system', 'a summon after startup opens its route directly')
menu.setActiveMenu('style', true)
loadDefault(menu)
assertEqual(menu.activeMenu, 'style', 'a later reload leaves the menu where the user navigated')
JS
2 changes: 1 addition & 1 deletion test/shell.d/menu-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -863,7 +863,7 @@ assert(
assert(
/function rebuildItemsFromSources\(skipGuards\)[\s\S]*?if \(!skipGuards && root\.defaultMenuSettled && root\.userMenuSettled\) root\.evaluateGuards\(\)/.test(menuQml)
&& /onLoaded: \{ root\.defaultMenuItems = [^}]*root\.defaultMenuSettled = true; root\.rebuildItemsFromSources\(\) \}/.test(menuQml)
&& /onLoadFailed: \{ root\.defaultMenuSettled = true; if \(root\.userMenuSettled\) root\.evaluateGuards\(\) \}/.test(menuQml)
&& /onLoadFailed: \{ root\.defaultMenuSettled = true; root\.rebuildItemsFromSources\(\) \}/.test(menuQml)
&& /onLoaded: \{ root\.userMenuItems = [^}]*root\.userMenuSettled = true; root\.rebuildItemsFromSources\(\) \}/.test(menuQml)
&& /onLoadFailed: \{ root\.userMenuItems = \[\]; root\.userMenuSettled = true; root\.rebuildItemsFromSources\(\) \}/.test(menuQml),
'menu evaluates guards once both menu files have answered, not once per file at startup'
Expand Down
Loading