repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

vim: fixes for neovim and neovide

0f9b35b7692bfdc5814d0ecec78ffd0c598098ae

Oliver Krylow <o.krylow@isp-insoft.de> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (18)

mise.toml

Modified
126 126 run("node", "--test", "wezterm/.pi/skills/modernize/scripts/inspect.test.mjs");
127 127 run("nu", "--no-config-file", "wezterm/tests/wezterm_instances_test.nu");
130 +[tasks.win32-drive-test]
131 +description = "Test the win32-drive skill script against a fixture window (takes over the Windows desktop)"
132 +run = '''
133 +run("powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "pi/agent/skills/win32-drive/scripts/win32-drive.test.ps1");
134 +'''

neovide/config.toml

Modified
1 1 frame = "none"
2 2 tabs = true
3 3 theme = "auto"
4 +fork = true

neovim/init.lua

Modified
70 70 defer_on_naked 'bugabinga.treesitter'
71 71 defer_on_naked 'bugabinga.lsp'
72 72 defer_on_naked 'bugabinga.bigfile'
73 +defer_on_naked 'bugabinga.file_changed'
73 74 defer_on_naked 'bugabinga.editorconfig'
74 75 defer 'bugabinga.sessions'
75 76 defer 'bugabinga.statusline'

neovim/justfile

Modified
29 29 drive:
30 30 nvim --headless --clean -l tests/drive/run.lua
32 +# drive a live neovim and mutate its files from the outside
33 +drive-file-changed:
34 + nvim --headless --clean -l tests/drive/file_changed.lua
36 +# drive a real neovide window over rpc, without touching mouse or keyboard
37 +drive-neovide:
38 + nvim --headless --clean -l tests/drive/neovide.lua
32 40 # run the pi contract tests against a real `pi --mode rpc` child
33 41 test-contract:
34 42 with-env { PIVI_CONTRACT: "1" } { nvim --headless --noplugin -u tests/minimal_init.lua -c "PlenaryBustedDirectory tests/contract {minimal_init = 'tests/minimal_init.lua'}" +q }

neovim/lua/bugabinga/file_changed.lua

Added
new file mode 100644
1 +-- Sane handling of files that change on disk while loaded in neovim.
2 +--
3 +-- Neovim already has `autoread` on by default, but it only ever looks at the
4 +-- filesystem after a shell command, after `:checktime` and on `FocusGained`
5 +-- ( see `:help timestamp` ). So a formatter, a git checkout or an agent can
6 +-- rewrite a file and neovim happily keeps showing stale text for minutes.
7 +--
8 +-- Three layers, from fastest to most reliable:
9 +--
10 +-- 1. `uv.fs_event` on the *parent directory* of every loaded file
11 +-- -> push notification, millisecond latency, but unreliable
12 +-- ( network shares, WSL interop, watcher limits ).
13 +-- 2. a plain repeating timer
14 +-- -> the floor. always works, independent of terminal focus reporting
15 +-- and of `updatetime`.
16 +-- 3. `FocusGained` and friends
17 +-- -> zero latency for the common "alt tab back into neovim" case.
18 +--
19 +-- All three funnel into `:checktime`, which decides nothing by itself. The
20 +-- actual policy lives in the `FileChangedShell` handler below.
21 +--
22 +-- Note on the directory watch: tools write files by creating a temporary file
23 +-- and renaming it over the target. That replaces the inode, so an `fs_event`
24 +-- registered on the *file* goes deaf after the first write. Watching the
25 +-- containing directory survives this.
27 +local auto = require 'std.auto'
28 +local uv = vim.uv
30 +-- reading a file again must stay undoable, also for big files.
31 +-- see `:help 'undoreload'`
32 +vim.opt.undoreload = 100000
33 +-- global value. plugins may still set a local one, that is their business.
34 +vim.opt.autoread = true
36 +--[[ POLICY ]]
38 +-- `FileChangedShell` only fires for the cases neovim can not decide on its
39 +-- own. A clean buffer whose file changed is reloaded silently by `autoread`
40 +-- and never reaches this handler.
41 +--
42 +-- Defining this autocommand suppresses the built in W11/W12/W16/E211 warnings
43 +-- and dialogs entirely, so it owns the whole user experience.
45 +--- remembers which buffers we already complained about, to not repeat
46 +--- ourselves on every check. keyed by buffer number.
47 +--- deliberately not a buffer local variable: `FileChangedShell` runs with the
48 +--- buffer list locked.
49 +---@type table<integer, string>
50 +local warned = {}
52 +local relative_name = function ( path ) return vim.fn.fnamemodify( path, ':~:.' ) end
54 +local warn_once = function ( buffer, reason, message )
55 + if warned[buffer] == reason then return end
56 + warned[buffer] = reason
57 + vim.notify( message, vim.log.levels.WARN, { title = 'file changed', } )
58 +end
60 +auto 'file_changed_policy' {
61 + {
62 + description = 'decide what to do with a file that changed outside of neovim',
63 + events = 'FileChangedShell',
64 + command = function ( event )
65 + local reason = vim.v.fcs_reason
66 + local name = relative_name( event.file )
68 + if reason == 'mode' or reason == 'time' then
69 + -- permissions or timestamp only, contents are identical.
70 + -- typical for version control checkouts. nothing to lose.
71 + vim.v.fcs_choice = 'reload'
72 + elseif reason == 'changed' then
73 + -- contents differ and the buffer is clean.
74 + -- 'edit' instead of 'reload' so that 'fileformat', 'fileencoding' and
75 + -- 'binary' are detected again. a formatter or a `dos2unix` run may
76 + -- have changed them.
77 + vim.v.fcs_choice = 'edit'
78 + elseif reason == 'conflict' then
79 + -- changed on disk AND in the buffer. never pick a winner.
80 + vim.v.fcs_choice = ''
81 + warn_once( event.buf, reason,
82 + ( '`%s` changed on disk **and** in the buffer.\n' ..
83 + '`:DiffDisk` compare · `:e!` take disk · `:w!` take buffer' ):format( name ) )
84 + elseif reason == 'deleted' then
85 + -- keep the text. it may be the only copy left.
86 + vim.v.fcs_choice = ''
87 + warn_once( event.buf, reason, ( '`%s` is gone from disk.' ):format( name ) )
88 + end
89 + end,
90 + },
91 + {
92 + description = 'report a file that was reloaded from disk',
93 + events = 'FileChangedShellPost',
94 + command = function ( event )
95 + warned[event.buf] = nil
96 + if vim.wo.diff then vim.cmd.diffupdate() end
97 + vim.notify( ( 'reloaded `%s`' ):format( relative_name( event.file ) ),
98 + vim.log.levels.INFO, { title = 'file changed', } )
99 + end,
100 + },
102 + -- writing, or reading the file again ( `:e!`, `:edit` ), means buffer and
103 + -- disk agree again. without this the next conflict would be swallowed by
104 + -- the latch of the previous one.
105 + description = 'forget complaints once the buffer is in sync again',
106 + events = { 'BufWritePost', 'BufReadPost', 'BufWipeout', },
107 + command = function ( event ) warned[event.buf] = nil end,
108 + },
111 +--[[ BUFFERS ]]
113 +--- the file a buffer is backed by, or nil if it is not a plain file buffer.
114 +---@param buffer integer
115 +---@return string? path, string? directory, string? file
116 +local file_of = function ( buffer )
117 + if not vim.api.nvim_buf_is_valid( buffer ) then return end
118 + if vim.bo[buffer].buftype ~= '' then return end
119 + -- reloading these costs more than the staleness does
120 + if vim.bo[buffer].filetype == 'bigfile' then return end
122 + local name = vim.api.nvim_buf_get_name( buffer )
123 + -- `oil://`, `fugitive://`, ... are not files
124 + if name == '' or name:match '^%a[%w+.-]*://' then return end
126 + local path = vim.fs.normalize( vim.fn.fnamemodify( name, ':p' ) )
127 + return path, vim.fs.dirname( path ), vim.fs.basename( path )
128 +end
130 +--[[ TRIGGERS ]]
132 +-- Everything funnels through one debounced, quiescence gated `:checktime`.
134 +-- The gate matters: a lot of tools truncate a file and only then write it,
135 +-- and on windows the gap between the two can be hundreds of milliseconds.
136 +-- Reading in that window loads an empty file, the cursor gets clamped to
137 +-- line 1, and the next read restores the contents but no longer knows where
138 +-- the cursor was. So wait until size and mtime of every watched file stopped
139 +-- moving before looking at them.
141 +local settle_delay = 150
142 +local settle_attempts = 8
144 +local timer = assert( uv.new_timer() )
145 +---@type table<string, string>?
146 +local previous_fingerprint = nil
147 +local attempt = 0
149 +--- size and modification time of every file a loaded buffer is backed by.
150 +--- The second return value marks a file that is almost certainly half written:
151 +--- it is empty while its buffer still holds text. Waiting for the fingerprint
152 +--- to stop moving does not catch this, because a truncated file sits there
153 +--- perfectly stable until the writer gets around to producing its bytes.
154 +---@return table<string, string> fingerprints, boolean half_written
155 +local fingerprint = function ()
156 + local prints = {}
157 + local half_written = false
158 + for _, buffer in ipairs( vim.api.nvim_list_bufs() ) do
159 + if vim.api.nvim_buf_is_loaded( buffer ) then
160 + local path = file_of( buffer )
161 + if path then
162 + local stat = uv.fs_stat( path )
163 + prints[path] = stat
164 + and ( '%d:%d:%d' ):format( stat.size, stat.mtime.sec, stat.mtime.nsec )
165 + or 'gone'
166 + if stat and stat.size == 0 and vim.api.nvim_buf_line_count( buffer ) > 1 then
167 + half_written = true
168 + end
169 + end
170 + end
171 + end
172 + return prints, half_written
173 +end
175 +local settle
177 +local function arm ( delay )
178 + timer:stop()
179 + timer:start( delay, 0, vim.schedule_wrap( settle ) )
180 +end
182 +settle = function ()
183 + -- the reload is postponed by neovim until it is harmless anyway, but
184 + -- checking while typing or selecting only produces noise.
185 + if vim.fn.getcmdwintype() ~= '' then return end -- E11
186 + if vim.api.nvim_get_mode().mode ~= 'n' then return end
188 + local current, half_written = fingerprint()
189 + local moved = not vim.deep_equal( previous_fingerprint, current )
190 + if attempt < settle_attempts and ( moved or half_written ) then
191 + -- somebody is still writing. look again in a moment.
192 + -- after `settle_attempts` we give up and read whatever is there: the file
193 + -- may really have been emptied on purpose.
194 + previous_fingerprint = current
195 + attempt = attempt + 1
196 + arm( settle_delay )
197 + return
198 + end
200 + previous_fingerprint = nil
201 + attempt = 0
202 + pcall( vim.cmd.checktime )
203 +end
205 +local check = function ( delay )
206 + previous_fingerprint = nil
207 + attempt = 0
208 + arm( delay )
209 +end
211 +auto 'file_changed_triggers' {
212 + description = 'check timestamps whenever attention returns to neovim',
213 + events = { 'FocusGained', 'BufEnter', 'TermLeave', 'TermClose', 'VimResume', 'InsertLeave', },
214 + command = function () check( 50 ) end,
217 +-- The floor. Deliberately not `CursorHold`: that event is edge triggered, it
218 +-- fires once per idle period and never again until the cursor moves. Sitting
219 +-- still and reading is exactly when an external change would be missed.
220 +local poll_interval = 2000
221 +local poll = assert( uv.new_timer() )
222 +poll:start( poll_interval, poll_interval, vim.schedule_wrap( function ()
223 + -- do not interrupt a debounce that is already running
224 + if timer:is_active() then return end
225 + check( 0 )
226 +end ) )
228 +--[[ DIRECTORY WATCHERS ]]
230 +-- one `uv_fs_event_t` per directory, shared by all buffers in it.
231 +local max_directories = 64
233 +---@type table<string, { handle: uv.uv_fs_event_t, files: table<string, true> }>
234 +local watchers = {}
236 +--- plain lua, no `vim.*`: this also runs inside libuv callbacks.
237 +local basename = function ( path ) return path:match '[^/\\]*$' end
239 +local watch = function ( buffer )
240 + local _, directory, file = file_of( buffer )
241 + if not directory or not file then return end
243 + local watcher = watchers[directory]
244 + if watcher then
245 + watcher.files[file] = true
246 + return
247 + end
249 + if vim.tbl_count( watchers ) >= max_directories then return end
251 + local handle = assert( uv.new_fs_event() )
252 + local _, error_message = handle:start( directory, {}, function ( error, changed )
253 + if error then return end
254 + local current = watchers[directory]
255 + if not current then return end
256 + -- `changed` is nil on some platforms. then we can not tell which file it
257 + -- was and have to check them all, which `:checktime` does anyway.
258 + if changed and not current.files[basename( changed )] then return end
259 + check( 100 )
260 + end )
262 + if error_message then
263 + -- unwatchable directory ( network share, permissions, ... ).
264 + -- the poll timer still covers this buffer.
265 + handle:close()
266 + return
267 + end
269 + watchers[directory] = { handle = handle, files = { [file] = true, }, }
270 +end
272 +local unwatch = function ( buffer )
273 + local _, directory, file = file_of( buffer )
274 + if not directory or not file then return end
276 + local watcher = watchers[directory]
277 + if not watcher then return end
279 + watcher.files[file] = nil
280 + if next( watcher.files ) == nil then
281 + watcher.handle:stop()
282 + watcher.handle:close()
283 + watchers[directory] = nil
284 + end
285 +end
287 +auto 'file_changed_watchers' {
289 + description = 'watch the directory of every file backed buffer',
290 + events = { 'BufReadPost', 'BufNewFile', 'BufFilePost', 'BufWritePost', },
291 + command = function ( event ) watch( event.buf ) end,
292 + },
294 + description = 'release the directory watcher when a buffer goes away',
295 + events = { 'BufWipeout', 'BufFilePre', },
296 + command = function ( event ) unwatch( event.buf ) end,
297 + },
300 +-- buffers that were already loaded before this module ran
301 +for _, buffer in ipairs( vim.api.nvim_list_bufs() ) do
302 + if vim.api.nvim_buf_is_loaded( buffer ) then watch( buffer ) end
303 +end
305 +--[[ COMMANDS ]]
307 +vim.api.nvim_create_user_command( 'DiffDisk', function ()
308 + local filetype = vim.bo.filetype
309 + vim.cmd 'vertical new'
310 + vim.opt_local.buftype = 'nofile'
311 + vim.opt_local.bufhidden = 'wipe'
312 + vim.opt_local.swapfile = false
313 + vim.cmd 'read ++edit #'
314 + vim.cmd '0d_'
315 + vim.bo.filetype = filetype
316 + vim.cmd 'diffthis'
317 + vim.cmd 'wincmd p'
318 + vim.cmd 'diffthis'
319 +end, { desc = 'diff the current buffer against the file on disk', } )

neovim/lua/bugabinga/options/behaviour.lua

Modified
29 29 local restore_cursor_handler = function(ev)
30 + -- BufReadPost fires on every read of this buffer, not just the first one.
31 + -- Reloading a file that changed on disk ( `:checktime`, 'autoread' ) reads
32 + -- it again with READ_NEW and therefore triggers this too.
33 + -- Restoring the last known position is a once per buffer action, so latch
34 + -- it. Buffer local variables survive a reload, the buffer object stays the
35 + -- same and only its lines are replaced.
36 + if vim.b[ev.buf].cursor_restored then return end
37 + vim.b[ev.buf].cursor_restored = true
30 39 if dbg.get() then
31 40 vim.notify(string.format('RCP stage1: buf=%d cursor_line=%d mark_line=%d',
32 41 ev.buf, vim.fn.line('.'), vim.fn.line([['"]])), vim.log.levels.DEBUG)

neovim/lua/bugabinga/options/core.lua

Modified
32 32 -- enable persistent undo. save undo history across neovim instances
33 33 vim.opt.undofile = true
35 --- How many milliseconds must pass before neovim decides I was "idle"
36 -vim.opt.updatetime = 50
35 +-- How many milliseconds must pass before neovim decides I was "idle".
36 +-- Drives the swap file flush and the CursorHold event. Below ~100ms nothing
37 +-- feels faster to a human, but every CursorHold consumer ( lsp document
38 +-- highlight, code action signs ) fires another round of requests.
39 +vim.opt.updatetime = 150
37 40 -- How long to wait between key sequences in order to chain them. e.g. <LEADER>b
38 41 vim.opt.timeoutlen = 250
182 185 -- pop up menu height
183 186 vim.opt.pumheight = 10
185 --- use this in various places for consistent border style
188 +-- use this in various places for consistent border style.
189 +-- plain box drawing ( U+2500 block ) on purpose: the prettier sextants from
190 +-- "Symbols for Legacy Computing" ( U+1FBxx ) are in almost no font. wezterm
191 +-- draws them itself, so they looked fine there, but every other frontend
192 +-- ( neovide, most terminals ) renders them as tofu boxes.
186 193 vim.g.border_style = {
187 - { '🬷', 'FloatBorderCorner' }, -- top left
188 - { '▔', 'FloatBorder' }, -- top
189 - { '🬲', 'FloatBorderCorner' }, -- top right
190 - { '🮈', 'FloatBorder' }, -- right
191 - { '🬕', 'FloatBorderCorner' }, -- bottom right
192 - { '▁', 'FloatBorder' }, -- bottom
193 - { '🬨', 'FloatBorderCorner' }, -- bottom left
194 - { '▍', 'FloatBorder' }, -- left
194 + { '┌', 'FloatBorderCorner' }, -- top left
195 + { '─', 'FloatBorder' }, -- top
196 + { '┐', 'FloatBorderCorner' }, -- top right
197 + { '│', 'FloatBorder' }, -- right
198 + { '┘', 'FloatBorderCorner' }, -- bottom right
199 + { '─', 'FloatBorder' }, -- bottom
200 + { '└', 'FloatBorderCorner' }, -- bottom left
201 + { '│', 'FloatBorder' }, -- left
197 204 -- hide the mode indicator in status

neovim/lua/bugabinga/options/neovide.lua

Modified
1 1 if vim.g.neovide then
2 + -- Neovide has no bundled fallback font, unlike wezterm, which also draws
3 + -- box and block glyphs itself instead of asking the font for them.
4 + -- So the chain has to be spelled out, and every link earns its place:
5 + -- JetBrains Mono the text, same as wezterm uses
6 + -- Symbols Nerd Font Mono every `nf-*` icon in `std.icon`
7 + -- Cascadia Code braille ( the spinner ) and block elements
8 + -- Segoe UI Symbol ↴ ⦿ 🔭 and friends, win32 only
9 + -- DejaVu Sans Mono the same job on linux
10 + -- Missing families are skipped, so listing both platforms is harmless.
11 + local font_size = vim.fn.hostname() == 'x230' and 11 or 13
12 + vim.opt.guifont = ( '%s:h%d' ):format( table.concat( {
13 + 'JetBrains Mono',
14 + 'Symbols Nerd Font Mono',
15 + 'Cascadia Code',
16 + 'Segoe UI Symbol',
17 + 'DejaVu Sans Mono',
18 + }, ',' ), font_size )
2 20 vim.opt.pumblend = 15
3 21 vim.opt.winblend = 15
4 22 vim.g.neovide_profiler = false

neovim/lua/std/icon.lua

Modified
4 4 return {
5 5 ['function'] = '󰡱',
6 6 ['local'] = '󱥕',
7 7 ['table'] = '',
8 8 arrow_left = '',
9 9 arrow_right = '',
10 - backspace_key = '',
10 + backspace_key = '󰌍',
11 11 block = '█',
12 12 branch = '',
13 13 carriage_return = '␍',
81 81 quot_right = '"',
82 82 reference = '󰈇 ',
83 83 replace = '',
84 - return_key = '',
84 + return_key = '󰌑',
85 85 running = ' ',
86 86 select = '󰒉',
87 87 slant_left = '▟',
90 90 space = '·',
91 91 space_key = '󱁐',
92 92 spelling = '󰓆',
93 - start = '',
94 93 struct = ' ',
95 94 subversion = '󰳗',
96 95 tab = '󰌒',
97 - tab_key = '',
96 + tab_key = '󰌒',
98 97 telescope = '🔭',
99 98 terminal = '',
100 99 text = ' ',

neovim/tests/bugabinga/cursor_restore_spec.lua

Modified
99 99 assert.equal(1, #stage2)
100 100 assert.equal(buf, stage2[1].buf)
103 + it('should only restore once per buffer, not on every read', function()
104 + local buf = vim.api.nvim_create_buf(false, false)
105 + make_buffer_with_lines(buf, { 'line 1', 'line 2', 'line 3', 'line 4', 'line 5' })
106 + set_shada_mark(buf, 3, 5)
107 + vim.api.nvim_set_current_buf(buf)
108 + vim.cmd.normal { 'gg' }
110 + auto 'restore_cursor_position' {
111 + events = 'BufReadPost',
112 + command = restore_cursor_handler,
115 + -- first read: opening the file
116 + vim.api.nvim_exec_autocmds('BufReadPost', { buf = buf })
117 + assert.is_true(vim.b[buf].cursor_restored)
118 + pcall(vim.api.nvim_del_augroup_by_name, 'restore_cursor_stage2')
120 + -- second read: the file changed on disk and was reloaded.
121 + -- must not queue another jump to the shada mark.
122 + vim.cmd.normal { 'gg' }
123 + vim.api.nvim_exec_autocmds('BufReadPost', { buf = buf })
124 + local ok, stage2 = pcall(vim.api.nvim_get_autocmds, { group = 'restore_cursor_stage2' })
125 + if ok then
126 + assert.equal(0, #stage2)
127 + end
128 + end)
104 131 describe('BufWinEnter stage', function()

neovim/tests/drive/file_changed.lua

Added
new file mode 100644
1 +---@diagnostic disable: need-check-nil, undefined-field, param-type-mismatch, assign-type-mismatch
2 +-- Drives a live Neovim over RPC and asserts how it reacts to files that
3 +-- change on disk while they are loaded.
4 +-- Run with: just drive-file-changed
5 +--
6 +-- This can not be a plenary spec: the whole feature is about timers, libuv
7 +-- filesystem events and neovim postponing reloads to a safe moment. It only
8 +-- means anything in a real, running neovim that is mutated from the outside
9 +-- by a real, separate process.
11 +local ADDRESS = '127.0.0.1:' .. tostring( 6400 + math.random( 1, 180 ) )
13 +local server = vim.system( {
14 + vim.v.progpath,
15 + '--headless',
16 + '--noplugin',
17 + '-u', 'tests/minimal_init.lua',
18 + '--listen', ADDRESS,
19 +}, { stdout = false, stderr = false, } )
21 +local channel
22 +local connected = vim.wait( 20000, function ()
23 + local ok, value = pcall( vim.fn.sockconnect, 'tcp', ADDRESS, { rpc = true, } )
24 + if ok and value ~= 0 then
25 + channel = value
26 + return true
27 + end
28 + return false
29 +end, 100 )
31 +if not connected then
32 + io.stderr:write( 'cannot reach the driven neovim at ' .. ADDRESS .. '\n' )
33 + server:kill 'sigterm'
34 + os.exit( 1 )
35 +end
37 +local remote = function ( code, arguments )
38 + return vim.rpcrequest( channel, 'nvim_exec_lua', code, arguments or {} )
39 +end
41 +local failures = {}
43 +local scenario = function ( name, body )
44 + local ok, failure = pcall( body )
45 + if ok then
46 + print( 'ok ' .. name )
47 + else
48 + failures[#failures + 1] = name
49 + print( 'FAIL ' .. name .. ': ' .. tostring( failure ) )
50 + end
51 +end
53 +local expect = function ( condition, message )
54 + if not condition then error( message or 'expectation failed', 2 ) end
55 +end
57 +--- polls the driven neovim until `code` returns a truthy value
58 +local until_remote = function ( code, timeout )
59 + return vim.wait( timeout or 8000, function ()
60 + local answer = remote( code )
61 + return answer ~= nil and answer ~= false and answer ~= vim.NIL
62 + end, 100 )
63 +end
65 +--[[ FIXTURE ]]
67 +local directory = vim.fn.tempname()
68 +vim.fn.mkdir( directory, 'p' )
69 +local target = directory .. '/watched.txt'
71 +--- overwrites the file from this process, the way any other tool would
72 +local write_file = function ( first, last )
73 + local handle = assert( io.open( target, 'w' ) )
74 + for number = first, last do handle:write( number .. '\n' ) end
75 + handle:close()
76 +end
78 +local read_file = function ()
79 + local handle = assert( io.open( target, 'r' ) )
80 + local content = handle:read 'a'
81 + handle:close()
82 + return content
83 +end
85 +write_file( 1, 20 )
87 +remote( [[
88 + local path = ...
89 + require 'bugabinga.file_changed'
91 + _G.DRIVE = { reloads = 0, notifications = {}, }
92 + vim.api.nvim_create_autocmd( 'FileChangedShellPost', {
93 + callback = function() _G.DRIVE.reloads = _G.DRIVE.reloads + 1 end,
94 + } )
95 + local original = vim.notify
96 + vim.notify = function( message, ... )
97 + table.insert( _G.DRIVE.notifications, message )
98 + return original( message, ... )
99 + end
101 + vim.cmd.edit( vim.fn.fnameescape( path ) )
102 + vim.api.nvim_win_set_cursor( 0, { 15, 0 } )
103 + return true
104 +]], { target, } )
106 +--- every scenario starts from the same place, so that one failure does not
107 +--- drag the next one down with it
108 +local reset = function ()
109 + remote [[
110 + _G.DRIVE.reloads = 0
111 + _G.DRIVE.notifications = {}
112 + pcall( vim.api.nvim_win_set_cursor, 0, { 15, 0 } )
113 + return true
114 + ]]
115 +end
117 +local state = function ()
118 + return remote [[
119 + return {
120 + reloads = _G.DRIVE.reloads,
121 + notifications = _G.DRIVE.notifications,
122 + line = vim.api.nvim_win_get_cursor( 0 )[1],
123 + text = vim.fn.getline '.',
124 + lines = vim.api.nvim_buf_line_count( 0 ),
125 + modified = vim.bo.modified,
127 + ]]
128 +end
130 +--[[ SCENARIOS ]]
132 +scenario( 'a changed file is reloaded without touching the cursor', function ()
133 + reset()
134 + write_file( 101, 120 )
136 + local reloaded = until_remote [[ return _G.DRIVE.reloads > 0 ]]
137 + expect( reloaded, 'the change was never noticed' )
139 + local now = state()
140 + expect( now.text == '115', 'expected line 115, got ' .. tostring( now.text ) )
141 + expect( now.line == 15, 'the cursor moved to line ' .. tostring( now.line ) )
142 +end )
144 +scenario( 'a file that is truncated first and written later is read only once it settled', function ()
145 + reset()
146 + -- the shell redirect plus slow writer case: truncate now, content later.
147 + local handle = assert( io.open( target, 'w' ) )
148 + handle:close()
149 + vim.uv.sleep( 400 )
150 + write_file( 201, 220 )
152 + local reloaded = until_remote [[ return _G.DRIVE.reloads > 0 ]]
153 + expect( reloaded, 'the change was never noticed' )
154 + -- give a mistaken second reload the chance to show up
155 + vim.uv.sleep( 3000 )
157 + local now = state()
158 + expect( now.reloads == 1, 'expected exactly one reload, got ' .. tostring( now.reloads ) )
159 + expect( now.lines == 20, 'the buffer holds ' .. tostring( now.lines ) .. ' lines, expected 20' )
160 + expect( now.text == '215', 'expected line 215, got ' .. tostring( now.text ) )
161 + expect( now.line == 15, 'the cursor moved to line ' .. tostring( now.line ) )
162 +end )
164 +scenario( 'a file replaced by rename is still followed', function ()
165 + reset()
166 + local temporary = target .. '.tmp'
167 + local handle = assert( io.open( temporary, 'w' ) )
168 + for number = 301, 320 do handle:write( number .. '\n' ) end
169 + handle:close()
170 + assert( os.remove( target ) )
171 + assert( os.rename( temporary, target ) )
173 + local reloaded = until_remote [[ return _G.DRIVE.reloads > 0 ]]
174 + expect( reloaded, 'the watcher did not survive the inode swap' )
176 + local now = state()
177 + expect( now.text == '315', 'expected line 315, got ' .. tostring( now.text ) )
178 + expect( now.line == 15, 'the cursor moved to line ' .. tostring( now.line ) )
179 +end )
181 +scenario( 'an unchanged file is never reloaded', function ()
182 + reset()
183 + vim.uv.sleep( 5000 ) -- several rounds of the fallback poll
185 + local now = state()
186 + expect( now.reloads == 0, 'reloaded ' .. tostring( now.reloads ) .. ' times without a change' )
187 + expect( #now.notifications == 0, 'notified without a change' )
188 +end )
190 +scenario( 'local edits are never overwritten by a change on disk', function ()
191 + reset()
192 + remote [[
193 + vim.api.nvim_buf_set_lines( 0, 14, 15, false, { 'MY UNSAVED EDIT' } )
194 + return true
195 + ]]
196 + write_file( 401, 420 )
197 + vim.uv.sleep( 4000 )
199 + local now = state()
200 + expect( now.reloads == 0, 'the buffer was reloaded over unsaved changes' )
201 + expect( now.text == 'MY UNSAVED EDIT', 'lost the local edit: ' .. tostring( now.text ) )
202 + expect( now.modified, 'the buffer is no longer marked modified' )
203 + expect( #now.notifications == 1,
204 + 'expected exactly one warning, got ' .. tostring( #now.notifications ) )
205 + expect( now.notifications[1]:find( 'DiffDisk', 1, true ) ~= nil,
206 + 'the warning does not offer a way out: ' .. tostring( now.notifications[1] ) )
207 +end )
209 +scenario( 'a conflict is reported again after taking the version from disk', function ()
210 + reset()
211 + remote [[ vim.cmd 'edit!' ; return true ]]
212 + remote [[
213 + vim.api.nvim_buf_set_lines( 0, 14, 15, false, { 'ANOTHER UNSAVED EDIT' } )
214 + return true
215 + ]]
216 + write_file( 451, 470 )
217 + vim.uv.sleep( 4000 )
219 + local now = state()
220 + expect( now.reloads == 0, 'the buffer was reloaded over unsaved changes' )
221 + expect( #now.notifications == 1,
222 + 'the warning was swallowed by the previous one, got ' .. tostring( #now.notifications ) )
223 +end )
225 +scenario( 'the buffer survives the file being deleted', function ()
226 + reset()
227 + assert( os.remove( target ) )
228 + vim.uv.sleep( 4000 )
230 + local now = state()
231 + expect( now.text == 'ANOTHER UNSAVED EDIT', 'the text was lost with the file' )
232 + expect( #now.notifications == 1,
233 + 'expected exactly one warning, got ' .. tostring( #now.notifications ) )
234 + expect( now.notifications[1]:find( 'gone from disk', 1, true ) ~= nil,
235 + 'unexpected warning: ' .. tostring( now.notifications[1] ) )
236 +end )
238 +scenario( 'writing the buffer resolves the conflict for good', function ()
239 + reset()
240 + remote [[ vim.cmd.write() ; return true ]]
241 + vim.uv.sleep( 4000 )
243 + local now = state()
244 + expect( not now.modified, 'the buffer is still modified after writing' )
245 + expect( now.reloads == 0, 'writing caused a reload' )
246 + expect( #now.notifications == 0, 'writing caused a warning' )
247 + expect( read_file():find( 'ANOTHER UNSAVED EDIT', 1, true ) ~= nil, 'the file on disk is wrong' )
248 +end )
250 +scenario( 'DiffDisk shows the buffer against the file on disk', function ()
251 + reset()
252 + write_file( 501, 520 )
253 + expect( until_remote [[ return _G.DRIVE.reloads > 0 ]], 'the change was never noticed' )
255 + local diffed = remote [[
256 + vim.api.nvim_buf_set_lines( 0, 0, 1, false, { 'ONLY IN THE BUFFER' } )
257 + vim.cmd 'DiffDisk'
258 + -- `:DiffDisk` leaves the cursor in the original window
259 + local scratch = vim.api.nvim_get_current_buf()
260 + local in_diff = 0
261 + local disk
262 + for _, window in ipairs( vim.api.nvim_tabpage_list_wins( 0 ) ) do
263 + if vim.wo[window].diff then in_diff = in_diff + 1 end
264 + local buffer = vim.api.nvim_win_get_buf( window )
265 + if buffer ~= scratch and vim.bo[buffer].buftype == 'nofile' then
266 + disk = vim.api.nvim_buf_get_lines( buffer, 0, 1, false )[1]
267 + end
268 + end
269 + vim.cmd 'only'
270 + vim.cmd 'silent! edit!'
271 + return { in_diff = in_diff, disk = disk }
272 + ]]
274 + expect( diffed.in_diff == 2, 'expected two windows in diff mode, got ' .. tostring( diffed.in_diff ) )
275 + expect( diffed.disk == '501', 'the scratch window does not hold the file on disk: ' .. tostring( diffed.disk ) )
276 +end )
278 +--[[ TEARDOWN ]]
280 +pcall( vim.fn.chanclose, channel )
281 +server:kill 'sigterm'
282 +vim.fn.delete( directory, 'rf' )
284 +if #failures > 0 then
285 + print( tostring( #failures ) .. ' scenario(s) failed' )
286 + os.exit( 1 )
287 +end
289 +print 'all file change scenarios passed'

neovim/tests/drive/neovide.lua

Added
new file mode 100644
1 +---@diagnostic disable: need-check-nil, undefined-field, param-type-mismatch, assign-type-mismatch
2 +-- The checks that a headless neovim can not answer: does this actually behave
3 +-- when a real GUI is painting it.
4 +-- Run with: just drive-neovide
5 +--
6 +-- Everything is driven over the RPC socket of the neovim that neovide is
7 +-- attached to. No mouse, no synthetic keystrokes, no foreground window
8 +-- stealing, so it does not fight the person sitting in front of the machine.
10 +if vim.fn.executable 'neovide' == 0 then
11 + print 'neovide is not installed, skipping'
12 + os.exit( 0 )
13 +end
15 +local ADDRESS = '127.0.0.1:' .. tostring( 6200 + math.random( 1, 180 ) )
17 +local fixture = vim.fn.tempname()
18 +vim.fn.mkdir( fixture, 'p' )
19 +fixture = fixture .. '/watched.txt'
20 +vim.fn.writefile( vim.fn.range( 1, 40 ), fixture )
22 +-- the real configuration on purpose: this checks what a person actually sees,
23 +-- including the notification plugin. `-i NONE` keeps it out of the shada file.
24 +local server = vim.system( {
25 + vim.v.progpath,
26 + '--headless',
27 + '-i', 'NONE',
28 + '--listen', ADDRESS,
29 + fixture,
30 +}, { stdout = false, stderr = false, } )
32 +local channel
33 +local connected = vim.wait( 20000, function ()
34 + local ok, value = pcall( vim.fn.sockconnect, 'tcp', ADDRESS, { rpc = true, } )
35 + if ok and value ~= 0 then
36 + channel = value
37 + return true
38 + end
39 + return false
40 +end, 100 )
42 +if not connected then
43 + io.stderr:write( 'cannot reach the driven neovim at ' .. ADDRESS .. '\n' )
44 + server:kill 'sigterm'
45 + os.exit( 1 )
46 +end
48 +local remote = function ( code, arguments )
49 + return vim.rpcrequest( channel, 'nvim_exec_lua', code, arguments or {} )
50 +end
52 +remote( [[
53 + require 'bugabinga.file_changed'
54 + return package.loaded['bugabinga.file_changed'] ~= nil
55 +]] )
57 +-- `--no-fork` keeps the window in the process we spawned, so it can be
58 +-- cleaned up again
59 +local gui = vim.system( { 'neovide', '--no-fork', '--server', ADDRESS, },
60 + { stdout = false, stderr = false, } )
62 +local attached = vim.wait( 30000, function ()
63 + return remote [[ return #vim.api.nvim_list_uis() > 0 ]] == true
64 +end, 200 )
66 +local finish = function ( code )
67 + pcall( vim.fn.chanclose, channel )
68 + pcall( function () server:kill 'sigterm' end )
69 + pcall( function () gui:kill 'sigterm' end )
70 + vim.fn.delete( vim.fs.dirname( fixture ), 'rf' )
71 + os.exit( code )
72 +end
74 +if not attached then
75 + io.stderr:write( 'neovide never attached to ' .. ADDRESS .. '\n' )
76 + finish( 1 )
77 +end
79 +local checks, failures = {}, 0
81 +local check = function ( name, body )
82 + local ok, failure = pcall( body )
83 + checks[#checks + 1] = ( ok and 'ok ' or 'FAIL ' ) .. name
84 + if not ok then
85 + failures = failures + 1
86 + checks[#checks] = checks[#checks] .. ': ' .. tostring( failure )
87 + end
88 +end
90 +local expect = function ( condition, message )
91 + if not condition then error( message or 'expectation failed', 2 ) end
92 +end
94 +local target = fixture
96 +--- binary mode, so lua does not turn every \n into \r\n behind our back
97 +local write_file = function ( first, last )
98 + local handle = assert( io.open( target, 'wb' ) )
99 + for number = first, last do handle:write( number .. '\n' ) end
100 + handle:close()
101 +end
103 +--- every floating window the attached UI is currently painting
104 +local floats = function ()
105 + return remote [[
106 + local found = {}
107 + for _, window in ipairs( vim.api.nvim_list_wins() ) do
108 + local config = vim.api.nvim_win_get_config( window )
109 + if config.relative ~= '' then
110 + local buffer = vim.api.nvim_win_get_buf( window )
111 + table.insert( found, {
112 + width = config.width,
113 + height = config.height,
114 + filetype = vim.bo[buffer].filetype,
115 + text = table.concat( vim.api.nvim_buf_get_lines( buffer, 0, -1, false ), '\n' ),
116 + } )
117 + end
118 + end
119 + return found
120 + ]]
121 +end
123 +-- start from a clean layout, so a previous run can not poison this one
124 +remote [[
125 + vim.cmd 'silent! diffoff!'
126 + vim.cmd 'silent! only'
127 + local current = vim.api.nvim_get_current_buf()
128 + for _, buffer in ipairs( vim.api.nvim_list_bufs() ) do
129 + if buffer ~= current and vim.api.nvim_buf_get_name( buffer ) == '' then
130 + pcall( vim.api.nvim_buf_delete, buffer, { force = true } )
131 + end
132 + end
133 + vim.cmd 'silent! edit!'
134 + return true
137 +remote [[
138 + _G.T = { reloads = 0, notes = {}, focus = {} }
139 + vim.api.nvim_create_autocmd( 'FileChangedShellPost', {
140 + callback = function() _G.T.reloads = _G.T.reloads + 1 end,
141 + } )
142 + vim.api.nvim_create_autocmd( { 'FocusGained', 'FocusLost' }, {
143 + callback = function( event ) table.insert( _G.T.focus, event.event ) end,
144 + } )
145 + -- the server outlives this script, so only ever wrap the real notify once
146 + _G.T_NOTIFY = _G.T_NOTIFY or vim.notify
147 + vim.notify = function( message, ... )
148 + table.insert( _G.T.notes, message )
149 + return _G.T_NOTIFY( message, ... )
150 + end
151 + return true
154 +local reset = function ()
155 + remote [[
156 + _G.T.reloads = 0
157 + _G.T.notes = {}
158 + pcall( vim.api.nvim_win_set_cursor, 0, { 15, 0 } )
159 + return true
160 + ]]
161 +end
163 +local state = function ()
164 + return remote [[
165 + return {
166 + reloads = _G.T.reloads,
167 + notes = _G.T.notes,
168 + focus = _G.T.focus,
169 + cursor = vim.api.nvim_win_get_cursor( 0 )[1],
170 + text = vim.fn.getline '.',
171 + first = vim.fn.getline( 1 ),
172 + lines = vim.api.nvim_buf_line_count( 0 ),
173 + modified = vim.bo.modified,
174 + mode = vim.api.nvim_get_mode().mode,
176 + ]]
177 +end
179 +local await_reload = function ()
180 + return vim.wait( 8000, function ()
181 + return remote [[ return _G.T.reloads > 0 ]] == true
182 + end, 100 )
183 +end
185 +--[[ CHECKS ]]
187 +check( 'a real neovide UI is attached', function ()
188 + local uis = remote [[ return vim.api.nvim_list_uis() ]]
189 + expect( #uis == 1, 'expected one attached UI, got ' .. tostring( #uis ) )
190 + expect( uis[1].width > 0 and uis[1].height > 0, 'the UI has no grid' )
191 +end )
193 +check( 'a change on disk reloads and the cursor stays put', function ()
194 + reset()
195 + write_file( 101, 140 )
196 + expect( await_reload(), 'the change was never noticed' )
198 + local now = state()
199 + expect( now.text == '115', 'expected 115 on the cursor line, got ' .. vim.inspect( now.text ) )
200 + expect( now.cursor == 15, 'the cursor moved to line ' .. tostring( now.cursor ) )
201 + expect( #now.notes == 1, 'expected one notification, got ' .. tostring( #now.notes ) )
202 +end )
204 +check( 'the reload notification is a real floating window in the UI', function ()
205 + reset()
206 + write_file( 151, 190 )
207 + expect( await_reload(), 'the change was never noticed' )
209 + local painted = floats()
210 + expect( #painted > 0, 'no floating window is being painted' )
211 + local found = false
212 + for _, float in ipairs( painted ) do
213 + if float.text:find( 'reloaded', 1, true ) then found = true end
214 + end
215 + expect( found, 'the reload notification is not on screen: ' .. vim.inspect( painted ) )
216 +end )
218 +check( 'nothing is reloaded under your fingers in insert mode', function ()
219 + reset()
220 + local before = state().text
221 + remote [[ vim.api.nvim_input 'i' ; return true ]]
222 + vim.uv.sleep( 500 )
223 + expect( state().mode == 'i', 'could not get into insert mode' )
225 + write_file( 201, 240 )
226 + vim.uv.sleep( 5000 )
228 + local now = state()
229 + expect( now.mode == 'i', 'insert mode was left on its own' )
230 + expect( now.reloads == 0, 'reloaded while typing' )
231 + expect( now.text == before,
232 + 'the buffer changed under the cursor: ' .. vim.inspect( before ) .. ' -> ' .. vim.inspect( now.text ) )
233 +end )
235 +check( 'leaving insert mode reloads immediately', function ()
236 + remote [[ vim.api.nvim_input '<Esc>' ; return true ]]
237 + expect( await_reload(), 'no reload after leaving insert mode' )
239 + local now = state()
240 + expect( now.text == '215', 'expected 215, got ' .. vim.inspect( now.text ) )
241 + expect( now.cursor == 15, 'the cursor moved to line ' .. tostring( now.cursor ) )
242 +end )
244 +check( 'undo brings the version from before the reload back', function ()
245 + remote [[ vim.api.nvim_input 'u' ; return true ]]
246 + vim.uv.sleep( 1500 )
248 + local now = state()
249 + expect( now.first == '151',
250 + 'undo did not restore the text from before the reload: ' .. vim.inspect( now.first ) )
251 + expect( now.modified, 'the buffer is not marked modified after undoing a reload' )
253 + remote [[ vim.cmd 'silent! edit!' ; return true ]]
254 + vim.uv.sleep( 1000 )
255 +end )
257 +check( 'unsaved edits are never overwritten', function ()
258 + reset()
259 + remote [[
260 + vim.api.nvim_buf_set_lines( 0, 14, 15, false, { 'MY UNSAVED EDIT' } )
261 + return true
262 + ]]
263 + write_file( 301, 340 )
264 + vim.uv.sleep( 4500 )
266 + local now = state()
267 + expect( now.reloads == 0, 'reloaded over unsaved changes' )
268 + expect( now.text == 'MY UNSAVED EDIT', 'lost the local edit: ' .. vim.inspect( now.text ) )
269 + expect( #now.notes == 1, 'expected one warning, got ' .. tostring( #now.notes ) )
270 + expect( now.notes[1]:find( 'DiffDisk', 1, true ) ~= nil, 'the warning offers no way out' )
271 +end )
273 +check( 'the conflict warning is legible in the UI', function ()
274 + local painted = floats()
275 + local warning
276 + for _, float in ipairs( painted ) do
277 + if float.text:find( 'changed on disk', 1, true ) then warning = float end
278 + end
279 + expect( warning, 'the conflict warning is not on screen: ' .. vim.inspect( painted ) )
280 + expect( warning.text:find( 'DiffDisk', 1, true ) ~= nil, 'the way out is cut off' )
281 + expect( warning.height >= 2, 'the warning is squeezed into one line' )
282 +end )
284 +check( 'a second conflict is reported again after :e!', function ()
285 + remote [[ vim.cmd 'edit!' ; return true ]]
286 + reset()
287 + remote [[
288 + vim.api.nvim_buf_set_lines( 0, 14, 15, false, { 'ANOTHER UNSAVED EDIT' } )
289 + return true
290 + ]]
291 + write_file( 401, 440 )
292 + vim.uv.sleep( 4500 )
294 + local now = state()
295 + expect( now.reloads == 0, 'reloaded over unsaved changes' )
296 + expect( #now.notes == 1, 'the warning was swallowed, got ' .. tostring( #now.notes ) )
297 +end )
299 +check( 'the buffer survives the file being deleted', function ()
300 + reset()
301 + assert( os.remove( target ) )
302 + vim.uv.sleep( 4500 )
304 + local now = state()
305 + expect( now.text == 'ANOTHER UNSAVED EDIT', 'the text died with the file' )
306 + expect( #now.notes == 1, 'expected one warning, got ' .. tostring( #now.notes ) )
307 + expect( now.notes[1]:find( 'gone from disk', 1, true ) ~= nil,
308 + 'unexpected warning: ' .. tostring( now.notes[1] ) )
309 +end )
311 +check( 'DiffDisk opens a real side by side diff', function ()
312 + remote [[ vim.cmd 'write' ; return true ]]
313 + reset()
314 + write_file( 501, 540 )
315 + expect( await_reload(), 'the change was never noticed' )
317 + local diffed = remote [[
318 + vim.api.nvim_buf_set_lines( 0, 0, 1, false, { 'ONLY IN THE BUFFER' } )
319 + vim.cmd 'DiffDisk'
320 + local original = vim.api.nvim_get_current_buf()
321 + local in_diff, disk = 0, nil
322 + for _, window in ipairs( vim.api.nvim_tabpage_list_wins( 0 ) ) do
323 + if vim.wo[window].diff then
324 + in_diff = in_diff + 1
325 + local buffer = vim.api.nvim_win_get_buf( window )
326 + if buffer ~= original then
327 + disk = vim.api.nvim_buf_get_lines( buffer, 0, 1, false )[1]
328 + end
329 + end
330 + end
331 + vim.cmd 'redraw'
332 + return { in_diff = in_diff, disk = disk }
333 + ]]
334 + expect( diffed.in_diff == 2, 'expected two diff windows, got ' .. tostring( diffed.in_diff ) )
335 + expect( diffed.disk == '501',
336 + 'the scratch side does not hold the disk version: ' .. vim.inspect( diffed.disk ) )
338 + remote [[ vim.cmd 'diffoff!' ; vim.cmd 'only' ; vim.cmd 'silent! edit!' ; return true ]]
339 +end )
341 +--[[ REPORT ]]
343 +print( table.concat( checks, '\n' ) )
345 +-- focus reporting can not be produced from inside neovim: it needs the window
346 +-- manager to actually move focus. report what was observed instead of pretending.
347 +local focus = state().focus
348 +print( ( '\nfocus events seen while driving: %d %s' )
349 + :format( #focus, vim.inspect( focus ) ) )
351 +print( failures == 0 and '\nall neovide checks passed'
352 + or ( '\n' .. tostring( failures ) .. ' check(s) failed' ) )
354 +finish( failures == 0 and 0 or 1 )

nushell/config.nu

Modified
53 53 $env.LS_COLORS = "rs=0:di=1;34:ln=1;35:ex=1;32:bd=1;33;40:cd=1;33;40:pi=33:so=35:do=35:or=1;31:mi=1;37;41:su=37;41:sg=30;43:tw=30;41:ow=37;41:st=37;44:*.tar=1;31:*.tgz=1;31:*.zip=1;31:*.gz=1;31:*.xz=1;31:*.7z=1;31:*.rar=1;31:*.jpg=1;35:*.png=1;35:*.gif=1;35:*.bmp=1;35:*.mp4=1;33:*.mp3=1;33:*.flac=1;33:*.pdf=1;33:*.doc=1;33:*.docx=1;33:*.txt=0:*.md=0:*.c=1;34:*.cpp=1;34:*.h=1;34:*.java=1;34:*.py=1;34:*.sh=1;34:"
55 +# Claude tweaking
56 +# do not ask for feedback
57 +$env.CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY = 1
58 +# disable remote control
59 +$env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = 1
60 +# no autoupdate
61 +$env.DISABLE_AUTOUPDATER = 1
62 +# Reduce splash screen size.
63 +$env.IS_DEMO = 1
55 65 # Carapace bridges available on this system: bash.
56 66 # fish/zsh/inshellisense executables are not installed, so those bridges add no completions.
57 67 $env.CARAPACE_BRIDGES = "bash"

nushell/secrets.nu

Modified

Previous version contains binary or non-UTF-8 data.

Current version contains binary or non-UTF-8 data.

pi/agent/settings.json

Modified
43 43 "defaultProvider": "openai-codex",
44 44 "defaultModel": "gpt-5.6-luna",
45 45 "defaultThinkingLevel": "high",
46 - "defaultTools": ["bash", "edit", "read", "write", "ls", "grep"],
46 + "defaultTools": [
47 + "bash",
48 + "edit",
49 + "read",
50 + "write",
51 + "ls",
52 + "grep"
53 + ],
47 54 "collapseChangelog": true,
48 55 "editorPaddingX": 1,
49 56 "tuiMode": "fullscreen",
50 57 "fullscreenExitOutput": "resume-hint",
51 - "terminal": { "showTerminalProgress": true },
58 + "terminal": {
59 + "showTerminalProgress": true
60 + },
52 61 "sessionDir": "~/.local/state/pi/sessions",
53 62 "masks": {
54 63 "pickerShortcut": "alt+m",
99 108 "angel": {
100 109 "thinkingLevel": "high",
101 110 "subagentExtensions": [
102 - "pfui",
103 - "klaus",
104 - "fast",
105 - "rtk",
106 - "uv",
107 - "git-safe",
108 - "web"
111 + "pfui",
112 + "klaus",
113 + "fast",
114 + "rtk",
115 + "uv",
116 + "git-safe",
117 + "web"
110 119 "pairs": [
120 129 "executor": "openai-codex/gpt-5.6-luna",
121 130 "advisor": "openai-codex/gpt-5.6-sol"
133 + "executor": "klaus/claude-opus-5",
134 + "advisor": "klaus/claude-fable-5-1"
135 + },
124 137 "executor": "zai/glm-5.3-flash",
125 138 "advisor": "zai/glm-5.3"
135 148 "klaus/claude-fable-5-1",
136 149 "klaus/claude-opus-5"
138 - "counterSampleRate": 0.25
151 + "counterSampleRate": 0.25
152 + },
153 + "fast": {
154 + "enable": true
140 - "fast": { "enable": true },
141 156 "ultra": {
142 157 "auto_enable": true,
143 158 "subagentExtensions": [
144 - "pfui",
145 - "klaus",
159 + "pfui",
160 + "klaus",
146 161 "angel",
147 162 "fast",
148 163 "git-safe",
188 203 "intellij": {
189 204 "url": "http://127.0.0.1:64343/stream"
191 - "hideThinkingBlock": false
206 + "hideThinkingBlock": false,
207 + "neko": {
208 + "enabled": false

pi/agent/skills/win32-drive/SKILL.md

Modified
2 2 name: win32-drive
3 3 description: "Use for inspecting, driving, or debugging Windows desktop GUIs, including cursor and pointer issues."
4 -compatibility: "Windows PowerShell 5.1+"
4 +compatibility: "Windows PowerShell 5.1 (powershell.exe), 64-bit recommended"
7 7 # Win32 Drive
9 -Run `scripts/win32-drive.ps1` relative to this skill.
9 +Resolve `scripts/win32-drive.ps1` against this skill's directory and pass that absolute path; never rely on the current directory.
11 11 ```powershell
12 -powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/win32-drive.ps1 <cmd> [opts]
12 +powershell.exe -NoProfile -ExecutionPolicy Bypass -File <skill-dir>/scripts/win32-drive.ps1 <cmd> [opts]
15 15 All commands emit JSON. On nonzero exit, JSON has `ok:false,error`.
17 17 ## Safety
19 -Nonracing: `help`, `list`, `shot`, `pixel`, `uia`, `cursor`, `idle`, clipboard read, theme read, `overlay`.
19 +Nonracing: `help`, `list`, `shot`, `pixel`, `uia`, `cursor`, `focus`, `idle`, clipboard read, theme read, `overlay`.
21 -Racing/mutating: `click`, `type`, `key`, `window`, `clipboard -Set`, theme set. These fade a 16px red border/ring, wait 800ms user-idle, then act. Screenshots never show the guard.
21 +Racing/mutating: `uia-invoke`, `uia-set`, `click`, `type`, `key`, `window`, `clipboard -Set`, theme set. These fade a 16px red border/ring, wait 800ms user-idle, then act. The overlay never takes focus and never swallows input. Screenshots never show the guard.
23 +`-IdleMs n` (default 800) and `-TimeoutMs n` (default 10000) tune that guard; `-IdleMs 0` skips waiting and is for tests, not for a desktop the user is touching.
23 25 ## Commands
28 30 shot [-Hwnd n|-Process p -TitleContains t|-X x -Y y -Width w -Height h] [-Out file.png]
29 31 pixel -X x -Y y
30 32 uia [-Hwnd n|-Process p|-TitleContains t] [-Depth n]
33 +uia-invoke -Hwnd n|-Process p|-TitleContains t [-Name n] [-AutomationId a] [-ClassName c] [-ControlType t] [-Index i]
34 +uia-set -Hwnd n|-Process p|-TitleContains t -Value text [-Name n] [-AutomationId a] [-ClassName c] [-ControlType t] [-Index i]
31 35 cursor
36 +focus
32 37 idle
33 38 clipboard | clipboard -Set text
34 -theme | theme -Mode dark|light [-Scope apps|system|both]
39 +theme | theme -Mode dark|light [-Scope apps|system|both] [-Refresh broadcast|full]
35 40 overlay [-X x -Y y] [-DurationMs ms]
36 -click [-Hwnd n|-Process p|-TitleContains t] [-X x -Y y] [-Button left|right] [-Count n]
37 -type [-Hwnd n|-Process p|-TitleContains t] -Text text
38 -key [-Hwnd n|-Process p|-TitleContains t] -Keys '^s'
39 -window -Hwnd n -Action move|min|max|restore|close [-X x -Y y -Width w -Height h]
41 +click -Pointer [-Hwnd n|-Process p|-TitleContains t] [-X x -Y y] [-Button left|right] [-Count n] [-Focus auto|require|skip] [-Cursor restore|keep]
42 +type [-Hwnd n|-Process p|-TitleContains t] -Text text [-Focus auto|require|skip] [-Pointer] [-Method unicode|sendkeys]
43 +key [-Hwnd n|-Process p|-TitleContains t] -Keys '^s' [-Focus auto|require|skip] [-Pointer]
44 +window -Action move|min|max|restore|close [-Hwnd n|-Process p|-TitleContains t] [-X x -Y y -Width w -Height h]
42 47 Selector preference: `-Hwnd` > `-Process` + `-TitleContains` > unique `-TitleContains` > coordinates.
44 -`click` coordinates are screen pixels unless a window selector is present; then they are window-relative. Without `-X/-Y`, window click targets center.
49 +## Coordinates
46 -After `shot`, immediately read the returned PNG path with the harness `read` tool.
51 +Screen pixels everywhere, except `click -X/-Y` with a window selector, which are relative to the window origin reported by `list` and `shot` (DWM frame bounds). Without `-X/-Y`, a window click targets the center.
48 -Limits: no UAC secure desktop/lock screen. Elevated apps may need elevated agent. GPU/fullscreen windows may need region/desktop screenshot fallback. Theme only updates Windows plus apps that follow system theme; apps/sites with explicit themes may ignore it.
53 +`uia` returns screen coordinates: convert with `click -X (uia.x - shot.x) -Y (uia.y - shot.y)`, or click without a selector.
55 +`shot -Hwnd` returns exactly the `list` frame bounds, so image pixel `(0,0)` is screen pixel `(x,y)` in both `printwindow` and `screen-crop` modes. After `shot`, immediately read the returned PNG path with the harness `read` tool.
57 +## Acting without stealing focus
59 +Prefer `uia-invoke` and `uia-set`. They drive the app through accessibility and posted messages: no activation, no cursor movement, no synthetic keystrokes, so the user keeps working in another window. Read the tree with `uia` first, then address the element by `-Name`, `-AutomationId`, `-ClassName`, or `-ControlType`; the string filters accept wildcards, `-Index` disambiguates, and an ambiguous match reports the candidates.
61 +`uia-invoke` tries `Invoke`, `Toggle`, `SelectionItem`, `ExpandCollapse`, then MSAA default action, then `BM_CLICK`, and reports which one it used. `uia-set` tries `Value`, then posts characters to the control and verifies the resulting text. Both fail loudly when the app exposes nothing usable, which is common for GPU-rendered apps with no accessibility tree; fall back to pointer input there.
63 +They cannot hover, drag, or reach anything outside the accessibility tree.
65 +## Focus and pointer input
67 +Synthetic mouse input requires the explicit `-Pointer` flag. `click` always needs it; `type` and `key` need it only for `-Focus auto`, whose fallback is a pointer click.
69 +`click`, `type`, and `key` with a selector focus the target and verify it actually became foreground; they fail instead of driving whatever window happens to be in front. Focusing happens after the racing guard, never before: Windows denies activation to background processes while the user is typing or moving the mouse.
71 +- `require` (default): activation APIs only; fails when Windows denies them, which is normal on systems with a large `ForegroundLockTimeout`.
72 +- `auto`: adds a single left click on the target's title bar, which always activates because it is real pointer input. Needs `-Pointer`. On a borderless window that click lands on content.
73 +- `skip`: no focusing at all; input goes to whatever is focused.
75 +Minimized targets fail: restore them first.
77 +Errors report the real foreground window, whether it is hung, the system `ForegroundLockTimeout`, and the current user idle time. `focus` reports the same foreground record on demand. A hung foreground window cannot be displaced at all; nothing can be driven until it recovers.
79 +Never use `AttachThreadInput` to force activation from this script: it couples input queues and has hung the host terminal here.
81 +## Typing
83 +`type` injects Unicode code units directly (`-Method unicode`, the default on 64-bit) so text arrives verbatim, newline as Enter, carriage returns dropped. `-Method sendkeys` uses the legacy escaped SendKeys path. `key` is always SendKeys, for chords like `^s` or `%{F4}`.
85 +## Limits
87 +No UAC secure desktop or lock screen. Elevated apps need an elevated agent. GPU/fullscreen windows fall back from `printwindow` to `screen-crop`, which captures whatever is on top. Theme only updates Windows plus apps that follow the system theme; `-Refresh full` additionally runs `UpdatePerUserSystemParameters`, which can perturb wallpaper and per-user parameters, so prefer the default broadcast. Even the default broadcasts `WM_SETTINGCHANGE` to every window, which has been observed to wedge apps that react to it: set the theme once, not in a loop. `theme -Mode` returns `previous` for restoring state.
89 +## Tests
91 +`mise run win32-drive-test` (from the dotfiles root) drives a fixture window and asserts real effects. It takes over mouse, keyboard, and clipboard for about a minute; never run it while the user is working. Theme writes are skipped unless the script is invoked directly with `-IncludeTheme`.

pi/agent/skills/win32-drive/scripts/win32-drive.ps1

Modified
3 3 $raw = [Environment]::GetCommandLineArgs()
4 4 $scriptIndex = -1
5 5 $scriptName = [IO.Path]::GetFileName($PSCommandPath)
6 6 for ($i = 0; $i -lt $raw.Count; $i++) {
7 7 try {
8 - if ([IO.Path]::GetFileName([string]$raw[$i]) -eq $scriptName) { $scriptIndex = $i }
8 + if ($scriptIndex -lt 0 -and [IO.Path]::GetFileName([string]$raw[$i]) -eq $scriptName) { $scriptIndex = $i }
9 9 } catch {}
11 11 $argv = @()
35 35 [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd);
36 36 [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hWnd);
37 37 [DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
38 + [DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetClassName(IntPtr hWnd, StringBuilder text, int count);
38 39 [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
39 40 [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
40 41 [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr hwnd, int attr, out RECT rect, int size);
48 49 [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT point);
49 50 [DllImport("user32.dll")] public static extern bool GetLastInputInfo(ref LASTINPUTINFO info);
50 51 [DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint msg, UIntPtr wParam, string lParam, uint flags, uint timeout, out UIntPtr result);
52 + [DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true, EntryPoint="SendMessageTimeoutW")] public static extern IntPtr SendMessageTimeoutPtr(IntPtr hWnd, uint msg, UIntPtr wParam, IntPtr lParam, uint flags, uint timeout, out UIntPtr result);
53 + [DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true, EntryPoint="SendMessageTimeoutW")] public static extern IntPtr SendMessageTimeoutText(IntPtr hWnd, uint msg, UIntPtr wParam, StringBuilder lParam, uint flags, uint timeout, out UIntPtr result);
51 54 [DllImport("kernel32.dll")] public static extern uint GetTickCount();
55 + [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
56 + [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd);
57 + [DllImport("user32.dll", SetLastError=true)] public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
58 + [DllImport("shcore.dll")] public static extern int SetProcessDpiAwareness(int value);
59 + [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
60 + [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hWnd);
61 + [DllImport("oleacc.dll")] public static extern int AccessibleObjectFromWindow(IntPtr hWnd, uint objectId, ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object accessible);
62 + [DllImport("user32.dll")] public static extern bool IsHungAppWindow(IntPtr hWnd);
63 + [DllImport("user32.dll", EntryPoint="SystemParametersInfoW")] static extern bool SystemParametersInfoGet(uint action, uint param, ref uint value, uint winIni);
64 + [DllImport("user32.dll", EntryPoint="SystemParametersInfoW")] static extern bool SystemParametersInfoSet(uint action, uint param, IntPtr value, uint winIni);
66 + // Activation is asynchronous across processes, so every attempt has to be
67 + // confirmed by polling instead of by an immediate GetForegroundWindow.
68 + public static bool WaitForeground(IntPtr hWnd, int waitMs) {
69 + for (int waited = 0; ; waited += 40) {
70 + if (GetForegroundWindow() == hWnd) { return true; }
71 + if (waited >= waitMs) { return false; }
72 + System.Threading.Thread.Sleep(40);
73 + }
74 + }
76 + public static bool Foreground(IntPtr hWnd, int waitMs) {
77 + if (GetForegroundWindow() == hWnd) { return true; }
78 + BringWindowToTop(hWnd);
79 + SetForegroundWindow(hWnd);
80 + return WaitForeground(hWnd, waitMs);
81 + }
83 + // Windows refuses SetForegroundWindow from a background process while the
84 + // foreground lock timeout is running. Relaxing that timeout around a single
85 + // attempt is the safe workaround: AttachThreadInput would couple our input
86 + // queue to the foreground application and can hang it. The parameter is
87 + // restored only after activation settled, and without SPIF_SENDCHANGE so no
88 + // WM_SETTINGCHANGE storm hits every window on the desktop.
89 + public static uint GetForegroundLockTimeout() {
90 + uint value = 0;
91 + SystemParametersInfoGet(0x2000, 0, ref value, 0);
92 + return value;
93 + }
95 + public static bool ForegroundUnlocked(IntPtr hWnd, int waitMs) {
96 + const uint SPI_GETFOREGROUNDLOCKTIMEOUT = 0x2000;
97 + const uint SPI_SETFOREGROUNDLOCKTIMEOUT = 0x2001;
98 + uint previous = 0;
99 + if (!SystemParametersInfoGet(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, ref previous, 0) || previous == 0) { return false; }
100 + SystemParametersInfoSet(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, IntPtr.Zero, 0);
101 + try {
102 + return Foreground(hWnd, waitMs);
103 + } finally {
104 + SystemParametersInfoSet(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, new IntPtr(previous), 0);
108 + [DllImport("user32.dll", EntryPoint="SetWindowLongPtr")] static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int index, IntPtr value);
109 + [DllImport("user32.dll", EntryPoint="GetWindowLongPtr")] static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, int index);
110 + [DllImport("user32.dll", EntryPoint="SetWindowLong")] static extern int SetWindowLong32(IntPtr hWnd, int index, int value);
111 + [DllImport("user32.dll", EntryPoint="GetWindowLong")] static extern int GetWindowLong32(IntPtr hWnd, int index);
113 + // Keeps the guard overlay out of the activation chain: without this the
114 + // overlay steals foreground from the window the command is about to drive.
115 + public static void AddExStyle(IntPtr hWnd, int bits) {
116 + const int GWL_EXSTYLE = -20;
117 + if (IntPtr.Size == 8) {
118 + long current = GetWindowLongPtr64(hWnd, GWL_EXSTYLE).ToInt64();
119 + SetWindowLongPtr64(hWnd, GWL_EXSTYLE, new IntPtr(current | (long) (uint) bits));
120 + } else {
121 + int current = GetWindowLong32(hWnd, GWL_EXSTYLE);
122 + SetWindowLong32(hWnd, GWL_EXSTYLE, current | bits);
126 + [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT64 { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public ulong dwExtraInfo; }
127 + [StructLayout(LayoutKind.Sequential, Size=40)] public struct INPUT64 { public uint type; public uint pad; public KEYBDINPUT64 ki; }
128 + [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT32 { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public uint dwExtraInfo; }
129 + [StructLayout(LayoutKind.Sequential, Size=28)] public struct INPUT32 { public uint type; public KEYBDINPUT32 ki; }
131 + [DllImport("user32.dll", SetLastError=true)] static extern uint SendInput(uint count, INPUT64[] inputs, int size);
132 + [DllImport("user32.dll", SetLastError=true, EntryPoint="SendInput")] static extern uint SendInput32(uint count, INPUT32[] inputs, int size);
134 + public static int TypeUnicode(string text) {
135 + const uint KEYEVENTF_KEYUP = 0x0002;
136 + const uint KEYEVENTF_UNICODE = 0x0004;
137 + const ushort VK_RETURN = 0x0D;
138 + int sent = 0;
139 + foreach (char ch in text) {
140 + if (ch == '\r') { continue; }
141 + bool enter = ch == '\n';
142 + ushort vk = enter ? VK_RETURN : (ushort) 0;
143 + ushort scan = enter ? (ushort) 0 : (ushort) ch;
144 + uint flags = enter ? 0u : KEYEVENTF_UNICODE;
145 + if (IntPtr.Size == 8) {
146 + INPUT64[] events = new INPUT64[2];
147 + events[0].type = 1; events[0].ki.wVk = vk; events[0].ki.wScan = scan; events[0].ki.dwFlags = flags;
148 + events[1] = events[0]; events[1].ki.dwFlags = flags | KEYEVENTF_KEYUP;
149 + sent += (int) SendInput(2, events, Marshal.SizeOf(typeof(INPUT64)));
150 + } else {
151 + INPUT32[] events = new INPUT32[2];
152 + events[0].type = 1; events[0].ki.wVk = vk; events[0].ki.wScan = scan; events[0].ki.dwFlags = flags;
153 + events[1] = events[0]; events[1].ki.dwFlags = flags | KEYEVENTF_KEYUP;
154 + sent += (int) SendInput32(2, events, Marshal.SizeOf(typeof(INPUT32)));
157 + return sent;
162 +function Set-DpiAwareness {
163 + try { if ([Win32DriveNative]::SetProcessDpiAwarenessContext([IntPtr] (-4))) { return 'per-monitor-v2' } } catch {}
164 + try { if ([Win32DriveNative]::SetProcessDpiAwareness(2) -eq 0) { return 'per-monitor' } } catch {}
165 + try { [void] [Win32DriveNative]::SetProcessDPIAware(); return 'system' } catch {}
166 + 'unaware'
169 +$script:win32DriveDpi = Set-DpiAwareness
55 171 function Write-Json($Value) {
56 172 $Value | ConvertTo-Json -Depth 24 -Compress
59 175 function Parse-Options([string[]] $ArgList) {
60 176 $opts = @{}
61 177 $pos = @()
62 - $valueOptions = @('Hwnd','Process','TitleContains','X','Y','Width','Height','Out','Text','Keys','Action','Button','Count','DurationMs','IdleMs','TimeoutMs','Set','Depth','Mode','Scope')
178 + $valueOptions = @('Hwnd','Process','TitleContains','X','Y','Width','Height','Out','Text','Keys','Action','Button','Count','DurationMs','IdleMs','TimeoutMs','Set','Depth','Mode','Scope','Focus','Cursor','Refresh','Method','Name','AutomationId','ClassName','ControlType','Index','Value')
179 + $flagOptions = @('Pointer')
63 180 for ($i = 0; $i -lt $ArgList.Count; $i++) {
64 181 $arg = $ArgList[$i]
65 182 if ($arg.StartsWith('-')) {
66 183 $key = $arg.TrimStart('-')
184 + if ($flagOptions -contains $key) { $opts[$key] = $true; continue }
67 185 if ($valueOptions -notcontains $key) { throw "Unknown option: -$key" }
68 186 if ($i + 1 -ge $ArgList.Count) { throw "Missing value for -$key" }
249 +function Get-RawRect([IntPtr] $Hwnd) {
250 + $rect = New-Object Win32DriveNative+RECT
251 + [void] [Win32DriveNative]::GetWindowRect($Hwnd, [ref] $rect)
252 + $rect
255 +function Has-Selector($Opts) {
256 + $Opts.ContainsKey('Hwnd') -or $Opts.ContainsKey('Process') -or $Opts.ContainsKey('TitleContains')
259 +function Get-FocusMode($Opts) {
260 + $focus = (Str-Opt $Opts 'Focus' 'require').ToLowerInvariant()
261 + if (@('auto','require','skip') -notcontains $focus) { throw 'Focus must be auto, require, or skip' }
262 + if ($focus -eq 'auto' -and -not $Opts.ContainsKey('Pointer')) { throw 'Focus auto falls back to clicking the target caption: pass -Pointer to allow pointer input' }
263 + $focus
266 +function Get-ForegroundInfo {
267 + $h = [Win32DriveNative]::GetForegroundWindow()
268 + $title = ''
269 + [uint32] $procId = 0
270 + if ($h -ne [IntPtr]::Zero) {
271 + $sb = [Text.StringBuilder]::new(1024)
272 + [void] [Win32DriveNative]::GetWindowText($h, $sb, $sb.Capacity)
273 + $title = $sb.ToString()
274 + [void] [Win32DriveNative]::GetWindowThreadProcessId($h, [ref] $procId)
276 + $proc = Get-Process -Id $procId -ErrorAction SilentlyContinue
277 + $hung = $false
278 + try { $hung = [bool] [Win32DriveNative]::IsHungAppWindow($h) } catch {}
279 + [pscustomobject] [ordered] @{
280 + hwnd = $h.ToInt64()
281 + pid = [int64] $procId
282 + process = if ($proc) { $proc.ProcessName } else { $null }
283 + title = $title
284 + hung = $hung
288 +function Invoke-PointerClick([int] $X, [int] $Y, [string] $Button = 'left', [int] $Count = 1, [bool] $RestoreCursor = $true) {
289 + $origin = New-Object Win32DriveNative+POINT
290 + [void] [Win32DriveNative]::GetCursorPos([ref] $origin)
291 + [void] [Win32DriveNative]::SetCursorPos($X, $Y)
292 + $down = if ($Button -eq 'right') { 0x0008 } else { 0x0002 }
293 + $up = if ($Button -eq 'right') { 0x0010 } else { 0x0004 }
294 + for ($i = 0; $i -lt $Count; $i++) {
295 + [Win32DriveNative]::mouse_event($down, 0, 0, 0, [UIntPtr]::Zero)
296 + Start-Sleep -Milliseconds 45
297 + [Win32DriveNative]::mouse_event($up, 0, 0, 0, [UIntPtr]::Zero)
298 + Start-Sleep -Milliseconds 80
300 + if ($RestoreCursor) { [void] [Win32DriveNative]::SetCursorPos($origin.X, $origin.Y) }
303 +# Activation APIs are denied to background processes on locked-down foreground
304 +# settings, but real pointer input always activates the window it lands on.
305 +function Invoke-CaptionClick([IntPtr] $Hwnd) {
306 + $r = Get-Rect $Hwnd
307 + $width = $r.Right - $r.Left
308 + if ($width -le 0) { return $false }
309 + Invoke-PointerClick ([int] ($r.Left + $width * 0.35)) ([int] ($r.Top + 6)) 'left' 1 $true
310 + [Win32DriveNative]::WaitForeground($Hwnd, 800)
313 +function Set-Foreground([IntPtr] $Hwnd, [string] $Mode = 'auto', [int] $TimeoutMs = 2500) {
314 + if ([Win32DriveNative]::IsIconic($Hwnd)) { throw ('Target window is minimized; run: window -Hwnd ' + $Hwnd.ToInt64() + ' -Action restore') }
315 + $deadline = (Get-Date).AddMilliseconds($TimeoutMs)
316 + do {
317 + # Windows denies activation to background processes while the user is
318 + # actually typing or moving the mouse, so only try during input gaps.
319 + if ((Get-IdleMs) -ge 250) {
320 + if ([Win32DriveNative]::Foreground($Hwnd, 300)) { return }
321 + if ([Win32DriveNative]::ForegroundUnlocked($Hwnd, 400)) { return }
323 + Start-Sleep -Milliseconds 80
324 + } while ((Get-Date) -lt $deadline)
325 + if ($Mode -eq 'auto' -and (Invoke-CaptionClick $Hwnd)) { return }
326 + $fg = Get-ForegroundInfo
327 + $reason = if ($fg.hung) { 'the current foreground window is not responding' } elseif ((Get-IdleMs) -lt 500) { 'the user is still providing input' } else { 'foreground lock' }
328 + $diagnostics = [ordered] @{ lockTimeoutMs = [int64] [Win32DriveNative]::GetForegroundLockTimeout(); idleMs = Get-IdleMs }
329 + throw ('Could not focus target window ' + $Hwnd.ToInt64() + ' (' + $reason + '); foreground is ' + ($fg | ConvertTo-Json -Compress) + '; ' + ($diagnostics | ConvertTo-Json -Compress))
131 332 function Resolve-Window($Opts) {
132 333 if ($Opts.ContainsKey('Hwnd')) {
133 334 $hwnd = [IntPtr] (Long-Opt $Opts 'Hwnd')
189 390 $pen.Dispose()
191 392 }.GetNewClosure())
192 - $form.Show()
393 + # WS_EX_NOACTIVATE | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW: never take focus,
394 + # never swallow input, never appear in the alt-tab list.
395 + [Win32DriveNative]::AddExStyle($form.Handle, (0x08000000 -bor 0x00000020 -bor 0x00000080))
396 + [void] [Win32DriveNative]::ShowWindow($form.Handle, 4)
193 397 $forms += $form
195 399 foreach ($opacity in 0.2,0.45,0.7,0.9) {
210 414 function Invoke-RacingGuard($Opts, $X = $null, $Y = $null) {
211 415 $idle = Int-Opt $Opts 'IdleMs' 800
212 416 $timeout = Int-Opt $Opts 'TimeoutMs' 10000
213 - Draw-Indicator $X $Y 80
214 417 Wait-UserIdle $idle $timeout
215 - Draw-Indicator $X $Y 80
418 + Draw-Indicator $X $Y 120
218 421 function Theme-Name($Value) {
235 438 [pscustomobject] [ordered] @{ ok = $true; apps = Theme-Name $apps; system = Theme-Name $system }
238 -function Broadcast-ThemeChange {
441 +function Broadcast-ThemeChange([string] $Refresh) {
239 442 $result = [UIntPtr]::Zero
240 443 foreach ($name in @('ImmersiveColorSet','WindowsThemeElement','Software\Microsoft\Windows\CurrentVersion\Themes\Personalize')) {
241 444 [void] [Win32DriveNative]::SendMessageTimeout([IntPtr]0xffff, 0x001A, [UIntPtr]::Zero, $name, 2, 5000, [ref] $result)
243 446 [void] [Win32DriveNative]::SendMessageTimeout([IntPtr]0xffff, 0x031A, [UIntPtr]::Zero, $null, 2, 5000, [ref] $result)
244 - Start-Process -WindowStyle Hidden -FilePath rundll32.exe -ArgumentList 'user32.dll,UpdatePerUserSystemParameters 1, True' -Wait
447 + if ($Refresh -eq 'full') {
448 + Start-Process -WindowStyle Hidden -FilePath rundll32.exe -ArgumentList 'user32.dll,UpdatePerUserSystemParameters 1, True' -Wait
247 -function Set-Theme([string] $Mode, [string] $Scope) {
452 +function Set-Theme([string] $Mode, [string] $Scope, [string] $Refresh) {
248 453 $value = Theme-Value $Mode
249 454 $scopeName = if ($Scope) { $Scope.ToLowerInvariant() } else { 'both' }
250 455 if (@('apps','system','both') -notcontains $scopeName) { throw 'Scope must be apps, system, or both' }
456 + $refreshName = if ($Refresh) { $Refresh.ToLowerInvariant() } else { 'broadcast' }
457 + if (@('broadcast','full') -notcontains $refreshName) { throw 'Refresh must be broadcast or full' }
458 + $previous = Get-Theme
251 459 $path = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize'
252 460 New-Item -Path $path -Force | Out-Null
253 461 if ($scopeName -eq 'apps' -or $scopeName -eq 'both') { Set-ItemProperty -Path $path -Name AppsUseLightTheme -Type DWord -Value $value }
254 462 if ($scopeName -eq 'system' -or $scopeName -eq 'both') { Set-ItemProperty -Path $path -Name SystemUsesLightTheme -Type DWord -Value $value }
255 - Broadcast-ThemeChange
256 - Get-Theme | Add-Member -PassThru -NotePropertyName scope -NotePropertyValue $scopeName
463 + Broadcast-ThemeChange $refreshName
464 + $current = Get-Theme
465 + [pscustomobject] [ordered] @{
466 + ok = $true
467 + apps = $current.apps
468 + system = $current.system
469 + scope = $scopeName
470 + refresh = $refreshName
471 + previous = [ordered] @{ apps = $previous.apps; system = $previous.system }
259 475 function Save-Bitmap($Bitmap, [string] $Out) {
260 476 if (-not $Out) { $Out = Join-Path $env:TEMP ("win32-drive-shot-" + [guid]::NewGuid().ToString('N') + '.png') }
261 - $full = [IO.Path]::GetFullPath($Out)
477 + $full = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Out)
262 478 $parent = Split-Path -Parent $full
263 479 if ($parent -and -not (Test-Path $parent)) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }
264 480 $Bitmap.Save($full, [Drawing.Imaging.ImageFormat]::Png)
508 +function Test-BlankBitmap($Bitmap) {
509 + $first = $null
510 + for ($ix = 0; $ix -lt 5; $ix++) {
511 + for ($iy = 0; $iy -lt 5; $iy++) {
512 + $px = [int] (($Bitmap.Width - 1) * $ix / 4)
513 + $py = [int] (($Bitmap.Height - 1) * $iy / 4)
514 + $argb = $Bitmap.GetPixel($px, $py).ToArgb()
515 + if ($null -eq $first) { $first = $argb } elseif ($argb -ne $first) { return $false }
518 + $true
292 521 function Capture-Window([IntPtr] $Hwnd, [string] $Out) {
293 - $r = Get-Rect $Hwnd
294 - $w = $r.Right - $r.Left
295 - $h = $r.Bottom - $r.Top
296 - if ($w -le 0 -or $h -le 0) { throw 'Window has empty bounds' }
297 - $bmp = [Drawing.Bitmap]::new($w, $h)
298 - $g = [Drawing.Graphics]::FromImage($bmp)
522 + $frame = Get-Rect $Hwnd
523 + $raw = Get-RawRect $Hwnd
524 + $w = $frame.Right - $frame.Left
525 + $h = $frame.Bottom - $frame.Top
526 + $rawW = $raw.Right - $raw.Left
527 + $rawH = $raw.Bottom - $raw.Top
528 + if ($w -le 0 -or $h -le 0 -or $rawW -le 0 -or $rawH -le 0) { throw 'Window has empty bounds' }
299 529 $used = 'printwindow'
530 + $image = $null
531 + $bmp = [Drawing.Bitmap]::new($rawW, $rawH)
532 + $g = [Drawing.Graphics]::FromImage($bmp)
301 534 $hdc = $g.GetHdc()
302 535 $ok = [Win32DriveNative]::PrintWindow($Hwnd, $hdc, 2)
303 536 $g.ReleaseHdc($hdc)
304 - if (-not $ok) {
537 + if ($ok -and (Test-BlankBitmap $bmp)) { $ok = $false }
538 + if ($ok) {
539 + # PrintWindow renders from the raw window rect; crop back to the DWM frame
540 + # bounds so capture pixels share the coordinate space of list/click/uia.
541 + $cropX = [Math]::Max(0, $frame.Left - $raw.Left)
542 + $cropY = [Math]::Max(0, $frame.Top - $raw.Top)
543 + $cropW = [Math]::Min($w, $rawW - $cropX)
544 + $cropH = [Math]::Min($h, $rawH - $cropY)
545 + $image = $bmp.Clone([Drawing.Rectangle]::new($cropX, $cropY, $cropW, $cropH), $bmp.PixelFormat)
546 + } else {
305 547 $used = 'screen-crop'
306 - $g.CopyFromScreen($r.Left, $r.Top, 0, 0, $bmp.Size)
548 + $image = [Drawing.Bitmap]::new($w, $h)
549 + $shotGraphics = [Drawing.Graphics]::FromImage($image)
550 + try { $shotGraphics.CopyFromScreen($frame.Left, $frame.Top, 0, 0, $image.Size) } finally { $shotGraphics.Dispose() }
308 - $path = Save-Bitmap $bmp $Out
309 - [pscustomobject] [ordered] @{ ok = $true; path = $path; hwnd = $Hwnd.ToInt64(); x = $r.Left; y = $r.Top; width = $w; height = $h; mode = $used }
552 + $path = Save-Bitmap $image $Out
553 + [pscustomobject] [ordered] @{ ok = $true; path = $path; hwnd = $Hwnd.ToInt64(); x = $frame.Left; y = $frame.Top; width = $image.Width; height = $image.Height; mode = $used }
310 554 } finally {
311 555 $g.Dispose(); $bmp.Dispose()
556 + if ($image) { $image.Dispose() }
560 +function Rect-Int($Value) {
561 + $d = [double] $Value
562 + if ([double]::IsNaN($d) -or [double]::IsInfinity($d)) { return $null }
563 + [int] [Math]::Round($d)
315 566 function Dump-Uia($Element, [int] $Depth, [int] $MaxDepth) {
316 567 if ($null -eq $Element) { return $null }
317 - $rect = $Element.Current.BoundingRectangle
318 568 $item = [ordered] @{
569 + name = $null
570 + automationId = $null
571 + className = $null
572 + controlType = $null
573 + x = $null
574 + y = $null
575 + width = $null
576 + height = $null
577 + truncated = $false
578 + error = $null
579 + children = @()
581 + try {
582 + $current = $Element.Current
583 + $rect = $current.BoundingRectangle
584 + $item.name = $current.Name
585 + $item.automationId = $current.AutomationId
586 + $item.className = $current.ClassName
587 + $item.controlType = $current.ControlType.ProgrammaticName
588 + $item.x = Rect-Int $rect.X
589 + $item.y = Rect-Int $rect.Y
590 + $item.width = Rect-Int $rect.Width
591 + $item.height = Rect-Int $rect.Height
592 + } catch {
593 + $item.error = $_.Exception.Message
594 + return [pscustomobject] $item
596 + if ($Depth -lt $MaxDepth) {
597 + try {
598 + $children = $Element.FindAll([Windows.Automation.TreeScope]::Children, [Windows.Automation.Condition]::TrueCondition)
599 + foreach ($child in $children) { $item.children += Dump-Uia $child ($Depth + 1) $MaxDepth }
600 + } catch {
601 + $item.error = $_.Exception.Message
603 + } else {
604 + try {
605 + if ($null -ne $Element.FindFirst([Windows.Automation.TreeScope]::Children, [Windows.Automation.Condition]::TrueCondition)) { $item.truncated = $true }
606 + } catch {}
608 + [pscustomobject] $item
611 +function Import-Uia {
612 + Add-Type -AssemblyName UIAutomationClient,UIAutomationTypes
615 +function Get-UiaControlType([string] $Name) {
616 + $field = [Windows.Automation.ControlType].GetField($Name, 'Public,Static,IgnoreCase')
617 + if ($null -eq $field) { throw "Unknown control type: $Name" }
618 + $field.GetValue($null)
621 +function Describe-UiaElement($Element) {
622 + $rect = $Element.Current.BoundingRectangle
623 + [pscustomobject] [ordered] @{
319 624 name = $Element.Current.Name
320 625 automationId = $Element.Current.AutomationId
321 626 className = $Element.Current.ClassName
322 627 controlType = $Element.Current.ControlType.ProgrammaticName
323 - x = [int] $rect.X
324 - y = [int] $rect.Y
325 - width = [int] $rect.Width
326 - height = [int] $rect.Height
327 - children = @()
628 + x = Rect-Int $rect.X
629 + y = Rect-Int $rect.Y
630 + width = Rect-Int $rect.Width
631 + height = Rect-Int $rect.Height
329 - if ($Depth -lt $MaxDepth) {
330 - $children = $Element.FindAll([Windows.Automation.TreeScope]::Children, [Windows.Automation.Condition]::TrueCondition)
331 - foreach ($child in $children) { $item.children += Dump-Uia $child ($Depth + 1) $MaxDepth }
635 +# Element addressing for the focus-free action commands: any combination of
636 +# -Name, -AutomationId, -ClassName, -ControlType, disambiguated by -Index.
637 +function Resolve-UiaElement($Opts) {
638 + Import-Uia
639 + $root = if (Has-Selector $Opts) {
640 + [Windows.Automation.AutomationElement]::FromHandle((Resolve-Window $Opts))
641 + } else {
642 + throw 'element commands need a window selector: -Hwnd, -Process, or -TitleContains'
644 + if (-not ($Opts.ContainsKey('Name') -or $Opts.ContainsKey('AutomationId') -or $Opts.ContainsKey('ClassName') -or $Opts.ContainsKey('ControlType'))) {
645 + throw 'element commands need -Name, -AutomationId, -ClassName, or -ControlType'
647 + # ControlType narrows the tree walk; the string filters are wildcards, because
648 + # bridged providers generate volatile class names and automation ids.
649 + $condition = if ($Opts.ContainsKey('ControlType')) {
650 + New-Object Windows.Automation.PropertyCondition ([Windows.Automation.AutomationElement]::ControlTypeProperty), (Get-UiaControlType (Str-Opt $Opts 'ControlType'))
651 + } else {
652 + [Windows.Automation.Condition]::TrueCondition
654 + $found = @($root.FindAll([Windows.Automation.TreeScope]::Descendants, $condition))
655 + foreach ($filter in @(@('Name','Name'), @('AutomationId','AutomationId'), @('ClassName','ClassName'))) {
656 + if (-not $Opts.ContainsKey($filter[0])) { continue }
657 + $pattern = Str-Opt $Opts $filter[0]
658 + $property = $filter[1]
659 + $found = @($found | Where-Object { [string] $_.Current.$property -like $pattern })
661 + if ($found.Count -eq 0) { throw 'No matching element' }
662 + if ($Opts.ContainsKey('Index')) {
663 + $index = Int-Opt $Opts 'Index'
664 + if ($index -lt 0 -or $index -ge $found.Count) { throw ('Index out of range: ' + $found.Count + ' matching elements') }
665 + return $found[$index]
667 + if ($found.Count -gt 1) {
668 + $preview = @($found | Select-Object -First 8 | ForEach-Object { Describe-UiaElement $_ })
669 + throw ('Ambiguous element, pass -Index: ' + ($preview | ConvertTo-Json -Compress))
671 + $found[0]
674 +# Acts through accessibility patterns: no activation, no pointer, no keyboard,
675 +# so the user's foreground window and cursor stay untouched.
676 +function Invoke-UiaElement($Element) {
677 + $pattern = $null
678 + if ($Element.TryGetCurrentPattern([Windows.Automation.InvokePattern]::Pattern, [ref] $pattern)) { $pattern.Invoke(); return 'Invoke' }
679 + if ($Element.TryGetCurrentPattern([Windows.Automation.TogglePattern]::Pattern, [ref] $pattern)) { $pattern.Toggle(); return 'Toggle' }
680 + if ($Element.TryGetCurrentPattern([Windows.Automation.SelectionItemPattern]::Pattern, [ref] $pattern)) { $pattern.Select(); return 'SelectionItem' }
681 + if ($Element.TryGetCurrentPattern([Windows.Automation.ExpandCollapsePattern]::Pattern, [ref] $pattern)) {
682 + if ($pattern.Current.ExpandCollapseState -eq [Windows.Automation.ExpandCollapseState]::Expanded) { $pattern.Collapse(); return 'Collapse' }
683 + $pattern.Expand(); return 'Expand'
685 + # Apps that only ship MSAA (WinForms, old Win32) surface as pattern-less panes
686 + # backed by a real HWND; both fallbacks below still avoid focus and pointer.
687 + $native = Get-UiaNativeHandle $Element
688 + if ($native -ne [IntPtr]::Zero) {
689 + if (Invoke-MsaaDefaultAction $native) { return 'MsaaDoDefaultAction' }
690 + if ((Get-WindowClassName $native) -match 'BUTTON') {
691 + [void] [Win32DriveNative]::PostMessage($native, 0x00F5, [IntPtr]::Zero, [IntPtr]::Zero)
692 + return 'BM_CLICK'
695 + throw 'Element supports no invokable pattern; use click -Pointer instead'
698 +function Set-UiaElementValue($Element, [string] $Value) {
699 + $pattern = $null
700 + if ($Element.TryGetCurrentPattern([Windows.Automation.ValuePattern]::Pattern, [ref] $pattern)) {
701 + if ($pattern.Current.IsReadOnly) { throw 'Element value is read-only' }
702 + $pattern.SetValue($Value)
703 + return 'Value'
705 + $native = Get-UiaNativeHandle $Element
706 + if ($native -ne [IntPtr]::Zero -and (Send-WindowText $native $Value)) { return 'WM_CHAR' }
707 + throw 'Element exposes no value pattern; use type -Pointer instead'
710 +# Posted characters reach a native edit control without focus and still raise
711 +# the app's change notifications, which WM_SETTEXT alone suppresses.
712 +function Send-WindowText([IntPtr] $Hwnd, [string] $Value) {
713 + $result = [UIntPtr]::Zero
714 + if ([Win32DriveNative]::SendMessageTimeoutPtr($Hwnd, 0x00B1, [UIntPtr]::Zero, [IntPtr] (-1), 2, 2000, [ref] $result) -eq [IntPtr]::Zero) { return $false }
715 + if ($Value.Length -eq 0) {
716 + [void] [Win32DriveNative]::PostMessage($Hwnd, 0x0102, [IntPtr] 8, [IntPtr] 1)
718 + foreach ($ch in $Value.ToCharArray()) {
719 + if ($ch -eq "`r") { continue }
720 + $code = if ($ch -eq "`n") { 13 } else { [int] $ch }
721 + [void] [Win32DriveNative]::PostMessage($Hwnd, 0x0102, [IntPtr] $code, [IntPtr] 1)
723 + # Posted messages are processed by the target's own loop, so confirm by polling.
724 + $expected = $Value.Replace("`r", '')
725 + $deadline = (Get-Date).AddMilliseconds(1200)
726 + do {
727 + Start-Sleep -Milliseconds 50
728 + if ((Get-RemoteWindowText $Hwnd).Replace("`r", '') -eq $expected) { return $true }
729 + } while ((Get-Date) -lt $deadline)
730 + $false
733 +# GetWindowText does not cross process boundaries for control text; WM_GETTEXT does.
734 +function Get-RemoteWindowText([IntPtr] $Hwnd) {
735 + $buffer = [Text.StringBuilder]::new(8192)
736 + $result = [UIntPtr]::Zero
737 + [void] [Win32DriveNative]::SendMessageTimeoutText($Hwnd, 0x000D, [UIntPtr]::new([uint32] $buffer.Capacity), $buffer, 2, 2000, [ref] $result)
738 + $buffer.ToString()
741 +function Get-UiaNativeHandle($Element) {
742 + try { [IntPtr] $Element.Current.NativeWindowHandle } catch { [IntPtr]::Zero }
745 +function Get-WindowClassName([IntPtr] $Hwnd) {
746 + $sb = [Text.StringBuilder]::new(256)
747 + [void] [Win32DriveNative]::GetClassName($Hwnd, $sb, $sb.Capacity)
748 + $sb.ToString()
751 +function Invoke-MsaaDefaultAction([IntPtr] $Hwnd) {
752 + $iid = [guid] '618736e0-3c3d-11cf-810c-00aa00389b71'
753 + $accessible = $null
754 + try {
755 + if ([Win32DriveNative]::AccessibleObjectFromWindow($Hwnd, 0xFFFFFFFC, [ref] $iid, [ref] $accessible) -ne 0) { return $false }
756 + if ($null -eq $accessible) { return $false }
757 + [void] $accessible.GetType().InvokeMember('accDoDefaultAction', 'InvokeMethod', $null, $accessible, @([int] 0))
758 + $true
759 + } catch {
760 + $false
333 - [pscustomobject] $item
336 764 function Escape-SendKeysText([string] $Text) {
356 784 [pscustomobject] [ordered] @{
357 785 ok = $true
358 786 runtime = 'Windows PowerShell 5.1+'
359 - coordinates = 'screen pixels; when -Hwnd and -X/-Y are used for click, X/Y are window-relative'
787 + dpiAwareness = $script:win32DriveDpi
788 + coordinates = 'screen pixels; with a window selector, click -X/-Y are relative to the DWM frame bounds reported by list and shot'
360 789 racingGuard = 'racing commands fade a 16px red border/ring, wait for user idle, then act'
790 + focus = 'uia-invoke and uia-set act without focus, pointer, or keyboard; click/type/key focus the target after the racing guard and verify it, where require uses activation APIs only, auto adds a caption click and needs -Pointer, and skip does not focus'
791 + pointerConsent = 'synthetic mouse input requires an explicit -Pointer flag'
792 + globalOptions = '-IdleMs n (default 800) and -TimeoutMs n (default 10000) tune the racing guard'
361 793 commands = [ordered] @{
362 794 help = [ordered] @{ racing = $false; usage = 'help' }
363 795 list = [ordered] @{ racing = $false; usage = 'list' }
364 796 shot = [ordered] @{ racing = $false; usage = 'shot [-Hwnd n|-Process p -TitleContains t|-X x -Y y -Width w -Height h] [-Out file.png]' }
365 797 pixel = [ordered] @{ racing = $false; usage = 'pixel -X x -Y y' }
366 798 uia = [ordered] @{ racing = $false; usage = 'uia [-Hwnd n|-Process p|-TitleContains t] [-Depth n]' }
799 + 'uia-invoke' = [ordered] @{ racing = $true; usage = 'uia-invoke -Hwnd n|-Process p|-TitleContains t [-Name n] [-AutomationId a] [-ClassName c] [-ControlType t] [-Index i]' }
800 + 'uia-set' = [ordered] @{ racing = $true; usage = 'uia-set -Hwnd n|-Process p|-TitleContains t -Value text [-Name n] [-AutomationId a] [-ClassName c] [-ControlType t] [-Index i]' }
367 801 cursor = [ordered] @{ racing = $false; usage = 'cursor' }
802 + focus = [ordered] @{ racing = $false; usage = 'focus' }
368 803 idle = [ordered] @{ racing = $false; usage = 'idle' }
369 804 clipboard = [ordered] @{ racing = $null; usage = 'clipboard | clipboard -Set text' }
370 - theme = [ordered] @{ racing = $true; usage = 'theme | theme -Mode dark|light [-Scope apps|system|both]' }
805 + theme = [ordered] @{ racing = $true; usage = 'theme | theme -Mode dark|light [-Scope apps|system|both] [-Refresh broadcast|full]' }
371 806 overlay = [ordered] @{ racing = $false; usage = 'overlay [-X x -Y y] [-DurationMs ms]' }
372 - click = [ordered] @{ racing = $true; usage = 'click [-Hwnd n|-Process p|-TitleContains t] -X x -Y y [-Button left|right] [-Count n]' }
373 - type = [ordered] @{ racing = $true; usage = 'type [-Hwnd n|-Process p|-TitleContains t] -Text text' }
374 - key = [ordered] @{ racing = $true; usage = 'key [-Hwnd n|-Process p|-TitleContains t] -Keys "^s"' }
375 - window = [ordered] @{ racing = $true; usage = 'window -Action move|min|max|restore|close -Hwnd n [-X x -Y y -Width w -Height h]' }
807 + click = [ordered] @{ racing = $true; usage = 'click [-Hwnd n|-Process p|-TitleContains t] [-X x -Y y] [-Button left|right] [-Count n] [-Focus auto|require|skip] [-Cursor restore|keep]' }
808 + type = [ordered] @{ racing = $true; usage = 'type [-Hwnd n|-Process p|-TitleContains t] -Text text [-Focus auto|require|skip] [-Method unicode|sendkeys]' }
809 + key = [ordered] @{ racing = $true; usage = 'key [-Hwnd n|-Process p|-TitleContains t] -Keys "^s" [-Focus auto|require|skip]' }
810 + window = [ordered] @{ racing = $true; usage = 'window -Action move|min|max|restore|close [-Hwnd n|-Process p|-TitleContains t] [-X x -Y y -Width w -Height h]' }
383 818 'help' { return Show-Help }
384 819 'list' { return [pscustomobject] [ordered] @{ ok = $true; windows = @(Get-Windows) } }
385 820 'idle' { return [pscustomobject] [ordered] @{ ok = $true; idleMs = Get-IdleMs } }
821 + 'focus' { return (Get-ForegroundInfo) | Add-Member -PassThru -NotePropertyName ok -NotePropertyValue $true }
386 822 'cursor' {
387 823 $p = New-Object Win32DriveNative+POINT
388 824 [void] [Win32DriveNative]::GetCursorPos([ref] $p)
401 837 'shot' {
402 838 $out = Str-Opt $opts 'Out'
403 - if ($opts.ContainsKey('Hwnd') -or $opts.ContainsKey('Process') -or $opts.ContainsKey('TitleContains')) { return Capture-Window (Resolve-Window $opts) $out }
839 + if (Has-Selector $opts) { return Capture-Window (Resolve-Window $opts) $out }
404 840 $screen = [System.Windows.Forms.SystemInformation]::VirtualScreen
405 841 $x = Int-Opt $opts 'X' $screen.Left
406 842 $y = Int-Opt $opts 'Y' $screen.Top
408 844 $h = Int-Opt $opts 'Height' $screen.Height
409 845 return Capture-Region $x $y $w $h $out
847 + 'uia-invoke' {
848 + $element = Resolve-UiaElement $opts
849 + $describe = Describe-UiaElement $element
850 + Invoke-RacingGuard $opts $describe.x $describe.y
851 + $pattern = Invoke-UiaElement $element
852 + return [pscustomobject] [ordered] @{ ok = $true; pattern = $pattern; element = $describe; foreground = (Get-ForegroundInfo) }
854 + 'uia-set' {
855 + if (-not $opts.ContainsKey('Value')) { throw 'uia-set needs -Value' }
856 + $element = Resolve-UiaElement $opts
857 + $describe = Describe-UiaElement $element
858 + Invoke-RacingGuard $opts $describe.x $describe.y
859 + $pattern = Set-UiaElementValue $element (Str-Opt $opts 'Value')
860 + return [pscustomobject] [ordered] @{ ok = $true; pattern = $pattern; element = $describe; foreground = (Get-ForegroundInfo) }
411 862 'uia' {
412 - Add-Type -AssemblyName UIAutomationClient,UIAutomationTypes
863 + Import-Uia
413 864 $depth = Int-Opt $opts 'Depth' 2
414 - if ($opts.ContainsKey('Hwnd') -or $opts.ContainsKey('Process') -or $opts.ContainsKey('TitleContains')) {
865 + if (Has-Selector $opts) {
415 866 $el = [Windows.Automation.AutomationElement]::FromHandle((Resolve-Window $opts))
416 867 } else {
417 868 $el = [Windows.Automation.AutomationElement]::FocusedElement
429 880 'theme' {
430 881 if (-not $opts.ContainsKey('Mode')) { return Get-Theme }
431 882 Invoke-RacingGuard $opts
432 - return Set-Theme (Str-Opt $opts 'Mode') (Str-Opt $opts 'Scope' 'both')
883 + return Set-Theme (Str-Opt $opts 'Mode') (Str-Opt $opts 'Scope' 'both') (Str-Opt $opts 'Refresh' 'broadcast')
434 885 'click' {
886 + if (-not $opts.ContainsKey('Pointer')) { throw 'click injects pointer input: pass -Pointer to allow it, or use uia-invoke' }
435 887 $button = (Str-Opt $opts 'Button' 'left').ToLowerInvariant()
436 888 $count = Int-Opt $opts 'Count' 1
889 + $focus = Get-FocusMode $opts
890 + $cursorMode = (Str-Opt $opts 'Cursor' 'restore').ToLowerInvariant()
891 + if (@('restore','keep') -notcontains $cursorMode) { throw 'Cursor must be restore or keep' }
437 892 $x = Int-Opt $opts 'X'
438 893 $y = Int-Opt $opts 'Y'
439 894 $hwnd = $null
440 - if ($opts.ContainsKey('Hwnd') -or $opts.ContainsKey('Process') -or $opts.ContainsKey('TitleContains')) {
895 + if (Has-Selector $opts) {
441 896 $hwnd = Resolve-Window $opts
442 897 $r = Get-Rect $hwnd
443 - [void] [Win32DriveNative]::SetForegroundWindow($hwnd)
444 898 if ($x -eq $null) { $x = [int] (($r.Left + $r.Right) / 2) } else { $x = $r.Left + $x }
445 899 if ($y -eq $null) { $y = [int] (($r.Top + $r.Bottom) / 2) } else { $y = $r.Top + $y }
447 901 if ($x -eq $null -or $y -eq $null) { throw 'click needs -X and -Y unless targeting a window center' }
902 + $origin = New-Object Win32DriveNative+POINT
903 + [void] [Win32DriveNative]::GetCursorPos([ref] $origin)
904 + # Focus after the guard: activation is only granted during input gaps.
448 905 Invoke-RacingGuard $opts $x $y
449 - [void] [Win32DriveNative]::SetCursorPos($x, $y)
450 - $down = if ($button -eq 'right') { 0x0008 } else { 0x0002 }
451 - $up = if ($button -eq 'right') { 0x0010 } else { 0x0004 }
452 - for ($i = 0; $i -lt $count; $i++) {
453 - [Win32DriveNative]::mouse_event($down, 0, 0, 0, [UIntPtr]::Zero)
454 - Start-Sleep -Milliseconds 45
455 - [Win32DriveNative]::mouse_event($up, 0, 0, 0, [UIntPtr]::Zero)
456 - Start-Sleep -Milliseconds 80
457 - }
458 - return [pscustomobject] [ordered] @{ ok = $true; x = $x; y = $y; button = $button; count = $count }
906 + if ($hwnd -ne $null -and $focus -ne 'skip') { Set-Foreground $hwnd $focus }
907 + Invoke-PointerClick $x $y $button $count $false
908 + if ($cursorMode -eq 'restore') { [void] [Win32DriveNative]::SetCursorPos($origin.X, $origin.Y) }
909 + return [pscustomobject] [ordered] @{ ok = $true; x = $x; y = $y; button = $button; count = $count; focus = $focus; cursor = $cursorMode; foreground = (Get-ForegroundInfo) }
460 911 'type' {
461 912 $text = Str-Opt $opts 'Text'
462 913 if ($null -eq $text) { throw 'type needs -Text' }
463 - if ($opts.ContainsKey('Hwnd') -or $opts.ContainsKey('Process') -or $opts.ContainsKey('TitleContains')) { [void] [Win32DriveNative]::SetForegroundWindow((Resolve-Window $opts)) }
914 + $focus = Get-FocusMode $opts
915 + $target = if (Has-Selector $opts) { Resolve-Window $opts } else { $null }
916 + $defaultMethod = if ([IntPtr]::Size -eq 8) { 'unicode' } else { 'sendkeys' }
917 + $method = (Str-Opt $opts 'Method' $defaultMethod).ToLowerInvariant()
918 + if (@('unicode','sendkeys') -notcontains $method) { throw 'Method must be unicode or sendkeys' }
464 919 Invoke-RacingGuard $opts
465 - [Windows.Forms.SendKeys]::SendWait((Escape-SendKeysText $text))
466 - return [pscustomobject] [ordered] @{ ok = $true; chars = $text.Length }
920 + if ($target -ne $null -and $focus -ne 'skip') { Set-Foreground $target $focus }
921 + if ($method -eq 'unicode') { [void] [Win32DriveNative]::TypeUnicode($text) }
922 + else { [Windows.Forms.SendKeys]::SendWait((Escape-SendKeysText $text)) }
923 + return [pscustomobject] [ordered] @{ ok = $true; chars = $text.Length; method = $method; focus = $focus; foreground = (Get-ForegroundInfo) }
468 925 'key' {
469 926 $keySpec = Str-Opt $opts 'Keys'
470 927 if (-not $keySpec) { throw 'key needs -Keys' }
471 - if ($opts.ContainsKey('Hwnd') -or $opts.ContainsKey('Process') -or $opts.ContainsKey('TitleContains')) { [void] [Win32DriveNative]::SetForegroundWindow((Resolve-Window $opts)) }
928 + $focus = Get-FocusMode $opts
929 + $target = if (Has-Selector $opts) { Resolve-Window $opts } else { $null }
472 930 Invoke-RacingGuard $opts
931 + if ($target -ne $null -and $focus -ne 'skip') { Set-Foreground $target $focus }
473 932 [Windows.Forms.SendKeys]::SendWait($keySpec)
474 - return [pscustomobject] [ordered] @{ ok = $true; keys = $keySpec }
933 + return [pscustomobject] [ordered] @{ ok = $true; keys = $keySpec; focus = $focus; foreground = (Get-ForegroundInfo) }
476 935 'window' {
477 936 $action = (Str-Opt $opts 'Action').ToLowerInvariant()

pi/agent/skills/win32-drive/scripts/win32-drive.test.ps1

Modified
1 +# -IncludeTheme also exercises theme writes. Those broadcast WM_SETTINGCHANGE to
2 +# every window on the desktop and have been observed to wedge apps that react to
3 +# it, so they stay opt-in.
4 +param([switch] $IncludeTheme)
1 6 $ErrorActionPreference = 'Stop'
2 7 $script = Join-Path $PSScriptRoot 'win32-drive.ps1'
3 8 if (-not (Test-Path $script)) { throw "Missing script: $script" }
9 +Add-Type -AssemblyName System.Drawing
5 11 function Invoke-Raw($arguments, [switch] $AllowFail) {
6 12 $raw = & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $script @arguments
18 24 Assert ($r.Json.ok -eq $false) 'failure JSON must have ok=false'
19 25 Assert ($r.Json.error -match $pattern) "error '$($r.Json.error)' does not match '$pattern'"
27 +function Wait-Title($hwnd, [string] $Expected, [int] $TimeoutMs = 4000) {
28 + $deadline = (Get-Date).AddMilliseconds($TimeoutMs)
29 + do {
30 + $win = @(Invoke-Json @('list')).windows | Where-Object hwnd -eq $hwnd | Select-Object -First 1
31 + if ($win -and $win.title -eq $Expected) { return $win.title }
32 + Start-Sleep -Milliseconds 120
33 + } while ((Get-Date) -lt $deadline)
34 + throw "window title never became '$Expected' (last: '$($win.title)')"
21 36 function Start-TestWindow($title) {
22 37 $app = Join-Path $env:TEMP ("win32-drive-app-" + [guid]::NewGuid().ToString('N') + '.ps1')
24 39 `$ErrorActionPreference = 'Stop'
25 40 Add-Type -AssemblyName System.Windows.Forms,System.Drawing
41 +[Windows.Forms.Application]::EnableVisualStyles()
26 42 `$form = New-Object Windows.Forms.Form
27 43 `$form.Text = '$title'
28 44 `$form.StartPosition = 'Manual'
29 45 `$form.SetBounds(80,80,420,260)
46 +`$form.BackColor = [Drawing.Color]::FromArgb(0,120,215)
30 47 `$box = New-Object Windows.Forms.TextBox
31 48 `$box.Multiline = `$true
32 49 `$box.Name = 'InputBox'
36 53 `$button.Text = 'ClickMe'
37 54 `$button.SetBounds(20,175,100,32)
38 55 `$button.Add_Click({ `$form.Text = '$title clicked' })
56 +`$box.Add_TextChanged({ `$form.Text = '$title text:' + `$box.Text })
39 57 `$form.Controls.Add(`$box)
40 58 `$form.Controls.Add(`$button)
41 59 `$form.Add_Shown({ `$box.Focus() })
48 66 $wins = @(Invoke-Json @('list')).windows | Where-Object { $_.pid -eq $p.Id -and $_.title -like "$title*" }
49 67 } while ($wins.Count -eq 0 -and (Get-Date) -lt $deadline)
50 68 if ($wins.Count -eq 0) { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue; throw 'test window did not appear' }
51 - [pscustomobject]@{ Process = $p; Script = $app; Window = $wins[0] }
69 + Start-Sleep -Milliseconds 500
70 + [pscustomobject]@{ Process = $p; Script = $app; Window = $wins[0]; Title = $title }
54 73 $created = @()
57 76 try { $originalClipboard = (Invoke-Json @('clipboard')).text } catch { $originalClipboard = $null }
59 78 $help = Invoke-Json @('help')
60 - foreach ($cmd in 'help','list','shot','pixel','uia','cursor','idle','clipboard','overlay','click','type','key','window','theme') {
79 + foreach ($cmd in 'help','list','shot','pixel','uia','uia-invoke','uia-set','cursor','focus','idle','clipboard','overlay','click','type','key','window','theme') {
61 80 Assert ($help.commands.PSObject.Properties.Name -contains $cmd) "help missing $cmd"
63 - foreach ($cmd in 'click','type','key','window','theme') { Assert ($help.commands.$cmd.racing -eq $true) "$cmd must be racing" }
64 - foreach ($cmd in 'list','shot','pixel','uia','cursor','idle','overlay') { Assert ($help.commands.$cmd.racing -eq $false) "$cmd must be nonracing" }
82 + foreach ($cmd in 'click','type','key','window','theme','uia-invoke','uia-set') { Assert ($help.commands.$cmd.racing -eq $true) "$cmd must be racing" }
83 + foreach ($cmd in 'list','shot','pixel','uia','cursor','focus','idle','overlay') { Assert ($help.commands.$cmd.racing -eq $false) "$cmd must be nonracing" }
84 + Assert ($help.dpiAwareness -in @('per-monitor-v2','per-monitor','system','unaware')) 'help must report dpi awareness'
85 + Assert ($help.dpiAwareness -ne 'unaware') 'process must be dpi aware'
66 87 $list = Invoke-Json @('list')
67 88 Assert ($list.windows.Count -gt 0) 'list should return visible windows'
90 111 $winShot = Invoke-Json @('shot','-Hwnd',$hwnd,'-Out',$winShotPath)
91 112 Assert-File $winShot.path
92 113 Assert ($winShot.hwnd -eq $app.Window.hwnd -and $winShot.width -gt 0 -and $winShot.height -gt 0) 'window shot metadata wrong'
94 - $byTitle = Invoke-Json @('shot','-Process','powershell','-TitleContains',$app.Window.title,'-Out',(Join-Path $env:TEMP ("win32-drive-test-title-" + [guid]::NewGuid().ToString('N') + '.png')))
95 - $created += $byTitle.path
96 - Assert-File $byTitle.path
114 + Assert ($winShot.width -eq $app.Window.width -and $winShot.height -eq $app.Window.height) 'window shot must match the frame bounds reported by list'
98 116 Assert ((Invoke-Json @('uia','-Depth','0')).ok) 'focused uia failed'
99 117 $uia = Invoke-Json @('uia','-Hwnd',$hwnd,'-Depth','1')
100 118 Assert ($uia.tree.name -like 'Win32DriveTest-*') 'uia root title wrong'
101 119 Assert ($uia.tree.children.Count -gt 0) 'uia children missing'
120 + Assert ($null -eq $uia.tree.error) 'uia root must not carry an error'
121 + Assert ((Invoke-Json @('uia','-Hwnd',$hwnd,'-Depth','0')).tree.truncated -eq $true) 'uia must flag truncated subtrees'
123 + # Capture origin must be the frame origin reported by list/shot: a control's
124 + # screen rect minus that origin must hit the same control inside the image.
125 + # This catches the PrintWindow shadow offset without depending on z-order.
126 + $edge = $uia.tree.children | Where-Object { $_.name -ne 'ClickMe' -and $_.width -gt 200 } | Select-Object -First 1
127 + Assert ($null -ne $edge) 'uia did not expose the text box'
128 + $geometryShotPath = Join-Path $env:TEMP ("win32-drive-test-geometry-" + [guid]::NewGuid().ToString('N') + '.png')
129 + $created += $geometryShotPath
130 + $geometryShot = Invoke-Json @('shot','-Hwnd',$hwnd,'-Out',$geometryShotPath)
131 + $bitmap = [Drawing.Bitmap]::FromFile($geometryShot.path)
132 + try {
133 + $inside = $bitmap.GetPixel([int]($edge.x - $geometryShot.x + 8), [int]($edge.y - $geometryShot.y + 8))
134 + $outside = $bitmap.GetPixel([int]($edge.x - $geometryShot.x - 4), [int]($edge.y - $geometryShot.y - 4))
135 + } finally { $bitmap.Dispose() }
136 + Assert ($inside.R -gt 200 -and $inside.G -gt 200 -and $inside.B -gt 200) "capture offset: inside text box is $($inside.R),$($inside.G),$($inside.B), expected white (mode=$($geometryShot.mode) shot=$($geometryShot.x),$($geometryShot.y) $($geometryShot.width)x$($geometryShot.height) edge=$($edge.x),$($edge.y) $($edge.width)x$($edge.height) file=$($geometryShot.path))"
137 + Assert ($outside.B -gt $outside.R) "capture offset: outside text box is $($outside.R),$($outside.G),$($outside.B), expected the blue form background"
139 + # Accessibility actions must change the app without touching focus or pointer.
140 + $foregroundBefore = Invoke-Json @('focus')
141 + $invoked = Invoke-Json @('uia-invoke','-Hwnd',$hwnd,'-Name','ClickMe','-IdleMs','0','-TimeoutMs','1000')
142 + Assert ($invoked.pattern -in @('Invoke','MsaaDoDefaultAction','BM_CLICK')) "unexpected invoke pattern: $($invoked.pattern)"
143 + Wait-Title $app.Window.hwnd "$($app.Title) clicked" | Out-Null
144 + $uiaText = 'uia-set-' + [guid]::NewGuid().ToString('N')
145 + $valued = Invoke-Json @('uia-set','-Hwnd',$hwnd,'-ClassName','*EDIT*','-Value',$uiaText,'-IdleMs','0','-TimeoutMs','1000')
146 + Assert ($valued.pattern -in @('Value','WM_CHAR')) "unexpected value pattern: $($valued.pattern)"
147 + Wait-Title $app.Window.hwnd "$($app.Title) text:$uiaText" | Out-Null
148 + Assert ((Invoke-Json @('focus')).hwnd -eq $foregroundBefore.hwnd) 'accessibility actions must not change the foreground window'
149 + Assert-Err @('uia-invoke','-Hwnd',$hwnd,'-IdleMs','0','-TimeoutMs','1000') 'need -Name, -AutomationId, -ClassName, or -ControlType'
150 + Assert-Err @('uia-invoke','-Name','ClickMe','-IdleMs','0','-TimeoutMs','1000') 'need a window selector'
151 + Assert-Err @('uia-set','-Hwnd',$hwnd,'-ClassName','*EDIT*','-IdleMs','0','-TimeoutMs','1000') 'uia-set needs -Value'
152 + Assert-Err @('uia-invoke','-Hwnd',$hwnd,'-Name','definitely-no-such-control','-IdleMs','0','-TimeoutMs','1000') 'No matching element'
154 + # pointer input needs explicit consent
155 + Assert-Err @('click','-Hwnd',$hwnd,'-IdleMs','0','-TimeoutMs','1000') 'pass -Pointer'
156 + Assert-Err @('type','-Hwnd',$hwnd,'-Text','x','-Focus','auto','-IdleMs','0','-TimeoutMs','1000') 'pass -Pointer'
103 158 $theme = Invoke-Json @('theme')
104 159 Assert ($theme.apps -in @('dark','light') -and $theme.system -in @('dark','light')) 'theme read failed'
105 - Assert ((Invoke-Json @('theme','-Mode',$theme.apps,'-Scope','apps','-IdleMs','0','-TimeoutMs','1000')).apps -eq $theme.apps) 'theme apps set failed'
106 - Assert ((Invoke-Json @('theme','-Mode',$theme.system,'-Scope','system','-IdleMs','0','-TimeoutMs','1000')).system -eq $theme.system) 'theme system set failed'
107 160 Assert-Err @('theme','-Mode','blue','-IdleMs','0','-TimeoutMs','1000') 'Mode must be dark or light'
108 161 Assert-Err @('theme','-Mode',$theme.apps,'-Scope','wat','-IdleMs','0','-TimeoutMs','1000') 'Scope must be apps, system, or both'
162 + Assert-Err @('theme','-Mode',$theme.apps,'-Refresh','wat','-IdleMs','0','-TimeoutMs','1000') 'Refresh must be broadcast or full'
163 + if ($IncludeTheme) {
164 + $themeSet = Invoke-Json @('theme','-Mode',$theme.apps,'-Scope','apps','-IdleMs','0','-TimeoutMs','1000')
165 + Assert ($themeSet.apps -eq $theme.apps) 'theme apps set failed'
166 + Assert ($themeSet.refresh -eq 'broadcast') 'theme must default to the broadcast refresh'
167 + Assert ($themeSet.previous.apps -in @('dark','light')) 'theme set must report previous values'
168 + Assert ((Invoke-Json @('theme','-Mode',$theme.system,'-Scope','system','-IdleMs','0','-TimeoutMs','1000')).system -eq $theme.system) 'theme system set failed'
169 + } else {
170 + Write-Host 'skipping theme writes (pass -IncludeTheme to exercise them)'
110 173 $clipValue = 'win32-drive-clip-' + [guid]::NewGuid().ToString('N')
111 174 Assert ((Invoke-Json @('clipboard','-Set',$clipValue,'-IdleMs','0','-TimeoutMs','1000')).ok) 'clipboard set failed'
112 175 Assert ((Invoke-Json @('clipboard')).text -eq $clipValue) 'clipboard read after set failed'
114 - Assert ((Invoke-Json @('click','-Hwnd',$hwnd,'-IdleMs','0','-TimeoutMs','1000')).ok) 'center click failed'
115 - Assert ((Invoke-Json @('click','-Hwnd',$hwnd,'-X','40','-Y','40','-IdleMs','0','-TimeoutMs','1000')).ok) 'left click failed'
116 - Assert ((Invoke-Json @('click','-Hwnd',$hwnd,'-X','42','-Y','42','-Button','right','-IdleMs','0','-TimeoutMs','1000')).ok) 'right click failed'
117 - $typed = 'abc+^%~(){}[]'
118 - Assert ((Invoke-Json @('type','-Hwnd',$hwnd,'-Text',$typed,'-IdleMs','0','-TimeoutMs','1000')).chars -eq $typed.Length) 'type failed'
119 - Assert ((Invoke-Json @('key','-Hwnd',$hwnd,'-Keys','^a','-IdleMs','0','-TimeoutMs','1000')).ok) 'key failed'
120 - Assert ((Invoke-Json @('type','-Hwnd',$hwnd,'-Text','selected','-IdleMs','0','-TimeoutMs','1000')).ok) 'second type failed'
177 + # click must land on the control, focus the target, and leave the cursor untouched
178 + $button = $uia.tree.children | Where-Object { $_.name -eq 'ClickMe' } | Select-Object -First 1
179 + Assert ($null -ne $button) 'uia did not expose the ClickMe button'
181 + $buttonX = [int]($button.x + $button.width / 2 - $winShot.x)
182 + $buttonY = [int]($button.y + $button.height / 2 - $winShot.y)
183 + $before = Invoke-Json @('cursor')
184 + $click = Invoke-Json @('click','-Hwnd',$hwnd,'-X',[string]$buttonX,'-Y',[string]$buttonY,'-Pointer','-Focus','auto','-IdleMs','0','-TimeoutMs','1000')
185 + Assert ($click.foreground.hwnd -eq $app.Window.hwnd) 'click must report the target window as foreground'
186 + Assert ($click.focus -eq 'auto' -and $click.cursor -eq 'restore') 'click focus/cursor reporting wrong'
187 + Wait-Title $app.Window.hwnd "$($app.Title) clicked" | Out-Null
188 + $after = Invoke-Json @('cursor')
189 + # Tolerates the human moving the mouse mid-run: the regression is a cursor
190 + # parked on the click target, not a cursor that simply moved.
191 + Assert (($after.x -eq $before.x -and $after.y -eq $before.y) -or $after.x -ne $click.x -or $after.y -ne $click.y) 'click must restore the cursor position'
192 + Assert ((Invoke-Json @('click','-Hwnd',$hwnd,'-X',[string]$buttonX,'-Y',[string]$buttonY,'-Pointer','-Cursor','keep','-Focus','skip','-IdleMs','0','-TimeoutMs','1000')).cursor -eq 'keep') 'click -Cursor keep failed'
193 + Assert-Err @('click','-Hwnd',$hwnd,'-Pointer','-Focus','wat','-IdleMs','0','-TimeoutMs','1000') 'Focus must be auto, require, or skip'
194 + Assert-Err @('click','-Hwnd',$hwnd,'-Pointer','-Cursor','wat','-IdleMs','0','-TimeoutMs','1000') 'Cursor must be restore or keep'
196 + # type must reach the focused control verbatim, including non-ASCII
197 + # WinForms controls surface through the MSAA bridge, so match the text box by
198 + # elimination instead of by AutomationId (which is just the raw HWND here).
199 + $textbox = $uia.tree.children | Where-Object { $_.name -ne 'ClickMe' -and $_.width -gt 200 } | Select-Object -First 1
200 + Assert ($null -ne $textbox) 'uia did not expose the text box'
201 + Assert ((Invoke-Json @('click','-Hwnd',$hwnd,'-X',[string]([int]($textbox.x + $textbox.width / 2 - $winShot.x)),'-Y',[string]([int]($textbox.y + $textbox.height / 2 - $winShot.y)),'-Pointer','-Focus','auto','-IdleMs','0','-TimeoutMs','1000')).ok) 'textbox click failed'
202 + $unicode = 'Grusse-ae-' + [char] 0x00E4 + [char] 0x20AC
203 + Assert ((Invoke-Json @('key','-Hwnd',$hwnd,'-Keys','^a','-Pointer','-Focus','auto','-IdleMs','0','-TimeoutMs','1000')).ok) 'select all before typing failed'
204 + $typed = Invoke-Json @('type','-Hwnd',$hwnd,'-Text',$unicode,'-Pointer','-Focus','auto','-IdleMs','0','-TimeoutMs','1000')
205 + Assert ($typed.chars -eq $unicode.Length) 'type failed'
206 + Assert ($typed.method -eq 'unicode') 'type must default to the unicode method on 64-bit'
207 + Assert ($typed.foreground.hwnd -eq $app.Window.hwnd) 'type must report the target window as foreground'
208 + Wait-Title $app.Window.hwnd "$($app.Title) text:$unicode" | Out-Null
210 + Assert ((Invoke-Json @('key','-Hwnd',$hwnd,'-Keys','^a','-Pointer','-Focus','auto','-IdleMs','0','-TimeoutMs','1000')).foreground.hwnd -eq $app.Window.hwnd) 'key failed'
211 + $sendkeys = 'sk+^%~(){}[]'
212 + Assert ((Invoke-Json @('type','-Hwnd',$hwnd,'-Text',$sendkeys,'-Method','sendkeys','-Pointer','-Focus','auto','-IdleMs','0','-TimeoutMs','1000')).method -eq 'sendkeys') 'type -Method sendkeys failed'
213 + Wait-Title $app.Window.hwnd "$($app.Title) text:$sendkeys" | Out-Null
214 + Assert-Err @('type','-Hwnd',$hwnd,'-Text','x','-Method','wat','-Pointer','-IdleMs','0','-TimeoutMs','1000') 'Method must be unicode or sendkeys'
216 + # focusing must fail loudly instead of driving whatever happens to be in front
217 + Assert ((Invoke-Json @('window','-Hwnd',$hwnd,'-Action','min','-IdleMs','0','-TimeoutMs','1000')).ok) 'window min failed'
218 + Start-Sleep -Milliseconds 250
219 + Assert-Err @('type','-Hwnd',$hwnd,'-Text','must-not-arrive','-Pointer','-Focus','auto','-IdleMs','0','-TimeoutMs','1000') 'minimized'
220 + Assert ((Invoke-Json @('window','-Hwnd',$hwnd,'-Action','restore','-IdleMs','0','-TimeoutMs','1000')).ok) 'window restore failed'
221 + Start-Sleep -Milliseconds 250
122 223 Assert ((Invoke-Json @('window','-Hwnd',$hwnd,'-Action','move','-X','100','-Y','100','-Width','430','-Height','270','-IdleMs','0','-TimeoutMs','1000')).ok) 'window move failed'
123 224 Start-Sleep -Milliseconds 150
135 236 Assert-Err @('shot','-Bogus','x') 'Unknown option'
136 237 Assert-Err @('shot','-X') 'Missing value'
137 238 Assert-Err @('shot','-TitleContains',('definitely-no-window-' + [guid]::NewGuid().ToString('N'))) 'No matching window'
239 + # an option value equal to the script name must not swallow the command line
240 + Assert-Err @('shot','-TitleContains','win32-drive.ps1') 'No matching window'
138 241 Assert-Err @('window','-Hwnd','999999999','-Action','move','-IdleMs','0','-TimeoutMs','1000') 'Invalid window|empty bounds|failed'
139 242 $bad = Start-TestWindow ("Win32DriveBadAction-" + [guid]::NewGuid().ToString('N'))
140 243 $created += $bad.Script