Compare commits

..
Author SHA1 Message Date
agrynco dfa2e38a0a Release KSwitcher v0.7.4
Include Google Drive sync and backups, offline help, and refreshed Settings and utilities.

Refs #84
2026-11-25 00:01:35 +02:00
agrynco 24905e8ced Group tray help and add help and coffee icons 2026-11-24 23:49:19 +02:00
agrynco b28a1f2e4d Add a searchable offline help window 2026-11-24 23:39:11 +02:00
agrynco fde74c1a51 Distinguish utility window icons and add a tray donation link 2026-11-24 23:31:35 +02:00
agrynco 81fbe6a216 Style the screenshot editor like Settings 2026-11-24 23:19:34 +02:00
agrynco f1e5b2b772 Style clipboard history like Settings 2026-11-24 23:14:13 +02:00
agrynco e9e8b2099e Align the computer settings action rows 2026-11-24 23:01:32 +02:00
agrynco dbb1fe166e Give the device list and monitor layout more room 2026-11-24 22:57:49 +02:00
agrynco 98de2dc010 Embed image text recognition under Clipboard settings 2026-11-24 22:49:17 +02:00
agrynco 696f48209d Add Drive backup history and make Settings editors resize
Refs #84
2026-11-24 22:42:30 +02:00
agrynco 5fae129ec0 Anchor Google Drive actions below the resizable status
Refs #84
2026-11-24 22:27:13 +02:00
agrynco 870ad6c2b3 Allow Google Drive as the automatic settings sync provider
Refs #84
2026-11-24 22:20:37 +02:00
agrynco 15b251e7fb Add manual Google Drive settings backup and restore
Refs #84
2026-11-24 21:51:42 +02:00
agrynco ee9b953533 Release KSwitcher v0.7.3
Commit Settings drafts through Apply or Save and make Close and Cancel reflect the pending state.
2026-11-24 21:22:57 +02:00
agrynco 0ce99e5af9 Release KSwitcher v0.7.2
Scale Settings navigation indentation with monitor DPI.
2026-11-24 18:23:02 +02:00
agrynco a517b6ceb0 Release KSwitcher v0.7.2 with DPI-aware Settings indentation 2026-11-24 18:22:49 +02:00
agrynco ab41b4383c Release KSwitcher v0.7.1
Embed OpenBao synchronization in the settings tree.
2026-11-24 17:54:01 +02:00
agrynco 0e9e5dd2ef Release KSwitcher v0.7.1 with embedded OpenBao settings 2026-11-24 17:53:50 +02:00
agrynco 40884cfc9e Release KSwitcher v0.7.0
Publish the native settings redesign.
2026-11-24 17:10:32 +02:00
agrynco 9db4a25c46 Release KSwitcher v0.7.0 with the native settings redesign 2026-11-24 17:08:16 +02:00
agrynco 15a95e5d74 Release KSwitcher v0.6.132
Record snippet keys with live feedback and improve clipboard snapshot capture.
2026-11-23 23:39:25 +02:00
agrynco 0de58834cf Release KSwitcher v0.6.132 with snippet key recording 2026-11-23 23:38:58 +02:00
agrynco 777af43c66 Release KSwitcher v0.6.131 2026-11-23 20:21:03 +02:00
agrynco c4a4f5e488 Release KSwitcher v0.6.131 with trusted LAN clients 2026-11-23 20:18:38 +02:00
agrynco 00966549d8 Release KSwitcher v0.6.130 (#76) 2026-11-22 15:22:05 +02:00
agrynco 783a6d69af Show the input state on the tray icon in KSwitcher v0.6.130 2026-11-22 15:21:22 +02:00
agrynco 4cd127a597 Release KSwitcher v0.6.129 (#75) 2026-11-22 14:40:31 +02:00
agrynco ff0d57d16b Prepare KSwitcher v0.6.129 with the tray input switch 2026-11-22 14:39:46 +02:00
agrynco 3be628cd8f Pause and resume resident input processing from the tray 2026-11-22 12:30:53 +02:00
agrynco f5fc7d205c Release KSwitcher v0.6.128 (#74) 2026-11-22 12:08:55 +02:00
agrynco 7387058dce Release the snippet window picker in KSwitcher v0.6.128 2026-11-22 12:08:25 +02:00
agrynco 8b3fe947a6 Release KSwitcher v0.6.127 (#73)
Confirm a single snippet suggestion with Enter before the focused application receives the key.
2026-11-21 23:56:17 +02:00
agrynco 7626e6c9c2 Release KSwitcher v0.6.126 (#72)
Ship literal snippet key presses and the configured pause without application-specific suggestion handling.
2026-11-21 23:45:42 +02:00
agrynco 3af1f09088 Release KSwitcher v0.6.125 (#71)
Run macros at their position in verified snippets and select Codex skills without submitting the draft.
2026-11-21 23:33:19 +02:00
agrynco 53842935a7 Release KSwitcher v0.6.124 (#70)
Ship keyboard macros and pauses in verified snippets, align the editor buttons, and include the verified Windows x64 package manifest and checksum.
2026-11-21 22:23:50 +02:00
agrynco bdd058f493 Release KSwitcher v0.6.123 (#69)
Ship the offline tray state and discovery-driven LAN input reconnection. Include the verified Windows x64 package manifest and checksum.
2026-11-20 20:40:01 +02:00
agrynco e7624b620e Release KSwitcher v0.6.122 (#68)
Ship LAN input reconnection and a tray connection indicator. Include the verified Windows x64 package manifest and checksum.
2026-11-20 18:44:21 +02:00
agrynco 367a5fd9f7 Release KSwitcher v0.6.121 (#67)
Ship the Files Markdown startup retry and apply word-boundary checks to all snippet triggers.
2026-11-20 16:40:10 +02:00
agrynco 4095c889c1 Release KSwitcher v0.6.120 (#66) 2026-11-20 00:42:13 +02:00
agrynco d8c329c265 Prepare KSwitcher v0.6.120
Keep image clipboard backups in a short-lived helper to reduce layout conversion latency while preserving newer copies.
2026-11-20 00:40:46 +02:00
agrynco debd2b9cd9 Release KSwitcher v0.6.119 (#65) 2026-11-18 13:08:23 +02:00
agrynco 90c93fba8c Prepare KSwitcher v0.6.119
Run local Files commands and resolve completion paths from the active pane.
2026-11-18 13:06:48 +02:00
agrynco a09d5e72d1 Release KSwitcher v0.6.118 (#64) 2026-11-18 02:19:11 +02:00
agrynco c0bca1b4a2 Record KSwitcher v0.6.118 package checksums 2026-11-18 02:18:30 +02:00
agrynco d5ee6ee024 Prepare KSwitcher v0.6.118 2026-11-18 02:17:34 +02:00
agrynco 5cf0ff5140 Release KSwitcher v0.6.117 (#63) 2026-11-18 00:21:06 +02:00
agrynco 9c3de731ec Synchronize updater version and release package 2026-11-18 00:20:38 +02:00
agrynco 3b487d0af4 Record the v0.6.117 package and verify folder sizing shortcuts 2026-11-18 00:16:10 +02:00
agrynco 9c935fe4da Fix the history-host test build include path 2026-11-18 00:13:14 +02:00
agrynco 4f0a1b5f27 Prepare KSwitcher v0.6.117 with FTP support in Files 2026-11-18 00:11:08 +02:00
agrynco 524a2d4329 Release KSwitcher v0.6.116 (#62)
Show folder reading progress and allow partial results. Improve terminal file-open output and history.
2026-11-17 20:27:27 +02:00
agrynco 5bca97f864 Record the v0.6.116 package manifest and checksum 2026-11-17 20:26:36 +02:00
agrynco 0d714147ea Prepare KSwitcher v0.6.116 with cancellable folder scans 2026-11-17 20:26:09 +02:00
agrynco a0aeb62270 Release KSwitcher v0.6.115 (#61)
Add Shift+F4, prevent editor flicker, and record file launches as short start commands.
2026-11-17 17:30:07 +02:00
agrynco 4be9b24c4b Record the v0.6.115 package manifest and checksum 2026-11-17 17:29:31 +02:00
agrynco 9c30dd91b4 Prepare KSwitcher v0.6.115 with new files and concise open history 2026-11-17 17:27:08 +02:00
agrynco 5ba51ebb00 Release KSwitcher v0.6.114 (#60)
Move the active pane highlight directly to the clicked row.
2026-11-17 16:35:49 +02:00
agrynco 2bc6eb60c9 Record the v0.6.114 package manifest and checksum 2026-11-17 16:35:40 +02:00
agrynco 9c1badcb45 Prepare KSwitcher v0.6.114 with direct panel cursor highlighting 2026-11-17 16:30:18 +02:00
agrynco 9dcc20673a Release KSwitcher v0.6.113 (#59)
Prevent the terminal startup flash and stabilize the clipboard regression test.
2026-11-17 16:14:27 +02:00
agrynco ec4079b346 Record the v0.6.113 package manifest and checksum 2026-11-17 16:13:36 +02:00
agrynco 41cef4d4f3 Prepare KSwitcher v0.6.113 with a dark terminal from startup 2026-11-17 16:11:41 +02:00
agrynco b53b5715ab Release KSwitcher v0.6.112 (#58)
Add backward Ctrl+Shift+Tab cycling in Files, Editor and Viewer.
2026-11-17 15:45:25 +02:00
agrynco 01f44d22b5 Record the v0.6.112 package manifest and checksum 2026-11-17 15:44:36 +02:00
agrynco c78090f7d4 Prepare KSwitcher v0.6.112 with reverse Files window cycling 2026-11-17 15:42:44 +02:00
agrynco 0d797c4f35 Release KSwitcher v0.6.111 (#57)
Ship faster Files folder navigation, panel shortcuts, and Far-style scrollbars.
2026-11-17 15:35:12 +02:00
agrynco b6eaa2c85d Use stripped binaries in the v0.6.111 portable archive 2026-11-17 15:30:50 +02:00
agrynco 72024c3385 Record the v0.6.111 package manifest and legacy upgrade instructions 2026-11-17 15:29:03 +02:00
agrynco d60ef626f0 Prepare KSwitcher v0.6.111 with Files navigation and scrollbars 2026-11-17 15:23:22 +02:00
agrynco e144cd6607 Release KSwitcher v0.6.110 (#56)
Fix unrelated panel repaint and preserve uppercase personal dictionary corrections.
2026-11-17 14:16:03 +02:00
agrynco 05a3f7a8f4 Record the package manifest for KSwitcher v0.6.110 2026-11-17 14:15:41 +02:00
agrynco 12b8f5090c Release KSwitcher v0.6.110 with panel repaint and uppercase correction fixes
Refresh only the affected panel after folder navigation. Preserve uppercase when the target is in the personal dictionary.
2026-11-17 14:10:59 +02:00
agrynco 19d574edcf Release KSwitcher v0.6.109 (#55)
Digit-specific folder shortcuts and support for hyphenated personal words.

Refs #23
2026-11-17 13:31:18 +02:00
agrynco 3840744819 Record the package manifest for KSwitcher v0.6.109 2026-11-17 13:30:44 +02:00
agrynco 94e8ba4304 Release KSwitcher v0.6.109 with digit-specific folder shortcuts
Use Ctrl+0–9 to open each folder group and Ctrl+F1/F2 for panel modes. Allow internal hyphens in personal dictionary entries. Synchronize the rendered Files tests with asynchronous directory scans.

Refs #23
2026-11-17 13:28:25 +02:00
agrynco edb1440be0 Release KSwitcher v0.6.108 (#53)
Wake-on-LAN for offline paired PCs in KSwitcher Files.
2026-11-17 10:56:54 +02:00
agrynco 8ef13ca9bd Record the package manifest for KSwitcher v0.6.108 2026-11-17 10:56:21 +02:00
agrynco c0eca89738 Release KSwitcher v0.6.108 with Wake-on-LAN in Files 2026-11-17 10:55:01 +02:00
agrynco 0b6709495b Release KSwitcher v0.6.107 (#52)
Files command suggestions, contextual Windows help, and the FAR-style icon.
2026-11-16 23:12:42 +02:00
agrynco 5f0c51b557 Restore command suggestions after focus returns
Refs #8
2026-11-16 23:12:36 +02:00
agrynco 733b6deefa Record the package manifest for KSwitcher v0.6.107 2026-11-16 23:08:28 +02:00
agrynco b3a1e762ec Release KSwitcher v0.6.107 with Files command completion
Refs #8
Refs #18
2026-11-16 23:06:09 +02:00
agrynco 219bdd4883 Keep release ZIPs out of the source tree 2026-11-16 20:00:09 +02:00
agrynco d018b91397 Release KSwitcher v0.6.106 (#51) 2026-11-16 19:51:19 +02:00
agrynco 2d4df0daa8 Record the package manifest for KSwitcher v0.6.106 2026-11-16 19:48:04 +02:00
agrynco 773df250a4 Release KSwitcher v0.6.106 with responsive Files operations 2026-11-16 19:45:45 +02:00
agrynco b5924feb23 Merge pull request 'Release KSwitcher v0.6.105 with document icons and the elevated LAN PowerShell fix' (#50) from codex/release-v0.6.105 into main 2026-11-16 17:52:02 +02:00
agrynco c285505d79 Record the package manifest for KSwitcher v0.6.105
Refs #8, #38
2026-11-16 17:50:53 +02:00
agrynco 2e1b0446bc Separate the Files editor and viewer icons for v0.6.105
Publish the generated Windows ZIP as a Gitea release asset without adding a copy to Git.

Refs #38
2026-11-16 17:50:10 +02:00
agrynco 5ac3735db3 Fix LAN PowerShell startup from an elevated resident
Refs #8
2026-11-16 17:50:10 +02:00
agrynco 03984705fe Merge pull request 'Release KSwitcher v0.6.104 with rendered Markdown search' (#49) from codex/release-v0.6.104 into main 2026-11-16 15:07:14 +02:00
agrynco dedc42f0db Package KSwitcher v0.6.104
Refs #38
2026-11-16 15:06:47 +02:00
agrynco e5d639a72f Add search to the rendered Markdown viewer
Refs #38
2026-11-16 15:06:47 +02:00
agrynco 4d68c80409 Merge pull request 'Release KSwitcher v0.6.103 with Markdown appearance and terminal selection copy' (#48) from codex/release-v0.6.103 into main 2026-11-16 14:54:38 +02:00
agrynco 6af042a524 Package KSwitcher v0.6.103 2026-11-16 14:51:32 +02:00
agrynco b28789a4f5 Render Markdown HTML and save viewer appearance in Files Options
Refs #38

Refs #8
2026-11-16 14:49:42 +02:00
agrynco eaae5389d9 Merge pull request 'Release KSwitcher v0.6.102 with command copy and LAN startup error handling' (#47) from codex/release-v0.6.102 into main 2026-11-16 14:20:22 +02:00
agrynco 88b8536116 Package KSwitcher v0.6.102 2026-11-16 14:19:57 +02:00
agrynco b8997d1dd2 Fix command-line copy and prevent LAN startup dialogs
Refs #8
2026-11-16 14:18:13 +02:00
agrynco 1926bce15f Merge pull request 'Release KSwitcher v0.6.101 with panel Enter and compact Computers' (#46) from codex/release-v0.6.101 into main 2026-11-16 13:57:54 +02:00
agrynco afddcafdac Package KSwitcher v0.6.101 2026-11-16 13:57:39 +02:00
agrynco 21d28a0f6d Release compact Computers and panel Enter fixes for v0.6.101
Refs #8
2026-11-16 13:57:39 +02:00
agrynco f73dce7bb3 Merge pull request 'Release KSwitcher v0.6.100 with terminal Enter fix' (#45) from codex/release-v0.6.100 into main 2026-11-16 13:35:34 +02:00
agrynco 3c5f59ed91 Package KSwitcher v0.6.100 2026-11-16 13:35:29 +02:00
agrynco e50fbbc119 Fix Enter from the Files terminal output for v0.6.100
Refs #8
2026-11-16 13:31:06 +02:00
agrynco 6c5b09132f Merge pull request 'Release KSwitcher v0.6.99 with command line priority fix' (#44) from codex/release-v0.6.99 into main 2026-11-16 13:09:30 +02:00
agrynco 92774881ed Release KSwitcher v0.6.99 2026-11-16 13:09:20 +02:00
agrynco 353f4c2919 Give the Files command line priority when submitting input 2026-11-16 13:05:12 +02:00
agrynco 733f1b0fc9 Merge pull request 'Release KSwitcher v0.6.98 with Files shortcuts and FAR key bar' (#43) from codex/release-v0.6.98 into main 2026-11-16 11:45:02 +02:00
agrynco 878ae8fce8 Release KSwitcher v0.6.98 2026-11-16 11:44:48 +02:00
agrynco edd9b2b3f9 Improve file opening, cursor redraw and the FAR-style key bar 2026-11-16 11:39:49 +02:00
agrynco 36b0002404 Merge pull request 'Release KSwitcher v0.6.97 with cursor highlight fix' (#42) from codex/release-v0.6.97 into main 2026-11-16 11:24:35 +02:00
agrynco 8ffafde12a Release KSwitcher v0.6.97 2026-11-16 11:24:24 +02:00
agrynco 2bd325d294 Clear the previous cursor highlight after pane selection changes 2026-11-16 11:20:20 +02:00
agrynco d4c4f9be76 Merge pull request 'Release KSwitcher v0.6.96 with file pane and F8 fixes' (#41) from codex/release-v0.6.96 into main 2026-11-16 11:14:51 +02:00
agrynco af388be4a7 Release KSwitcher v0.6.96 2026-11-16 11:13:37 +02:00
agrynco 3efdd2ef06 Avoid file pane repaint on click and expose F8 Delete 2026-11-16 11:09:46 +02:00
agrynco 01b467e149 Merge pull request 'Release KSwitcher v0.6.95 with Markdown navigation and update fixes' (#40) from codex/release-v0.6.95 into main 2026-11-16 11:01:55 +02:00
agrynco cf2dd6c419 Refresh v0.6.95 package and verify window cycling
Refs #38
2026-11-16 11:00:13 +02:00
agrynco 293c5fd47e Cycle Files editor and viewer windows with Ctrl+Tab
Refs #38
2026-11-16 10:56:47 +02:00
agrynco 1dd6d75596 Release KSwitcher v0.6.95
Refs #38
2026-11-16 10:54:13 +02:00
agrynco 1aa23636ea Improve Markdown preview, menu navigation and update shutdown
Refs #38
2026-11-16 10:49:22 +02:00
agrynco 886532f831 Merge pull request 'Release KSwitcher v0.6.94 with Markdown preview' (#39) from codex/release-v0.6.94 into main 2026-11-16 10:21:49 +02:00
agrynco abaf73a050 Release KSwitcher v0.6.94
Refs #38
2026-11-16 10:18:44 +02:00
agrynco b16e50bee9 Render Markdown and Mermaid in KSwitcher Files
Refs #38
2026-11-16 10:13:42 +02:00
agrynco 3ed17fa6e8 Merge pull request 'Release KSwitcher v0.6.93' (#37)
Release KSwitcher v0.6.93
2026-11-16 01:26:42 +02:00
agrynco a1df56177d Release KSwitcher v0.6.93 2026-11-16 01:26:12 +02:00
agrynco 09db0e1051 Merge pull request 'Release KSwitcher v0.6.92' (#36)
Release KSwitcher v0.6.92
2026-11-16 01:19:49 +02:00
agrynco e1d8343c32 Release KSwitcher v0.6.92 2026-11-16 01:19:24 +02:00
agrynco 1ecd57a5e4 Merge pull request 'Release KSwitcher v0.6.91' (#35)
Release KSwitcher v0.6.91
2026-11-16 01:09:12 +02:00
agrynco 1ba169874a Release KSwitcher v0.6.91 2026-11-16 01:08:40 +02:00
agrynco 3037f9840e Merge pull request 'Release KSwitcher v0.6.90' (#34)
Release KSwitcher v0.6.90
2026-11-16 00:46:44 +02:00
agrynco 6b3a382f70 Release KSwitcher v0.6.90 2026-11-16 00:46:06 +02:00
agrynco ef4438359f Merge pull request 'Release KSwitcher v0.6.89' (#33)
Release KSwitcher v0.6.89
2026-11-16 00:31:10 +02:00
agrynco d2082f1593 Release KSwitcher v0.6.89 2026-11-16 00:30:48 +02:00
agrynco 57ccb2322d Merge pull request 'Release KSwitcher v0.6.88' (#32)
Release KSwitcher v0.6.88
2026-11-16 00:03:55 +02:00
agrynco 710d0cd591 Activate the Files test window before sending shortcuts 2026-11-16 00:03:42 +02:00
agrynco 8b53392b20 Release KSwitcher v0.6.88 2026-11-16 00:02:59 +02:00
agrynco 2824bef442 Merge pull request 'Release KSwitcher v0.6.87 with clean LAN PowerShell output' (#31) from codex/release-v0.6.87 into main
Release KSwitcher v0.6.87
2026-11-15 23:50:24 +02:00
agrynco a8cf51002d Package KSwitcher v0.6.87 2026-11-15 23:49:54 +02:00
agrynco 0298e98bbe Fix remote PowerShell text output for v0.6.87 2026-11-15 23:48:53 +02:00
agrynco cc6a832c73 Merge pull request 'Release KSwitcher v0.6.86 with LAN PowerShell' (#30) from codex/release-v0.6.86 into main
Release KSwitcher v0.6.86
2026-11-15 23:41:30 +02:00
agrynco 7873b1afda Package KSwitcher v0.6.86 2026-11-15 23:40:56 +02:00
agrynco 0f9e62abf2 Add approved LAN PowerShell commands and fix editor startup for v0.6.86 2026-11-15 23:39:59 +02:00
agrynco 3b4bc3f3b9 Merge pull request 'Release KSwitcher v0.6.85 with independent editor and LAN editing' (#29) from codex/release-v0.6.85 into main
Release KSwitcher v0.6.85
2026-11-15 23:10:40 +02:00
agrynco 9649248dae Package KSwitcher v0.6.85 2026-11-15 23:10:08 +02:00
agrynco 47541dabc4 Add independent Files windows and LAN editing for v0.6.85 2026-11-15 23:09:00 +02:00
agrynco 59a07d91dc Merge pull request 'Release KSwitcher v0.6.84 with Files editor and folder creation' (#28) from codex/release-v0.6.84 into main
Release KSwitcher v0.6.84
2026-11-15 22:35:51 +02:00
agrynco 9f37549a6c Package KSwitcher v0.6.84 2026-11-15 22:35:01 +02:00
agrynco badb789e19 Add Files editor, viewer and Far dialogs for v0.6.84 2026-11-15 22:34:02 +02:00
agrynco d80dfb0b91 Merge pull request 'Release KSwitcher v0.6.83 with Files keyboard navigation' (#27) from codex/release-v0.6.83 into main 2026-11-15 10:33:10 +02:00
agrynco eefa3e0baf Package KSwitcher v0.6.83 2026-11-15 10:32:46 +02:00
agrynco 1cd351a356 Restore Files command focus after panel clicks 2026-11-15 10:32:35 +02:00
agrynco 31958ee448 Keep Files commands focused during pane navigation 2026-11-15 10:29:35 +02:00
agrynco f3803e32b4 Merge pull request 'Release KSwitcher v0.6.82 with Files activation and refresh' (#26) from codex/files-activation-25 into main 2026-11-14 21:57:54 +02:00
agrynco 2f96efb2e6 chore(release): package KSwitcher v0.6.82
Refs #25
2026-11-14 21:56:10 +02:00
agrynco 05b648f110 feat(files): open local files and refresh panels automatically
Refs #25
2026-11-14 21:53:00 +02:00
agrynco 6e0246f0e5 Merge pull request 'Package KSwitcher 0.6.81' (#24) from codex/release-0681 into main 2026-11-14 16:34:11 +02:00
agrynco bcd8d2bc1f chore(release): package kswitcher v0.6.81 2026-11-14 16:32:06 +02:00
agrynco 012af57aae Merge pull request 'Show all folder shortcuts with Ctrl+8 and reuse the Files window' (#23) from codex/files-all-folder-shortcuts into main 2026-11-14 16:25:07 +02:00
152 changed files with 31501 additions and 3558 deletions

No files matched your search

+1
View File
@@ -4,5 +4,6 @@
/.vs/
/.idea/
/dist/
/Release/KSwitcher-win-x64.zip
/build-output.txt
*.user
+3
View File
@@ -54,6 +54,9 @@ command output.
Before changing the file manager UI, read [FILES-UI.md](FILES-UI.md).
Reuse the shared dialog rendering and layout helpers. Update the document
when an agreed UI requirement changes.
Verify visible changes in a rendered window. For rendering regressions,
add an automated check that fails on the reported appearance and run it
before handing off a new build.
## Link changes to Gitea issues
+133 -7
View File
@@ -1,11 +1,18 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.80 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.7.4 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(KSwitcherFiles WIN32 src/files_main.cpp resources/files.rc)
add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
src/files_text_document.cpp src/files_text_language.cpp resources/files.rc)
set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-viewer.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-editor.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-compare.ico")
include(cmake/FilesTextLibraries.cmake)
set_target_properties(KSwitcherFiles PROPERTIES OUTPUT_NAME "KSwitcher.Files")
target_compile_definitions(KSwitcherFiles PRIVATE UNICODE _UNICODE NOMINMAX _WIN32_WINNT=0x0A00)
find_program(KSWITCHER_POWERSHELL NAMES pwsh powershell REQUIRED)
@@ -14,8 +21,13 @@ add_custom_target(KSwitcherTerminalAssets
-Destination "$<TARGET_FILE_DIR:KSwitcherFiles>"
VERBATIM)
add_dependencies(KSwitcherFiles KSwitcherTerminalAssets)
add_custom_target(check-files-search-arrow
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_search_arrow.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>"
DEPENDS KSwitcherFiles
VERBATIM)
target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid)
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet)
if(MSVC)
target_compile_options(KSwitcherFiles PRIVATE /utf-8)
else()
@@ -36,11 +48,32 @@ foreach(utilityTarget StayHere StayHereTest)
endif()
endforeach()
add_library(kscore src/lan_files.cpp src/lan_channel.cpp src/lan_input.cpp src/lan.cpp src/lan_pairing.cpp src/core.cpp src/platform.cpp src/autostart.cpp src/autocorrect.cpp src/storage.cpp src/ocr.cpp src/richtext.cpp src/update.cpp src/sync.cpp)
target_sources(kscore PRIVATE src/drive_snapshot.cpp src/google_drive.cpp)
foreach(field IN ITEMS ID SECRET)
set(KS_GOOGLE_CLIENT_${field} "$ENV{KSWITCHER_GOOGLE_CLIENT_${field}}")
if(NOT KS_GOOGLE_CLIENT_${field} MATCHES "^[A-Za-z0-9_.-]*$")
message(FATAL_ERROR "Invalid Google OAuth client configuration.")
endif()
endforeach()
configure_file(cmake/google_drive_oauth_config.h.in generated/google_drive_oauth_config.h @ONLY)
target_link_libraries(KSwitcherFiles PRIVATE kscore)
target_include_directories(kscore PUBLIC src PRIVATE vendor)
target_include_directories(kscore PUBLIC src PRIVATE vendor "${CMAKE_CURRENT_BINARY_DIR}/generated")
target_compile_definitions(kscore PUBLIC UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX _WIN32_WINNT=0x0A00)
target_link_libraries(kscore PUBLIC ws2_32 bcrypt iphlpapi winhttp user32 shell32 shlwapi advapi32 crypt32 imm32 comctl32 gdi32 ole32 oleaut32 taskschd comdlg32 uuid windowscodecs runtimeobject uiautomationcore)
add_executable(KSwitcher WIN32 src/main.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
target_link_libraries(kscore PUBLIC ws2_32 bcrypt iphlpapi winhttp user32 shell32 shlwapi advapi32 crypt32 imm32 comctl32 gdi32 ole32 oleaut32 taskschd comdlg32 uuid windowscodecs runtimeobject uiautomationcore dwmapi)
set_property(SOURCE resources/app.rc APPEND PROPERTY OBJECT_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/resources/update.ps1"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-paused.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-history.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-screenshot.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-help.ico"
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-donate.ico")
set_property(SOURCE resources/help.rc APPEND PROPERTY OBJECT_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/resources/help-guide.md"
"${CMAKE_CURRENT_SOURCE_DIR}/README.md"
"${CMAKE_CURRENT_SOURCE_DIR}/FILES-UI.md"
"${CMAKE_CURRENT_SOURCE_DIR}/LAN-PREVIEW.md")
add_executable(KSwitcher WIN32 src/main.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/configuration.cpp src/ui.cpp resources/app.rc resources/help.rc)
target_compile_definitions(KSwitcher PRIVATE KS_RESIDENT_APP)
target_link_libraries(KSwitcher PRIVATE kscore)
add_executable(KSwitcherConfig WIN32 src/config_main.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
@@ -48,6 +81,7 @@ set_target_properties(KSwitcherConfig PROPERTIES OUTPUT_NAME "KSwitcher.Config")
target_compile_definitions(KSwitcherConfig PRIVATE KS_CONFIG_APP)
target_link_libraries(KSwitcherConfig PRIVATE kscore)
add_executable(KSwitcherTests tests/tests.cpp)
target_include_directories(KSwitcherTests PRIVATE vendor)
add_executable(KSwitcherSyncTests tests/sync.cpp)
target_include_directories(KSwitcherSyncTests PRIVATE vendor)
target_link_libraries(KSwitcherSyncTests PRIVATE kscore)
@@ -70,7 +104,7 @@ if(MSVC)
else()
target_link_options(KSwitcherFarSnippetTests PRIVATE -municode -static -static-libgcc -static-libstdc++)
endif()
add_executable(KSwitcherInputTests tests/input.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc)
add_executable(KSwitcherInputTests tests/input.cpp tests/input_pause.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot.cpp src/configuration.cpp src/ui.cpp resources/app.rc resources/help.rc)
target_link_libraries(KSwitcherInputTests PRIVATE kscore)
target_compile_definitions(KSwitcherInputTests PRIVATE KS_SCREENSHOT_RESOURCES)
add_executable(KSwitcherScreenshotUITests tests/screenshot_ui.cpp resources/app.rc)
@@ -106,6 +140,21 @@ else()
target_link_options(KSwitcherOcrTests PRIVATE -static -static-libgcc -static-libstdc++)
endif()
enable_testing()
add_executable(KSwitcherFilesTextTests tests/files_text_document.cpp src/files_text_document.cpp)
target_include_directories(KSwitcherFilesTextTests PRIVATE src)
target_compile_definitions(KSwitcherFilesTextTests PRIVATE UNICODE _UNICODE NOMINMAX WIN32_LEAN_AND_MEAN)
target_link_libraries(KSwitcherFilesTextTests PRIVATE ole32)
if(NOT MSVC)
target_link_options(KSwitcherFilesTextTests PRIVATE -static)
endif()
add_test(NAME files-text-document COMMAND KSwitcherFilesTextTests)
add_executable(KSwitcherFilesModalTests tests/files_modal_dialog.cpp)
target_include_directories(KSwitcherFilesModalTests PRIVATE src)
target_link_libraries(KSwitcherFilesModalTests PRIVATE user32 comctl32)
if(NOT MSVC)
target_link_options(KSwitcherFilesModalTests PRIVATE -static)
endif()
add_test(NAME files-modal-dialog COMMAND KSwitcherFilesModalTests)
add_executable(KSwitcherLanTests tests/lan.cpp)
target_link_libraries(KSwitcherLanTests PRIVATE kscore)
if(MSVC)
@@ -114,9 +163,63 @@ else()
target_link_options(KSwitcherLanTests PRIVATE -static -static-libgcc -static-libstdc++)
endif()
add_test(NAME lan-pairing-regressions COMMAND KSwitcherLanTests)
add_executable(KSwitcherLanClientsTests tests/lan_clients.cpp)
target_link_libraries(KSwitcherLanClientsTests PRIVATE kscore)
if(NOT MSVC)
target_link_options(KSwitcherLanClientsTests PRIVATE -static)
endif()
add_test(NAME lan-trusted-clients COMMAND KSwitcherLanClientsTests)
set_tests_properties(lan-trusted-clients PROPERTIES TIMEOUT 15)
add_executable(KSwitcherLanFilesTests tests/lan_files.cpp)
target_link_libraries(KSwitcherLanFilesTests PRIVATE kscore)
add_test(NAME lan-files-regressions COMMAND KSwitcherLanFilesTests)
add_executable(KSwitcherFilesActivationFixture tests/files_activation_fixture.cpp)
if(NOT MSVC)
target_link_options(KSwitcherFilesActivationFixture PRIVATE -municode -static)
endif()
add_test(NAME files-activation-and-refresh
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>")
set_tests_properties(files-activation-and-refresh PROPERTIES RUN_SERIAL TRUE TIMEOUT 120)
add_test(NAME files-system-open
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>"
-SystemOpenOnly)
set_tests_properties(files-system-open PROPERTIES RUN_SERIAL TRUE TIMEOUT 60)
add_test(NAME files-comparison-splitter
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_comparison_splitter.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-comparison-splitter PROPERTIES RUN_SERIAL TRUE TIMEOUT 35)
find_program(KSWITCHER_NODE NAMES node)
if(KSWITCHER_NODE)
add_test(NAME files-terminal-enter
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>"
-TerminalOnly -Node "${KSWITCHER_NODE}")
set_tests_properties(files-terminal-enter PROPERTIES RUN_SERIAL TRUE TIMEOUT 90)
add_executable(KSwitcherFilesMarkdownLanFixture WIN32 tests/files_markdown_lan.cpp
src/files_text_window.cpp src/files_text_document.cpp src/files_text_language.cpp resources/files.rc)
target_include_directories(KSwitcherFilesMarkdownLanFixture PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
target_link_libraries(KSwitcherFilesMarkdownLanFixture PRIVATE kscore KSwitcherFilesText)
add_dependencies(KSwitcherFilesMarkdownLanFixture KSwitcherTerminalAssets)
if(MSVC)
set_property(TARGET KSwitcherFilesMarkdownLanFixture PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
target_compile_options(KSwitcherFilesMarkdownLanFixture PRIVATE /utf-8)
else()
target_link_options(KSwitcherFilesMarkdownLanFixture PRIVATE -municode -static)
endif()
add_test(NAME files-markdown-viewer
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_markdown.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Node "${KSWITCHER_NODE}"
-LanFixture "$<TARGET_FILE:KSwitcherFilesMarkdownLanFixture>")
set_tests_properties(files-markdown-viewer PROPERTIES RUN_SERIAL TRUE TIMEOUT 120)
endif()
add_executable(KSwitcherLanInputTests tests/lan_input.cpp)
target_link_libraries(KSwitcherLanInputTests PRIVATE kscore)
if(MSVC)
@@ -134,7 +237,11 @@ else()
target_link_options(KSwitcherChatProfileTests PRIVATE -static -static-libgcc -static-libstdc++)
endif()
add_test(NAME chat-profile-regressions COMMAND KSwitcherChatProfileTests)
add_test(NAME lan-window-layout COMMAND KSwitcherChatProfileTests --lan-layout)
add_test(NAME google-drive-settings-page COMMAND KSwitcherChatProfileTests --google-drive-layout)
set_tests_properties(lan-window-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
add_executable(KSwitcherHistoryHostTests tests/history_host.cpp)
target_include_directories(KSwitcherHistoryHostTests PRIVATE vendor)
target_link_libraries(KSwitcherHistoryHostTests PRIVATE kscore psapi)
set_target_properties(KSwitcherHistoryHostTests PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/history-host-fixture-$<CONFIG>")
add_dependencies(KSwitcherHistoryHostTests KSwitcher KSwitcherScreenshot)
@@ -189,7 +296,15 @@ add_test(NAME utilities-regressions COMMAND KSwitcherUtilitiesTests)
add_test(NAME stayhere-lifecycle COMMAND powershell -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/stayhere.ps1" -Executable "$<TARGET_FILE:StayHereTest>")
add_test(NAME scroll-regressions COMMAND KSwitcherScrollTests)
add_test(NAME input-regressions COMMAND KSwitcherInputTests)
add_dependencies(KSwitcherInputTests KSwitcherScreenshot)
add_test(NAME clipboard-history-layout COMMAND KSwitcherInputTests --history-layout)
set_tests_properties(clipboard-history-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 20)
add_test(NAME offline-help-window COMMAND KSwitcherInputTests --help-layout)
set_tests_properties(offline-help-window PROPERTIES RUN_SERIAL TRUE TIMEOUT 20)
add_test(NAME tray-input-pause COMMAND KSwitcherInputTests --input-pause)
add_test(NAME screenshot-ui-regressions COMMAND KSwitcherScreenshotUITests)
add_test(NAME screenshot-editor-layout COMMAND KSwitcherScreenshotUITests --layout-only)
set_tests_properties(screenshot-editor-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 20)
add_test(NAME screenshot-save-regressions COMMAND KSwitcherScreenshotUITests --save-only)
add_test(NAME updater-regressions COMMAND powershell.exe -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/update.ps1" -Executable "$<TARGET_FILE:KSwitcher>")
set_tests_properties(native-regressions PROPERTIES WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
@@ -216,3 +331,14 @@ else()
target_link_options(KSwitcherSettingsMergeTests PRIVATE -static -static-libgcc -static-libstdc++)
endif()
add_test(NAME settings-save-merge COMMAND KSwitcherSettingsMergeTests)
add_executable(KSwitcherDriveTests tests/drive_snapshot.cpp)
target_include_directories(KSwitcherDriveTests PRIVATE vendor)
target_link_libraries(KSwitcherDriveTests PRIVATE kscore)
if(MSVC)
target_compile_options(KSwitcherDriveTests PRIVATE /utf-8)
set_property(TARGET KSwitcherDriveTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
else()
target_link_options(KSwitcherDriveTests PRIVATE -static -static-libgcc -static-libstdc++)
endif()
add_test(NAME google-drive-backup COMMAND KSwitcherDriveTests)
+405 -21
View File
@@ -1,17 +1,243 @@
# Оформлення KSwitcher Files
Far Manager є зразком для оформлення файлового менеджера. Основне вікно використовує системний заголовок Windows. Панелі, меню й діалоги операцій використовують моноширинний шрифт менеджера та оформлення в стилі Far.
Іконка головного вікна показує дві сині панелі з бірюзовою рамкою та виділеним рядком.
Власні модальні діалоги панелей, редактора й переглядача використовують
`FilesModalDialog`. Escape і клік поза діалогом у клієнтській області Files
виконують Cancel, а фокус повертається до елемента, з якого відкрили діалог.
Кліки на робочому столі та в інших застосунках залишають діалог відкритим.
Заголовок і рамка вікна-власника доступні, а діалог рухається разом із
власником. Діалог центрується відносно власника та звужується разом із ним
до власної мінімальної ширини. Поки діалог відкритий, ширина власника
обмежена цією мінімальною шириною з відступами.
Це діє і для вкладених діалогів. Під час файлової операції Cancel спершу
просить підтвердити переривання.
Спільне повідомлення Files підлаштовується під заголовок і кількість рядків.
Висота діалогу залежить від видимого вмісту. Приховані та порожні секції
не займають місця. Перед завершенням змін перевір коротке повідомлення й
повідомлення з кількома рядками, включно з відступами до рамки та кнопок.
Смуга прокрутки з’являється, лише коли текст не вміщується в доступну висоту.
Панелі, списки попапів і довгі повідомлення використовують вузьку смугу
прокрутки зі стрілками вгорі й унизу та крапковою доріжкою. Відтінки доріжки
й повзунка залежать від фону, на якому вони малюються. Повзунок світліший
за доріжку й показує положення та розмір видимої частини списку.
Оформлення, кнопки й необов’язковий прапорець задаються параметрами шаблону.
Підтвердження гібернації та віддаленого оновлення мають червоне оформлення
Warning і початковий фокус на No.
## Скорочення
- У командному рядку Ctrl+V і Shift+Insert вставляють текст із буфера обміну
в позицію курсора або замінюють виділення. Якщо фокус на файловій панелі,
ці клавіші переводять його до командного рядка й вставляють текст там.
Enter запускає команду. Escape очищає поле й залишає фокус у командному рядку.
Промпт і текст команди вирівняні по спільній базовій лінії.
- **FTP** у меню джерел (Alt+F1 для лівої панелі, Alt+F2 для правої)
відкриває список збережених підключень у вибраній панелі. Shift+F4
додає підключення, F4 редагує виділене, Enter відкриває його.
У формі вкажи назву, сервер, порт (типово 21), ім’я користувача й пароль.
Порожнє ім’я означає анонімний вхід. Паролі зберігаються локально
із захистом Windows DPAPI. Звичайний FTP передає дані без шифрування.
Після підключення панель показує справжній шлях початкового каталогу
сервера. Enter або подвійний клік на `..` відкриває батьківську папку.
У корені рядка `..` немає. Щоб повернутися до списку підключень,
вибери FTP в меню джерел панелі.
Назви файлів і папок передаються в UTF-8. Для старого сервера, який
використовує системну кодову сторінку Windows, увімкни в профілі
**Use Windows encoding for file names** і підключися знову.
- F5 копіює поточний або позначені файли й папки між локальною та
підключеною FTP-панелями в обидва боки. Призначенням є каталог іншої
панелі. Для одного елемента можна вказати ім’я копії в цьому каталозі.
Використовуються спільні діалоги Copy, прогресу та конфлікту імен.
Поточний файл записується під тимчасовим ім’ям до завершення передачі.
Для заміни файла FTP-сервер має приймати перейменування поверх нього.
- У підключеній FTP-панелі F3 та Enter відкривають файл у Viewer, а F4
відкриває Editor. Файл завантажується у тимчасову копію у фоні.
F2 в Editor передає зміни назад на FTP. Якщо сервер повідомляє інший
розмір або час зміни файла, запис скасовується, а правки лишаються в редакторі.
- У підключеній FTP-панелі F6 перейменовує один файл або папку в поточному
каталозі. Якщо нове ім’я зайняте, Files показує помилку. F8 запитує
підтвердження й видаляє вибрані елементи з FTP-сервера без кошика.
Для непорожньої папки Files окремо підтверджує видалення її вмісту.
- Ctrl+E підставляє останню команду та переводить фокус із файлової панелі
до командного рядка. Повторне натискання
- **F9 → Commands → Compare files** порівнює два позначені текстові файли
активної панелі або по одному файлу з кожної панелі. Якщо в панелі немає
позначок, береться файл під курсором. Підтримуються локальні, LAN- та
FTP-файли. Файли показуються поруч із синхронною прокруткою, номерами
рядків і підсвічуванням вставок, видалень і замін. У замінених рядках
виділяється змінений фрагмент. **Previous** (F7) і **Next** (F8)
переходять між блоками змін. Подвійний клік відкриває повний текст пари рядків.
Лічильник, навігація й перемикач пробілів розміщені в одному компактному
рядку над заголовками файлів. Вікно закривається системним хрестиком або Esc.
Вікно має системну рамку зі зміною розміру й нативний тулбар Windows
зі стрілками переходу, розділювачами та кнопкою-перемикачем пробілів.
Текст файлів і порожня область під ним мають білий фон, рядки
зі змінами виділяються кольором. Область порівняння займає всю ширину вікна.
Центральний розділювач можна перетягнути мишею. Під час зміни розміру
вікна пропорція колонок зберігається.
Ctrl+колесо змінює масштаб тексту в поточному вікні.
Порівняння відкривається в окремому вікні із власною іконкою та кнопкою
на панелі завдань. У **Options → File comparison → Font and colors**
можна окремо налаштувати шрифт, тло, текст і кольори змін.
Shift+F11 відкриває порівняння. Комбінацію можна змінити в тому ж розділі,
і меню Commands показує поточне призначення.
Рядки зіставляються за вмістом. Зміни лише у відступах і кінцевих пробілах
типово пропускаються. Перемикач **Show whitespace changes** показує їх.
Вставлені й видалені порожні рядки враховуються завжди.
Кнопка розгортання в системному заголовку збільшує вікно порівняння
до робочої області екрана. Повторне натискання відновлює попередній розмір.
Вікно працює в режимі перегляду. Підтримуються UTF-8 і UTF-16 з BOM,
до 2 МіБ і 100 000 рядків на файл. Стилі переносу рядків порівнюються
як рівнозначні.
- У меню Files і його списках, що випадають, стрілки вгору й вниз
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
У меню джерел горизонтальна лінія відділяє FTP від локальних дисків,
а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP.
Літера відкриває локальний диск, цифра 1 відкриває FTP. Для LAN-дисків
і Wake меню показує доступні цифри 2–9 і 0. Призначена цифра зберігається
до закриття меню, навіть коли оновлюється список LAN.
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
документ — у програмі, призначеній для його типу у Windows. EXE запускається
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
панелі LAN, спочатку скопіюй його до локальної папки.
Після успішного відкриття локального файла через Windows його шлях
з’являється у виводі термінала й списку історії. Коли термінал неактивний,
його курсор приховано. При виборі
з історії у командний рядок підставляється команда, яка повторює відкриття.
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
елемент через Windows.
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
- У головному вікні клавіатурний фокус залишається в командному рядку.
Tab без модифікаторів перемикає активну панель, а клік вибирає рядок.
Ctrl+U міняє видимі панелі місцями разом із їхніми папками, режимами,
курсорами й позначками. Активна панель залишається активною на новому боці.
Page Up і Page Down пересувають курсор у панелі. Стрілки вгору й вниз
керують панеллю, коли список підказок закритий.
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
командний рядок порожній.
Ctrl+← і Ctrl+→ зміщують розділювач видимих панелей на ширину одного символу.
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
При кліку в іншу панель курсор відразу з’являється на вибраному рядку.
Попередній рядок цієї панелі оновлюється лише тоді, коли для неактивного
курсора він мав інше оформлення.
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
текст із буфера обміну в позицію курсора або замінюють виділення.
Enter виконує введену команду, якщо підказку не вибрано. Shift+Enter
виконує команду одразу. Коли рядок
порожній, Enter відкриває поточний елемент. Якщо панелі приховано,
Enter передає порожній рядок у термінал.
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
командного рядка й виконують відповідну дію за тими самими правилами.
Локальна команда запускається в папці активної панелі, яку показано
перед командним рядком. Після перемикання панелі або переходу до іншої
папки наступна команда використовує нову папку навіть у вже відкритому
PowerShell. Якщо команда змінює папку (наприклад, через `cd`), панель
переходить до неї, якщо користувач за цей час не змінив її розташування.
Під час запуску термінала область виводу має темне тло, поки WebView2
готує сторінку.
Промпт і текст команди вирівняні по спільній базовій лінії.
- Під час набору локальної команди над полем з’являються підказки PowerShell.
Автодоповнення працює з відкритими й прихованими панелями (Ctrl+O).
Список уточнюється після кожної зміни тексту й доповнює команди, параметри
та шляхи відносно робочої папки активної панелі.
Після `cd ` список пропонує папки,
а після вибору можна продовжити шлях через `\`, зокрема всередині лапок.
Стрілки вгору й вниз вибирають підказку. Tab вставляє вибрану або першу,
Enter вставляє виділену, а клік вставляє підказку під вказівником.
Щоб виконати команду після вставлення, натисни Enter ще раз.
Escape закриває список зі збереженням тексту. Без списку Escape очищає
рядок, а Tab перемикає панель, якщо панелі відкриті. Доступні підказки стандартної локальної
сесії PowerShell, включно з програмами з PATH. Для команд без аргументів,
як-от `cls`, список не пропонує шляхи.
Для `dotnet` підкоманди й параметри підказує встановлений .NET SDK.
Для `git` підкоманди, параметри й доречні назви гілок бере штатний
скрипт Git for Windows. Підказки використовують локальні дані репозиторію.
- Довідник Windows Commands надає офлайн підказки ключів і підкоманд для
системних утиліт. Наприклад, `ipconfig /re` пропонує `/release` і `/renew`,
`reg q` пропонує `query`, а `cmd /c dir /` пропонує ключі `dir` для CMD.
Каталог також підказує вкладені підкоманди та значення, перелічені в
синтаксисі. Наприклад, `netsh interface ipv4 show co` пропонує `config`,
а `schtasks /query /fo ` пропонує `CSV`, `LIST` і `TABLE`. F1 у командному
рядку відкриває статтю Microsoft Learn для поточної команди чи підкоманди.
Якщо ввести `dir` безпосередньо у Files, PowerShell підказує власні параметри.
Після `ipconfig /renew ` або `ipconfig /release ` список підказує назви
локальних адаптерів із DHCP для IPv4. Назви з пробілами вставляються в лапках.
- Коли курсор у кінці рядка, список спочатку показує до 5 різних
останніх команд з історії, які починаються з набраного тексту.
Вибір підставляє всю команду. Підказки з історії доступні й у LAN-панелі.
- **F8 Delete** у нижньому рядку клавіш викликає той самий діалог видалення,
що й клавіша F8.
- У нижньому рядку, як у FAR, позначення клавіш сірі на чорному тлі,
а назви дій темні на бірюзових сегментах.
- У віддаленій панелі Enter запускає введену команду PowerShell на
спареному ПК в поточному каталозі цієї панелі. Вивід і код завершення
з’являються в терміналі Files як текст. Службовий прогрес PowerShell
приховано. Кожна команда запускається окремо,
тому змінні середовища й `cd` між командами не зберігаються. Escape
в порожньому командному рядку скасовує поточну віддалену команду.
- На ПК, який приймає команди, увімкніть **Options → Command line →
Command history → Allow paired PCs to run PowerShell commands here**.
Дозвіл за замовчуванням вимкнений і діє лише для спарених ПК. Команди
запускаються без підвищених прав. Для цієї функції оновіть обидва ПК.
- **F9 → Commands → Hibernate remote PC** доступна для активної LAN-панелі.
У підтвердженні показується ім’я цільового ПК. На цільовому ПК ввімкніть
**Options → Command line → Command history → Allow paired PCs to hibernate this PC**.
Дозвіл за замовчуванням вимкнений і діє лише для спарених ПК. Для цієї дії
потрібні оновлення на обох ПК і ввімкнена гібернація Windows.
- У **Change drive** (Alt+F1 або Alt+F2) підкреслена дія **Wake** є праворуч
від стану офлайн-ПК. Клік по слову або Enter з фокусом на дії надсилає пакет.
Статус відображається на тлі списку. Для текстових дій усередині рядків
використовуй спільний компонент `InlineListAction` для малювання, фокуса
й обробки кліків. KSwitcher
має зберегти MAC-адресу мережевого адаптера. Оновіть KSwitcher та дайте
обом ПК побачити один одного в локальній мережі. На цільовому ПК потрібна
підтримка Wake-on-LAN у прошивці та налаштуваннях адаптера. Рядок стану
повідомляє про надсилання пакета або відсутність збереженої MAC-адреси.
- **F9 → Commands → Update remote KSwitcher** запускає штатне оновлення для
ПК активної LAN-панелі. Підтвердження з іменем ПК показується у Files
відправника. На цільовому ПК потрібен дозвіл **Options → Command line →
Command history → Allow paired PCs to update KSwitcher here**. Після
перевірки нового стабільного пакета оновлювач без запитань закриває
KSwitcher, Files, Config і редактори скриншотів цієї інсталяції.
Незбережені зміни у примусово закритих вікнах втрачаються.
Закриття процесів і результат записуються до `kswitcher.log`.
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
курсора командного рядка або замінює виділення. Подвійні лапки додаються
лише до шляхів із пробілами. На рядку `..` вставляється шлях папки,
відкритої в активній панелі.
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
- Локальні й LAN-каталоги скануються у фоновому потоці. Рядок стану активної
панелі показує «Reading» з лічильником прочитаних файлів і папок та
підказкою [Esc].
До завершення читання панель зберігає попередній список. Escape зупиняє
сканування активної панелі й відкриває прочитану частину папки. Якщо
папку ще не вдалося відкрити, попередній список залишається. Ctrl+R
повторює сканування, щоб отримати повний список. Після переходу
оновлюються шлях і список цієї панелі та командний рядок. Сусідня
панель не перемальовується через цей перехід.
Якщо надійшов новіший запит, результат попереднього
сканування пропускається. Після підтвердження UAC очікування списку
від підвищеного процесу теж відбувається у фоні.
- Якщо Windows відмовляє у правах для F5, F6, F7 або F8 на локальних
дисках, Files пропонує повторити операцію з правами адміністратора.
Після підтвердження UAC допоміжний процес обробляє захищені елементи
поточної операції. Відмова в діалозі або в UAC зупиняє операцію.
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
зберігаються для наявних елементів, а підраховані через F3 розміри папок
скидаються. F2 також виконує цю дію.
- Ctrl+C і Ctrl+Insert копіюють виділений текст із виводу термінала.
- За відсутності виділення у виводі Ctrl+C копіює весь введений у командний
рядок текст, навіть коли виділено лише його частину.
- Ctrl+Insert копіює весь текст непорожнього командного рядка. Якщо рядок
порожній, копіюються імена позначених файлів і папок активної панелі в
порядку відображення, по одному на рядок. Якщо позначок немає, копіюється
ім’я під курсором. Шляхи й рядок `..` пропускаються.
- Ctrl+E підставляє останню команду. Повторне натискання
підставляє старішу, доки не досягне початку історії. Alt+F8 відкриває історію
з групуванням за датами. Enter або подвійний клік у списку підставляє вибрану
команду в поле. Для запуску натисни Enter у самому полі.
@@ -33,7 +259,7 @@ Far Manager є зразком для оформлення файлового м
Вікно історії бірюзове, поле пошуку сіро-бірюзове. Поки історія відкрита,
дії в панелях, меню й командному рядку заблоковано. Заголовок і рамка
головного вікна доступні для переміщення, зміни розміру та керування вікном.
Escape або клік поза діалогом закриває історію. Заголовок і рамка головного
Escape або клік у Files поза діалогом закриває історію. Заголовок і рамка головного
вікна залишають історію відкритою під час керування вікном.
Історія центрується відносно головного вікна й рухається разом із ним.
Tab циклічно переводить фокус між пошуком і списком.
@@ -41,20 +267,157 @@ Far Manager є зразком для оформлення файлового м
Висота списку залежить від кількості результатів. Коли місця бракує,
прокручується список.
- Короткий Alt перемикає головне меню Files при відпусканні. F9 також перемикає меню. Після закриття фокус повертається до активної панелі. Alt з літерою верхнього рівня спрацьовує одразу при натисканні літери. Alt+O відкриває Options, а відпускання Alt після комбінації не перемикає меню.
- Alt із символом шукає початок назви файлу чи папки. Після першого збігу
внизу активної панелі відкривається компактне поле Search у подвійній рамці.
Наступні символи можна набирати без Alt. Пошук враховує поточну розкладку
та ігнорує регістр. Backspace прибирає останній символ, Escape закриває пошук,
а Enter відкриває поточний елемент.
- F9 перемикає головне меню Files. Після закриття фокус повертається в командний рядок. Коли меню відкрите, Alt з літерою верхнього рівня відкриває відповідний пункт.
- Коли головне меню відкрите, L, F, C, O та R відкривають Left, Files, Commands, Options та Right. У підменю підсвічена літера викликає відповідну команду. Літери унікальні в межах поточного рівня. Усталені мнемоніки мають пріоритет, зокрема X для Exit.
- У Commands лінії відокремлюють навігацію панелі, перегляд і редагування
та керування віддаленим ПК. Остання група з’являється разом зі своїм
роздільником лише в активній LAN-панелі. Роздільники пропускаються під
час навігації й не реагують на клік.
- Глобальне скорочення **Open KSwitcher Files** можна змінити або очистити в налаштуваннях. Для профілю без цього поля пропонується Ctrl+Alt+F, якщо Windows реєструє комбінацію і вона вільна серед прив’язок KSwitcher.
- Глобальне скорочення повертає до відкритого вікна Files у поточній сесії Windows або запускає Files, якщо такого вікна немає. Пункт **Files** у треї відкриває нове вікно.
- Ctrl+Shift+0–9 відкриває діалог Title і Path із поточною папкою. OK додає запис без дублювання, Escape скасовує. Title необов’язковий, порожнє значення показує шлях. Записи LAN зберігають ID ПК, а редагування Path залишає запис на тому самому ПК.
- Ctrl+0–9 одразу відкриває єдину папку. Для кількох папок відкривається компактний попап Far з одним заголовком Folder shortcuts у подвійній рамці та коротким рядом клавіш у нижній рамці. Ширина залежить від найдовшого запису й обмежується розміром вікна, а висота — кількістю видимих рядків. Нижня рамка показує Ins Del F4 Ctrl+Up Ctrl+Down. Insert додає поточну папку через Title і Path, Delete відв’язує, F4 редагує, Ctrl+Up і Ctrl+Down змінюють і зберігають порядок. Enter відкриває папку. Escape або клік поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису. Brief і Wide доступні в меню Left/Right та Options.
- Ctrl+0–9 відкриває лише папки, призначені натиснутій цифрі. Єдина папка відкривається одразу. Для кількох папок відкривається компактний попап Far з одним заголовком Folder shortcuts у подвійній рамці та коротким рядом клавіш у нижній рамці. Ширина залежить від найдовшого запису й обмежується розміром вікна, а висота — кількістю видимих рядків. Нижня рамка показує Ins Del F4 Ctrl+Up Ctrl+Down. Insert додає поточну папку через Title і Path, Delete відв’язує, F4 редагує, Ctrl+Up і Ctrl+Down змінюють і зберігають порядок. Enter відкриває папку. Escape або клік у Files поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису.
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F12 зарезервовані для інших режимів панелей. Brief і Wide також доступні в меню Left/Right та Options.
## Налаштування Files
- Options у головному меню одразу відкриває стандартний діалог Windows. Ліворуч є пошук за назвою категорії чи параметра й дерево результатів. Вибір дочірнього вузла відкриває лише його редактор праворуч. Пошук за назвою окремої властивості відкриває вузол, що її містить. Перемикання вузлів зберігає незастосовані зміни.
### Переглядач і редактор
- F3 відкриває поточний локальний файл у вбудованому переглядачі лише
для читання. F4 відкриває спільне вікно в режимі редагування. Alt+F3
відкриває файл у програмі, призначеній Windows для цього типу, а Alt+F4
викликає зареєстровану дію Edit. Ці команди також є в меню Commands.
F10 або × закривають головне вікно Files. Вбудовані Viewer та Editor
відкриваються в окремих немодальних вікнах. Редактор має іконку олівця,
переглядач — іконку ока. Ці іконки видно в заголовку, в Alt+Tab і в окремих
групах на панелі завдань Windows. F6 змінює іконку й групу поточного вікна.
При повторному відкритті Files пропонує перейти до вже
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
Помилка збереження залишає відкритим редактор зі змінами.
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному
порядку. Коли відкрито лише Files, активна панель не змінюється.
- Shift+F4 у локальній панелі відкриває Editor для наявного або нового файла.
Порожнє ім’я підставляє `New_File_<дата>_<час>.txt`. Новий файл з’являється
на диску після збереження. Esc після змін пропонує Save, Discard або Cancel.
Save для нового файла відкриває параметри імені, кодування, BOM та кінців
рядків. Скасування параметрів залишає текст у редакторі.
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
інтерактивними чекбоксами списків і діаграмами Mermaid. Клік по чекбоксу
одразу записує позначку у вихідний Markdown. У разі помилки збереження
попередній стан відновлюється. Підписи з'єднань малюються поверх стрілок.
F4 відкриває текст із підсвічуванням Markdown.
HTML усередині Markdown підтримує таблиці, текстове форматування, посилання,
відносні зображення й окремі стилі, зокрема `white-space: nowrap` у клітинках.
Скрипти, вбудовані сторінки та обробники подій відфільтровуються.
Відносні посилання й зображення відкриваються від каталогу вихідного файла.
Вихідний текст приховано, доки Markdown і Mermaid готують перегляд.
Звичайний клік відкриває внутрішнє посилання в тому самому вікні,
Shift+клік відкриває окреме вікно. Назад і вперед працюють через стрілки
перегляду, бічні кнопки миші й Alt+←/→. Ctrl+W закриває перегляд.
Ctrl+F або кнопка пошуку відкриває пошук у відрендерованому документі.
Пошук без урахування регістру показує кількість збігів і підсвічує поточний.
Enter і F3 переходять до наступного збігу, а Shift+Enter і Shift+F3 — до
попереднього, циклічно. Escape спочатку закриває поле пошуку.
Коли локальний Markdown оновлюється на диску, відкритий перегляд
перерендерюється зі збереженням позиції прокрутки.
Вебпосилання HTTP і HTTPS відкриваються в системному браузері.
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
кліку. Mermaid працює офлайн і завантажується лише для документів із
діаграмами Mermaid. Якщо WebView2 не завершує запуск, Files один раз
повторює спробу в тому самому вікні. Якщо форматований перегляд недоступний
або файл більший за 8 МіБ, F3 відкриває текстовий перегляд.
- F3 у фоні підраховує сумарний розмір файлів у папці та її підпапках.
На рядку `..` F3 рахує всі папки поточного списку, а за наявності
позначених папок в інших рядках рахує позначені папки. Без позначок
F3 рахує папку під курсором або відкриває файл. Папки обробляються по черзі,
і результат кожної видно в колонці Size у широкому режимі та в рядку
стану, коли там увімкнено розмір. Це працює і в LAN- та FTP-панелях. Посилання й
junction не обходяться. Недоступний вміст позначається як частковий результат.
Папки, які чекають на підрахунок, мають позначку Queued. Через дві секунди
підрахунку в рядку поточної папки з’являється спінер.
Пересування курсора в списку залишає спінер у рядку папки, яку ще рахують.
Esc скасовує поточний підрахунок і чергу активної панелі, залишаючи
вже обчислені розміри та поточний каталог.
Перехід до іншого каталогу чи джерела панелі скасовує підрахунок.
- Під списком кожної панелі з позначками показано кількість позначених
елементів і їхній сумарний розмір. Файли враховуються одразу, папки — у
міру завершення підрахунку через F3. Позначка ≥ означає, що сума
неповна, а число біля «to measure» показує, скільки позначених папок
ще без розміру.
- F3 і F4 працюють і на панелі LAN. Файл завантажується у тимчасову копію
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
копії, Files відхиляє запис і залишає зміни в редакторі. Для F4 оновіть
KSwitcher також на віддаленому ПК. Alt+F3 і Alt+F4 потребують локальної копії.
- Вікно використовує той самий шрифт і розмір, що й файлові панелі,
синю палітру Far за замовчуванням,
рядок стану згори й підказки клавіш унизу. Інформація про файл
вирівняна праворуч. Режим (Edit або View) стоїть у дужках після імені,
далі йдуть кодування, синтаксис, позиція курсора й сторінка великого файла.
Номери рядків показані приглушеним кольором з невеликим відступом від тексту.
Меню редактора й переглядача використовують моноширинний шрифт і кольори
обраної схеми. У FAR (blue) написи верхнього меню чорні, поточний пункт
має чорне тло, а літери доступу жовті. F9 відкриває меню, Alt з літерою
доступу відкриває потрібний розділ. Редактор позначає незбережені зміни зірочкою.
Esc і F10 закривають незмінений файл одразу. Якщо вміст змінився,
діалог Far пропонує Save, Discard або Cancel.
- Syntax → Automatic визначає синтаксис за іменем, розширенням або
shebang. Відомі типи включають C#, C/C++, JavaScript/TypeScript,
HTML, XML, CSS, SQL, Python, PowerShell, Bash, JSON, YAML, TOML і Markdown.
У меню Syntax можна вибрати будь-який вбудований лексер Lexilla або Plain text.
Стан багаторядкової конструкції починається заново на межі сторінки.
- Ctrl+PgUp/PgDn перемикають сторінки, F5 переходить до заданої сторінки,
Ctrl+Shift+Home/End відкривають першу й останню. Ctrl+F шукає в поточній
сторінці, F3 повторює пошук. Ctrl+A виділяє поточну сторінку.
Історія Undo/Redo діє в межах відкритої сторінки.
- Початкова сторінка займає близько 1 МіБ файла. Для вставок і редагування
сторінка може вирости до 8 МіБ у UTF-8. Зміни інших сторінок тимчасово
зберігаються на диску. F2 або Ctrl+S потоково записують нову копію в
папку файла, тож збереження потребує вільного місця для цієї копії.
UTF-8 із BOM або без нього та UTF-16 LE/BE із BOM зберігають своє
кодування. Нередаговані байти копіюються без перетворення.
- Команда Options у панелях, редакторі й переглядачі відкриває один діалог
KSwitcher Files Options. Розділи Viewer та Editor зберігають окремі профілі.
**Viewer → Markdown** задає максимальну ширину документа (0 — усе вікно),
гарнітуру та розмір основного тексту. Порожня гарнітура використовує системний
шрифт. Apply одразу оновлює відкриті перегляди Markdown.
Після повторного відкриття Options відновлюється останній розділ, зокрема
після Cancel. Пошуковий запит і чернетка змін не зберігаються.
З редактора або переглядача діалог відкриває відповідний розділ. Apply
застосовує зміни до відкритих вікон, Cancel відкидає незастосовану чернетку.
Доступні перенесення рядків, номери рядків, показ пробілів і
кінців рядків, підсвічування поточного рядка, ширина табуляції від 1 до 16,
схеми FAR (blue), Dark і Light та власні кольори. Save scheme у розділі
Viewer або Editor додає поточну палітру до спільного списку схем. Apply
зберігає її та робить доступною в обох розділах. У редакторі також можна
ввімкнути вставлення пробілів замість табуляцій і автоматичні відступи,
а також вибрати символи кінця для нових рядків.
- Діалоги пошуку й переходу до сторінки використовують подвійні рамки та
кнопки Files. Search має компактний розмір, сіре тло, бірюзове поле та окремі кнопки
Find previous і Find next. Word і Selection підставляють у поле слово
під курсором або однорядкове виділення. Поле має висоту одного рядка
й вертикально центрований текст. Стрілка біля поля або Alt+Down
відкриває історію з групуванням за датами. Вибір запису підставляє
запит у поле. Editor і Viewer спільно зберігають до 100 останніх
різних запитів між запусками. Спільний шрифт панелей, меню й тексту змінюється в
Options → Appearance → Font. Редактор і переглядач отримують новий
шрифт після Apply.
### Параметри файлових панелей
- Options у головному меню спочатку прибирає смугу меню й одразу відкриває стандартний діалог Windows. Ліворуч є пошук за назвою категорії чи параметра й дерево результатів. Вибір дочірнього вузла відкриває лише його редактор праворуч. Пошук за назвою окремої властивості відкриває вузол, що її містить. Перемикання вузлів зберігає незастосовані зміни.
- File panel modes має вузли Panel layout, Wide panel columns і Status line columns. У Colors кожен колір має власний вузол. В Appearance шрифт редагується у вузлі Font. Діалог змінює розмір від розміру, який вміщує всі параметри. Ширина лівої навігації стала, дерево росте по висоті, а права область використовує додатковий простір. OK, Cancel та Apply лишаються внизу праворуч.
- Reset selected to defaults скидає вибраний рівень дерева. Корінь All settings скидає всі параметри, навіть коли пошук приховує частину дерева. У редакторах із кількома параметрами Reset property скидає лише вибрану властивість. Скидання змінює чернетку до Apply або OK. Стандартний Panel background — `#000080`.
- Apply доступна, коли чернетка відрізняється від застосованих налаштувань. Після Apply або повернення всіх значень до застосованих вона вимикається. Apply одразу зберігає зміни й перемальовує панелі за відкритим діалогом. OK робить те саме й закриває діалог. Cancel і Escape відкидають зміни після останнього Apply та повертають фокус до панелі.
- Apply доступна, коли чернетка відрізняється від застосованих налаштувань. Після Apply або повернення всіх значень до застосованих вона вимикається. Apply одразу зберігає зміни й перемальовує панелі за відкритим діалогом. OK робить те саме й закриває діалог. Cancel і Escape відкидають зміни після останнього Apply та повертають фокус до командного рядка.
- Colors → File type styles налаштовує текст, фон, підкреслення й закреслення для правил за розширенням і групи System and hidden. Розширення можна вибрати зі списку Windows або додати вручну з крапкою чи без неї. Вони зберігаються в KSwitcher, незалежно від асоціацій Windows. Курсор, позначки й результат передачі зберігають свої сигнальні кольори. Кольори правила можна перевизначити окремо для звичайного рядка, позначки Insert, курсора у фокусі та курсора без фокуса. Позначка має пріоритет над курсором, а підсвічування передачі має пріоритет над кольорами курсора. Без перевизначення стан зберігає звичайний вигляд панелі. Мініпанель унизу редактора одразу показує всі чотири стани на синтетичних рядках до Apply.
@@ -66,9 +429,9 @@ Far Manager є зразком для оформлення файлового м
## Панелі
- Ctrl+8 відкриває список усіх ярликів папок. Кожен рядок показує групу
й назву або шлях. Enter відкриває папку в активній панелі, F4 редагує
ярлик, а Delete прибирає його зі списку.
- Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів
у відкритих локальних папках. Фокус залишається там, де був, а курсор
лишається на поточному елементі, якщо той ще існує.
- У Change drive повідомлення No paired computers з’являється після
успішної відповіді з порожнім списком. Збої локального запиту до
@@ -96,11 +459,14 @@ Far Manager є зразком для оформлення файлового м
- F5, F6, F8 і Shift+Delete у віддалених панелях використовують спільні підтвердження, попередження й прогрес. F5/F6 працюють із файлами та деревами папок між локальними й віддаленими панелями, зокрема між двома різними ПК. Між шляхами одного віддаленого ПК вміст копіюється на ньому. F8 використовує кошик того ПК, на якому лежить файл.
- Після розриву з’єднання повтори F5 або F6 до того самого призначення. Віддалене копіювання відновлюється з підтвердженої позиції, якщо збережені байти відповідають початку вихідного файла. Підтверджене скасування видаляє частковий запис поточного файла. Завершені файли лишаються на місці. Наявний файл призначення замінюється після повного запису, а при переміщенні джерело видаляється після підтвердження запису призначення.
- F7, пункт Files → Make folder і кнопка F7 Mkdir відкривають модальний діалог Far. Стрілка біля імені та Alt+Down відкривають історію успішних введень. Link type має варіанти none, directory junction і symbolic link. Поле Target активне для посилань і приймає абсолютний шлях або шлях від поточної папки. У віддаленій панелі посилання створюється на віддаленому ПК, а symbolic link залежить від дозволів Windows на цьому ПК.
- Process multiple names дозволяє розділити імена комами або крапками з комою. Якщо такий символ є частиною імені, візьми ім’я в подвійні лапки. Діалог створює елементи у поточному каталозі, оновлює панель і ставить курсор на останній створений елемент. При помилці в середині списку вже створені елементи зберігаються.
- Після F5 або F6 успішно оброблені елементи коротко підсвічуються в панелі, що показує папку призначення. Підсвітка тексту відрізняється від курсора й не переносить фокус.
- У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size.
Розділювач Size проходить по одній вертикалі в заголовку та списку, а праві краї підпису й значень вирівняні.
- Бірюзовий курсор поточного рядка видно лише в активній панелі, зокрема коли клавіатурний фокус переходить у командний рядок. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
- Поточний шлях відображається по центру верхньої подвійної лінії панелі. Лінію видно з обох боків напису. Бірюзове тло активної панелі охоплює лише напис шляху з невеликими відступами. Довгий шлях скорочується в межах панелі.
@@ -108,9 +474,11 @@ Far Manager є зразком для оформлення файлового м
## Спільні елементи діалогів
- Власні діалоги Files блокують дії панелей і командного рядка, залишаючи
системний заголовок і рамку головного вікна доступними. Клік поза діалогом
системний заголовок і рамку головного вікна доступними. Клік у Files поза діалогом
діє як Cancel. Для прогресу копіювання, переміщення й видалення це відкриває
підтвердження скасування.
підтвердження скасування. Перелік і обробка файлів виконуються у фоновому
потоці. Діалог залишається доступним під час очікування файлового вводу-виводу.
Скасування перевіряється між кроками операції та під час передачі блоків.
- Enter активує кнопку у фокусі. Для кнопок із власним малюванням використовуй спільний обробник `dialogButtonEnter`. У підтвердженні скасування початковий фокус стоїть на No.
@@ -118,10 +486,26 @@ Far Manager є зразком для оформлення файлового м
- Для власних діалогів і списків Far використовуй спільні метрики та малювання подвійної рамки. Еталон Delete задає 8 px від краю тла до першої лінії та 14 px від внутрішньої лінії до бічної межі вмісту при 96 DPI. Обидва відступи масштабуються за DPI. Вертикальний відступ враховує висоту заголовка та нижніх підказок. Діалоги й списки зберігають свою палітру та поведінку.
- Appearance → Dialog frame налаштовує зовнішній і внутрішній відступи від 0 до 24 px при 96 DPI. Row text padding додає від 0 до 4 ширин символу з кожного боку тексту в рядках Folder shortcuts. Inner padding задає відстань від рамки до краю списку. Ширина попапа враховує обидва текстові відступи, а довгі шляхи скорочуються в межах доступної ширини. Живий зразок показує чернетку. Apply зберігає значення, Cancel відкидає незастосовані зміни, Reset selected to defaults повертає 8 px, 14 px і 0 символів. Профілі без цих параметрів використовують ті самі значення.
- У ресурсі чи виклику задавай назву кнопки й клавішу доступу. Спільна функція `paintDialogButton` центрує текст, підсвічує фокус і додає фігурні дужки для дії за замовчуванням та квадратні для решти кнопок.
- Модальні діалоги редактора й переглядача використовують той самий шрифт, що й діалоги операцій Files. Розміри полів і кнопок враховують метрики цього шрифту.
- Нижні секції з кнопками у Copy, Warning і вікні прогресу мають однакову висоту, прив’язану до висоти рядка шрифту. Використовуй `layoutDialogButtons` для такої секції та `centerDialogRow` для інших рядків між роздільниками. Межі секції визначають положення рядка.
- Для текстових полів Far використовуй ресурс `FAR_EDIT` і спільну підготовку та палітру діалогів. Поля призначення Copy/Rename і Title/Path використовують нативний Win32 Edit без рамки, моноширинний шрифт і вертикальне центрування. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
- Search і спільні нижні секції Far використовують компактні проміжки між рядками й кнопками, прив’язані до метрик моноширинного шрифту. У Search висота кнопки дорівнює висоті одного рядка.
- Нижні кнопки Far групуються по центру. Їхня ширина залежить від напису й дужок, а проміжок між ними становить приблизно половину символу.
- Прапорці Far у Search, Copy і попередженнях використовують спільний компонент. У фокусі короткий системний курсор блимає між дужками, а тло рядка зберігає колір діалогу.
- У Copy і Rename/Move шлях перевіряється у фоновому потоці, і в цей час
діалог можна скасувати. Помилки шляху показує окремий червоний модальний діалог Far. Після його закриття фокус повертається до поля шляху.
- Помилки копіювання, переміщення й видалення показуються в червоному
модальному діалозі Far із причиною помилки та кнопкою OK.
- Якщо локальне перейменування або видалення заблоковане, кнопка Processes… відкриває
список процесів із назвою та PID. Перевірка папки включає вкладені елементи.
End process завершує вибраний процес після окремого підтвердження, після
чого список оновлюється. Якщо Windows обмежила доступ або перевірку
великої папки завершено частково, про це повідомляється в діалозі.
Операцію можна повторити після звільнення файла чи папки.
- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення.
- Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
- Випадаючі списки Far використовують бірюзове тло палітри менеджера. Текст і стрілку вирівнюй вертикально по центру. Прапорці в діалогах операцій використовують позначки `[ ]` та `[x]` і видимий клавіатурний фокус.
- Випадаючі списки й поля Far мають висоту одного рядка шрифту. Бірюзове поле прилягає до сірої ділянки завширшки один символ із темною, вертикально центрованою стрілкою. Make folder, Search і Copy використовують спільне малювання стрілки. Прапорці в діалогах операцій використовують позначки `[ ]` та `[x]` і видимий клавіатурний фокус.
- Розкриті списки й історія Far використовують спільний попап із бірюзовим тлом, світлою рамкою та чорним вибраним рядком. Попап прилягає до обох країв бірюзового поля, стрілка лишається праворуч за межами списку. Історія групується за датами. Довгі списки прокручуються, Enter вибирає рядок, Escape закриває список і повертає фокус до поля.
- Повторно використовуй спільне оформлення. Текст, дії та стан операції передавай із коду конкретної операції. Наприклад, Warning повертає відповідь і стан прапорця, а копіювання вирішує, чи застосувати відповідь до наступних конфліктів.
## Діалог Copy
@@ -152,7 +536,7 @@ Far Manager є зразком для оформлення файлового м
## Видалення
- F8 показує сіре підтвердження з дією Move. Shift+Delete і підтвердження непорожньої папки мають темно-червоне тло. Вікно прогресу видалення має сіре тло, як у Copy.
- Escape у початковому підтвердженні повертає фокус до панелі, з якої викликано видалення. Поточний рядок зберігається, а стрілки одразу працюють.
- Escape у початковому підтвердженні повертає фокус до командного рядка. Поточний рядок активної панелі зберігається, а стрілки одразу працюють.
- F8 переміщує підтверджені елементи в кошик Windows. Shift+Delete видаляє підтверджене дерево від вкладених елементів до батьківської папки. Прогрес і підсумок окремо показують успішні, пропущені й невдалі дії.
- Cancel і Esc у вікні прогресу відкривають спільне червоне підтвердження скасування. Yes зупиняє операцію, а No або Esc у підтвердженні повертає до прогресу. Початковий фокус стоїть на No.
+37 -20
View File
@@ -7,21 +7,22 @@ arranged on a monitor grid. Mouse and keyboard follow neighboring cells, includi
A → B → C, without relaying input through B. New text and images are also shared
with all online paired computers: history and the active clipboard.
## Files and diagnostic logs
## Trusted LAN clients
In **Settings → Computers → Manage computers…**, select an online paired
computer and choose **Send file…**. Both computers need a build with file transfer.
Files up to 16 MiB travel over encrypted LAN. On the destination, open
**Incoming files…** to save or discard each file. The save dialog suggests the
original filename. KSwitcher shows a Windows notification when a file is ready
to save, and its tray tooltip shows the pending count. Pending files are held
in memory until saved, discarded, or KSwitcher closes.
Open **Settings → Computers → Manage computers → Trusted clients** and choose **Add client…**. Select the Dirlume executable, confirm, then click **Save** in Settings. Dirlume can list existing LAN pairs, browse their drives, and download regular files using each remote computer’s file-access permissions. Pairing credentials stay in the resident KSwitcher process.
To retrieve the current or rotated diagnostic log, enable **Allow paired
computers to download diagnostic logs** on the computer that owns the logs.
This setting defaults to off. On the requesting PC, select that computer and
choose **Download log…** or **Previous log…**. Diagnostic logs may contain
text copied from applications.
Select an executable, choose **Remove**, then click **Save** to revoke access. Add the executable again after updating it, since KSwitcher checks the approved path and SHA-256 fingerprint.
## Remote files and diagnostic logs
Use **KSwitcher Files → Change drive** or Dirlume with a trusted-client entry
to browse and copy remote files. Starting in v0.7.0, Manage computers
focuses on pairing, shared input and diagnostic logs.
On the computer that owns the logs, enable **Allow paired computers to download
logs** in **Diagnostic logs** (off by default). On the requesting computer,
select the paired PC and choose **Current log…** or **Previous log…**.
Diagnostic logs may contain text copied from applications.
### MCP
@@ -37,17 +38,21 @@ the local resident process running and log downloads enabled on the remote PC.
## Set up multiple computers
1. Install the v0.6.58 or newer on every participating PC. Input protocol v2 requires all participants to update; earlier one-pair builds cannot connect. Preserve local data; do not copy pairing identities between PCs.
2. Open **Settings → Computers → Manage computers…** and enable discovery on both PCs.
2. Open **Settings → Computers → Manage computers** and enable discovery on both PCs.
Only running LAN-enabled KSwitcher instances appear, not generic network devices.
In wide windows, the computer list and monitor layout grow side by side.
In narrow windows, they stack above Diagnostic logs. The list identifies
offline pairs, and Connection help appears below the input sharing controls.
3. Match the computer name and instance-ID prefix displayed on the other PC.
Select each other, generate one code, enter that same code on both, then click
Pair on both within two minutes. Spaces, hyphens and uppercase hex are accepted.
Enable discovery and click **Save** on each PC to make peers visible.
Select each other, generate one code, and enter it on both. Click **Pair**, then
**Apply** or **Save** on each PC within two minutes. Use **Apply** to keep the pairing status visible. Spaces, hyphens and uppercase hex are accepted.
4. Pair each physical input source with every destination it must control. For
unrestricted control from any PC, pair every pair of PCs. Drag monitors into
neighboring grid cells and arrange the same physical layout relative to each
local PC. For A → B → C, A sees B at (1,0), C at (2,0); B sees A at (-1,0),
C at (1,0). Enable input sharing on all PCs. The button controls all pairs,
independently of the selected list item. Positions save immediately.
C at (1,0). Enable input sharing and click **Save** on all PCs to apply sharing
and the monitor layout. The input sharing setting covers all pairs.
5. Stop MWB or another mouse/keyboard router on both computers before trying
KSwitcher input sharing, to avoid two tools forwarding the same events.
6. Wait for the authenticated input connection. Move the cursor through the
@@ -57,6 +62,12 @@ the local resident process running and log downloads enabled on the remote PC.
into the source computer restores its cursor at the corresponding edge. Empty
cells, diagonal-only neighbors and offline PCs do not transfer control.
When input sharing is enabled, the tray icon shows a steady gray dot if all
paired PCs are offline, a pulsing amber dot while a discovered PC is connecting,
a green dot when all online paired PCs are connected, and a red dot if the LAN
worker stops. Hover over the icon to see the connection status and the connected
count when only some paired PCs are connected.
The source cursor is parked and hidden beneath a tiny no-activation window. A
small banner identifies remote control; no full-screen layered bitmap is retained.
The destination uses its own keyboard layout and runs its own hotkeys/snippets.
@@ -103,8 +114,14 @@ VLANs, public IPv4 and IPv6-only networks are not supported by discovery yet.
A second LAN-enabled KSwitcher cannot use the same ports on one computer.
Input first tries TCP in the usual direction, then reverse TCP after 1.5 seconds.
If TCP has not authenticated after 5 seconds, the lower-ID peer negotiates an
encrypted UDP input session on the existing discovery socket (UDP 45883).
LAN discovery authenticates paired PCs before starting new input connections.
Discovery remains active while all paired PCs are offline and wakes input sharing
when one reappears. An authenticated input connection survives missed discovery
announcements. Once discovery has expired and the channel closes, further input
attempts wait for fresh discovery.
After at least 5 seconds, the lower-ID peer starts encrypted UDP fallback on the
discovery socket (UDP 45883) once its current TCP connection attempt has failed
or reached its 10-second deadline.
UDP uses fresh session challenges, authenticated encryption, ordered event
numbers, acknowledgements and bounded retries; duplicated packets do not repeat
key presses. Two seconds without authenticated traffic or acknowledgement
+172 -62
View File
@@ -7,11 +7,11 @@ The original [Typlo](https://github.com/bitcodepro/Typlo) project and its data r
**[User guide / Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki)** — setup, features, shortcuts, dictionaries, screenshots and troubleshooting in **English** and **[Українська](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home-uk)**. Each wiki page links to its translation.
From v0.6.72, use **Settings → Snippets** to edit snippets in place and
**Save snippets** to save them independently. **Clipboard** contains OCR
**Save** to apply snippet edits together with other settings. **Clipboard** contains OCR
options. **Sync**, **Computers**, and **Diagnostics** have their own tabs.
**Українською.** З v0.6.72 сніпети редагуються у **Settings → Snippets**
і зберігаються окремою кнопкою **Save snippets**. OCR розміщено у
і зберігаються разом з іншими налаштуваннями кнопкою **Save**. OCR розміщено у
**Clipboard**, а для синхронізації, ПК та журналу є окремі вкладки
**Sync**, **Computers** і **Diagnostics**.
@@ -114,18 +114,20 @@ Run `build/KSwitcher.exe`, or extract `dist/KSwitcher-win-x64.zip` and run the e
The build also refreshes the release copy in `build/release/`. Exit KSwitcher before rebuilding.
The application lives in the notification area. Right-click its icon for Settings, Snippets and history.
Double-click the tray icon to open Settings, the bold default menu item.
Closing Settings with unsaved changes (including accepted auto-correction or OCR options)
asks whether to save, discard changes, or keep editing. Unchanged settings close without a prompt.
**Apply** and **Save** at the bottom of Settings commit the pending edits across every page,
including Mouse, Manage computers and OpenBao. **Apply** keeps the current page open.
**Save** closes Settings. With pending edits, **Cancel** or closing the window asks whether
to discard them or keep editing. When there are no pending edits, **Close** exits without a prompt.
If saving fails, the window stays open with your edits intact.
Settings displays **No unsaved settings** when the draft matches the saved settings. If **Start with Windows** is enabled, **Save** remains available to recheck the autostart path.
The Computers window applies and saves network changes immediately, separately from Settings.
Pairing shows the target computer and remaining wait time; enter the same code and click **Pair** on both PCs.
Enable discovery and click **Save** on each PC before looking for peers. Enter the same code and
click **Pair**, then **Apply** or **Save**, on both PCs. Use **Apply** to watch the target and
remaining wait time without closing Settings.
The code stays visible for copying or retry until the pair is saved. A saved pair still requires input sharing to be enabled on both PCs.
Input automatically tries direct TCP, reverse TCP (after 1.5 seconds), and encrypted UDP over discovery (after 5 seconds).
Both PCs need an updated build for all fallback methods. The connection status identifies the selected transport.
If attempts remain unsuccessful for 15 seconds, **Connection help** explains checks and provides copyable administrator PowerShell commands for the running executable on that PC. Run each PC's own command locally; rules allow only the local subnet. Commands are never executed automatically.
**Unsaved changes — click Save to apply** appears for pending edits, including accepted
chat-language, auto-correction and OCR changes. Cancelling a child dialog or restoring
The Settings footer shows pending edits, including accepted chat-language, auto-correction and OCR changes. Cancelling a child dialog or restoring
the original values clears its pending changes. Snippets saved in their own window
remain saved independently; the Settings indicator reflects any other pending edits.
Menus support access keys: press the underlined letter while the menu is open (for example,
@@ -144,15 +146,18 @@ in the resident app. Screen capture and all screenshot editors run on demand in
process. Closing the last editor (or cancelling the only selection) exits that process. It does not
load resident settings, dictionaries, clipboard history or keyboard hooks. Editor windows have
stable numbered titles within that process. Keep all three executables together when copying or
updating the application. Close screenshot editors before installing an update.
updating the application. After verifying a new package, the updater closes Files, the text and
screenshot editors, Settings, and bundled StayHere for that installation. Save open work before approving an update.
If settings change in the tray while the configurator is open, a conflicting Save is rejected; reopen
the configurator to load the latest settings.
Updates from v0.3.x–v0.4.1 first install the compatible **v0.4.2 bridge** through
Update in the tray menu. Select Update again to install the full current release;
manual extraction is not required. Future full releases use stable `release-vX.Y.Z`
tags, which the bridge and newer clients recognize. Older clients ignore those tags
and continue to find the bridge instead of skipping it. Versions v0.2.3 and earlier
still require the previously documented initial configurator migration.
Updates from v0.3.x–v0.4.1 go through the compatible **v0.4.2 bridge**. If tray
**Update** does not find it, download [v0.4.2](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases/tag/v0.4.2),
close KSwitcher and its editors, and extract the bridge ZIP into the installation
directory while keeping personal data, dictionaries, and tools. Start v0.4.2
and select **Update** to install the current full release. Full releases use
stable `release-vX.Y.Z` tags recognized by the bridge and newer clients.
Versions v0.2.3 and earlier still require the previously documented initial
configurator migration.
Modern ZIPs contain `release-files.json` (schema, version, file paths, sizes and SHA-256
hashes). The updater validates that every packaged file is declared, all hashes match,
@@ -182,10 +187,10 @@ Exit [Typlo](https://github.com/bitcodepro/Typlo) when using overlapping shortcu
This also works for each layout's **Direct layout shortcut**. Backspace or Delete without modifiers
clears a shortcut. Tab moves to the next field. The recorded shortcut is suppressed while the field
has focus, so recording the conversion shortcut does not perform a conversion.
All configured shortcuts use the existing keyboard hook and can replace ordinary Windows/app
The Files shortcut is registered with Windows. The other configured shortcuts use the keyboard hook and can replace ordinary Windows/app
shortcuts, including **Win+V** and **Win+Shift+S**, while KSwitcher is running. Only exact configured
combinations are intercepted. Unassigned shortcuts and simulated copy/paste pass through.
Choose another shortcut or exit KSwitcher to restore the original action. Windows protects
Pause input processing, choose another shortcut or exit KSwitcher to restore the original action. Windows protects
Ctrl+Alt+Delete and Win+L; these cannot be assigned.
Keyboard and mouse input forwarded by Microsoft Mouse Without Borders follows the same input
@@ -198,6 +203,28 @@ keys cannot trigger recursive commands or overwrite the recorded typing run. Oth
is accepted, including key-up events and VK-only keyboard events. Unicode packets do not provide
physical key positions and therefore reset recent-word tracking; selection conversion still works.
### Pause input processing
Right-click the KSwitcher tray icon and choose **Pause input processing** before testing another keyboard tool.
The purple **K** changes to two white pause bars on a gray tile. The tooltip says **Input processing paused** once KSwitcher releases its shortcuts and
stops keyboard and mouse actions, autocorrection, snippets, automatic layout switching, LAN mouse and keyboard
control, and simulated F15 activity. Clipboard history has its own pause control. You can browse entries
during an input pause and paste them after resuming. If you launched the standalone **StayHere** utility,
its own tray icon controls its F15 activity.
Choose **Resume input processing** in the same menu after testing. The tooltip then shows **Input processing active**. If another program still holds a shortcut,
KSwitcher identifies the combination and stays paused. Release it in the other program and retry.
The pause lasts for the current run.
**Українською.** Перед тестуванням іншої програми клацни правою кнопкою значок KSwitcher у треї й вибери
**Pause input processing**. Фіолетова **K** зміниться на дві білі смуги на сірому тлі. Підказка **Input processing paused** підтвердить паузу. KSwitcher
звільняє гарячі клавіші й призупиняє дії клавіатури та миші, автокорекцію, сніпети, автоматичне перемикання
розкладки, LAN-керування й імітацію F15. Історія буфера обміну має окремий перемикач. Записи можна переглядати
під час паузи та вставляти після відновлення. Якщо окремо запущена утиліта **StayHere**, її імітація F15
керується з її власного значка в треї.
Для відновлення вибери **Resume input processing**. Підказка покаже **Input processing active**. Якщо комбінація зайнята, звільни вказаний хоткей
в іншій програмі та повтори спробу. Пауза діє до завершення поточного запуску.
### Screen capture and annotations
Press **Win+Shift+S**, choose **Capture screen region…** in the tray menu, or run
@@ -408,8 +435,9 @@ thumbnails and source labels aligned with the scaled fonts and spacing.
> З v0.6.50: OCR чатів Viber тимчасово вимкнений. Збережені профілі Viber залишаються, але не діють. Профілі Telegram і Teams та OCR зображень/буфера працюють як раніше.
Settings separates General, Languages, Shortcuts, Clipboard and Tools into native tabs.
Switching tabs preserves edits; Save, Cancel, Import and Export stay available below every page.
In Settings, choose a section in the navigation tree or use **Search settings** to find an individual option.
Drag the divider to resize navigation. The window remembers its size, position, and active section.
Switching sections preserves your edits. Save, Cancel, Import and Export stay below every page.
Open the desired chat in Telegram Desktop or Microsoft Teams, then open Settings → Languages →
**Languages for a chat…**. Select the chat and click the languages to include. Choose
@@ -430,9 +458,9 @@ profile. Telegram unread counters are ignored. Teams currently recognizes the de
Experimental Viber profiles introduced in v0.6.49 are disabled in v0.6.50 because repeated OCR caused delays. There is no background Viber OCR, recognition during language switching, or recognition when opening profiles. Saved Viber profiles are retained and marked inactive; Windows switching and Next layout use their normal/global behavior in Viber. Clipboard and image OCR are unchanged.
From v0.6.53, chat profiles (application, visible chat name and ordered language IDs) are included in settings synchronization and manual export/import. Update every synchronizing PC to v0.6.53 or newer first: older clients reject this shared field. Profiles for different chats merge independently; conflicting edits or deletion versus editing of one chat require a choice. Missing Windows layouts stay saved and are skipped during switching, with global-cycle fallback if none are installed. Keep this PC's layouts preserves the global cycle and shortcuts while chat profiles still synchronize. Downloading a pre-v0.6.53 profile preserves existing chat profiles. Chat matching is unchanged; Viber profiles remain inactive.
**Українською.** Налаштування розділено на вкладки General, Languages, Shortcuts, Clipboard
і Tools. Перехід між ними зберігає незбережені зміни; Save, Cancel, Import і Export доступні
на кожній вкладці. Відкрий потрібний чат у Telegram або Teams, потім **Settings → Languages → Languages
**Українською.** Вибирайте розділ у дереві Settings або шукайте окремий параметр через **Search settings**.
Перетягніть розділювач, щоб змінити ширину дерева. Settings запам’ятовує розмір і положення вікна
та активний розділ. Перехід між розділами зберігає чернетку. Save, Cancel, Import і Export доступні знизу. Відкрий потрібний чат у Telegram або Teams, потім **Settings → Languages → Languages
for a chat…**. Вибери чат і потрібні мови, натисни **Use languages**, а потім **Save**.
Набір діє для **Alt+Shift**, **Win+Space**, **Win+Shift+Space** та **Next layout** KSwitcher.
Можна вибрати й одну мову; порядок зберігається із загального списку під час редагування профілю. **Remove profile**
@@ -458,10 +486,11 @@ Recognition uses Chrome accessibility: the address bar and active document must
### Snippet autocomplete — v0.6.69
Starting with v0.6.71, **Enter** accepts a suggestion after you navigate
the list with **↑ / ↓**. Without arrow navigation, **Enter** goes to the
editor. З v0.6.71 **Enter** після вибору стрілками вставляє сніпет. Без
переміщення списком **Enter** надходить до редактора.
**Enter** accepts a single visible suggestion directly. When several suggestions
are visible, navigate the list with **↑ / ↓** to select one for **Enter**.
**Українською.** **Enter** одразу підтверджує єдину видиму підказку. Якщо
підказок кілька, виберіть потрібну стрілками **↑ / ↓**, а тоді натисніть **Enter**.
Starting with v0.6.70, suggestions open at the text caret. If the editor
provides no caret position, you can still type the complete trigger to
@@ -470,14 +499,16 @@ expand the snippet.
Type `;` at the start of a trigger to open suggestions near the caret, or
type the first three characters of another trigger. The list filters as you
type and fits the widest matching trigger. Use **↑ / ↓** and **Tab** or click
an entry. **Esc** dismisses the list. Full triggers still expand
automatically. See the [snippet guide](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets).
an entry. **Esc** dismisses the list. Full triggers expand automatically at the
start of a word, including when typed in another keyboard layout. See the
[snippet guide](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets).
**Українською.** Введіть `;` на початку тригера або три перші символи іншого
тригера, щоб відкрити підказки біля курсора. Список фільтрується під час набору
й підлаштовує ширину під найдовший збіг. Для вибору натисніть **↑ / ↓** і
**Tab** або клацніть рядок. **Esc** закриває список. Повні тригери й далі
спрацьовують автоматично. Дивіться [посібник зі сніпетів](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets-uk).
**Tab** або клацніть рядок. **Esc** закриває список. Повні тригери спрацьовують
автоматично на межі перед словом, зокрема під час набору в іншій розкладці.
Дивіться [посібник зі сніпетів](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Snippets-uk).
З v0.6.70 підказки відкриваються біля текстового курсора. Якщо редактор не
надає його позицію, введіть повний тригер для розгортання сніпета.
@@ -488,15 +519,35 @@ ChatGPT and Codex desktop editors use paced selection for snippet triggers. If o
**Українською.** У настільних ChatGPT і Codex тригер виділяється з паузами між натисканнями. Якщо виділилася лише перевірена кінцева частина, KSwitcher доповнює виділення й перевіряє весь тригер перед заміною. Інший текст або зміна фокусу скасовують операцію. Тригери розпізнаються в різних розкладках. Один сніпет можна прив’язати до кількох програм через **Add app** або назви процесів через кому; ці прив’язки вже підтримують синхронізацію.
### Snippet macros
In **Settings → Snippets**, choose **Insert macro or marker…**. Enter a pause duration or click the recording field and press the keys. They appear as you press them. Release the keys and click **Insert**. You can also type expressions into the replacement text. KSwitcher runs each macro between text segments in the listed order. A leading macro runs after the first text segment, as in earlier versions. A snippet needs some replacement text.
- `{{shift}}`, `{{alt}}` and `{{tab}}` tap individual keys. Key names are case-insensitive. Letters, digits, `F1`–`F24`, navigation and editing keys also work.
- `{{altr}}+{{ctrl}}` holds both keys together. Join key markers with `+` without spaces and put modifiers before the final key, as in `{{ctrl}}+{{shift}}+{{A}}`. Use `l` or `r` after `ctrl`, `alt`, `shift` or `win` to select a side. The unsuffixed names use the left keys.
- `rider .{pause:50}{enter}` inserts `rider .`, waits 50 milliseconds, then presses Enter. One pause can be 0–10,000 milliseconds. Use `{{return}}` for Enter inside a chord, as in `{{ctrl}}+{{return}}`.
- Write `{{cursor}}`, `{{enter}}`, `{{pause:50}}` or `{{{shift}}}` to insert the corresponding marker literally.
**Українською.** У **Settings → Snippets** натисни **Insert macro or marker…**. Для паузи введи тривалість, а для клавіш клацни поле запису й натисни потрібні клавіші. Вони з’являються під час натискання. Відпусти їх і натисни **Insert**. Макроси також можна вписати в текст заміни. KSwitcher виконує макроси між частинами тексту за порядком запису. Макрос на початку, як і раніше, виконується після першої частини тексту. Сніпет має містити текст заміни.
- `{{shift}}`, `{{alt}}` і `{{tab}}` натискають окремі клавіші. Регістр назви клавіші не має значення. Також підтримуються літери, цифри, `F1`–`F24`, клавіші навігації та редагування.
- `{{altr}}+{{ctrl}}` затискає обидві клавіші разом. З’єднуй маркери знаком `+` без пробілів і став модифікатори перед основною клавішею, як у `{{ctrl}}+{{shift}}+{{A}}`. Суфікси `l` і `r` у назвах `ctrl`, `alt`, `shift` і `win` вибирають ліву й праву клавіші. Без суфікса використовується ліва.
- `rider .{pause:50}{enter}` вставляє `rider .`, чекає 50 мілісекунд і натискає Enter. Допустимий діапазон однієї паузи — від 0 до 10 000 мілісекунд. Для Enter у комбінації використовуй `{{return}}`, наприклад `{{ctrl}}+{{return}}`.
- Записуй `{{cursor}}`, `{{enter}}`, `{{pause:50}}` або `{{{shift}}}`, щоб вставити відповідний маркер як звичайний текст.
For example, `$skill-name{pause:500}{enter} Draft text{cursor}` types the token, waits 500 milliseconds, presses Enter once, then types the draft. The focused application handles Enter. Each `{enter}` sends a separate press.
Наприклад, `$skill-name{pause:500}{enter} Текст чернетки{cursor}` вводить назву, чекає 500 мілісекунд, натискає Enter один раз і вводить чернетку. Enter обробляє програма у фокусі. Кожен `{enter}` надсилає окреме натискання.
### Application-specific snippets — v0.6.51
In **Settings → Snippets**, select a snippet and enable **Only in these applications**. Enter executable names separated by commas, or select a currently open application's process and choose **Add app**. For example: `ms-teams.exe, outlook.exe`. Uncheck the option for a global snippet. A checked but empty restriction cannot be saved. Use **Save snippets** to apply the changes.
In **Settings → Snippets**, select a snippet and enable **Only in these applications**. Drag the crosshair next to **Add app** onto an open window to add its application. Repeat for each application. You can also select a process from the dropdown and click **Add app**, or type executable names separated by commas, such as `ms-teams.exe, outlook.exe`. Uncheck the option for a global snippet. A checked but empty restriction cannot be saved. Click **Save** at the bottom of Settings to apply the changes.
A matching application-specific snippet takes precedence over a global snippet with the same trigger. The same trigger can be used for different applications; overlapping scopes for the same trigger are rejected. Existing snippets without a scope remain global. Matching is case-insensitive by process name, with or without `.exe`, and is checked before insertion. No OCR or timer is involved. Chrome scope means the entire browser, not one website.
Scopes are saved with snippets and included in manual import/export and synchronization; merge conflicts consider the application scopes. Use v0.6.51 or newer on every synchronizing PC before sharing scoped snippets: older versions do not understand the restriction and may treat the snippet as global.
**Українською.** У **Settings → Snippets** вибери сніпет, увімкни **Only in these applications** та задай назви процесів через кому або вибери відкриту програму зі списку й натисни **Add app**. Наприклад: `ms-teams.exe, outlook.exe`. Вимкнений прапорець означає всі програми. Увімкнений прапорець із порожнім списком не можна зберегти. Натисни **Save snippets**, щоб застосувати зміни.
**Українською.** У **Settings → Snippets** вибери сніпет і ввімкни **Only in these applications**. Перетягни мішень поруч із **Add app** на відкрите вікно, щоб додати його програму. Повтори для кожної потрібної програми. Також можна вибрати процес зі списку й натиснути **Add app** або вписати назви процесів через кому, наприклад `ms-teams.exe, outlook.exe`. Вимкнений прапорець означає всі програми. Увімкнений прапорець із порожнім списком не можна зберегти. Натисни **Save** внизу Settings, щоб застосувати зміни.
Сніпет конкретної програми має пріоритет над глобальним із тим самим тригером. Для різних програм однакові тригери дозволені, для перетинних областей — ні. Старі сніпети залишаються глобальними. Зіставлення за назвою процесу не залежить від регістру та суфікса `.exe`; OCR і таймерів немає. Для Chrome це весь браузер, а не окремий сайт. Обмеження входять до експорту/імпорту та синхронізації. Перед синхронізацією онови всі ПК до v0.6.51 або новішої: старі версії не розуміють обмеження та можуть застосувати сніпет глобально.
### Existing features
@@ -513,12 +564,12 @@ Scopes are saved with snippets and included in manual import/export and synchron
editor selection metadata remain identical. Unobserved or altered foreign copies are rejected.
Snippets normally require accessibility verification of their selected trigger and pasted text,
even with logging disabled. If verification is unavailable or the paste differs, expansion
stops without running cursor or Enter actions. Clipboard changes during paste also cancel actions.
stops before placing the cursor or running key actions. Clipboard changes during paste also cancel actions.
Far Manager uses its native Alt+Shift+Arrow selection, Ctrl+Insert copy and Shift+Insert
paste commands instead: both the trigger and inserted text must match verified clipboard
copies from Far. Cancellation restores the full temporary selection, not one cursor step.
Far supports nonempty single-line replacements up to 4096 caret steps, including
`{cursor}` and verified `{enter}` actions. Empty or multiline replacements are rejected
`{cursor}` and key macros after verification. Empty or multiline replacements are rejected
before selection; pasting a newline could execute a command before it can be verified.
- Teams recent-word conversion uses a single word-selection command and validates the copied range.
If the editor's word boundary differs from the recorded typing, it falls back to paced character
@@ -535,12 +586,10 @@ Scopes are saved with snippets and included in manual import/export and synchron
repeat-conversion state and does not switch the Windows layout.
- Case cycling, Russian/Ukrainian transliteration, verified undo and repeated conversion.
- Text snippets across layouts, multiline insertion and a verified `{cursor}` position;
`{enter}` presses Enter after insertion and cursor placement (once per marker), before buffered typing resumes.
For example, `rider .{enter}` inserts `rider .` and presses Enter.
macros run between text segments, before buffered typing resumes.
Automatic correction is suppressed during snippet expansion and for typing buffered by that expansion; the global setting is preserved.
If the trigger cannot be verified after the copy attempts, it is preserved, queued typing resumes,
and no Enter action is sent.
`{{cursor}}` and `{{enter}}` insert literal markers. Snippets are stored as plaintext settings, as in [Typlo](https://github.com/bitcodepro/Typlo).
and no key actions are sent. Snippets are stored as plaintext settings, as in [Typlo](https://github.com/bitcodepro/Typlo).
- Clipboard history for text, HTML/RTF, file lists, DIB and PNG images; plain-text paste;
full-text search, pinning, deletion, full text viewing and image previews.
- Image thumbnails and text/file icons appear directly in the history list. Only visible rows
@@ -561,13 +610,13 @@ Scopes are saved with snippets and included in manual import/export and synchron
retry recognition. Requires a Windows OCR language installed for the user profile; automatic
failures are logged quietly. OCR sidecars count toward the history size limit and are removed
with their images.
- Optional Tesseract 5 support is available in **Settings → OCR options…**. Windows OCR remains
- Optional Tesseract 5 support is available in **Settings → Clipboard → Image text recognition**. Windows OCR remains
the default and has no Tesseract dependency. Install the 64-bit Tesseract 5 Windows package
separately, then enable it and choose language codes such as `ukr+eng+rus`. Leave the executable
path blank to detect a standard installation, or select `tesseract.exe`; its neighboring
`libtesseract-5.dll`, dependencies and `tessdata` language files are required. **Check installation**
validates the selected models. **Download Tesseract…** opens the Windows installer page in your
browser. No packages or models are downloaded automatically.
browser. Use **Apply** or **Save** in Settings to commit OCR changes.
Tesseract processes screenshots locally in memory with a 30-second recognition deadline.
Changing engine, executable path or languages refreshes cached image text in the background.
- History exclusion flags and excluded processes, pause/resume, count/size limits.
@@ -599,8 +648,9 @@ Pressing the history shortcut a second time pastes the second-most-recent item.
Data is in `data/` beside the executable, falling back to `%LOCALAPPDATA%/KSwitcher` when
the executable's directory is not writable. Each clipboard payload is an encrypted disk file;
only bounded previews/metadata stay in memory. Image data is loaded on demand and released when
the history popup is hidden. Settings **Write log** (`writeLog`, enabled by default) controls all
log writes. Disabling it also clears diagnostic context from memory; existing log files remain.
the history popup is hidden. Settings **Write log** (`writeLog`, off by default) controls all
log writes. Enable it when collecting diagnostics that may include typed or copied text.
Disabling it also clears diagnostic context from memory. Existing log files remain.
Diagnostic stages stay in a memory buffer of at most 128 events for 30 seconds.
Selection diagnostics include the expected text, each copied candidate before and after suffix
recovery, paced Shift+Left progress or batch delivery counts, and clipboard sequence changes,
@@ -660,9 +710,57 @@ This is a working native implementation, not a claim of complete UI/release pari
The Windows focus/injection rules still apply: an unelevated process cannot edit an elevated app.
Conversion is cancelled rather than pasting into a different window or replacing unverified recent text.
## Google Drive settings backup
Open **Settings → Sync → Google Drive** and choose **Connect** to authorize
KSwitcher in your browser. To sync between PCs, check **Use Google Drive for
automatic synchronization**, then click **Apply** or **Save**. On the first
PC, choose **Upload local settings to sync profile** to create the initial
profile. On the other PCs, connect to the same account, enable Google Drive
sync and choose **Sync now**. The resident syncs at startup, every ten minutes
and after saving. Independent changes merge, and concurrent edits to the same
setting can be reviewed under **Resolve individual conflicts**.
Each PC uses one automatic provider. Enabling Google Drive turns off OpenBao
sync and keeps its connection details. Enabling OpenBao turns off Google Drive
sync. Manual Google Drive backups remain available with either provider.
Turn off Google Drive sync and apply the change before switching Google
accounts or disconnecting.
**Back up saved settings** adds a copy of your last applied settings to the
backup list. The list shows the backup date, source and size, newest first.
Use **Load older backups** to see more when available. Select a row and choose
**Restore selected backup** to load that copy into the draft after confirmation. Review the result
and choose **Apply** or **Save**. **Disconnect** removes the refresh token from
Windows Credential Manager and leaves existing backups in Google Drive.
The automatic sync profile is separate from manual backup history. Applying
a manual restore makes it a local change that the active provider can sync.
Backups include layouts, shortcuts, snippets, compatible language and mouse
profiles, personal dictionaries and clipboard history preferences. Windows
autostart, diagnostic logging, credentials, paired computer state, clipboard
contents, screenshots and local executable paths stay on the computer.
Install any Windows layouts used by the backup before restoring. Each backup
is limited to 2 MiB.
The Win32 app can read KSwitcher-New's `kswitcher-drive-backup-v1` snapshots
when both builds have access to the same Google application's private Drive
folder. Win32 imports supported settings and keeps destination values for
fields absent from the backup. Preview-only settings such as the theme and
disabled snippets have no Win32 equivalent. Win32 writes its own versioned
snapshot, which KSwitcher-New does not import.
To enable the page in a build, supply `KSWITCHER_GOOGLE_CLIENT_ID` and
`KSWITCHER_GOOGLE_CLIENT_SECRET` in the build environment before running
`build.ps1` or configuring CMake. Use a Google OAuth **Desktop app** client
with the Drive API enabled. Use the same authorized Google application as
KSwitcher-New for access to its existing backups. The browser flow uses
PKCE and requests the `drive.appdata` scope. Builds without both values
show the page with its actions disabled.
## OpenBao synchronization (experimental, opt-in)
The **Sync...** button is available in Settings for everyone. Synchronization remains disabled
Open **Settings → Sync → OpenBao**. Synchronization remains disabled
until you configure your own OpenBao and enable it. Connection configuration is saved separately
in `sync.json`. The portable data directory is normally `data/` beside the executable; installations
without a writable application directory use the existing local-app-data fallback.
@@ -674,23 +772,22 @@ authentication mount (default `userpass`). Use the same profile on each of your
administrator-provisioned private access, not public account registration. Non-root namespaces,
reverse-proxy URL prefixes, MFA login flows and other providers are not implemented yet.
Enable synchronization and choose **Save / Sign in / Sync**. The dialog saves connection changes
immediately; the main Settings window's Save/Cancel does not control this separate configuration.
When synchronization is disabled, connection fields and sync actions are inactive. Check **Enable
synchronization** to make them available. To disable an existing connection, uncheck it and click
**Save**; this preserves the saved connection and password without starting a sync request.
Check **Enable synchronization**, enter the connection details and click **Save** at the bottom of
Settings. Use **Sync now** on the OpenBao page to start an immediate sync with the saved connection.
To disable synchronization and keep the saved password, uncheck **Enable synchronization** and click
**Save**.
**Disconnect / forget password** remains available while synchronization is disabled.
A blank password keeps the existing Windows credential for that server, login mount and username.
The password is saved in Windows Credential Manager, not in settings exports, logs or the remote
profile. HTTPS certificate validation is mandatory and redirects are refused. Login tokens are
kept in memory for one sync attempt, with best-effort self-revocation afterwards. Configure bounded
token lifetimes on the server as well (for example a 5-minute default and 10-minute maximum).
**Disconnect / forget password** disables synchronization and removes the current connection's
Choose **Disconnect / forget password**, then click **Save** to disable synchronization and remove the current connection's
saved credential. A request already sent to the server may still complete; its downloaded settings
will not be applied after the connection changes. Old credentials for other connection identities
can be removed in Windows Credential Manager under `KSwitcher.Sync/`.
On the first connection, **Save / Sign in / Sync** merges the existing profiles without
On the first connection, **Sync now** merges the existing profiles without
requiring a whole-profile replacement. Independent entries (such as snippets, exclusions and
replacement pairs) are combined. Different values for the same setting remain on their respective
sides and appear in **Resolve individual conflicts...**; no value is guessed without a common history.
@@ -699,7 +796,7 @@ Nonconflicting changes synchronize immediately, and unresolved conflicts survive
- **Upload local** creates the remote profile or replaces it with this PC's saved shared settings.
- **Download remote** replaces this PC's shared settings with the server profile.
- If the server has no profile yet, choose **Upload local** to create it.
- Unsaved edits in Settings are not synchronized. After a successful **Download remote**, the open Settings window refreshes automatically and keeps the selected tab. The download confirmation warns that unsaved edits will be discarded.
- Unsaved edits in Settings are not synchronized. After a successful **Download remote**, the open Settings window refreshes automatically and keeps the selected section. The download confirmation warns that pending edits to shared settings will be discarded.
- The status distinguishes downloading, downloaded settings, no local changes and failure. HTTP 400 errors identify authentication, download or upload; field errors remain visible until the next action.
Once connected, the resident checks at startup, every **10 minutes**, and about two seconds after saving settings, on a separate
@@ -738,8 +835,8 @@ paths refer to the same locations and may need updating on a fresh installation.
Connection details and credentials stay local so you can sign in again after reinstalling.
Clipboard history, screenshots and dictionary files are never uploaded. Full synchronization identifies
missing keyboard layouts by language (when Windows can identify it) and exact ID.
Install the same layout variant, or select **Keep this PC's layouts and layout shortcuts (sync
other settings)** and click **Save / Sign in / Sync**. This device-local option keeps the entire
Install the same layout variant, or select **Keep this PC's layouts and layout shortcuts**
and click **Save**. This device-local option keeps the entire
local layout cycle and its direct shortcuts unchanged while synchronizing the other shared settings.
The server's layout cycle and direct shortcuts are preserved on automatic sync and explicit Upload;
Download also keeps the local layout configuration. Later syncs cannot erase missing server layouts
@@ -828,7 +925,7 @@ Target layouts must also be enabled in the layout cycle.
### Custom replacements and spelling typos
Two optional modes in **Auto-correction options…** extend layout correction. Both are off by
Two optional modes in **General → Correction options** extend layout correction. Both are off by
default and require the main **Automatic correction (experimental)** checkbox to be enabled.
- **Use custom replacements**: enter one `typo=correction` pair per line, for example
@@ -871,7 +968,8 @@ after Space, not immediately after a punctuation key. Save Settings to apply cha
only to words with a rank at or below that number (for example, 10000). All dictionary words still
protect already valid input, and ambiguous alternatives remain unchanged regardless of this limit.
**My dictionary** provides separate English, Ukrainian and Russian fields for correct words missing
from the bundled dictionaries. Enter words separated by commas or new lines, then click OK and Save
from the bundled dictionaries. A hyphen is allowed between letters, as in `test-mt` or `dev-mt`.
Enter words separated by commas or new lines, then click OK and Save
in Settings. Case and duplicates are normalized automatically; no file editing or ranks are needed.
The v0.6.23 bundled Ukrainian dictionary includes `поточні`. The updater preserves existing dictionary files;
if upgrading from an older dictionary, add this word in My dictionary → Ukrainian and click OK → Save.
@@ -895,8 +993,10 @@ language in the configured dictionary order (the UI uses English, Ukrainian, Rus
Different valid spellings remain ambiguous and are left unchanged.
**Minimum word length** defaults to 3 and can be set from 1 to 32 letters. Surrounding punctuation
does not count toward this minimum; the maximum word length is 32 letters.
Known words, ambiguous alternatives, ALL CAPS, mixed-case identifiers, numbers, URLs and email
addresses are left unchanged. Short trailing punctuation is retained when the editor selects it
Known words, ambiguous alternatives, mixed-case identifiers, numbers, URLs and email addresses
are left unchanged. Fully uppercase words can be corrected when the target is in **My dictionary**.
For example, add `qa` under English and set the minimum word length to 2 or lower to correct
`ЙФ` to `QA` after Space. Short trailing punctuation is retained when the editor selects it
together with the word. Actual selected text is verified before replacement. Layout switching follows
the existing switch-layout setting. The configured Undo shortcut restores the original and suppresses
that word for the rest of the session (until restart).
@@ -920,11 +1020,20 @@ CC BY-SA 4.0; attribution, pinned source revision and license are in `dictionari
## Latest compiled release
The [Release folder](Release/README.md) contains the latest portable Windows x64 ZIP and SHA-256 checksum.
Run `./package.ps1 -PublishRelease` after building and testing to refresh the tracked release archive.
Download the portable Windows x64 ZIP from [Gitea Releases](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases).
The [Release folder](Release/README.md) tracks the release notes, manifest and SHA-256 checksum.
Run `./package.ps1 -PublishRelease` after building and testing. Upload `dist/KSwitcher-win-x64.zip`,
`dist/KSwitcher/release-files.json` and `Release/SHA256SUMS.txt` as Gitea release assets.
Keep the ZIP in `dist/` and attach it to the release without committing it to Git.
## Verification
The Files build uses CMake 3.24 or later and Ninja, both included in the local
w64devkit toolchain. CMake downloads pinned Scintilla and Lexilla source
archives for the built-in viewer and editor on the first configure. The
[Scintilla and Lexilla license](resources/files-text-license.txt) is also
embedded in KSwitcher.Files.exe.
```powershell
.\build.ps1 -Test # Pure/native regression checks; does not touch the user's clipboard
.\build.ps1 -Ocr # Render a synthetic image, decode it with WIC and recognize it with Windows OCR
@@ -983,8 +1092,7 @@ Keep `v0.4.2` as the last legacy `vX.Y.Z` release. Publish full packages as
`release-vX.Y.Z` (stable, not prerelease), including `release-files.json`,
`KSwitcher-win-x64.zip` and `SHA256SUMS.txt`. Never publish a manifest package under a
legacy version tag: clients that have not installed the bridge would select it.
Keep the compatibility bridge in the first 100 releases returned by Gitea while
supporting old clients; their immutable update code only reads that page.
Legacy clients only read the first 100 releases returned by Gitea. The bridge is now outside that page. For v0.3.x–v0.4.1, follow the manual bridge installation instructions above.
### Editors that omit copied trailing spaces
@@ -1010,7 +1118,9 @@ Check **★ Pinned only** beside the history search box to show only pinned entr
History opens in a separate, short-lived instance of **KSwitcher.exe**. **Esc** closes it even when focus is on the window or an action button, releasing Windows UI allocations with the process. The resident keeps keyboard hooks, clipboard capture and history storage. Search and the pinned-only filter are preserved in encrypted view state. Each fresh opening selects and reveals the newest matching entry; background refreshes preserve the selected record while browsing. If a full-text item viewer is still open, the helper stays alive until the last viewer closes. Pin/delete, formatted/plain paste and OCR remain available; settings and default shortcuts are unchanged.
Image thumbnails are decoded in **KSwitcher.Screenshot.exe**, returning only bounded preview pixels. Image clipboard backup/restore also uses that helper and encrypted temporary files, with clipboard-sequence checks before restoring. Selection reads avoid loading image formats. Keep all three executables together; no fourth executable is required. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident.
Image thumbnails are decoded in **KSwitcher.Screenshot.exe**, returning only bounded preview pixels.
History reuses separate helper processes for OCR and thumbnails so recognition can run alongside previews.
Idle history helpers exit after 30 seconds, and closing the history host stops its helpers. During text conversion, a short-lived instance of **KSwitcher.Screenshot.exe** holds the image clipboard backup in memory and restores it only if the clipboard sequence still matches. Selection reads avoid loading image formats. Keep the executables from the same ZIP together. Paste allows a brief foreground handoff after history closes while preserving cancellation checks. UI Automation remains in the resident.
A live development-build test measured **4.37 MiB before history and 4.35 MiB after two open/Esc cycles**, compared with an earlier roughly 8–9 MiB plateau. A same-image clipboard-backup benchmark retained **12.78 MiB before versus 0.05 MiB after**. These measure private working set, not a guaranteed total footprint. Include all helpers when measuring active use: combined memory can be higher while history is open. No forced working-set trimming is used. Existing screenshots and shortcuts remain applicable. The v0.6.38 approach of retaining a hidden history window/RichEdit control is superseded by process termination.
+475 -2
View File
@@ -1,5 +1,478 @@
# Latest Windows release
## v0.7.4 — 2026-11-25
- **Settings → Sync → Google Drive** supports automatic synchronization and a dated list of manual backups. Only one automatic provider is active per PC. Restore a selected backup into the Settings draft and review it before pressing **Apply** or **Save**.
- **Help → User guide** opens a searchable offline guide with the current keyboard shortcuts and built-in manuals. The tray also has **Help → About KSwitcher** and a separate coffee icon for **Donate via Monobank**.
- Clipboard history, the screenshot editor and Help have distinct window and taskbar icons. Clipboard history and the screenshot editor use the Settings palette. OCR is a child page under **Clipboard**, and clipboard exclusions can be added using the window picker.
- The editors on **Custom replacements**, **Snippets** and **Mouse** use the available window height. The computer list, monitor layout and action rows on **Manage computers** are aligned.
**Українською.**
- **Settings → Sync → Google Drive** підтримує автосинхронізацію та список ручних резервних копій із датами. На кожному ПК активний лише один автоматичний провайдер. Вибрана копія завантажується в чернетку, яку можна переглянути перед **Apply** або **Save**.
- **Help → User guide** відкриває офлайн-довідку з пошуком, поточними гарячими клавішами та вбудованими посібниками. У треї також є **Help → About KSwitcher** і чашка біля окремого пункту **Donate via Monobank**.
- Історія буфера, редактор скріншотів і довідка мають окремі значки вікон і панелі завдань. Історія та редактор використовують палітру Settings. OCR винесено на дочірню сторінку **Clipboard**, а програми до винятків буфера можна додавати через приціл.
- Редактори **Custom replacements**, **Snippets** і **Mouse** розтягуються за висотою вікна. На **Manage computers** вирівняно список ПК, схему моніторів і ряди дій.
## v0.7.3 — 2026-11-24
- **Apply** commits pending edits across Settings and keeps the current page open. **Save** commits the same edits and closes Settings. **Close** appears when the draft is clean. **Cancel** asks before discarding pending edits.
- Mouse actions, discovery, pairing, monitor positions, input sharing, trusted clients, diagnostic log permissions and the OpenBao connection are part of the Settings draft. For new LAN pairs, enter the same code and choose **Pair**, then **Apply** or **Save**, on both PCs. Use **Sync now** to synchronize with a saved OpenBao connection.
- Settings and the diagnostic log viewer follow the Windows accent and contrast settings.
**Українською.**
- **Apply** зберігає правки всіх розділів Settings і залишає поточну сторінку відкритою. **Save** зберігає ті самі правки й закриває Settings. За відсутності незбережених правок доступна кнопка **Close**. **Cancel** запитує підтвердження перед відкиданням чернетки.
- Дії миші, пошук комп’ютерів, сполучення, розташування моніторів, спільний ввід, довірені клієнти, дозвіл на завантаження журналів і підключення OpenBao входять до чернетки Settings. Для нового сполучення введіть однаковий код і натисніть **Pair**, а тоді **Apply** або **Save** на обох ПК. **Sync now** запускає синхронізацію зі збереженим підключенням OpenBao.
- Settings і переглядач діагностичних журналів враховують акцентний колір і параметри контрастності Windows.
## v0.7.2 — 2026-11-24
Nested entries in the Settings navigation tree have a compact indent that follows Windows display scaling, including when you move Settings between monitors.
**Українською.** Вкладені пункти в дереві налаштувань мають компактний відступ, який враховує масштаб Windows і перераховується при перенесенні вікна між моніторами.
## v0.7.1 — 2026-11-24
OpenBao connection and synchronization actions are now on **Settings → Sync → OpenBao**. Choose **Save and sync** on that page to save the connection and start synchronization. Settings search can find OpenBao fields, and switching sections preserves the connection draft.
**Українською.** Підключення й дії синхронізації OpenBao тепер доступні в **Settings → Sync → OpenBao**. Натисніть **Save and sync** на цій сторінці, щоб зберегти підключення й запустити синхронізацію. Пошук Settings знаходить поля OpenBao, а перехід між розділами зберігає чернетку підключення.
## v0.7.0 — 2026-11-24
- The native Settings window has a resizable navigation tree and a **Search settings** field. Search finds individual settings, highlights matches, and scrolls the selected control into view.
- Settings remembers its window position, size, sidebar width, and last section. Pages adapt to narrower windows. **General → Correction options** groups dictionaries, exceptions, word boundaries, and substitutions.
- **Computers → Manage computers** opens in Settings and groups pairing, input sharing, and diagnostic logs. Use KSwitcher Files or Dirlume for browsing and copying remote files.
**Українською.**
- У нативному вікні Settings з’явилися дерево розділів зі змінною шириною та поле **Search settings**. Пошук знаходить окремі параметри, підсвічує збіги й прокручує до вибраного поля.
- Settings запам’ятовує положення й розмір вікна, ширину дерева та останній розділ. Сторінки підлаштовуються під вузькі вікна. У **General → Correction options** згруповано словники, винятки, межі слів і заміни.
- **Computers → Manage computers** відкривається в Settings і групує спарювання, спільний ввід та діагностичні журнали. Для перегляду й копіювання файлів з іншого ПК використовуйте KSwitcher Files або Dirlume.
## v0.6.132 — 2026-11-23
In **Settings → Snippets**, **Insert macro or marker…** can add cursor and Enter markers, a pause in milliseconds, or a recorded key or key combination. Keys appear as you press them. Release the keys, click **Insert**, and use the main **Save** button to apply snippet edits together with other settings.
Clipboard snapshots track the sequence after Windows prepares delayed formats. A sequence advance caused by the read can no longer abort the text operation. When image backup fails, diagnostics include the helper's error.
**Українською.** У **Settings → Snippets** кнопка **Insert macro or marker…** додає маркери курсора й Enter, паузу в мілісекундах або записану клавішу чи комбінацію. Клавіші видно під час натискання. Відпустіть їх, натисніть **Insert** і збережіть правки головною кнопкою **Save**.
Під час створення копії буфера KSwitcher бере номер послідовності після підготовки відкладених форматів Windows. Зміна номера під час самого читання більше не перериває текстову операцію. Якщо резервне копіювання зображення не вдалося, журнал показує помилку допоміжного процесу.
## v0.6.131 — 2026-11-23
In **Settings → Computers → Manage computers… → Trusted clients**, choose **Add client…** and select Dirlume.exe. Dirlume can then browse drives on computers already paired in KSwitcher and download regular files. Remove the executable to revoke access. After updating Dirlume, add the new executable again.
**Українською.**
У **Settings → Computers → Manage computers… → Trusted clients** натисніть **Add client…** і виберіть Dirlume.exe. У Dirlume можна відкривати диски комп’ютерів, які вже спарені в KSwitcher, і завантажувати файли. Видаліть виконуваний файл зі списку, щоб відкликати доступ. Після оновлення Dirlume додайте новий файл повторно.
## v0.6.130 — 2026-11-22
The tray shows a purple **K** while KSwitcher processes input. Choose **Pause input processing** to see two white pause bars on a gray tile. The purple **K** returns after **Resume input processing** succeeds. If another program still holds a shortcut, the pause bars stay visible.
**Українською.**
Фіолетова **K** у треї означає, що KSwitcher обробляє введення. Після вибору **Pause input processing** з’являються дві білі смуги на сірому тлі. Фіолетова **K** повертається після успішного **Resume input processing**. Якщо інша програма ще утримує гарячу клавішу, значок паузи залишається.
## v0.6.129 — 2026-11-22
Choose **Pause input processing** in the tray to test another keyboard tool. The tooltip shows **Input processing paused** once KSwitcher releases its shortcuts and stops keyboard and mouse actions, snippets, autocorrection, automatic layout switching, LAN input and simulated F15 activity. Clipboard history can still record entries. Choose **Resume input processing** to restore input. If a shortcut is occupied, KSwitcher names it and stays paused until you retry. Restarting KSwitcher also clears the pause.
**Українською.**
Щоб протестувати іншу програму для клавіатури, виберіть **Pause input processing** у треї. Підказка **Input processing paused** з’явиться, коли KSwitcher звільнить гарячі клавіші та призупинить дії клавіатури й миші, сніпети, автокорекцію, автоматичне перемикання розкладки, LAN-керування й імітацію F15. Історія буфера може й далі записувати нові елементи. Виберіть **Resume input processing** для відновлення. Якщо комбінація зайнята, KSwitcher покаже її та залишиться на паузі до повторної спроби. Перезапуск KSwitcher також скидає паузу.
## v0.6.128 — 2026-11-22
In **Settings → Snippets**, drag the crosshair next to **Add app** onto an open window to add its application. Repeat for each application, then choose **Save snippets**. Esc cancels a drag. Picking the same application twice adds it only once.
**Українською.**
На вкладці **Settings → Snippets** перетягніть мішень поруч із **Add app** на відкрите вікно, щоб додати його програму. Повторіть для кожної потрібної програми й натисніть **Save snippets**. Esc скасовує перетягування. Повторний вибір програми не створює дубліката.
## v0.6.127 — 2026-11-21
When the snippet popup shows one match, pressing Enter expands it immediately and consumes the key. With several matches, use the arrow keys and then press Enter to confirm.
**Українською.**
Якщо у списку підказок є один збіг, Enter одразу розгортає сніпет. KSwitcher перехоплює це натискання. Якщо збігів кілька, виберіть потрібний стрілками й підтвердьте через Enter.
## v0.6.126 — 2026-11-21 (withdrawn / відкликано)
Snippet macros send the configured keys at the position where they appear. `$skill{pause:500}{enter} Draft text` types the name, waits 500 milliseconds, presses Enter once, then types the remaining text. The focused application handles each key.
**Українською.**
Макроси сніпетів натискають задані клавіші в указаній позиції. `$skill{pause:500}{enter} Текст` вводить назву, чекає 500 мілісекунд, один раз натискає Enter і вводить решту тексту. Кожне натискання обробляє програма у фокусі.
## v0.6.125 — 2026-11-21 (withdrawn / відкликано)
Snippet macros between text segments run before the next segment is inserted. In Codex, `$skill{pause:500}{enter} Draft text` selects the matching skill suggestion and leaves the following text in the composer. Extra Enter markers at the same selection point do not submit the draft. Expansion stops when the suggestion cannot be verified.
**Українською.**
Макроси між частинами сніпета виконуються перед вставленням наступної частини. У Codex `$skill{pause:500}{enter} Текст чернетки` вибирає відповідний скіл із підказок і залишає наступний текст у редакторі. Повторні маркери Enter у тій самій позиції не надсилають чернетку. Якщо підказку не вдалося перевірити, розгортання зупиняється.
## v0.6.124 — 2026-11-21
Snippets can tap keys such as `{{shift}}`, hold combinations such as `{{altr}}+{{ctrl}}`, and wait with `{pause:50}`. After verifying the inserted text and placing `{cursor}`, KSwitcher runs the macros in order. The Snippets tab groups marker buttons and **Macro help…** below the editor, with **Save snippets** at the right.
**Українською.**
Сніпети підтримують окремі клавіші, як-от `{{shift}}`, комбінації на кшталт `{{altr}}+{{ctrl}}` і паузи, як-от `{pause:50}` на 50 мс. KSwitcher виконує макроси за порядком запису після перевірки вставленого тексту й встановлення `{cursor}`. На вкладці **Snippets** кнопки маркерів і **Macro help…** згруповані під редактором, а **Save snippets** розташована праворуч.
## v0.6.123 — 2026-11-20
- The tray shows a steady gray dot when all paired PCs are offline. The amber dot pulses while a discovered PC is connecting. Green means every online paired PC is connected.
- LAN discovery stays active. Once discovery has expired and the last input channel closes, KSwitcher pauses mouse and keyboard connection attempts until a paired PC reappears.
**Українською.**
- Коли всі спаровані ПК офлайн, у треї видно статичну сіру крапку. Жовта крапка пульсує під час підключення до знайденого ПК. Зелена означає, що всі доступні спаровані ПК під’єднані.
- Пошук у LAN продовжує працювати. Коли строк дії підтвердження присутності спливає й останній канал вводу закривається, KSwitcher призупиняє спроби підключення миші та клавіатури до появи спарованого ПК.
## v0.6.122 — 2026-11-20
- LAN mouse and keyboard sharing lets a TCP attempt finish or time out before starting the encrypted UDP fallback.
- The tray icon pulses amber while reconnecting, shows green when all paired PCs are connected, and shows red if the LAN service stops. Hover to see connection status and how many PCs are connected. Diagnostic logs distinguish a declined cursor handoff from returned control.
**Українською.**
- Під час передавання миші та клавіатури KSwitcher чекає завершення TCP-спроби або її тайм-ауту, перш ніж запустити резервне з’єднання через зашифрований UDP.
- Іконка в треї пульсує жовтим під час перепідключення, показує зелену крапку, коли всі спаровані ПК під’єднані, і червону, якщо LAN-модуль зупинився. Наведіть курсор, щоб побачити стан і кількість підключених ПК. У діагностичному журналі видно, коли другий ПК відхилив перехід курсора або повернув керування.
## v0.6.121 — 2026-11-20
KSwitcher Files retries WebView2 startup once when a Markdown preview fails to initialize. If the retry succeeds, the same window displays the formatted document. The Markdown viewer loads the bundled Mermaid library only for documents with Mermaid diagrams.
Snippet expansion now requires a word boundary before the trigger, even after a pause. The same rule applies across keyboard layouts and in Far Manager.
**Українською.**
Якщо перегляд Markdown не запускається, KSwitcher Files один раз повторює запуск WebView2. Після успішної спроби форматований документ з’являється в тому самому вікні. Бібліотека Mermaid завантажується лише для документів із діаграмами Mermaid.
KSwitcher розгортає сніпети, коли тригер відокремлено від попереднього слова. Перевірка діє після паузи, у різних розкладках і у Far Manager.
## v0.6.120 — 2026-11-20
Layout conversion starts faster when the Windows clipboard contains an image. KSwitcher keeps the image and accompanying formats in memory for the duration of the operation. It restores them after conversion if the clipboard still belongs to the operation. A newer copy takes precedence.
**Українською.**
Перетворення розкладки починається швидше, коли в буфері обміну Windows є зображення. KSwitcher тримає зображення й супровідні формати в пам’яті до завершення операції. Копія відновлюється, якщо буфер усе ще належить операції. Новіше копіювання має пріоритет.
## v0.6.119 — 2026-11-18
KSwitcher Files runs local commands in the folder shown at the command prompt. After switching panes or opening a different folder, commands such as `git clone` and relative path suggestions use that folder in the same PowerShell session.
**Українською.**
KSwitcher Files запускає локальні команди в папці, показаній перед командним рядком. Після перемикання панелі або переходу до іншої папки команди на кшталт `git clone` і підказки відносних шляхів використовують цю папку в тій самій сесії PowerShell.
## v0.6.118 — 2026-11-18
- **Shift+F11** opens a side-by-side comparison of two selected text files from local, LAN or FTP panes. The comparison has its own taskbar button, a movable divider, a native toolbar, **F7/F8** change navigation, and **Ctrl+wheel** text zoom. The shortcut, font and colors are configurable in **Options → File comparison**.
- The footer of each file pane shows the number and combined size of marked items, including folders measured by **F3**. **Ctrl+Left/Right** resize the file panes.
- When Windows denies access during a supported local **F5–F8** operation, Files offers to retry with administrator rights through UAC.
- Markdown task checkboxes save their state to the source file. Mermaid flowchart labels appear above the connecting lines.
**Українською.**
- **Shift+F11** відкриває двостороннє порівняння двох вибраних текстових файлів із локальних, LAN- або FTP-панелей. Вікно має власну кнопку на панелі завдань, рухомий розділювач і системний тулбар. **F7/F8** переходять між змінами, **Ctrl+колесо** змінює масштаб тексту. Комбінація, шрифт і кольори налаштовуються в **Options → File comparison**.
- Унизу кожної панелі видно кількість і сумарний розмір позначених елементів, зокрема папок, виміряних через **F3**. **Ctrl+←/→** змінюють ширину панелей.
- Якщо Windows відмовляє в доступі під час підтримуваної локальної операції **F5–F8**, Files пропонує повторити її з правами адміністратора через UAC.
- Чекбокси Markdown зберігають стан у вихідному файлі. Підписи з’єднань у блок-схемах Mermaid відображаються поверх ліній.
## v0.6.117 — 2026-11-18
- KSwitcher Files supports saved FTP connections in both panes. Browse UTF-8 file names, open or edit remote files with **F3/F4**, save with **F2**, copy between a local and FTP pane with **F5**, rename with **F6**, and permanently delete with **F8**.
- **F3** measures folders on local, LAN and FTP panes. On `..` it queues every folder in the current list. Waiting folders show **Queued** and the active folder shows a spinner after two seconds. **Esc** cancels the active pane’s calculation and queue.
- The source menu separates local drives, FTP and KSwitcher LAN. **1** opens FTP and the remaining displayed digits select LAN actions. Wide pane **Size** dividers align, and **Ctrl+F** on `..` inserts the open folder’s path.
**Українською.**
- KSwitcher Files підтримує збережені FTP-підключення в обох панелях. Назви файлів читаються в UTF-8. **F3/F4** відкривають перегляд і редактор, **F2** зберігає зміни, **F5** копіює між локальною та FTP-панелями, **F6** перейменовує, **F8** видаляє без кошика.
- **F3** рахує розмір локальних, LAN- і FTP-папок. На `..` до черги додаються всі папки списку. Папки в черзі мають позначку **Queued**, а біля поточної через дві секунди з’являється спінер. **Esc** скасовує підрахунок і чергу активної панелі.
- Меню джерел розділяє локальні диски, FTP і KSwitcher LAN. **1** відкриває FTP, решта показаних цифр вибирають LAN-дії. Розділювачі колонки **Size** вирівняні, а **Ctrl+F** на `..` вставляє шлях відкритої папки.
## v0.6.116 — 2026-11-17
- Files displays a live count while reading a folder. **Esc** stops the scan and shows the entries already read. **Ctrl+R** reads the folder again. Mouse selection works beyond the first 65,536 rows.
- Files shows the path of files opened through Windows in the terminal and command history. Choosing a history entry still inserts the command that reopens the file. The embedded terminal hides its inactive cursor.
**Українською.**
- Files показує лічильник під час читання папки. **Esc** зупиняє читання й показує вже прочитані записи. **Ctrl+R** перечитує папку. Вибір мишею працює після перших 65 536 рядків.
- Files показує шлях до файла, відкритого через Windows, у терміналі й історії команд. Вибір запису історії підставляє команду для повторного відкриття. Вбудований термінал приховує курсор, коли він неактивний.
## v0.6.115 — 2026-11-17
- **Shift+F4** opens or creates a file in the active local panel. Leave the name blank for a generated `New_File_…txt` name. After editing a draft, **Esc → Save** opens options for the file name, encoding, BOM, and line endings.
- Typing updates the editor status line without repainting the menu or flashing the editor window.
- When **Enter** opens a local file through Windows, Files displays `start 'path'` in the terminal and saves it in command history.
**Українською.**
- **Shift+F4** відкриває або створює файл в активній локальній панелі. Якщо залишити ім’я порожнім, Files підставить `New_File_…txt`. Після редагування чернетки **Esc → Save** відкриває параметри імені, кодування, BOM і кінців рядків.
- Під час набору редактор оновлює рядок стану без перемальовування меню й миготіння вікна.
- Коли **Enter** відкриває локальний файл через Windows, Files показує `start 'шлях'` у терміналі й додає команду до історії.
## v0.6.114 — 2026-11-17
In KSwitcher Files, clicking a row in the inactive pane highlights that row immediately. The previous cursor row in that pane no longer flashes with the active highlight. If it had a custom unfocused cursor color, it returns directly to its normal style.
**Українською.**
У KSwitcher Files клік по рядку неактивної панелі одразу підсвічує вибраний рядок. Попередній рядок курсора цієї панелі більше не блимає активним підсвічуванням. Якщо він мав окремий колір неактивного курсора, рядок одразу повертається до звичайного оформлення.
## v0.6.113 — 2026-11-17
- KSwitcher Files keeps the terminal output area dark while WebView2 initializes. This fixes the white flash during startup.
- The terminal copy regression test checks for a new clipboard write and verifies its contents without first taking clipboard ownership.
**Українською.**
- Під час запуску термінала область виводу KSwitcher Files залишається темною, поки WebView2 готує сторінку. Це усуває білий спалах під час відкриття термінала.
- Тест копіювання з термінала перевіряє новий запис і його вміст без попереднього захоплення буфера обміну.
## v0.6.112 — 2026-11-17
In KSwitcher Files, **Ctrl+Shift+Tab** cycles backward through Files, Editor, and Viewer windows. **Ctrl+Tab** cycles forward. Both shortcuts wrap at the ends of the window list, including in the Markdown preview.
**Українською.**
У KSwitcher Files **Ctrl+Shift+Tab** обходить вікна Files, редактора й переглядача у зворотному порядку. **Ctrl+Tab** обходить їх у прямому порядку. Обидві комбінації працюють циклічно, зокрема в перегляді Markdown.
## v0.6.111 — 2026-11-17
- KSwitcher Files updates a panel as soon as its background folder scan finishes.
- **Ctrl+U** swaps the panels, keeping their folders, view modes, cursors, marked items, and active panel together. Use **Tab** by itself to switch the active panel. **Ctrl+Tab** cycles between Files, Editor, and Viewer windows.
- Panels and scrollable Files popups share a Far-style scrollbar with up and down arrows, a dotted track, and a thumb lighter than its background.
**Українською.**
- KSwitcher Files оновлює панель одразу після завершення фонового читання папки.
- **Ctrl+U** міняє панелі місцями разом із папками, режимами перегляду, курсорами й позначками. Активна панель залишається активною на новому боці. Для перемикання активної панелі натисніть **Tab** без модифікаторів. **Ctrl+Tab** перемикає вікна Files, редактора й переглядача.
- Панелі та попапи з прокруткою у Files мають спільний скролбар у стилі Far зі стрілками вгорі й унизу, крапковою доріжкою та повзунком, світлішим за фон.
## v0.6.110 — 2026-11-17
Entering a folder or returning to its parent in KSwitcher Files refreshes the affected panel and the command line without repainting the other panel.
Auto-correction can preserve all uppercase letters when correcting to a word in **My dictionary**. With `qa` in the English personal dictionary and **Minimum word length** set to 2 or lower, typing `ЙФ` and pressing Space yields `QA`.
**Українською.**
Під час входу в папку або повернення до батьківської папки KSwitcher Files оновлює потрібну панель і командний рядок. Сусідня панель більше не перемальовується через цей перехід.
Автокорекція зберігає верхній регістр для слів з **My dictionary**. Якщо в особистому словнику English є `qa`, а **Minimum word length** дорівнює 2 або менше, після пробілу `ЙФ` виправиться на `QA`.
## v0.6.109 — 2026-11-17
**Ctrl+0–9** in KSwitcher Files opens the assigned folder or shows only the folders assigned to that digit. **Ctrl+F1** selects Brief and **Ctrl+F2** selects Wide in the active panel. **Ctrl+F3–F12** are reserved for other panel modes. If command history used a Ctrl+function shortcut, set a new binding under **Options → Command line → Command history**.
**My dictionary** accepts hyphens between letters, for example `test-mt` and `dev-mt`. Enter the correct spelling in the dictionary for its language, then click **OK → Save**. Update all PCs that share settings before syncing hyphenated entries.
**Українською.**
У KSwitcher Files **Ctrl+0–9** відкриває призначену папку або показує лише папки, призначені натиснутій цифрі. **Ctrl+F1** вмикає Brief, а **Ctrl+F2** вмикає Wide в активній панелі. **Ctrl+F3–F12** зарезервовані для інших режимів панелей. Якщо історія команд використовувала Ctrl із функціональною клавішею, задайте нову комбінацію в **Options → Command line → Command history**.
**My dictionary** приймає дефіси між літерами, наприклад `test-mt` і `dev-mt`. Введіть правильне написання у словник відповідної мови й натисніть **OK → Save**. Перед синхронізацією слів із дефісами оновіть усі ПК, які обмінюються налаштуваннями.
## v0.6.108 — 2026-11-17
KSwitcher Files adds **Wake** beside the offline status of a paired PC in **Change drive** (Alt+F1 or Alt+F2). Click **Wake** or focus it with the arrow keys and press **Enter**. The status bar reports whether KSwitcher sent the Wake-on-LAN packet.
Update both PCs and let them discover each other once while the target is online so KSwitcher can save its network adapter’s MAC address. Enable Wake-on-LAN on the target. Ethernet is the most reliable option. Wi-Fi requires compatible Wake on Wireless LAN hardware and drivers.
**Українською.**
У KSwitcher Files біля статусу спареного офлайн-ПК у меню **Change drive** (Alt+F1 або Alt+F2) є дія **Wake**. Клацніть **Wake** або виберіть її стрілками й натисніть **Enter**. Рядок стану повідомить, чи вдалося надіслати пакет Wake-on-LAN.
Оновіть обидва ПК і дайте їм один раз побачити один одного, поки цільовий ПК увімкнено, щоб KSwitcher зберіг MAC-адресу його мережевого адаптера. Увімкніть Wake-on-LAN на цільовому ПК. Найнадійніше підключення через Ethernet. Для Wi-Fi потрібна підтримка Wake on Wireless LAN з боку обладнання й драйвера.
## v0.6.107 — 2026-11-16
KSwitcher Files suggests recent commands, PowerShell commands and parameters, and paths as you type. The list works with the panes visible or hidden. Use **Up** or **Down** to select, **Tab** or **Enter** on a selected suggestion to insert it, and **Escape** to close the list. Press **F1** in the command line to open the Microsoft Learn article for a documented Windows command or subcommand.
The offline Windows command catalog includes nested syntax and documented choices such as `schtasks /query /fo LIST`. After `ipconfig /renew ` or `ipconfig /release `, Files suggests local IPv4 adapters configured for DHCP. With Git for Windows, Git completion includes options and matching branch names. With the .NET SDK, `dotnet` completion delegates to the CLI. The main Files window has a new blue two-pane icon inspired by FAR.
**Українською.**
KSwitcher Files підказує недавні команди з історії, команди й параметри PowerShell та шляхи під час набору. Список працює з відкритими й прихованими панелями. Стрілки **↑** і **↓** вибирають підказку, **Tab** або **Enter** на вибраній підказці вставляє її, а **Escape** закриває список. **F1** у командному рядку відкриває статтю Microsoft Learn для документованої команди чи підкоманди Windows.
Офлайн-каталог команд Windows містить вкладений синтаксис і документовані значення, наприклад `schtasks /query /fo LIST`. Після `ipconfig /renew ` або `ipconfig /release ` Files підказує локальні адаптери з DHCP для IPv4. За наявності Git for Windows підказки Git включають параметри й відповідні назви гілок. За наявності .NET SDK підказки для `dotnet` надає сама утиліта. Головне вікно Files має нову синю іконку з двома панелями в стилі FAR.
## v0.6.106 — 2026-11-16
Files scans local and LAN folders and runs copy, move, rename and delete in the background. Copy and Rename/Move validate destinations in the background. A failed operation opens a red Far-style dialog. For local sharing violations, **Processes…** shows possible blockers and **End process** ends the selected process after confirmation. Retry **F6**, **F8**, or **Shift+Delete** after releasing the item.
The screenshot editor repaints the affected area while dragging. History reuses separate OCR and thumbnail helpers, and Windows OCR scales images to the engine’s size limit. Shortcut and snippet processing does less work on keystrokes, and LAN transfers wait for a timeout before retrying unacknowledged chunks.
**Write log** defaults to off for new settings. Existing explicit choices still apply. When enabled, diagnostic logs can contain typed or copied text.
**Українською.**
Files сканує локальні й LAN-каталоги та виконує копіювання, переміщення, перейменування й видалення у фоні. Copy і Rename/Move перевіряють шлях у фоні. Помилки операцій відкривають червоний діалог у стилі Far. При локальному блокуванні **Processes…** показує можливі процеси, а **End process** завершує вибраний процес після підтвердження. Після звільнення повторіть **F6**, **F8** або **Shift+Delete**.
Редактор скриншотів перемальовує змінену область під час перетягування. Історія повторно використовує окремі процеси OCR і мініатюр, а Windows OCR масштабує зображення до ліміту рушія. Обробка хоткеїв і сніпетів виконує менше роботи під час набору. LAN-передача повторно надсилає непідтверджені блоки після тайм-ауту.
**Write log** вимкнено за замовчуванням для нових налаштувань. Явно збережений вибір продовжує діяти. Увімкнений журнал може містити введений або скопійований текст.
## v0.6.105 — 2026-11-16
KSwitcher Files gives the Editor a pencil icon and the Viewer an eye icon. The two modes have separate taskbar groups, and **F6** switches the icon and group in the same window. On a PC running KSwitcher as administrator, LAN PowerShell commands such as `dir` now start with standard user rights. This fixes the `0xC0000142` startup failure on that path. This release replaces v0.6.104.
**Українською.** Редактор KSwitcher Files має іконку олівця, а переглядач — іконку ока. Режими мають окремі групи на панелі завдань Windows, і **F6** перемикає іконку й групу в тому самому вікні. Якщо KSwitcher на ПК-отримувачі запущено від адміністратора, команди PowerShell через LAN, зокрема `dir`, запускаються з правами звичайного користувача. Виправлено помилку запуску `0xC0000142` у цьому сценарії. Цей реліз замінює v0.6.104.
## v0.6.104 — 2026-11-16
**Ctrl+F** or the search icon opens search in the rendered KSwitcher Files Markdown preview. Search ignores case and highlights the current match. **Enter** or **F3** moves to the next match, and **Shift+Enter** or **Shift+F3** moves back. **Escape** closes the search first. This release includes the HTML, Markdown appearance, Options and terminal copy updates from v0.6.103.
**Українською.** **Ctrl+F** або піктограма пошуку відкриває пошук у відрендерованому Markdown у KSwitcher Files. Пошук ігнорує регістр і підсвічує поточний збіг. **Enter** або **F3** переходить до наступного збігу, а **Shift+Enter** або **Shift+F3** повертає до попереднього. **Escape** спочатку закриває пошук. Реліз включає підтримку HTML, налаштування вигляду Markdown, запам’ятовування розділу Options і копіювання з термінала з v0.6.103.
## v0.6.103 — 2026-11-16
The KSwitcher Files Markdown preview renders embedded HTML tables and inline styles such as `white-space: nowrap`. **Options → Viewer → Markdown** sets the preview width, font family and font size. Files Options reopens the last section. **Ctrl+C** and **Ctrl+Insert** copy selected terminal output. This release replaces v0.6.102.
**Українською.** Перегляд Markdown у KSwitcher Files відображає вбудовані HTML-таблиці й стилі, зокрема `white-space: nowrap`. У **Options → Viewer → Markdown** можна задати ширину перегляду, гарнітуру й розмір шрифту. Options відкриває останній відвіданий розділ. **Ctrl+C** і **Ctrl+Insert** копіюють виділений текст із виводу термінала. Цей реліз замінює v0.6.102.
## v0.6.102 — 2026-11-16
In KSwitcher Files, Ctrl+Insert copies the full command line when it contains text. With an empty command line, it copies names from the active pane. The LAN host returns Windows PowerShell startup errors without waiting for a system error dialog. Files explains DLL initialization failure `0xC0000142` and accepts another command. This release replaces v0.6.101.
**Українською.** У KSwitcher Files Ctrl+Insert копіює весь текст непорожнього командного рядка. Якщо рядок порожній, копіюються імена з активної панелі. ПК, який приймає LAN-команду, повертає помилки запуску Windows PowerShell без очікування системного діалогу. Files пояснює помилку ініціалізації DLL `0xC0000142` і знову приймає команди. Цей реліз замінює v0.6.101.
## v0.6.101 — 2026-11-16
In KSwitcher Files, Enter opens the selected item when the command line is empty, including when focus is in the terminal output. The Computers window places pairing and the monitor grid side by side so the bottom actions fit at high display scaling. This release replaces v0.6.100.
**Українською.** У KSwitcher Files Enter відкриває вибраний елемент, коли командний рядок порожній, зокрема коли фокус у виводі термінала. У вікні Computers спарювання та схема моніторів розташовані поруч, тож нижні дії поміщаються і при високому масштабі. Цей реліз замінює v0.6.100.
## v0.6.100 — 2026-11-16
In KSwitcher Files, Enter and Shift+Enter submit the command line when focus is in the terminal output. The terminal scrolls to the latest output when a command is submitted. While a LAN command is still running, Files shows how to cancel it and keeps the next command in the input field. This release replaces v0.6.99.
**Українською.** У KSwitcher Files Enter і Shift+Enter виконують введену команду, коли фокус у виводі термінала. Під час запуску команди термінал прокручується до останнього виводу. Поки виконується LAN-команда, Files показує, як її скасувати, і зберігає наступну команду в полі вводу. Цей реліз замінює v0.6.99.
## v0.6.99 — 2026-11-16
In KSwitcher Files, Enter and Shift+Enter run the command in the command line, including when the file panes are hidden. With visible panes and an empty command line, the keys act on the selected item. A command reveals the terminal output if it was hidden. This release replaces v0.6.98.
**Українською.** У KSwitcher Files Enter і Shift+Enter виконують команду з командного рядка, зокрема коли файлові панелі приховані. Коли панелі видимі й рядок порожній, клавіші діють на вибраний елемент. Якщо вивід термінала приховано, команда відкриває його. Цей реліз замінює v0.6.98.
## v0.6.98 — 2026-11-16
In Files, Enter opens folders in the current pane, uses the Windows default action for local files, and runs BAT and CMD in the embedded terminal. Shift+Enter opens local folders in File Explorer and passes files, including BAT and CMD, to Windows. It preserves the draft command. Left and Right clear the previous cursor highlight when jumping to the first or last row. The FAR-style key bar uses gray key labels on black and dark action names on teal.
**Українською.** У Files Enter відкриває папки в поточній панелі, викликає стандартну дію Windows для локальних файлів, а BAT і CMD запускає у вбудованому терміналі. Shift+Enter відкриває локальні папки у Провіднику й передає файли, зокрема BAT і CMD, Windows. Чернетка команди зберігається. Стрілки вліво й вправо скидають старе підсвічування при переході до першого чи останнього рядка. Нижній рядок клавіш у стилі FAR має сірі позначення клавіш на чорному тлі й темні назви дій на бірюзовому.
## v0.6.97 — 2026-11-16
KSwitcher Files clears the highlight from the previous cursor row after a selection change and highlights the new row. It keeps the targeted repaint introduced in v0.6.96. This release replaces v0.6.96.
**Українською.** KSwitcher Files знімає підсвічування з попереднього рядка курсора після зміни вибору й виділяє новий рядок. Панель і далі перемальовує лише потрібні рядки. Цей реліз замінює v0.6.96.
## v0.6.96 — 2026-11-16
Clicking a file row in Files now redraws only the affected cursor rows, including when switching panes. The key bar adds **F8 Delete**, which opens the same confirmation as pressing F8.
**Українською.** Клік по рядку у Files перемальовує лише рядки курсора, зокрема при переході на іншу панель. У нижньому рядку клавіш є **F8 Delete**, що відкриває той самий діалог підтвердження, що й клавіша F8.
## v0.6.95 — 2026-11-16
Files shows Markdown after rendering completes, refreshes local previews when the file changes on disk, and opens internal links in the same window. Shift+click opens a separate window. The arrow controls, mouse side buttons and Alt+Left/Right navigate history. Ctrl+W closes the viewer. Ctrl+Tab cycles through Files and its open editors and viewers. Up and Down wrap in Files menus and drop-downs. Manual and LAN updates close Files, editors, Settings and bundled StayHere from the target installation before replacing its files. Save open work before updating. When installing this release with an older updater, close Files and its separate windows first. This release replaces v0.6.94.
**Українською.** Files показує Markdown після рендерингу й автоматично оновлює локальний перегляд після змін на диску. Внутрішні посилання відкриваються в тому самому вікні, Shift+клік — в окремому. Історією керують стрілки перегляду, бічні кнопки миші та Alt+←/→. Ctrl+W закриває перегляд. Ctrl+Tab циклічно перемикає Files та відкриті редактори й переглядачі. Стрілки вгору й вниз циклічно проходять меню та розкривні списки. Ручне оновлення й оновлення через LAN закривають Files, редактори, Settings і вбудований StayHere цільової інсталяції перед заміною файлів. Збережіть відкриті правки перед оновленням. Якщо цей реліз встановлює старий оновлювач, спочатку закрийте Files та його окремі вікна. Цей реліз замінює v0.6.94.
## v0.6.94 — 2026-11-16
In KSwitcher Files, F3 renders Markdown with offline Mermaid diagrams, tables, and interactive task lists. Relative links and images work for local and LAN documents. Checkbox changes last for the current preview. F4 opens the syntax-highlighted text editor and F6 switches between View and Edit in the same window, prompting before leaving unsaved edits.
**Українською.** У KSwitcher Files клавіша F3 відкриває форматований Markdown із діаграмами Mermaid, таблицями та інтерактивними списками завдань. Mermaid працює офлайн. Відносні посилання й зображення працюють для локальних і LAN-файлів. Відмітки чекбоксів діють у поточному сеансі перегляду. F4 відкриває редактор із підсвічуванням синтаксису, а F6 перемикає перегляд і редагування в тому самому вікні. Якщо є незбережені зміни, Files пропонує їх зберегти.
## v0.6.93 — 2026-11-16
In Files, Ctrl+R refreshes the active pane as in FAR Manager. The menu and key bar show Ctrl+R. F2 also refreshes the pane. Refresh preserves marks and the cursor where possible, and clears folder sizes calculated with F3.
**Українською.** У Files Ctrl+R перечитує активну панель, як у FAR Manager. Комбінація показана в меню та рядку клавіш. F2 також перечитує панель. Перечитування зберігає позначки й курсор для наявних елементів і скидає розміри папок, підраховані через F3.
## v0.6.92 — 2026-11-16
In Files, F3 on a folder measures file sizes throughout the directory tree. If folders are marked, Files measures each marked folder separately. Results appear in the Size column in Wide mode. F3 on a file opens the viewer even when folders are marked. Folder sizing runs in the background and supports LAN panes.
**Українською.** У Files F3 на папці підраховує сумарний розмір файлів у всьому дереві. Якщо позначено папки, Files рахує розмір кожної окремо. Результат з’являється в колонці Size у широкому режимі. F3 на файлі відкриває переглядач, навіть коли позначено папки. Підрахунок виконується у фоні й підтримує LAN-панелі.
## v0.6.91 — 2026-11-16
Ctrl+Insert copies the marked file and folder names from the active pane, one per line. Without marks, it copies the name under the cursor. LAN Files retries opening TCP 45885 if the port is busy at startup, and Change drive retries failed drive queries. A remote update request waits for an in-progress update check. The updater identifies and closes companion processes from its installation, including Files running from an update backup, and records confirmed exits in the journal.
**Українською.** Ctrl+Insert копіює імена позначених файлів і папок активної панелі, по одному на рядок. Якщо позначок немає, копіюється ім’я під курсором. LAN Files повторює відкриття TCP 45885, якщо порт зайнятий під час старту, а Change drive повторює невдалі запити дисків. Запит віддаленого оновлення чекає завершення поточної перевірки. Оновлювач визначає й закриває процеси своєї інсталяції, зокрема Files із резервної папки, і записує підтверджене завершення в журнал.
## v0.6.90 — 2026-11-16
Files groups Commands into navigation, viewing and editing, and remote PC actions. The remote group appears in an active LAN pane. Shared notices fit their contents and show a scrollbar only when needed. Remote hibernation and update confirmations use a compact red warning with No focused by default.
**Українською.** Меню Commands у Files групує навігацію, перегляд і редагування та дії для віддаленого ПК. Віддалена група доступна в активній LAN-панелі. Спільні повідомлення підлаштовуються під вміст і показують прокрутку лише за потреби. Гібернація та віддалене оновлення використовують компактне червоне підтвердження з фокусом на No.
## v0.6.89 — 2026-11-16
In Files, Commands now offers **Hibernate remote PC** and **Update remote KSwitcher** for the active LAN pane. The target PC has separate, default-off permissions for each action. Unattended updates verify the stable package, close the target installation's Files, Config and screenshot windows, and restart KSwitcher. Forced closure discards unsaved changes. The target journal records closed processes and the update result.
**Українською.** У меню Commands з’явилися **Hibernate remote PC** і **Update remote KSwitcher** для активної LAN-панелі. На цільовому ПК кожна дія має окремий дозвіл, вимкнений за замовчуванням. Оновлювач перевіряє стабільний пакет, без запитань закриває Files, Config і редактори скриншотів цієї інсталяції та перезапускає KSwitcher. Примусове закриття відкидає незбережені зміни. Журнал цільового ПК фіксує закриті процеси й результат оновлення.
## v0.6.88 — 2026-11-16
In Files, Ctrl+Enter inserts the name of the file or folder under the active pane cursor into the command line. An open Files window can still request the LAN peer list after KSwitcher updates and restarts.
**Українською.** У Files Ctrl+Enter вставляє в командний рядок назву файла або папки під курсором активної панелі. Відкрите вікно Files і далі може отримувати список LAN-комп’ютерів після оновлення та автоматичного перезапуску KSwitcher.
## v0.6.87 — 2026-11-15
Remote PowerShell in Files now displays errors as text and hides progress metadata. Update the PC that runs the commands to remove raw CLIXML from terminal output. This release supersedes v0.6.86.
**Українською.** Віддалений PowerShell у Files тепер показує помилки як текст і приховує службові повідомлення прогресу. Щоб прибрати сирий CLIXML із термінала, оновіть ПК, який виконує команди. Цей реліз замінює v0.6.86.
## v0.6.86 — 2026-11-15
The Files editor applies its palette before the text area appears. In a LAN pane, enter a PowerShell command to run it in that pane’s directory on the paired PC. The Files terminal displays output and the exit code. On the remote PC, enable **Allow paired PCs to run PowerShell commands here** in **Files → Options → Command line → Command history**. Both PCs need v0.6.86 or later.
**Українською.** Редактор Files застосовує палітру до появи текстового поля. У панелі LAN введена команда PowerShell виконується в каталозі цієї панелі на спареному ПК. Термінал Files показує вивід і код завершення. На віддаленому ПК увімкніть **Allow paired PCs to run PowerShell commands here** у **Files → Options → Command line → Command history**. На обох ПК потрібен v0.6.86 або новіший.
## v0.6.85 — 2026-11-15
Files viewer and editor windows now run independently with separate Windows taskbar buttons. Reopening a file offers to switch to its existing window. F3 and F4 work in LAN panes. The editor downloads files in the background and checks the remote file before replacing it on save. Update KSwitcher on the remote PC for writeback.
**Українською.** Переглядач і редактор Files працюють в окремих вікнах із власними кнопками на панелі завдань Windows. При повторному відкритті Files пропонує перейти до наявного вікна. F3 і F4 працюють у панелях LAN. Редактор завантажує файл у фоні та перевіряє віддалений файл перед записом. Для збереження оновіть KSwitcher також на віддаленому ПК.
## v0.6.84 — 2026-11-15
KSwitcher Files adds an internal viewer on F3 and editor on F4 with syntax highlighting, paged access to large text files, and shared search history. Alt+F3 and Alt+F4 open external applications. Files Options now includes viewer and editor settings, including tab width and the FAR (blue) color scheme. F7 creates folders and directory links, supports multiple names, and remembers successful inputs. Far-style dialogs share focus, resizing and keyboard behavior.
**Українською.** У KSwitcher Files з’явилися вбудований переглядач по F3 і редактор по F4 з підсвічуванням синтаксису, посторінковою роботою з великими текстовими файлами та спільною історією пошуку. Alt+F3 і Alt+F4 відкривають зовнішні програми. Спільні Options містять параметри переглядача й редактора, зокрема ширину табуляції та схему FAR (blue). F7 створює папки й посилання на каталоги, підтримує кілька імен і запам’ятовує успішні введення. Модальні діалоги Far мають спільну поведінку фокуса, зміни розміру й клавіатурної навігації.
## v0.6.83 — 2026-11-15
In KSwitcher Files, the command line keeps keyboard focus while Tab switches panes and Up, Down, Page Up, and Page Down move the active pane's cursor. Ctrl+F inserts the full path under the cursor, using double quotes only for paths with spaces. Ctrl+C copies the entire command line. Alt plus a character starts a filename or folder search. After the first match, type without Alt in the Search popup at the bottom of the active pane. F9 opens the menu.
**Українською.** У KSwitcher Files клавіатурний фокус залишається в командному рядку. Tab перемикає панелі, а стрілки вгору й вниз, Page Up і Page Down пересувають курсор активної панелі. Ctrl+F вставляє повний шлях під курсором і додає подвійні лапки лише до шляхів із пробілами. Ctrl+C копіює весь командний рядок. Alt із символом починає пошук файлу чи папки за назвою. Після першого збігу уточнюйте запит без Alt у полі Search внизу активної панелі. F9 відкриває меню.
## v0.6.82 — 2026-11-14
Enter and double-click open folders in the current pane, open local documents with their Windows default apps, and launch EXE files in separate processes. BAT and CMD files run in the existing embedded PowerShell session, and their output appears below the panes. Both local panes refresh when files are created, modified, or deleted externally and preserve focus.
**Українською.** Enter і подвійний клік відкривають папки в поточній панелі та локальні документи у стандартних програмах Windows. EXE запускаються окремими процесами, а BAT і CMD виконуються в поточній сесії вбудованого PowerShell із виводом під панелями. Обидві локальні панелі підхоплюють створення, зміну й видалення файлів ззовні та зберігають фокус.
## v0.6.81 — 2026-11-14
Ctrl+8 lists all folder shortcuts. Press Enter to open a folder, F4 to edit the shortcut, or Delete to remove it. Ctrl+Alt+F brings an open Files window forward.
**Українською.** Ctrl+8 показує всі ярлики папок. Enter відкриває папку, F4 редагує ярлик, Delete видаляє його. Ctrl+Alt+F повертає до відкритого вікна Files.
## v0.6.80 — 2026-11-14
Includes the Files updates from v0.6.79. Change drive now explains why the local peer lookup failed and shows No paired computers only when the response is empty.
@@ -223,8 +696,8 @@ Use **Test mouse buttons here** to check which events Windows delivers. Mouse pr
## Upgrade
Choose **Update** in the tray menu. Legacy v0.3.0–v0.4.1 clients first receive the v0.4.2 compatibility bridge, then the current full release. v0.2.3 and earlier require manual installation.
Choose **Update** in the tray menu. For v0.3.x–v0.4.1, install the [v0.4.2 bridge](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/releases/tag/v0.4.2) manually first. Close KSwitcher and its editors, extract the bridge ZIP into the installation folder while keeping personal data, dictionaries, and tools, then start v0.4.2 and choose **Update**. v0.2.3 and earlier require manual installation.
For a manual upgrade, exit KSwitcher and its configurator and screenshot editors, then extract the entire **KSwitcher-win-x64.zip** into its installation folder. Verify it with **SHA256SUMS.txt**. Keep personal data, customized dictionaries and tools. Keep the three KSwitcher executables together.
For a manual upgrade, save your work and exit KSwitcher, Settings, Files, screenshot editors and bundled StayHere. Verify **KSwitcher-win-x64.zip** with **SHA256SUMS.txt**, then extract the entire ZIP into the installation folder. Keep personal data, customized dictionaries and tools.
See the [English Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home) or [Українська Wiki](https://gitea.hrynco.com/hrynco/hrynco-kswitcher/wiki/Home-uk).
+1 -1
View File
@@ -1 +1 @@
f6067958677c4045fc5243459fc37522489a7f081969dac42befd07101814e61 KSwitcher-win-x64.zip
0209951cbe8c5a202dba12a807895ce7146dc6640f96704f6a4aa9afaa4fd3af KSwitcher-win-x64.zip
+98 -63
View File
@@ -1,131 +1,166 @@
{
"version": "0.7.4",
"schema": 1,
"version": "0.6.80",
"files": [
{
"sha256": "654544aa5a7c944f607edf5324cff68d1f447b9219fb9b3933e90b0eb8a3ba13",
"path": "KSwitcher.exe",
"size": 2341376
"size": 3082752,
"sha256": "31a41c6ecc3387fc9f2b3f228ed64fa916d723654c02dc19bbbb558f94def4b8",
"path": "KSwitcher.exe"
},
{
"sha256": "a546c2dfd811ee8a3cf4301b5b21d1d6a72dd7280c3eac272eebd7963bc48b32",
"path": "KSwitcher.Config.exe",
"size": 2341888
"size": 2832384,
"sha256": "b993c050a96215aa63be97e9f05764ead13fcaf4b68fbb99f3d2f9a7d49a629a",
"path": "KSwitcher.Config.exe"
},
{
"sha256": "a5cc8809b12698b266857440eece154a26bba64570bc65be1cb77959f7b0ebef",
"path": "KSwitcher.Screenshot.exe",
"size": 3319808
"size": 3187712,
"sha256": "eff5921b9067e0f4805c83d3cea10ddaa32b0b4e29f408b71b1004f78754afb9",
"path": "KSwitcher.Screenshot.exe"
},
{
"sha256": "d827cf29385db23dbdc5729d4397d768c32dd5ed7581ef10cb9f8c81370ec8a0",
"path": "KSwitcher.Files.exe",
"size": 1826304
"size": 4409344,
"sha256": "569d016d1eff9519cd33aa848723cea0365cbebe9333ed390245d098c4074d8e",
"path": "KSwitcher.Files.exe"
},
{
"size": 194912,
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"path": "WebView2Loader.dll",
"size": 194912
"path": "WebView2Loader.dll"
},
{
"size": 1103,
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"path": "terminal/addon-fit-LICENSE.txt",
"size": 1103
"path": "terminal/addon-fit-LICENSE.txt"
},
{
"size": 1521,
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"path": "terminal/addon-fit.js",
"size": 1521
"path": "terminal/addon-fit.js"
},
{
"size": 527,
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"path": "terminal/index.html",
"size": 527
"path": "terminal/index.html"
},
{
"sha256": "f677e61d7d90d3023839ee131ddabed7a5c3510b18d47cc9a3c19353913ca5cc",
"path": "terminal/terminal.js",
"size": 3481
"size": 1073,
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"path": "terminal/markdown-it-LICENSE.txt"
},
{
"size": 100786,
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"path": "terminal/markdown-it.js"
},
{
"size": 3599,
"sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094",
"path": "terminal/markdown.html"
},
{
"size": 17575,
"sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8",
"path": "terminal/markdown.js"
},
{
"size": 1089,
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"path": "terminal/mermaid-LICENSE.txt"
},
{
"size": 5537838,
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"path": "terminal/mermaid.js"
},
{
"size": 5065,
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
"path": "terminal/terminal.js"
},
{
"size": 1261,
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"path": "terminal/xterm-LICENSE.txt",
"size": 1261
"path": "terminal/xterm-LICENSE.txt"
},
{
"size": 7112,
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"path": "terminal/xterm.css",
"size": 7112
"path": "terminal/xterm.css"
},
{
"size": 488663,
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"path": "terminal/xterm.js",
"size": 488663
"path": "terminal/xterm.js"
},
{
"size": 4401,
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"path": "LICENSE",
"size": 4401
"path": "LICENSE"
},
{
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86",
"path": "json-LICENSE.txt",
"size": 1075
"size": 1096,
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"path": "json-LICENSE.txt"
},
{
"sha256": "df6d40d0eb66ad7da8db1cffe6bd211de70dfee474cc228e041c821b3940718b",
"path": "README.md",
"size": 93885
"size": 883,
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"path": "files-text-license.txt"
},
{
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada",
"path": "LAN-PREVIEW.md",
"size": 11418
"size": 105515,
"sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01",
"path": "README.md"
},
{
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21",
"path": "dictionaries/en.txt",
"size": 682867
"size": 12804,
"sha256": "f5bfc48e44af14dd6c45f56f689b4034ef1f7bdaca02f9d15ebc32af387366cf",
"path": "LAN-PREVIEW.md"
},
{
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5",
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"size": 20138
"size": 732485,
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"path": "dictionaries/en.txt"
},
{
"size": 20566,
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
},
{
"size": 2265,
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"path": "dictionaries/README.md",
"size": 2265
"path": "dictionaries/README.md"
},
{
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b",
"path": "dictionaries/ru.txt",
"size": 1060364
"size": 1109134,
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"path": "dictionaries/ru.txt"
},
{
"size": 1280,
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"path": "dictionaries/sources.json",
"size": 1280
"path": "dictionaries/sources.json"
},
{
"size": 940799,
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"path": "dictionaries/uk.txt",
"size": 940799
"path": "dictionaries/uk.txt"
},
{
"size": 993,
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"path": "tools/README.txt",
"size": 993
"path": "tools/README.txt"
},
{
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
"path": "tools/StayHere.exe",
"size": 134656
"size": 133120,
"sha256": "ba891b6cc5d35d26520fa9ad34e136124e90ed10e0cff2f25dedadd0b48fb88e",
"path": "tools/StayHere.exe"
},
{
"size": 2796,
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"path": "tools/StayHere-README.md",
"size": 2796
"path": "tools/StayHere-README.md"
}
]
}
+39 -17
View File
@@ -15,14 +15,19 @@ Set-Content -LiteralPath (Join-Path (Split-Path $executablePath) '.local-dev') -
Push-Location $root
try {
$common = @('-std=c++20','-Os','-DNDEBUG','-DUNICODE','-D_UNICODE','-DWIN32_LEAN_AND_MEAN','-DNOMINMAX','-D_WIN32_WINNT=0x0A00','-Wall','-Wextra','-Wno-missing-field-initializers','-Isrc','-Ivendor','-ffunction-sections','-fdata-sections')
$libs = @('-lws2_32','-lbcrypt','-liphlpapi','-lwinhttp','-luser32','-lshell32','-lshlwapi','-ladvapi32','-lcrypt32','-limm32','-lcomctl32','-lgdi32','-lole32','-loleaut32','-ltaskschd','-lcomdlg32','-luuid','-lwindowscodecs','-lruntimeobject','-luiautomationcore')
$libs = @('-lws2_32','-lbcrypt','-liphlpapi','-lwinhttp','-luser32','-lshell32','-lshlwapi','-ladvapi32','-lcrypt32','-limm32','-lcomctl32','-lgdi32','-lole32','-loleaut32','-ltaskschd','-lcomdlg32','-luuid','-lwindowscodecs','-lruntimeobject','-luiautomationcore','-ldwmapi')
$utilityDirectory = Join-Path (Split-Path $executablePath) 'tools'
New-Item -ItemType Directory -Force $utilityDirectory,build/release/tools | Out-Null
$stayHere = Join-Path $utilityDirectory 'StayHere.exe'
& $compiler @common -Werror -mwindows -municode -static -s utilities/StayHere/main.cpp -luser32 -lshell32 -lgdi32 -lwtsapi32 -o $stayHere
if ($LASTEXITCODE) { throw 'StayHere build failed' }
Copy-Item -LiteralPath $stayHere -Destination build/release/tools/StayHere.exe -Force
foreach ($name in @('lan_files','lan_channel','lan_input','lan','lan_pairing','core','platform','autostart','autocorrect','storage','sync','ocr','richtext','update','screenshot','screenshot_main','screenshot_notifications','screenshot_activation','screenshot_launcher','app','ui','main','configuration','config_main')) {
$filesBuild = Join-Path $outDir 'files-cmake'
& cmake -S $root -B $filesBuild -G Ninja "-DCMAKE_CXX_COMPILER=$compiler" -DCMAKE_BUILD_TYPE=MinSizeRel
if ($LASTEXITCODE) { throw 'CMake configuration failed' }
$common += "-I$(Join-Path $filesBuild 'generated')"
$driveObjects = @('build/drive_snapshot.o','build/google_drive.o')
foreach ($name in @('lan_files','lan_channel','lan_input','lan','lan_pairing','core','platform','autostart','autocorrect','storage','sync','drive_snapshot','google_drive','ocr','richtext','update','screenshot','screenshot_main','screenshot_notifications','screenshot_activation','screenshot_launcher','app','ui','main','configuration','config_main')) {
& $compiler @common -c "src/$name.cpp" -o "build/$name.o"
if ($LASTEXITCODE) { throw "Compilation failed: $name" }
}
@@ -32,14 +37,16 @@ try {
if ($LASTEXITCODE) { throw 'Configurator UI compilation failed' }
& windres --codepage=65001 resources/app.rc -O coff -o build/app-res.o
if ($LASTEXITCODE) { throw 'Resource compilation failed' }
& windres --codepage=65001 resources/help.rc -O coff -o build/help-res.o
if ($LASTEXITCODE) { throw 'Help resource compilation failed' }
& windres --codepage=65001 -DKS_SCREENSHOT_RESOURCES resources/app.rc -O coff -o build/screenshot-res.o
if ($LASTEXITCODE) { throw 'Screenshot resource compilation failed' }
New-Item -ItemType Directory -Force build/release | Out-Null
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui-resident.o build/main.o build/app-res.o @libs -o $executablePath
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o @driveObjects build/ocr.o build/richtext.o build/update.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui-resident.o build/main.o build/app-res.o build/help-res.o @libs -o $executablePath
if ($LASTEXITCODE) { throw 'Link failed' }
Copy-Item -LiteralPath $executablePath -Destination build/release/KSwitcher.exe -Force
$configPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Config.exe'
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/sync.o build/ocr.o build/configuration.o build/config_main.o build/ui-config.o build/app-res.o @libs -o $configPath
& $compiler -mwindows -municode -static -s '-Wl,--gc-sections' build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/sync.o @driveObjects build/ocr.o build/configuration.o build/config_main.o build/ui-config.o build/app-res.o @libs -o $configPath
if ($LASTEXITCODE) { throw 'Configurator link failed' }
Copy-Item -LiteralPath $configPath -Destination build/release/KSwitcher.Config.exe -Force
$screenshotPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Screenshot.exe'
@@ -47,18 +54,27 @@ try {
if ($LASTEXITCODE) { throw 'Screenshot link failed' }
Copy-Item -LiteralPath $screenshotPath -Destination build/release/KSwitcher.Screenshot.exe -Force
$filesPath = Join-Path (Split-Path $executablePath) 'KSwitcher.Files.exe'
$terminalIncludes = & "$root/tools/stage-files-terminal.ps1" -Destination (Split-Path $filesPath)
& "$root/tools/stage-files-terminal.ps1" -Destination build/release | Out-Null
& windres resources/files.rc -O coff -o build/files-res.o
if ($LASTEXITCODE) { throw 'File manager resource compilation failed' }
& $compiler @common "-I$terminalIncludes" -mwindows -municode -static -s src/files_main.cpp build/files-res.o build/lan_files.o build/lan_channel.o build/lan_pairing.o build/platform.o build/core.o '-Wl,--gc-sections' @libs -o $filesPath
& cmake --build $filesBuild --target KSwitcherFiles --parallel 8
if ($LASTEXITCODE) { throw 'File manager build failed' }
Copy-Item -LiteralPath (Join-Path $filesBuild 'KSwitcher.Files.exe') -Destination $filesPath -Force
& strip $filesPath
if ($LASTEXITCODE) { throw 'File manager stripping failed' }
& "$root/tools/stage-files-terminal.ps1" -Destination (Split-Path $filesPath) | Out-Null
& "$root/tools/stage-files-terminal.ps1" -Destination build/release | Out-Null
Copy-Item -LiteralPath $filesPath -Destination build/release/KSwitcher.Files.exe -Force
if ($Test) {
& $compiler @common -Werror tests/settings_merge.cpp build/sync.o build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherSettingsMergeTests.exe
& cmake --build $filesBuild --target KSwitcherFilesTextTests
if ($LASTEXITCODE) { throw 'Files text test build failed' }
& (Join-Path $filesBuild 'KSwitcherFilesTextTests.exe')
if ($LASTEXITCODE) { throw 'Files text tests failed' }
& $compiler @common -Werror tests/settings_merge.cpp build/sync.o @driveObjects build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherSettingsMergeTests.exe
if ($LASTEXITCODE) { throw 'Settings merge test build failed' }
& .\build\KSwitcherSettingsMergeTests.exe
if ($LASTEXITCODE) { throw 'Settings merge tests failed' }
& $compiler @common -Werror tests/drive_snapshot.cpp build/sync.o @driveObjects build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherDriveTests.exe
if ($LASTEXITCODE) { throw 'Google Drive snapshot test build failed' }
& .\build\KSwitcherDriveTests.exe
if ($LASTEXITCODE) { throw 'Google Drive snapshot tests failed' }
& $compiler @common -Werror tests/lan_clipboard.cpp build/lan_channel.o build/lan_pairing.o build/core.o build/platform.o @libs -static -s -o build/KSwitcherLanClipboardTests.exe
if ($LASTEXITCODE) { throw 'LAN clipboard test build failed' }
& .\build\KSwitcherLanClipboardTests.exe
@@ -87,7 +103,7 @@ try {
if ($LASTEXITCODE) { throw 'Dictionary test build failed' }
& .\build\KSwitcherDictionaryTests.exe
if ($LASTEXITCODE) { throw 'Dictionary tests failed' }
& $compiler @common tests/sync.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/sync.o build/ocr.o @libs -static -s -o build/KSwitcherSyncTests.exe
& $compiler @common tests/sync.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/storage.o build/sync.o @driveObjects build/ocr.o @libs -static -s -o build/KSwitcherSyncTests.exe
if ($LASTEXITCODE) { throw 'Sync test build failed' }
& .\build\KSwitcherSyncTests.exe
if ($LASTEXITCODE) { throw 'Sync tests failed' }
@@ -95,18 +111,24 @@ try {
if ($LASTEXITCODE) { throw 'Scroll test build failed' }
& .\build\KSwitcherScrollTests.exe
if ($LASTEXITCODE) { throw 'Scroll tests failed' }
& $compiler @common tests/tests.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o @libs -static -s -o build/KSwitcherTests.exe
& $compiler @common tests/tests.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o @driveObjects build/ocr.o build/richtext.o build/update.o @libs -static -s -o build/KSwitcherTests.exe
if ($LASTEXITCODE) { throw 'Test build failed' }
& .\build\KSwitcherTests.exe
if ($LASTEXITCODE) { throw 'Tests failed' }
& $compiler @common tests/input.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherInputTests.exe
& $compiler @common tests/input.cpp tests/input_pause.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o @driveObjects build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o build/help-res.o @libs -static -s -o build/KSwitcherInputTests.exe
if ($LASTEXITCODE) { throw 'Input test build failed' }
& .\build\KSwitcherInputTests.exe
if ($LASTEXITCODE) { throw 'Input tests failed' }
& $compiler @common tests/chat_profiles.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherChatProfileTests.exe
& .\build\KSwitcherInputTests.exe --help-layout
if ($LASTEXITCODE) { throw 'Offline help test failed' }
& .\build\KSwitcherInputTests.exe --input-pause
if ($LASTEXITCODE) { throw 'Tray pause/resume test failed' }
& $compiler @common tests/chat_profiles.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o @driveObjects build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherChatProfileTests.exe
if ($LASTEXITCODE) { throw 'Chat profile test build failed' }
& .\build\KSwitcherChatProfileTests.exe
if ($LASTEXITCODE) { throw 'Chat profile tests failed' }
& .\build\KSwitcherChatProfileTests.exe --google-drive-layout
if ($LASTEXITCODE) { throw 'Google Drive Settings test failed' }
& $compiler @common tests/screenshot_ui.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/ocr.o build/screenshot-res.o @libs -static -s -o build/KSwitcherScreenshotUITests.exe
if ($LASTEXITCODE) { throw 'Screenshot UI test build failed' }
& .\build\KSwitcherScreenshotUITests.exe
@@ -127,7 +149,7 @@ try {
if ($LASTEXITCODE) { throw 'Updater progress UI tests failed' }
}
if ($Far) {
& $compiler @common tests/far_snippets.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -mwindows -municode -static -s -o build/KSwitcherFarSnippetTests.exe
& $compiler @common tests/far_snippets.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o @driveObjects build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -mwindows -municode -static -s -o build/KSwitcherFarSnippetTests.exe
if ($LASTEXITCODE) { throw 'Far snippet test build failed' }
$fixture = Start-Process -FilePath (Join-Path $outDir 'KSwitcherFarSnippetTests.exe') -WindowStyle Hidden -Wait -PassThru
Get-Content -LiteralPath (Join-Path $outDir 'far-snippets.log')
@@ -153,14 +175,14 @@ try {
if ($LASTEXITCODE) { throw 'Image capture test build failed' }
& $captureTest
if ($LASTEXITCODE) { throw 'Image capture tests failed' }
& $compiler @common tests/integration.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherIntegration.exe
& $compiler @common tests/integration.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o @driveObjects build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o build/KSwitcherIntegration.exe
if ($LASTEXITCODE) { throw 'Integration test build failed' }
& .\build\KSwitcherIntegration.exe
if ($LASTEXITCODE) { throw 'Integration tests failed' }
}
if ($Ocr) {
$ocrTest = Join-Path (Split-Path $executablePath) 'KSwitcherOcrTests.exe'
& $compiler @common tests/ocr.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o $ocrTest
& $compiler @common tests/ocr.cpp build/lan_channel.o build/lan_input.o build/lan.o build/lan_files.o build/lan_pairing.o build/core.o build/platform.o build/autostart.o build/autocorrect.o build/storage.o build/sync.o @driveObjects build/ocr.o build/richtext.o build/update.o build/screenshot.o build/screenshot_launcher.o build/screenshot_activation.o build/screenshot_notifications.o build/app.o build/configuration.o build/ui.o build/screenshot-res.o @libs -static -s -o $ocrTest
if ($LASTEXITCODE) { throw 'OCR test build failed' }
& $ocrTest
if ($LASTEXITCODE) { throw 'OCR tests failed' }
+26
View File
@@ -0,0 +1,26 @@
include(FetchContent)
FetchContent_Declare(scintilla
URL https://www.scintilla.org/scintilla569.zip
URL_HASH SHA256=fddc637afa6e3a9205a5ad67c777d711a921ed2797d792f3034010c1be1539d6
DOWNLOAD_EXTRACT_TIMESTAMP FALSE)
FetchContent_Declare(lexilla
URL https://www.scintilla.org/lexilla555.zip
URL_HASH SHA256=713ada097b7da0594638e2c5723d8dea486653c23ec2e0c12631df7e5b7f0991
DOWNLOAD_EXTRACT_TIMESTAMP FALSE)
FetchContent_MakeAvailable(scintilla lexilla)
file(GLOB scintilla_sources "${scintilla_SOURCE_DIR}/src/*.cxx" "${scintilla_SOURCE_DIR}/win32/*.cxx")
list(FILTER scintilla_sources EXCLUDE REGEX "/ScintillaDLL\\.cxx$")
file(GLOB lexilla_sources "${lexilla_SOURCE_DIR}/lexlib/*.cxx" "${lexilla_SOURCE_DIR}/lexers/*.cxx")
add_library(KSwitcherFilesText STATIC ${scintilla_sources} ${lexilla_sources}
"${lexilla_SOURCE_DIR}/src/Lexilla.cxx")
target_include_directories(KSwitcherFilesText
PUBLIC "${scintilla_SOURCE_DIR}/include" "${lexilla_SOURCE_DIR}/include"
PRIVATE "${scintilla_SOURCE_DIR}/src" "${lexilla_SOURCE_DIR}/lexlib")
target_compile_definitions(KSwitcherFilesText PRIVATE UNICODE _UNICODE NOMINMAX LEXILLA_NO_EXPORT)
target_link_libraries(KSwitcherFilesText PRIVATE imm32 ole32 oleaut32 msimg32)
target_link_libraries(KSwitcherFiles PRIVATE KSwitcherFilesText)
if(MSVC)
set_property(TARGET KSwitcherFilesText KSwitcherFiles PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
target_compile_options(KSwitcherFilesText PRIVATE /utf-8)
endif()
+3
View File
@@ -0,0 +1,3 @@
#pragma once
#define KS_GOOGLE_CLIENT_ID "@KS_GOOGLE_CLIENT_ID@"
#define KS_GOOGLE_CLIENT_SECRET "@KS_GOOGLE_CLIENT_SECRET@"
+5 -5
View File
@@ -11,6 +11,7 @@ Copy-Item -LiteralPath (Join-Path $root 'build\release\WebView2Loader.dll') -Des
Copy-Item -LiteralPath (Join-Path $root 'build\release\terminal') -Destination $destination -Recurse -Force
Copy-Item -LiteralPath (Join-Path $root 'LICENSE') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'vendor\json-LICENSE.txt') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'resources\files-text-license.txt') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'README.md') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'LAN-PREVIEW.md') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'dictionaries') -Destination $destination -Recurse -Force
@@ -19,7 +20,7 @@ Copy-Item -LiteralPath (Join-Path $root 'resources\portable-tools-README.txt') -
Copy-Item -LiteralPath (Join-Path $root 'build\release\tools\StayHere.exe') -Destination (Join-Path $destination 'tools\StayHere.exe') -Force
Copy-Item -LiteralPath (Join-Path $root 'utilities\StayHere\README.md') -Destination (Join-Path $destination 'tools\StayHere-README.md') -Force
# Enumerate the distributable files explicitly; do not include a user's data directory.
$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','WebView2Loader.dll','terminal','LICENSE','json-LICENSE.txt','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ }
$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','WebView2Loader.dll','terminal','LICENSE','json-LICENSE.txt','files-text-license.txt','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ }
$entries = foreach ($path in $files) {
foreach ($file in @(Get-ChildItem -LiteralPath $path -File -Recurse)) {
@{path=$file.FullName.Substring($destination.Length+1).Replace('\','/'); size=$file.Length; sha256=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant()}
@@ -40,12 +41,11 @@ try {
[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,(Join-Path $destination $name),$name,[IO.Compression.CompressionLevel]::Optimal) | Out-Null
}
} finally { $zip.Dispose(); $stream.Dispose() }
Get-FileHash -LiteralPath $archive -Algorithm SHA256
$archiveHash = Get-FileHash -LiteralPath $archive -Algorithm SHA256
$archiveHash
if ($PublishRelease) {
$release = Join-Path $root 'Release'
New-Item -ItemType Directory -Force $release | Out-Null
$published = Join-Path $release 'KSwitcher-win-x64.zip'
Copy-Item -LiteralPath $archive -Destination $published -Force
$hash = (Get-FileHash -LiteralPath $published -Algorithm SHA256).Hash.ToLowerInvariant()
$hash = $archiveHash.Hash.ToLowerInvariant()
"$hash KSwitcher-win-x64.zip" | Set-Content -LiteralPath (Join-Path $release 'SHA256SUMS.txt') -Encoding ascii
}
+8 -3
View File
@@ -2,6 +2,11 @@
#include <windows.h>
#include "resource.h"
IDI_KSWITCHER ICON "kswitcher.ico"
IDI_KSWITCHER_PAUSED ICON "kswitcher-paused.ico"
IDI_KSWITCHER_HISTORY ICON "kswitcher-history.ico"
IDI_KSWITCHER_SCREENSHOT ICON "kswitcher-screenshot.ico"
IDI_KSWITCHER_HELP ICON "kswitcher-help.ico"
IDI_KSWITCHER_DONATE ICON "kswitcher-donate.ico"
#ifdef KS_SCREENSHOT_RESOURCES
IDI_SCREENSHOT_QUESTION ICON "icons/question.ico"
IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
@@ -9,8 +14,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
1 RT_MANIFEST "app.manifest"
201 RCDATA "update.ps1"
1 VERSIONINFO
FILEVERSION 0,6,80,0
PRODUCTVERSION 0,6,80,0
FILEVERSION 0,7,4,0
PRODUCTVERSION 0,7,4,0
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
BEGIN
@@ -20,7 +25,7 @@ BEGIN
BEGIN
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
VALUE "ProductName", "KSwitcher"
VALUE "FileVersion", "0.6.80"
VALUE "FileVersion", "0.7.4"
END
END
BLOCK "VarFileInfo"
+20
View File
@@ -0,0 +1,20 @@
License for Lexilla, Scintilla, and SciTE
Copyright 1998-2021 by Neil Hodgson <[email protected]>
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation.
NEIL HODGSON DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS, IN NO EVENT SHALL NEIL HODGSON BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
OR PERFORMANCE OF THIS SOFTWARE.
+234 -11
View File
@@ -1,11 +1,127 @@
#pragma code_page(65001)
#include <windows.h>
#include <commctrl.h>
#include "resource.h"
#define FAR_EDIT(id, mode, x, y, width, height) \
CONTROL "", id, "Edit", ES_AUTOHSCROLL | WS_TABSTOP | mode, x, y, width, height
CONTROL "", id, "KSwitcher.Files.FarEdit", ES_MULTILINE | ES_AUTOHSCROLL | WS_TABSTOP | mode, x, y, width, height
1 ICON "kswitcher-files.ico"
IDI_FILES_VIEWER ICON "kswitcher-files-viewer.ico"
IDI_FILES_EDITOR ICON "kswitcher-files-editor.ico"
IDI_FILES_COMPARE ICON "kswitcher-files-compare.ico"
1 RT_MANIFEST "app.manifest"
601 RCDATA "files-text-license.txt"
602 DIALOGEX 0, 0, 230, 85
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
FONT 10, "Consolas"
BEGIN
LTEXT "&Page number", 101, 18, 21, 194, 12
FAR_EDIT(100, ES_NUMBER, 18, 38, 194, 16)
CONTROL "&Go", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 53, 59, 60, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 117, 59, 60, 17
END
604 DIALOGEX 0, 0, 268, 101
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
CONTROL "&Search for", 109, "Static", SS_OWNERDRAW, 18, 17, 130, 12
FAR_EDIT(100, 0, 18, 30, 241, 14)
CONTROL "↓", 108, "Button", BS_OWNERDRAW | WS_TABSTOP, 259, 30, 11, 14
CONTROL "W&ord", 106, "Button", BS_OWNERDRAW | WS_TABSTOP, 160, 14, 49, 15
CONTROL "Se&lection", 107, "Button", BS_OWNERDRAW | WS_TABSTOP, 212, 14, 58, 15
CONTROL "", 104, "Static", NOT WS_VISIBLE, 18, 51, 1, 1
AUTOCHECKBOX "&Case sensitive", 101, 18, 52, 110, 12
AUTOCHECKBOX "&Whole words", 102, 18, 64, 110, 12
CONTROL "", 105, "Static", NOT WS_VISIBLE, 18, 81, 1, 1
CONTROL "Find pre&vious", 103, "Button", BS_OWNERDRAW | WS_TABSTOP, 33, 80, 83, 15
CONTROL "Find &next", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 121, 80, 76, 15
CONTROL "Canc&el", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 202, 80, 53, 15
END
603 DIALOGEX 0, 0, 230, 72
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
FONT 10, "Consolas"
BEGIN
LTEXT "Save changes to this file?", -1, 18, 23, 194, 12, SS_CENTER
CONTROL "&Save", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 17, 42, 60, 17
CONTROL "&Discard", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 82, 42, 66, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 153, 42, 60, 17
END
611 DIALOGEX 0, 0, 332, 96
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "&Open/create file:", 460, 14, 16, 304, 12
FAR_EDIT(461, 0, 14, 29, 304, 14)
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
LTEXT "&Code page:", 462, 14, 53, 94, 12
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
CONTROL "", 467, "Static", NOT WS_VISIBLE, 14, 72, 1, 1
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 76, 60, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 76, 60, 16
END
612 DIALOGEX 0, 0, 332, 184
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "Save file &as:", 460, 14, 16, 304, 12
FAR_EDIT(461, 0, 14, 29, 304, 14)
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
LTEXT "&Code page:", 462, 14, 53, 94, 12
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
AUTOCHECKBOX "Add signature (&BOM)", 464, 14, 66, 304, 12
CONTROL "", 468, "Static", NOT WS_VISIBLE, 14, 86, 1, 1
LTEXT "Change line breaks to:", 469, 14, 87, 304, 12
AUTORADIOBUTTON "Do &not change", 470, 14, 100, 304, 12, WS_GROUP | WS_TABSTOP
AUTORADIOBUTTON "&Windows (CR LF)", 471, 14, 112, 304, 12
AUTORADIOBUTTON "&Unix (LF)", 472, 14, 124, 304, 12
AUTORADIOBUTTON "&Mac (CR)", 473, 14, 136, 304, 12
CONTROL "", 467, "Static", NOT WS_VISIBLE | WS_GROUP, 14, 155, 1, 1
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 157, 60, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 157, 60, 16
END
607 DIALOGEX 0, 0, 185, 57
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL, 14, 16, 157, 13
AUTOCHECKBOX "&Remember for this session", 101, 14, 30, 157, 13, NOT WS_VISIBLE
CONTROL "", 102, "Static", NOT WS_VISIBLE, 14, 35, 1, 1
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 67, 38, 51, 15
CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 36, 38, 51, 15
CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 98, 38, 51, 15
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 129, 38, 51, 15
CONTROL "&Processes…", 103, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 14, 38, 75, 15
END
609 DIALOGEX 0, 0, 350, 135
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "", 430, 14, 17, 322, 20
LISTBOX 431, 14, 41, 322, 61, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
CONTROL "", 432, "Static", NOT WS_VISIBLE, 14, 108, 1, 1
CONTROL "&End process", 433, "Button", BS_OWNERDRAW | WS_TABSTOP, 56, 110, 80, 16
CONTROL "&Refresh", 434, "Button", BS_OWNERDRAW | WS_TABSTOP, 140, 110, 74, 16
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 218, 110, 65, 16
END
608 DIALOGEX 0, 0, 220, 67
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Save color scheme"
FONT 9, "Segoe UI"
BEGIN
LTEXT "Scheme &name", -1, 8, 8, 204, 10
EDITTEXT 100, 8, 21, 204, 14, ES_AUTOHSCROLL
DEFPUSHBUTTON "Save", IDOK, 105, 44, 50, 14
PUSHBUTTON "Cancel", IDCANCEL, 162, 44, 50, 14
END
101 DIALOGEX 0, 0, 397, 310
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN
@@ -43,6 +159,9 @@ BEGIN
CONTROL "", 321, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 27, 110, 15
LTEXT "Open command history", 322, 131, 53, 120, 12
CONTROL "", 323, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 50, 110, 15
AUTOCHECKBOX "Allow &paired PCs to run PowerShell commands here", 370, 131, 79, 250, 14
AUTOCHECKBOX "Allow paired PCs to &hibernate this PC", 371, 131, 95, 250, 14
AUTOCHECKBOX "Allow paired PCs to &update KSwitcher here", 372, 131, 111, 250, 14
PUSHBUTTON "Reset selected to defaults", 284, 131, 181, 125, 15
COMBOBOX 285, 131, 183, 139, 95, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
PUSHBUTTON "Reset property", 286, 278, 183, 108, 15
@@ -61,24 +180,55 @@ BEGIN
AUTOCHECKBOX "&Underline", 297, 131, 166, 80, 12
AUTOCHECKBOX "Stri&kethrough", 298, 218, 166, 100, 12
CONTROL "Settings preview", 299, "Static", SS_OWNERDRAW | WS_BORDER, 131, 202, 253, 81
AUTOCHECKBOX "&Wrap lines", 350, 131, 28, 118, 12
AUTOCHECKBOX "&Line numbers", 351, 257, 28, 125, 12
AUTOCHECKBOX "Show &whitespace and line endings", 352, 131, 45, 118, 12
AUTOCHECKBOX "&Highlight current line", 353, 257, 45, 125, 12
AUTOCHECKBOX "Insert &spaces for tabs", 354, 131, 62, 118, 12
AUTOCHECKBOX "Auto &indent", 355, 257, 62, 125, 12
LTEXT "&Tab width", 356, 131, 84, 118, 10
COMBOBOX 357, 257, 81, 125, 100, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "Line &endings for new lines", 358, 131, 104, 118, 10
COMBOBOX 359, 257, 101, 125, 77, CBS_DROPDOWNLIST | WS_TABSTOP
LTEXT "Color sc&heme", 362, 131, 125, 118, 10
COMBOBOX 363, 257, 122, 125, 67, CBS_DROPDOWNLIST | WS_TABSTOP
LTEXT "Customize &color", 364, 131, 145, 118, 10
COMBOBOX 365, 257, 142, 125, 116, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
PUSHBUTTON "Change color…", 366, 257, 181, 82, 15
LTEXT "", 367, 345, 184, 45, 12
PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15
LTEXT "Maximum &width (px, 0 = full window)", 373, 131, 31, 184, 12
EDITTEXT 374, 318, 28, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
LTEXT "Font &family (blank = system default)", 375, 131, 54, 250, 12
EDITTEXT 376, 131, 68, 168, 14, ES_AUTOHSCROLL
PUSHBUTTON "Choose &font…", 377, 306, 68, 76, 14
LTEXT "Font &size (8–72 pt)", 378, 131, 99, 184, 12
EDITTEXT 379, 318, 96, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
LTEXT "", 408, 131, 30, 254, 14
PUSHBUTTON "Change &font…", 409, 131, 49, 82, 15
LTEXT "Comparison &color", 410, 131, 79, 117, 12
COMBOBOX 411, 250, 76, 132, 126, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
PUSHBUTTON "Change color…", 412, 250, 97, 82, 15
LTEXT "", 413, 338, 100, 45, 12
LTEXT "Compare files &shortcut", 414, 131, 130, 117, 12
CONTROL "", 415, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 250, 127, 132, 15
DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14
PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14
PUSHBUTTON "&Apply", 283, 338, 289, 50, 14
END
102 DIALOGEX 0, 0, 350, 145
102 DIALOGEX 0, 0, 350, 110
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Copy"
FONT 10, "Consolas"
BEGIN
LTEXT "Copy to", 210, 14, 15, 322, 12, SS_PATHELLIPSIS
FAR_EDIT(211, ES_MULTILINE, 14, 29, 322, 18)
LTEXT "", 328, 14, 49, 322, 35, SS_NOPREFIX
LTEXT "Existing files:", 212, 14, 92, 122, 14, SS_CENTERIMAGE
COMBOBOX 213, 140, 92, 196, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP
CONTROL "Also ask on read-only files", 214, "Button", BS_OWNERDRAW | WS_TABSTOP, 14, 112, 322, 14
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 127, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 127, 86, 18
FAR_EDIT(211, 0, 14, 29, 322, 18)
LTEXT "Existing files:", 212, 14, 57, 122, 14, SS_CENTERIMAGE
COMBOBOX 213, 140, 57, 196, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP
AUTOCHECKBOX "Also ask on read-only files", 214, 14, 77, 322, 14
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 92, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 92, 86, 18
END
103 DIALOGEX 0, 0, 460, 126
@@ -111,7 +261,7 @@ BEGIN
RTEXT "", 332, 78, 72, 270, 13
LTEXT "", 333, 12, 88, 1, 1
LTEXT "", 234, 12, 114, 1, 1
CONTROL "Remember choice", 232, "Button", BS_OWNERDRAW | WS_TABSTOP, 12, 90, 336, 18
AUTOCHECKBOX "Remember choice", 232, 12, 90, 336, 18
CONTROL "&Overwrite", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 42, 122, 110, 18
CONTROL "&Skip", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 158, 122, 68, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 232, 122, 86, 18
@@ -154,6 +304,24 @@ BEGIN
LTEXT "", 248, 14, 73, 1, 1
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 157, 74, 86, 18
END
108 DIALOGEX 0, 0, 264, 110
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
CONTROL "Create the &folder:", 360, "Static", SS_OWNERDRAW, 14, 15, 236, 12
FAR_EDIT(361, 0, 14, 27, 225, 16)
CONTROL "↓", 363, "Button", BS_OWNERDRAW | WS_TABSTOP, 239, 27, 11, 16
CONTROL "", 362, "Static", NOT WS_VISIBLE, 14, 48, 1, 1
CONTROL "&Link type:", 364, "Static", SS_OWNERDRAW, 14, 51, 73, 12
COMBOBOX 365, 90, 48, 160, 64, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
CONTROL "&Target:", 366, "Static", SS_OWNERDRAW, 14, 65, 73, 12
FAR_EDIT(367, 0, 90, 63, 160, 16)
AUTOCHECKBOX "Process &multiple names", 368, 14, 79, 236, 13
CONTROL "", 369, "Static", NOT WS_VISIBLE, 14, 96, 1, 1
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 72, 97, 54, 15
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 132, 97, 60, 15
END
109 DIALOGEX 0, 0, 250, 85
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Folder shortcuts"
@@ -181,6 +349,61 @@ STYLE DS_SETFONT | DS_CENTER | WS_POPUP
FONT 9, "Consolas"
BEGIN
LTEXT "&Search commands or topics", 326, 12, 14, 361, 12
FAR_EDIT(325, ES_MULTILINE, 12, 28, 361, 16)
FAR_EDIT(325, 0, 12, 28, 361, 16)
LISTBOX 324, 12, 49, 361, 155, LBS_NOTIFY | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
END
112 DIALOGEX 0, 0, 360, 186
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "FTP connection"
FONT 10, "Consolas"
BEGIN
LTEXT "&Name", 381, 16, 18, 328, 12
FAR_EDIT(382, ES_LEFT, 16, 31, 328, 15)
LTEXT "&Server", 383, 16, 49, 250, 12
LTEXT "Por&t", 384, 278, 49, 66, 12
FAR_EDIT(385, ES_LEFT, 16, 62, 250, 15)
FAR_EDIT(386, ES_LEFT | ES_NUMBER, 278, 62, 66, 15)
LTEXT "&User name (blank for anonymous)", 387, 16, 80, 328, 12
FAR_EDIT(388, ES_LEFT, 16, 93, 328, 15)
LTEXT "&Password", 389, 16, 111, 328, 12
EDITTEXT 390, 16, 124, 328, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL
AUTOCHECKBOX "Use &Windows encoding for file names", 392, 16, 144, 328, 14
LTEXT "", 391, 10, 161, 1, 1, NOT WS_VISIBLE
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 92, 164, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 182, 164, 86, 18
END
113 DIALOGEX 0, 0, 350, 73
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Rename"
FONT 10, "Consolas"
BEGIN
LTEXT "New name in the current FTP folder:", 210, 14, 15, 322, 12
FAR_EDIT(211, 0, 14, 29, 322, 18)
LTEXT "", 217, 10, 49, 1, 1, NOT WS_VISIBLE
CONTROL "&Rename", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 51, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 51, 86, 18
END
114 DIALOGEX 0, 0, 510, 252
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_CLIPCHILDREN
EXSTYLE WS_EX_APPWINDOW
CAPTION "Compare files"
FONT 9, "Segoe UI"
BEGIN
LTEXT "", 400, 4, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 401, 259, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 45, 510, 207
CONTROL "", 407, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 8, 200, 19
LTEXT "", 403, 216, 12, 98, 14
END
115 DIALOGEX 0, 0, 290, 58
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Compare files"
FONT 10, "Consolas"
BEGIN
LTEXT "Reading and comparing files...", -1, 14, 15, 262, 13
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 101, 31, 88, 17
END
+63
View File
@@ -0,0 +1,63 @@
# Getting started
KSwitcher runs in the Windows notification area. Right-click the KSwitcher icon to open Settings, Clipboard history, Capture screen region, Files, Snippets, Keyboard shortcuts, Tools, Help and other commands. Windows may place the icon under Show hidden icons.
Use Keyboard shortcuts in this help window to see the shortcuts currently configured on this PC. To change them, open Settings → Shortcuts, select a field, press the desired combination and choose Apply or Save.
Choose a topic on the left or search the guide. The detailed manuals are part of the application and can be read offline.
# Keyboard and correction
KSwitcher can switch between installed layouts, convert text typed in the wrong layout, change case, transliterate and undo a recent transformation. Apply a text shortcut to selected text or let KSwitcher work with the recent text detected in the active application. KSwitcher skips transformations when it cannot verify the target or text.
Settings → Languages controls layout order and application or chat profiles. The layouts themselves are installed through Windows. Application and chat rules can narrow the layouts cycled for a particular context.
Settings → General → Correction options controls automatic correction. Its child pages cover offline dictionaries, exceptions, personal dictionaries, word boundaries and custom replacements. For a custom replacement, put one typo=correction pair per line.
# Clipboard history and OCR
Open Clipboard history from the tray or its configured shortcut. Search the list, filter it by computer or select Pinned only. Choose an entry and press Enter to paste, Shift+Enter for plain text, Ctrl+P to pin or unpin, Delete to remove it or Ctrl+O to open the full entry. Ctrl+1 through Ctrl+9 paste entries by position.
Open an image in the screenshot editor or use Copy text from image (OCR) in the context menu. Image text can also be searched once recognized. Settings → Clipboard controls recording, size limits and excluded apps. Settings → Clipboard → Image text recognition controls Windows OCR or optional local Tesseract.
Clear history deletes saved entries, including pinned ones, after confirmation. Use Pause clipboard history in the tray to suspend recording temporarily.
# Screenshots and annotations
Choose Capture screen region from the tray or use the configured shortcut. Drag around the area to capture. The capture is copied, and Settings can open the editor automatically. You can also open an image from Clipboard history.
The editor offers pointer selection, numbered markers, arrows, straight lines, shapes, pencil strokes, highlighting, text, color and undo/redo. Pick a mark with the pointer to edit its geometry or text. Line style, arrowheads and pencil smoothing are available below the toolbar.
Copy sends the annotated screenshot to the clipboard. Save exports a full-resolution PNG. Ctrl+Shift+S chooses another file. Ctrl+mouse wheel zooms, Ctrl+0 fits the image and the middle mouse button pans.
# Snippets and mouse profiles
In Settings → Snippets, add a trigger and its replacement text. Restrict it to specific applications when needed. Insert macro or marker opens the available insertions. The detailed manual describes autocomplete, cursor markers and supported macros.
In Settings → Mouse, create a profile for one or more applications and assign actions to mouse events. The Global profile is the fallback. Use Test mouse buttons here to check what the device reports.
# Settings, backup and sync
Use Apply to save edits and keep Settings open, or Save to save and close. Import loads settings for review before applying them. Export writes settings to a file.
Under Settings → Sync, configure OpenBao or Google Drive. A PC uses one automatic provider at a time. Use Sync now for an immediate sync and Resolve individual conflicts to review conflicting changes when available.
Manual Google Drive copies are separate from the auto-sync profile. Back up saved settings creates a dated copy. Restore selected backup loads that copy into the Settings draft. Review it before applying, especially if automatic sync is on. Google Drive features require a build with OAuth configured.
# Paired computers
Open Settings → Computers → Manage computers. Enable discovery on both PCs and use the same pairing code to connect them. Drag the monitors into position and enable input sharing to move the pointer across shared edges. Each PC can control whether its paired computers may download diagnostic logs.
The paired computers manual explains discovery, trust, sharing, file operations and troubleshooting in more detail.
# KSwitcher Files
Choose Files from the tray. Use the two file panels to browse, move and copy files. The manual covers local and remote locations, FTP, the viewer and editor, comparisons, search, dialogs, the integrated terminal and keyboard operation.
# Tray, updates and diagnostics
Use the tray menu to pause or resume input processing, keep the display awake, pause clipboard history, open the data folder, check for updates or exit. Tools lists supported portable utilities placed in the tools folder.
If a shortcut stops working, check whether input processing is paused and whether another application owns the binding. If a paired PC is missing, check discovery and access on both computers. Settings → Diagnostics and View log in the tray provide logs. Settings → MCP displays management integration settings.
Donate via Monobank opens the project's donation jar in the browser. Choose Help → About KSwitcher to see the running version.
+6
View File
@@ -0,0 +1,6 @@
#include <windows.h>
#include "resource.h"
IDR_HELP_GUIDE RCDATA "help-guide.md"
IDR_HELP_MANUAL RCDATA "../README.md"
IDR_HELP_FILES RCDATA "../FILES-UI.md"
IDR_HELP_COMPUTERS RCDATA "../LAN-PREVIEW.md"
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

+12
View File
@@ -1,4 +1,16 @@
#pragma once
#define IDI_KSWITCHER 101
#define IDI_SCREENSHOT_QUESTION 102
#define IDI_FILES_VIEWER 103
#define IDI_FILES_EDITOR 104
#define IDI_FILES_COMPARE 105
#define IDI_KSWITCHER_PAUSED 106
#define IDI_KSWITCHER_HISTORY 107
#define IDI_KSWITCHER_SCREENSHOT 108
#define IDI_KSWITCHER_HELP 109
#define IDI_KSWITCHER_DONATE 110
#define IDC_SCREENSHOT_PENCIL 500
#define IDR_HELP_GUIDE 600
#define IDR_HELP_MANUAL 601
#define IDR_HELP_FILES 602
#define IDR_HELP_COMPUTERS 603
+56
View File
@@ -0,0 +1,56 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'">
<title>Markdown preview</title>
<style>
:root { color-scheme: light dark; font: 16px/1.55 system-ui, sans-serif; }
:root:not(.rendered) body { visibility: hidden; }
body { max-width: var(--markdown-width, 960px); margin: auto; padding: 20px 28px; overflow-wrap: anywhere; }
main { font: var(--markdown-font-size, 12pt)/1.55 var(--markdown-font, system-ui, sans-serif); }
nav { position: sticky; top: 0; display: flex; flex-wrap: wrap; gap: .4em; padding-block: .25em; background: Canvas; }
nav button { appearance: none; border: 0; background: transparent; color: LinkText;
font: 1.35em/1.25 system-ui, sans-serif; min-width: 1.55em; padding: 0; cursor: pointer; }
nav button:disabled { color: GrayText; opacity: .6; cursor: default; }
nav button:hover:not(:disabled) { text-decoration: underline; }
nav button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
#search { margin-inline-start: auto; display: flex; align-items: center; gap: .35em;
flex: 0 1 22em; min-width: 0; max-width: 100%; }
#search[hidden] { display: none; }
#search-query { box-sizing: border-box; flex: 1; min-width: 0; width: 0; font: inherit; }
#search-status { white-space: nowrap; font-size: .8em; }
::highlight(markdown-search-active) { background: #ffab45; color: #171717; }
:is(h1,h2,h3,h4,h5,h6) { scroll-margin-top: 2.5em; }
h1, h2 { border-bottom: 1px solid GrayText; padding-bottom: .25em; }
a { color: LinkText; }
pre, table, figure { overflow: auto; }
pre, code { background: color-mix(in srgb, CanvasText 8%, Canvas); border-radius: 4px; }
pre { padding: .75em; }
code { padding: .1em .25em; }
pre code { padding: 0; background: none; }
blockquote { margin-left: 0; padding-left: 1em; border-left: 3px solid GrayText; }
table { display: block; border-collapse: collapse; }
th, td { border: 1px solid GrayText; padding: .3em .65em; }
img, svg { max-width: 100%; height: auto; }
figure { margin: 1em 0; }
figure svg .edgeLabel rect { fill: Canvas !important; opacity: 1 !important; stroke: none !important; }
.task { list-style: none; }
.task input { margin-inline: -1.15em .4em; cursor: pointer; }
</style>
<nav aria-label="Markdown preview">
<button id="back" type="button" title="Back (Alt+Left)" aria-label="Back" disabled>←</button>
<button id="forward" type="button" title="Forward (Alt+Right)" aria-label="Forward" disabled>→</button>
<button id="search-open" type="button" title="Find (Ctrl+F)" aria-label="Find in document" aria-controls="search" aria-expanded="false">⌕</button>
<div id="search" role="search" hidden>
<input id="search-query" type="search" aria-label="Find in document" placeholder="Find in document" autocomplete="off">
<output id="search-status" for="search-query" aria-live="polite"></output>
<button id="search-previous" type="button" title="Previous match (Shift+Enter)" aria-label="Previous match" disabled>↑</button>
<button id="search-next" type="button" title="Next match (Enter)" aria-label="Next match" disabled>↓</button>
<button id="search-close" type="button" title="Close search (Esc)" aria-label="Close search">×</button>
</div>
</nav>
<main></main>
<script src="markdown-it.js"></script>
<script src="markdown.js"></script>
</html>
+379
View File
@@ -0,0 +1,379 @@
'use strict';
const bridge = window.chrome.webview;
const content = document.querySelector('main');
const back = document.querySelector('#back');
const forward = document.querySelector('#forward');
const searchOpen = document.querySelector('#search-open');
const search = document.querySelector('#search');
const searchQuery = document.querySelector('#search-query');
const searchStatus = document.querySelector('#search-status');
const searchPrevious = document.querySelector('#search-previous');
const searchNext = document.querySelector('#search-next');
const markdown = markdownit({ html: true, linkify: true });
let generation = 0;
let images = [];
let matches = [];
let activeMatch = -1;
let taskMarkers = new WeakMap();
let pendingTask;
let previewRevision = 0;
let mermaidReady;
function loadMermaid() {
mermaidReady ??= new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'mermaid.js';
script.onload = resolve;
script.onerror = () => reject(new Error('Could not load Mermaid'));
document.head.append(script);
}).then(() => {
const renderer = window.mermaid;
renderer.initialize({
startOnLoad: false,
securityLevel: 'strict',
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
suppressErrorRendering: true,
flowchart: { htmlLabels: false }
});
return renderer;
});
return mermaidReady;
}
markdown.core.ruler.after('inline', 'task_lists', ({ tokens, src, env }) => {
const lines = src.split('\n');
for (let i = 2; i < tokens.length; ++i) {
const token = tokens[i];
if (token.type !== 'inline' || tokens[i - 1].type !== 'paragraph_open' ||
tokens[i - 2].type !== 'list_item_open') continue;
const text = token.children[0];
const marker = text?.type === 'text' && /^\[([ xX])\][ \t]+/.exec(text.content);
if (!marker) continue;
text.content = text.content.slice(marker[0].length);
const box = new text.constructor('task_checkbox', '', 0);
box.checked = marker[1] !== ' ';
box.content = token.content.slice(marker[0].length);
const line = tokens[i - 1].map?.[0];
const sourceMarker = /^[ \t]*(?:>[ \t]*)*(?:[-+*]|\d{1,9}[.)])[ \t]+\[([ xX])\][ \t]+/.exec(lines[line]);
if (sourceMarker) box.source = env.taskKey + ':' + line + ':' + (sourceMarker[0].lastIndexOf('[') + 1);
token.children.unshift(box);
tokens[i - 2].attrJoin('class', 'task');
}
});
markdown.renderer.rules.task_checkbox = (tokens, i) =>
'<input type="checkbox" aria-label="' + markdown.utils.escapeHtml(tokens[i].content) + '"' +
(tokens[i].checked ? ' checked' : '') + (tokens[i].source ? ' data-task="' + tokens[i].source + '"' : '') + '>';
markdown.renderer.rules.image = (tokens, i) => {
const token = tokens[i];
const alt = markdown.renderer.renderInlineAsText(token.children, markdown.options, {});
const escape = markdown.utils.escapeHtml;
return '<img alt="' + escape(alt) + '" data-path="' + escape(token.attrGet('src')) + '">';
};
const htmlTags = new Set(`a abbr address article aside b blockquote br caption code col colgroup dd del
details div dl dt em figcaption figure footer h1 h2 h3 h4 h5 h6 header hr i img input ins kbd li
mark ol p pre s samp section small span strong sub summary sup table tbody td tfoot th thead time
tr u ul var wbr`.split(/\s+/));
const htmlAttributes = new Set(['id', 'class', 'title', 'lang', 'dir', 'aria-label']);
const tagAttributes = {
a: ['href'], col: ['span'], colgroup: ['span'], details: ['open'], img: ['alt', 'width', 'height'],
input: ['type', 'checked', 'disabled'], ol: ['start', 'reversed', 'type'], li: ['value'],
td: ['colspan', 'rowspan'], th: ['colspan', 'rowspan', 'scope'], time: ['datetime']
};
const inlineStyles = ['white-space', 'text-align', 'vertical-align', 'color', 'background-color',
'font-weight', 'font-style', 'text-decoration-line', 'width', 'max-width'];
function relativeResource(path) {
return path && !/^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path) && !/[\u0000-\u001f\u007f]/.test(path);
}
function renderContent(text, canSave) {
// Parse in an inert template and allow only document markup before attaching it to the preview.
const template = document.createElement('template');
const taskKey = [...crypto.getRandomValues(new Uint32Array(4))].join('-');
taskMarkers = new WeakMap();
pendingTask = undefined;
template.innerHTML = markdown.render(text, { taskKey });
for (const element of template.content.querySelectorAll('*')) {
const tag = element.localName;
if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !htmlTags.has(tag) ||
(tag === 'input' && element.type !== 'checkbox')) {
element.remove();
continue;
}
const imagePath = tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
const task = tag === 'input' && element.getAttribute('data-task');
if (task && task.startsWith(taskKey + ':')) {
const [, line, column] = task.split(':');
taskMarkers.set(element, { line: Number(line), column: Number(column) });
element.disabled = !canSave;
}
const styles = element.hasAttribute('style')
? inlineStyles.map(name => [name, element.style.getPropertyValue(name)]) : [];
for (const { name } of [...element.attributes]) {
if (!htmlAttributes.has(name) && !tagAttributes[tag]?.includes(name)) element.removeAttribute(name);
}
for (const [name, value] of styles) {
if (value) element.style.setProperty(name, value);
}
if (relativeResource(imagePath)) element.dataset.path = imagePath;
if (tag === 'a' && element.hasAttribute('href')) {
const path = element.getAttribute('href').trim();
if (relativeResource(path) || /^https?:\/\/[^\s\u0000-\u001f\u007f]+$/i.test(path)) element.setAttribute('href', path);
else element.removeAttribute('href');
}
}
content.replaceChildren(template.content);
}
function send(action, options = {}) {
bridge.postMessage(JSON.stringify({ action, ...options }));
}
function scrollToHeading(fragment) {
if (!fragment) { window.scrollTo(0, 0); return; }
try { content.querySelector('#' + CSS.escape(decodeURIComponent(fragment)))?.scrollIntoView(); } catch {}
}
function restorePosition({ fragment, scroll }) {
if (typeof scroll === 'number') window.scrollTo(0, scroll);
else scrollToHeading(fragment);
}
function navigate(action) {
const button = action === 'back' ? back : forward;
if (!button.disabled) send(action, { scroll: Math.round(window.scrollY) });
}
back.addEventListener('click', () => navigate('back'));
forward.addEventListener('click', () => navigate('forward'));
function updateSearch(reveal = true) {
matches = [];
activeMatch = -1;
const query = searchQuery.value.trim();
if (query) {
const pattern = query.replace(/[.*+?^$(){}|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+');
const expression = new RegExp(pattern, 'giu');
const blockTags = 'article,aside,blockquote,caption,dd,div,dt,figcaption,footer,h1,h2,h3,h4,h5,h6,header,li,p,pre,section,summary,td,th,text';
const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT);
let block = null;
let parts = [];
let text = '';
const searchBlock = () => {
let first = 0;
let last = 0;
for (const match of text.matchAll(expression)) {
const end = match.index + match[0].length;
while (parts[first].end <= match.index) ++first;
last = Math.max(last, first);
while (parts[last].end < end) ++last;
matches.push([parts[first].node, match.index - parts[first].start,
parts[last].node, end - parts[last].start]);
}
parts = [];
text = '';
};
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
const element = node.parentElement;
if (!node.length || element.closest('style,svg title,svg desc,svg defs') ||
!element.checkVisibility({ visibilityProperty: true })) continue;
const nextBlock = element.closest(blockTags);
if (block !== nextBlock) searchBlock();
block = nextBlock;
const start = text.length;
text += node.data;
parts.push({ node, start, end: text.length });
}
searchBlock();
}
showSearchMatch(matches.length ? 0 : -1, reveal);
}
function showSearchMatch(index, reveal) {
activeMatch = index;
searchPrevious.disabled = searchNext.disabled = matches.length < 2;
searchStatus.value = !searchQuery.value.trim() ? '' : index < 0 ? 'No matches' : (index + 1) + ' / ' + matches.length;
CSS.highlights.delete('markdown-search-active');
if (index < 0) return;
const [start, from, end, to] = matches[index];
const range = new Range();
range.setStart(start, from);
range.setEnd(end, to);
CSS.highlights.set('markdown-search-active', new Highlight(range));
if (!reveal) return;
const rect = range.getBoundingClientRect();
const toolbarBottom = search.parentElement.getBoundingClientRect().bottom;
if (rect.top < toolbarBottom || rect.bottom > innerHeight) {
scrollBy(0, rect.top - Math.max(toolbarBottom, innerHeight / 2));
}
const scroller = start.parentElement.closest('pre, table');
if (scroller) {
const bounds = scroller.getBoundingClientRect();
if (rect.left < bounds.left || rect.right > bounds.right) {
scroller.scrollLeft += rect.left - bounds.left;
}
}
}
function openSearch() {
search.hidden = false;
searchOpen.setAttribute('aria-expanded', 'true');
searchQuery.focus({ preventScroll: true });
searchQuery.select();
}
function closeSearch() {
if (search.hidden) return false;
const hadFocus = search.contains(document.activeElement);
search.hidden = true;
searchOpen.setAttribute('aria-expanded', 'false');
searchQuery.value = '';
updateSearch();
if (hadFocus) searchOpen.focus({ preventScroll: true });
return true;
}
function stepSearch(direction) {
if (search.hidden) openSearch();
else if (matches.length) showSearchMatch((activeMatch + direction + matches.length) % matches.length, true);
}
searchOpen.addEventListener('click', openSearch);
document.querySelector('#search-close').addEventListener('click', closeSearch);
searchQuery.addEventListener('input', () => updateSearch());
searchPrevious.addEventListener('click', () => stepSearch(-1));
searchNext.addEventListener('click', () => stepSearch(1));
content.addEventListener('toggle', () => { if (!search.hidden) updateSearch(false); }, true);
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave }) {
const current = ++generation;
if (keepPosition) scroll = window.scrollY;
else closeSearch();
document.documentElement.classList.remove('rendered');
document.title = title;
previewRevision = revision;
renderContent(text, canSave);
const headings = new Set();
for (const heading of content.querySelectorAll('h1,h2,h3,h4,h5,h6')) {
const base = heading.id || heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
let id = base;
for (let n = 1; headings.has(id); ++n) id = base + '-' + n;
heading.id = id;
headings.add(id);
}
images = Array.from(content.querySelectorAll('img[data-path]'));
images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current }));
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
for (const [index, block] of blocks.entries()) {
try {
const renderer = await loadMermaid();
if (current !== generation) return;
const { svg } = await renderer.render('diagram-' + current + '-' + index, block.textContent);
if (current !== generation) return;
const figure = document.createElement('figure');
figure.innerHTML = svg;
const paths = figure.querySelector('g.edgePaths');
const labels = figure.querySelector('g.edgeLabels');
if (paths && labels && paths.parentNode === labels.parentNode) paths.after(labels);
block.parentElement.replaceWith(figure);
} catch (error) {
if (current !== generation) return;
const caption = document.createElement('div');
caption.textContent = 'Invalid Mermaid diagram';
caption.title = error instanceof Error ? error.message : String(error);
block.parentElement.before(caption);
}
}
restorePosition({ fragment, scroll });
document.documentElement.classList.add('rendered');
if (!search.hidden) updateSearch(false);
send('rendered');
}
content.addEventListener('change', ({ target }) => {
const marker = taskMarkers.get(target);
if (!marker) return;
if (pendingTask) {
target.checked = !target.checked;
return;
}
pendingTask = { target, checked: target.checked };
send('save-task', { ...marker, revision: previewRevision, checked: target.checked });
});
content.addEventListener('click', event => {
const link = event.target.closest('a');
if (!link) return;
event.preventDefault();
const path = link.getAttribute('href');
if (!path || event.ctrlKey || event.metaKey || link.closest('svg')) return;
send('link', { path, newWindow: event.shiftKey, scroll: Math.round(window.scrollY) });
});
document.addEventListener('pointerup', event => {
if (event.button !== 3 && event.button !== 4) return;
event.preventDefault();
navigate(event.button === 3 ? 'back' : 'forward');
});
document.addEventListener('keydown', event => {
if (event.isComposing) return;
if (event.ctrlKey && !event.altKey && event.key.toLowerCase() === 'f') {
event.preventDefault();
openSearch();
} else if (event.key === 'F3' || (event.key === 'Enter' && event.target === searchQuery)) {
event.preventDefault();
stepSearch(event.shiftKey ? -1 : 1);
} else if (event.key === 'Escape' && closeSearch()) {
event.preventDefault();
} else if (event.ctrlKey && !event.altKey && event.key === 'Tab') {
event.preventDefault();
send('cycle', {reverse: event.shiftKey});
} else if ((event.altKey && ['ArrowLeft', 'ArrowRight'].includes(event.key)) ||
['BrowserBack', 'BrowserForward'].includes(event.key)) {
event.preventDefault();
navigate(['ArrowLeft', 'BrowserBack'].includes(event.key) ? 'back' : 'forward');
} else if (event.key === 'F6' || event.key === 'Escape' || event.key === 'F10' ||
(event.ctrlKey && event.key.toLowerCase() === 'w')) {
event.preventDefault();
send(event.key === 'F6' ? 'edit' : 'close');
}
});
bridge.addEventListener('message', ({ data }) => {
const message = JSON.parse(data);
if (message.action === 'clear') {
++generation;
closeSearch();
document.documentElement.classList.remove('rendered');
content.replaceChildren();
}
if (message.action === 'render') void render(message).catch(() => send('failed'));
if (message.action === 'task-result' && message.revision === previewRevision && pendingTask) {
if (!message.saved) pendingTask.target.checked = !pendingTask.checked;
pendingTask = undefined;
}
if (message.action === 'appearance') {
const style = document.documentElement.style;
style.setProperty('--markdown-width', message.width ? message.width + 'px' : 'none');
style.setProperty('--markdown-font-size', message.fontSize + 'pt');
style.setProperty('--markdown-font', message.font ? CSS.escape(message.font) + ', system-ui, sans-serif' : 'system-ui, sans-serif');
}
if (message.action === 'anchor') restorePosition(message);
if (message.action === 'find') openSearch();
if (message.action === 'find-next') stepSearch(message.previous ? -1 : 1);
if (message.action === 'escape' && !closeSearch()) send('close');
if (message.action === 'back' || message.action === 'forward') navigate(message.action);
if (message.action === 'history') {
back.disabled = !message.back;
forward.disabled = !message.forward;
}
if (message.action === 'image' && message.generation === generation && images[message.index]) {
const image = images[message.index];
if (message.source) image.src = message.source;
else image.title = 'Image unavailable';
}
});
bridge.postMessage('ready');
+44 -4
View File
@@ -3,7 +3,8 @@ const terminal = new Terminal({
fontFamily: 'Consolas, monospace',
fontSize: 16,
cursorBlink: false,
stdinDisabled: true,
cursorInactiveStyle: 'none',
disableStdin: true,
theme: { background: '#181818', foreground: '#e8e8e8' },
});
const fit = new FitAddon.FitAddon();
@@ -20,10 +21,13 @@ terminal.parser.registerOscHandler(633, data => {
terminal.loadAddon(fit);
const host = document.getElementById('terminal');
terminal.open(host);
terminal.onSelectionChange(() => bridge.postMessage('selection:' + terminal.getSelection()));
host.addEventListener('pointerup', () => bridge.postMessage('focus-input'), true);
const screen = host.querySelector('.xterm-screen');
let traceEnabled = false;
let traceBudget = 4096;
let outputTraceBudget = 256;
let traceOutput = false;
let currentOffset = 0;
function trace(phase) {
if (!traceEnabled || traceBudget <= 0) return;
@@ -49,10 +53,27 @@ function anchorOutput() {
trace(2);
}
terminal.attachCustomKeyEventHandler(event => {
if (event.type !== 'keydown' || !event.ctrlKey || event.altKey || event.shiftKey) return true;
if (event.type === 'keydown' && event.key === 'Enter' && !event.ctrlKey && !event.altKey && !event.metaKey) {
if (!event.repeat) bridge.postMessage(event.shiftKey ? 'shift-enter' : 'enter');
event.preventDefault();
return false;
}
if (event.type !== 'keydown' || !event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) return true;
if (event.code === 'KeyO') bridge.postMessage('toggle');
else if (event.code === 'ArrowUp') bridge.postMessage('grow');
else if (event.code === 'ArrowDown') bridge.postMessage('shrink');
else if (event.code === 'KeyF' || event.code === 'KeyC') {
if (!event.repeat) bridge.postMessage(event.code === 'KeyF' ? 'insert-path' : 'copy-command-line');
}
else if (event.key === 'Enter') {
if (!event.repeat) bridge.postMessage('insert-name');
}
else if (event.key === 'Insert') {
if (!event.repeat) bridge.postMessage('copy-command-line-or-panel-names');
}
else if (event.code === 'KeyR') {
if (!event.repeat) bridge.postMessage('refresh-panel');
}
else return true;
event.preventDefault();
return false;
@@ -64,8 +85,18 @@ terminal.onScroll(() => {
anchorOutput();
});
bridge.addEventListener('message', ({ data }) => {
if (data === 'trace:on') {
if (data === 'clear-selection') {
terminal.clearSelection();
return;
}
if (data === 'scroll-bottom') {
terminal.scrollToBottom();
anchorOutput();
return;
}
if (data === 'trace:on' || data === 'trace:output') {
traceEnabled = true;
traceOutput = data === 'trace:output';
trace(2);
return;
}
@@ -83,7 +114,16 @@ bridge.addEventListener('message', ({ data }) => {
}
const bytes = new Uint8Array(data.length / 2);
for (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(data.slice(2*i, 2*i+2), 16);
terminal.write(bytes, anchorOutput);
terminal.write(bytes, () => {
anchorOutput();
if (traceOutput && outputTraceBudget > 0) {
outputTraceBudget--;
const buffer = terminal.buffer.active;
const lines = Array.from({ length: terminal.rows }, (_, row) =>
buffer.getLine(buffer.viewportY + row)?.translateToString(true) ?? '');
bridge.postMessage('output:' + lines.join('\n').trimEnd());
}
});
});
new ResizeObserver(() => {
const buffer = terminal.buffer.active;
+62 -6
View File
@@ -4,6 +4,7 @@
[string]$InstallDirectory, [string]$WorkDirectory,
[int]$ParentProcessId, [string]$ReadyEvent,
[switch]$ShowProgress,
[switch]$Unattended, [string]$Journal,
[switch]$Library
)
$ErrorActionPreference = 'Stop'
@@ -408,12 +409,60 @@ function Undo-Files([string]$Target,[string]$Backup,[Collections.Generic.List[st
function Write-Result($Value) {
$Value | ConvertTo-Json -Compress | Set-Content -LiteralPath (Join-Path $WorkDirectory 'result.json') -Encoding UTF8
}
function Write-UpdateJournal([string]$Message) {
if (!$Journal) { return }
$label = if ($Unattended) { 'LAN update' } else { 'Update' }
[IO.File]::AppendAllText($Journal, "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') ${label}: $Message`n",
[Text.UTF8Encoding]::new($false))
}
function Stop-UpdateCompanions([string]$Directory) {
if (!('KSwitcherUpdateProcessImage' -as [type])) {
Add-Type @'
using System;
using System.Runtime.InteropServices;
using System.Text;
public static class KSwitcherUpdateProcessImage {
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
[DllImport("kernel32.dll", CharSet=CharSet.Unicode)]
static extern bool QueryFullProcessImageName(IntPtr process, int flags, StringBuilder image, ref int length);
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
public static string Read(int pid) {
var process = OpenProcess(0x1000, false, pid);
if (process == IntPtr.Zero) return null;
try {
var length = 32768;
var image = new StringBuilder(length);
return QueryFullProcessImageName(process, 0, image, ref length) ? image.ToString() : null;
} finally { CloseHandle(process); }
}
}
'@
}
$root = [IO.Path]::GetFullPath($Directory).TrimEnd('\')
$prefix = [regex]::Escape($root + '\')
$pattern = '^' + $prefix + '(?:\.kswitcher-update-[0-9a-f]{32}\\backup\\)?(?:KSwitcher(?:\.(?:Config|Screenshot|Files))?\.exe|tools\\StayHere\.exe)$'
foreach ($process in @(Get-Process 'KSwitcher','KSwitcher.Config','KSwitcher.Screenshot','KSwitcher.Files','StayHere' -ErrorAction SilentlyContinue)) {
$image = [KSwitcherUpdateProcessImage]::Read($process.Id)
if (!$image -and !$process.HasExited) {
Write-UpdateJournal "Could not identify $($process.ProcessName) (PID $($process.Id))."
}
if ($image -notmatch $pattern) { continue }
Write-UpdateJournal "Closing $($process.ProcessName) (PID $($process.Id))."
if (!$process.HasExited) {
try { $process.Kill() } catch { if (!$process.HasExited) { throw } }
if (!$process.WaitForExit(10000)) { throw "Could not close $($process.ProcessName) (PID $($process.Id))." }
}
Write-UpdateJournal "Closed $($process.ProcessName) (PID $($process.Id))."
}
}
if ($Library) { return }
$transaction = $null; $parentProcess = $null; $ready = $null; $started = $null
$changed = [Collections.Generic.List[string]]::new()
$parentExited = $false; $success = $false; $preserveBackup = $false; $child = $null; $uiFinished = $false
try {
if ($ShowProgress -or $Mode -eq 'Install') { Start-UpdateProgress }
if (!$Unattended -and ($ShowProgress -or $Mode -eq 'Install')) { Start-UpdateProgress }
$current = Get-StableVersion $CurrentVersion
if (!$current) { throw 'Invalid installed version.' }
if ($Mode -eq 'Install') {
@@ -426,9 +475,12 @@ try {
$metadata = Join-Path $WorkDirectory 'releases.json'
Receive-File 'https://gitea.hrynco.com/api/v1/repos/hrynco/hrynco-kswitcher/releases?limit=100' $metadata 2MB
$release = Select-Release (Get-Content -LiteralPath $metadata -Raw | ConvertFrom-Json) $current
if (!$release) { Write-Result @{state='current'}; exit 0 }
if (!$release) {
if ($Unattended) { Write-UpdateJournal "No newer stable release is available ($CurrentVersion)." }
Write-Result @{state='current'}; exit 0
}
if ($Mode -eq 'Check') { Write-Result @{state='available';version=$release.version}; exit 0 }
if ($ExpectedVersion -ne $release.version) { throw 'Release changed since checking. Please select Update again.' }
if (!$Unattended -and $ExpectedVersion -ne $release.version) { throw 'Release changed since checking. Please select Update again.' }
Assert-PlainDirectory $InstallDirectory
$transaction = Join-Path $InstallDirectory ('.kswitcher-update-'+[guid]::NewGuid().ToString('N'))
$stage = Join-Path $transaction 'stage'; $backup = Join-Path $transaction 'backup'
@@ -441,13 +493,15 @@ try {
Assert-Checksum $archive $checksum
Show-UpdateProgress 'Preparing installation' 'Validating and unpacking the release files'
Expand-Release $archive $stage (Get-StableVersion $release.version)
$screenshotPath = [IO.Path]::GetFullPath((Join-Path $InstallDirectory 'KSwitcher.Screenshot.exe'))
if (Get-Process 'KSwitcher.Screenshot' -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $screenshotPath }) { throw 'Close screenshot editors before installing an update.' }
Write-UpdateJournal "Verified $($release.version). Closing KSwitcher (PID $ParentProcessId)."
Write-Result @{state='prepared';version=$release.version}
Show-UpdateProgress 'Closing KSwitcher' 'Waiting for the running application to exit safely'
$ready.Set() | Out-Null
if (!$parentProcess.WaitForExit(120000)) { throw 'KSwitcher did not exit; the installed files were not changed.' }
$parentExited = $true
Write-UpdateJournal "Closed KSwitcher (PID $ParentProcessId)."
Show-UpdateProgress 'Closing KSwitcher components' 'Closing Files, editors, Settings and StayHere'
Stop-UpdateCompanions $InstallDirectory
Show-UpdateProgress 'Installing update' 'Replacing application files; keeping your personal data'
Install-Files $stage $InstallDirectory $backup $changed
$startedName = 'Local\KSwitcher.Update.Started.'+[guid]::NewGuid().ToString('N')
@@ -456,6 +510,7 @@ try {
$child = Start-Process -FilePath (Join-Path $InstallDirectory 'KSwitcher.exe') -ArgumentList "--update-ready-event=$startedName" -WorkingDirectory $InstallDirectory -WindowStyle Hidden -PassThru
if (!$started.WaitOne(30000) -or $child.HasExited) { throw 'The updated application did not confirm startup.' }
$success = $true
try { Write-UpdateJournal "Completed $($release.version). KSwitcher restarted." } catch {}
if ($script:progressWindow) {
$uiFinished = Complete-UpdateProgress 'Update completed' "KSwitcher $(Get-StableVersion $release.version) is now running." $true
}
@@ -474,7 +529,8 @@ try {
}
}
Write-Result @{state='error';error=$message}
if ($ready -and $ready.WaitOne(0)) {
try { Write-UpdateJournal "Failed. $($message -replace '[\r\n]+',' ')" } catch {}
if (!$Unattended -and $ready -and $ready.WaitOne(0)) {
if ($script:progressWindow) {
$uiFinished = Complete-UpdateProgress 'Update failed' $message $false
} else {
+609 -158
View File
File diff suppressed because it is too large. Load diff
+21 -6
View File
@@ -36,7 +36,7 @@ struct LastTransform
class App
{
public:
HWND window{}, historyWindow{}, settingsWindow{}, snippetsWindow{};
HWND window{}, historyWindow{}, settingsWindow{}, snippetsWindow{}, helpWindow{};
HWND historyService{}; // Non-null only in the short-lived history UI process.
bool isolateHistory{};
unsigned historyEntryWindows{};
@@ -81,7 +81,7 @@ class App
void trayMenu();
void addTray();
bool registerHotkeys(const Settings &, bool rollback = false);
void applySettings(const Settings &);
void applySettings(const Settings &, const Bytes &supplement = {});
void reloadLayouts();
void clearHistory();
void openHistoryProcess();
@@ -105,11 +105,19 @@ class App
private:
friend struct InputRegressionAccess;
friend void commitConfigurationSupplement(App &, const Bytes &);
void releaseIdleMemory(ULONGLONG now);
void applySettings(const Settings &, bool validateOcrInstallation);
void applySettings(const Settings &, bool validateOcrInstallation, const std::function<void()> &commit = {});
void checkAutostartPath();
bool checkingAutostartPath{};
HHOOK keyboardHook{}, mouseHook{};
enum class InputState { Active, Pausing, Paused };
std::atomic<InputState> inputState{InputState::Active};
bool installInputHooks();
void releaseInputHooks();
void toggleInputProcessing();
void updateLanInputTimer();
void pollLanInput();
struct MousePress
{
HWND target{};
@@ -151,24 +159,29 @@ class App
ULONGLONG nextSync{}, syncRetryAfter{};
SyncResult syncResult;
SyncConfig syncConnection;
std::string syncDriveKey;
SyncConfig conflictConnection;
std::vector<SyncConflict> pendingSyncConflicts;
Bytes syncSnapshot;
std::wstring syncStatus = L"Not connected.";
bool updateRunning{}, installingUpdate{};
bool updateRunning{}, installingUpdate{}, lanUpdatePending{};
std::wstring availableUpdate, notifiedUpdate;
bool (*updateNotifier)(const std::wstring &){};
bool stop{};
UINT taskbarCreated{};
bool trayRetryPending{};
LanInputConnections trayInput;
bool trayInputPulse{};
HICON trayBaseIcon(int width, int height) const;
bool updateTray(DWORD action);
void refreshTrayInput();
uint64_t transformAttempt{}, previousAttemptVersion{};
size_t incomingLanFileCount{};
bool incomingFileBalloon{};
std::atomic<uint64_t> activeTransformAttempt{};
ULONGLONG previousAttemptAt{};
HWND previousAttemptWindow{};
int previousAttemptCommand{}, repeatAttempts{};
std::vector<std::pair<int, Hotkey>> hookBindings;
std::vector<Hotkey> availableBeforePause;
Hotkey registeredFilesHotkey{};
int filesHotkeyId{};
HotkeyHook hotkeyHook;
@@ -192,6 +205,7 @@ class App
RECT snippetPopupAnchor{};
bool snippetCaretPending{};
std::optional<RECT> snippetCaret;
std::vector<std::pair<std::wstring, std::vector<std::wstring>>> snippetTriggers;
std::vector<size_t> snippetMatches;
std::array<bool, 256> snippetKeys{};
void matchSnippets(HWND, bool expandExact);
@@ -219,5 +233,6 @@ void showSettings(App &, bool visible = true);
void showLogs(App &);
void showSnippets(App &);
void showShortcuts(App &);
void showHelp(App &);
void showEntry(App &, const std::wstring &);
} // namespace ks
+20 -13
View File
@@ -9,7 +9,7 @@ std::wstring App::syncCommand(int action, const std::vector<SyncChoice> &choices
if (action == 0) return syncStatus;
if (syncRunning) return L"Synchronization is already running.";
auto c = loadSyncConfig(data);
if (!c.enabled) return syncStatus = L"Synchronization is disabled.";
if (!automaticSyncEnabled(c)) return syncStatus = L"Synchronization is disabled.";
validateSyncConfig(c);
if (action == 4 && (c != conflictConnection || choices.empty()))
throw std::runtime_error("Connection changed or no choices selected. Sync again.");
@@ -17,28 +17,33 @@ std::wstring App::syncCommand(int action, const std::vector<SyncChoice> &choices
syncRetryAfter = 0; // Explicit retries may bypass the automatic error backoff.
if (syncWorker.joinable()) syncWorker.join();
syncConnection = c;
const auto driveKey = syncDriveKey = c.driveEnabled ? googleDriveCredentialKey() : std::string{};
syncSnapshot = encodeSettings(settings);
auto snapshot = settings;
auto availableLayouts = layouts;
syncRunning = true;
syncDone = false;
syncStatus = action == 2 ? L"Downloading remote settings from OpenBao..." :
action == 3 ? L"Uploading local settings to OpenBao..." : L"Connecting to OpenBao...";
const auto providerName = std::wstring(automaticSyncProviderName(c));
syncStatus = action == 2 ? L"Downloading remote settings from " + providerName + L"..." :
action == 3 ? L"Uploading local settings to " + providerName + L"..." : L"Connecting to " + providerName + L"...";
nextSync = GetTickCount64() + SyncIntervalMs;
try
{
syncWorker = std::thread([this, c, snapshot, availableLayouts, action, choices] {
syncWorker = std::thread([this, c, snapshot, availableLayouts, action, choices, driveKey] {
SyncResult result;
try
{
auto provider = makeSyncProvider(c);
// An explicit choice also repairs a missing/corrupt local baseline.
auto base = action == 1 || action == 4 ? loadSyncBase(data, c) : Bytes{};
result = synchronize(*provider, base, sharedSyncSettings(snapshot),
const bool keepLayouts = c.enabled && c.keepLocalLayouts;
auto base = action == 1 || action == 4 ? loadSyncBase(data, c, driveKey) : Bytes{};
result = synchronize(*provider, base, c.driveEnabled ? sharedDriveSettings(snapshot) : sharedSyncSettings(snapshot),
action == 2 ? SyncAction::Download : action == 3 ? SyncAction::Upload : SyncAction::Automatic,
[&](const Bytes &b) { restoreSyncSettings(b, snapshot, availableLayouts, c.keepLocalLayouts); }, choices,
c.keepLocalLayouts);
if (result.success && c.keepLocalLayouts)
[&](const Bytes &b) {
if (c.driveEnabled) restoreSharedDriveSettings(b, snapshot, availableLayouts);
else restoreSyncSettings(b, snapshot, availableLayouts, keepLayouts);
}, choices, keepLayouts);
if (result.success && keepLayouts)
result.status += L" Partial sync: this PC's layouts and their shortcuts were kept; server layouts were preserved.";
}
catch (const nlohmann::json::exception &) { result.status = L"Invalid sync data or server response."; }
@@ -69,13 +74,15 @@ void App::pollSync()
syncStatus = result.status;
if (result.success)
{
if (loadSyncConfig(data) != syncConnection || encodeSettings(settings) != snapshot)
if (loadSyncConfig(data) != syncConnection || encodeSettings(settings) != snapshot ||
(syncConnection.driveEnabled && googleDriveCredentialKey() != syncDriveKey))
{
syncStatus = L"Local settings or connection changed during sync. Checking again shortly.";
nextSync = GetTickCount64() + 2000;
return;
}
auto next = restoreSyncSettings(result.settings, settings, layouts, syncConnection.keepLocalLayouts);
auto next = syncConnection.driveEnabled ? restoreSharedDriveSettings(result.settings, settings, layouts) :
restoreSyncSettings(result.settings, settings, layouts, syncConnection.keepLocalLayouts);
if (encodeSettings(next) != snapshot)
{
atomicWrite(data / L"settings-before-sync.bin", protect(snapshot));
@@ -85,7 +92,7 @@ void App::pollSync()
}
else syncStatus += result.conflicts.empty() ? L" This PC's settings are already up to date; no local changes needed." :
L" No local settings were changed; conflicts still need your choice.";
saveSyncBase(data, syncConnection, result.base.empty() ? result.settings : result.base);
saveSyncBase(data, syncConnection, result.base.empty() ? result.settings : result.base, syncDriveKey);
if (result.downloaded)
{
if (settingsWindow) SendMessageW(settingsWindow, ConfigSettingsDownloaded, 0, 0);
@@ -108,7 +115,7 @@ void App::pollSync()
if (!syncRunning && GetTickCount64() >= nextSync)
{
nextSync = GetTickCount64() + SyncIntervalMs;
if (loadSyncConfig(data).enabled) syncCommand(1);
if (automaticSyncEnabled(loadSyncConfig(data))) syncCommand(1);
}
}
catch (const nlohmann::json::exception &) { syncStatus = L"Invalid local sync configuration or cached profile."; nextSync = GetTickCount64() + SyncIntervalMs; }
+11 -4
View File
@@ -34,13 +34,14 @@ std::wstring layoutLanguage(const Layout &layout)
return {};
}
}
bool safeAutoWord(const std::wstring &word, int minimumLength)
bool safeAutoWord(const std::wstring &word, int minimumLength, bool allowUppercase)
{
if (minimumLength < 1 || minimumLength > 32 || word.size() < (size_t)minimumLength || word.size() > 32 ||
!std::all_of(word.begin(), word.end(), letter))
return false;
auto small = lower(word);
return word == small || (word.substr(1) == small.substr(1) && word != upper(word));
const bool allUppercase = word == upper(word);
return word == small || (allUppercase ? allowUppercase : word.substr(1) == small.substr(1));
}
namespace {
constexpr size_t DictionaryBlockWords = 32;
@@ -289,9 +290,15 @@ std::optional<AutoSuggestion> AutoCorrector::suggest(const std::wstring &typed,
if (dictionary == dictionaries.end())
continue;
auto converted = convert(word, layouts[source], layouts[i], true);
if (converted == word || !safeAutoWord(converted, settings.autoMinLength))
if (converted == word)
continue;
int rank = personal(dictionary->first, converted) ? 1 : dictionary->second->rank(converted);
const bool knownPersonal = personal(dictionary->first, converted);
auto letters = converted;
if (knownPersonal)
std::erase(letters, L'-');
if (!safeAutoWord(letters, settings.autoMinLength, knownPersonal))
continue;
int rank = knownPersonal ? 1 : dictionary->second->rank(converted);
if (!rank)
continue;
if (matchedText && *matchedText != converted)
+1 -1
View File
@@ -12,7 +12,7 @@ struct AutoSuggestion
std::wstring text;
};
std::wstring layoutLanguage(const Layout &);
bool safeAutoWord(const std::wstring &, int minimumLength = 3);
bool safeAutoWord(const std::wstring &, int minimumLength = 3, bool allowUppercase = false);
bool autoClosingSelection(const std::wstring &, const Settings & = {});
int matchAutoInput(const Run &, const std::wstring &, const std::vector<Layout> &, const Layout &,
const Settings & = {});
+14 -6
View File
@@ -107,7 +107,7 @@ App::~App()
if (window) DestroyWindow(window);
current = nullptr;
}
void App::applySettings(const Settings &next)
void App::applySettings(const Settings &next, const Bytes &supplement)
{
validateSettings(next);
auto before = encodeSettings(settings), after = encodeSettings(next);
@@ -115,15 +115,22 @@ void App::applySettings(const Settings &next)
Bytes payload(sizeof(length));
memcpy(payload.data(), &length, sizeof(length));
payload.insert(payload.end(), before.begin(), before.end());
if (!supplement.empty())
{
DWORD length = (DWORD)after.size();
auto first = reinterpret_cast<const unsigned char *>(&length);
payload.insert(payload.end(), first, first + sizeof(length));
}
payload.insert(payload.end(), after.begin(), after.end());
payload.insert(payload.end(), supplement.begin(), supplement.end());
Bytes saved;
try {saved=request(*this,ConfigSave,payload);}
try {saved=request(*this,supplement.empty() ? ConfigSave : ConfigSaveDraft,payload);}
catch(const std::exception &error){
if(!std::string(error.what()).starts_with("Settings conflict: "))throw;
auto text=wide(error.what())+L"\n\nThese settings changed both here and in KSwitcher.\nKeep your edits for these settings? Other changes will be preserved.\n\nNo leaves this window open with all your edits.";
if(MessageBoxW(settingsWindow?settingsWindow:snippetsWindow,text.c_str(),L"Save conflicting settings",MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON2)!=IDYES)
throw std::runtime_error("Not saved. Your edits are still in this window.");
saved=request(*this,ConfigSaveEdited,payload);
saved=request(*this,supplement.empty() ? ConfigSaveEdited : ConfigSaveEditedDraft,payload);
}
settings=decodeSettings(saved,layouts);
}
@@ -229,16 +236,17 @@ int runConfigurator(HINSTANCE instance, bool snippets, bool logs)
MSG message;
while ((app.settingsWindow || app.snippetsWindow || app.logWindow) && GetMessageW(&message, nullptr, 0, 0) > 0)
{
if (app.settingsWindow && !IsWindowEnabled(app.settingsWindow))
const auto editor = app.settingsWindow ? app.settingsWindow : app.snippetsWindow;
if (editor && !IsWindowEnabled(editor))
{
HWND popup = GetLastActivePopup(app.settingsWindow);
HWND popup = GetLastActivePopup(editor);
while (!IsWindowEnabled(popup))
{
HWND next = GetLastActivePopup(popup);
if (next == popup) break;
popup = next;
}
if (popup != app.settingsWindow && IsDialogMessageW(popup, &message)) continue;
if (popup != editor && IsDialogMessageW(popup, &message)) continue;
}
if (app.settingsWindow && IsDialogMessageW(app.settingsWindow, &message)) continue;
if (app.snippetsWindow && IsDialogMessageW(app.snippetsWindow, &message)) continue;
+63 -9
View File
@@ -4,17 +4,25 @@
#include <cstring>
namespace ks
{
bool configurationPeer(HWND window, const wchar_t *filename)
namespace
{
std::filesystem::path processImage(HWND window)
{
DWORD pid{};
GetWindowThreadProcessId(window, &pid);
HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!process) return false;
if (!process) return {};
wchar_t path[32768]; DWORD count = std::size(path);
bool ok = QueryFullProcessImageNameW(process, 0, path, &count) != 0;
CloseHandle(process);
auto expected = std::filesystem::path(executable()).parent_path() / filename;
return ok && _wcsicmp(path, expected.c_str()) == 0;
return ok ? std::filesystem::path(path) : std::filesystem::path{};
}
}
bool configurationPeer(HWND window, const wchar_t *filename)
{
const auto expected = std::filesystem::path(executable()).parent_path() / filename;
return _wcsicmp(processImage(window).c_str(), expected.c_str()) == 0;
}
void launchConfiguration(App &app, bool snippets, bool logs)
{
@@ -32,10 +40,41 @@ void launchConfiguration(App &app, bool snippets, bool logs)
CloseHandle(process.hProcess);
(void)app;
}
void commitConfigurationSupplement(App &app, const Bytes &supplement)
{
const auto draft = nlohmann::json::parse(supplement);
auto commitLan = [&] {
if (!draft.contains("lan")) return;
const auto command = nlohmann::json{{"action", "applySettings"}, {"draft", draft.at("lan")}}.dump();
app.lanCommand(Bytes(command.begin(), command.end()));
};
if (draft.contains("sync"))
{
const auto &sync = draft.at("sync");
const auto config = decodeSyncConfig(sync.at("config").get<Bytes>());
const auto previous = loadSyncConfig(app.data);
if (previous != decodeSyncConfig(sync.at("base").get<Bytes>()))
throw std::runtime_error("The synchronization connection changed. Reopen Settings to edit the current connection.");
const bool switching = previous.enabled != config.enabled || previous.driveEnabled != config.driveEnabled;
if (switching && app.syncRunning)
throw std::runtime_error("Wait for the current synchronization to finish before changing providers.");
applySyncConnection(app.data, config, sync.at("password").get<Bytes>(), sync.at("forget").get<bool>(), commitLan);
if (switching)
{
app.pendingSyncConflicts.clear();
app.syncRetryAfter = 0;
app.syncStatus = automaticSyncEnabled(config) ? L"Waiting to synchronize." : L"Synchronization is disabled.";
}
}
else commitLan();
}
LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &message)
{
const bool filesPeers = message.dwData == FilesLanPeers;
if (!configurationPeer(sender, filesPeers ? L"KSwitcher.Files.exe" : L"KSwitcher.Config.exe") || message.cbData > ConfigLimit ||
const bool knownSender = filesPeers
? isFilesPeerImage(processImage(sender), std::filesystem::path(executable()).parent_path())
: configurationPeer(sender, L"KSwitcher.Config.exe");
if (!knownSender || message.cbData > ConfigLimit ||
(message.cbData && !message.lpData)) return FALSE;
Bytes reply;
bool ok = false;
@@ -88,6 +127,8 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag
}
case ConfigSave:
case ConfigSaveEdited:
case ConfigSaveDraft:
case ConfigSaveEditedDraft:
{
if (app.busy) throw std::runtime_error("Wait for the current text operation to finish.");
if (message.cbData < sizeof(DWORD)) throw std::runtime_error("Invalid settings request.");
@@ -95,10 +136,23 @@ LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &messag
memcpy(&length, message.lpData, sizeof(length));
if (length > message.cbData - sizeof(length)) throw std::runtime_error("Invalid settings snapshot.");
auto begin = static_cast<const unsigned char *>(message.lpData) + sizeof(length);
Bytes next(begin + length, static_cast<const unsigned char *>(message.lpData) + message.cbData);
if (next.empty()) throw std::runtime_error("Empty settings request.");
auto merged=mergeConfigurationSettings(Bytes(begin,begin+length),next,encodeSettings(app.settings),message.dwData==ConfigSaveEdited);
app.applySettings(decodeSettings(merged, app.layouts));
const auto end = static_cast<const unsigned char *>(message.lpData) + message.cbData;
auto next = begin + length;
auto nextEnd = end;
const bool hasDraft = message.dwData == ConfigSaveDraft || message.dwData == ConfigSaveEditedDraft;
if (hasDraft)
{
DWORD nextLength{};
if (end - next < sizeof(nextLength)) throw std::runtime_error("Invalid settings draft.");
memcpy(&nextLength, next, sizeof(nextLength));
next += sizeof(nextLength);
if (nextLength >= end - next) throw std::runtime_error("Invalid settings draft.");
nextEnd = next + nextLength;
}
if (next == nextEnd) throw std::runtime_error("Empty settings request.");
auto merged = mergeConfigurationSettings(Bytes(begin, begin + length), Bytes(next, nextEnd),
encodeSettings(app.settings), message.dwData == ConfigSaveEdited || message.dwData == ConfigSaveEditedDraft);
app.applySettings(decodeSettings(merged, app.layouts), Bytes(nextEnd, end));
reply = encodeSettings(app.settings);
break;
}
+2 -1
View File
@@ -9,9 +9,10 @@ inline constexpr ULONG_PTR ConfigRead = 0x4b530100, ConfigSave = ConfigRead + 1,
ConfigCapture = ConfigRead + 4, ConfigLogs = ConfigRead + 5,
ConfigReply = ConfigRead + 6, ConfigClearLog = ConfigRead + 7,
ConfigSync = ConfigRead + 8, ConfigSyncConflicts = ConfigRead + 9,
ConfigSyncResolve = ConfigRead + 10, ConfigLan = ConfigRead + 11, ConfigSaveEdited = ConfigRead + 12, ConfigEnd = FilesLanPeers + 1;
ConfigSyncResolve = ConfigRead + 10, ConfigLan = ConfigRead + 11, ConfigSaveEdited = ConfigRead + 12, ConfigSaveDraft = FilesLanPeersReply + 1, ConfigSaveEditedDraft = ConfigSaveDraft + 1, ConfigEnd = ConfigSaveEditedDraft + 1;
inline constexpr size_t ConfigLimit = 8 * 1024 * 1024;
bool configurationPeer(HWND, const wchar_t *filename);
void commitConfigurationSupplement(App &, const Bytes &);
void launchConfiguration(App &, bool snippets = false, bool logs = false);
LRESULT configurationRequest(App &, HWND sender, const COPYDATASTRUCT &);
}
+182 -62
View File
@@ -3,6 +3,7 @@
#include <cwctype>
#include <map>
#include <stdexcept>
#include <string_view>
namespace ks
{
@@ -21,20 +22,29 @@ int snippetAppPriority(const Snippet &snippet, const std::wstring &process)
for (const auto &app : snippet.apps) if (snippetAppName(app) == name && !name.empty()) return 2;
return 0;
}
bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet)
static bool validSeparatedWord(const std::wstring &text, const std::wstring &alphabet,
std::wstring_view separators)
{
if (text.empty() || text.size() > 32) return false;
auto isLetter = [&](wchar_t c) { return alphabet.find(c) != alphabet.npos; };
for (size_t i = 0; i < text.size(); ++i)
{
if (isLetter(text[i])) continue;
if (text[i] != L' ' && text[i] != L'\'' && text[i] != L'\u2019' && text[i] != L'\u02bc')
if (separators.find(text[i]) == separators.npos)
return false;
if (i == 0 || i + 1 == text.size() || !isLetter(text[i - 1]) || !isLetter(text[i + 1]))
return false;
}
return true;
}
bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet)
{
return validSeparatedWord(text, alphabet, L" '\u2019\u02bc");
}
bool validPersonalWord(const std::wstring &text, const std::wstring &alphabet)
{
return validSeparatedWord(lower(text), alphabet, L"-");
}
bool validAutoReplacementSource(const std::wstring &text, const std::wstring &alphabet)
{
return text.find(L' ') == text.npos && text.find_first_of(alphabet) != text.npos &&
@@ -309,40 +319,6 @@ std::wstring transliterate(const std::wstring &text)
}
return out;
}
Template parseTemplate(const std::wstring &text)
{
Template t;
size_t cursor = std::wstring::npos;
for (size_t i = 0; i < text.size();)
{
if (text.compare(i, 9, L"{{enter}}") == 0)
{
t.text += L"{enter}";
i += 9;
}
else if (text.compare(i, 7, L"{enter}") == 0)
{
++t.enters;
i += 7;
}
else if (text.compare(i, 10, L"{{cursor}}\0", 10) == 0)
{
t.text += L"{cursor}";
i += 10;
}
else if (text.compare(i, 8, L"{cursor}") == 0)
{
cursor = t.text.size();
++t.cursors;
i += 8;
}
else
t.text += text[i++];
}
if (cursor != text.npos)
t.suffix = t.text.substr(cursor);
return t;
}
namespace
{
const std::vector<std::pair<UINT, std::wstring>> &namedKeys()
@@ -367,7 +343,176 @@ const std::vector<std::pair<UINT, std::wstring>> &namedKeys()
{VK_DIVIDE, L"Divide"}, {VK_DECIMAL, L"Decimal"}};
return names;
}
WORD namedKey(const std::wstring &token)
{
if (token.size() == 1 && ((token[0] >= L'a' && token[0] <= L'z') || iswdigit(token[0])))
return upper(token)[0];
if (token.size() == 4 && token.starts_with(L"num") && token[3] >= L'0' && token[3] <= L'9')
return VK_NUMPAD0 + token[3] - L'0';
if (token.size() >= 2 && token[0] == L'f')
{
wchar_t *tail{};
long n = wcstol(token.c_str() + 1, &tail, 10);
if (!*tail && n >= 1 && n <= 24) return static_cast<WORD>(VK_F1 + n - 1);
return 0;
}
for (const auto &[key, name] : namedKeys())
if (lower(name) == token) return static_cast<WORD>(key);
return 0;
}
WORD snippetKey(std::wstring_view name)
{
const auto token = lower(std::wstring(name));
static constexpr std::pair<std::wstring_view, WORD> modifiers[] = {
{L"shift", VK_LSHIFT}, {L"shiftl", VK_LSHIFT}, {L"shiftr", VK_RSHIFT},
{L"ctrl", VK_LCONTROL}, {L"ctrll", VK_LCONTROL}, {L"ctrlr", VK_RCONTROL},
{L"alt", VK_LMENU}, {L"altl", VK_LMENU}, {L"altr", VK_RMENU},
{L"win", VK_LWIN}, {L"winl", VK_LWIN}, {L"winr", VK_RWIN}};
for (const auto &[label, key] : modifiers)
if (label == token) return key;
if (token == L"return") return VK_RETURN;
// The old double-braced Enter marker is still an escape.
return token == L"enter" ? 0 : namedKey(token);
}
struct SnippetMarker
{
std::wstring_view name;
size_t length, depth;
};
std::optional<SnippetMarker> snippetMarker(std::wstring_view input)
{
if (!input.starts_with(L'{')) return {};
size_t depth = 1;
while (depth < 3 && depth < input.size() && input[depth] == L'{') ++depth;
const auto end = input.find_first_of(L"{}", depth);
if (end == input.npos || !input.substr(end).starts_with(std::wstring_view(L"}}}", depth)))
return {};
return SnippetMarker{input.substr(depth, end - depth), end + depth, depth};
}
std::optional<DWORD> snippetPause(std::wstring_view token)
{
constexpr std::wstring_view prefix = L"pause:";
constexpr DWORD maxPause = 10000;
if (!token.starts_with(prefix) || token.size() == prefix.size()) return {};
DWORD duration = 0;
for (wchar_t digit : token.substr(prefix.size()))
{
if (digit < L'0' || digit > L'9') return {};
duration = duration * 10 + (digit - L'0');
if (duration > maxPause) return {};
}
return duration;
}
} // namespace
std::wstring snippetKeyName(WORD key)
{
switch (key)
{
case VK_LSHIFT: return L"Shift";
case VK_RSHIFT: return L"ShiftR";
case VK_LCONTROL: return L"Ctrl";
case VK_RCONTROL: return L"CtrlR";
case VK_LMENU: return L"Alt";
case VK_RMENU: return L"AltR";
case VK_LWIN: return L"Win";
case VK_RWIN: return L"WinR";
default: return Hotkey{0, key}.format();
}
}
std::wstring formatSnippetInsertion(SnippetInsertion type, std::wstring_view parameter)
{
if (type == SnippetInsertion::Cursor) return L"{cursor}";
if (type == SnippetInsertion::Enter) return L"{enter}";
if (type == SnippetInsertion::Pause)
{
auto pause = L"pause:" + std::wstring(parameter);
return snippetPause(pause) ? L"{" + pause + L"}" : std::wstring{};
}
const bool chord = type == SnippetInsertion::Chord;
if (!chord && type != SnippetInsertion::Key) return {};
std::wstring text;
std::vector<WORD> keys;
while (true)
{
const auto end = parameter.find(L'+');
const auto token = parameter.substr(0, end);
const auto first = token.find_first_not_of(L" \t");
if (first == token.npos) return {};
auto name = lower(std::wstring(token.substr(first, token.find_last_not_of(L" \t") - first + 1)));
if (name == L"enter") name = L"return";
const auto key = snippetKey(name);
if (!key || std::find(keys.begin(), keys.end(), key) != keys.end()) return {};
keys.push_back(key);
if (!text.empty()) text += L'+';
text += L"{{" + name + L"}}";
if (end == parameter.npos) break;
if (!chord) return {};
parameter.remove_prefix(end + 1);
}
return chord && keys.size() < 2 ? std::wstring{} : text;
}
Template parseTemplate(const std::wstring &text)
{
Template t;
std::wstring_view remaining(text);
size_t cursor = text.npos;
while (!remaining.empty())
{
const auto marker = snippetMarker(remaining);
if (!marker)
{
t.text += remaining.front();
remaining.remove_prefix(1);
continue;
}
const auto [name, length, depth] = *marker;
const auto pause = depth <= 2 ? snippetPause(name) : std::nullopt;
const WORD key = depth >= 2 ? snippetKey(name) : 0;
const bool legacyEscape = name == L"cursor" || name == L"enter";
if (depth == 1 && name == L"cursor")
{
cursor = t.text.size();
++t.cursors;
}
else if (depth == 1 && name == L"enter")
t.actions.push_back({t.text.size(), std::vector<WORD>{VK_RETURN}});
else if (depth == 1 && pause)
t.actions.push_back({t.text.size(), *pause});
else if (depth == 2 && key)
{
std::vector<WORD> keys{key};
remaining.remove_prefix(length);
while (remaining.starts_with(L'+'))
{
const auto next = snippetMarker(remaining.substr(1));
if (!next || next->depth != 2) break;
const WORD nextKey = snippetKey(next->name);
if (!nextKey) break;
if (std::find(keys.begin(), keys.end(), nextKey) == keys.end())
keys.push_back(nextKey);
remaining.remove_prefix(1 + next->length);
}
t.actions.push_back({t.text.size(), std::move(keys)});
continue;
}
else if ((depth >= 2 && legacyEscape) || (depth == 2 && pause) || (depth == 3 && key))
t.text += remaining.substr(1, length - 2);
else
t.text += remaining.substr(0, length);
remaining.remove_prefix(length);
}
if (cursor != text.npos)
t.suffix = t.text.substr(cursor);
// A leading action has historically followed replacement of the trigger.
// Keep that behavior while allowing actions between text segments.
const auto first = std::find_if(t.actions.begin(), t.actions.end(),
[](const SnippetAction &action) { return action.offset != 0; });
const auto firstText = first == t.actions.end() ? t.text.size() : first->offset;
for (auto it = t.actions.begin(); it != first; ++it)
it->offset = firstText;
return t;
}
std::wstring Hotkey::format() const
{
if (!key)
@@ -413,32 +558,7 @@ std::optional<Hotkey> Hotkey::parse(std::wstring s)
h.modifiers |= MOD_WIN;
else
{
if (h.key)
return {};
if (token.size() == 1 && ((token[0] >= L'a' && token[0] <= L'z') || iswdigit(token[0])))
h.key = upper(token)[0];
else if (token.size() == 4 && token.substr(0, 3) == L"num" && token[3] >= L'0' &&
token[3] <= L'9')
h.key = VK_NUMPAD0 + token[3] - L'0';
else if (token.size() >= 2 && token[0] == L'f')
{
wchar_t *tail{};
long n = wcstol(token.c_str() + 1, &tail, 10);
if (*tail || n < 1 || n > 24)
return {};
h.key = VK_F1 + (UINT)n - 1;
}
else
{
for (auto &[key, name] : namedKeys())
if (lower(name) == token)
{
h.key = key;
break;
}
if (!h.key)
return {};
}
if (h.key || !(h.key = namedKey(token))) return {};
}
if (end == s.npos)
break;
+13 -2
View File
@@ -5,6 +5,7 @@
#include <optional>
#include <set>
#include <string>
#include <variant>
#include <vector>
#include <windows.h>
@@ -22,6 +23,7 @@ struct Layout
bool letter(wchar_t ch);
bool validAutoCorrection(const std::wstring &text, const std::wstring &alphabet);
bool validAutoReplacementSource(const std::wstring &text, const std::wstring &alphabet);
bool validPersonalWord(const std::wstring &text, const std::wstring &alphabet);
std::wstring lower(std::wstring text);
std::wstring upper(std::wstring text);
std::wstring convert(const std::wstring &, const Layout &, const Layout &, bool force = false);
@@ -41,13 +43,22 @@ std::wstring snippetAppName(std::wstring);
int snippetAppPriority(const Snippet &, const std::wstring &process);
std::wstring snippetId(const Snippet &);
std::wstring newSnippetId();
struct SnippetAction
{
size_t offset;
std::variant<std::vector<WORD>, DWORD> value;
bool operator==(const SnippetAction &) const = default;
};
struct Template
{
std::wstring text, suffix;
std::vector<SnippetAction> actions;
int cursors = 0;
int enters = 0;
};
Template parseTemplate(const std::wstring &);
enum class SnippetInsertion { Cursor, Enter, Pause, Key, Chord };
std::wstring snippetKeyName(WORD);
std::wstring formatSnippetInsertion(SnippetInsertion, std::wstring_view parameter);
struct Hotkey
{
UINT modifiers{}, key{};
@@ -78,7 +89,7 @@ struct Settings
bool autoCorrect = false;
bool autoReplace = false, autoTypos = false;
std::map<std::wstring, std::wstring> autoReplacements;
bool writeLog = true;
bool writeLog = false;
bool screenshotAutoOpenEditor = false;
bool useTesseract = false;
std::wstring tesseractPath;
+495
View File
@@ -0,0 +1,495 @@
#include "google_drive.h"
#include "sync.h"
#include "mouse_buttons.h"
#include "json.hpp"
#include <algorithm>
#include <sstream>
#include <tuple>
namespace ks
{
namespace
{
using Json = nlohmann::json;
constexpr auto NativeFormat = "kswitcher-win32-drive-backup-v1";
constexpr auto PreviewFormat = "kswitcher-drive-backup-v1";
// Select fields explicitly so changes to native serialization cannot expand the backup.
constexpr const char *PortableFields[] = {
"convertLastWord", "switchSystemLayout", "autoCorrectLayout", "autoCorrectReplace", "autoCorrectTypos",
"autoCorrectReplacements", "autoCorrectMaxRank", "autoCorrectMinLength", "autoCorrectPrefixChars",
"autoCorrectSuffixChars", "autoCorrectLanguages", "autoCorrectNever", "autoCorrectExcludedApps",
"autoCorrectWords", "preventScreenLock", "toggleHotkey", "caseHotkey", "translitHotkey", "undoHotkey",
"clipboardHotkey", "screenshotHotkey", "filesHotkey", "screenshotAutoOpenEditor", "historyEnabled",
"maxItems", "maxTotalMegabytes", "maxImageMegabytes", "excludedApps", "useTesseract", "tesseractLanguages",
"layouts", "layoutHotkeys", "chatCycles", "appLanguageSets", "snippets", "mouseBindings",
"mouseProfileApplications", "disabledMouseProfiles", "customMouseEvents"
};
Bytes bytes(const Json &object)
{
const auto text = object.dump();
return {text.begin(), text.end()};
}
Json portableFields(const Json &source)
{
auto result = Json::object();
for (const auto *key : PortableFields)
if (source.contains(key)) result[key] = source.at(key);
return result;
}
bool machineLocalMouseAction(const Json &binding)
{
if (!binding.is_object() || binding.value("action", "") != "Launch application") return false;
return binding.at("executable").get<std::string>().find_first_of("\\/:") != std::string::npos;
}
void excludeMousePaths(Json &settings)
{
if (!settings.contains("mouseBindings")) return;
auto &profiles = settings.at("mouseBindings");
if (!profiles.is_object()) throw std::runtime_error("Invalid mouse profiles.");
for (auto &bindings : profiles)
{
if (!bindings.is_object()) throw std::runtime_error("Invalid mouse actions.");
for (auto action = bindings.begin(); action != bindings.end();)
{
if (machineLocalMouseAction(*action)) action = bindings.erase(action);
else ++action;
}
}
}
void preserveMousePaths(Json &settings, const Json &local)
{
if (!settings.contains("mouseBindings")) return;
for (const auto &[profile, bindings] : local.at("mouseBindings").items())
for (const auto &[event, action] : bindings.items())
{
if (!machineLocalMouseAction(action)) continue;
settings["mouseBindings"][profile][event] = action;
if (!settings.contains("mouseProfileApplications") ||
!settings.at("mouseProfileApplications").is_object())
throw std::runtime_error("Invalid mouse profile applications.");
auto &scopes = settings.at("mouseProfileApplications");
if (local.at("mouseProfileApplications").contains(profile))
scopes[profile] = local.at("mouseProfileApplications").at(profile);
else scopes.erase(profile);
if (local.at("customMouseEvents").contains(event) && !settings.at("customMouseEvents").contains(event))
settings["customMouseEvents"][event] = local.at("customMouseEvents").at(event);
auto &disabled = settings.at("disabledMouseProfiles");
if (!disabled.is_array()) throw std::runtime_error("Invalid disabled mouse profiles.");
const bool wasDisabled = std::find(local.at("disabledMouseProfiles").begin(),
local.at("disabledMouseProfiles").end(), profile) != local.at("disabledMouseProfiles").end();
const auto entry = std::find(disabled.begin(), disabled.end(), profile);
if (wasDisabled && entry == disabled.end()) disabled.push_back(profile);
if (!wasDisabled && entry != disabled.end()) disabled.erase(entry);
}
}
std::vector<std::string> list(const Json &value)
{
if (value.is_array()) return value.get<std::vector<std::string>>();
auto input = wide(value.get<std::string>());
std::replace(input.begin(), input.end(), L',', L' ');
std::wistringstream stream(input);
std::vector<std::string> result;
for (std::wstring item; stream >> item;) result.push_back(utf8(item));
return result;
}
std::string layoutId(const Json &value)
{
auto id = utf8(lower(wide(value.get<std::string>())));
if (id == "english" || id == "en" || id == "us" || id == "00000409") return "win:04090409";
if (id == "ukrainian" || id == "uk" || id == "ua" || id == "00000422") return "win:04220422";
if (id == "russian" || id == "ru" || id == "00000419") return "win:04190419";
if (id == "00000809") return "win:08090809";
return id;
}
Json layoutList(const Json &value)
{
auto result = Json::array();
for (const auto &id : list(value)) result.push_back(layoutId(id));
return result;
}
std::string appName(const Json &value)
{
return utf8(snippetAppName(wide(value.get<std::string>())));
}
void previewLayouts(const Json &options, Json &result)
{
if (options.contains("layouts"))
{
auto &cycle = result["layouts"] = Json::array();
auto &keys = result["layoutHotkeys"] = Json::array();
for (const auto &row : options.at("layouts").get<Json::array_t>())
{
auto id = layoutId(row.at("layout"));
if (row.value("included", true)) cycle.push_back(id);
keys.push_back({{"layoutId", id}, {"hotkey", row.value("shortcut", "")}});
}
}
else if (options.contains("legacySettings"))
{
const auto &legacy = options.at("legacySettings");
if (legacy.contains("layouts")) result["layouts"] = layoutList(legacy.at("layouts"));
if (legacy.contains("layoutHotkeys"))
{
auto &keys = result["layoutHotkeys"] = Json::array();
for (const auto &row : legacy.at("layoutHotkeys").get<Json::array_t>())
keys.push_back({{"layoutId", layoutId(row.at("layoutId"))}, {"hotkey", row.at("hotkey").get<std::string>()}});
}
}
if (options.contains("appLanguages"))
{
auto &profiles = result["appLanguageSets"] = Json::object();
for (const auto &row : options.at("appLanguages").get<Json::array_t>())
{
auto app = appName(row.at("app"));
auto cycle = layoutList(row.at("languages"));
if (!app.empty() && !cycle.empty())
profiles[app] = {{"applications", Json::array({app})}, {"languages", cycle}};
}
}
if (options.contains("chatLanguages"))
{
auto &profiles = result["chatCycles"] = Json::object();
for (const auto &row : options.at("chatLanguages").get<Json::array_t>())
{
auto app = appName(row.at("app"));
auto contact = row.at("contact").get<std::string>();
auto cycle = layoutList(row.at("languages"));
if ((app == "telegram" || app == "telegram-web" || app == "ms-teams" || app == "viber") &&
!contact.empty() && !cycle.empty())
profiles[app + "\n" + contact] = cycle;
}
}
}
void previewSnippets(const Json &settings, const Json &options, Json &result)
{
using SnippetKey = std::tuple<std::string, std::string, std::set<std::string>>;
auto keyFor = [](const Json &row)
{
std::set<std::string> apps;
if (row.contains("apps") && row.value("scoped", true))
for (const auto &app : list(row.at("apps"))) apps.insert(appName(app));
return SnippetKey{row.at("trigger").get<std::string>(), row.at("replacement").get<std::string>(), std::move(apps)};
};
const auto optionRows = options.value("snippets", Json::array()).get<Json::array_t>();
std::map<SnippetKey, std::string> ids;
for (const auto &row : optionRows)
if (row.value("enabled", false) && row.contains("id"))
ids.emplace(keyFor(row), row.at("id").get<std::string>());
Json::array_t rows;
if (settings.contains("snippets") && !settings.at("snippets").is_null())
rows = settings.at("snippets").get<Json::array_t>();
else if (options.contains("snippets"))
rows = optionRows;
else if (settings.contains("snippet"))
rows.push_back(settings.at("snippet"));
else
return;
auto &snippets = result["snippets"] = Json::array();
for (const auto &row : rows)
{
if (!row.value("enabled", false)) continue;
auto key = keyFor(row);
const auto &[trigger, replacement, apps] = key;
Json item{{"trigger", trigger}, {"text", replacement}};
if (!apps.empty()) item["apps"] = apps;
if (row.value("scoped", false) && (!item.contains("apps") || item.at("apps").empty()))
throw std::runtime_error("A scoped snippet needs an application.");
if (row.contains("id")) item["id"] = row.at("id").get<std::string>();
else if (const auto id = ids.find(key); id != ids.end()) item["id"] = id->second;
snippets.push_back(std::move(item));
}
}
void previewMouse(const Json &settings, const Json &options, Json &result)
{
if (!options.contains("mouseProfiles") && !options.contains("mouseActions") &&
!options.contains("mouseEvents") && !settings.contains("mouse")) return;
auto &bindings = result["mouseBindings"] = Json::object();
auto &scopes = result["mouseProfileApplications"] = Json::object();
auto &disabled = result["disabledMouseProfiles"] = Json::array();
auto &custom = result["customMouseEvents"] = Json::object();
constexpr const char *events[] = {"Left click", "Right click", "Middle click", "First side button",
"Second side button", "Left double-click", "Right double-click", "Middle double-click",
"Wheel up", "Wheel down", "Wheel left", "Wheel right"};
static_assert(std::size(events) == std::size(MouseEvents));
std::map<std::string, std::string> signals, profiles{{"*", "*"}, {"default", "*"}};
for (size_t i = 0; i < std::size(events); ++i) signals[events[i]] = utf8(MouseEvents[i]);
for (const auto &row : options.value("mouseEvents", Json::array()).get<Json::array_t>())
{
auto signal = row.value("signal", "");
if (!signals.contains(signal) || !signal.starts_with("Wheel ")) continue;
auto name = row.at("name").get<std::string>();
custom[signal] = name;
signals[name] = signal;
}
for (const auto &row : options.value("mouseProfiles", Json::array()).get<Json::array_t>())
{
auto id = row.at("id").get<std::string>();
auto name = row.at("name").get<std::string>();
auto apps = list(row.value("apps", Json("")));
for (auto &app : apps) app = appName(app);
if (id == "*" || (id == "default" && apps.empty())) continue;
if (id == name && !id.starts_with("name:") && apps.empty() &&
row.value("enabled", true) && validMouseApplication(wide(id)))
{
profiles[id] = id;
continue;
}
auto profile = "name:" + name;
profiles[id] = profile;
bindings[profile] = Json::object();
scopes[profile] = apps;
if (!row.value("enabled", true)) disabled.push_back(profile);
}
auto add = [&](const std::string &profile, const std::string &event, const Json &row)
{
constexpr const char *actions[] = {"Unassigned", "Shortcut", "Back", "Forward", "VolumeUp",
"VolumeDown", "Mute", "Launch"};
static_assert(std::size(actions) == std::size(MouseActions));
auto name = row.at("action").get<std::string>();
auto match = std::find(std::begin(actions), std::end(actions), name);
if (match == std::end(actions)) throw std::runtime_error("Unknown mouse action.");
const auto type = static_cast<MouseActionType>(match - std::begin(actions));
Json binding{{"action", utf8(MouseActions[static_cast<size_t>(type)])}};
if (type == MouseActionType::Shortcut) binding["shortcut"] = row.at("shortcut").get<std::string>();
if (type == MouseActionType::Launch) binding["executable"] = row.at("executable").get<std::string>();
if (isMouseVolumeStep(type)) binding["volumeStep"] = row.value("step", Json(DefaultMouseVolumeStep));
auto apps = list(row.value("apps", Json("")));
for (auto &app : apps) app = appName(app);
if (!apps.empty() && !profile.starts_with("name:")) binding["applications"] = apps;
if (event.starts_with("Wheel ") && !custom.contains(event)) custom[event] = event;
if (!machineLocalMouseAction(binding)) bindings[profile][event] = std::move(binding);
};
const auto rows = options.value("mouseActions", Json::array()).get<Json::array_t>();
for (const auto &row : rows)
{
auto event = row.at("event").get<std::string>();
if (signals.contains(event)) add(profiles.at(row.at("profile").get<std::string>()), signals.at(event), row);
}
const auto mouse = settings.value("mouse", Json::object());
if (rows.empty() && mouse.value("enabled", false))
{
add("*", "XButton1", {{"action", mouse.value("default_action", "Unassigned")}});
auto app = appName(mouse.value("application", ""));
if (!app.empty()) add(app, "XButton1", {{"action", mouse.value("application_action", "Unassigned")}});
}
}
Json previewFields(const Json &profile, const Json &local)
{
const auto &options = profile.at("options");
const auto &settings = profile.at("settings");
if (!options.is_object() || !settings.is_object() || (options.empty() && settings.empty()))
throw std::runtime_error("Invalid preview profile.");
auto result = Json::object();
constexpr std::pair<const char *, const char *> fields[] = {
{"general.conversion.recent", "convertLastWord"}, {"general.conversion.switchLayout", "switchSystemLayout"},
{"general.correction.maxRank", "autoCorrectMaxRank"}, {"general.correction.minLength", "autoCorrectMinLength"},
{"general.correction.prefix", "autoCorrectPrefixChars"}, {"general.correction.suffix", "autoCorrectSuffixChars"},
{"general.correction.autoReplace", "autoCorrectReplace"}, {"general.correction.autoTypos", "autoCorrectTypos"},
{"general.integration.awake", "preventScreenLock"},
{"shortcuts.key-bindings.toggle", "toggleHotkey"}, {"shortcuts.key-bindings.case", "caseHotkey"},
{"shortcuts.key-bindings.transliterate", "translitHotkey"}, {"shortcuts.key-bindings.undo", "undoHotkey"},
{"shortcuts.key-bindings.clipboard", "clipboardHotkey"}, {"shortcuts.key-bindings.capture", "screenshotHotkey"},
{"shortcuts.key-bindings.files", "filesHotkey"}, {"shortcuts.capture.openEditor", "screenshotAutoOpenEditor"},
{"clipboard.history.record", "historyEnabled"}, {"clipboard.history.items", "maxItems"},
{"clipboard.history.capacity", "maxTotalMegabytes"}, {"clipboard.history.perItem", "maxImageMegabytes"},
{"clipboard.ocr.useTesseract", "useTesseract"}, {"clipboard.ocr.tesseractLanguages", "tesseractLanguages"}
};
for (const auto &[from, to] : fields)
if (options.contains(from)) result[to] = options.at(from);
for (const auto &[from, to] : {std::pair{"general.correction.dictionaryLanguages", "autoCorrectLanguages"},
{"general.correction.autoExcluded", "autoCorrectExcludedApps"}, {"clipboard.history.excluded", "excludedApps"}})
if (options.contains(from)) result[to] = list(options.at(from));
if (options.contains("general.correction.autoReplacements"))
{
auto &pairs = result["autoCorrectReplacements"] = Json::object();
std::istringstream lines(options.at("general.correction.autoReplacements").get<std::string>());
for (std::string line; std::getline(lines, line);)
{
auto split = line.find('=');
if (line.find_first_not_of(" \t\r") == line.npos) continue;
if (split == line.npos) throw std::runtime_error("Invalid automatic replacement.");
auto trim = [](std::string text)
{
const auto first = text.find_first_not_of(" \t\r");
return first == text.npos ? std::string{} :
text.substr(first, text.find_last_not_of(" \t\r") - first + 1);
};
if (!pairs.emplace(trim(line.substr(0, split)), trim(line.substr(split + 1))).second)
throw std::runtime_error("Duplicate automatic replacement.");
}
}
if (settings.contains("autocorrect")) result["autoCorrectLayout"] = settings.at("autocorrect");
const auto dictionary = settings.value("personal_dictionary", Json::object());
auto words = local.at("autoCorrectWords");
bool hasWords = false;
for (const auto &[key, language] : {std::pair{"en", "english"}, {"uk", "ukrainian"}, {"ru", "russian"}})
{
const std::string field = std::string("general.correction.words.") + key;
if (options.contains(field)) words[key] = list(options.at(field));
else if (dictionary.contains(language)) words[key] = dictionary.at(language).get<std::vector<std::string>>();
else continue;
hasWords = true;
}
if (hasWords) result["autoCorrectWords"] = std::move(words);
if (options.contains("general.correction.autoNever"))
result["autoCorrectNever"] = list(options.at("general.correction.autoNever"));
else if (dictionary.contains("never")) result["autoCorrectNever"] = list(dictionary.at("never"));
previewLayouts(options, result);
previewSnippets(settings, options, result);
previewMouse(settings, options, result);
if (result.empty()) throw std::runtime_error("No supported preview settings.");
return result;
}
void checkLayouts(const Json &fields, const std::vector<Layout> &layouts)
{
auto check = [&](const std::string &id)
{
const auto w = wide(id);
if (std::none_of(layouts.begin(), layouts.end(), [&](const auto &layout) { return layout.id == w; }))
throw std::runtime_error("Install the keyboard layouts used by this backup in Windows, then try restoring again.");
};
if (fields.contains("layouts"))
for (const auto &id : fields.at("layouts").get<std::vector<std::string>>()) check(id);
if (fields.contains("layoutHotkeys"))
for (const auto &binding : fields.at("layoutHotkeys").get<Json::array_t>())
if (!binding.at("hotkey").get<std::string>().empty()) check(binding.at("layoutId").get<std::string>());
}
void allowRestoredSnippets(Json &settings)
{
std::set<std::string> ids;
for (const auto &item : settings.at("snippets").get<Json::array_t>())
{
auto id = item.value("id", "");
if (id.empty() && (!item.contains("apps") || item.at("apps").empty()))
id = utf8(snippetId({wide(item.at("trigger").get<std::string>()), {}, {}, {}}));
if (!id.empty()) ids.insert(std::move(id));
}
auto tombstones = settings.at("snippetTombstones").get<std::vector<std::string>>();
std::erase_if(tombstones, [&](const auto &id) { return ids.contains(id); });
settings["snippetTombstones"] = std::move(tombstones);
}
Json mergeDriveFields(Json fields, const Json &original)
{
excludeMousePaths(fields);
auto local = original;
local.update(fields);
if (local.contains("filesHotkey") && local.at("filesHotkey").is_null()) local.erase("filesHotkey");
if (fields.contains("mouseBindings")) preserveMousePaths(local, original);
if (fields.contains("snippets")) allowRestoredSnippets(local);
return local;
}
}
Bytes sharedDriveSettings(const Settings &saved)
{
const auto source = Json::parse(sharedSyncSettings(saved));
auto profile = portableFields(source);
excludeMousePaths(profile);
auto &bindings = profile.at("mouseBindings");
for (auto it = bindings.begin(); it != bindings.end();)
// Named profiles can retain their application scope without actions.
if (it->empty() && !isNamedMouseProfile(wide(it.key()))) it = bindings.erase(it);
else ++it;
if (!profile.contains("filesHotkey")) profile["filesHotkey"] = nullptr;
for (const auto *field : {"format", "schemaVersion", "snippetTombstones"}) profile[field] = source.at(field);
return bytes(profile);
}
Settings restoreSharedDriveSettings(const Bytes &shared, const Settings &local, const std::vector<Layout> &layouts)
{
const auto source = Json::parse(shared);
if (!source.is_object() || source.value("format", "") != "kswitcher-settings" ||
source.value("schemaVersion", 0) != 1 || source.size() != std::size(PortableFields) + 3 ||
!source.contains("snippetTombstones"))
throw std::runtime_error("Invalid Google Drive synchronization profile.");
auto fields = portableFields(source);
if (fields.size() != std::size(PortableFields))
throw std::runtime_error("Incomplete Google Drive synchronization profile.");
fields["snippetTombstones"] = source.at("snippetTombstones");
checkLayouts(fields, layouts);
return decodeSettings(bytes(mergeDriveFields(std::move(fields), Json::parse(encodeSettings(local)))), layouts);
}
Bytes encodeDriveBackup(const Settings &saved)
{
auto profile = portableFields(Json::parse(encodeSettings(saved)));
if (!profile.contains("filesHotkey")) profile["filesHotkey"] = nullptr;
excludeMousePaths(profile);
auto result = bytes({{"format", NativeFormat}, {"settings", std::move(profile)}});
if (result.size() > GoogleDriveBackupLimit) throw std::runtime_error("Saved settings exceed the 2 MiB backup limit.");
return result;
}
Settings restoreDriveBackup(const Bytes &backup, const Settings &draft, const std::vector<Layout> &layouts)
{
if (backup.size() > GoogleDriveBackupLimit) throw std::runtime_error("This Drive backup exceeds the 2 MiB limit.");
// Limit nesting before the parser allocates a tree from downloaded data.
const auto document = Json::parse(backup, [](int depth, Json::parse_event_t, Json &)
{
if (depth > 32) throw std::runtime_error("This Drive backup is corrupt.");
return true;
}, false);
if (!document.is_object() || !document.contains("format") || !document.at("format").is_string())
throw std::runtime_error("This Drive backup is corrupt.");
const auto format = document.at("format").get<std::string>();
if (format != NativeFormat && format != PreviewFormat)
throw std::runtime_error("This Drive backup format is unsupported.");
const auto original = Json::parse(encodeSettings(draft));
auto local = original;
Json fields;
try
{
if (format == NativeFormat)
{
const auto &source = document.at("settings");
if (!source.is_object()) throw std::runtime_error("Invalid settings.");
for (const auto *key : PortableFields)
if (!source.contains(key)) throw std::runtime_error("Incomplete settings.");
fields = portableFields(source);
}
else fields = previewFields(document.at("profile"), local);
local = mergeDriveFields(fields, original);
}
catch (const std::exception &)
{
throw std::runtime_error("This Drive backup contains invalid settings.");
}
try
{
checkLayouts(fields, layouts);
}
catch (const Json::exception &)
{
throw std::runtime_error("This Drive backup contains invalid layouts or shortcuts.");
}
try
{
return decodeSettings(bytes(local), layouts);
}
catch (const std::exception &)
{
throw std::runtime_error("This Drive backup contains settings that are invalid or conflict with this PC's settings.");
}
}
}
+321
View File
@@ -0,0 +1,321 @@
#pragma once
#include "platform.h"
#include "files_powershell.h"
#include "files_windows_command_catalog.h"
#include "../vendor/json.hpp"
#include <optional>
#include <vector>
namespace ks::files
{
class CommandCompletion
{
public:
using Json = nlohmann::json;
CommandCompletion() = default;
CommandCompletion(const CommandCompletion &) = delete;
CommandCompletion &operator=(const CommandCompletion &) = delete;
~CommandCompletion() { close(); }
bool request(const std::wstring &line, DWORD caret, const std::wstring &directory)
{
auto message=Json{{"line",utf8(line)},{"caret",caret},{"directory",utf8(directory)}}.dump(
-1,' ',true,Json::error_handler_t::replace)+"\n";
if(message.size()>32768 || (!process && !start())) return false;
if(!write(message))
{
close();
return false;
}
deadline=GetTickCount64()+5000;
return true;
}
// An empty optional means the request is still running.
std::optional<Json> poll()
{
DWORD available{},count{};
char chunk[8192];
if(!PeekNamedPipe(output,nullptr,0,nullptr,&available,nullptr) ||
GetTickCount64()>=deadline || pending.size()>1024*1024)
{
close();
return Json{};
}
if(available && ReadFile(output,chunk,std::min<DWORD>(available,sizeof(chunk)),&count,nullptr))
pending.append(chunk,count);
const auto end=pending.find('\n');
if(end==pending.npos) return {};
auto result=Json::parse(pending.begin(),pending.begin()+end,nullptr,false);
pending.erase(0,end+1);
return result;
}
private:
HANDLE process{},input{},output{},job{};
ULONGLONG deadline{};
std::string pending;
bool write(std::string_view message)
{
DWORD written{};
return WriteFile(input,message.data(),static_cast<DWORD>(message.size()),&written,nullptr) &&
written==message.size();
}
bool start()
{
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
HANDLE childInput{},childOutput{};
std::string catalog;
for(const auto row:windowsCommandCatalog) catalog.append(row).push_back('\n');
const auto initial=Json{{"catalog",std::move(catalog)}}.dump()+"\n";
const auto inputCapacity=static_cast<DWORD>(initial.size()+32768);
const bool pipes=CreatePipe(&childInput,&input,&inheritable,inputCapacity) &&
CreatePipe(&output,&childOutput,&inheritable,65536) &&
SetHandleInformation(input,HANDLE_FLAG_INHERIT,0) &&
SetHandleInformation(output,HANDLE_FLAG_INHERIT,0);
const bool started=pipes && launch(childInput,childOutput) && write(initial);
if(childInput) CloseHandle(childInput);
if(childOutput) CloseHandle(childOutput);
if(!started) close();
return started;
}
bool launch(HANDLE childInput,HANDLE childOutput)
{
const auto shell=windowsPowerShell();
if(shell.empty()) return false;
// The request is data on stdin. PowerShell parses it for completion in this separate session.
wchar_t command[]=LR"PS(powershell.exe -NoLogo -NoProfile -NonInteractive -Command "
$ProgressPreference = 'SilentlyContinue';
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false);
function Get-CompletedArguments($command, $position, $includeCurrent) {
foreach ($element in ($command.CommandElements | Select-Object -Skip 1)) {
if ($element.Extent.EndOffset -gt $position -or
(!$includeCurrent -and $element.Extent.EndOffset -eq $position)) { break }
if ($element -is [System.Management.Automation.Language.StringConstantExpressionAst]) {
$element.Value;
} else { $element.Extent.Text }
}
}
function New-ArgumentCompletion([string]$value) {
$text = $value;
if ($value.StartsWith('@') -or $value -notmatch '^[\p{L}\p{M}\p{N}._/@:+,=\-]+$') {
$quote = [string][char]39;
$text = $quote + [System.Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($value) + $quote;
}
[System.Management.Automation.CompletionResult]::new($text, $value, 'ParameterValue', $value)
}
function Get-DhcpAdapterNames {
foreach ($adapter in [Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
if (!$adapter.Supports([Net.NetworkInformation.NetworkInterfaceComponent]::IPv4)) { continue }
try {
if ($adapter.GetIPProperties().GetIPv4Properties().IsDhcpEnabled) { $adapter.Name }
} catch {}
}
}
$initial = ConvertFrom-Json -InputObject ([Console]::ReadLine());
$windowsCommands = @{};
$windowsHelp = @{};
foreach ($row in ($initial.catalog -split '\r?\n')) {
if (!$row) { continue }
$name, $values, $article = $row.Split([char]9, 3);
$windowsCommands[$name] = if ($values) { $values.Split(' ') } else { @() };
if ($article) { $windowsHelp[$name] = $article }
}
$windowsRoots = @($windowsCommands.Keys | Where-Object { !($_.Contains(' ')) } | Sort-Object);
$windowsPrograms = @(foreach ($name in $windowsRoots) { $name; $name + '.exe'; $name + '.com' });
function Get-WindowsCommandContext($command, $position, $includeCurrent) {
if (!$command) { return }
$invoked = $command.GetCommandName();
if (!$invoked -or !$windowsCommands.ContainsKey([IO.Path]::GetFileNameWithoutExtension($invoked))) { return }
$resolved = Get-Command -Name ([WildcardPattern]::Escape($invoked)) -ErrorAction SilentlyContinue |
Select-Object -First 1;
if ($resolved -is [System.Management.Automation.AliasInfo]) { $resolved = $resolved.ResolvedCommand }
if ($resolved -isnot [System.Management.Automation.ApplicationInfo]) { return }
$name = [IO.Path]::GetFileNameWithoutExtension($resolved.Name);
$arguments = @(Get-CompletedArguments $command $position $includeCurrent);
$values = $null;
if ($name -eq 'cmd') {
for ($i = 0; $i -lt $arguments.Count; ++$i) {
if ($arguments[$i] -notin '/c', '/k') { continue }
if ($i + 1 -lt $arguments.Count) {
$name = [IO.Path]::GetFileNameWithoutExtension($arguments[$i + 1]);
$arguments = @($arguments | Select-Object -Skip ($i + 2));
} else { $values = $windowsRoots }
break
}
}
$root = $name;
$article = $windowsHelp[$name];
if (!$values) {
foreach ($argument in $arguments) {
$child = $name + ' ' + $argument;
if (!$windowsCommands.ContainsKey($child)) { break }
$name = $child;
if ($windowsHelp[$name]) { $article = $windowsHelp[$name] }
}
$values = $windowsCommands[$name];
}
@{ root = $root; values = $values; arguments = $arguments; article = $article }
}
Register-ArgumentCompleter -Native -CommandName $windowsPrograms -ScriptBlock {
param($word, $command, $position)
$context = Get-WindowsCommandContext $command $position $false;
if (!$context) { return }
if ($context.root -eq 'ipconfig' -and $context.arguments.Count -and
$context.arguments[0] -in '/renew','/release') {
$script:adapterArguments = $true;
if ($context.arguments.Count -ne 1) { return }
$prefix = ([string]$word).Trim([char[]]@([char]39, [char]34));
foreach ($adapterName in (Get-DhcpAdapterNames | Sort-Object -Unique)) {
if ($adapterName.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) {
New-ArgumentCompletion $adapterName
}
}
return
}
if ($word -eq '?') { $word = '/?' }
foreach ($value in $context.values) {
if ($value.StartsWith([string]$word, [StringComparison]::OrdinalIgnoreCase)) {
[System.Management.Automation.CompletionResult]::new($value)
}
}
};
Register-ArgumentCompleter -Native -CommandName dotnet,dotnet.exe -ScriptBlock {
param($word, $command, $position)
$offset = $position - $command.Extent.StartOffset;
dotnet.exe complete --position $offset $command.ToString() 2>$null | ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_)
}
};
function Find-GitCompletionTools {
$git = Get-Command git.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1;
if (!$git) { return }
$location = [IO.DirectoryInfo]::new([IO.Path]::GetDirectoryName($git.Source));
for ($level = 0; $location -and $level -lt 3; ++$level) {
$root = $location.FullName;
$location = $location.Parent;
$bash = Join-Path $root 'usr/bin/bash.exe';
if (![IO.File]::Exists($bash)) { continue }
foreach ($architecture in 'mingw64', 'mingw32', 'clangarm64') {
$script = Join-Path $root ($architecture + '/share/git/completion/git-completion.bash');
if ([IO.File]::Exists($script)) { return @{ bash = $bash; script = $script } }
}
}
}
# Send words as data to Git for Windows. Backslash-quote escapes are for Windows PowerShell's native argv.
$gitCompletionRunner = @'
export GIT_ALLOW_PROTOCOL= GIT_TERMINAL_PROMPT=0
mapfile -t input
for i in ~${!input[@]}~; do input[i]=~${input[i]%$'\r'}~; done
source ~${input[0]}~ || exit
words=(~${input[@]:1}~)
cword=$(( ${#words[@]} - 1 ))
cur=${words[cword]}
prev=${words[cword-1]}
__git_main
if (( ${#COMPREPLY[@]} )); then printf '%s\n' ~${COMPREPLY[@]}~; fi
'@.Replace('~', ('\' + [char]34));
$OutputEncoding = [Console]::OutputEncoding;
Register-ArgumentCompleter -Native -CommandName git,git.exe -ScriptBlock {
param($word, $command, $position)
if (!$script:gitCompletionTools) { $script:gitCompletionTools = Find-GitCompletionTools }
if (!$script:gitCompletionTools) { return }
$arguments = @('git') + @(Get-CompletedArguments $command $position) + @([string]$word);
@($script:gitCompletionTools.script) + $arguments |
& $script:gitCompletionTools.bash --noprofile --norc -p -c $gitCompletionRunner 2>$null |
ForEach-Object {
$value = $_.TrimEnd();
if ($value) { New-ArgumentCompletion $value }
}
};
function Get-CompletionCommand($request) {
$prefix = $request.line.Substring(0, $request.caret).TrimEnd();
$ast = [System.Management.Automation.Language.Parser]::ParseInput($prefix, [ref]$null, [ref]$null);
$ast.FindAll({
param($node)
$node -is [System.Management.Automation.Language.CommandAst] -and
$node.Extent.EndOffset -eq $prefix.Length
}, $true) | Select-Object -Last 1;
}
function Test-NoCommandArguments($command) {
if (!$command) { return $false }
$name = $command.GetCommandName();
if (!$name) { return $false }
$info = Get-Command -Name ([WildcardPattern]::Escape($name)) -ErrorAction SilentlyContinue;
if ($info -is [System.Management.Automation.AliasInfo]) { $info = $info.ResolvedCommand }
return ($info -is [System.Management.Automation.FunctionInfo] -or
$info -is [System.Management.Automation.CmdletInfo]) -and $info.Parameters.Count -eq 0;
}
while ($null -ne ($line = [Console]::ReadLine())) {
try {
$request = ConvertFrom-Json -InputObject $line -ErrorAction Stop;
Set-Location -LiteralPath $request.directory -ErrorAction Stop;
$script:adapterArguments = $false;
$command = Get-CompletionCommand $request;
$context = Get-WindowsCommandContext $command $request.caret $true;
$result = TabExpansion2 -inputScript $request.line -cursorColumn $request.caret;
$candidates = $result.CompletionMatches;
if ($candidates.Count -and $candidates[0].ResultType -in 'ProviderItem','ProviderContainer' -and
($script:adapterArguments -or (Test-NoCommandArguments $command))) {
$candidates = $candidates | Where-Object { $_.ResultType -notin 'ProviderItem','ProviderContainer' };
}
$items = @($candidates | Select-Object -First 100 | ForEach-Object {
@{ label = $_.ListItemText; text = $_.CompletionText; directory = ($_.ResultType -eq 'ProviderContainer') }
});
$reply = @{ index = $result.ReplacementIndex; length = $result.ReplacementLength;
matches = $items; article = [string]$context.article };
[Console]::WriteLine((ConvertTo-Json -InputObject $reply -Compress -Depth 4));
} catch { [Console]::WriteLine('{}') }
}")PS";
job=CreateJobObjectW(nullptr,nullptr);
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if(!job || !SetInformationJobObject(job,JobObjectExtendedLimitInformation,&limits,sizeof(limits))) return false;
SIZE_T bytes{};
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
std::vector<unsigned char> storage(bytes);
auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes)) return false;
HANDLE inherited[]{childInput,childOutput};
STARTUPINFOEXW startup{};
startup.StartupInfo.cb=sizeof(startup);
startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES;
startup.StartupInfo.hStdInput=childInput;
startup.StartupInfo.hStdOutput=startup.StartupInfo.hStdError=childOutput;
startup.lpAttributeList=attributes;
PROCESS_INFORMATION child{};
const bool started=UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
inherited,sizeof(inherited),nullptr,nullptr) &&
CreateProcessW(shell.c_str(),command,nullptr,nullptr,TRUE,
CREATE_SUSPENDED|CREATE_NO_WINDOW|EXTENDED_STARTUPINFO_PRESENT,
nullptr,nullptr,&startup.StartupInfo,&child);
DeleteProcThreadAttributeList(attributes);
if(!started) return false;
process=child.hProcess;
const bool running=AssignProcessToJobObject(job,process) && ResumeThread(child.hThread)!=DWORD(-1);
if(!running) TerminateProcess(process,1);
CloseHandle(child.hThread);
return running;
}
void close()
{
for(const auto handle:{job,input,output,process})
if(handle) CloseHandle(handle);
job=input=output=process=nullptr;
pending.clear();
}
};
}
+20 -6
View File
@@ -2,6 +2,23 @@ constexpr std::array<WORD,2> defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MA
auto commandHistoryKeys=defaultHistoryKeys;
constexpr size_t commandHistoryLimit=1000;
std::wstring commandHistoryLabel(const std::wstring &command)
{
constexpr std::wstring_view prefix=L"start '";
if(!command.starts_with(prefix) || command.size()<=prefix.size() || command.back()!=L'\'')
return command;
const std::wstring_view literal(command.data()+prefix.size(),command.size()-prefix.size()-1);
std::wstring path;
for(size_t i=0;i<literal.size();++i)
{
const auto character=literal[i];
if(character==L'\'' || character==L'\u2018' || character==L'\u2019')
if(++i==literal.size() || literal[i]!=character) return command;
path+=character;
}
return fs::path(path).is_absolute()?path:command;
}
bool validHistoryKeys(const std::array<WORD,2> &keys)
{
if(keys[0]==keys[1]) return false;
@@ -11,7 +28,8 @@ bool validHistoryKeys(const std::array<WORD,2> &keys)
const bool letter=key>='A' && key<='Z';
const bool function=key>=VK_F1 && key<=VK_F12;
if(!letter && !function) return false;
if(modifiers==HOTKEYF_CONTROL) return (letter && key!='C' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y') || function;
if(modifiers==HOTKEYF_CONTROL)
return letter && key!='C' && key!='F' && key!='R' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y';
if(modifiers==HOTKEYF_ALT) return function && key!=VK_F1 && key!=VK_F2 && key!=VK_F4 && key!=VK_F10;
return false;
});
@@ -60,11 +78,7 @@ void loadCommandHistory()
void rememberCommand(const std::wstring &command)
{
SYSTEMTIME now{};
GetLocalTime(&now);
wchar_t date[24]{};
GetDateFormatEx(LOCALE_NAME_USER_DEFAULT,0,&now,L"dd.MM.yyyy",date,std::size(date),nullptr);
terminalHistory.push_back({date,command});
terminalHistory.push_back({ks::files::historyDate(),command});
if(terminalHistory.size()>commandHistoryLimit) terminalHistory.erase(terminalHistory.begin());
std::wstring data;
for(const auto &entry:terminalHistory)
+37 -78
View File
@@ -4,36 +4,6 @@ constexpr int historySearch=325;
constexpr COLORREF historySearchSurface=RGB(132,177,177);
constexpr int historySearchLabel=326;
HWND commandHistoryWindow{};
HHOOK historyMouseHook{};
LRESULT CALLBACK dismissHistoryOnOutsideClick(int code,WPARAM message,LPARAM data)
{
const auto dialog=commandHistoryWindow;
if(code==HC_ACTION && dialog && IsWindowVisible(dialog) &&
(message==WM_LBUTTONDOWN || message==WM_RBUTTONDOWN ||
message==WM_MBUTTONDOWN || message==WM_XBUTTONDOWN))
{
const auto point=reinterpret_cast<const MSLLHOOKSTRUCT*>(data)->pt;
const auto clicked=WindowFromPoint(point);
const auto owner=GetWindow(dialog,GW_OWNER);
if(clicked!=dialog && !IsChild(dialog,clicked))
{
POINT local=point;
RECT client{};
GetClientRect(owner,&client);
ScreenToClient(owner,&local);
const bool ownerClient=clicked==owner || IsChild(owner,clicked);
if(!ownerClient || PtInRect(&client,local))
{
const auto focusPanel=clicked==panels[0].list?panels[0].list:
clicked==panels[1].list?panels[1].list:panels[active].list;
if(PostMessageW(dialog,WM_CLOSE,reinterpret_cast<WPARAM>(ownerClient?focusPanel:nullptr),0)
&& ownerClient) return 1;
}
}
}
return CallNextHookEx(nullptr,code,message,data);
}
std::wstring historyLower(std::wstring value)
{
@@ -99,7 +69,7 @@ void populateCommandHistory(HWND dialog)
{
return std::all_of(words.begin(),words.end(),[&](const auto &word){return text.find(word)!=text.npos;});
};
if(containsAll(command+L" "+entry.date))
if(containsAll(command+L" "+historyLower(commandHistoryLabel(entry.command))+L" "+entry.date))
{
matches[0].push_back(index);
continue;
@@ -121,7 +91,7 @@ void populateCommandHistory(HWND dialog)
if(first || date!=lastDate) add(date,-1);
first=false;
lastDate=date;
const auto row=add(entry.command,index);
const auto row=add(commandHistoryLabel(entry.command),index);
if(row>=0 && (words.empty() || selected==LB_ERR)) selected=row;
}
}
@@ -136,9 +106,15 @@ LRESULT CALLBACK historySearchKeys(HWND search,UINT message,WPARAM key,LPARAM fl
if(message==WM_GETDLGCODE)
{
const auto code=DefSubclassProc(search,message,key,flags);
if(key==VK_RETURN || key==VK_TAB || key==VK_ESCAPE) return code&~DLGC_WANTALLKEYS;
if(key==VK_TAB || key==VK_ESCAPE) return code&~DLGC_WANTALLKEYS;
if(key==VK_RETURN) return code|DLGC_WANTMESSAGE;
return code|DLGC_WANTARROWS;
}
if(message==WM_KEYDOWN && key==VK_RETURN)
{
SendMessageW(GetParent(search),WM_COMMAND,IDOK,0);
return 0;
}
if(message==WM_KEYDOWN && (key==VK_UP || key==VK_DOWN))
{
const auto list=GetDlgItem(GetParent(search),historyList);
@@ -157,16 +133,17 @@ int historyRowInset(UINT dpi)
LRESULT CALLBACK historyListScroll(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==LB_GETTOPINDEX || message==WM_NCDESTROY)
return DefSubclassProc(list,message,wp,lp);
const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0);
const auto result=scrollList(list,message,wp,lp);
if(top!=SendMessageW(list,LB_GETTOPINDEX,0,0))
InvalidateRect(GetParent(list),nullptr,FALSE);
return result;
if(message==WM_GETDLGCODE && wp==VK_RETURN)
return DefSubclassProc(list,message,wp,lp)|DLGC_WANTMESSAGE;
if(message==WM_KEYDOWN && wp==VK_RETURN)
{
SendMessageW(GetParent(list),WM_COMMAND,IDOK,0);
return 0;
}
return DefSubclassProc(list,message,wp,lp);
}
void sizeCommandHistory(HWND dialog,HWND list,bool movingOwner=false)
void sizeCommandHistory(HWND dialog,HWND list)
{
const auto owner=GetWindow(dialog,GW_OWNER);
RECT ownerBounds{};
@@ -182,8 +159,9 @@ void sizeCommandHistory(HWND dialog,HWND list,bool movingOwner=false)
LONG longest{};
for(const auto &entry:terminalHistory)
{
const auto label=commandHistoryLabel(entry.command);
SIZE size{};
if(GetTextExtentPoint32W(dc,entry.command.c_str(),static_cast<int>(entry.command.size()),&size))
if(GetTextExtentPoint32W(dc,label.c_str(),static_cast<int>(label.size()),&size))
longest=std::max(longest,size.cx);
}
SelectObject(dc,previous);
@@ -196,7 +174,7 @@ void sizeCommandHistory(HWND dialog,HWND list,bool movingOwner=false)
const int gap=MulDiv(4,dpi,96);
const int listTop=top+2*textHeight+2*gap;
const LONG desired=std::max<LONG>(MulDiv(320,dpi,96),
longest+2*cellWidth+2*historyRowInset(dpi)+GetSystemMetricsForDpi(SM_CXVSCROLL,dpi))+2*inset;
longest+2*cellWidth+2*historyRowInset(dpi)+scrollBarWidth(list))+2*inset;
const auto target=std::min(desired,area.right-area.left);
const auto rows=std::max<LRESULT>(1,SendMessageW(list,LB_GETCOUNT,0,0));
RECT listWindow{},listClient{};
@@ -207,14 +185,6 @@ void sizeCommandHistory(HWND dialog,HWND list,bool movingOwner=false)
area.bottom-area.top);
const auto left=std::clamp((ownerBounds.left+ownerBounds.right-target)/2,area.left,area.right-target);
const auto y=std::clamp((ownerBounds.top+ownerBounds.bottom-height)/2,area.top,area.bottom-height);
RECT current{};
if(movingOwner && GetWindowRect(dialog,&current) &&
current.right-current.left==target && current.bottom-current.top==height)
{
if(current.left!=left || current.top!=y)
SetWindowPos(dialog,nullptr,left,y,0,0,SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
return;
}
SetWindowPos(dialog,nullptr,left,y,target,height,SWP_NOZORDER|SWP_NOACTIVATE);
const auto place=[&](HWND control,int rowTop,int rowHeight)
{
@@ -223,26 +193,30 @@ void sizeCommandHistory(HWND dialog,HWND list,bool movingOwner=false)
};
place(GetDlgItem(dialog,historySearchLabel),top,textHeight);
place(GetDlgItem(dialog,historySearch),top+textHeight+gap,textHeight);
SetWindowPos(list,nullptr,inset,listTop,std::max(1L,target-2*inset-5),
SetWindowPos(list,nullptr,inset,listTop,std::max(1L,target-2*inset-scrollBarWidth(list)),
std::max(1L,height-listTop-inset),SWP_NOZORDER|SWP_NOACTIVATE);
GetClientRect(list,&listClient);
if(rows*textHeight<=listClient.bottom) SendMessageW(list,LB_SETTOPINDEX,0,0);
InvalidateRect(dialog,nullptr,FALSE);
FilesModalDialog::refreshLayout(dialog);
}
void layoutOpenCommandHistory(bool movingOwner=false)
void layoutOpenCommandHistory()
{
if(commandHistoryWindow)
sizeCommandHistory(commandHistoryWindow,GetDlgItem(commandHistoryWindow,historyList),movingOwner);
sizeCommandHistory(commandHistoryWindow,GetDlgItem(commandHistoryWindow,historyList));
}
INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
commandHistoryWindow=dialog;
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareCopyDialog(dialog);
const auto list=GetDlgItem(dialog,historyList);
SetWindowSubclass(list,historyListScroll,1,0);
installScrollBar(list,dialog);
SendMessageW(list,WM_SETFONT,reinterpret_cast<WPARAM>(mono),TRUE);
SendMessageW(list,LB_SETITEMHEIGHT,0,std::max(1,textHeight));
const auto search=GetDlgItem(dialog,historySearch);
@@ -260,11 +234,7 @@ INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM
return TRUE;
}
if(message==WM_NCDESTROY && commandHistoryWindow==dialog)
{
if(historyMouseHook) UnhookWindowsHookEx(historyMouseHook);
historyMouseHook=nullptr;
commandHistoryWindow=nullptr;
}
if(message==WM_CTLCOLORLISTBOX || message==WM_CTLCOLOREDIT)
{
const auto dc=reinterpret_cast<HDC>(wp);
@@ -320,14 +290,7 @@ INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
const auto owner=GetWindow(dialog,GW_OWNER);
const auto focusPanel=message==WM_CLOSE?reinterpret_cast<HWND>(wp):panels[active].list;
DestroyWindow(dialog);
if(focusPanel && IsWindow(owner) && !IsIconic(owner))
{
SetActiveWindow(owner);
SetFocus(focusPanel);
}
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message==WM_COMMAND && (LOWORD(wp)==IDOK || (LOWORD(wp)==historyList && HIWORD(wp)==LBN_DBLCLK)))
@@ -336,10 +299,9 @@ INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM
const auto index=SendDlgItemMessageW(dialog,historyList,LB_GETITEMDATA,row,0);
if(index>=0 && static_cast<size_t>(index)<terminalHistory.size())
{
const auto owner=GetWindow(dialog,GW_OWNER);
DestroyWindow(dialog);
SetActiveWindow(owner);
recallCommand(static_cast<size_t>(index));
auto &choice=*reinterpret_cast<size_t *>(GetWindowLongPtrW(dialog,DWLP_USER));
choice=static_cast<size_t>(index);
FilesModalDialog::finish(dialog,IDOK);
}
return TRUE;
}
@@ -354,12 +316,9 @@ void refreshCommandHistory()
void showCommandHistory(HWND owner)
{
if(!commandHistoryWindow)
commandHistoryWindow=CreateDialogParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(111),owner,commandHistoryDialog,0);
if(!commandHistoryWindow) return;
if(!historyMouseHook)
historyMouseHook=SetWindowsHookExW(WH_MOUSE_LL,dismissHistoryOnOutsideClick,GetModuleHandleW(nullptr),0);
ShowWindow(commandHistoryWindow,SW_SHOW);
SetActiveWindow(commandHistoryWindow);
SetFocus(GetDlgItem(commandHistoryWindow,historySearch));
if(commandHistoryWindow) return;
size_t choice{};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(111),owner,commandHistoryDialog,
reinterpret_cast<LPARAM>(&choice))==IDOK)
recallCommand(choice);
}
+868
View File
@@ -0,0 +1,868 @@
constexpr uint64_t compareFileLimit=2*ks::files::TextDocument::pageBytes;
enum ComparisonColor { CompareBackground, CompareText, CompareInsert, CompareDelete, CompareReplace,
CompareInline, ComparePadding, CompareDivider, CompareChangedText, CompareColorCount };
constexpr const wchar_t *comparisonColorNames[]{L"Background",L"Text",L"Insertion",L"Deletion",L"Replacement",
L"Changed fragment",L"Alignment padding",L"Divider",L"Text on changed lines"};
constexpr wchar_t comparisonAppearanceKey[]=L"ComparisonAppearance";
constexpr wchar_t comparisonShortcutKey[]=L"ComparisonShortcut";
constexpr WORD defaultComparisonShortcut=MAKEWORD(VK_F11,HOTKEYF_SHIFT);
WORD comparisonShortcut=defaultComparisonShortcut;
constexpr int comparisonSplitScale=10000;
bool validComparisonShortcut(WORD shortcut)
{
const auto key=LOBYTE(shortcut),modifiers=HIBYTE(shortcut);
return key>=VK_F1 && key<=VK_F12 &&
(modifiers==(HOTKEYF_CONTROL|HOTKEYF_SHIFT) ||
(modifiers==HOTKEYF_SHIFT && key!=VK_F4 && key!=VK_F8));
}
void loadComparisonShortcut()
{
const auto shortcut=static_cast<WORD>(preference(comparisonShortcutKey,defaultComparisonShortcut));
comparisonShortcut=validComparisonShortcut(shortcut)?shortcut:defaultComparisonShortcut;
}
std::wstring comparisonShortcutLabel()
{
return std::wstring(HIBYTE(comparisonShortcut)&HOTKEYF_CONTROL?L"Ctrl+Shift+F":L"Shift+F")+
std::to_wstring(LOBYTE(comparisonShortcut)-VK_F1+1);
}
struct ComparisonAppearance
{
LOGFONTW font=defaultFilesFont();
int points=defaultFontPoints;
std::array<COLORREF,CompareColorCount> palette{RGB(255,255,255),RGB(24,24,24),RGB(177,226,184),
RGB(249,194,194),RGB(251,224,154),RGB(245,170,90),RGB(230,230,230),RGB(160,160,160),RGB(24,24,24)};
bool operator==(const ComparisonAppearance &other) const
{
return points==other.points && palette==other.palette && !memcmp(&font,&other.font,sizeof(font));
}
};
ComparisonAppearance readComparisonAppearance()
{
ComparisonAppearance appearance;
DWORD bytes=sizeof(appearance);
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,comparisonAppearanceKey,RRF_RT_REG_BINARY,nullptr,
&appearance,&bytes)!=ERROR_SUCCESS || bytes!=sizeof(appearance) ||
appearance.points<80 || appearance.points>240 ||
std::any_of(appearance.palette.begin(),appearance.palette.end(),[](auto color){return color>0xffffff;}))
return {};
appearance.font.lfFaceName[LF_FACESIZE-1]=0;
return appearance;
}
bool saveComparisonAppearance(const ComparisonAppearance &appearance)
{
return RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,comparisonAppearanceKey,REG_BINARY,
&appearance,sizeof(appearance))==ERROR_SUCCESS;
}
struct CompareFile
{
fs::path path;
std::wstring label;
std::optional<FilesPeer> peer;
std::optional<FtpProfile> ftp;
};
struct CompareRow
{
int left=-1,right=-1;
bool changed{};
size_t commonStart{},commonEnd{};
bool whitespaceOnly{};
bool hasChange(bool showWhitespace) const {return changed && (showWhitespace || !whitespaceOnly);}
};
struct FileComparison
{
static constexpr std::array controls{400,401,402,403,407};
CompareFile files[2];
std::vector<std::wstring> lines[2];
std::vector<CompareRow> rows;
std::vector<int> changes,allChanges;
bool showWhitespace{};
RECT initialClient{};
std::array<RECT,controls.size()> initialControls{};
SIZE minimumWindow{};
ComparisonAppearance appearance;
HFONT font{};
HBRUSH background{};
int characterWidth=1;
int split=comparisonSplitScale/2;
std::optional<int> splitDragOffset;
int zoom{},wheelRemainder{};
~FileComparison()
{
if(font) DeleteObject(font);
if(background) DeleteObject(background);
}
};
std::map<HWND,std::unique_ptr<FileComparison>> comparisonWindows;
LONG comparisonSplitX(const FileComparison &comparison,LONG width)
{
return MulDiv(width,comparison.split,comparisonSplitScale);
}
void layoutComparisonHeaders(HWND dialog,const FileComparison &comparison)
{
const auto list=GetDlgItem(dialog,402);
RECT bounds{};
GetClientRect(list,&bounds);
MapWindowPoints(list,dialog,reinterpret_cast<POINT*>(&bounds),2);
const auto middle=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
const auto inset=comparison.initialControls[0].left;
for(int side=0;side<2;++side)
{
const auto &initial=comparison.initialControls[side];
const auto left=(side?middle:bounds.left)+inset;
const auto right=(side?bounds.right:middle)-inset;
SetWindowPos(GetDlgItem(dialog,400+side),nullptr,left,initial.top,std::max(0L,right-left),
initial.bottom-initial.top,SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
}
}
void applyComparisonFont(HWND dialog,FileComparison &comparison)
{
auto font=comparison.appearance.font;
const auto dpi=GetDpiForWindow(dialog);
const auto points=std::clamp(comparison.appearance.points+comparison.zoom,80,240);
comparison.zoom=points-comparison.appearance.points;
font.lfHeight=-MulDiv(points,dpi,720);
font.lfWidth=0;
if(const auto next=CreateFontIndirectW(&font))
{
if(comparison.font) DeleteObject(comparison.font);
comparison.font=next;
}
const auto list=GetDlgItem(dialog,402);
if(const auto dc=GetDC(list))
{
const auto previous=SelectObject(dc,comparison.font?comparison.font:mono);
TEXTMETRICW metrics{};
if(GetTextMetricsW(dc,&metrics))
{
comparison.characterWidth=std::max(1L,metrics.tmAveCharWidth);
const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0);
SendMessageW(list,LB_SETITEMHEIGHT,0,metrics.tmHeight+MulDiv(6,dpi,96));
SendMessageW(list,LB_SETTOPINDEX,top,0);
}
SelectObject(dc,previous);
ReleaseDC(list,dc);
}
InvalidateRect(list,nullptr,TRUE);
}
void applyComparisonAppearance(HWND dialog,FileComparison &comparison)
{
comparison.appearance=readComparisonAppearance();
if(const auto next=CreateSolidBrush(comparison.appearance.palette[CompareBackground]))
{
if(comparison.background) DeleteObject(comparison.background);
comparison.background=next;
}
applyComparisonFont(dialog,comparison);
}
bool zoomComparison(HWND dialog,FileComparison &comparison,WPARAM wheel)
{
if(!(GET_KEYSTATE_WPARAM(wheel)&MK_CONTROL)) return false;
comparison.wheelRemainder+=GET_WHEEL_DELTA_WPARAM(wheel);
const auto steps=comparison.wheelRemainder/WHEEL_DELTA;
comparison.wheelRemainder%=WHEEL_DELTA;
const auto base=comparison.appearance.points;
const auto zoom=std::clamp(base+comparison.zoom+10*steps,80,240)-base;
if(zoom!=comparison.zoom)
{
comparison.zoom=zoom;
applyComparisonFont(dialog,comparison);
layoutComparisonHeaders(dialog,comparison);
}
return true;
}
bool handleComparisonMessage(MSG &message)
{
if(!message.hwnd) return false;
const auto window=GetAncestor(message.hwnd,GA_ROOT);
if(!comparisonWindows.contains(window)) return false;
if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)
{
SendMessageW(window,WM_CLOSE,0,0);
return true;
}
if(!IsDialogMessageW(window,&message))
{
TranslateMessage(&message);
DispatchMessageW(&message);
}
return true;
}
std::vector<std::wstring> readComparisonLines(const CompareFile &input,const std::atomic_bool &canceled)
{
struct TemporaryDirectory
{
fs::path path;
~TemporaryDirectory()
{
if(path.empty()) return;
std::error_code ignored;
fs::remove_all(path,ignored);
}
} temporary;
auto path=input.path;
if(input.ftp || input.peer)
{
const auto directory=fs::temp_directory_path()/(L"ks-files-compare-"+ks::wide(ks::lan::randomHex(16)));
requireFileOperation(fs::create_directory(directory),ERROR_ALREADY_EXISTS);
temporary.path=directory;
path=directory/L"file";
CopyHost source(input.peer?&*input.peer:nullptr,input.ftp);
const auto info=source.stat(input.path,canceled);
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
ERROR_NOT_SUPPORTED);
requireFileOperation(info->size<=compareFileLimit,ERROR_FILE_TOO_LARGE);
FilesConnection local;
const auto progress=[&](uint64_t,uint64_t){return !canceled;};
if(source.ftp) downloadFtpFile(*source.ftp,local,input.path,path,*info,false,progress);
else ks::lan::streamFile(*source.files,local,input.peer->id,input.path,path,info->size,
info->modified,false,false,progress);
}
ks::files::TextDocument document(path,false);
requireFileOperation(document.size()<=compareFileLimit,ERROR_FILE_TOO_LARGE);
std::string text;
for(uint64_t page=0;page<document.pages() && !canceled;++page) text+=document.readPage(page);
requireFileOperation(!canceled,ERROR_CANCELLED);
if(std::any_of(text.begin(),text.end(),[](unsigned char ch){
return ch<32 && ch!='\t' && ch!='\r' && ch!='\n' && ch!='\f';
})) throw std::runtime_error("Select two text files.");
if(text.empty()) return {};
const auto bytes=static_cast<int>(text.size());
const auto count=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,nullptr,0);
if(!count) throw std::runtime_error("Compare files supports UTF-8 and UTF-16 text.");
std::wstring decoded(count,L'\0');
checkFileOperation(MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,decoded.data(),count)!=0);
std::vector<std::wstring> lines;
size_t start=0;
while(true)
{
requireFileOperation(!canceled,ERROR_CANCELLED);
if(lines.size()==100'000) throw std::runtime_error("Each file can contain up to 100,000 lines.");
const auto end=decoded.find_first_of(L"\r\n",start);
lines.push_back(decoded.substr(start,end==decoded.npos?end:end-start));
if(end==decoded.npos) break;
start=end+((decoded[end]==L'\r' && end+1<decoded.size() && decoded[end+1]==L'\n')?2:1);
}
return lines;
}
std::wstring_view comparisonContent(std::wstring_view line)
{
const auto start=line.find_first_not_of(L" \t");
if(start==line.npos) return {};
return line.substr(start,line.find_last_not_of(L" \t")-start+1);
}
void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
{
const auto &left=result.lines[0],&right=result.lines[1];
std::map<std::wstring_view,unsigned> ids;
std::map<unsigned,unsigned> blankIds;
unsigned nextId=1;
const auto encode=[&](const auto &lines)
{
std::vector<unsigned> values;
values.reserve(lines.size());
unsigned previousContent=0;
for(const auto &line:lines)
{
requireFileOperation(!canceled,ERROR_CANCELLED);
const auto content=comparisonContent(line);
// Blank lines can anchor alignment alongside the preceding content.
if(content.empty())
{
const auto [entry,inserted]=blankIds.try_emplace(previousContent,nextId);
nextId+=inserted;
values.push_back(entry->second);
}
else
{
const auto [entry,inserted]=ids.try_emplace(content,nextId);
nextId+=inserted;
previousContent=entry->second;
values.push_back(previousContent);
}
}
return values;
};
const auto a=encode(left),b=encode(right);
size_t prefix=0, suffix=0;
while(prefix<a.size() && prefix<b.size() && a[prefix]==b[prefix]) ++prefix;
while(suffix<a.size()-prefix && suffix<b.size()-prefix &&
a[a.size()-1-suffix]==b[b.size()-1-suffix]) ++suffix;
const auto n=static_cast<int>(a.size()-prefix-suffix),m=static_cast<int>(b.size()-prefix-suffix);
const auto append=[&](int x,int y)
{
CompareRow row{x,y,x<0 || y<0 || left[x]!=right[y]};
if(row.changed && (result.rows.empty() || !result.rows.back().changed))
result.allChanges.push_back(static_cast<int>(result.rows.size()));
if(row.changed && x>=0 && y>=0)
{
const auto &l=left[x],&r=right[y];
row.whitespaceOnly=comparisonContent(l)==comparisonContent(r);
const size_t length=std::min(l.size(),r.size());
while(row.commonStart<length && l[row.commonStart]==r[row.commonStart]) ++row.commonStart;
if(row.commonStart && l[row.commonStart-1]>=0xd800 && l[row.commonStart-1]<=0xdbff)
--row.commonStart;
while(row.commonEnd<length-row.commonStart &&
l[l.size()-1-row.commonEnd]==r[r.size()-1-row.commonEnd]) ++row.commonEnd;
if(row.commonEnd && l[l.size()-row.commonEnd]>=0xdc00 && l[l.size()-row.commonEnd]<=0xdfff)
--row.commonEnd;
}
if(row.hasChange(false) && (result.rows.empty() || !result.rows.back().hasChange(false)))
result.changes.push_back(static_cast<int>(result.rows.size()));
result.rows.push_back(row);
};
const auto change=[&](size_t x,size_t y,size_t countLeft,size_t countRight)
{
// Prefer pairing structurally similar lines, leaving unmatched lines on their own side.
const auto score=[](std::wstring_view l,std::wstring_view r)
{
if(l.empty() || r.empty()) return l.empty() && r.empty()?1u:0u;
const auto cap=std::min({l.size(),r.size(),size_t{64}});
size_t start=0,end=0;
while(start<cap && l[start]==r[start]) ++start;
while(end<cap-start && l[l.size()-1-end]==r[r.size()-1-end]) ++end;
return 1u+static_cast<unsigned>(4*(start+end));
};
if(!countLeft || !countRight || countLeft>160'000/countRight)
{
for(size_t i=0;i<std::max(countLeft,countRight);++i)
append(i<countLeft?static_cast<int>(x+i):-1,i<countRight?static_cast<int>(y+i):-1);
return;
}
const auto stride=countRight+1;
std::vector<std::wstring_view> l,r;
for(size_t i=0;i<countLeft;++i) l.push_back(comparisonContent(left[x+i]));
for(size_t j=0;j<countRight;++j) r.push_back(comparisonContent(right[y+j]));
std::vector<unsigned> best((countLeft+1)*stride);
for(size_t i=countLeft;i-->0;)
for(size_t j=countRight;j-->0;)
best[i*stride+j]=std::max({best[(i+1)*stride+j],best[i*stride+j+1],
best[(i+1)*stride+j+1]+score(l[i],r[j])});
size_t i=0,j=0;
while(i<countLeft && j<countRight)
{
const auto pairScore=score(l[i],r[j]);
if(pairScore && best[i*stride+j]==best[(i+1)*stride+j+1]+pairScore)
{
append(static_cast<int>(x+i),static_cast<int>(y+j));
++i;
++j;
}
else if(best[(i+1)*stride+j]>=best[i*stride+j+1]) append(static_cast<int>(x+i++),-1);
else append(-1,static_cast<int>(y+j++));
}
while(i<countLeft) append(static_cast<int>(x+i++),-1);
while(j<countRight) append(-1,static_cast<int>(y+j++));
};
for(size_t i=0;i<prefix;++i) append(static_cast<int>(i),static_cast<int>(i));
if(n && m)
{
// Myers alignment. Each pass records the farthest left index per edit diagonal.
std::vector<std::vector<int>> trace;
const auto previousDiagonal=[](const std::vector<int> &prior,int d,int k)
{
if(k==-d || (k!=d && prior[(d+k-2)/2]<prior[(d+k)/2])) return k+1;
return k-1;
};
bool complete=false;
for(int d=0;!complete;++d)
{
requireFileOperation(!canceled,ERROR_CANCELLED);
if(d>2'500) throw std::runtime_error("Too many differing lines to align in this comparison.");
std::vector<int> level;
level.reserve(d+1);
for(int k=-d;k<=d;k+=2)
{
int x=0;
if(d)
{
const auto &prior=trace.back();
const auto previous=previousDiagonal(prior,d,k);
x=prior[(d-1+previous)/2]+(previous<k);
}
int y=x-k;
while(x<n && y<m && a[prefix+x]==b[prefix+y]) {++x;++y;}
level.push_back(x);
if(x>=n && y>=m) {complete=true;break;}
}
trace.push_back(std::move(level));
}
std::vector<std::pair<int,int>> matches;
int x=n,y=m;
for(int d=static_cast<int>(trace.size())-1;d>0;--d)
{
const auto &prior=trace[d-1];
const auto previous=previousDiagonal(prior,d,x-y);
const int startX=prior[(d-1+previous)/2],startY=startX-previous;
while(x>startX && y>startY) {--x;--y;matches.emplace_back(x,y);}
x=startX;
y=startY;
}
while(x>0 && y>0) {--x;--y;matches.emplace_back(x,y);}
int fromLeft=0,fromRight=0;
for(auto it=matches.rbegin();it!=matches.rend();++it)
{
const auto [leftLine,rightLine]=*it;
change(prefix+fromLeft,prefix+fromRight,leftLine-fromLeft,rightLine-fromRight);
append(static_cast<int>(prefix+leftLine),static_cast<int>(prefix+rightLine));
fromLeft=leftLine+1;
fromRight=rightLine+1;
}
change(prefix+fromLeft,prefix+fromRight,n-fromLeft,m-fromRight);
}
else change(prefix,prefix,n,m);
for(size_t i=0;i<suffix;++i)
append(static_cast<int>(a.size()-suffix+i),static_cast<int>(b.size()-suffix+i));
}
void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &item)
{
const auto dc=item.hDC;
const auto bounds=item.rcItem;
const auto fill=[&](const RECT &area,COLORREF color)
{
SetDCBrushColor(dc,color);
FillRect(dc,&area,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
};
const auto &palette=comparison.appearance.palette;
const auto cell=comparison.characterWidth;
fill(bounds,palette[CompareBackground]);
if(item.itemID>=comparison.rows.size()) return;
const auto &row=comparison.rows[item.itemID];
const bool changed=row.hasChange(comparison.showWhitespace);
const LONG center=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
const LONG gutter=std::max(4,cell);
const RECT link{center-gutter,bounds.top,center+gutter,bounds.bottom};
const auto highlight=palette[row.left<0?CompareInsert:row.right<0?CompareDelete:CompareReplace];
if(changed) fill(link,highlight);
else
{
const RECT divider{center,bounds.top,center+1,bounds.bottom};
fill(divider,palette[CompareDivider]);
}
if(changed)
{
const LONG middle=(bounds.top+bounds.bottom)/2;
const LONG start=row.left<0?bounds.top:middle,end=row.right<0?bounds.top:middle;
SetDCPenColor(dc,palette[CompareChangedText]);
const auto pen=SelectObject(dc,GetStockObject(DC_PEN));
MoveToEx(dc,link.left,start,nullptr);
LineTo(dc,link.right,end);
SelectObject(dc,pen);
}
SelectObject(dc,comparison.font?comparison.font:mono);
SetBkMode(dc,TRANSPARENT);
const auto ink=palette[changed?CompareChangedText:CompareText];
SetTextColor(dc,ink);
const auto drawSide=[&](int side,int number,RECT area)
{
if(number<0)
{
fill(area,palette[ComparePadding]);
return;
}
if(changed) fill(area,highlight);
const auto numberText=std::to_wstring(number+1);
RECT numberArea=area;
numberArea.right=std::min(area.right,area.left+7*cell);
DrawTextW(dc,numberText.c_str(),-1,&numberArea,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX);
area.left=std::min(area.right,numberArea.right+cell);
const auto &line=comparison.lines[side][number];
const auto paneWidth=area.right-area.left;
if(paneWidth<=0) return;
const auto limit=static_cast<size_t>(paneWidth/cell+2)*4;
auto visible=std::wstring_view(line).substr(0,limit);
const bool clipped=visible.size()<line.size();
if(clipped && visible.back()>=0xd800 && visible.back()<=0xdbff)
visible.remove_suffix(1);
if(changed && row.left>=0 && row.right>=0)
{
const auto width=[&](size_t chars)->LONG
{
if(chars>visible.size()) return paneWidth;
RECT measured{};
if(chars) DrawTextW(dc,visible.data(),static_cast<int>(chars),&measured,
DT_CALCRECT|DT_SINGLELINE|DT_EXPANDTABS|DT_NOPREFIX);
return std::min(paneWidth,measured.right);
};
const auto start=std::min(area.right,area.left+width(row.commonStart));
const auto end=std::min(area.right,area.left+width(line.size()-row.commonEnd));
const RECT changed{start,area.top,std::min(area.right,std::max(start+2,end)),area.bottom};
fill(changed,palette[CompareInline]);
}
constexpr UINT flags=DT_SINGLELINE|DT_VCENTER|DT_EXPANDTABS|DT_NOPREFIX|DT_END_ELLIPSIS;
if(clipped)
{
auto text=std::wstring(visible)+L"…";
DrawTextW(dc,text.c_str(),static_cast<int>(text.size()),&area,flags);
}
else if(!visible.empty()) DrawTextW(dc,visible.data(),static_cast<int>(visible.size()),&area,flags);
};
drawSide(0,row.left,{bounds.left,bounds.top,link.left,bounds.bottom});
drawSide(1,row.right,{link.right,bounds.top,bounds.right,bounds.bottom});
if(item.itemState&ODS_SELECTED)
{
SetDCBrushColor(dc,ink);
FrameRect(dc,&bounds,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
}
}
LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_KEYDOWN && (wp==VK_F7 || wp==VK_F8))
{
SendMessageW(GetParent(control),WM_COMMAND,wp==VK_F7?404:405,0);
return 0;
}
if(GetDlgCtrlID(control)!=402) return DefSubclassProc(control,message,wp,lp);
const auto dialog=GetParent(control);
auto *comparison=reinterpret_cast<FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!comparison) return DefSubclassProc(control,message,wp,lp);
if(message==WM_MOUSEWHEEL && zoomComparison(dialog,*comparison,wp)) return 0;
if(message==WM_SETCURSOR || message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK)
{
RECT client{};
GetClientRect(control,&client);
const auto middle=comparisonSplitX(*comparison,client.right);
POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
if(message==WM_SETCURSOR)
{
if(LOWORD(lp)!=HTCLIENT) return DefSubclassProc(control,message,wp,lp);
GetCursorPos(&point);
ScreenToClient(control,&point);
}
const auto grip=MulDiv(5,GetDpiForWindow(control),96);
if(comparison->splitDragOffset || std::abs(point.x-middle)<=grip)
{
SetCursor(LoadCursorW(nullptr,IDC_SIZEWE));
if(message!=WM_SETCURSOR)
{
comparison->splitDragOffset=point.x-middle;
SetCapture(control);
if(GetCapture()!=control) comparison->splitDragOffset.reset();
}
return TRUE;
}
}
if(comparison->splitDragOffset && (message==WM_MOUSEMOVE || message==WM_LBUTTONUP))
{
RECT client{};
GetClientRect(control,&client);
if(client.right>0)
{
constexpr int minimumShare=1500;
const auto position=GET_X_LPARAM(lp)-*comparison->splitDragOffset;
const auto split=std::clamp(MulDiv(position,comparisonSplitScale,client.right),
minimumShare,comparisonSplitScale-minimumShare);
if(split!=comparison->split)
{
comparison->split=split;
layoutComparisonHeaders(dialog,*comparison);
InvalidateRect(control,nullptr,FALSE);
}
}
if(message==WM_LBUTTONUP) ReleaseCapture();
return 0;
}
if(message==WM_CAPTURECHANGED) comparison->splitDragOffset.reset();
const auto result=DefSubclassProc(control,message,wp,lp);
if(message==WM_PAINT)
{
RECT client{},last{};
GetClientRect(control,&client);
const auto count=SendMessageW(control,LB_GETCOUNT,0,0);
if(count>0 && SendMessageW(control,LB_GETITEMRECT,count-1,reinterpret_cast<LPARAM>(&last))==LB_ERR)
return result;
const auto middle=comparisonSplitX(*comparison,client.right);
const RECT blank{client.left,std::max(client.top,last.bottom),client.right,client.bottom};
if(blank.top<blank.bottom)
{
const auto dc=GetDC(control);
if(dc)
{
// The list box repaints its rows but can leave earlier divider marks below them.
FillRect(dc,&blank,comparison->background?comparison->background:
static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
const RECT divider{middle,blank.top,middle+1,blank.bottom};
SetDCBrushColor(dc,comparison->appearance.palette[CompareDivider]);
FillRect(dc,&divider,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
ReleaseDC(control,dc);
}
}
}
return result;
}
void layoutComparison(HWND dialog)
{
const auto *comparison=reinterpret_cast<const FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!comparison || comparison->initialClient.right<=0) return;
RECT client{};
GetClientRect(dialog,&client);
for(size_t i=0;i<FileComparison::controls.size();++i)
{
const auto id=FileComparison::controls[i];
if(id==400 || id==401) continue;
auto bounds=comparison->initialControls[i];
if(id==402) bounds={0,bounds.top,client.right,client.bottom};
SetWindowPos(GetDlgItem(dialog,id),nullptr,bounds.left,bounds.top,
bounds.right-bounds.left,std::max(0L,bounds.bottom-bounds.top),
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
}
layoutComparisonHeaders(dialog,*comparison);
InvalidateRect(dialog,nullptr,FALSE);
}
void updateComparisonSummary(HWND dialog,const FileComparison &comparison)
{
const auto blocks=(comparison.showWhitespace?comparison.allChanges:comparison.changes).size();
const auto summary=blocks==0?L"Text is identical":blocks==1?L"1 change block":
std::to_wstring(blocks)+L" change blocks";
SetDlgItemTextW(dialog,403,summary.c_str());
const auto toolbar=GetDlgItem(dialog,407);
for(const auto id:{404,405}) SendMessageW(toolbar,TB_ENABLEBUTTON,id,MAKELONG(blocks!=0,0));
}
void initializeComparisonToolbar(HWND toolbar)
{
SendMessageW(toolbar,TB_BUTTONSTRUCTSIZE,sizeof(TBBUTTON),0);
SendMessageW(toolbar,TB_SETEXTENDEDSTYLE,0,TBSTYLE_EX_MIXEDBUTTONS);
SendMessageW(toolbar,TB_SETMAXTEXTROWS,1,0);
const auto first=SendMessageW(toolbar,TB_LOADIMAGES,IDB_HIST_SMALL_COLOR,reinterpret_cast<LPARAM>(HINST_COMMCTRL));
const auto icon=[&](int index){return first<0?I_IMAGENONE:static_cast<int>(first)+index;};
constexpr BYTE text=BTNS_AUTOSIZE|BTNS_SHOWTEXT;
const auto separator=MulDiv(8,GetDpiForWindow(toolbar),96);
const TBBUTTON buttons[]{
{icon(HIST_BACK),404,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Previous")},
{icon(HIST_FORWARD),405,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Next")},
{separator,0,0,BTNS_SEP,{},0,0},
{I_IMAGENONE,406,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast<INT_PTR>(L"Show whitespace changes")}
};
SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast<LPARAM>(buttons));
}
INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
auto *comparison=reinterpret_cast<FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
const auto list=GetDlgItem(dialog,402);
const auto toolbar=GetDlgItem(dialog,407);
if(message==WM_INITDIALOG)
{
comparison=reinterpret_cast<FileComparison*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
GetClientRect(dialog,&comparison->initialClient);
for(size_t i=0;i<FileComparison::controls.size();++i)
comparison->initialControls[i]=dialogControlBounds(dialog,FileComparison::controls[i]);
RECT window{};
GetWindowRect(dialog,&window);
comparison->minimumWindow={MulDiv(window.right-window.left,3,4),(window.bottom-window.top)/2};
const auto resource=MAKEINTRESOURCEW(IDI_FILES_COMPARE);
const auto dpi=GetDpiForWindow(dialog);
const auto small=LoadImageW(GetModuleHandleW(nullptr),resource,IMAGE_ICON,
GetSystemMetricsForDpi(SM_CXSMICON,dpi),GetSystemMetricsForDpi(SM_CYSMICON,dpi),LR_SHARED);
const auto large=LoadIconW(GetModuleHandleW(nullptr),resource);
SendMessageW(dialog,WM_SETICON,ICON_SMALL,reinterpret_cast<LPARAM>(small));
SendMessageW(dialog,WM_SETICON,ICON_BIG,reinterpret_cast<LPARAM>(large));
ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,L"HrynCo.KSwitcher.Files.Compare");
for(int side=0;side<2;++side) SetDlgItemTextW(dialog,400+side,comparison->files[side].label.c_str());
initializeComparisonToolbar(toolbar);
updateComparisonSummary(dialog,*comparison);
SetWindowSubclass(list,comparisonKeys,1,0);
SetWindowSubclass(toolbar,comparisonKeys,1,0);
applyComparisonAppearance(dialog,*comparison);
SendMessageW(list,LB_SETCOUNT,comparison->rows.size(),0);
layoutComparisonHeaders(dialog,*comparison);
if(!comparison->changes.empty()) SendMessageW(list,LB_SETCURSEL,comparison->changes.front(),0);
return TRUE;
}
if(message==filesPreferencesChanged && comparison)
{
applyComparisonAppearance(dialog,*comparison);
layoutComparisonHeaders(dialog,*comparison);
return TRUE;
}
if(message==WM_CLOSE)
{
DestroyWindow(dialog);
return TRUE;
}
if(message==WM_MOUSEWHEEL && comparison && zoomComparison(dialog,*comparison,wp)) return TRUE;
if(message==WM_NCDESTROY)
{
ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,nullptr);
comparisonWindows.erase(dialog);
return FALSE;
}
if(message==WM_GETMINMAXINFO && comparison && comparison->minimumWindow.cx)
{
auto &size=reinterpret_cast<MINMAXINFO*>(lp)->ptMinTrackSize;
size.x=comparison->minimumWindow.cx;
size.y=comparison->minimumWindow.cy;
return TRUE;
}
if(message==WM_SIZE && wp!=SIZE_MINIMIZED)
{
layoutComparison(dialog);
return TRUE;
}
if(message==WM_DRAWITEM && wp==402 && comparison)
{
drawComparisonRow(*comparison,*reinterpret_cast<const DRAWITEMSTRUCT*>(lp));
return TRUE;
}
if(message==WM_CTLCOLORLISTBOX)
return reinterpret_cast<INT_PTR>(comparison && comparison->background?comparison->background:
GetStockObject(WHITE_BRUSH));
if(message==WM_COMMAND && comparison)
{
const auto id=LOWORD(wp);
if(id==IDCANCEL) {DestroyWindow(dialog);return TRUE;}
if(id==406 && HIWORD(wp)==BN_CLICKED)
{
comparison->showWhitespace=SendMessageW(toolbar,TB_ISBUTTONCHECKED,id,0)!=0;
updateComparisonSummary(dialog,*comparison);
InvalidateRect(list,nullptr,FALSE);
return TRUE;
}
const auto &changes=comparison->showWhitespace?comparison->allChanges:comparison->changes;
if((id==404 || id==405) && !changes.empty())
{
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
if(id==404)
{
const auto previous=std::lower_bound(changes.begin(),changes.end(),current);
if(previous!=changes.begin()) SendMessageW(list,LB_SETCURSEL,*std::prev(previous),0);
}
else
{
const auto next=std::upper_bound(changes.begin(),changes.end(),current);
if(next!=changes.end()) SendMessageW(list,LB_SETCURSEL,*next,0);
}
return TRUE;
}
if(id==402 && HIWORD(wp)==LBN_DBLCLK)
{
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
if(current>=0 && static_cast<size_t>(current)<comparison->rows.size())
{
const auto &row=comparison->rows[current];
const auto side=[&](int file,int line)
{
return line<0?std::wstring(L"—"):comparison->lines[file][line];
};
const auto detail=L"Left\n"+side(0,row.left)+L"\n\nRight\n"+side(1,row.right);
showFilesNotice(dialog,detail.c_str(),L"Line details");
}
return TRUE;
}
}
return FALSE;
}
INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
return TRUE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDCANCEL)
{
*reinterpret_cast<std::atomic_bool*>(GetWindowLongPtrW(dialog,DWLP_USER))=true;
EnableWindow(GetDlgItem(dialog,IDCANCEL),FALSE);
return TRUE;
}
return paintTextDialog(dialog,message,wp,lp,L" Compare files ");
}
void compareSelectedFiles(HWND owner)
{
auto &current=panels[active],&other=panels[1-active];
const auto selected=selectedPanelPaths(current);
const auto opposite=selectedPanelPaths(other);
auto state=std::make_unique<FileComparison>();
auto &comparison=*state;
const auto pick=[](const Panel &panel,const fs::path &path,CompareFile &file)
{
const auto row=std::find(panel.rows.begin(),panel.rows.end(),path);
if(ftpProfileList(panel) || row==panel.rows.end() || panel.sizes[row-panel.rows.begin()]==L"Folder")
return false;
const auto directory=path.parent_path();
const auto tail=(directory.filename()/path.filename()).native();
const auto location=panelLocation(panel);
const auto label=tail+L" · "+location;
file={path,label,panel.peer,panel.ftp};
return true;
};
bool valid=false;
if(selected.size()==2)
valid=pick(current,selected[0],comparison.files[0]) && pick(current,selected[1],comparison.files[1]);
else if(selected.size()==1 && opposite.size()==1)
valid=pick(current,selected.front(),comparison.files[active]) &&
pick(other,opposite.front(),comparison.files[1-active]);
if(!valid)
{
showFilesNotice(owner,L"Mark two text files in the active panel or select one text file in each panel.",
L"Compare files");
return;
}
std::atomic_bool canceled{};
try
{
{
FileOperationUi worker;
FilesModalDialog progress(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(115),owner,
comparisonProgressDialog,reinterpret_cast<LPARAM>(&canceled),false);
if(!progress.window()) throw std::runtime_error("Could not open the progress dialog.");
progress.show();
worker.run(progress.window(),canceled,[&]
{
for(int side=0;side<2;++side)
comparison.lines[side]=readComparisonLines(comparison.files[side],canceled);
alignComparison(comparison,canceled);
});
}
if(!canceled)
{
const auto window=CreateDialogParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(114),nullptr,
comparisonDialog,reinterpret_cast<LPARAM>(&comparison));
if(!window) throw std::runtime_error("Could not open the comparison window.");
comparisonWindows.emplace(window,std::move(state));
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
SetFocus(GetDlgItem(window,402));
}
}
catch(const std::system_error &error)
{
if(canceled || error.code().value()==ERROR_CANCELLED) return;
const auto detail=error.code().value()==ERROR_FILE_TOO_LARGE?L"Each text file can be up to 2 MiB.":
fileError(error);
showFileOperationError(owner,L"Comparison failed",detail);
}
catch(const std::exception &error)
{
if(!canceled) showFileOperationError(owner,L"Comparison failed",ks::wide(error.what()));
}
}
+314 -94
View File
@@ -7,122 +7,342 @@ bool filesMouseDown(UINT message)
message==WM_MBUTTONDOWN || message==WM_XBUTTONDOWN;
}
bool handleFilesDialogClick(HWND dialog,HWND clicked,POINT point)
{
if(!clicked || clicked==dialog || IsChild(dialog,clicked) ||
GetAncestor(clicked,GA_ROOTOWNER)!=GetAncestor(dialog,GA_ROOTOWNER))
return false;
wchar_t windowClass[16]{};
if(GetClassNameW(clicked,windowClass,16) && std::wstring_view(windowClass)==L"#32768")
{
GUITHREADINFO thread{sizeof(thread)};
if(GetGUIThreadInfo(GetWindowThreadProcessId(dialog,nullptr),&thread) &&
(thread.hwndMenuOwner==dialog || IsChild(dialog,thread.hwndMenuOwner)))
return false;
}
// System pickers and dropdowns owned by this dialog handle their own input.
for(auto popup=GetAncestor(clicked,GA_ROOT);popup;popup=GetWindow(popup,GW_OWNER))
if(popup==dialog || IsChild(dialog,popup)) return false;
for(auto owner=GetWindow(dialog,GW_OWNER);owner;owner=GetWindow(owner,GW_OWNER))
{
if(clicked!=owner) continue;
RECT client{};
GetClientRect(owner,&client);
ScreenToClient(owner,&point);
if(!PtInRect(&client,point)) return false;
break;
}
if(const auto dropdown=static_cast<HWND>(GetPropW(dialog,ks::files::farDropDownProperty)))
return PostMessageW(dropdown,WM_CLOSE,0,0)!=FALSE;
return PostMessageW(dialog,WM_COMMAND,IDCANCEL,0)!=FALSE;
}
LRESULT CALLBACK filesDialogMouse(int code,WPARAM message,LPARAM data)
{
const auto dialog=activeFilesDialog;
if(code==HC_ACTION && dialog && IsWindowVisible(dialog) && filesMouseDown(static_cast<UINT>(message)))
{
const auto point=reinterpret_cast<const MSLLHOOKSTRUCT*>(data)->pt;
const auto clicked=WindowFromPoint(point);
const auto root=GetAncestor(dialog,GA_ROOTOWNER);
if(clicked!=dialog && !IsChild(dialog,clicked))
{
RECT client{};
POINT local=point;
GetClientRect(root,&client);
ScreenToClient(root,&local);
if(clicked!=root || PtInRect(&client,local))
{
const bool internal=clicked==root || IsChild(root,clicked) ||
(clicked && GetAncestor(clicked,GA_ROOTOWNER)==root);
if(PostMessageW(dialog,WM_COMMAND,IDCANCEL,0) && internal) return 1;
}
}
if(handleFilesDialogClick(dialog,WindowFromPoint(point),point)) return 1;
}
return CallNextHookEx(nullptr,code,message,data);
}
struct FilesDialogInput
class FilesModalDialog
{
HWND previous=activeFilesDialog;
explicit FilesDialogInput(HWND dialog)
public:
FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument,
bool watchOutsideClicks=true)
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument),
watchOutsideClicks_(watchOutsideClicks)
{
activeFilesDialog=dialog;
if(!filesDialogMouseHook)
filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0);
window_=CreateDialogParamW(instance,resource,owner,dispatchDialog,reinterpret_cast<LPARAM>(this));
}
~FilesDialogInput()
~FilesModalDialog() { close(); }
FilesModalDialog(const FilesModalDialog &)=delete;
FilesModalDialog &operator=(const FilesModalDialog &)=delete;
HWND window() const { return window_; }
static HWND activeFor(HWND owner)
{
activeFilesDialog=previous;
if(!previous && filesDialogMouseHook)
const auto root=GetAncestor(owner,GA_ROOTOWNER);
for(auto dialog=activeFilesDialog;dialog;)
{
if(GetAncestor(dialog,GA_ROOTOWNER)==root) return dialog;
const auto *state=reinterpret_cast<const FilesModalDialog *>(GetPropW(dialog,stateProperty_));
dialog=state?state->previous_:nullptr;
}
return nullptr;
}
static void fitWidthToOwner(HWND dialog,int minimum,void (*layout)(HWND))
{
auto *state=reinterpret_cast<FilesModalDialog *>(GetPropW(dialog,stateProperty_));
RECT bounds{};
if(!state || !GetWindowRect(dialog,&bounds)) return;
state->preferredWidth_=bounds.right-bounds.left;
state->minimumWidth_=minimum;
state->layout_=layout;
}
static void refreshLayout(HWND dialog)
{
auto *state=reinterpret_cast<FilesModalDialog *>(GetPropW(dialog,stateProperty_));
if(!state || !state->entered_ || state->layout_) return;
state->captureLayout();
state->fitWidth(dialog,state->ownerBounds_);
}
static bool dismissOwned(HWND owner)
{
const auto dialog=activeFor(owner);
for(auto parent=GetWindow(dialog,GW_OWNER);parent;parent=GetWindow(parent,GW_OWNER))
if(parent==owner) return PostMessageW(dialog,WM_CLOSE,0,0)!=FALSE;
return false;
}
void show()
{
if(!window_ || entered_) return;
previous_=activeFilesDialog;
activeFilesDialog=window_;
entered_=true;
refreshMouseHook();
if(GetWindowRect(owner_,&ownerBounds_))
{
if(!layout_) captureLayout();
SetWindowSubclass(owner_,trackOwner,reinterpret_cast<UINT_PTR>(this),reinterpret_cast<DWORD_PTR>(this));
if(ownerBounds_.right-ownerBounds_.left<minimumOwnerWidth() && !IsZoomed(owner_))
SetWindowPos(owner_,nullptr,0,0,minimumOwnerWidth(),ownerBounds_.bottom-ownerBounds_.top,
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
fitWidth(window_,ownerBounds_,true);
}
ShowWindow(window_,SW_SHOW);
SetActiveWindow(window_);
}
void close()
{
if(entered_ && IsWindow(owner_))
RemoveWindowSubclass(owner_,trackOwner,reinterpret_cast<UINT_PTR>(this));
if(window_ && IsWindow(window_)) DestroyWindow(window_);
window_=nullptr;
if(!entered_) return;
entered_=false;
activeFilesDialog=previous_;
refreshMouseHook();
if(IsWindow(owner_) && !IsIconic(GetAncestor(owner_,GA_ROOTOWNER)))
{
SetActiveWindow(owner_);
if(IsWindow(focus_) && IsWindowEnabled(focus_) && (focus_==owner_ || IsChild(owner_,focus_)))
SetFocus(focus_);
}
}
static bool handleMessage(HWND dialog,MSG &message)
{
if(message.hwnd==dialog || IsChild(dialog,message.hwnd))
{
if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)
{
SendMessageW(dialog,WM_COMMAND,IDCANCEL,0);
return true;
}
return IsDialogMessageW(dialog,&message)!=FALSE;
}
if(!message.hwnd || GetAncestor(message.hwnd,GA_ROOTOWNER)!=GetAncestor(dialog,GA_ROOTOWNER))
return false;
const bool input=(message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST) ||
(message.message>=WM_MOUSEFIRST && message.message<=WM_MOUSELAST) ||
message.message==WM_CONTEXTMENU;
if(input && (filesMouseDown(message.message) ||
(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)))
PostMessageW(dialog,WM_COMMAND,IDCANCEL,0);
return input;
}
static void finish(HWND dialog,INT_PTR answer)
{
auto *state=reinterpret_cast<FilesModalDialog *>(GetPropW(dialog,stateProperty_));
if(!state) return;
state->result_=answer;
state->finished_=true;
ShowWindow(dialog,SW_HIDE);
}
static INT_PTR run(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument)
{
FilesModalDialog dialog(instance,resource,owner,procedure,argument);
return dialog.runModal();
}
INT_PTR runModal()
{
if(!window_) return -1;
show();
MSG message{};
while(!finished_ && IsWindow(window_))
{
const auto status=GetMessageW(&message,nullptr,0,0);
if(status<=0)
{
if(status==0) PostQuitMessage(static_cast<int>(message.wParam));
break;
}
if(handleMessage(window_,message)) continue;
TranslateMessage(&message);
DispatchMessageW(&message);
}
return result_;
}
private:
static constexpr wchar_t stateProperty_[]=L"KSwitcher.Files.ModalDialog";
HWND window_{},owner_{},focus_{},previous_{};
RECT ownerBounds_{};
int preferredWidth_{},minimumWidth_{};
std::vector<std::pair<HWND,RECT>> controls_;
void (*layout_)(HWND){};
DLGPROC procedure_;
LPARAM argument_;
INT_PTR result_=IDCANCEL;
bool entered_{},finished_{},watchOutsideClicks_;
static void refreshMouseHook()
{
const auto *active=activeFilesDialog?
reinterpret_cast<const FilesModalDialog*>(GetPropW(activeFilesDialog,stateProperty_)):nullptr;
if(active && active->watchOutsideClicks_)
{
if(!filesDialogMouseHook)
filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0);
}
else if(filesDialogMouseHook)
{
UnhookWindowsHookEx(filesDialogMouseHook);
filesDialogMouseHook=nullptr;
}
}
};
bool filesDialogHandlesMessage(HWND dialog,MSG &message)
{
if(message.hwnd==dialog || IsChild(dialog,message.hwnd)) return IsDialogMessageW(dialog,&message);
if(!message.hwnd || GetAncestor(message.hwnd,GA_ROOTOWNER)!=GetAncestor(dialog,GA_ROOTOWNER)) return false;
const bool input=(message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST) ||
(message.message>=WM_MOUSEFIRST && message.message<=WM_MOUSELAST) ||
message.message==WM_CONTEXTMENU;
if(input && message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)
PostMessageW(dialog,WM_COMMAND,IDCANCEL,0);
return input;
}
struct FilesDialogResult
{
DLGPROC procedure;
LPARAM argument;
INT_PTR result=IDCANCEL;
bool finished=false;
};
constexpr wchar_t filesDialogResultProperty[]=L"KSwitcher.Files.DialogResult";
INT_PTR CALLBACK filesDialogProcedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
auto *result=reinterpret_cast<FilesDialogResult*>(GetPropW(dialog,filesDialogResultProperty));
if(message==WM_INITDIALOG)
void captureLayout()
{
result=reinterpret_cast<FilesDialogResult*>(lp);
if(!SetPropW(dialog,filesDialogResultProperty,result)) return FALSE;
lp=result->argument;
}
if(!result) return FALSE;
const auto handled=result->procedure(dialog,message,wp,lp);
if(message==WM_NCDESTROY) RemovePropW(dialog,filesDialogResultProperty);
return handled;
}
void finishFilesDialog(HWND dialog,INT_PTR answer)
{
auto *result=reinterpret_cast<FilesDialogResult*>(GetPropW(dialog,filesDialogResultProperty));
if(!result) return;
result->result=answer;
result->finished=true;
ShowWindow(dialog,SW_HIDE);
}
INT_PTR runFilesDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument)
{
FilesDialogResult result{procedure,argument};
const auto dialog=CreateDialogParamW(instance,resource,owner,filesDialogProcedure,
reinterpret_cast<LPARAM>(&result));
if(!dialog) return -1;
GetWindowRect(GetAncestor(owner,GA_ROOTOWNER),&previousOwnerBounds);
FilesDialogInput input(dialog);
ShowWindow(dialog,SW_SHOW);
SetActiveWindow(dialog);
MSG message{};
while(!result.finished && IsWindow(dialog))
{
const auto status=GetMessageW(&message,nullptr,0,0);
if(status<=0)
RECT bounds{};
GetWindowRect(window_,&bounds);
preferredWidth_=bounds.right-bounds.left;
minimumWidth_=MulDiv(preferredWidth_,3,4);
controls_.clear();
if(GetWindowLongPtrW(window_,GWL_STYLE)&WS_THICKFRAME)
{
if(status==0) PostQuitMessage(static_cast<int>(message.wParam));
break;
MINMAXINFO limits{};
SendMessageW(window_,WM_GETMINMAXINFO,0,reinterpret_cast<LPARAM>(&limits));
minimumWidth_=std::max<int>(minimumWidth_,limits.ptMinTrackSize.x);
return;
}
if(filesDialogHandlesMessage(dialog,message)) continue;
TranslateMessage(&message);
DispatchMessageW(&message);
const auto dc=GetDC(window_);
if(!dc) return;
for(auto field=GetWindow(window_,GW_CHILD);field;field=GetWindow(field,GW_HWNDNEXT))
{
RECT rect{};
GetWindowRect(field,&rect);
MapWindowPoints(nullptr,window_,reinterpret_cast<POINT *>(&rect),2);
wchar_t type[16]{},label[128]{};
GetClassNameW(field,type,16);
RECT dropdown{};
if(lstrcmpiW(type,L"ComboBox")==0 &&
SendMessageW(field,CB_GETDROPPEDCONTROLRECT,0,reinterpret_cast<LPARAM>(&dropdown)))
rect.bottom=rect.top+dropdown.bottom-dropdown.top;
controls_.emplace_back(field,rect);
const auto fieldWidth=rect.right-rect.left;
if(!(GetWindowLongPtrW(field,GWL_STYLE)&WS_VISIBLE) || fieldWidth<=0) continue;
if(lstrcmpiW(type,L"Button")!=0 || !GetWindowTextW(field,label,128)) continue;
const auto font=reinterpret_cast<HFONT>(SendMessageW(field,WM_GETFONT,0,0));
const auto previous=font?SelectObject(dc,font):nullptr;
RECT text{};
DrawTextW(dc,label,-1,&text,DT_SINGLELINE|DT_CALCRECT);
TEXTMETRICW metrics{};
GetTextMetricsW(dc,&metrics);
if(previous) SelectObject(dc,previous);
const auto needed=std::min(fieldWidth,text.right+4*metrics.tmAveCharWidth);
minimumWidth_=std::max(minimumWidth_,static_cast<int>(
(preferredWidth_*needed+fieldWidth-1)/fieldWidth));
}
ReleaseDC(window_,dc);
}
if(IsWindow(dialog)) DestroyWindow(dialog);
if(IsWindow(owner) && !IsIconic(GetAncestor(owner,GA_ROOTOWNER))) SetActiveWindow(owner);
return result.result;
}
int ownerMargin() const { return MulDiv(12,GetDpiForWindow(owner_),96); }
int minimumOwnerWidth() const { return minimumWidth_+2*ownerMargin(); }
void fitWidth(HWND window,const RECT &owner,bool initial=false)
{
RECT bounds{};
if(IsZoomed(window) || !GetWindowRect(window,&bounds)) return;
const int width=std::clamp(static_cast<int>(owner.right-owner.left)-2*ownerMargin(),
minimumWidth_,std::max(minimumWidth_,preferredWidth_));
const int height=bounds.bottom-bounds.top;
const int x=(owner.left+owner.right-width)/2;
const int y=(owner.top+owner.bottom-height)/2;
const bool resized=width!=bounds.right-bounds.left;
if(x!=bounds.left || y!=bounds.top || resized)
SetWindowPos(window,nullptr,x,y,width,height,SWP_NOZORDER|SWP_NOACTIVATE|
(resized?SWP_NOCOPYBITS:0));
if(layout_ && (initial || resized)) layout_(window);
else if(resized && preferredWidth_>0)
for(const auto &[field,rect]:controls_)
{
const auto left=MulDiv(rect.left,width,preferredWidth_);
const auto right=MulDiv(rect.right,width,preferredWidth_);
SetWindowPos(field,nullptr,left,rect.top,right-left,rect.bottom-rect.top,
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
}
if(initial || resized) RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
}
static LRESULT CALLBACK trackOwner(HWND owner,UINT message,WPARAM wp,LPARAM lp,UINT_PTR id,DWORD_PTR data)
{
auto &dialog=*reinterpret_cast<FilesModalDialog *>(data);
if(message==WM_WINDOWPOSCHANGING && !IsIconic(owner))
{
auto &position=*reinterpret_cast<WINDOWPOS *>(lp);
if(!(position.flags&SWP_NOSIZE) && position.cx>0)
position.cx=std::max(position.cx,dialog.minimumOwnerWidth());
}
if(message==WM_NCDESTROY) RemoveWindowSubclass(owner,trackOwner,id);
const auto result=DefSubclassProc(owner,message,wp,lp);
if(message==WM_GETMINMAXINFO)
{
auto &limits=*reinterpret_cast<MINMAXINFO *>(lp);
limits.ptMinTrackSize.x=std::max<LONG>(limits.ptMinTrackSize.x,dialog.minimumOwnerWidth());
return result;
}
if((message!=WM_MOVE && message!=WM_SIZE) || IsIconic(owner)) return result;
RECT ownerBounds{};
if(!GetWindowRect(owner,&ownerBounds)) return result;
if(EqualRect(&ownerBounds,&dialog.ownerBounds_)) return result;
dialog.ownerBounds_=ownerBounds;
dialog.fitWidth(dialog.window_,ownerBounds);
return result;
}
static INT_PTR CALLBACK dispatchDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
auto *state=reinterpret_cast<FilesModalDialog *>(GetPropW(dialog,stateProperty_));
if(message==WM_INITDIALOG)
{
state=reinterpret_cast<FilesModalDialog *>(lp);
if(!SetPropW(dialog,stateProperty_,state)) return FALSE;
lp=state->argument_;
}
if(!state) return FALSE;
const auto handled=state->procedure_(dialog,message,wp,lp);
if(message==WM_NCDESTROY) RemovePropW(dialog,stateProperty_);
if(!handled && message==WM_CLOSE)
{
SendMessageW(dialog,WM_COMMAND,IDCANCEL,0);
return TRUE;
}
return handled;
}
};
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include <windows.h>
#include <algorithm>
namespace ks::files
{
inline void paintFarDropDownArrow(HDC dc, const RECT &bounds, HBRUSH surface, COLORREF ink, UINT dpi)
{
FillRect(dc, &bounds, surface);
// Center the drawn pixels. A font's arrow glyph can sit below the center of its line box.
const auto halfWidth = std::min((bounds.right - bounds.left - 1) / 2,
static_cast<LONG>(MulDiv(3, dpi, 96)));
const auto halfHeight = std::min((bounds.bottom - bounds.top - 1) / 2,
static_cast<LONG>(MulDiv(5, dpi, 96)));
if (halfWidth < 1 || halfHeight < 1) return;
const auto x = (bounds.left + bounds.right - 1) / 2;
const auto y = (bounds.top + bounds.bottom - 1) / 2;
const auto tip = y + halfHeight;
const auto head = std::min(halfWidth, halfHeight);
for (LONG row = y - halfHeight; row <= tip; ++row)
SetPixelV(dc, x, row, ink);
for (LONG offset = 1; offset <= head; ++offset)
{
SetPixelV(dc, x - offset, tip - offset, ink);
SetPixelV(dc, x + offset, tip - offset, ink);
}
}
inline void paintFarFieldArrow(HDC dc, const RECT &bounds, bool enabled, UINT dpi)
{
paintFarDropDownArrow(dc, bounds, static_cast<HBRUSH>(GetStockObject(LTGRAY_BRUSH)),
enabled ? RGB(0,0,0) : RGB(48,48,48), dpi);
}
}
+202
View File
@@ -0,0 +1,202 @@
constexpr wchar_t operationPipePrefix[]=L"\\\\.\\pipe\\KSwitcher.Files.Operation.";
constexpr DWORD operationMessageLimit=256*1024;
void writeElevationMessage(HANDLE pipe,const Json &message)
{
const auto bytes=message.dump();
requireFileOperation(bytes.size()<=operationMessageLimit,ERROR_BUFFER_OVERFLOW);
DWORD written{};
checkFileOperation(WriteFile(pipe,bytes.data(),static_cast<DWORD>(bytes.size()),&written,nullptr));
requireFileOperation(written==bytes.size(),ERROR_WRITE_FAULT);
}
Json readElevationMessage(HANDLE pipe)
{
std::array<char,operationMessageLimit> bytes;
DWORD read{};
checkFileOperation(ReadFile(pipe,bytes.data(),operationMessageLimit,&read,nullptr));
return Json::parse(bytes.data(),bytes.data()+read);
}
bool localElevationPath(const fs::path &path)
{
const auto root=path.root_name().native();
return path.is_absolute() && root.size()==2 && root[1]==L':' &&
path.native().find(L'\0')==std::wstring::npos && path.has_relative_path() &&
GetDriveTypeW(path.root_path().c_str())!=DRIVE_REMOTE;
}
bool allowedElevationRequest(const Json &request)
{
const auto action=request.at("action").get<std::string>();
if(action!="copy" && action!="move" && action!="mkdir" && action!="mkdir-link" &&
action!="remove" && action!="recycle" && action!="rmdir" && action!="stat" &&
action!="canonical" && action!="list") return false;
if(!localElevationPath(filePath(request.at("path")))) return false;
if(action=="copy" || action=="move" || action=="mkdir-link")
return localElevationPath(filePath(request.at("target")));
return true;
}
DWORD serveElevatedFileOperations(const std::wstring &parent,const std::wstring &pipeName)
{
try
{
if(!IsUserAnAdmin() || !pipeName.starts_with(operationPipePrefix)) return ERROR_ACCESS_DENIED;
DWORD expected{};
for(const auto ch:parent)
{
if(ch<L'0' || ch>L'9' || expected>(MAXDWORD-(ch-L'0'))/10) return ERROR_INVALID_PARAMETER;
expected=expected*10+(ch-L'0');
}
Handle pipe{CreateFileW(pipeName.c_str(),GENERIC_READ|GENERIC_WRITE,0,nullptr,OPEN_EXISTING,
SECURITY_SQOS_PRESENT|SECURITY_IDENTIFICATION,nullptr)};
checkFileOperation(pipe.value!=INVALID_HANDLE_VALUE);
ULONG server{};
checkFileOperation(GetNamedPipeServerProcessId(pipe.value,&server));
requireFileOperation(server==expected,ERROR_ACCESS_DENIED);
DWORD mode=PIPE_READMODE_MESSAGE;
checkFileOperation(SetNamedPipeHandleState(pipe.value,&mode,nullptr,nullptr));
FilesConnection listing;
bool more=false;
while(true)
{
const auto request=readElevationMessage(pipe.value);
Json reply;
try
{
const auto action=request.at("action").get<std::string>();
if(action=="listNext" || action=="list")
{
requireFileOperation(action=="listNext"?more:allowedElevationRequest(request),ERROR_ACCESS_DENIED);
more=false;
reply=listing.call(request);
more=reply.value("more",false);
}
else
{
requireFileOperation(allowedElevationRequest(request),ERROR_ACCESS_DENIED);
FilesConnection local;
ULONGLONG lastUpdate{};
reply=local.call(request,[&](uint64_t done,uint64_t total)
{
const auto now=GetTickCount64();
if(lastUpdate && now-lastUpdate<100 && done!=total) return true;
lastUpdate=now;
writeElevationMessage(pipe.value,{{"progress",{done,total}}});
return readElevationMessage(pipe.value).at("continue").get<bool>();
});
}
}
catch(const std::system_error &error) {reply={{"error",error.code().value()}};}
catch(const std::exception &) {reply={{"error",ERROR_INVALID_DATA}};}
writeElevationMessage(pipe.value,reply);
}
}
catch(const std::system_error &error)
{
const auto code=error.code().value();
return code==ERROR_BROKEN_PIPE || code==ERROR_NO_DATA?ERROR_SUCCESS:static_cast<DWORD>(code);
}
catch(const std::exception &) {return ERROR_INVALID_DATA;}
}
class FileOperationElevation
{
HWND owner_;
FileOperationUi *ui_;
std::atomic_bool &canceled_;
ElevatedHelper helper_;
bool connected_{};
DWORD connect()
{
const auto deadline=GetTickCount64()+10000;
while(!canceled_ && GetTickCount64()<deadline)
{
if(ConnectNamedPipe(helper_.pipe.value,nullptr) || GetLastError()==ERROR_PIPE_CONNECTED)
{
ULONG client{};
if(!GetNamedPipeClientProcessId(helper_.pipe.value,&client)) return GetLastError();
if(client!=GetProcessId(helper_.process.value)) return ERROR_ACCESS_DENIED;
DWORD mode=PIPE_READMODE_MESSAGE;
if(!SetNamedPipeHandleState(helper_.pipe.value,&mode,nullptr,nullptr)) return GetLastError();
connected_=true;
return ERROR_SUCCESS;
}
if(WaitForSingleObject(helper_.process.value,20)==WAIT_OBJECT_0)
{
DWORD result{};
if(!GetExitCodeProcess(helper_.process.value,&result)) return GetLastError();
return result?result:ERROR_PIPE_NOT_CONNECTED;
}
}
return canceled_?ERROR_CANCELLED:ERROR_TIMEOUT;
}
DWORD requestConsent(const Json &request)
{
if(canceled_) return ERROR_CANCELLED;
auto paths=filePath(request.at("path")).wstring();
if(request.contains("target")) paths+=L"\r\n"+filePath(request.at("target")).wstring();
const auto question=L"Windows denied access to the following path:\r\n"+paths+
L"\r\n\r\nRetry with administrator rights for the current operation?";
if(showFilesNotice(owner_,question.c_str(),L"Access denied",{.confirm=true})!=IDYES)
return ERROR_CANCELLED;
const auto error=launchElevatedHelper(owner_,operationPipePrefix,L"--elevated-file-operation",
std::to_wstring(GetCurrentProcessId()),helper_);
SetForegroundWindow(owner_);
return error;
}
Json send(const Json &request,const ks::lan::FileProgress &progress={})
{
if(canceled_) return {{"error",ERROR_CANCELLED}};
writeElevationMessage(helper_.pipe.value,request);
for(;;)
{
auto message=readElevationMessage(helper_.pipe.value);
if(!message.contains("progress")) return message;
const auto &value=message.at("progress");
writeElevationMessage(helper_.pipe.value,{{"continue",!canceled_ &&
(!progress || progress(value.at(0).get<uint64_t>(),value.at(1).get<uint64_t>()))}});
}
}
public:
FileOperationElevation(HWND owner,std::atomic_bool &canceled,FileOperationUi *ui=nullptr):
owner_(owner),ui_(ui),canceled_(canceled){}
Json retry(const Json &request,Json reply,const ks::lan::FileProgress &progress={})
{
const auto failure=reply.at("error").get<DWORD>();
if((failure!=ERROR_ACCESS_DENIED && failure!=ERROR_PRIVILEGE_NOT_HELD && failure!=ERROR_ELEVATION_REQUIRED) ||
IsUserAnAdmin() || !allowedElevationRequest(request))
return reply;
if(!connected_)
{
auto error=ui_?ui_->invoke([&]{return requestConsent(request);}):requestConsent(request);
if(error==ERROR_SUCCESS) error=connect();
if(error==ERROR_CANCELLED) canceled_=true;
if(error!=ERROR_SUCCESS) return {{"error",error}};
}
return send(request,progress);
}
Json call(FilesConnection &local,const Json &request,const ks::lan::FileProgress &progress={})
{
return retry(request,local.call(request,progress),progress);
}
void list(FilesConnection &local,const fs::path &path,const FileVisitor &visit)
{
const auto request=fileRequest("list",path);
auto reply=local.call(request);
const bool elevated=reply.at("error")==ERROR_ACCESS_DENIED;
if(elevated) reply=retry(request,std::move(reply));
listFilePages(std::move(reply),path,visit,[&]{
const Json next{{"action","listNext"}};
return elevated?send(next):local.call(next);
});
}
};
+28 -44
View File
@@ -104,7 +104,7 @@ INT_PTR CALLBACK folderShortcutEditDialog(HWND dialog,UINT message,WPARAM wp,LPA
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
finishFilesDialog(dialog,IDCANCEL);
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
@@ -116,7 +116,7 @@ INT_PTR CALLBACK folderShortcutEditDialog(HWND dialog,UINT message,WPARAM wp,LPA
((root[0]>=L'A' && root[0]<=L'Z') || (root[0]>=L'a' && root[0]<=L'z'));
if(!path.is_absolute() || (!edit.entry.peerId.empty() && !lanDrive))
{
MessageBoxW(dialog,L"Enter an absolute folder path on the original computer.",L"Folder shortcuts",MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"Enter an absolute folder path on the original computer.",L"Folder shortcuts");
SetFocus(GetDlgItem(dialog,shortcutPath));
return TRUE;
}
@@ -127,7 +127,7 @@ INT_PTR CALLBACK folderShortcutEditDialog(HWND dialog,UINT message,WPARAM wp,LPA
for(size_t i=0;i<group.size();++i)
if((!edit.index || i!=*edit.index) && sameFolderShortcut(group[i],entry))
{
MessageBoxW(dialog,L"This folder is already assigned to this digit.",L"Folder shortcuts",MB_OK|MB_ICONINFORMATION);
showFilesNotice(dialog,L"This folder is already assigned to this digit.",L"Folder shortcuts");
return TRUE;
}
auto updated=folderShortcuts;
@@ -135,24 +135,24 @@ INT_PTR CALLBACK folderShortcutEditDialog(HWND dialog,UINT message,WPARAM wp,LPA
else updated[edit.digit].push_back(std::move(entry));
if(!saveFolderShortcuts(updated))
{
MessageBoxW(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts",MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts");
return TRUE;
}
folderShortcuts=std::move(updated);
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
finishFilesDialog(dialog,IDOK);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
bool editFolderShortcut(HWND owner,FolderShortcutEdit &edit)
{
return runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(110),owner,
return FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(110),owner,
folderShortcutEditDialog,reinterpret_cast<LPARAM>(&edit))==IDOK;
}
void addFolderShortcut(const Panel &panel,int digit)
{
if(panel.directory.empty()) return;
if(panel.directory.empty() || panel.ftp) return;
FolderShortcutEdit edit{{panel.directory,panel.peer?panel.peer->id:"",
panel.peer?panel.peer->name:L""},digit,{}};
if(editFolderShortcut(GetParent(panel.list),edit))
@@ -187,8 +187,6 @@ struct FolderShortcutView
std::vector<int> digits;
int rowHeight{};
Panel *panel{};
bool all{};
std::vector<std::pair<int,size_t>> entries;
};
std::wstring shortcutLabel(const FolderShortcut &entry)
@@ -201,7 +199,6 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
const auto list=GetDlgItem(dialog,shortcutList);
SendMessageW(list,LB_RESETCONTENT,0,0);
view.digits.clear();
view.entries.clear();
const auto owner=GetWindow(dialog,GW_OWNER);
const auto dc=GetDC(dialog);
const auto font=SelectObject(dc,mono);
@@ -219,23 +216,14 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
GetTextExtentPoint32W(dc,label.data(),static_cast<int>(label.size()),&size);
return static_cast<int>(size.cx);
};
int width=std::max(measure(L"Folder shortcuts"),measure(view.all?L"Del F4":view.digit<0?L"Enter Esc":quickFolderHints))+3*cellWidth;
int width=std::max(measure(L"Folder shortcuts"),measure(view.digit<0?L"Enter Esc":quickFolderHints))+3*cellWidth;
const int textInset=dialogRowTextInset(cellWidth);
const auto add=[&](const std::wstring &label)
{
width=std::max(width,measure(label)+2*textInset);
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
};
if(view.all)
{
for(int digit=0;digit<static_cast<int>(folderShortcuts.size());++digit)
for(size_t index=0;index<folderShortcuts[digit].size();++index)
{
view.entries.emplace_back(digit,index);
add(std::to_wstring(digit)+L" "+shortcutLabel(folderShortcuts[digit][index]));
}
}
else if(view.digit<0)
if(view.digit<0)
{
for(int digit=0;digit<10;++digit)
if(!folderShortcuts[digit].empty())
@@ -255,7 +243,8 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
GetWindowRect(owner,&parent);
const auto windowWidth=std::max(px(260),static_cast<int>(parent.right-parent.left));
const auto windowHeight=std::max(px(140),static_cast<int>(parent.bottom-parent.top));
width=std::min(width,std::max(1,std::min(windowWidth,static_cast<int>(work.right-work.left))-2*inset));
width=std::min(width+scrollBarWidth(list),
std::max(1,std::min(windowWidth,static_cast<int>(work.right-work.left))-2*inset));
const auto maxRows=std::max(1,(std::min(windowHeight,static_cast<int>(work.bottom-work.top))-2*listTop)/view.rowHeight);
const auto count=static_cast<int>(SendMessageW(list,LB_GETCOUNT,0,0));
const int rows=std::min(count,maxRows);
@@ -267,9 +256,11 @@ void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection)
const int y=std::clamp(static_cast<int>((parent.top+parent.bottom-h)/2),
static_cast<int>(work.top),std::max(static_cast<int>(work.top),static_cast<int>(work.bottom)-h));
SetWindowPos(dialog,nullptr,x,y,w,h,SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(list,nullptr,inset,listTop,width,listHeight,SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(list,nullptr,inset,listTop,std::max(1,width-scrollBarWidth(list)),listHeight,
SWP_NOZORDER|SWP_NOACTIVATE);
SendMessageW(list,LB_SETCURSEL,std::clamp(selection,0,std::max(0,count-1)),0);
InvalidateRect(dialog,nullptr,TRUE);
FilesModalDialog::refreshLayout(dialog);
}
LRESULT CALLBACK quickFolderKeys(HWND list,UINT message,WPARAM key,LPARAM flags,UINT_PTR,DWORD_PTR)
@@ -289,7 +280,7 @@ LRESULT CALLBACK quickFolderKeys(HWND list,UINT message,WPARAM key,LPARAM flags,
return 0;
}
}
return scrollList(list,message,key,flags);
return DefSubclassProc(list,message,key,flags);
}
INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
@@ -302,6 +293,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
layoutQuickFolders(dialog,view,0);
const auto list=GetDlgItem(dialog,shortcutList);
SetWindowSubclass(list,quickFolderKeys,1,0);
installScrollBar(list,dialog);
SetFocus(list);
return FALSE;
}
@@ -321,7 +313,8 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
const auto bounds=paintDialogFrame(dc,client,dialogFrameMetrics(GetDpiForWindow(dialog)),teal,frame);
DeleteObject(frame);
paintDialogFrameCaptions(dc,client,bounds,L"Folder shortcuts",teal,colors[Text],mono,
view->all?L"Del F4":view->digit<0?L"Enter Esc":quickFolderHints);
view->digit<0?L"Enter Esc":quickFolderHints);
paintScrollPosition(dialog,dc,GetDlgItem(dialog,shortcutList),colors[Dialog]);
EndPaint(dialog,&ps);
return TRUE;
}
@@ -340,7 +333,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
finishFilesDialog(dialog,IDCANCEL);
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
@@ -348,7 +341,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(action!=quickRemove && action!=quickEdit && action!=quickInsert && action!=quickMoveUp &&
action!=quickMoveDown && action!=IDOK && !(action==shortcutList && HIWORD(wp)==LBN_DBLCLK)) return FALSE;
const auto row=SendDlgItemMessageW(dialog,shortcutList,LB_GETCURSEL,0,0);
if(!view->all && view->digit<0)
if(view->digit<0)
{
if((action==IDOK || action==shortcutList) && row>=0 && static_cast<size_t>(row)<view->digits.size())
{
@@ -357,16 +350,8 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
return TRUE;
}
int digit=view->digit;
size_t index=static_cast<size_t>(row);
if(view->all)
{
if(index>=view->entries.size() || action==quickInsert ||
action==quickMoveUp || action==quickMoveDown) return TRUE;
const auto &entry=view->entries[index];
digit=entry.first;
index=entry.second;
}
const auto digit=view->digit;
const auto index=static_cast<size_t>(row);
const auto &group=folderShortcuts[digit];
if(action==quickInsert)
{
@@ -386,7 +371,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
auto updated=folderShortcuts;
std::swap(updated[view->digit][row],updated[view->digit][target]);
if(!saveFolderShortcuts(updated))
MessageBoxW(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts",MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts");
else
{
folderShortcuts=std::move(updated);
@@ -408,22 +393,22 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
updated[digit].erase(updated[digit].begin()+index);
if(!saveFolderShortcuts(updated))
{
MessageBoxW(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts",MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"Could not save folder shortcuts.",L"Folder shortcuts");
return TRUE;
}
folderShortcuts=std::move(updated);
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
if(view->all?view->entries.size()==1:folderShortcuts[digit].empty()) finishFilesDialog(dialog,IDCANCEL);
if(folderShortcuts[digit].empty()) FilesModalDialog::finish(dialog,IDCANCEL);
else layoutQuickFolders(dialog,*view,static_cast<int>(row));
return TRUE;
}
view->chosen=group[index];
finishFilesDialog(dialog,IDOK);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
void showFolderShortcuts(Panel &panel,int digit,bool all)
void showFolderShortcuts(Panel &panel,int digit)
{
if(digit>=0)
{
@@ -446,8 +431,7 @@ void showFolderShortcuts(Panel &panel,int digit,bool all)
}
FolderShortcutView view{digit};
view.panel=&panel;
view.all=all;
const auto result=runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(109),GetParent(panel.list),
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(109),GetParent(panel.list),
quickFolderDialog,reinterpret_cast<LPARAM>(&view));
SetFocus(panel.list);
if(result==IDOK && view.chosen) openFolderShortcut(panel,*view.chosen);
+217
View File
@@ -0,0 +1,217 @@
struct FtpProfile
{
std::wstring name, host, user;
INTERNET_PORT port=INTERNET_DEFAULT_FTP_PORT;
ks::Bytes secret;
bool legacyNames{};
};
std::vector<FtpProfile> ftpProfiles;
bool ftpProfilesLoaded{};
constexpr wchar_t ftpProfilesValue[]=L"FtpProfiles";
constexpr DWORD ftpProfilesMaxBytes=1024*1024;
const fs::path ftpRoot=L"\\";
std::wstring ftpPath(const fs::path &path)
{
auto value=path.native();
std::replace(value.begin(),value.end(),L'\\',L'/');
return value;
}
bool saveFtpProfiles(const std::vector<FtpProfile> &profiles)
{
auto rows=Json::array();
for(const auto &profile:profiles)
rows.push_back({{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)},
{"port",profile.port},{"user",ks::utf8(profile.user)},{"secret",profile.secret},
{"legacyNames",profile.legacyNames}});
const auto data=rows.dump();
return data.size()<=ftpProfilesMaxBytes &&
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
}
bool loadFtpProfiles()
{
if(ftpProfilesLoaded) return true;
DWORD bytes{};
const auto query=RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,
RRF_RT_REG_BINARY,nullptr,nullptr,&bytes);
if(query==ERROR_FILE_NOT_FOUND)
{
ftpProfilesLoaded=true;
return true;
}
if(query!=ERROR_SUCCESS || !bytes || bytes>ftpProfilesMaxBytes) return false;
std::string data(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,RRF_RT_REG_BINARY,
nullptr,data.data(),&bytes)!=ERROR_SUCCESS) return false;
try
{
const auto rows=Json::parse(data.begin(),data.begin()+bytes);
if(!rows.is_array()) return false;
std::vector<FtpProfile> profiles;
for(const auto &row:rows)
{
const auto port=row.at("port").get<unsigned>();
if(!port || port>65535) return false;
FtpProfile profile{ks::wide(row.at("name")),ks::wide(row.at("host")),
ks::wide(row.at("user")),static_cast<INTERNET_PORT>(port),row.at("secret").get<ks::Bytes>(),
row.value("legacyNames",false)};
if(profile.name.empty() || profile.host.empty()) return false;
profiles.push_back(std::move(profile));
}
ftpProfiles=std::move(profiles);
ftpProfilesLoaded=true;
return true;
}
catch(const std::exception &) {return false;}
}
std::wstring ftpPassword(const FtpProfile &profile)
{
if(profile.secret.empty()) return {};
auto bytes=ks::unprotect(profile.secret);
if(bytes.size()%sizeof(wchar_t)) throw std::runtime_error("Invalid FTP password");
std::wstring password(bytes.size()/sizeof(wchar_t),L'\0');
std::copy(bytes.begin(),bytes.end(),reinterpret_cast<unsigned char*>(password.data()));
SecureZeroMemory(bytes.data(),bytes.size());
return password;
}
struct FtpHandle
{
HINTERNET value{};
~FtpHandle() {if(value) InternetCloseHandle(value);}
explicit FtpHandle(HINTERNET handle=nullptr):value(handle) {}
FtpHandle(const FtpHandle &)=delete;
FtpHandle &operator=(const FtpHandle &)=delete;
};
void requireFileOperation(bool success,DWORD error)
{
if(!success) throw std::system_error(error,std::system_category());
}
void checkFileOperation(bool success)
{
if(!success) requireFileOperation(false,GetLastError());
}
class FtpSession
{
FtpHandle internet_{InternetOpenW(L"KSwitcher Files",INTERNET_OPEN_TYPE_DIRECT,nullptr,nullptr,0)};
FtpHandle connection_;
fs::path current_;
UINT nameCodePage_;
public:
explicit FtpSession(const FtpProfile &profile):nameCodePage_(profile.legacyNames?GetACP():CP_UTF8)
{
checkFileOperation(internet_.value!=nullptr);
DWORD timeout=10000, retries=1;
InternetSetOptionW(internet_.value,INTERNET_OPTION_CONNECT_TIMEOUT,&timeout,sizeof(timeout));
InternetSetOptionW(internet_.value,INTERNET_OPTION_CONNECT_RETRIES,&retries,sizeof(retries));
InternetSetOptionW(internet_.value,INTERNET_OPTION_RECEIVE_TIMEOUT,&timeout,sizeof(timeout));
InternetSetOptionW(internet_.value,INTERNET_OPTION_SEND_TIMEOUT,&timeout,sizeof(timeout));
auto password=ftpPassword(profile);
const auto user=profile.user.empty()?(password.empty()?nullptr:L"anonymous"):profile.user.c_str();
connection_.value=InternetConnectW(internet_.value,profile.host.c_str(),profile.port,
user,password.empty()?nullptr:password.c_str(),INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,0);
const auto error=GetLastError();
SecureZeroMemory(password.data(),password.size()*sizeof(wchar_t));
requireFileOperation(connection_.value!=nullptr,error);
if(!profile.legacyNames)
FtpCommandA(handle(),FALSE,0,"OPTS UTF8 ON",0,nullptr);
}
HINTERNET handle() const {return connection_.value;}
// WinINet's A entry points transfer FTP pathname bytes without a Unicode conversion.
std::wstring decodeName(std::string_view bytes) const
{
if(bytes.empty()) return {};
const auto length=static_cast<int>(bytes.size());
const auto count=MultiByteToWideChar(nameCodePage_,MB_ERR_INVALID_CHARS,bytes.data(),length,nullptr,0);
if(!count)
throw std::runtime_error("The FTP server returned a name in another encoding. Check the FTP connection's file name encoding.");
std::wstring name(count,L'\0');
checkFileOperation(MultiByteToWideChar(nameCodePage_,MB_ERR_INVALID_CHARS,bytes.data(),length,name.data(),count)>0);
return name;
}
std::string encodeName(const fs::path &path) const
{
const auto name=ftpPath(path);
if(name.empty()) return {};
const auto length=static_cast<int>(name.size());
BOOL substituted=FALSE;
const auto legacy=nameCodePage_!=CP_UTF8;
const auto flags=legacy?WC_NO_BEST_FIT_CHARS:WC_ERR_INVALID_CHARS;
const auto replacement=legacy?&substituted:nullptr;
const auto count=WideCharToMultiByte(nameCodePage_,flags,name.data(),length,nullptr,0,nullptr,replacement);
requireFileOperation(count>0 && !substituted,ERROR_NO_UNICODE_TRANSLATION);
std::string bytes(count,'\0');
checkFileOperation(WideCharToMultiByte(nameCodePage_,flags,name.data(),length,bytes.data(),count,nullptr,replacement)>0);
requireFileOperation(!substituted,ERROR_NO_UNICODE_TRANSLATION);
return bytes;
}
const fs::path &initialDirectory()
{
std::string bytes(32768,'\0');
DWORD length=static_cast<DWORD>(bytes.size());
checkFileOperation(FtpGetCurrentDirectoryA(handle(),bytes.data(),&length));
auto initial=decodeName(bytes.c_str());
if(initial.empty() || initial.front()!=L'/' || initial.find_first_of(L"\\\r\n")!=initial.npos)
throw std::system_error(ERROR_BAD_PATHNAME,std::system_category());
const auto first=initial.find_first_not_of(L'/');
if(first==initial.npos) current_=ftpRoot;
else
{
initial.erase(1,first-1);
std::replace(initial.begin(),initial.end(),L'/',L'\\');
current_=fs::path(initial).lexically_normal();
if(current_.has_relative_path() && !current_.has_filename()) current_=current_.parent_path();
}
return current_;
}
void setDirectory(const fs::path &path)
{
if(current_==path) return;
checkFileOperation(FtpSetCurrentDirectoryA(handle(),encodeName(path).c_str()));
current_=path;
}
};
DWORD listFtpDirectory(FtpSession &session,const fs::path &directory,const FileVisitor &visit,
std::stop_token stop={})
{
if(stop.stop_requested()) return ERROR_CANCELLED;
session.setDirectory(directory);
if(stop.stop_requested()) return ERROR_CANCELLED;
WIN32_FIND_DATAA entry{};
const FtpHandle search{FtpFindFirstFileA(session.handle(),nullptr,&entry,
INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE,0)};
if(!search.value) return GetLastError();
do
{
const auto name=session.decodeName(entry.cFileName);
if(name.empty() || name==L"." || name==L".." || name.find_first_of(L"/\\:\r\n")!=name.npos)
continue;
ULARGE_INTEGER modified{}, size{};
FILETIME utc{};
if(LocalFileTimeToFileTime(&entry.ftLastWriteTime,&utc))
{
modified.HighPart=utc.dwHighDateTime;
modified.LowPart=utc.dwLowDateTime;
}
size.HighPart=entry.nFileSizeHigh;
size.LowPart=entry.nFileSizeLow;
if(!visit(directory/name,{entry.dwFileAttributes,size.QuadPart,modified.QuadPart}))
return ERROR_CANCELLED;
} while(!stop.stop_requested() && InternetFindNextFileA(search.value,&entry));
return stop.stop_requested()?ERROR_CANCELLED:GetLastError();
}
+210
View File
@@ -0,0 +1,210 @@
FileEntries ftpChildren(FtpSession &session,const fs::path &directory,const std::atomic_bool *canceled=nullptr)
{
FileEntries entries;
const auto error=listFtpDirectory(session,directory,[&](const fs::path &path,const FileInfo &info)
{
if(canceled && *canceled) return false;
entries.emplace_back(path,info);
return true;
});
requireFileOperation(error==ERROR_NO_MORE_FILES,error);
return entries;
}
std::optional<FileInfo> ftpEntry(const FileEntries &entries,const fs::path &path)
{
const auto entry=std::find_if(entries.begin(),entries.end(),
[&](const auto &item){return item.first==path;});
return entry==entries.end()?std::nullopt:std::optional<FileInfo>(entry->second);
}
void renameFtpEntry(FtpSession &ftp,const fs::path &source,const fs::path &target)
{
ftp.setDirectory(source.parent_path());
const auto oldName=ftp.encodeName(source.filename());
const auto newName=ftp.encodeName(target.filename());
checkFileOperation(FtpRenameFileA(ftp.handle(),oldName.c_str(),newName.c_str()));
}
struct CopyHost
{
std::optional<FilesConnection> files;
std::optional<FtpSession> ftp;
FileOperationElevation *elevation{};
fs::path listedDirectory;
FileEntries listedEntries;
CopyHost(const FilesPeer *peer,const std::optional<FtpProfile> &profile,FileOperationElevation *admin=nullptr)
{
if(profile) ftp.emplace(*profile);
else files.emplace(peer);
if(!peer && !profile) elevation=admin;
}
Json request(const Json &message,const ks::lan::FileProgress &progress={})
{
return elevation?elevation->call(*files,message,progress):files->call(message,progress);
}
const FileEntries &ftpListing(const fs::path &path,const std::atomic_bool &canceled)
{
if(path!=listedDirectory)
{
listedEntries=ftpChildren(*ftp,path,&canceled);
listedDirectory=path;
}
return listedEntries;
}
std::optional<FileInfo> stat(const fs::path &path,const std::atomic_bool &canceled)
{
return ftp?ftpEntry(ftpListing(path.parent_path(),canceled),path):statFile(request(fileRequest("stat",path)));
}
FileEntries children(const fs::path &path,const std::atomic_bool &canceled)
{
if(ftp) return ftpListing(path,canceled);
if(!elevation) return childrenOf(*files,path);
FileEntries entries;
elevation->list(*files,path,[&](const fs::path &child,const FileInfo &info)
{
if(canceled) return false;
entries.emplace_back(child,info);
return true;
});
return entries;
}
void makeDirectory(const fs::path &path)
{
if(!ftp)
{
checkFileReply(request(fileRequest("mkdir",path)));
return;
}
ftp->setDirectory(path.parent_path());
checkFileOperation(FtpCreateDirectoryA(ftp->handle(),ftp->encodeName(path.filename()).c_str()));
listedDirectory.clear();
}
void remove(const fs::path &path,bool permanent,DWORD attributes,bool readOnly)
{
if(ftp)
{
ftp->setDirectory(path.parent_path());
const auto name=ftp->encodeName(path.filename());
checkFileOperation(attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY)?
FtpRemoveDirectoryA(ftp->handle(),name.c_str()):FtpDeleteFileA(ftp->handle(),name.c_str()));
return;
}
auto message=fileRequest(permanent?"remove":"recycle",path);
message["readOnly"]=readOnly;
checkFileReply(request(message));
}
};
constexpr DWORD ftpCopyFlags=INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE;
void downloadFtpFile(FtpSession &ftp,FilesConnection &local,const fs::path &source,const fs::path &target,
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress)
{
ftp.setDirectory(source.parent_path());
const FtpHandle input{FtpOpenFileA(ftp.handle(),ftp.encodeName(source.filename()).c_str(),GENERIC_READ,ftpCopyFlags,0)};
checkFileOperation(input.value!=nullptr);
auto upload=fileRequest("openWrite",target);
upload["transfer"]=ks::lan::randomHex(32);
upload["size"]=info.size;
try
{
const auto output=local.call(upload);
checkFileReply(output);
requireFileOperation(output.value("offset",uint64_t{1})==0,ERROR_FILE_INVALID);
uint64_t done=0;
ks::Bytes bytes(ks::lan::FileChunk);
while(!progress || progress(done,info.size))
{
DWORD read{};
checkFileOperation(InternetReadFile(input.value,bytes.data(),static_cast<DWORD>(bytes.size()),&read));
if(!read)
{
requireFileOperation(done==info.size,ERROR_FILE_INVALID);
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
checkFileReply(local.call({{"action","commit"},{"replace",replace},{"modified",info.modified}}));
return;
}
requireFileOperation(read<=info.size-done,ERROR_FILE_INVALID);
checkFileReply(local.call({{"action","write"},
{"data",Json::binary(ks::Bytes(bytes.begin(),bytes.begin()+read))}}));
done+=read;
}
requireFileOperation(false,ERROR_CANCELLED);
}
catch(...)
{
local.call({{"action","abort"}});
throw;
}
}
FileInfo uploadFtpFile(FilesConnection &local,FtpSession &ftp,const fs::path &source,const fs::path &target,
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress,
const ks::files::RemoteTextRevision *expected=nullptr)
{
const auto directory=target.parent_path();
const auto temporary=directory/ks::wide("kswitcher-"+ks::lan::randomHex(16)+".partial");
auto open=fileRequest("openRead",source);
open["size"]=info.size;
open["modified"]=info.modified;
checkFileReply(local.call(open));
ftp.setDirectory(directory);
const auto stage=ftp.encodeName(temporary.filename());
bool staged=false;
try
{
uint64_t done=0;
{
FtpHandle output{FtpOpenFileA(ftp.handle(),stage.c_str(),GENERIC_WRITE,ftpCopyFlags,0)};
checkFileOperation(output.value!=nullptr);
staged=true;
for(;;)
{
requireFileOperation(progress(done,info.size),ERROR_CANCELLED);
const auto packet=local.call({{"action","read"}});
checkFileReply(packet);
const auto &bytes=packet.at("data").get_binary();
if(bytes.empty()) break;
requireFileOperation(bytes.size()<=info.size-done,ERROR_FILE_INVALID);
for(DWORD offset=0;offset<bytes.size();)
{
DWORD written{};
checkFileOperation(InternetWriteFile(output.value,bytes.data()+offset,
static_cast<DWORD>(bytes.size()-offset),&written));
requireFileOperation(written!=0,ERROR_WRITE_FAULT);
offset+=written;
}
done+=bytes.size();
}
requireFileOperation(done==info.size,ERROR_FILE_INVALID);
checkFileOperation(InternetCloseHandle(output.value));
output.value=nullptr;
}
checkFileReply(local.call({{"action","closeRead"}}));
const auto entries=ftpChildren(ftp,directory);
const auto uploaded=ftpEntry(entries,temporary);
requireFileOperation(uploaded && uploaded->size==done,ERROR_WRITE_FAULT);
const auto existing=ftpEntry(entries,target);
if(expected && (!existing || existing->size!=expected->size || existing->modified!=expected->modified))
throw std::runtime_error("The FTP file changed since it was opened. Your edits are still in the editor.");
if(existing)
requireFileOperation(replace && !(existing->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
ERROR_ALREADY_EXISTS);
requireFileOperation(progress(done,info.size),ERROR_CANCELLED);
renameFtpEntry(ftp,temporary,target);
return *uploaded;
}
catch(...)
{
if(staged) FtpDeleteFileA(ftp.handle(),stage.c_str());
throw;
}
}
+129
View File
@@ -0,0 +1,129 @@
namespace ftpDialog
{
constexpr int name=382, host=385, port=386, user=388, password=390, footer=391, legacy=392;
std::wstring trim(std::wstring value)
{
const auto first=value.find_first_not_of(L" \t\r\n");
if(first==value.npos) return {};
return value.substr(first,value.find_last_not_of(L" \t\r\n")-first+1);
}
struct Edit
{
FtpProfile profile;
std::optional<size_t> index;
};
INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" FTP connection ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
auto &profile=reinterpret_cast<Edit*>(lp)->profile;
prepareCopyDialog(dialog);
layoutDialogContent(dialog,381);
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL})
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
for(const auto id:{name,host,user,password})
SendDlgItemMessageW(dialog,id,EM_SETLIMITTEXT,255,0);
SendDlgItemMessageW(dialog,port,EM_SETLIMITTEXT,5,0);
SetDlgItemTextW(dialog,name,profile.name.c_str());
SetDlgItemTextW(dialog,host,profile.host.c_str());
SetDlgItemTextW(dialog,port,std::to_wstring(profile.port).c_str());
SetDlgItemTextW(dialog,user,profile.user.c_str());
installFarCheckbox(GetDlgItem(dialog,legacy),FarCheckboxSurface::gray);
CheckDlgButton(dialog,legacy,profile.legacyNames?BST_CHECKED:BST_UNCHECKED);
try
{
auto secret=ftpPassword(profile);
SetDlgItemTextW(dialog,password,secret.c_str());
SecureZeroMemory(secret.data(),secret.size()*sizeof(wchar_t));
}
catch(const std::exception &)
{
SetWindowTextW(GetDlgItem(dialog,389),L"&Password (re-enter to replace saved password)");
}
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &edit=*reinterpret_cast<Edit*>(GetWindowLongPtrW(dialog,DWLP_USER));
const auto invalid=[&](int field,const wchar_t *message)
{
showFilesNotice(dialog,message,L"FTP connection");
SetFocus(GetDlgItem(dialog,field));
return TRUE;
};
FtpProfile profile;
profile.legacyNames=IsDlgButtonChecked(dialog,legacy)==BST_CHECKED;
profile.name=trim(shortcutField(dialog,name));
if(profile.name.empty() || profile.name==L".." || profile.name.find_first_of(L"\r\n\t")!=profile.name.npos)
return invalid(name,L"Enter a name for this connection.");
for(size_t i=0;i<ftpProfiles.size();++i)
if(edit.index!=i && CompareStringOrdinal(ftpProfiles[i].name.c_str(),-1,profile.name.c_str(),-1,TRUE)==CSTR_EQUAL)
return invalid(name,L"A connection with this name already exists.");
profile.host=trim(shortcutField(dialog,host));
if(profile.host.empty() || profile.host.find_first_of(L" /\\@\t\r\n")!=profile.host.npos)
return invalid(host,L"Enter the server host name or IP address.");
const auto value=shortcutField(dialog,port);
const auto number=value.empty() || value.find_first_not_of(L"0123456789")!=value.npos?0:std::stoul(value);
if(!number || number>65535) return invalid(port,L"Enter a port from 1 to 65535.");
profile.port=static_cast<INTERNET_PORT>(number);
profile.user=shortcutField(dialog,user);
if(profile.user.find_first_of(L"\r\n")!=profile.user.npos)
return invalid(user,L"Enter the user name on one line.");
try
{
auto plain=shortcutField(dialog,password);
if(!plain.empty())
{
const auto start=reinterpret_cast<const unsigned char*>(plain.data());
ks::Bytes bytes(start,start+plain.size()*sizeof(wchar_t));
SecureZeroMemory(plain.data(),plain.size()*sizeof(wchar_t));
profile.secret=ks::protect(bytes);
SecureZeroMemory(bytes.data(),bytes.size());
}
auto updated=ftpProfiles;
if(edit.index) updated[*edit.index]=std::move(profile);
else updated.push_back(std::move(profile));
if(saveFtpProfiles(updated))
{
ftpProfiles=std::move(updated);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
}
catch(const std::exception &) {}
showFilesNotice(dialog,L"Could not save the FTP connection.",L"FTP connection");
return TRUE;
}
}
void editFtpProfile(Panel &panel,bool create)
{
ftpDialog::Edit edit;
if(!create)
{
const auto row=currentPanelRow(panel);
if(row<0 || static_cast<size_t>(row)>=ftpProfiles.size()) return;
edit.index=static_cast<size_t>(row);
edit.profile=ftpProfiles[*edit.index];
}
const auto owner=GetParent(panel.list);
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(112),owner,
ftpDialog::procedure,reinterpret_cast<LPARAM>(&edit))!=IDOK) return;
for(auto &other:panels)
{
if(!ftpProfileList(other) || other.scan.valid()) continue;
const auto selection=&other==&panel?ftpRoot/std::to_wstring(edit.index.value_or(ftpProfiles.size()-1)):fs::path{};
showFtpProfiles(other,selection);
}
}
+16
View File
@@ -0,0 +1,16 @@
#pragma once
#include <windows.h>
#include <string>
namespace ks::files
{
inline std::wstring historyDate()
{
SYSTEMTIME now{};
GetLocalTime(&now);
wchar_t date[24]{};
GetDateFormatEx(LOCALE_NAME_USER_DEFAULT,0,&now,L"dd.MM.yyyy",date,24,nullptr);
return date;
}
}
+69
View File
@@ -0,0 +1,69 @@
#pragma once
#include <windows.h>
#include <algorithm>
#include <string_view>
#include <windowsx.h>
namespace ks::files
{
inline COLORREF hoverSurface(COLORREF surface)
{
return RGB(3*GetRValue(surface)/4,3*GetGValue(surface)/4,3*GetBValue(surface)/4);
}
class InlineListAction
{
std::wstring_view label;
LRESULT pressedRow=LB_ERR;
public:
explicit InlineListAction(std::wstring_view text):label(text){}
RECT bounds(RECT row,int cellWidth) const
{
row.right-=2*cellWidth;
row.left=std::max(row.left,row.right-static_cast<LONG>(label.size()*cellWidth));
return row;
}
bool hit(HWND list,LRESULT row,LPARAM point,int cellWidth) const
{
RECT item{};
if(SendMessageW(list,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&item))==LB_ERR) return false;
const auto action=bounds(item,cellWidth);
return PtInRect(&action,{GET_X_LPARAM(point),GET_Y_LPARAM(point)});
}
void press(HWND list,LRESULT row)
{
pressedRow=row;
SetCapture(list);
}
bool pressed() const { return pressedRow!=LB_ERR; }
void cancel() { pressedRow=LB_ERR; }
bool release(HWND list,LRESULT row,bool overAction)
{
const bool activate=pressedRow==row && overAction;
cancel();
if(GetCapture()==list) ReleaseCapture();
return activate;
}
void paint(HDC dc,const RECT &action,int textInset,COLORREF ink,COLORREF surface,bool highlighted) const
{
SetTextColor(dc,ink);
SetBkColor(dc,highlighted?hoverSurface(surface):surface);
ExtTextOutW(dc,action.left,action.top+textInset,ETO_OPAQUE|ETO_CLIPPED,&action,
label.data(),static_cast<UINT>(label.size()),nullptr);
TEXTMETRICW metrics{};
GetTextMetricsW(dc,&metrics);
const LONG underline=std::min(action.bottom-1,action.top+textInset+metrics.tmAscent+1);
const RECT line{action.left,underline,action.right,underline+1};
SetDCBrushColor(dc,ink);
FillRect(dc,&line,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
}
};
}
+24
View File
@@ -1,6 +1,30 @@
#pragma once
#include <windows.h>
#include <filesystem>
#include <string_view>
inline constexpr ULONG_PTR FilesLanPeers = 0x4b53010d;
inline constexpr ULONG_PTR FilesLanPeersReply = 0x4b53010e;
inline constexpr DWORD FilesLanPeersLimit = 64 * 1024;
namespace ks
{
inline bool isFilesPeerImage(const std::filesystem::path &image, const std::filesystem::path &install)
{
if (_wcsicmp(image.filename().c_str(), L"KSwitcher.Files.exe") != 0) return false;
const auto directory = image.parent_path();
if (_wcsicmp(directory.c_str(), install.c_str()) == 0) return true;
// Updating moves a still-running Files executable into the transaction backup.
// Windows then reports the moved path for its process image.
if (_wcsicmp(directory.filename().c_str(), L"backup") != 0) return false;
const auto transaction = directory.parent_path();
if (_wcsicmp(transaction.parent_path().c_str(), install.c_str()) != 0) return false;
constexpr std::wstring_view prefix = L".kswitcher-update-";
const auto name = transaction.filename().wstring();
if (name.size() != prefix.size() + 32 || _wcsnicmp(name.c_str(), prefix.data(), prefix.size()) != 0)
return false;
return std::wstring_view(name).substr(prefix.size()).find_first_not_of(L"0123456789abcdefABCDEF")
== std::wstring_view::npos;
}
}
+251
View File
@@ -0,0 +1,251 @@
bool isSharingError(int error)
{
return error==ERROR_SHARING_VIOLATION || error==ERROR_LOCK_VIOLATION;
}
constexpr DWORD lockProbeShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
constexpr DWORD lockProbeFlags=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT;
DWORD probeDeleteAccess(const fs::path &path)
{
Handle probe{CreateFileW(path.c_str(),DELETE,lockProbeShare,nullptr,OPEN_EXISTING,lockProbeFlags,nullptr)};
return probe.value==INVALID_HANDLE_VALUE?GetLastError():ERROR_SUCCESS;
}
struct LockProcess
{
DWORD pid;
FILETIME started{};
std::wstring name;
};
struct LockScan
{
std::vector<LockProcess> processes;
bool incomplete{};
};
LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token stop)
{
LockScan result;
const auto query=reinterpret_cast<decltype(&NtQueryInformationFile)>(
GetProcAddress(GetModuleHandleW(L"ntdll.dll"),"NtQueryInformationFile"));
if(!query) { result.incomplete=true; return result; }
std::set<DWORD> pids;
std::vector<ULONG_PTR> buffer(128);
const auto inspect=[&](const fs::path &path) {
const auto error=probeDeleteAccess(path);
if(error==ERROR_SUCCESS) return;
if(!isSharingError(error))
{
if(error!=ERROR_FILE_NOT_FOUND && error!=ERROR_PATH_NOT_FOUND) result.incomplete=true;
return;
}
Handle file{CreateFileW(path.c_str(),0,lockProbeShare,nullptr,OPEN_EXISTING,lockProbeFlags,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) {result.incomplete=true;return;}
IO_STATUS_BLOCK status{};
// FileProcessIdsUsingFileInformation (47) returns an ULONG count followed by aligned ULONG_PTR PIDs.
auto code=query(file.value,&status,buffer.data(),static_cast<ULONG>(buffer.size()*sizeof(ULONG_PTR)),
static_cast<FILE_INFORMATION_CLASS>(47));
while((static_cast<ULONG>(code)==0xC0000023 || static_cast<ULONG>(code)==0x80000005 ||
static_cast<ULONG>(code)==0xC0000004) && buffer.size()<8192)
{
buffer.resize(buffer.size()*2);
code=query(file.value,&status,buffer.data(),static_cast<ULONG>(buffer.size()*sizeof(ULONG_PTR)),
static_cast<FILE_INFORMATION_CLASS>(47));
}
if(code<0 || status.Information<sizeof(ULONG_PTR)) {result.incomplete=true;return;}
ULONG count{};
memcpy(&count,buffer.data(),sizeof(count));
if(count>buffer.size()-1 || size_t(count)+1>status.Information/sizeof(ULONG_PTR))
{
result.incomplete=true;
return;
}
for(ULONG i=0;i<count;++i)
if(const auto pid=buffer[i+1];pid && pid<=MAXDWORD && pid!=GetCurrentProcessId())
pids.insert(static_cast<DWORD>(pid));
};
auto remaining=8192u;
const auto deadline=GetTickCount64()+4000;
for(const auto &path:paths)
{
if(stop.stop_requested()) return {};
inspect(path);
const auto attributes=GetFileAttributesW(path.c_str());
if(attributes==INVALID_FILE_ATTRIBUTES || !(attributes&FILE_ATTRIBUTE_DIRECTORY) ||
(attributes&FILE_ATTRIBUTE_REPARSE_POINT)) continue;
std::error_code error;
fs::recursive_directory_iterator it(path,error),end;
while(!error && it!=end)
{
if(stop.stop_requested()) return {};
if(!remaining || GetTickCount64()>=deadline) {result.incomplete=true;break;}
--remaining;
const auto item=it->path();
const auto flags=GetFileAttributesW(item.c_str());
if(flags==INVALID_FILE_ATTRIBUTES || flags&FILE_ATTRIBUTE_REPARSE_POINT)
it.disable_recursion_pending();
inspect(item);
it.increment(error);
}
if(error) result.incomplete=true;
}
for(const auto pid:pids)
{
Handle process{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,pid)};
LockProcess entry{pid};
if(process.value)
{
FILETIME exit{},kernel{},user{};
GetProcessTimes(process.value,&entry.started,&exit,&kernel,&user);
wchar_t path[32768];
DWORD count=std::size(path);
if(QueryFullProcessImageNameW(process.value,0,path,&count))
entry.name=fs::path(std::wstring_view(path,count)).filename().wstring();
}
if(entry.name.empty()) entry.name=L"Unknown process";
result.processes.push_back(std::move(entry));
}
return result;
}
struct LockDialog
{
std::vector<fs::path> paths;
std::vector<LockProcess> processes;
std::future<LockScan> scan;
std::stop_source stop;
};
constexpr UINT_PTR lockScanTimer=1;
void refreshLockProcesses(HWND window,LockDialog &state,std::shared_ptr<Handle> terminated={})
{
if(state.scan.valid()) return;
state.processes.clear();
SendDlgItemMessageW(window,431,LB_RESETCONTENT,0,0);
EnableWindow(GetDlgItem(window,433),FALSE);
EnableWindow(GetDlgItem(window,434),FALSE);
SetDlgItemTextW(window,430,L"Checking which processes are using the file or folder…");
try
{
std::packaged_task<LockScan()> task([paths=state.paths,stop=state.stop.get_token(),terminated=std::move(terminated)] {
if(terminated) WaitForSingleObject(terminated->value,2500);
return scanLockProcesses(paths,stop);
});
auto future=task.get_future();
if(!SetTimer(window,lockScanTimer,50,nullptr))
throw std::runtime_error("Could not start the process scan.");
std::thread(std::move(task)).detach();
state.scan=std::move(future);
}
catch(const std::exception &)
{
KillTimer(window,lockScanTimer);
EnableWindow(GetDlgItem(window,434),TRUE);
SetDlgItemTextW(window,430,L"Could not start the process scan.");
}
}
void endLockProcess(HWND window,LockDialog &state)
{
const auto index=SendDlgItemMessageW(window,431,LB_GETCURSEL,0,0);
if(index<0 || size_t(index)>=state.processes.size()) return;
const auto &entry=state.processes[index];
auto error=[&](const wchar_t *message) {
showFilesNotice(window,message,L"End process",{.tone=FilesNoticeTone::warning});
};
auto process=std::make_shared<Handle>();
process->value=OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,entry.pid);
FILETIME started{},exited{},kernel{},user{};
BOOL critical{};
if(!process->value || !(entry.started.dwHighDateTime || entry.started.dwLowDateTime) ||
!GetProcessTimes(process->value,&started,&exited,&kernel,&user) ||
CompareFileTime(&started,&entry.started)!=0 || !IsProcessCritical(process->value,&critical) || critical)
{
error(L"This process has exited, is protected, or cannot be identified.");
return;
}
const auto question=L"End "+entry.name+L" (PID "+std::to_wstring(entry.pid)+
L")?\r\nUnsaved work in the process may be lost.";
if(showFilesNotice(window,question.c_str(),L"End process",{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES)
return;
if(WaitForSingleObject(process->value,0)==WAIT_TIMEOUT && !TerminateProcess(process->value,1))
{
const auto message=ks::lastError(L"Could not end the process");
error(message.c_str());
return;
}
refreshLockProcesses(window,state,std::move(process));
}
INT_PTR CALLBACK lockProcessesDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(window,DWLP_USER,lp);
prepareCopyDialog(window);
for(const auto id:{430,431}) SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
const auto list=GetDlgItem(window,431);
RECT bounds{};
GetWindowRect(list,&bounds);
SetWindowPos(list,nullptr,0,0,std::max(1L,bounds.right-bounds.left-scrollBarWidth(list)),
bounds.bottom-bounds.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
installScrollBar(list,window);
layoutDialogButtons(window,432,{433,434,IDOK});
SendMessageW(window,DM_SETDEFID,IDOK,0);
SetFocus(GetDlgItem(window,IDOK));
refreshLockProcesses(window,*reinterpret_cast<LockDialog *>(lp));
return FALSE;
}
auto *data=reinterpret_cast<LockDialog *>(GetWindowLongPtrW(window,DWLP_USER));
if(!data) return FALSE;
auto &state=*data;
if(message==WM_TIMER && wp==lockScanTimer)
{
if(!state.scan.valid() || state.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready)
return TRUE;
KillTimer(window,lockScanTimer);
EnableWindow(GetDlgItem(window,434),TRUE);
try
{
auto result=state.scan.get();
for(auto &entry:result.processes)
{
const auto label=entry.name+L" (PID "+std::to_wstring(entry.pid)+L")";
if(SendDlgItemMessageW(window,431,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()))>=0)
state.processes.push_back(std::move(entry));
}
SetDlgItemTextW(window,430,state.processes.empty()?
(result.incomplete?L"No processes found. Some items could not be checked.":L"No locking processes found."):
(result.incomplete?L"Possible locking processes. The scan was incomplete.":L"Processes using locked files or folders."));
if(!state.processes.empty())
{
SendDlgItemMessageW(window,431,LB_SETCURSEL,0,0);
EnableWindow(GetDlgItem(window,433),TRUE);
}
}
catch(const std::exception &) {SetDlgItemTextW(window,430,L"Could not check for locking processes.");}
return TRUE;
}
if(message==WM_COMMAND)
{
switch(LOWORD(wp))
{
case 433: endLockProcess(window,state); return TRUE;
case 434: refreshLockProcesses(window,state); return TRUE;
case IDOK:
case IDCANCEL: FilesModalDialog::finish(window,IDCANCEL); return TRUE;
}
}
if(message==WM_CLOSE) {FilesModalDialog::finish(window,IDCANCEL);return TRUE;}
return paintCopyDialog(window,message,wp,lp,L" Locking processes ",false,{432},false,GetDlgItem(window,431));
}
void showLockProcesses(HWND owner,std::vector<fs::path> paths)
{
LockDialog state{std::move(paths)};
FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(609),owner,lockProcessesDialog,
reinterpret_cast<LPARAM>(&state));
state.stop.request_stop();
}
+4348 -966
View File
File diff suppressed because it is too large. Load diff
+18
View File
@@ -0,0 +1,18 @@
#pragma once
namespace ks::files
{
template<class Index, class Selectable>
Index adjacentMenuRow(Index current, Index size, int direction, Selectable selectable)
{
auto row=current;
for(Index visited=0;visited<size;++visited)
{
row+=direction;
if(row<0) row=size-1;
if(row>=size) row=0;
if(selectable(row)) return row;
}
return current;
}
}
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include <windows.h>
#include <string_view>
namespace ks::files
{
inline void paintMenuAccessKey(HDC dc, const RECT &clip, POINT origin, std::wstring_view title,
size_t access, COLORREF ink)
{
if (access >= title.size()) return;
SIZE prefix{};
GetTextExtentPoint32W(dc, title.data(), static_cast<int>(access), &prefix);
const auto background = SetBkMode(dc, TRANSPARENT);
const auto text = SetTextColor(dc, ink);
const auto alignment = SetTextAlign(dc, TA_LEFT | TA_TOP);
ExtTextOutW(dc, origin.x + prefix.cx, origin.y, ETO_CLIPPED, &clip, title.data() + access, 1, nullptr);
SetTextAlign(dc, alignment);
SetTextColor(dc, text);
SetBkMode(dc, background);
}
}
+494 -32
View File
@@ -1,7 +1,12 @@
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286;
constexpr int allOptions=4;
enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine };
constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line"};
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286,
optionsRemoteTerminal=370,optionsRemoteHibernate=371,optionsRemoteUpdate=372;
enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine, TextViewer, TextEditor, allOptions, CompareFiles };
constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line",
L"Viewer",L"Editor",L"All settings",L"File comparison"};
constexpr int comparisonFontLabel=408,comparisonChooseFont=409,comparisonColorCombo=411,
comparisonChooseColor=412,comparisonColorValue=413,comparisonShortcutControl=415;
constexpr int comparisonControls[]{comparisonFontLabel,comparisonChooseFont,410,comparisonColorCombo,
comparisonChooseColor,comparisonColorValue,414,comparisonShortcutControl};
constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Popup background",
L"Menu selection",L"Command bar",L"File cursor"};
enum PanelSection { PanelLayout, WideColumns, StatusColumns };
@@ -14,6 +19,28 @@ constexpr int appearanceControls[]{281,282};
enum AppearanceSection { Font, DialogFrame };
constexpr int outerFramePadding=303,innerFramePadding=305,rowTextPadding=307;
constexpr int dialogFrameControls[]{302,outerFramePadding,304,innerFramePadding,306,rowTextPadding};
constexpr int textTabWidth=357,textLineEnding=359,
textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368;
constexpr int textControls[]{350,351,352,353,356,textTabWidth,
362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme};
constexpr int editingControls[]{354,355,358,textLineEnding};
constexpr int markdownSection=1,markdownWidth=374,markdownFamily=376,markdownChoose=377,markdownSize=379;
constexpr int markdownControls[]{373,markdownWidth,375,markdownFamily,markdownChoose,378,markdownSize};
constexpr wchar_t optionsLocationKey[]=L"OptionsLocation";
constexpr struct
{
int id;
bool ks::files::TextPreferences::*value;
const wchar_t *name;
} textChecks[]{
{350,&ks::files::TextPreferences::wrap,L"Wrap lines"},
{351,&ks::files::TextPreferences::numbers,L"Line numbers"},
{352,&ks::files::TextPreferences::whitespace,L"Show whitespace and line endings"},
{353,&ks::files::TextPreferences::caretLine,L"Highlight current line"},
{354,&ks::files::TextPreferences::tabsAsSpaces,L"Insert spaces for tabs"},
{355,&ks::files::TextPreferences::autoIndent,L"Auto indent"}};
bool textOptionsPage(int page) { return page==TextViewer || page==TextEditor; }
constexpr struct
{
int id;
@@ -60,14 +87,23 @@ struct OptionsBaseline
std::array<COLORREF,ColorCount> palette=colors;
std::vector<FileStyle> styles=fileStyles;
std::array<WORD,2> keys=commandHistoryKeys;
bool remoteTerminal=ks::lan::remoteTerminalAllowed();
bool remoteHibernate=ks::lan::remoteHibernateAllowed();
bool remoteUpdate=ks::lan::remoteUpdateAllowed();
DWORD width=static_cast<DWORD>(sizeWidth), fields=statusFields;
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
std::array<bool,2> wide{panels[0].wide,panels[1].wide};
ks::files::TextSettings text=ks::files::loadTextPreferences();
ComparisonAppearance comparison=readComparisonAppearance();
WORD compareShortcut=comparisonShortcut;
};
struct OptionsDraft
{
OptionsBaseline baseline;
ks::files::TextSettings text=baseline.text;
ComparisonAppearance comparison=baseline.comparison;
HWND filesWindow{};
LOGFONTW font=displayFont;
int points=fontPoints;
DialogFramePadding framePadding=dialogFramePadding;
@@ -77,7 +113,9 @@ struct OptionsDraft
int styleIndex=0;
bool styleSuggestionsLoaded{};
int page=PanelModes, section=PanelLayout;
HTREEITEM wideColumnsNode{};
DWORD location{};
int markdownError{};
HTREEITEM wideColumnsNode{},markdownNode{};
RECT initialClient{};
UINT initialDpi=96;
OptionsControl controls[8]{
@@ -125,12 +163,16 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
DWORD fields=0;
for(int i=0;i<4;++i) if(checked(205+i)) fields|=1u<<i;
const auto &base=draft.baseline;
const bool dirty=!valid || width!=base.width ||
const bool dirty=!valid || draft.markdownError || width!=base.width ||
checked(273)!=base.wide[0] || checked(274)!=base.wide[1] ||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
optionHistoryKeys(dialog)!=base.keys;
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
checked(optionsRemoteHibernate)!=base.remoteHibernate ||
checked(optionsRemoteUpdate)!=base.remoteUpdate ||
draft.text!=base.text || draft.comparison!=base.comparison ||
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_GETHOTKEY,0,0)!=base.compareShortcut;
EnableWindow(GetDlgItem(dialog,optionsApply),dirty);
InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE);
}
@@ -192,22 +234,216 @@ void layoutOptions(HWND dialog,const OptionsDraft &draft)
SetWindowPos(GetDlgItem(dialog,control.id),nullptr,x,y,width,height,
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOREDRAW);
}
groupDialogButtons(dialog,{IDOK,IDCANCEL,optionsApply},true);
if(draft.page==PanelColors && draft.section==fileStyleSection) layoutFileStyleFields(dialog,false);
layoutOptionsPreview(dialog);
// Paint the final layout together, including the areas vacated by moved controls.
RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN|RDW_UPDATENOW);
}
void refreshTextColor(HWND dialog,const ks::files::TextPreferences &profile)
{
const auto index=SendDlgItemMessageW(dialog,textColor,CB_GETCURSEL,0,0);
if(index<0 || static_cast<size_t>(index)>=profile.colors.size()) return;
const auto color=profile.colors[index];
wchar_t hex[8]{};
swprintf_s(hex,L"#%02X%02X%02X",unsigned(GetRValue(color)),unsigned(GetGValue(color)),unsigned(GetBValue(color)));
SetDlgItemTextW(dialog,textColorValue,hex);
}
bool sameSchemeName(const std::wstring &left,const wchar_t *right)
{
return CompareStringOrdinal(left.c_str(),-1,right,-1,TRUE)==CSTR_EQUAL;
}
void populateTextSchemes(HWND dialog,const ks::files::TextSettings &settings)
{
SendDlgItemMessageW(dialog,textTheme,CB_RESETCONTENT,0,0);
const auto add=[&](const wchar_t *name)
{
SendDlgItemMessageW(dialog,textTheme,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
};
add(L"Custom");
for(const auto name:ks::files::textPaletteNames) add(name);
for(const auto &scheme:settings.schemes) add(scheme.name.c_str());
}
size_t currentTextScheme(const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
{
for(size_t index=0;index<std::size(ks::files::textPalettes);++index)
if(profile.scheme==ks::files::textPaletteNames[index] && profile.colors==ks::files::textPalettes[index])
return index+1;
for(size_t index=0;index<settings.schemes.size();++index)
{
const auto &scheme=settings.schemes[index];
if(profile.scheme==scheme.name && profile.colors==scheme.colors)
return std::size(ks::files::textPalettes)+index+1;
}
return 0;
}
INT_PTR CALLBACK schemeNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
SendDlgItemMessageW(dialog,100,EM_SETLIMITTEXT,ks::files::maxTextPaletteName,0);
groupDialogButtons(dialog,{IDOK,IDCANCEL},true);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
if(LOWORD(wp)==IDCANCEL) { FilesModalDialog::finish(dialog,IDCANCEL); return TRUE; }
if(LOWORD(wp)!=IDOK) return FALSE;
wchar_t text[ks::files::maxTextPaletteName+1]{};
GetDlgItemTextW(dialog,100,text,static_cast<int>(std::size(text)));
std::wstring name=text;
const auto first=name.find_first_not_of(L" \t");
if(first==name.npos) { MessageBeep(MB_ICONWARNING); return TRUE; }
*reinterpret_cast<std::wstring *>(GetWindowLongPtrW(dialog,DWLP_USER))=
name.substr(first,name.find_last_not_of(L" \t")-first+1);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files::TextPreferences &profile)
{
std::wstring name;
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(608),dialog,schemeNameDialog,
reinterpret_cast<LPARAM>(&name))!=IDOK) return;
if(sameSchemeName(name,L"Custom") || std::any_of(std::begin(ks::files::textPaletteNames),
std::end(ks::files::textPaletteNames),[&](const wchar_t *preset){return sameSchemeName(name,preset);}))
{
showFilesNotice(dialog,L"Choose a different name for your color scheme.",L"Save color scheme");
return;
}
const auto existing=std::find_if(settings.schemes.begin(),settings.schemes.end(),
[&](const auto &scheme){return sameSchemeName(name,scheme.name.c_str());});
if(existing!=settings.schemes.end())
{
if(showFilesNotice(dialog,L"Replace the saved scheme with the current colors?",L"Save color scheme",
{.confirm=true,.tone=FilesNoticeTone::neutral})!=IDYES) return;
existing->colors=profile.colors;
profile.scheme=existing->name;
}
else
{
if(settings.schemes.size()>=ks::files::maxTextPalettes)
{
showFilesNotice(dialog,L"The color scheme list is full.",L"Save color scheme");
return;
}
settings.schemes.push_back({name,profile.colors});
profile.scheme=std::move(name);
}
populateTextSchemes(dialog,settings);
}
void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
{
for(const auto &check:textChecks) CheckDlgButton(dialog,check.id,profile.*check.value?BST_CHECKED:BST_UNCHECKED);
SendDlgItemMessageW(dialog,textTabWidth,CB_SETCURSEL,profile.tabWidth-1,0);
SendDlgItemMessageW(dialog,textLineEnding,CB_SETCURSEL,profile.lineEnding,0);
SendDlgItemMessageW(dialog,textTheme,CB_SETCURSEL,currentTextScheme(settings,profile),0);
refreshTextColor(dialog,profile);
}
void showMarkdownOptions(HWND dialog,const ks::files::MarkdownPreferences &settings)
{
// SetDlgItemText sends EN_CHANGE synchronously, so take a snapshot first.
const auto values=settings;
SetDlgItemInt(dialog,markdownWidth,values.width,FALSE);
SetDlgItemInt(dialog,markdownSize,values.fontSize,FALSE);
SetDlgItemTextW(dialog,markdownFamily,values.font.c_str());
}
int readMarkdownOptions(HWND dialog,ks::files::MarkdownPreferences &settings)
{
BOOL widthValid{}, sizeValid{};
const auto width=GetDlgItemInt(dialog,markdownWidth,&widthValid,FALSE);
const auto size=GetDlgItemInt(dialog,markdownSize,&sizeValid,FALSE);
if(!widthValid || width>999999) return markdownWidth;
if(!sizeValid || size<8 || size>72) return markdownSize;
wchar_t font[LF_FACESIZE]{};
GetDlgItemTextW(dialog,markdownFamily,font,std::size(font));
settings={width,size,font};
return 0;
}
bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
{
if(!textOptionsPage(draft.page) || (draft.page==TextViewer && draft.section==markdownSection)) return false;
auto &profile=draft.text.profiles[draft.page==TextEditor];
const auto id=LOWORD(command);
const auto row=[&](int control){return SendDlgItemMessageW(dialog,control,CB_GETCURSEL,0,0);};
if(const auto check=std::find_if(std::begin(textChecks),std::end(textChecks),
[id](const auto &entry){return entry.id==id;});check!=std::end(textChecks))
profile.*check->value=IsDlgButtonChecked(dialog,id)==BST_CHECKED;
else if(id==textSaveScheme) saveTextSchemeDraft(dialog,draft.text,profile);
else if(id==textChangeColor)
{
const auto index=row(textColor);
if(index>=0 && static_cast<size_t>(index)<profile.colors.size())
choosePanelColor(dialog,profile.colors[index],draft.custom.data());
}
else if(HIWORD(command)==CBN_SELCHANGE)
{
const auto selected=row(id);
if(selected<0) return false;
switch(id)
{
case textColor: break;
case textTabWidth: profile.tabWidth=static_cast<int>(selected)+1; break;
case textLineEnding: profile.lineEnding=static_cast<int>(selected); break;
case textTheme:
if(selected==0) profile.scheme.clear();
else if(const auto scheme=static_cast<size_t>(selected-1);scheme<std::size(ks::files::textPalettes))
{
profile.scheme=ks::files::textPaletteNames[scheme];
profile.colors=ks::files::textPalettes[scheme];
}
else
{
const auto index=scheme-std::size(ks::files::textPalettes);
if(index>=draft.text.schemes.size()) return false;
profile.scheme=draft.text.schemes[index].name;
profile.colors=draft.text.schemes[index].colors;
}
break;
default: return false;
}
}
else return false;
showTextOptions(dialog,draft.text,profile);
updateOptionsApply(dialog,draft);
return true;
}
void showComparisonOptions(HWND dialog,const ComparisonAppearance &appearance)
{
const auto points=appearance.points;
const auto description=std::wstring(appearance.font.lfFaceName)+L" · "+std::to_wstring(points/10)+
(points%10?L"."+std::to_wstring(points%10):L"")+L" pt";
SetDlgItemTextW(dialog,comparisonFontLabel,description.c_str());
const auto index=SendDlgItemMessageW(dialog,comparisonColorCombo,CB_GETCURSEL,0,0);
if(index<0 || index>=CompareColorCount) return;
const auto color=appearance.palette[index];
wchar_t hex[8]{};
swprintf_s(hex,L"#%02X%02X%02X",unsigned(GetRValue(color)),unsigned(GetGValue(color)),unsigned(GetBValue(color)));
SetDlgItemTextW(dialog,comparisonColorValue,hex);
}
void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
{
draft.page=page;
draft.section=section;
const bool markdown=page==TextViewer && section==markdownSection;
const wchar_t *title=L"No matching settings";
if(page==allOptions) title=L"All settings";
else if(page>=0)
{
title=optionsTitles[page];
if(section>=0)
if(markdown) title=L"Markdown";
else if(section>=0 && !textOptionsPage(page) && page!=CompareFiles)
title=page==PanelModes?panelSectionNames[section]:page==PanelColors?
(section==fileStyleSection?L"File type styles":colorNames[section]):
page==CommandLine?L"Command history":section==DialogFrame?L"Dialog frame":L"Font";
@@ -238,14 +474,20 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
show(wideColumnControls,page==PanelModes && section==WideColumns);
show(statusColumnControls,page==PanelModes && section==StatusColumns);
show(appearanceControls,page==Appearance && section==Font);
show(comparisonControls,page==CompareFiles);
if(page==CompareFiles) showComparisonOptions(dialog,draft.comparison);
show(dialogFrameControls,page==Appearance && section==DialogFrame);
if(page==Appearance && section==DialogFrame)
{
for(const auto &option:frameOptions)
SendDlgItemMessageW(dialog,option.id,CB_SETCURSEL,draft.framePadding.*option.value,0);
}
constexpr int commandLineControls[]{320,321,322,323};
constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
show(commandLineControls,page==CommandLine && section==0);
show(markdownControls,markdown);
show(textControls,textOptionsPage(page) && !markdown);
show(editingControls,page==TextEditor);
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]);
const bool fileTypes=page==PanelColors && section==fileStyleSection;
constexpr int fileStyleControls[]{287,288,289,290,291,292,293,294,295,296,297,298,300,fileStyleState};
show(fileStyleControls,fileTypes);
@@ -304,20 +546,27 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
const int previousPage=draft.page,previousSection=draft.section;
TreeView_DeleteAllItems(tree);
draft.wideColumnsNode=nullptr;
draft.markdownNode=nullptr;
const auto root=add(L"All settings",allOptions,-1,TVI_ROOT);
HTREEITEM first{},selected{};
for(int page=PanelModes;page<=CommandLine;++page)
for(int page=PanelModes;page<=CompareFiles;++page)
{
if(page==allOptions) continue;
HTREEITEM category{};
const bool wholeCategory=matches(optionsTitles[page]) || (!query.empty() && matches(L"All settings"));
const auto addSection=[&](const wchar_t *label,int section,bool aliasMatches=false)
{
if(!wholeCategory && !aliasMatches && !matches(label)) return;
if(!category) category=add(optionsTitles[page],page,-1,root);
if(!category)
{
category=add(optionsTitles[page],page,-1,root);
if(page==previousPage && previousSection<0) selected=category;
}
const auto node=add(label,page,section,category);
if(!first) first=node;
if(page==previousPage && section==previousSection) selected=node;
if(page==PanelModes && section==WideColumns) draft.wideColumnsNode=node;
if(page==TextViewer && section==markdownSection) draft.markdownNode=node;
};
if(page==PanelModes)
{
@@ -336,7 +585,24 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
addSection(L"File type styles",fileStyleSection,extensionMatches || matches(L"System and hidden") ||
matches(L"Underline") || matches(L"Strikethrough") || matches(L"Foreground"));
}
else if(page==CommandLine) addSection(L"Command history",0,matches(L"Previous command"));
else if(page==CommandLine) addSection(L"Command history",0,
matches(L"Previous command") || matches(L"Allow paired PCs to run PowerShell commands here") ||
matches(L"Allow paired PCs to hibernate this PC") || matches(L"Allow paired PCs to update KSwitcher here"));
else if(page==CompareFiles)
addSection(L"Font and colors",0,matches(L"Compare files shortcut") || std::any_of(std::begin(comparisonColorNames),
std::end(comparisonColorNames),matches));
else if(textOptionsPage(page))
{
const bool propertyMatches=matches(L"Tab width") ||
matches(L"Color scheme") || matches(L"Save scheme") || matches(L"Customize colors") ||
(page==TextEditor && matches(L"Line endings for new lines")) ||
std::any_of(std::begin(textChecks),std::end(textChecks),[&](const auto &check)
{return (page==TextEditor || check.id<354) && matches(check.name);}) ||
std::any_of(std::begin(ks::files::textColorNames),std::end(ks::files::textColorNames),matches);
addSection(page==TextEditor?L"Editing and appearance":L"Viewing and appearance",0,propertyMatches);
if(page==TextViewer) addSection(L"Markdown",markdownSection,
matches(L"Maximum width") || matches(L"Full window") || matches(L"Font family") || matches(L"Font size"));
}
else
{
addSection(L"Font",Font,matches(L"Display font"));
@@ -370,11 +636,28 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
SetDlgItemInt(dialog,201,sizeWidth,FALSE);
SendDlgItemMessageW(dialog,201,EM_SETLIMITTEXT,2,0);
SendDlgItemMessageW(dialog,markdownWidth,EM_SETLIMITTEXT,6,0);
SendDlgItemMessageW(dialog,markdownSize,EM_SETLIMITTEXT,2,0);
SendDlgItemMessageW(dialog,markdownFamily,EM_SETLIMITTEXT,LF_FACESIZE-1,0);
showMarkdownOptions(dialog,draft.text.markdown);
for(const auto label:comparisonColorNames)
SendDlgItemMessageW(dialog,comparisonColorCombo,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
SendDlgItemMessageW(dialog,comparisonColorCombo,CB_SETCURSEL,0,0);
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETRULES,HKCOMB_NONE,HOTKEYF_SHIFT);
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,comparisonShortcut,0);
SendDlgItemMessageW(dialog,optionsSearch,EM_SETLIMITTEXT,255,0);
for(const auto &option:frameOptions)
for(DWORD value=0;value<=option.maximum;++value)
SendDlgItemMessageW(dialog,option.id,CB_ADDSTRING,0,
reinterpret_cast<LPARAM>(std::to_wstring(value).c_str()));
for(int width=1;width<=16;++width)
SendDlgItemMessageW(dialog,textTabWidth,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(std::to_wstring(width).c_str()));
for(const auto label:{L"Automatic",L"Windows (CRLF)",L"Unix (LF)",L"Classic Mac (CR)"})
SendDlgItemMessageW(dialog,textLineEnding,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
populateTextSchemes(dialog,draft.text);
for(const auto label:ks::files::textColorNames)
SendDlgItemMessageW(dialog,textColor,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label));
SendDlgItemMessageW(dialog,textColor,CB_SETCURSEL,0,0);
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
@@ -382,6 +665,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,274,panels[1].wide);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
setOptionHistoryKeys(dialog,commandHistoryKeys);
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed());
CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed());
filterOptions(dialog,draft);
updateOptionsApply(dialog,draft);
return TRUE;
@@ -416,15 +702,21 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
const auto &change=*reinterpret_cast<const NMTREEVIEWW*>(lp);
if(change.hdr.code==TVN_SELCHANGEDW && change.itemNew.hItem)
showOptionsPage(dialog,*draft,static_cast<int>(change.itemNew.lParam>>8),static_cast<int>(change.itemNew.lParam&255)-1);
{
const auto page=static_cast<int>(change.itemNew.lParam>>8);
if(page!=allOptions || !GetWindowTextLengthW(GetDlgItem(dialog,optionsSearch)))
draft->location=static_cast<DWORD>(change.itemNew.lParam);
showOptionsPage(dialog,*draft,page,static_cast<int>(change.itemNew.lParam&255)-1);
}
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
finishFilesDialog(dialog,IDCANCEL);
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
if(changeTextOption(dialog,*draft,wp)) return TRUE;
switch(LOWORD(wp))
{
case optionsSearch:
@@ -443,6 +735,49 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
showOptionsPage(dialog,*draft,Appearance,Font);
updateOptionsApply(dialog,*draft);
return TRUE;
case comparisonChooseFont:
if(chooseDisplayFont(dialog,draft->comparison.font,draft->comparison.points))
{
draft->comparison.font.lfHeight=draft->comparison.font.lfWidth=0;
showComparisonOptions(dialog,draft->comparison);
updateOptionsApply(dialog,*draft);
}
return TRUE;
case comparisonColorCombo:
if(HIWORD(wp)==CBN_SELCHANGE) showComparisonOptions(dialog,draft->comparison);
return TRUE;
case comparisonChooseColor:
{
const auto index=SendDlgItemMessageW(dialog,comparisonColorCombo,CB_GETCURSEL,0,0);
if(index>=0 && index<CompareColorCount &&
choosePanelColor(dialog,draft->comparison.palette[index],draft->custom.data()))
{
showComparisonOptions(dialog,draft->comparison);
updateOptionsApply(dialog,*draft);
}
return TRUE;
}
case markdownWidth: case markdownSize: case markdownFamily:
if(HIWORD(wp)==EN_CHANGE)
{
draft->markdownError=readMarkdownOptions(dialog,draft->text.markdown);
updateOptionsApply(dialog,*draft);
}
return TRUE;
case markdownChoose:
{
LOGFONTW font{};
const auto &settings=draft->text.markdown;
wcsncpy_s(font.lfFaceName,settings.font.empty()?L"Segoe UI":settings.font.c_str(),_TRUNCATE);
auto size=static_cast<int>(settings.fontSize)*10;
font.lfHeight=-MulDiv(size,GetDpiForWindow(dialog),720);
if(chooseDisplayFont(dialog,font,size,72))
{
SetDlgItemTextW(dialog,markdownFamily,font.lfFaceName);
SetDlgItemInt(dialog,markdownSize,(size+5)/10,FALSE);
}
return TRUE;
}
case outerFramePadding: case innerFramePadding: case rowTextPadding:
if(HIWORD(wp)==CBN_SELCHANGE)
{
@@ -494,7 +829,18 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
return TRUE;
case optionsReset:
if(draft->page==allOptions || draft->page==CommandLine) setOptionHistoryKeys(dialog,defaultHistoryKeys);
if(draft->page==allOptions || draft->page==CompareFiles)
{
draft->comparison=ComparisonAppearance{};
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,defaultComparisonShortcut,0);
}
if(draft->page==allOptions || draft->page==CommandLine)
{
setOptionHistoryKeys(dialog,defaultHistoryKeys);
CheckDlgButton(dialog,optionsRemoteTerminal,BST_UNCHECKED);
CheckDlgButton(dialog,optionsRemoteHibernate,BST_UNCHECKED);
CheckDlgButton(dialog,optionsRemoteUpdate,BST_UNCHECKED);
}
if(draft->page==allOptions || draft->page==PanelModes)
for(const auto &property:panelProperties)
if(draft->section<0 || property.section==draft->section) resetPanelProperty(dialog,property);
@@ -512,6 +858,12 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=Font))
draft->framePadding=defaultDialogFramePadding;
if(draft->page==allOptions || textOptionsPage(draft->page))
for(int page=TextViewer;page<=TextEditor;++page)
if(draft->page==allOptions || (draft->page==page && draft->section!=markdownSection))
draft->text.profiles[page==TextEditor]=ks::files::TextPreferences{};
if(draft->page==allOptions || (draft->page==TextViewer && (draft->section<0 || draft->section==markdownSection)))
showMarkdownOptions(dialog,ks::files::MarkdownPreferences{});
showOptionsPage(dialog,*draft,draft->page,draft->section);
updateOptionsApply(dialog,*draft);
return TRUE;
@@ -529,27 +881,45 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
case 201:
case 202: case 203: case 204: case 205: case 206: case 207: case 208:
case 273: case 274:
case 273: case 274: case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
updateOptionsApply(dialog,*draft);
return TRUE;
case 321: case 323:
case 321: case 323: case comparisonShortcutControl:
updateOptionsApply(dialog,*draft);
return TRUE;
case optionsApply:
case IDOK:
{
const auto compareShortcut=static_cast<WORD>(
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_GETHOTKEY,0,0));
if(!validComparisonShortcut(compareShortcut))
{
showFilesNotice(dialog,L"Choose Shift or Ctrl+Shift with a function key. Shift+F4 and Shift+F8 are reserved.",
optionsTitles[CompareFiles]);
if(IsWindowVisible(GetDlgItem(dialog,comparisonShortcutControl)))
SetFocus(GetDlgItem(dialog,comparisonShortcutControl));
return TRUE;
}
if(draft->markdownError)
{
if(!draft->markdownNode) SetDlgItemTextW(dialog,optionsSearch,L"");
TreeView_SelectItem(GetDlgItem(dialog,optionsTree),draft->markdownNode);
showFilesNotice(dialog,L"Enter a width in pixels (0 for full window) and a font size from 8 to 72 pt.",L"Markdown");
SetFocus(GetDlgItem(dialog,draft->markdownError));
return TRUE;
}
BOOL valid{};
const auto width=GetDlgItemInt(dialog,201,&valid,FALSE);
if(!valid || width<6 || width>16)
{
SetDlgItemTextW(dialog,optionsSearch,L"");
TreeView_SelectItem(GetDlgItem(dialog,optionsTree),draft->wideColumnsNode);
MessageBoxW(dialog,L"Enter a width from 6 to 16 characters.",optionsTitles[PanelModes],MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"Enter a width from 6 to 16 characters.",optionsTitles[PanelModes]);
SetFocus(GetDlgItem(dialog,201));
SendDlgItemMessageW(dialog,201,EM_SETSEL,0,-1);
return TRUE;
}
const auto owner=GetWindow(dialog,GW_OWNER);
const auto owner=draft->filesWindow;
const OptionsWriteLock writeLock;
if(!writeLock.acquired())
{
@@ -557,35 +927,96 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
}
const auto &base=draft->baseline;
const auto storedComparison=readComparisonAppearance();
const bool comparisonChanged=draft->comparison!=base.comparison;
if(comparisonChanged && storedComparison!=base.comparison && storedComparison!=draft->comparison)
{
showFilesNotice(dialog,L"Comparison settings changed in another window. Reopen Options before editing them again.",
optionsTitles[CompareFiles]);
return TRUE;
}
const bool textChanged=draft->text!=base.text;
auto textSettings=ks::files::loadTextPreferences();
if(draft->text.markdown!=base.text.markdown)
{
if(textSettings.markdown!=base.text.markdown && textSettings.markdown!=draft->text.markdown)
{
showFilesNotice(dialog,L"Markdown settings changed in another window. Reopen Options before editing them again.",
L"KSwitcher Files Options");
return TRUE;
}
textSettings.markdown=draft->text.markdown;
}
for(size_t i=0;i<textSettings.profiles.size();++i)
{
if(draft->text.profiles[i]==base.text.profiles[i]) continue;
if(textSettings.profiles[i]!=base.text.profiles[i] && textSettings.profiles[i]!=draft->text.profiles[i])
{
showFilesNotice(dialog,L"Text settings changed in another window. Reopen Options before editing them again.",
L"KSwitcher Files Options");
return TRUE;
}
textSettings.profiles[i]=draft->text.profiles[i];
}
if(draft->text.schemes!=base.text.schemes)
{
if(textSettings.schemes!=base.text.schemes && textSettings.schemes!=draft->text.schemes)
{
showFilesNotice(dialog,L"Color schemes changed in another window. Reopen Options before editing them again.",
L"KSwitcher Files Options");
return TRUE;
}
textSettings.schemes=draft->text.schemes;
}
auto keys=optionHistoryKeys(dialog);
loadCommandHistoryKeys();
for(size_t i=0;i<keys.size();++i)
if(keys[i]==base.keys[i]) keys[i]=commandHistoryKeys[i];
if(!validHistoryKeys(keys))
{
MessageBoxW(dialog,L"Choose distinct shortcuts using Ctrl or Alt that are free in Files.",L"Command history",MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"Choose distinct shortcuts using Ctrl or Alt that are free in Files.",L"Command history");
return TRUE;
}
const bool stylesChanged=draft->styles!=base.styles;
loadFileStyles();
if(stylesChanged && fileStyles!=base.styles && fileStyles!=draft->styles)
{
MessageBoxW(dialog,L"File type styles changed in another window. Reopen Options before editing them again.",
L"KSwitcher Files Options",MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"File type styles changed in another window. Reopen Options before editing them again.",
L"KSwitcher Files Options");
return TRUE;
}
if(stylesChanged && !saveFileStyles(draft->styles))
{
MessageBoxW(dialog,L"Could not save the file type styles.",L"KSwitcher Files Options",MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"Could not save the file type styles.",L"KSwitcher Files Options");
return TRUE;
}
const bool fontChanged=optionsFontChanged(*draft);
if(fontChanged && !applyFont(owner,draft->font,draft->points))
{
if(stylesChanged) saveFileStyles(fileStyles);
MessageBoxW(dialog,L"Could not apply the selected font.",optionsTitles[Appearance],MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"Could not apply the selected font.",optionsTitles[Appearance]);
return TRUE;
}
if(comparisonChanged && !saveComparisonAppearance(draft->comparison))
{
if(fontChanged) applyFont(owner,base.font,base.points);
if(stylesChanged) saveFileStyles(fileStyles);
showFilesNotice(dialog,L"Could not save comparison settings.",optionsTitles[CompareFiles]);
return TRUE;
}
if(textChanged)
{
try { ks::files::saveTextPreferences(textSettings); }
catch(const std::exception &error)
{
if(comparisonChanged) saveComparisonAppearance(storedComparison);
if(fontChanged) applyFont(owner,base.font,base.points);
if(stylesChanged) saveFileStyles(fileStyles);
const auto message=L"Could not save text settings. "+ks::wide(error.what());
showFilesNotice(dialog,message.c_str(),L"KSwitcher Files Options");
return TRUE;
}
}
const auto saveChanged=[](const wchar_t *name,DWORD value,DWORD initial)
{
if(value!=initial) savePreference(name,value);
@@ -594,6 +1025,10 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
const auto inputKeys=optionHistoryKeys(dialog);
saveChanged(L"PreviousCommandKey",inputKeys[0],base.keys[0]);
saveChanged(L"CommandHistoryKey",inputKeys[1],base.keys[1]);
saveChanged(comparisonShortcutKey,compareShortcut,base.compareShortcut);
saveChanged(ks::lan::remoteTerminalPreference,checked(optionsRemoteTerminal),base.remoteTerminal);
saveChanged(ks::lan::remoteHibernatePreference,checked(optionsRemoteHibernate),base.remoteHibernate);
saveChanged(ks::lan::remoteUpdatePreference,checked(optionsRemoteUpdate),base.remoteUpdate);
saveChanged(L"SizeWidth",width,base.width);
saveChanged(L"AlignExtensions",checked(202),base.extensions);
saveChanged(L"AlignFolders",checked(204),base.folders);
@@ -620,7 +1055,14 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
saveChanged(L"RightWide",checked(274),base.wide[1]);
loadFilesPreferences(owner);
notifyFilesPreferences(owner);
const auto dialogOwner=GetWindow(dialog,GW_OWNER);
if(dialogOwner!=owner)
SendMessageW(dialogOwner,filesPreferencesChanged,reinterpret_cast<WPARAM>(owner),0);
draft->baseline=OptionsBaseline{};
draft->text=draft->baseline.text;
draft->comparison=draft->baseline.comparison;
showMarkdownOptions(dialog,draft->text.markdown);
populateTextSchemes(dialog,draft->text);
draft->font=displayFont;
draft->points=fontPoints;
draft->styles=fileStyles;
@@ -634,13 +1076,17 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,274,panels[1].wide);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
setOptionHistoryKeys(dialog,commandHistoryKeys);
SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,comparisonShortcut,0);
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed());
CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed());
if(draft->page==PanelColors && draft->section==fileStyleSection)
updateFileStyleEditor(dialog,*draft,true);
showOptionsPage(dialog,*draft,draft->page,draft->section);
layout(owner);
showFileDetails(panels[active]);
RedrawWindow(owner,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN|RDW_UPDATENOW);
if(LOWORD(wp)==IDOK) finishFilesDialog(dialog,IDOK);
if(LOWORD(wp)==IDOK) FilesModalDialog::finish(dialog,IDOK);
else updateOptionsApply(dialog,*draft);
return TRUE;
}
@@ -648,13 +1094,29 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return FALSE;
}
void runOptions(HWND owner,int page)
{
OptionsDraft draft;
draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER);
const DWORD initial=static_cast<DWORD>((page<<8)|1);
const auto saved=preference(optionsLocationKey,initial);
draft.location=(saved>>8)<=CompareFiles?saved:initial;
draft.page=static_cast<int>(draft.location>>8);
draft.section=static_cast<int>(draft.location&255)-1;
std::copy(std::begin(colors),std::end(colors),draft.palette.begin());
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(101),owner,optionsDialog,
reinterpret_cast<LPARAM>(&draft));
if(result==-1) setStatus(L"Could not open Files Options.");
else savePreference(optionsLocationKey,draft.location);
}
void editOptions(HWND owner)
{
const auto panel=panels[active].list;
OptionsDraft draft;
std::copy(std::begin(colors),std::end(colors),draft.palette.begin());
const auto result=runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(101),owner,optionsDialog,
reinterpret_cast<LPARAM>(&draft));
SetFocus(panel);
if(result==-1) setStatus(L"Could not open Files Options.");
runOptions(owner,PanelModes);
SetFocus(panels[active].list);
}
void editTextOptions(HWND owner,bool edit)
{
runOptions(owner,edit?TextEditor:TextViewer);
}
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include <windows.h>
#include <string>
namespace ks::files
{
inline std::wstring windowsPowerShell()
{
wchar_t system[MAX_PATH]{};
const auto length=GetSystemDirectoryW(system,MAX_PATH);
return length && length<MAX_PATH
? std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe" : std::wstring{};
}
}
+99
View File
@@ -0,0 +1,99 @@
#pragma once
#include <windows.h>
#include <algorithm>
namespace ks::files
{
inline int scrollBarWidth(HWND window) {return std::max(7,MulDiv(12,GetDpiForWindow(window),96));}
inline int scrollArrowHeight(RECT bounds)
{
return std::min(bounds.right-bounds.left,(bounds.bottom-bounds.top)/3);
}
struct ScrollPosition
{
int count, visible, top;
int last() const {return std::max(0,count-visible);}
RECT thumb(RECT track) const
{
const auto arrow=scrollArrowHeight(track);
track.top+=arrow;
track.bottom-=arrow;
const int height=track.bottom-track.top;
if(height<=0 || !last()) return {};
const int size=std::clamp(MulDiv(height,visible,count),std::min(height,arrow),height);
track.top+=MulDiv(std::clamp(top,0,last()),height-size,last());
track.bottom=track.top+size;
return track;
}
int click(RECT track,int y) const
{
const auto arrow=scrollArrowHeight(track);
const auto grip=thumb(track);
const int delta=y<track.top+arrow?-1:y>=track.bottom-arrow?1:
y<grip.top?-visible:y>=grip.bottom?visible:0;
return std::clamp(top+delta,0,last());
}
int drag(RECT track,int y,int offset) const
{
const auto grip=thumb(track);
const auto arrow=scrollArrowHeight(track);
const auto travel=track.bottom-track.top-2*arrow-(grip.bottom-grip.top);
return travel>0?std::clamp(MulDiv(y-track.top-arrow-offset,last(),travel),0,last()):top;
}
};
inline void paintScrollBar(HDC dc,RECT track,ScrollPosition position,COLORREF background)
{
const auto brush=static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
SetDCBrushColor(dc,background);
FillRect(dc,&track,brush);
if(!position.last()) return;
const auto lighter=[&](int divisor){return RGB(GetRValue(background)+(257-GetRValue(background))/divisor,
GetGValue(background)+(257-GetGValue(background))/divisor,
GetBValue(background)+(257-GetBValue(background))/divisor);};
const auto ink=lighter(4),dots=lighter(7);
const int height=scrollArrowHeight(track);
struct
{
BITMAPINFOHEADER header{sizeof(BITMAPINFOHEADER),4,4,1,32,BI_RGB};
DWORD pixels[16]{};
} tile;
for(int y=0;y<4;++y)
for(int x=0;x<4;++x)
{
const auto color=y%2==0 && x%2==y/2?dots:background;
// DIB pixels are stored bottom-up in BGR order.
tile.pixels[(3-y)*4+x]=RGB(GetBValue(color),GetGValue(color),GetRValue(color));
}
if(const auto pattern=CreateDIBPatternBrushPt(&tile,DIB_RGB_COLORS))
{
const RECT channel{track.left,track.top+height,track.right,track.bottom-height};
POINT origin{};
SetBrushOrgEx(dc,channel.left,channel.top,&origin);
FillRect(dc,&channel,pattern);
SetBrushOrgEx(dc,origin.x,origin.y,nullptr);
DeleteObject(pattern);
}
SetDCBrushColor(dc,ink);
const auto thumb=position.thumb(track);
FillRect(dc,&thumb,brush);
const int middle=(track.left+track.right)/2;
const int radius=std::max(0,(height-3)/2);
for(int row=0;row<=radius;++row)
{
const int y=track.top+(height-radius-1)/2+row;
const int mirrored=track.bottom-1-(y-track.top);
const RECT up{middle-row,y,middle+row+1,y+1};
const RECT down{middle-row,mirrored,middle+row+1,mirrored+1};
FillRect(dc,&up,brush);
FillRect(dc,&down,brush);
}
}
}
+2 -2
View File
@@ -127,7 +127,7 @@ bool addFileStyle(HWND dialog,OptionsDraft &draft)
const auto extension=fileStyleExtension(input);
if(extension.empty())
{
MessageBoxW(dialog,L"Enter a file extension such as .txt.",L"File type styles",MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"Enter a file extension such as .txt.",L"File type styles");
SetFocus(GetDlgItem(dialog,fileStyleSuggestion));
return false;
}
@@ -138,7 +138,7 @@ bool addFileStyle(HWND dialog,OptionsDraft &draft)
{
if(draft.styles.size()>=64)
{
MessageBoxW(dialog,L"The profile can contain up to 64 file type rules.",L"File type styles",MB_OK|MB_ICONWARNING);
showFilesNotice(dialog,L"The profile can contain up to 64 file type rules.",L"File type styles");
return false;
}
draft.styles.push_back({extension});
+1
View File
@@ -128,6 +128,7 @@ struct FileRowStyle
{
COLORREF foreground,background;
unsigned decorations{};
bool operator==(const FileRowStyle &) const = default;
};
FileRowStyle resolveFileStyle(std::wstring_view extension,bool file,bool dimmed,bool protectedRow,
COLORREF foreground,COLORREF background,const std::vector<FileStyle> &styles=fileStyles,
+3 -4
View File
@@ -1,5 +1,6 @@
#pragma once
#include "files_powershell.h"
#include <mutex>
#include <string>
#include <thread>
@@ -50,10 +51,8 @@ public:
startup.lpAttributeList=attributes;
PROCESS_INFORMATION info{};
wchar_t command[]=L"powershell.exe -NoLogo -NoProfile -NoExit -Command \"Remove-Module PSReadLine -ErrorAction SilentlyContinue; function global:prompt { $location = Get-Location; $path = if ($location.Provider.Name -eq 'FileSystem') { [Uri]::EscapeDataString($location.ProviderPath) }; ([string][char]27) + ']633;ks-directory:' + $path + [char]7 + [char]27 + '[?25l' }; Clear-Host\"";
wchar_t system[MAX_PATH]{};
const auto length=GetSystemDirectoryW(system,MAX_PATH);
const auto shell=std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe";
const bool started=length && length<MAX_PATH &&
const auto shell=ks::files::windowsPowerShell();
const bool started=!shell.empty() &&
UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
console,sizeof(console),nullptr,nullptr) &&
CreateProcessW(shell.c_str(),command,nullptr,nullptr,FALSE,EXTENDED_STARTUPINFO_PRESENT,
+101 -25
View File
@@ -3,17 +3,24 @@
#ifdef __MINGW32__
__CRT_UUID_DECL(ICoreWebView2_3, 0xA0D6DF20, 0x3B92, 0x416D, 0xAA, 0x0C, 0x43, 0x7A, 0x9C, 0x72, 0x78, 0x57)
__CRT_UUID_DECL(ICoreWebView2Controller2, 0xc979903e, 0xd4ca, 0x4228, 0x92, 0xeb, 0x47, 0xee, 0x3f, 0xa9, 0x6e, 0xab)
__CRT_UUID_DECL(ICoreWebView2ControllerOptions3, 0xb32b191a, 0x8998, 0x57ca, 0xb7, 0xcb, 0xe0, 0x46, 0x17, 0xe4, 0xce, 0x4a)
__CRT_UUID_DECL(ICoreWebView2Environment10, 0xee0eb9df, 0x6f12, 0x46ce, 0xb5, 0x3f, 0x3f, 0x47, 0xb9, 0xc9, 0x28, 0xe0)
__CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler, 0x4e8a3389, 0xc9d8, 0x4bd2, 0xb6, 0xb5, 0x12, 0x4f, 0xee, 0x6c, 0xc1, 0x4d)
__CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler, 0x6c4819f3, 0xc9b7, 0x4260, 0x81, 0x27, 0xc9, 0xf5, 0xbd, 0xe7, 0xf6, 0x8c)
__CRT_UUID_DECL(ICoreWebView2WebMessageReceivedEventHandler, 0x57213f19, 0x00e6, 0x49fa, 0x8e, 0x07, 0x89, 0x8e, 0xa0, 0x1e, 0xcb, 0xd2)
__CRT_UUID_DECL(ICoreWebView2NewWindowRequestedEventHandler, 0xd4c185fe, 0xc81c, 0x4989, 0x97, 0xaf, 0x2d, 0x3f, 0xa7, 0xab, 0x56, 0x51)
__CRT_UUID_DECL(ICoreWebView2NavigationStartingEventHandler, 0x9adbe429, 0xf36d, 0x432b, 0x9d, 0xdc, 0xf8, 0x88, 0x1f, 0xbd, 0x76, 0xe3)
__CRT_UUID_DECL(ICoreWebView2AcceleratorKeyPressedEventHandler, 0xb29c7e28, 0xfa79, 0x41a8, 0x8e, 0x44, 0x65, 0x81, 0x1c, 0x76, 0xdc, 0xb2)
#endif
#include <wrl/client.h>
#include <filesystem>
#include <functional>
#include <memory>
#include <utility>
inline constexpr COLORREF terminalSurface=RGB(24,24,24);
template<class Interface, class... Args>
class TerminalCallback final : public Interface
{
@@ -50,13 +57,26 @@ class FilesTerminalView
{
Microsoft::WRL::ComPtr<ICoreWebView2Controller> controller;
Microsoft::WRL::ComPtr<ICoreWebView2> web;
HMODULE loader{};
std::shared_ptr<int> lifetime;
RECT bounds{};
bool ready{};
bool visible{};
int viewportHeight{};
bool waitForReady{};
public:
~FilesTerminalView() { close(); }
void focus()
{
if(controller) controller->MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC);
}
void post(const std::wstring &message)
{
if(ready) web->PostWebMessageAsString(message.c_str());
}
bool initialized() const { return ready; }
void enableTrace() { if(ready) web->PostWebMessageAsString(L"trace:on"); }
void enableTrace(bool output)
{
if(ready) web->PostWebMessageAsString(output?L"trace:output":L"trace:on");
}
void setFont(const LOGFONTW &font,int points)
{
if(!ready) return;
@@ -67,21 +87,27 @@ public:
}
void layout(HWND host,bool show,int fullHeight)
{
RECT area{};
GetClientRect(host,&area);
area.top=area.bottom-fullHeight;
layout(area,show);
}
void layout(RECT area,bool show)
{
bounds=area;
visible=show;
viewportHeight=fullHeight;
if(!controller) return;
RECT bounds{};
GetClientRect(host,&bounds);
bounds.top=bounds.bottom-viewportHeight;
RECT current{};
if(FAILED(controller->get_Bounds(&current)) || !EqualRect(&current,&bounds))
controller->put_Bounds(bounds);
const bool showController=show && (!waitForReady || ready);
BOOL currentVisibility{};
if(FAILED(controller->get_IsVisible(&currentVisibility)) || !!currentVisibility!=show)
controller->put_IsVisible(show);
if(FAILED(controller->get_IsVisible(&currentVisibility)) || !!currentVisibility!=showController)
controller->put_IsVisible(showController);
}
void close()
{
lifetime.reset();
if(controller) controller->Close();
web.Reset();
controller.Reset();
@@ -100,12 +126,13 @@ public:
}
return SUCCEEDED(web->PostWebMessageAsString(message.c_str()));
}
bool create(HWND host,std::function<void(const std::wstring&)> receive,std::function<void()> failed)
bool create(HWND host,std::function<void(const std::wstring&)> receive,std::function<void()> failed,
bool markdown=false,std::function<bool(UINT)> handleKey={})
{
wchar_t exe[MAX_PATH]{};
if(!GetModuleFileNameW(nullptr,exe,MAX_PATH)) return false;
const auto folder=std::filesystem::path(exe).parent_path();
loader=LoadLibraryExW((folder/L"WebView2Loader.dll").c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32);
static const auto loader=LoadLibraryExW((folder/L"WebView2Loader.dll").c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32);
if(!loader) return false;
using Create=HRESULT (STDAPICALLTYPE*)(PCWSTR,PCWSTR,ICoreWebView2EnvironmentOptions*,
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*);
@@ -115,23 +142,37 @@ public:
wchar_t local[MAX_PATH]{};
const auto length=GetEnvironmentVariableW(L"LOCALAPPDATA",local,MAX_PATH);
if(!length || length>=MAX_PATH) return false;
const auto profile=std::filesystem::path(local)/L"KSwitcher"/L"TerminalWebView";
const auto profile=std::filesystem::path(local)/L"KSwitcher"/(markdown?L"MarkdownWebView":L"TerminalWebView");
const auto origin=markdown?L"kswitcher-markdown.invalid":L"kswitcher-terminal.invalid";
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":L"/index.html");
const auto assets=folder/L"terminal";
if(markdown && !std::filesystem::exists(assets/L"markdown.html")) return false;
waitForReady=!markdown;
constexpr COREWEBVIEW2_COLOR background{
255,GetRValue(terminalSurface),GetGValue(terminalSurface),GetBValue(terminalSurface)};
lifetime=std::make_shared<int>(0);
const std::weak_ptr<int> alive=lifetime;
auto environment=terminalCallback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler,
HRESULT,ICoreWebView2Environment*>([=,this](HRESULT hr,ICoreWebView2Environment *env)
{
if(!IsWindow(host)) return S_OK;
if(alive.expired()) return S_OK;
if(FAILED(hr) || !env) { failed(); return S_OK; }
auto completed=terminalCallback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler,
HRESULT,ICoreWebView2Controller*>([=,this](HRESULT result,ICoreWebView2Controller *view)
{
if(!IsWindow(host)) return S_OK;
if(alive.expired()) return S_OK;
if(FAILED(result) || !view) { failed(); return S_OK; }
controller=view;
if(!markdown)
{
view->put_IsVisible(FALSE);
Microsoft::WRL::ComPtr<ICoreWebView2Controller2> colors;
if(SUCCEEDED(controller.As(&colors))) colors->put_DefaultBackgroundColor(background);
}
view->get_CoreWebView2(&web);
Microsoft::WRL::ComPtr<ICoreWebView2_3> mapped;
if(!web || FAILED(web.As(&mapped)) || FAILED(mapped->SetVirtualHostNameToFolderMapping(
L"kswitcher-terminal.invalid",assets.c_str(),COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_DENY)))
origin,assets.c_str(),COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_DENY)))
{ failed(); return S_OK; }
Microsoft::WRL::ComPtr<ICoreWebView2Settings> settings;
if(SUCCEEDED(web->get_Settings(&settings)))
@@ -141,14 +182,32 @@ public:
settings->put_AreHostObjectsAllowed(FALSE);
}
EventRegistrationToken token{};
auto navigation=terminalCallback<ICoreWebView2NavigationStartingEventHandler,
ICoreWebView2*,ICoreWebView2NavigationStartingEventArgs*>([](auto*,auto *args)
if(handleKey)
{
PWSTR uri{};
if(SUCCEEDED(args->get_Uri(&uri)))
auto accelerator=terminalCallback<ICoreWebView2AcceleratorKeyPressedEventHandler,
ICoreWebView2Controller*,ICoreWebView2AcceleratorKeyPressedEventArgs*>(
[alive,handleKey](auto*,auto *args)
{
COREWEBVIEW2_KEY_EVENT_KIND kind{};
UINT key{};
if(!alive.expired() && SUCCEEDED(args->get_KeyEventKind(&kind)) &&
(kind==COREWEBVIEW2_KEY_EVENT_KIND_KEY_DOWN ||
kind==COREWEBVIEW2_KEY_EVENT_KIND_SYSTEM_KEY_DOWN) &&
SUCCEEDED(args->get_VirtualKey(&key)) && handleKey(key))
args->put_Handled(TRUE);
return S_OK;
});
if(FAILED(view->add_AcceleratorKeyPressed(accelerator.Get(),&token)))
{ failed(); return S_OK; }
}
auto navigation=terminalCallback<ICoreWebView2NavigationStartingEventHandler,
ICoreWebView2*,ICoreWebView2NavigationStartingEventArgs*>([uri](auto*,auto *args)
{
PWSTR address{};
if(SUCCEEDED(args->get_Uri(&address)))
{
args->put_Cancel(wcscmp(uri,L"https://kswitcher-terminal.invalid/index.html")!=0);
CoTaskMemFree(uri);
args->put_Cancel(uri!=address);
CoTaskMemFree(address);
}
return S_OK;
});
@@ -158,12 +217,17 @@ public:
auto messages=terminalCallback<ICoreWebView2WebMessageReceivedEventHandler,
ICoreWebView2*,ICoreWebView2WebMessageReceivedEventArgs*>([=,this](auto*,auto *args)
{
if(alive.expired()) return S_OK;
PWSTR source{}, value{};
if(SUCCEEDED(args->get_Source(&source)) &&
wcscmp(source,L"https://kswitcher-terminal.invalid/index.html")==0 &&
uri==source &&
SUCCEEDED(args->TryGetWebMessageAsString(&value)))
{
if(wcscmp(value,L"ready")==0) ready=true;
if(!ready && wcscmp(value,L"ready")==0)
{
ready=true;
if(waitForReady) layout(bounds,visible);
}
if(ready) receive(value);
}
CoTaskMemFree(value);
@@ -173,11 +237,23 @@ public:
if(FAILED(web->add_NavigationStarting(navigation.Get(),&token)) ||
FAILED(web->add_NewWindowRequested(newWindow.Get(),&token)) ||
FAILED(web->add_WebMessageReceived(messages.Get(),&token)) ||
FAILED(web->Navigate(L"https://kswitcher-terminal.invalid/index.html")))
FAILED(web->Navigate(uri.c_str())))
failed();
layout(host,visible,viewportHeight);
layout(bounds,visible);
return S_OK;
});
if(!markdown)
{
Microsoft::WRL::ComPtr<ICoreWebView2Environment10> configurable;
Microsoft::WRL::ComPtr<ICoreWebView2ControllerOptions> options;
Microsoft::WRL::ComPtr<ICoreWebView2ControllerOptions3> colors;
if(SUCCEEDED(env->QueryInterface(IID_PPV_ARGS(&configurable))) &&
SUCCEEDED(configurable->CreateCoreWebView2ControllerOptions(&options)) &&
SUCCEEDED(options.As(&colors)) &&
SUCCEEDED(colors->put_DefaultBackgroundColor(background)) &&
SUCCEEDED(configurable->CreateCoreWebView2ControllerWithOptions(host,options.Get(),completed.Get())))
return S_OK;
}
if(FAILED(env->CreateCoreWebView2Controller(host,completed.Get()))) failed();
return S_OK;
});
+439
View File
@@ -0,0 +1,439 @@
#include "files_text_document.h"
#include <objbase.h>
#include <algorithm>
#include <stdexcept>
#include <system_error>
#include <utility>
#include <vector>
namespace ks::files
{
namespace
{
[[noreturn]] void fail(const char *operation)
{
throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), operation);
}
struct File
{
HANDLE handle = INVALID_HANDLE_VALUE;
~File() { if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle); }
HANDLE release() { return std::exchange(handle, INVALID_HANDLE_VALUE); }
};
struct PendingSave
{
std::filesystem::path path;
~PendingSave() { if (!path.empty()) DeleteFileW(path.c_str()); }
};
HANDLE openSource(const std::filesystem::path &path, bool editable)
{
const auto sharing = FILE_SHARE_READ | FILE_SHARE_DELETE | (editable ? 0 : FILE_SHARE_WRITE);
const auto result = CreateFileW(path.c_str(), GENERIC_READ, sharing,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (result == INVALID_HANDLE_VALUE) fail("Open file");
return result;
}
HANDLE trackReplacement(const std::filesystem::path &path)
{
// A metadata-only handle survives the rename without blocking ReplaceFile.
const auto handle=CreateFileW(path.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if(handle==INVALID_HANDLE_VALUE) fail("Track replacement file");
return handle;
}
uint64_t fileSize(HANDLE file)
{
LARGE_INTEGER size{};
if (!GetFileSizeEx(file, &size)) fail("Read file size");
return size.QuadPart;
}
void seek(HANDLE file, uint64_t offset)
{
LARGE_INTEGER position{};
position.QuadPart = static_cast<LONGLONG>(offset);
if (!SetFilePointerEx(file, position, nullptr, FILE_BEGIN)) fail("Seek");
}
std::string read(HANDLE file, uint64_t offset, size_t length)
{
if (!length) return {};
seek(file, offset);
std::string result(length, '\0');
DWORD count{};
if (!ReadFile(file, result.data(), static_cast<DWORD>(length), &count, nullptr)) fail("Read file");
if (count != length) throw std::runtime_error("The file ended unexpectedly.");
return result;
}
void write(HANDLE file, std::string_view bytes)
{
if (bytes.empty()) return;
DWORD written{};
if (!WriteFile(file, bytes.data(), static_cast<DWORD>(bytes.size()), &written, nullptr))
fail("Write file");
if (written != bytes.size()) throw std::runtime_error("The complete block could not be written.");
}
bool sameFile(HANDLE a, HANDLE b)
{
BY_HANDLE_FILE_INFORMATION first{}, second{};
if (!GetFileInformationByHandle(a, &first) || !GetFileInformationByHandle(b, &second))
fail("Check file identity");
return first.dwVolumeSerialNumber == second.dwVolumeSerialNumber &&
first.nFileIndexHigh == second.nFileIndexHigh && first.nFileIndexLow == second.nFileIndexLow;
}
std::filesystem::path temporaryPath(const std::filesystem::path &directory)
{
GUID id{};
wchar_t name[40]{};
if (FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id, name, 40))
throw std::runtime_error("Cannot create a temporary file name.");
return directory / (std::wstring(L".kswitcher-") + name + L".tmp");
}
std::filesystem::path createTemporary(const std::filesystem::path &directory, File &file, DWORD flags)
{
auto path = temporaryPath(directory);
file.handle = CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_NEW, flags, nullptr);
if (file.handle == INVALID_HANDLE_VALUE) fail("Create temporary file");
return path;
}
bool isUtf16(TextEncoding encoding)
{
return encoding==TextEncoding::utf16le || encoding==TextEncoding::utf16be;
}
std::string_view signature(TextEncoding encoding)
{
switch(encoding)
{
case TextEncoding::utf16le: return "\xff\xfe";
case TextEncoding::utf16be: return "\xfe\xff";
case TextEncoding::utf8: return "\xef\xbb\xbf";
default: return {};
}
}
std::wstring decodeMultibyte(std::string_view bytes,UINT codePage,DWORD flags)
{
const int length=static_cast<int>(bytes.size());
const auto required=MultiByteToWideChar(codePage,flags,bytes.data(),length,nullptr,0);
if(!required) fail("Decode text");
std::wstring units(required,L'\0');
if(!MultiByteToWideChar(codePage,flags,bytes.data(),length,units.data(),required)) fail("Decode text");
return units;
}
std::string encode(std::string_view utf8,TextEncoding encoding)
{
if(encoding==TextEncoding::utf8 || utf8.empty()) return std::string(utf8);
const auto units=decodeMultibyte(utf8,CP_UTF8,MB_ERR_INVALID_CHARS);
if(encoding==TextEncoding::windows1252)
{
BOOL substituted{};
const int length=static_cast<int>(units.size());
const auto required=WideCharToMultiByte(1252,WC_NO_BEST_FIT_CHARS,units.data(),length,
nullptr,0,nullptr,&substituted);
if(!required) fail("Encode Windows-1252");
if(substituted) throw std::runtime_error("Some characters cannot be saved as Windows-1252. Choose a Unicode encoding.");
std::string bytes(required,'\0');
if(!WideCharToMultiByte(1252,WC_NO_BEST_FIT_CHARS,units.data(),length,bytes.data(),required,nullptr,&substituted))
fail("Encode Windows-1252");
return bytes;
}
std::string bytes(units.size()*2,'\0');
const size_t low=encoding==TextEncoding::utf16le?0:1;
for(size_t i=0;i<units.size();++i)
{
bytes[2*i+low]=static_cast<char>(units[i]&0xff);
bytes[2*i+1-low]=static_cast<char>(units[i]>>8);
}
return bytes;
}
std::string convertLineEndings(std::string_view text,TextLineEnding ending)
{
if(ending==TextLineEnding::preserve) return std::string(text);
const std::string_view replacement=ending==TextLineEnding::crlf?"\r\n":ending==TextLineEnding::lf?"\n":"\r";
std::string result;
result.reserve(text.size());
for(size_t start=0;start<text.size();)
{
const auto next=text.find_first_of("\r\n",start);
result.append(text.substr(start,next==text.npos?text.npos:next-start));
if(next==text.npos) break;
result.append(replacement);
start=next+1;
if(text[next]=='\r' && start<text.size() && text[start]=='\n') ++start;
}
return result;
}
}
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding)
: path_(std::move(path)), editable_(editable)
{
if(path_.empty())
{
if(encoding!=TextEncoding::automatic) encoding_=encoding;
return;
}
File source{openSource(path_, editable)};
if (editable)
{
std::wstring resolved(32768, L'\0');
const auto length = GetFinalPathNameByHandleW(source.handle, resolved.data(),
static_cast<DWORD>(resolved.size()), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
if (length && length < resolved.size())
{
resolved.resize(length);
path_ = resolved;
}
}
size_ = fileSize(source.handle);
const auto prefix = read(source.handle, 0, static_cast<size_t>(std::min<uint64_t>(3, size_)));
if(encoding==TextEncoding::automatic)
{
encoding=TextEncoding::utf8;
for(const auto candidate:{TextEncoding::utf16le,TextEncoding::utf16be})
if(prefix.starts_with(signature(candidate))) encoding=candidate;
}
encoding_=encoding;
if(prefix.starts_with(signature(encoding_))) bom_=signature(encoding_).size();
if(isUtf16(encoding_) && size_%2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
source_ = source.release();
}
TextDocument::~TextDocument()
{
if (source_ != INVALID_HANDLE_VALUE) CloseHandle(source_);
if (spool_ != INVALID_HANDLE_VALUE) CloseHandle(spool_);
}
const wchar_t *TextDocument::encodingName() const
{
switch (encoding_)
{
case TextEncoding::utf16le: return L"UTF-16 LE";
case TextEncoding::utf16be: return L"UTF-16 BE";
case TextEncoding::windows1252: return L"Windows-1252";
default: return bom_ ? L"UTF-8 BOM" : L"UTF-8";
}
}
uint64_t TextDocument::pages() const
{
return std::max<uint64_t>(1, (size_ - bom_ + pageBytes - 1) / pageBytes);
}
uint64_t TextDocument::boundary(uint64_t page) const
{
if (!page) return bom_;
if (page >= pages()) return size_;
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
return boundary(page,source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_);
}
uint64_t TextDocument::boundary(uint64_t page,HANDLE source) const
{
if (!page) return bom_;
if (page >= pages()) return size_;
const auto offset = bom_ + page * pageBytes;
const auto unit = isUtf16(encoding_) ? 2u : 1u;
const auto sample = read(source, offset - unit,
static_cast<size_t>(std::min<uint64_t>(4096 + unit, size_ - offset + unit)));
const auto getUnit = [&](size_t i) -> unsigned {
const auto first = static_cast<unsigned char>(sample[i]);
if (unit == 1) return first;
const auto second = static_cast<unsigned char>(sample[i + 1]);
return encoding_ == TextEncoding::utf16le ? first | (second << 8) : (first << 8) | second;
};
if (getUnit(0) == '\n') return offset;
for (size_t i = unit; i + unit < sample.size(); i += unit)
if (getUnit(i) == '\n') return offset + i;
size_t i = unit;
if (encoding_ == TextEncoding::utf8)
{
// Advance past at most one UTF-8 code point, even on malformed input.
while (i < sample.size() && i <= 3 && (getUnit(i) & 0xc0) == 0x80) ++i;
}
else if (isUtf16(encoding_))
if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
if (i == unit && getUnit(0) == '\r' && getUnit(i) == '\n') i += unit;
return offset + i - unit;
}
std::string TextDocument::decode(std::string bytes) const
{
if (encoding_ == TextEncoding::utf8 || bytes.empty()) return bytes;
std::wstring units;
if(encoding_==TextEncoding::windows1252) units=decodeMultibyte(bytes,1252,0);
else
{
units.resize(bytes.size() / 2);
for (size_t i = 0; i < units.size(); ++i)
{
const auto a = static_cast<unsigned char>(bytes[2 * i]);
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
units[i] = static_cast<wchar_t>(encoding_ == TextEncoding::utf16le ? a | (b << 8) : (a << 8) | b);
}
}
const auto length = static_cast<int>(units.size());
const int required = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, nullptr, 0, nullptr, nullptr);
if (!required) fail("Decode UTF-16");
std::string result(required, '\0');
if (!WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, result.data(), required, nullptr, nullptr))
fail("Decode UTF-16");
return result;
}
std::string TextDocument::readPage(uint64_t page) const
{
if (const auto it = changes_.find(page); it != changes_.end())
return read(spool_, it->second.offset, it->second.size);
return readOriginal(page);
}
std::string TextDocument::readOriginal(uint64_t page) const
{
if(path_.empty()) return {};
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
const auto source=source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_;
const auto start = boundary(page,source);
return decode(read(source, start, static_cast<size_t>(boundary(page + 1,source) - start)));
}
void TextDocument::releaseReadHandle()
{
if(!editable_ && source_!=INVALID_HANDLE_VALUE)
CloseHandle(std::exchange(source_,INVALID_HANDLE_VALUE));
}
bool TextDocument::modifiedWith(uint64_t page, std::string_view current) const
{
const size_t changesOnPage = changes_.contains(page) ? 1 : 0;
return changes_.size() > changesOnPage || current != readOriginal(page);
}
void TextDocument::stage(uint64_t page, std::string_view utf8)
{
if (!editable_) throw std::logic_error("The file is open for viewing.");
if (utf8.size() > editLimit) throw std::runtime_error("The edit exceeds 8 MiB on this page.");
if (utf8 == readOriginal(page))
{
changes_.erase(page);
return;
}
if (spool_ == INVALID_HANDLE_VALUE)
{
wchar_t directory[32768]{};
const auto length = GetTempPathW(static_cast<DWORD>(std::size(directory)), directory);
if (!length || length >= std::size(directory)) fail("Locate temporary directory");
File file;
createTemporary(directory, file, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE);
spool_ = file.release();
}
seek(spool_, spoolSize_);
write(spool_, utf8);
changes_.insert_or_assign(page, Change{spoolSize_, utf8.size()});
spoolSize_ += utf8.size();
}
bool TextDocument::save()
{
if (!modified()) return true;
PendingSave pending;
File output;
pending.path = createTemporary(path_.parent_path(), output, FILE_ATTRIBUTE_NORMAL);
uint64_t written{};
const auto append = [&](std::string_view bytes) {
write(output.handle, bytes);
written += bytes.size();
};
const auto copyUntil = [&](uint64_t &offset, uint64_t end) {
while (offset < end)
{
const auto block = read(source_, offset, static_cast<size_t>(std::min(pageBytes, end - offset)));
append(block);
offset += block.size();
}
};
uint64_t offset{};
for (const auto &[page, change] : changes_)
{
copyUntil(offset, boundary(page));
append(encode(read(spool_, change.offset, change.size),encoding_));
offset = boundary(page + 1);
}
copyUntil(offset, size_);
if (!FlushFileBuffers(output.handle)) fail("Flush saved file");
CloseHandle(output.release());
File replacement{trackReplacement(pending.path)};
File current{openSource(path_, true)};
if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher.");
const auto backup = temporaryPath(path_.parent_path());
if (!ReplaceFileW(path_.c_str(), pending.path.c_str(), backup.c_str(), 0, nullptr, nullptr))
{
const auto error = GetLastError();
if (GetFileAttributesW(backup.c_str()) != INVALID_FILE_ATTRIBUTES &&
!MoveFileExW(backup.c_str(), path_.c_str(), MOVEFILE_WRITE_THROUGH))
{
const auto location = backup.u8string();
throw std::runtime_error("Could not restore the original name after a save error. The original is at " +
std::string(location.begin(), location.end()));
}
SetLastError(error);
fail("Replace original file");
}
pending.path.clear();
const auto newSource = ReOpenFile(replacement.handle, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, 0);
DeleteFileW(backup.c_str());
CloseHandle(source_);
source_ = newSource;
size_ = written;
changes_.clear();
if (spool_ != INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_, INVALID_HANDLE_VALUE));
spoolSize_ = 0;
return source_ != INVALID_HANDLE_VALUE;
}
bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
{
if(!path_.empty() || !editable_) throw std::logic_error("The document is not a new editable file.");
if(format.encoding==TextEncoding::automatic) format.encoding=TextEncoding::utf8;
const auto bytes=encode(convertLineEndings(readPage(0),format.lineEnding),format.encoding);
const auto bom=format.bom?signature(format.encoding):std::string_view{};
PendingSave pending;
File output;
pending.path=createTemporary(path.parent_path(),output,FILE_ATTRIBUTE_NORMAL);
write(output.handle,bom);
write(output.handle,bytes);
if(!FlushFileBuffers(output.handle)) fail("Flush saved file");
CloseHandle(output.release());
File replacement{trackReplacement(pending.path)};
if(!MoveFileExW(pending.path.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH)) fail("Create new file");
pending.path.clear();
path_=std::move(path);
encoding_=format.encoding;
bom_=bom.size();
size_=bom_+bytes.size();
changes_.clear();
if(spool_!=INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_,INVALID_HANDLE_VALUE));
spoolSize_=0;
source_=ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
return source_!=INVALID_HANDLE_VALUE;
}
}
+63
View File
@@ -0,0 +1,63 @@
#pragma once
#include <windows.h>
#include <cstdint>
#include <filesystem>
#include <map>
#include <string>
#include <string_view>
namespace ks::files
{
enum class TextEncoding { automatic, utf8, utf16le, utf16be, windows1252 };
enum class TextLineEnding { preserve, crlf, lf, cr };
struct TextSaveFormat
{
TextEncoding encoding=TextEncoding::utf8;
bool bom{};
TextLineEnding lineEnding=TextLineEnding::preserve;
};
class TextDocument
{
public:
static constexpr uint64_t pageBytes = 1024 * 1024;
static constexpr size_t editLimit = 8 * pageBytes;
explicit TextDocument(std::filesystem::path path, bool editable = true,
TextEncoding encoding=TextEncoding::automatic);
~TextDocument();
TextDocument(const TextDocument &) = delete;
TextDocument &operator=(const TextDocument &) = delete;
uint64_t pages() const;
uint64_t size() const { return size_; }
uint64_t boundary(uint64_t page) const;
std::string readPage(uint64_t page) const;
void releaseReadHandle();
void stage(uint64_t page, std::string_view utf8);
bool modified() const { return !changes_.empty(); }
bool modifiedWith(uint64_t page, std::string_view current) const;
bool save();
bool saveNew(std::filesystem::path path, TextSaveFormat format);
const wchar_t *encodingName() const;
TextEncoding encoding() const { return encoding_; }
private:
struct Change { uint64_t offset; size_t size; };
std::filesystem::path path_;
HANDLE source_ = INVALID_HANDLE_VALUE;
HANDLE spool_ = INVALID_HANDLE_VALUE;
uint64_t size_{}, spoolSize_{};
size_t bom_{};
TextEncoding encoding_ = TextEncoding::utf8;
bool editable_;
std::map<uint64_t, Change> changes_;
std::string decode(std::string bytes) const;
uint64_t boundary(uint64_t page,HANDLE source) const;
std::string readOriginal(uint64_t page) const;
};
}
+270
View File
@@ -0,0 +1,270 @@
#include "files_text_language.h"
#include "core.h"
#include <Sci_Position.h>
#include <ILexer.h>
#include <Lexilla.h>
#include <Scintilla.h>
#include <SciLexer.h>
#include <algorithm>
#include <cwctype>
namespace ks::files
{
namespace
{
constexpr char cpp[] = "alignas alignof asm auto bool break case catch char char8_t char16_t char32_t class concept const "
"consteval constexpr constinit const_cast continue co_await co_return co_yield decltype default delete do double "
"dynamic_cast else enum explicit export extern false float for friend goto if inline int long mutable namespace "
"new noexcept nullptr operator private protected public register reinterpret_cast requires return short signed "
"sizeof static static_assert static_cast struct switch template this thread_local throw true try typedef typeid "
"typename union unsigned using virtual void volatile wchar_t while import module";
constexpr char csharp[] = "abstract as async await base bool break byte case catch char checked class const continue "
"decimal default delegate do double else enum event explicit extern false file finally fixed float for foreach from "
"get global goto if implicit in init int interface internal is let lock long namespace new not null object operator "
"or out override partial private protected public readonly record ref required return sbyte sealed select set short "
"sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unmanaged unsafe "
"ushort using value var virtual void volatile when where while with yield";
constexpr char javascript[] = "abstract any as async await boolean break case catch class const continue debugger declare "
"default delete do else enum export extends false finally for from function get if implements import in infer "
"instanceof interface keyof let module namespace never new null number object of override private protected public "
"readonly return satisfies set static string super switch symbol this throw true try type typeof undefined unknown "
"using var void while with yield";
constexpr char java[] = "abstract assert boolean break byte case catch char class const continue default do double else "
"enum exports extends final finally float for if implements import instanceof int interface long module native new "
"non-sealed null open opens package permits private protected public record requires return sealed short static super "
"switch synchronized this throw throws transient true try var void volatile while yield false";
constexpr char sql[] = "add alter and any as asc begin between by case check column commit constraint create cross "
"database declare default delete desc distinct drop else end except exists fetch foreign from full function grant "
"group having in index inner insert intersect into is join left like limit merge not null offset on or order outer "
"over partition primary procedure references returning right rollback row select set table then top transaction "
"truncate union unique update using values view when where window with";
constexpr char python[] = "and as assert async await break class continue def del elif else except False finally for from "
"global if import in is lambda match case None nonlocal not or pass raise return True try while with yield";
constexpr char ps[] = "begin break catch class continue data define do dynamicparam else elseif end enum exit filter finally "
"for foreach from function if in param process return switch throw trap try until using var while workflow";
constexpr char shell[] = "alias bg break case cd continue declare do done echo elif else esac eval exec exit export "
"false fi for function if in local read readonly return select set shift source test then time trap true type "
"typeset ulimit umask unalias unset until wait while";
constexpr char rust[] = "as async await break const continue crate dyn else enum extern false fn for if impl in let loop "
"match mod move mut pub ref return self Self static struct super trait true type unsafe use where while";
constexpr char go[] = "break case chan const continue default defer else fallthrough for func go goto if import interface "
"map package range return select struct switch type var nil false true";
constexpr char lua[] = "and break do else elseif end false for function goto if in local nil not or repeat return then true until while";
constexpr char ruby[] = "BEGIN END alias and begin break case class def defined do else elsif end ensure false for if in "
"module next nil not or redo rescue retry return self super then true undef unless until when while yield";
constexpr char html[] = "a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption "
"cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer "
"form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd label legend li link main map mark "
"menu meta meter nav noscript object ol optgroup option output p picture pre progress q rp rt ruby s samp script "
"search section select slot small source span strong style sub summary sup table tbody td template textarea tfoot "
"th thead time title tr track u ul var video wbr accept action alt aria-label async cellpadding charset checked cite "
"class content controls defer disabled for height href http-equiv id lang maxlength method multiple name placeholder "
"readonly rel required role rows scope selected src srcset style tabindex target type value width";
struct Mapping
{
std::wstring_view names;
const char *lexer;
const char *keywords = "";
};
constexpr Mapping languages[] = {
{L".c .h .cc .cpp .cxx .hh .hpp .hxx .inl .ipp .ixx .cppm .cu .cuh .m .mm .rc .idl .ino", "cpp", cpp},
{L".cs .csx .razor.cs", "cpp", csharp},
{L".js .jsx .mjs .cjs .ts .tsx .mts .cts .es", "cpp", javascript},
{L".java .pde", "cpp", java},
{L".kt .kts", "cpp", "abstract actual as break by catch class companion const constructor continue data do else enum "
"expect false finally for fun if import in init interface internal is lateinit null object open operator out "
"override package private protected public return sealed super suspend this throw true try typealias val var when while"},
{L".glsl .vert .frag .geom .hlsl .fx .metal", "cpp", cpp},
{L".html .htm .xhtml .shtml .vue .svelte .astro .cshtml .razor .aspx .jsp .php .phtml", "hypertext", html},
{L".xml .xsl .xslt .xsd .svg .resx .xaml .csproj .fsproj .vbproj .vcxproj .props .targets .config .nuspec "
L".wixproj .wxs .plist .rss .atom .gpx .kml .ui .iml .wsdl .manifest .slnx .axaml", "xml"},
{L".css .scss .sass .less", "css", "color background display position width height margin padding border font "
"grid flex content gap box-shadow transform animation opacity overflow text-align align-items justify-content"},
{L".sql .psql .ddl .dml .mysql", "sql", sql},
{L".py .pyw .pyi .rpy sconstruct sconscript", "python", python},
{L".json .jsonc .json5 .ipynb .webmanifest .geojson .topojson .code-workspace .sublime-settings .sublime-project",
"json", "false null true Infinity NaN"},
{L".yaml .yml .eyaml .clang-format .clang-tidy", "yaml", "true false null yes no on off"},
{L".toml pipfile uv.lock cargo.lock poetry.lock", "toml", "true false"},
{L".md .markdown .mdown .mkd .mdx readme", "markdown"},
{L".adoc .asciidoc", "asciidoc"},
{L".ini .cfg .conf .properties .url .inf .reg .editorconfig .gitconfig .gitattributes .gitmodules .npmrc .env", "props"},
{L".sh .bash .zsh .ksh .bats .bashrc .bash_profile .zshrc .profile configure gradlew mvnw", "bash", shell},
{L".ps1 .psm1 .psd1", "powershell", ps},
{L".bat .cmd", "batch", "call cd chdir cls copy del dir echo endlocal exit for goto if md mkdir move path pause popd "
"pushd rd rem ren rename set setlocal shift start title type"},
{L".cmake cmakelists.txt", "cmake", "add_executable add_library add_subdirectory cmake_minimum_required "
"configure_file else elseif endforeach endfunction endif endwhile file find_package foreach function if include "
"install list message option project set string target_compile_definitions target_include_directories "
"target_link_libraries unset while"},
{L".mk .mak makefile gnumakefile", "makefile"},
{L".rs", "rust", rust}, {L".go", "cpp", go}, {L".lua", "lua", lua}, {L".rb .rake .gemspec gemfile rakefile", "ruby", ruby},
{L".dart", "dart", "abstract as assert async await break case class const continue default do else enum extends "
"false final finally for if implements import in interface late mixin new null on override return sealed static "
"super switch this throw true try typedef var void while with yield"},
{L".swift", "cpp", "actor as associatedtype await break case catch class continue default defer deinit do else "
"enum extension false for func guard if import in init let nil private protocol public return self some "
"static struct super switch throw throws true try typealias var where while"},
{L".zig", "zig"}, {L".d .di", "d"}, {L".nim .nims .nimble", "nim"},
{L".fs .fsi .fsx", "fsharp"}, {L".ml .mli", "caml"}, {L".sml .sig", "SML"},
{L".vb .bas .frm .cls", "vb", "as byref byval class const dim each else elseif end enum for function if implements "
"imports inherits interface module new next nothing private property public return select shared sub then try while"},
{L".vbs", "vbscript"}, {L".pl .pm .t", "perl"}, {L".r .rprofile", "r"},
{L".jl", "julia"}, {L".matlab", "matlab"}, {L".oct", "octave"},
{L".tex .sty .ltx", "latex"}, {L".bib", "bib"}, {L".hs", "haskell"}, {L".lhs", "literatehaskell"},
{L".lisp .lsp .cl .el .scm .ss .rkt", "lisp"},
{L".s .asm .nasm .inc", "asm"}, {L".a68k", "a68k"},
{L".v .vh .sv .svh", "verilog"}, {L".vhd .vhdl", "vhdl"},
{L".f .for .f77", "f77"}, {L".f90 .f95 .f03 .f08", "fortran"},
{L".ada .adb .ads", "ada"}, {L".pas .pp .dpr", "pascal"}, {L".cob .cbl .cpy", "COBOL"},
{L".tcl .tk", "tcl"}, {L".coffee .litcoffee", "coffeescript"}, {L".au3", "au3"},
{L".st", "smalltalk"}, {L".erl .hrl", "erlang"},
{L".purs", "haskell"}, {L".diff .patch", "diff"}, {L".po .pot", "po"},
{L".iss", "inno"}, {L".nsi .nsh", "nsis"}, {L".idl3 .odl", "cpp", cpp},
{L".dmap", "DMAP"}, {L".dns .zone", "props"}, {L".ihex .hex", "ihex"}, {L".srec .s19 .s28 .s37", "srec"},
{L".edifact .edi", "edifact"}, {L".x12", "x12"}, {L".g4", "cpp", java},
{L".nix", "nix"}, {L".gd", "gdscript", python}, {L".il", "cil"}, {L".as", "cpp", javascript},
{L".frt .fth", "forth"}, {L".e .eif", "eiffel"}, {L".pov .povray", "pov"},
{L".rebol .reb", "rebol"}, {L".asn .asn1", "asn1"}, {L".asy", "asy"},
{L".raku .rakumod .rakutest .p6 .pm6", "raku"}, {L".bb", "blitzbasic"}, {L".bi", "freebasic"},
{L".t2t", "txt2tags"}, {L".troff .roff .man", "troff"},
{L".clw", "clarion"}, {L".spice .cir", "spice"},
};
bool containsWord(std::wstring_view words, std::wstring_view key)
{
if (key.empty()) return false;
for (size_t start = 0; start < words.size();)
{
const auto end = words.find(L' ', start);
if (words.substr(start, end == words.npos ? end : end - start) == key) return true;
if (end == words.npos) break;
start = end + 1;
}
return false;
}
}
TextLanguage detectLanguage(const std::filesystem::path &path, std::string_view firstPage)
{
auto filename = path.filename().wstring();
auto extension = path.extension().wstring();
for (auto *value : {&filename, &extension})
std::transform(value->begin(), value->end(), value->begin(), [](wchar_t ch) { return std::towlower(ch); });
for (const auto &language : languages)
if (containsWord(language.names, filename) || containsWord(language.names, extension))
return {language.lexer, language.keywords};
if (filename.starts_with(L".env.") || extension == L".env") return {"props"};
if (firstPage.starts_with("<?xml")) return {"xml"};
if (firstPage.starts_with("#!"))
{
const auto line = firstPage.substr(0, firstPage.find_first_of("\r\n"));
for (const auto &[needle, language] : {std::pair{"python", TextLanguage{"python", python}},
{"ruby", {"ruby", ruby}}, {"node", {"cpp", javascript}}, {"perl", {"perl"}},
{"pwsh", {"powershell", ps}}, {"lua", {"lua", lua}}, {"sh", {"bash", shell}}})
if (line.find(needle) != line.npos) return language;
}
return {};
}
std::wstring textLanguageLabel(const TextLanguage &language)
{
if (language.keywords == csharp) return L"C#";
if (language.keywords == javascript) return L"JavaScript / TypeScript";
if (language.keywords == java) return L"Java";
if (language.keywords == go) return L"Go";
if (language.lexer == "cpp") return L"C-family";
if (language.lexer == "hypertext") return L"HTML";
return language.lexer.empty() ? L"Plain text" : wide(language.lexer);
}
Scintilla::ILexer5 *createTextLexer(const TextLanguage &language)
{
if (language.lexer.empty()) return nullptr;
auto *lexer = CreateLexer(language.lexer.c_str());
if (!lexer) return nullptr;
const auto *keywords = language.keywords;
if (!*keywords)
for (const auto &mapping : languages)
if (language.lexer == mapping.lexer && *mapping.keywords)
{
keywords = mapping.keywords;
break;
}
if (*keywords) lexer->WordListSet(0, keywords);
if (language.lexer == "hypertext") lexer->WordListSet(1, javascript);
if (language.lexer == "json") lexer->PropertySet("lexer.json.allow.comments", "1");
if (language.lexer == "cpp" && (language.keywords == javascript || language.keywords == go))
{
lexer->PropertySet("lexer.cpp.backquoted.strings", language.keywords == javascript ? "2" : "1");
if (language.keywords == javascript) lexer->PropertySet("lexer.cpp.regex", "1");
}
if (language.lexer == "cpp" && language.keywords == csharp)
lexer->PropertySet("lexer.cpp.triplequoted.strings", "1");
return lexer;
}
TextColor syntaxColor(Scintilla::ILexer5 &lexer, std::string_view name, int style)
{
if (!style || (style >= STYLE_DEFAULT && style <= STYLE_LASTPREDEFINED)) return TextColor::text;
const auto *styleTags = lexer.TagsOfStyle(style);
const auto *styleName = lexer.NameOfStyle(style);
const std::string_view tags = styleTags ? styleTags : "";
const std::string_view token = styleName ? styleName : "";
const auto has = [&](std::string_view word) {
return tags.find(word) != tags.npos || token.find(word) != token.npos;
};
if (has("comment")) return TextColor::comment;
if (has("string") || has("character") || has("quoted") || has("regex")) return TextColor::string;
if (has("number") || has("numeric")) return TextColor::number;
if (has("keyword") || has("command") || has("tag") || has("heading") || has("header") ||
has("preprocessor") || has("keywordclass")) return TextColor::keyword;
if (has("operator") || has("attribute") || has("property") || has("variable") || has("label"))
return TextColor::symbol;
if (name == "markdown")
{
if (style >= SCE_MARKDOWN_HEADER1 && style <= SCE_MARKDOWN_HEADER6) return TextColor::keyword;
if (style >= SCE_MARKDOWN_CODE && style <= SCE_MARKDOWN_CODEBK) return TextColor::string;
return TextColor::symbol;
}
if (name == "diff")
{
if (style == SCE_DIFF_ADDED) return TextColor::string;
if (style == SCE_DIFF_DELETED) return TextColor::number;
if (style == SCE_DIFF_COMMENT) return TextColor::comment;
return TextColor::keyword;
}
if (name == "sql")
{
if (style >= SCE_SQL_COMMENT && style <= SCE_SQL_COMMENTDOC) return TextColor::comment;
if (style == SCE_SQL_NUMBER) return TextColor::number;
if (style == SCE_SQL_WORD || style == SCE_SQL_WORD2) return TextColor::keyword;
if (style == SCE_SQL_STRING || style == SCE_SQL_CHARACTER) return TextColor::string;
}
if (name == "json")
{
if (style == SCE_JSON_LINECOMMENT || style == SCE_JSON_BLOCKCOMMENT) return TextColor::comment;
if (style == SCE_JSON_STRING || style == SCE_JSON_STRINGEOL) return TextColor::string;
if (style == SCE_JSON_NUMBER) return TextColor::number;
if (style == SCE_JSON_KEYWORD || style == SCE_JSON_LDKEYWORD) return TextColor::keyword;
}
if (name == "css")
{
if (style == SCE_CSS_COMMENT) return TextColor::comment;
if (style == SCE_CSS_DOUBLESTRING || style == SCE_CSS_SINGLESTRING || style == SCE_CSS_VALUE)
return TextColor::string;
if (style == SCE_CSS_TAG || style == SCE_CSS_DIRECTIVE) return TextColor::keyword;
}
if (name == "yaml" || name == "toml")
{
// The two lexers assign the same IDs to these categories.
if (style == SCE_YAML_COMMENT) return TextColor::comment;
if (style == SCE_YAML_KEYWORD) return TextColor::keyword;
if (style == SCE_YAML_NUMBER) return TextColor::number;
}
if (token.empty()) return TextColor::symbol;
return TextColor::text;
}
}
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include <filesystem>
#include <string>
#include <string_view>
namespace Scintilla { class ILexer5; }
namespace ks::files
{
enum class TextColor { background, text, chromebg, chrome, selection, comment, keyword, string, number, symbol,
menuText, menuHighlight, menuHighlightText, menuAccessKey, count };
struct TextLanguage
{
std::string lexer;
const char *keywords = "";
};
TextLanguage detectLanguage(const std::filesystem::path &path, std::string_view firstPage);
std::wstring textLanguageLabel(const TextLanguage &language);
Scintilla::ILexer5 *createTextLexer(const TextLanguage &language);
TextColor syntaxColor(Scintilla::ILexer5 &lexer, std::string_view name, int style);
}
+63
View File
@@ -0,0 +1,63 @@
#pragma once
#include <windows.h>
#include <array>
#include <string>
#include <vector>
namespace ks::files
{
inline constexpr size_t documentColorCount = 10;
using TextPalette = std::array<COLORREF, 14>;
inline constexpr const wchar_t *textPaletteNames[] = {L"FAR (blue)", L"Dark", L"Light"};
inline constexpr TextPalette textPalettes[] = {
{RGB(0,0,128), RGB(215,230,255), RGB(0,128,128), RGB(255,255,255), RGB(0,115,115),
RGB(143,195,157), RGB(255,235,118), RGB(165,235,255), RGB(255,181,228), RGB(155,214,255),
RGB(0,0,0), RGB(0,0,0), RGB(255,255,255), RGB(255,255,0)},
{RGB(29,33,38), RGB(234,237,241), RGB(45,60,70), RGB(255,255,255), RGB(42,86,127),
RGB(155,185,150), RGB(145,201,255), RGB(241,186,143), RGB(208,170,255), RGB(152,226,218),
RGB(255,255,255), RGB(42,86,127), RGB(255,255,255), RGB(255,255,0)},
{RGB(255,255,255), RGB(28,35,46), RGB(221,231,237), RGB(25,38,54), RGB(74,104,146),
RGB(45,111,70), RGB(103,40,154), RGB(152,52,30), RGB(35,82,156), RGB(0,99,109),
RGB(0,0,0), RGB(189,207,223), RGB(0,0,0), RGB(111,77,0)},
};
inline constexpr const wchar_t *textColorNames[] = {L"Background", L"Text", L"Status background", L"Status text",
L"Selection", L"Comment", L"Keyword", L"String", L"Number", L"Symbol",
L"Top menu text", L"Selected menu background", L"Selected menu text", L"Menu access key"};
struct TextPreferences
{
bool wrap{}, numbers{true}, whitespace{}, tabsAsSpaces{}, autoIndent{true}, caretLine{true};
int tabWidth{4}, lineEnding{};
std::wstring scheme = textPaletteNames[0];
TextPalette colors = textPalettes[0];
bool operator==(const TextPreferences &) const = default;
};
// Index 0 is Viewer and index 1 is Editor.
using TextPreferencesSet = std::array<TextPreferences, 2>;
struct NamedTextPalette
{
std::wstring name;
TextPalette colors;
bool operator==(const NamedTextPalette &) const = default;
};
inline constexpr size_t maxTextPalettes = 48;
inline constexpr size_t maxTextPaletteName = 48;
struct MarkdownPreferences
{
unsigned width{960}, fontSize{12};
std::wstring font;
bool operator==(const MarkdownPreferences &) const = default;
};
struct TextSettings
{
TextPreferencesSet profiles;
std::vector<NamedTextPalette> schemes;
MarkdownPreferences markdown;
bool operator==(const TextSettings &) const = default;
};
TextSettings loadTextPreferences();
void saveTextPreferences(const TextSettings &settings);
}
File diff suppressed because it is too large. Load diff
+90
View File
@@ -0,0 +1,90 @@
#pragma once
#include <windows.h>
#include <filesystem>
#include <functional>
#include <cstdint>
#include <string_view>
#include <vector>
#include "files_text_document.h"
namespace ks::lan { struct FilesPeer; }
namespace ks::files
{
inline constexpr int searchOptionsDivider = 104;
inline constexpr int searchButtonsDivider = 105;
inline constexpr int searchHistoryButton = 108;
inline constexpr wchar_t farDropDownProperty[]=L"KSwitcher.Files.ActiveDropDown";
struct TextWindowFont
{
LOGFONTW font;
int tenthsOfPoint;
};
void setFileWindowTaskbar(HWND window,int iconResource,const wchar_t *identity);
struct FarDropDownPalette
{
COLORREF surface, text, selection;
};
enum class FarHistoryKind { search, folder };
struct FarHistoryEntry { std::wstring date,text; };
std::vector<FarHistoryEntry> loadFarHistory(FarHistoryKind kind);
void rememberFarHistory(FarHistoryKind kind,std::wstring_view text);
int chooseFarDropDown(HWND anchor,const std::vector<FarHistoryEntry> &entries,int selected,
FarDropDownPalette palette,int rightInset=0);
void showFarHistory(HWND dialog,int fieldId,const std::vector<FarHistoryEntry> &history,
FarDropDownPalette palette);
void installFarHistoryKey(HWND field,int arrowId);
struct TextDialogs
{
INT_PTR (*confirmSave)(HWND,bool draft);
INT_PTR (*paint)(HWND, UINT, WPARAM, LPARAM, const wchar_t *);
INT_PTR (*paintSearch)(HWND, UINT, WPARAM, LPARAM);
void (*prepare)(HWND);
void (*options)(HWND, bool);
void (*message)(HWND, const wchar_t *);
TextWindowFont (*readFont)();
FarDropDownPalette (*dropDownPalette)();
INT_PTR (*run)(HINSTANCE,LPCWSTR,HWND,DLGPROC,LPARAM);
void (*finish)(HWND,INT_PTR);
bool (*dismissOwned)(HWND);
bool (*confirmExisting)(HWND);
bool (*saveOptions)(HWND,std::filesystem::path &,TextSaveFormat &);
};
struct TextOpenOptions
{
TextEncoding encoding=TextEncoding::automatic;
bool draft{};
};
struct RemoteTextRevision
{
uint64_t size{}, modified{};
bool editable{};
};
struct RemoteTextSource
{
using Progress=std::function<bool(uint64_t,uint64_t)>;
std::string id;
std::wstring name;
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
bool,const Progress &,uint64_t)> download;
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
const RemoteTextRevision &)> upload;
};
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false,
TextOpenOptions options={});
void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false);
void textWindowOwnerClosed();
bool cycleTextWindows(HWND current,bool reverse);
}
File diff suppressed because it is too large. Load diff
+679
View File
@@ -0,0 +1,679 @@
#include <winsock2.h>
#include <ws2tcpip.h>
#include <bcrypt.h>
#include <wincrypt.h>
#include <wincred.h>
#include <shellapi.h>
#include <objbase.h>
#include "google_drive.h"
#include "sync.h"
#include "google_drive_oauth.h"
#include "http_handle.h"
#include "json.hpp"
#if __has_include("google_drive_oauth_config.h")
#include "google_drive_oauth_config.h"
#endif
#include <array>
#include <charconv>
#include <initializer_list>
#include <string_view>
namespace ks
{
namespace
{
using Json = nlohmann::json;
constexpr std::string_view Scope = "https://www.googleapis.com/auth/drive.appdata";
constexpr auto TokenHost = L"oauth2.googleapis.com";
constexpr auto DriveHost = L"www.googleapis.com";
constexpr auto NativeName = "kswitcher-win32-settings.json";
constexpr auto PreviewName = "kswitcher-settings.json";
constexpr auto SyncName = "kswitcher-win32-sync-v1.json";
constexpr auto Reconnect = "Google Drive needs authorization again. Reconnect your Google account.";
constexpr auto Network = "Could not reach Google Drive. Check your connection and try again.";
#ifdef KS_GOOGLE_CLIENT_ID
constexpr std::string_view ClientId = KS_GOOGLE_CLIENT_ID, ClientSecret = KS_GOOGLE_CLIENT_SECRET;
#else
constexpr std::string_view ClientId, ClientSecret;
#endif
void requireConfiguration()
{
if (!googleDriveConfigured()) throw std::runtime_error("Google Drive is unavailable in this build.");
}
std::wstring credentialName()
{
return L"KSwitcher.GoogleDrive/" + wide(std::string(ClientId));
}
std::string refreshToken()
{
PCREDENTIALW raw{};
if (!CredReadW(credentialName().c_str(), CRED_TYPE_GENERIC, 0, &raw))
{
if (GetLastError() == ERROR_NOT_FOUND) return {};
throw std::runtime_error("Could not read the Google Drive connection from Windows Credential Manager.");
}
struct Credential
{
PCREDENTIALW value;
~Credential()
{
if (value->CredentialBlobSize) SecureZeroMemory(value->CredentialBlob, value->CredentialBlobSize);
CredFree(value);
}
} credential{raw};
if (!raw->CredentialBlobSize) return {};
return {reinterpret_cast<const char *>(raw->CredentialBlob), raw->CredentialBlobSize};
}
void saveRefreshToken(std::string &token)
{
if (token.empty() || token.size() > CRED_MAX_CREDENTIAL_BLOB_SIZE)
throw std::runtime_error("Google did not return a usable offline connection. Reconnect and allow access.");
auto target = credentialName();
CREDENTIALW credential{};
credential.Type = CRED_TYPE_GENERIC;
credential.TargetName = target.data();
credential.CredentialBlobSize = static_cast<DWORD>(token.size());
credential.CredentialBlob = reinterpret_cast<LPBYTE>(token.data());
credential.Persist = CRED_PERSIST_LOCAL_MACHINE;
if (!CredWriteW(&credential, 0))
throw std::runtime_error("Could not save the Google Drive connection in Windows Credential Manager.");
}
std::string urlEncode(std::string_view value)
{
constexpr char hex[] = "0123456789ABCDEF";
std::string result;
for (unsigned char c : value)
{
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
c == '-' || c == '_' || c == '.' || c == '~') result += static_cast<char>(c);
else
{
result += '%';
result += hex[c >> 4];
result += hex[c & 15];
}
}
return result;
}
std::string form(std::initializer_list<std::pair<std::string_view, std::string_view>> fields)
{
std::string result;
for (const auto &[key, value] : fields)
{
if (!result.empty()) result += '&';
result += key;
result += '=';
result += urlEncode(value);
}
return result;
}
std::optional<std::string> urlDecode(std::string_view value)
{
auto digit = [](char c)
{
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
};
std::string result;
while (!value.empty())
{
const char c = value.front();
value.remove_prefix(1);
if (c != '%') result += (c == '+' ? ' ' : c);
else
{
if (value.size() < 2 || digit(value[0]) < 0 || digit(value[1]) < 0) return {};
result += static_cast<char>(digit(value[0]) * 16 + digit(value[1]));
value.remove_prefix(2);
}
}
return result;
}
std::string base64Url(const std::array<unsigned char, 32> &data)
{
std::array<char, 45> encoded{};
DWORD length = static_cast<DWORD>(encoded.size());
if (!CryptBinaryToStringA(data.data(), static_cast<DWORD>(data.size()),
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, encoded.data(), &length))
throw std::runtime_error("Could not start a secure Google connection.");
std::string result(encoded.data(), length);
for (char &c : result)
{
if (c == '/') c = '_';
if (c == '+') c = '-';
}
result.resize(result.find('='));
return result;
}
std::string randomParameter()
{
std::array<unsigned char, 32> data{};
if (BCryptGenRandom(nullptr, data.data(), static_cast<ULONG>(data.size()), BCRYPT_USE_SYSTEM_PREFERRED_RNG) < 0)
throw std::runtime_error("Could not start a secure Google connection.");
return base64Url(data);
}
}
std::string google_drive_oauth::challengeFor(const std::string &verifier)
{
BCRYPT_ALG_HANDLE algorithm{};
if (BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr, 0) < 0)
throw std::runtime_error("Could not start a secure Google connection.");
std::array<unsigned char, 32> hash{};
const auto status = BCryptHash(algorithm, nullptr, 0,
reinterpret_cast<PUCHAR>(const_cast<char *>(verifier.data())), static_cast<ULONG>(verifier.size()),
hash.data(), static_cast<ULONG>(hash.size()));
BCryptCloseAlgorithmProvider(algorithm, 0);
if (status < 0) throw std::runtime_error("Could not start a secure Google connection.");
return base64Url(hash);
}
namespace
{
struct HttpResponse { DWORD status{}; Bytes body; };
HttpResponse https(const wchar_t *host, const wchar_t *method, const std::wstring &path,
const std::wstring &headers, std::string &payload, size_t limit)
{
HttpHandle session{WinHttpOpen(L"KSwitcher Google Drive/1", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0)};
if (!session.h || !WinHttpSetTimeouts(session.h, 5000, 5000, 10000, 10000))
throw std::runtime_error(Network);
HttpHandle connection{WinHttpConnect(session.h, host, INTERNET_DEFAULT_HTTPS_PORT, 0)};
HttpHandle request{connection.h ? WinHttpOpenRequest(connection.h, method, path.c_str(), nullptr,
WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) : nullptr};
DWORD redirects = WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
DWORD disable = WINHTTP_DISABLE_COOKIES | WINHTTP_DISABLE_AUTHENTICATION;
if (!request.h ||
!WinHttpSetOption(request.h, WINHTTP_OPTION_REDIRECT_POLICY, &redirects, sizeof(redirects)) ||
!WinHttpSetOption(request.h, WINHTTP_OPTION_DISABLE_FEATURE, &disable, sizeof(disable)) ||
!WinHttpSendRequest(request.h, headers.c_str(), static_cast<DWORD>(headers.size()),
payload.empty() ? WINHTTP_NO_REQUEST_DATA : payload.data(), static_cast<DWORD>(payload.size()),
static_cast<DWORD>(payload.size()), 0) ||
!WinHttpReceiveResponse(request.h, nullptr))
throw std::runtime_error(Network);
HttpResponse response;
DWORD length = sizeof(response.status);
if (!WinHttpQueryHeaders(request.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX, &response.status, &length, WINHTTP_NO_HEADER_INDEX))
throw std::runtime_error(Network);
if (response.status < 200 || response.status >= 300) return response;
const auto deadline = GetTickCount64() + 30000;
for (;;)
{
unsigned char buffer[8192];
DWORD count{};
if (GetTickCount64() >= deadline || !WinHttpReadData(request.h, buffer, sizeof(buffer), &count))
throw std::runtime_error(Network);
if (!count) return response;
if (count > limit - response.body.size())
throw std::runtime_error(limit == GoogleDriveBackupLimit ? "This Drive backup exceeds the 2 MiB limit." :
"Google returned an oversized response.");
response.body.insert(response.body.end(), buffer, buffer + count);
}
}
struct ClearString
{
std::string &value;
~ClearString() { if (!value.empty()) SecureZeroMemory(value.data(), value.size()); }
};
struct Tokens { std::string access, refresh; };
Tokens requestTokens(std::string payload)
{
ClearString clear{payload};
payload += "&" + form({{"client_id", ClientId}, {"client_secret", ClientSecret}});
auto response = https(TokenHost, L"POST", L"/token", L"Content-Type: application/x-www-form-urlencoded\r\n",
payload, 64 * 1024);
if (response.status == 400 || response.status == 401 || response.status == 403)
throw std::runtime_error(Reconnect);
if (response.status < 200 || response.status >= 300)
throw std::runtime_error("Google could not authorize the connection. Try again.");
const auto data = Json::parse(response.body, nullptr, false);
if (!response.body.empty()) SecureZeroMemory(response.body.data(), response.body.size());
try
{
Tokens tokens{data.at("access_token").get<std::string>(), data.value("refresh_token", "")};
if (tokens.access.empty() || tokens.access.find_first_not_of(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~+/=") != std::string::npos)
throw std::runtime_error("Invalid Google access token.");
return tokens;
}
catch (const std::exception &)
{
throw std::runtime_error("Google returned an invalid authorization response.");
}
}
struct Winsock
{
Winsock()
{
WSADATA data{};
if (WSAStartup(MAKEWORD(2, 2), &data)) throw std::runtime_error("Could not open a local sign-in callback.");
}
~Winsock() { WSACleanup(); }
};
struct Socket
{
SOCKET handle;
~Socket() { if (handle != INVALID_SOCKET) closesocket(handle); }
};
}
std::optional<std::string> google_drive_oauth::callbackCode(std::string_view request, std::string_view state)
{
constexpr std::string_view prefix = "GET /oauth/callback?";
const auto end = request.find(' ', prefix.size());
if (!request.starts_with(prefix) || end == std::string_view::npos) return {};
auto query = request.substr(prefix.size(), end - prefix.size());
std::optional<std::string> returnedState, code;
bool denied = false;
while (!query.empty())
{
const auto next = query.find('&');
const auto entry = query.substr(0, next);
const auto equals = entry.find('=');
if (equals != std::string_view::npos)
{
const auto key = entry.substr(0, equals);
const auto value = entry.substr(equals + 1);
if (key == "state")
{
if (returnedState) return {};
returnedState = urlDecode(value);
if (!returnedState) return {};
}
if (key == "code")
{
if (code) return {};
code = urlDecode(value);
if (!code) return {};
}
if (key == "error") denied = true;
}
if (next == std::string_view::npos) break;
query.remove_prefix(next + 1);
}
if (!returnedState || *returnedState != state) return {};
return denied ? std::string{} : code.value_or("");
}
namespace
{
void checkCanceled(std::stop_token stop)
{
if (stop.stop_requested()) throw std::runtime_error("Google sign-in was canceled.");
}
std::optional<std::string> readCallback(SOCKET socket, std::string_view state, std::stop_token stop)
{
const DWORD timeout = 200;
const auto timeoutValue = reinterpret_cast<const char *>(&timeout);
if (setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, timeoutValue, sizeof(timeout)) ||
setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, timeoutValue, sizeof(timeout))) return {};
const auto deadline = GetTickCount64() + 2000;
std::string request;
for (;;)
{
checkCanceled(stop);
if (GetTickCount64() >= deadline || request.size() >= 8192) return {};
char buffer[1024];
const auto count = recv(socket, buffer, static_cast<int>(sizeof(buffer)), 0);
if (count <= 0) return {};
request.append(buffer, count);
if (request.find("\r\n") != request.npos) break;
}
auto code = google_drive_oauth::callbackCode(request.substr(0, request.find("\r\n")), state);
const std::string message = !code ? "This sign-in response did not match KSwitcher." :
code->empty() ? "Google sign-in was canceled. Return to KSwitcher." : "Return to KSwitcher to finish signing in.";
const std::string reply = std::string(code ? "HTTP/1.1 200 OK" : "HTTP/1.1 400 Bad Request") +
"\r\nContent-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\nReferrer-Policy: no-referrer"
"\r\nConnection: close\r\nContent-Length: " + std::to_string(message.size()) + "\r\n\r\n" + message;
send(socket, reply.data(), static_cast<int>(reply.size()), 0);
return code;
}
std::string waitForCode(SOCKET listener, const std::string &state, std::stop_token stop)
{
const auto deadline = GetTickCount64() + 120000;
while (GetTickCount64() < deadline)
{
checkCanceled(stop);
fd_set readable;
FD_ZERO(&readable);
FD_SET(listener, &readable);
timeval interval{0, 200000};
const int ready = select(0, &readable, nullptr, nullptr, &interval);
if (!ready) continue;
Socket peer{ready == SOCKET_ERROR ? INVALID_SOCKET : accept(listener, nullptr, nullptr)};
if (peer.handle == INVALID_SOCKET) throw std::runtime_error("Could not receive the Google sign-in response.");
const auto code = readCallback(peer.handle, state, stop);
if (!code) continue;
if (code->empty()) throw std::runtime_error("Google sign-in was declined or canceled.");
return *code;
}
throw std::runtime_error("Google sign-in timed out. Connect again to retry.");
}
void checkDrive(DWORD status)
{
if (status == 401) throw std::runtime_error(Reconnect);
if (status == 403) throw std::runtime_error("Google Drive denied access. Reconnect or check your account's access.");
if (status == 404) throw std::runtime_error("The requested file is no longer available on Google Drive.");
if (status == 412) throw std::runtime_error("The Google Drive profile changed on another PC. Sync again.");
if (status < 200 || status >= 300) throw std::runtime_error("Google Drive could not complete the request. Try again.");
}
HttpResponse driveRequest(const wchar_t *method, const std::string &path, const std::string &access,
const std::wstring &contentType = {}, std::string payload = {}, size_t limit = 64 * 1024,
const std::wstring &additionalHeaders = {})
{
auto response = https(DriveHost, method, wide(path), L"Authorization: Bearer " + wide(access) + L"\r\n" +
(contentType.empty() ? L"" : L"Content-Type: " + contentType + L"\r\n") + additionalHeaders, payload, limit);
checkDrive(response.status);
return response;
}
std::string accessToken()
{
requireConfiguration();
auto refresh = refreshToken();
ClearString clear{refresh};
if (refresh.empty()) throw std::runtime_error(Reconnect);
return requestTokens(form({{"grant_type", "refresh_token"}, {"refresh_token", refresh}})).access;
}
struct DriveFile { std::string id; std::wstring created; };
DriveFile driveFile(const Json &file)
{
DriveFile result{file.at("id").get<std::string>(), wide(file.at("createdTime").get<std::string>())};
if (result.id.empty() || result.created.empty()) throw std::runtime_error("Incomplete backup metadata.");
return result;
}
Json driveFilePage(const std::string &access, const std::string &filter, size_t count,
std::string_view page, std::string_view fields)
{
const auto query = form({{"spaces", "appDataFolder"}, {"pageSize", std::to_string(count)},
{"orderBy", "createdTime desc"}, {"q", filter}, {"fields", fields}});
const auto response = driveRequest(L"GET", "/drive/v3/files?" + query +
(page.empty() ? "" : "&pageToken=" + urlEncode(page)), access);
auto data = Json::parse(response.body, nullptr, false);
if (!data.is_object() || !data.contains("files") || !data.at("files").is_array() ||
data.value("incompleteSearch", false))
throw std::runtime_error("Google Drive returned an unreadable file list.");
return data;
}
std::vector<DriveFile> matchingFiles(const std::string &access, const std::string &filter, size_t count)
{
std::vector<DriveFile> matches;
std::string page;
// Drive can return an empty page with a continuation token.
for (int i = 0; i < 20; ++i)
{
const auto data = driveFilePage(access, filter, count, page, "nextPageToken,incompleteSearch,files(id,createdTime)");
try
{
const auto &files = data.at("files").get_ref<const Json::array_t &>();
for (const auto &file : files)
{
matches.push_back(driveFile(file));
if (matches.size() == count) return matches;
}
page = data.value("nextPageToken", "");
if (page.empty()) return matches;
}
catch (const std::exception &)
{
throw std::runtime_error("Google Drive returned an unreadable backup list.");
}
}
throw std::runtime_error("Google Drive did not finish listing backups. Try again.");
}
DriveFile createDriveFile(const std::string &access, const std::string &name, const std::string &settings)
{
if (settings.size() > GoogleDriveBackupLimit) throw std::runtime_error("Settings exceed the 2 MiB Drive limit.");
const auto boundary = randomParameter();
const auto metadata = Json{{"name", name}, {"parents", Json::array({"appDataFolder"})}}.dump();
auto payload = "--" + boundary + "\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n" +
metadata + "\r\n--" + boundary + "\r\nContent-Type: application/json\r\n\r\n" +
settings + "\r\n--" + boundary + "--\r\n";
const auto response = driveRequest(L"POST", "/upload/drive/v3/files?uploadType=multipart&fields=id%2CcreatedTime",
access, L"multipart/related; boundary=" + wide(boundary), std::move(payload));
try { return driveFile(Json::parse(response.body, nullptr, false)); }
catch (const std::exception &) { throw std::runtime_error("Google Drive did not confirm the upload."); }
}
class GoogleDriveSync final : public SyncProvider
{
std::string access, name;
std::string file;
std::wstring etag;
uint64_t revision{};
std::string findProfile()
{
auto files = matchingFiles(access, "name = '" + name + "'", 2);
if (files.size() > 1) throw std::runtime_error("Multiple Google Drive sync profiles were found. Automatic sync is paused.");
return files.empty() ? std::string{} : urlEncode(files.front().id);
}
std::wstring revisionTag()
{
// Drive v2 exposes the ETag and enforces it on the media PUT.
const auto meta = driveRequest(L"GET", "/drive/v2/files/" + file + "?fields=etag", access);
const auto tag = Json::parse(meta.body).at("etag").get<std::string>();
if (tag.size() < 3 || tag.size() > 1024 || tag.front() != '"' || tag.back() != '"' ||
tag.find_first_of("\r\n") != tag.npos)
throw std::runtime_error("Google Drive returned an invalid sync revision.");
return wide(tag);
}
public:
GoogleDriveSync(std::string token, std::string profileName) : access(std::move(token)), name(std::move(profileName)) {}
~GoogleDriveSync() override { ClearString clear{access}; }
SyncDocument read() override
{
file = findProfile();
if (file.empty())
{
etag.clear();
revision = 0;
return {};
}
for (int attempt = 0; attempt < 3; ++attempt)
{
const auto before = revisionTag();
const auto media = driveRequest(L"GET", "/drive/v3/files/" + file + "?alt=media",
access, {}, {}, GoogleDriveBackupLimit);
etag = revisionTag();
if (before != etag) continue;
const auto profile = Json::parse(media.body, [](int depth, Json::parse_event_t, Json &)
{
if (depth > 32) throw std::runtime_error("Invalid Google Drive synchronization profile.");
return true;
});
if (profile.value("format", "") != "kswitcher-drive-sync-v1" ||
!profile.at("revision").is_number_unsigned())
throw std::runtime_error("Unsupported Google Drive synchronization profile.");
revision = profile.at("revision").get<uint64_t>();
if (!revision || revision == UINT64_MAX) throw std::runtime_error("Invalid Google Drive sync revision.");
const auto settings = profile.at("settings").dump();
return {revision, Bytes(settings.begin(), settings.end())};
}
throw std::runtime_error("The Google Drive profile changed during download. Sync again.");
}
uint64_t write(const Bytes &settings, uint64_t expectedRevision) override
{
if (revision != expectedRevision) throw std::runtime_error("The Google Drive profile changed. Sync again.");
const auto body = Json{{"format", "kswitcher-drive-sync-v1"}, {"revision", revision + 1},
{"settings", Json::parse(settings)}}.dump();
if (body.size() > GoogleDriveBackupLimit) throw std::runtime_error("Settings exceed the 2 MiB Drive limit.");
if (!revision)
{
if (!findProfile().empty()) throw std::runtime_error("Google Drive already has a sync profile. Sync again.");
createDriveFile(access, name, body);
findProfile();
}
else
{
driveRequest(L"PUT", "/upload/drive/v2/files/" + file + "?uploadType=media&fields=id", access,
L"application/json", body, 64 * 1024, L"If-Match: " + etag + L"\r\n");
}
return ++revision;
}
};
}
bool googleDriveConfigured()
{
return !ClientId.empty() && !ClientSecret.empty();
}
bool googleDriveConnected()
{
if (!googleDriveConfigured()) return false;
auto token = refreshToken();
ClearString clear{token};
return !token.empty();
}
std::string googleDriveCredentialKey()
{
auto token = refreshToken();
ClearString clear{token};
return token.empty() ? std::string{} : google_drive_oauth::challengeFor(token);
}
std::unique_ptr<SyncProvider> makeGoogleDriveSyncProvider()
{
return std::make_unique<GoogleDriveSync>(accessToken(), SyncName);
}
void connectGoogleDrive(std::stop_token stop)
{
requireConfiguration();
checkCanceled(stop);
Winsock winsock;
Socket listener{socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)};
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
int length = sizeof(address);
const BOOL exclusive = TRUE;
if (listener.handle == INVALID_SOCKET ||
setsockopt(listener.handle, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast<const char *>(&exclusive), sizeof(exclusive)) ||
bind(listener.handle, reinterpret_cast<const sockaddr *>(&address), length) ||
listen(listener.handle, SOMAXCONN) ||
getsockname(listener.handle, reinterpret_cast<sockaddr *>(&address), &length))
throw std::runtime_error("Could not open a local sign-in callback.");
const auto redirect = "http://127.0.0.1:" + std::to_string(ntohs(address.sin_port)) + "/oauth/callback";
const auto state = randomParameter();
const auto verifier = randomParameter();
const auto url = wide("https://accounts.google.com/o/oauth2/v2/auth?" + form({
{"client_id", ClientId}, {"redirect_uri", redirect}, {"response_type", "code"}, {"scope", Scope},
{"access_type", "offline"}, {"prompt", "consent select_account"}, {"state", state},
{"code_challenge", google_drive_oauth::challengeFor(verifier)}, {"code_challenge_method", "S256"}}));
const auto initialized = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
const auto opened = ShellExecuteW(nullptr, L"open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
if (SUCCEEDED(initialized)) CoUninitialize();
if (reinterpret_cast<INT_PTR>(opened) <= 32)
throw std::runtime_error("Could not open the system browser.");
auto code = waitForCode(listener.handle, state, stop);
ClearString clearCode{code};
checkCanceled(stop);
auto tokens = requestTokens(form({{"grant_type", "authorization_code"}, {"code", code},
{"redirect_uri", redirect}, {"code_verifier", verifier}}));
ClearString clearAccess{tokens.access}, clearRefresh{tokens.refresh};
checkCanceled(stop);
saveRefreshToken(tokens.refresh);
}
void disconnectGoogleDrive()
{
requireConfiguration();
if (!CredDeleteW(credentialName().c_str(), CRED_TYPE_GENERIC, 0) && GetLastError() != ERROR_NOT_FOUND)
throw std::runtime_error("Could not remove the Google Drive connection from Windows Credential Manager.");
}
GoogleDriveBackupPage listGoogleDriveBackups(std::string_view page)
{
auto access = accessToken();
ClearString clear{access};
const auto filter = std::string("name = '") + PreviewName + "' or name = '" + NativeName + "'";
std::string token(page);
// An empty page with a continuation token can occur before the end.
for (int attempt = 0; attempt < 20; ++attempt)
{
const auto data = driveFilePage(access, filter, 50, token,
"nextPageToken,incompleteSearch,files(id,createdTime,name,size)");
GoogleDriveBackupPage result;
try
{
result.nextPage = data.value("nextPageToken", "");
for (const auto &file : data.at("files"))
{
auto info = driveFile(file);
const auto name = file.at("name").get<std::string>();
if (name != NativeName && name != PreviewName) continue;
std::optional<uint64_t> size;
if (file.contains("size"))
{
const auto value = file.at("size").get<std::string>();
uint64_t parsed{};
const auto [end, error] = std::from_chars(value.data(), value.data() + value.size(), parsed);
if (error == std::errc{} && end == value.data() + value.size()) size = parsed;
}
result.backups.push_back({std::move(info.id), std::move(info.created), size, name == PreviewName});
}
}
catch (const std::exception &)
{
throw std::runtime_error("Google Drive returned an unreadable backup list.");
}
if (!result.backups.empty() || result.nextPage.empty()) return result;
token = std::move(result.nextPage);
}
throw std::runtime_error("Google Drive did not finish listing backups. Try again.");
}
GoogleDriveBackupInfo uploadGoogleDriveBackup(const Bytes &settings)
{
auto access = accessToken();
ClearString clear{access};
auto file = createDriveFile(access, NativeName, {settings.begin(), settings.end()});
return {std::move(file.id), std::move(file.created), settings.size(), false};
}
Bytes fetchGoogleDriveBackup(std::string_view id)
{
if (id.empty()) throw std::runtime_error("Select a Google Drive backup to restore.");
auto access = accessToken();
ClearString clear{access};
auto response = driveRequest(L"GET", "/drive/v3/files/" + urlEncode(id) + "?alt=media",
access, {}, {}, GoogleDriveBackupLimit);
return std::move(response.body);
}
}
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include "storage.h"
#include <memory>
#include <stop_token>
namespace ks
{
class SyncProvider;
inline constexpr size_t GoogleDriveBackupLimit = 2 * 1024 * 1024;
Bytes encodeDriveBackup(const Settings &saved);
Settings restoreDriveBackup(const Bytes &, const Settings &draft, const std::vector<Layout> &);
Bytes sharedDriveSettings(const Settings &);
Settings restoreSharedDriveSettings(const Bytes &, const Settings &, const std::vector<Layout> &);
std::string googleDriveCredentialKey();
std::unique_ptr<SyncProvider> makeGoogleDriveSyncProvider();
bool googleDriveConfigured();
bool googleDriveConnected();
void connectGoogleDrive(std::stop_token);
void disconnectGoogleDrive();
struct GoogleDriveBackupInfo
{
std::string id;
std::wstring created;
std::optional<uint64_t> size;
bool preview{};
};
struct GoogleDriveBackupPage
{
std::vector<GoogleDriveBackupInfo> backups;
std::string nextPage;
};
GoogleDriveBackupPage listGoogleDriveBackups(std::string_view page = {});
GoogleDriveBackupInfo uploadGoogleDriveBackup(const Bytes &);
Bytes fetchGoogleDriveBackup(std::string_view id);
}
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#include <optional>
#include <string>
#include <string_view>
namespace ks::google_drive_oauth
{
std::string challengeFor(const std::string &verifier);
// nullopt ignores unrelated requests. An empty code is a rejected authorization.
std::optional<std::string> callbackCode(std::string_view request, std::string_view state);
}
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include <windows.h>
#include <winhttp.h>
namespace ks
{
struct HttpHandle
{
explicit HttpHandle(HINTERNET handle) : h(handle) {}
HttpHandle(const HttpHandle &) = delete;
HttpHandle &operator=(const HttpHandle &) = delete;
~HttpHandle() { if (h) WinHttpCloseHandle(h); }
HINTERNET h;
};
}
+428 -54
View File
@@ -7,6 +7,9 @@
#include "lan_mesh.h"
#include "lan_clipboard.h"
#include "lan_layout.h"
#include "lan_network.h"
#include "lan_wake.h"
#include "lan_clients.h"
#include <atomic>
#include <mutex>
#include <thread>
@@ -28,14 +31,41 @@ std::string hostName()
wchar_t name[256]{}; DWORD size=256;
return GetComputerNameW(name,&size) ? utf8(std::wstring(name,size)) : "KSwitcher";
}
std::vector<ULONG> broadcasts()
Bytes ipv4Adapters()
{
ULONG size=16384; Bytes data(size);
auto flags=GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER;
auto result=GetAdaptersAddresses(AF_INET,flags,nullptr,(IP_ADAPTER_ADDRESSES*)data.data(),&size);
if(result==ERROR_BUFFER_OVERFLOW) { data.resize(size); result=GetAdaptersAddresses(AF_INET,flags,nullptr,(IP_ADAPTER_ADDRESSES*)data.data(),&size); }
if(result!=NO_ERROR) return {};
return data;
}
std::string wakeMacFor(ULONG remote)
{
DWORD interfaceIndex{};
if(GetBestInterface(remote,&interfaceIndex)!=NO_ERROR) return {};
auto data=ipv4Adapters();
if(data.empty()) return {};
for(auto a=reinterpret_cast<const IP_ADAPTER_ADDRESSES*>(data.data());a;a=a->Next)
{
if(a->IfIndex!=interfaceIndex || a->OperStatus!=IfOperStatusUp || a->PhysicalAddressLength!=6 ||
(a->IfType!=IF_TYPE_ETHERNET_CSMACD && a->IfType!=IF_TYPE_IEEE80211)) continue;
std::string result;
for(size_t i=0;i<a->PhysicalAddressLength;++i)
{
const auto byte=a->PhysicalAddress[i];
result+="0123456789abcdef"[byte>>4];
result+="0123456789abcdef"[byte&15];
}
return lan::wakePacket(result)?result:std::string{};
}
return {};
}
std::vector<ULONG> broadcasts()
{
auto data=ipv4Adapters();
std::vector<ULONG> out;
if(result!=NO_ERROR) return out;
if(data.empty()) return out;
for(auto a=(IP_ADAPTER_ADDRESSES*)data.data();a;a=a->Next)
if(a->OperStatus==IfOperStatusUp)
for(auto u=a->FirstUnicastAddress;u;u=u->Next)
@@ -47,9 +77,48 @@ std::vector<ULONG> broadcasts()
return out;
}
}
void lan::wakeFilesPeer(const std::string &id)
{
const auto settings=Json::parse(unprotect(readFile(dataDirectory()/L"lan-pairing.bin",256*1024)));
const auto &trusted=settings.at("trusted");
if(!settings.value("enabled",false) || !trusted.contains(id))
throw std::runtime_error("Enable KSwitcher LAN and select a paired PC.");
const auto packet=wakePacket(trusted.at(id).value("wakeMac",""));
if(!packet) throw std::runtime_error("No saved MAC address. Run updated KSwitcher on this PC while it is online once.");
const auto destinations=broadcasts();
if(destinations.empty()) throw std::runtime_error("No local IPv4 network is available.");
Network network;
WinSocket socket{::socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)};
if(socket.value==INVALID_SOCKET) socketError();
const BOOL broadcast=TRUE;
if(setsockopt(socket.value,SOL_SOCKET,SO_BROADCAST,reinterpret_cast<const char*>(&broadcast),sizeof(broadcast)))
socketError();
bool sent=false;
int error=WSAEHOSTUNREACH;
for(const auto ip:destinations)
{
sockaddr_in destination{};
destination.sin_family=AF_INET;
destination.sin_port=htons(9);
destination.sin_addr.s_addr=ip;
if(sendto(socket.value,reinterpret_cast<const char*>(packet->data()),static_cast<int>(packet->size()),0,
reinterpret_cast<const sockaddr*>(&destination),sizeof(destination))==SOCKET_ERROR)
error=WSAGetLastError();
else sent=true;
}
if(!sent) throw std::system_error(error,std::system_category());
}
struct LanService::Impl
{
struct Peer { std::string name,epoch; sockaddr_in address{}; uint64_t seen{},verified{}; bool files{}; };
struct Peer
{
std::string name,epoch;
sockaddr_in address{};
uint64_t seen{},verified{};
bool files{};
bool present(uint64_t now)const{return verified && now-verified<lan::PeerLifetime;}
};
std::filesystem::path path;
std::string id,epoch=lan::randomHex(16),name=hostName(),status="Disabled.";
std::map<std::string,Peer> peers;
@@ -66,9 +135,12 @@ struct LanService::Impl
std::mutex mutex;
std::thread worker;
bool shareInput{};
bool inputPaused{};
std::mutex transportMutex;
bool resetInputChannels{};
std::string inputPeer;
int inputEdge=1;
std::atomic<bool> inputConnected{false},abortInput{false};
std::atomic<bool> abortInput{false};
std::atomic<uint64_t> inputEpoch{0};
std::atomic<uint64_t> inputConfiguration{0};
std::atomic<bool> layoutChanged{false};
@@ -78,9 +150,13 @@ struct LanService::Impl
std::map<std::string,uint64_t> inputReady;
std::unique_ptr<lan::InputMesh> router;
std::string inputStatus="Input sharing disabled.";
size_t inputConnectedPeers{}, inputOnlinePeers{};
bool inputWorkerStopped{};
bool inputNeedsHelp{};
HWND inputWindow{};std::atomic<bool> inputNotification{false};
explicit Impl(const std::filesystem::path &root,HWND window) : path(root/L"lan-pairing.bin"),inputWindow(window)
lan::LanClients clients;
explicit Impl(const std::filesystem::path &root,HWND window,bool paused)
: path(root/L"lan-pairing.bin"),inputPaused(paused),inputWindow(window),clients(root)
{
if(std::filesystem::exists(path))
{
@@ -104,7 +180,105 @@ struct LanService::Impl
configureRouter();
if(enabled) start();
}
~Impl() { stop(); }
~Impl() { clients.stop(); stop(); }
void startClients()
{
clients.start([this](const Json &request, const auto &allowed, const auto &send) {
const auto action = request.at("action").get<std::string>();
auto reply = [&](const Json &result) {
const auto text = result.dump();
send(text.data(), DWORD(text.size()));
};
lan::FilesPeer target;
std::string local, key;
auto machines = Json::array();
{
std::lock_guard gate(commandGate);
std::lock_guard lock(mutex);
const auto now = GetTickCount64();
const auto reachable = [&](const Peer &peer) {
return enabled && peer.files && peer.verified && now - peer.verified < lan::PeerLifetime;
};
if (action == "peers")
{
refreshFiles = true;
for (const auto &[peer, pair] : trusted.items())
{
const auto found = peers.find(peer);
machines.push_back({{"id", peer}, {"name", pair.at("name")},
{"online", found != peers.end() && reachable(found->second)}});
}
}
else
{
if (action != "drives" && action != "list" && action != "download")
throw std::runtime_error("Unsupported LAN client operation.");
const auto peer = request.at("peer").get<std::string>();
const auto found = peers.find(peer);
if (!trusted.contains(peer) || found == peers.end() || !reachable(found->second))
throw std::runtime_error("The paired computer is offline or file browsing is unavailable.");
char address[INET_ADDRSTRLEN]{};
auto ip = found->second.address.sin_addr;
if (!InetNtopA(AF_INET, &ip, address, sizeof(address)))
throw std::runtime_error("The paired computer has no usable address.");
target = {peer, address, wide(found->second.name), lan::FilesPort, true};
local = id;
key = trusted.at(peer).at("key").get<std::string>();
}
}
if (action == "peers")
{
reply(machines);
return;
}
lan::FilesConnection connection(target, local, key);
if (action == "drives")
{
const auto result = connection.call({{"action", "drives"}});
lan::checkFileReply(result);
reply(result.at("drives"));
return;
}
const auto path = lan::filePath(request.at("path"));
if (action == "list")
{
auto page = connection.call(lan::fileRequest("list", path));
auto entries = Json::array();
size_t bytes{};
for (;;)
{
lan::checkFileReply(page);
for (auto &entry : page.at("entries"))
{
bytes += entry.dump().size() + 1;
if (bytes > 8 * 1024 * 1024) throw std::runtime_error("The remote directory listing is too large.");
entries.push_back(std::move(entry));
}
if (!page.at("more").get<bool>()) break;
allowed();
page = connection.call({{"action", "listNext"}});
}
reply(entries);
return;
}
const auto file = connection.call(lan::fileRequest("stat", path));
lan::checkFileReply(file);
auto open = lan::fileRequest("openRead", path);
open["size"] = file.at("size");
open["modified"] = file.at("modified");
lan::checkFileReply(connection.call(open));
reply({{"size", file.at("size")}});
for (;;)
{
allowed();
const auto chunk = connection.call({{"action", "read"}});
lan::checkFileReply(chunk);
const auto &data = chunk.at("data").get_binary();
send(data.data(), DWORD(data.size()));
if (data.empty()) break;
}
});
}
void save() { atomicWrite(path,protect(encoded({{"version",1},{"id",id},{"enabled",enabled},{"trusted",trusted},
{"shareInput",shareInput},{"shareLogs",shareLogs},{"inputPeer",inputPeer},{"inputEdge",inputEdge},{"positions",positions}}))); }
bool queue(const std::string &peer,lan::InputFrame frame)
@@ -122,13 +296,32 @@ struct LanService::Impl
{
if(router)router->cancel(GetTickCount64());
router.reset();++inputConfiguration;
if(enabled&&shareInput){
if(enabled&&shareInput&&!inputPaused){
std::map<std::string,POINT> layout;for(auto &[peer,cell]:positions.items())if(trusted.contains(peer))layout[peer]={cell[0].get<LONG>(),cell[1].get<LONG>()};
router=std::make_unique<lan::InputMesh>(id,lan::windowsInputEnvironment(),std::move(layout),[this](const auto &peer,auto f){return queue(peer,f);});
}
inputStatus=enabled&&shareInput?"Connecting input channels...":"Input sharing disabled.";
observedRevision=0;
}
void setInputPaused(bool paused)
{
// A poll can own a batch outside the queues. Finish that poll before
// cancelling the router and discarding both directions of the old session.
std::lock_guard transportLock(transportMutex);
std::lock_guard lock(mutex);
if (inputPaused == paused) return;
inputPaused = paused;
configureRouter();
if (paused)
{
resetInputChannels = true;
std::lock_guard queueLock(inputMutex);
inputIn.clear();
inputOut.clear();
inputReady.clear();
inputConnectedPeers = inputOnlinePeers = 0;
}
}
bool takeChange()
{
auto revision=router?router->revision():0;auto configuration=inputConfiguration.load();
@@ -151,6 +344,7 @@ struct LanService::Impl
void start()
{
stopping=false; epoch=lan::randomHex(16); status="Searching for KSwitcher computers...";
updateInputStatus(0,0,"Waiting for paired computers...",false);
worker=std::thread([this]{ run(); });
}
void stop()
@@ -158,17 +352,38 @@ struct LanService::Impl
if(router)router->cancel(GetTickCount64());
stopping=true;
if(worker.joinable()) worker.join();
inputConnected=false;++inputEpoch;
{std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();}
std::lock_guard lock(mutex); pending.reset(); peers.clear();clipboard=std::make_unique<lan::ClipboardExchange>(id);
transfers=std::make_unique<lan::ClipboardExchange>(id,"file-transfer");incomingFiles.clear();logDownload.reset();
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,0,FALSE);
}
void updateInputStatus(size_t connected,size_t online,std::string status,bool needsHelp,bool stopped=false)
{
bool changed;
{
std::lock_guard lock(mutex);
changed=connected!=inputConnectedPeers||online!=inputOnlinePeers||stopped!=inputWorkerStopped;
inputConnectedPeers=connected;
inputOnlinePeers=online;
inputWorkerStopped=stopped;
inputStatus=std::move(status);
inputNeedsHelp=needsHelp;
}
if(changed&&inputWindow)PostMessageW(inputWindow,LanInputStatusMessage,0,0);
}
void send(SOCKET socket,const sockaddr_in &address,const Json &j)
{
auto bytes=j.dump(); if(bytes.size()>2048) return;
sendto(socket,bytes.data(),int(bytes.size()),0,(const sockaddr*)&address,sizeof(address));
}
Json discoveryAnnouncement(bool filesListening)const
{
auto hello=lan::envelope("hello",id);
hello["name"]=name;
hello["epoch"]=epoch;
hello["clipboardSession"]=clipboard->session();
hello["fileSession"]=transfers->session();
hello["filesBrowse"]=filesListening;
return hello;
}
std::string heartbeat(const std::string &from,const std::string &to,const std::string &a,const std::string &b)
{ return "KSwitcher LAN v1|presence|"+from+"|"+to+"|"+a+"|"+b; }
void receiveTransfers(uint64_t now)
@@ -180,10 +395,7 @@ struct LanService::Impl
auto end=std::find(item.bytes.begin(),item.bytes.end(),0);
if(end!=item.bytes.begin() && end!=item.bytes.end() && end-item.bytes.begin()<=1024 &&
item.bytes.end()-end-1<=16*1024*1024)
{
incomingFiles.push_back(std::move(item));
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),TRUE);
}
}
else if(item.app=="log-request" && item.bytes.size()==33)
{
@@ -206,7 +418,7 @@ struct LanService::Impl
}
transfers->deliveries.clear();
}
void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now)
void receive(SOCKET socket,const sockaddr_in &address,const Json &j,uint64_t now,bool filesListening)
{
if(j.value("app","")!="KSwitcher-LAN" || j.value("version",0)!=1) return;
auto other=j.value("id",""); if(!lan::identifier(other)||other==id) return;
@@ -217,21 +429,33 @@ struct LanService::Impl
if(display.empty()||display.size()>128||!lan::identifier(session)||
std::any_of(display.begin(),display.end(),[](unsigned char c){return c<32||c==127;})) return;
// Discovery is untrusted and never grants input access.
if(!peers.contains(other) && peers.size()>=64) return;
const bool firstAnnouncement=!peers.contains(other);
if(firstAnnouncement && peers.size()>=64) return;
auto &peer=peers[other];
// A fresh announcement rotates the challenge every three seconds; it
// does not revoke a recent successful proof for the same address.
// Only a valid presence response renews verified, so untrusted/replayed
// announcements cannot extend its PeerLifetime expiry.
if(peer.address.sin_addr.s_addr!=address.sin_addr.s_addr) peer.verified=0;
const bool addressChanged=peer.address.sin_addr.s_addr!=address.sin_addr.s_addr;
if(addressChanged) peer.verified=0;
clipboard->peerSession(other,j.value("clipboardSession",""));
transfers->peerSession(other,j.value("fileSession",""));
peer.files=j.value("filesBrowse",false);
peer.name=display; peer.epoch=session; peer.address=address; peer.seen=now;
if(trusted.contains(other))
{
// A returning peer can prove presence right away using our current challenge.
if(firstAnnouncement) send(socket,address,discoveryAnnouncement(filesListening));
auto response=lan::envelope("presence",id); response["to"]=other; response["epoch"]=epoch;
response["proof"]=lan::mac(trusted[other].at("key"),heartbeat(id,other,epoch,session));
const auto &key=trusted[other].at("key");
const auto challenge=heartbeat(id,other,epoch,session);
response["proof"]=lan::mac(key,challenge);
const auto wakeMac=wakeMacFor(address.sin_addr.s_addr);
if(!wakeMac.empty())
{
response["wakeMac"]=wakeMac;
response["wakeProof"]=lan::mac(key,challenge+"|wake|"+wakeMac);
}
send(socket,address,response);
}
return;
@@ -260,7 +484,21 @@ struct LanService::Impl
}
if(type=="presence" && trusted.contains(other) && j.value("epoch","")==peer.epoch &&
lan::equal(j.value("proof",""),lan::mac(trusted[other].at("key"),heartbeat(other,id,peer.epoch,epoch))))
{ peer.verified=now; return; }
{
peer.verified=now;
auto &entry=trusted.at(other);
const auto wakeMac=j.value("wakeMac","");
if(lan::wakePacket(wakeMac) && wakeMac!=entry.value("wakeMac","") &&
lan::equal(j.value("wakeProof",""),
lan::mac(entry.at("key"),heartbeat(other,id,peer.epoch,epoch)+"|wake|"+wakeMac)))
{
auto previous=entry;
entry["wakeMac"]=wakeMac;
try {save();}
catch(const std::exception &){entry=std::move(previous);}
}
return;
}
if(pending && pending->peer==other)
{
for(const auto &response:pending->receive(j,now)) send(socket,address,response);
@@ -269,7 +507,7 @@ struct LanService::Impl
auto previous=trusted;auto previousPositions=positions;
trusted[other]={{"name",peer.name},{"key",pending->derived}};
try {lan::fillPositions(positions,trusted,inputPeer,inputEdge);save();} catch(...) {trusted=std::move(previous);positions=std::move(previousPositions);throw;}
layoutChanged=true;peer.verified=now; status="Pair saved automatically. Arrange the monitors, then enable input sharing on both PCs.";
layoutChanged=true;peer.verified=now; status="Pair saved. Arrange the monitors, then enable input sharing and click Apply or Save on both PCs.";
}
}
}
@@ -295,15 +533,25 @@ struct LanService::Impl
{
std::lock_guard lock(mutex);
return !stopping && trusted.contains(peer)?trusted.at(peer).at("key").get<std::string>():std::string{};
},lan::FilesPort,lan::remoteTerminalAllowed,lan::hibernateFromPairedPC,[this]() -> DWORD
{
if(!lan::remoteUpdateAllowed()) return ERROR_ACCESS_DENIED;
if(!inputWindow) return ERROR_INVALID_WINDOW_HANDLE;
return PostMessageW(inputWindow,LanUpdateRequestedMessage,0,0)?ERROR_SUCCESS:GetLastError();
});
hub.datagrams([&](const auto &target,const auto &packet){
std::lock_guard lock(mutex);
if(shareInput&&trusted.contains(target)&&peers.contains(target))send(socket,peers.at(target).address,packet);
});
const bool filesListening=files.port()!=0;
if(!filesListening) diagnosticEvent(L"LAN Files could not listen on TCP 45885.");
bool filesListening=files.port()!=0;
while(!stopping)
{
files.poll();
if(filesListening!=(files.port()!=0))
{
filesListening=files.port()!=0;
nextHello=0;
}
auto now=GetTickCount64();bool clipboardActive=false;
std::vector<lan::InputEndpoint> endpoints;
{
@@ -315,14 +563,17 @@ struct LanService::Impl
if(peers.contains(target))send(socket,peers.at(target).address,packet);
});
clipboardActive=clipboard->active()||transfers->active();
if(shareInput)for(auto &[peer,entry]:trusted.items())
endpoints.push_back({peer,entry.at("key"),peers.contains(peer)?peers.at(peer).address.sin_addr.s_addr:0});
if(shareInput&&!inputPaused)for(auto &[peer,entry]:trusted.items())
{
const auto found=peers.find(peer);
const bool discovered=found!=peers.end()&&found->second.present(now);
endpoints.push_back({.id=peer,.key=entry.at("key"),
.address=discovered?found->second.address.sin_addr.s_addr:0,.discovered=discovered});
}
if(refreshFiles.exchange(false) || now>=nextHello)
{
epoch=lan::randomHex(16); // Fresh challenge prevents replayed presence from staying online.
auto hello=lan::envelope("hello",id); hello["name"]=name; hello["epoch"]=epoch;hello["clipboardSession"]=clipboard->session();
hello["fileSession"]=transfers->session();
hello["filesBrowse"]=filesListening;
const auto hello=discoveryAnnouncement(filesListening);
for(auto ip:broadcasts()) { auto address=bound; address.sin_addr.s_addr=ip; send(socket,address,hello); }
nextHello=now+3000;
}
@@ -338,11 +589,17 @@ struct LanService::Impl
}
}
std::vector<lan::RoutedInput> out,in;
std::unique_lock transportLock(transportMutex);
if (resetInputChannels)
{
hub.poll({}, {}, in, now);
resetInputChannels = false;
}
if (inputPaused) endpoints.clear();
{std::lock_guard lock(inputMutex);out.swap(inputOut);}
if(abortInput.exchange(false)){hub.disconnect();out.clear();}
hub.poll(endpoints,out,in,now);
files.poll();
auto readyPeers=hub.ready();inputConnected=!readyPeers.empty();
auto readyPeers=hub.ready();const auto connected=readyPeers.size();
{std::lock_guard lock(inputMutex);inputReady=std::move(readyPeers);
for(auto &frame:in){
if(!inputIn.empty()&&inputIn.back().peer==frame.peer&&inputIn.back().epoch==frame.epoch){
@@ -355,8 +612,11 @@ struct LanService::Impl
}
if(!in.empty()&&inputWindow&&!inputNotification.exchange(true))
if(!PostMessageW(inputWindow,LanInputReadyMessage,0,0))inputNotification=false;
{std::lock_guard lock(mutex);inputStatus=hub.status();inputNeedsHelp=hub.needsHelp();}
fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,!endpoints.empty()||clipboardActive?5000:100000};
const auto online=hub.onlinePeers();
updateInputStatus(connected,online,online||endpoints.empty()?hub.status():
"All paired PCs are offline. Waiting for LAN discovery.",hub.needsHelp());
transportLock.unlock();
fd_set read; FD_ZERO(&read); FD_SET(socket,&read); timeval delay{0,online||clipboardActive?5000:100000};
int ready=select(0,&read,nullptr,nullptr,&delay);
if(ready==SOCKET_ERROR) throw std::runtime_error("LAN discovery socket failed.");
if(ready>0) for(int count=0;count<64;++count)
@@ -369,23 +629,117 @@ struct LanService::Impl
auto j=Json::parse(buffer,buffer+received);
if(j.value("type","")=="input-udp"){
bool allowed=false;auto peer=j.value("id","");
{std::lock_guard lock(mutex);allowed=shareInput&&trusted.contains(peer)&&peers.contains(peer)&&peers.at(peer).address.sin_addr.s_addr==sender.sin_addr.s_addr;}
{std::lock_guard lock(mutex);allowed=shareInput&&!inputPaused&&trusted.contains(peer)&&peers.contains(peer)&&peers.at(peer).address.sin_addr.s_addr==sender.sin_addr.s_addr;}
if(allowed)hub.receiveDatagram(j,GetTickCount64());
}else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64());}
}else {std::lock_guard lock(mutex);receive(socket,sender,j,GetTickCount64(),filesListening);}
}
catch(const Json::exception &) {} // Malformed network data cannot interrupt discovery.
}
}
}
catch(const std::exception &e) { std::lock_guard lock(mutex); status=std::string("LAN stopped: ")+e.what(); }
inputConnected=false;++inputEpoch;
{std::lock_guard lock(mutex);if(shareInput)inputStatus="Input connection closed.";}
{std::lock_guard lock(inputMutex);inputOut.clear();inputIn.clear();inputReady.clear();}
++inputEpoch;
updateInputStatus(0,0,"Input connection closed.",false,true);
if(socket!=INVALID_SOCKET) closesocket(socket);
if(winsock) WSACleanup();
}
void removePeerState(const std::string &peer)
{
std::erase_if(incomingFiles, [&](const auto &file) { return file.peer == peer; });
if (logDownload && logDownload->peer == peer) logDownload.reset();
if (pending && pending->peer == peer) pending.reset();
}
void applySettings(const Json &draft)
{
std::unique_lock lock(mutex);
const auto before = std::tuple{enabled, shareInput, shareLogs, inputEdge, trusted, positions};
const bool discovery = draft.value("enabled", enabled);
const auto forgotten = draft.value("forget", Json::object());
auto nextTrusted = trusted;
for (const auto &[peer, ignored] : forgotten.items()) nextTrusted.erase(peer);
const bool nextInput = !nextTrusted.empty() && draft.value("shareInput", shareInput);
if (draft.value("shareInput", false) && (!discovery || nextTrusted.empty()))
throw std::runtime_error("Enable discovery and select a paired KSwitcher first.");
auto nextPositions = positions;
const auto moved = draft.value("positions", Json::object());
for (const auto &[peer, cell] : moved.items())
{
if (!nextTrusted.contains(peer)) throw std::runtime_error("Pair this computer before arranging it.");
nextPositions[peer] = cell;
}
lan::fillPositions(nextPositions, nextTrusted, inputPeer, inputEdge);
int edge = moved.contains(inputPeer) ? lan::cellEdge(nextPositions.at(inputPeer)) : -1;
std::unique_ptr<lan::Pairing> nextPair;
if (draft.contains("pair"))
{
const auto &pair = draft.at("pair");
auto peer = pair.at("peer").get<std::string>();
if (!enabled || !discovery || !peers.contains(peer) || !peers.at(peer).present(GetTickCount64()))
throw std::runtime_error("Select an available KSwitcher computer first.");
if (!nextTrusted.contains(peer) && nextTrusted.size() >= 64)
throw std::runtime_error("Remove an old pair before adding another computer.");
nextPair = std::make_unique<lan::Pairing>(id, peer, pair.at("code").get<std::string>(), GetTickCount64());
}
const bool discoveryChanged = discovery != enabled;
const bool routerChanged = discoveryChanged || nextInput != shareInput ||
nextPositions != positions || nextTrusted != trusted;
const bool nextLogs = draft.value("shareLogs", shareLogs);
const bool saveLan = routerChanged || nextLogs != shareLogs;
const bool hadFile = saveLan && std::filesystem::exists(path);
enabled = discovery;
shareInput = nextInput;
shareLogs = nextLogs;
if (edge >= 0) inputEdge = edge;
positions = std::move(nextPositions);
trusted = std::move(nextTrusted);
auto current = std::tie(enabled, shareInput, shareLogs, inputEdge, trusted, positions);
bool written = false;
try
{
if (saveLan) { save(); written = true; }
if (draft.contains("clients")) clients.apply(draft.at("clients"));
}
catch (...)
{
current = before;
if (written)
{
if (hadFile) save();
else std::filesystem::remove(path);
}
throw;
}
for (const auto &[peer, ignored] : forgotten.items()) removePeerState(peer);
if (std::get<2>(before) && !shareLogs)
for (const auto &[peer, entry] : trusted.items()) transfers->cancel(peer, "log-reply-");
if (nextPair)
{
pending = std::move(nextPair);
status = "Waiting for the same code on the other KSwitcher (2 minutes)...";
}
if (routerChanged) configureRouter();
lock.unlock();
if (discoveryChanged && discovery) start();
if (discoveryChanged && !discovery)
{
stop();
status = "Disabled. No discovery sockets or worker thread.";
}
}
std::mutex commandGate;
Bytes command(const Bytes &input)
{
std::lock_guard commandLock(commandGate);
auto j=Json::parse(input); auto action=j.value("action","status");
if (action == "trustedClients" || action == "inspectClient" || action == "trustClient" || action == "removeClient")
return encoded(clients.settings(action, j));
if (action == "applySettings")
{
applySettings(j.at("draft"));
return encoded(Json::object());
}
if(action=="enable")
{
stop();
@@ -394,7 +748,7 @@ struct LanService::Impl
configureRouter();
if(enabled) start(); else status="Disabled. No discovery sockets or worker thread.";
}
std::lock_guard lock(mutex);
std::unique_lock lock(mutex);
auto now=GetTickCount64();
if(action=="filesPeers") refreshFiles=true;
if(action=="shareLogs")
@@ -408,12 +762,16 @@ struct LanService::Impl
if(action=="sendFile" || action=="requestLog")
{
auto peer=j.at("peer").get<std::string>();
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).verified||
now-peers.at(peer).verified>=lan::PeerLifetime)
throw std::runtime_error("Select an online paired computer.");
if(!transfers->hasSession(peer))throw std::runtime_error("Update KSwitcher on the selected computer to use file transfers.");
const auto checkPeer = [&] {
if(!enabled||!trusted.contains(peer)||!peers.contains(peer)||!peers.at(peer).present(now))
throw std::runtime_error("Select an online paired computer.");
if(!transfers->hasSession(peer))
throw std::runtime_error("Update KSwitcher on the selected computer to use file transfers.");
};
checkPeer();
if(action=="sendFile")
{
lock.unlock();
auto file=std::filesystem::path(wide(j.at("path").get<std::string>()));
auto name=utf8(file.filename().wstring());
if(name.empty()||name.size()>1024)throw std::runtime_error("Invalid file name.");
@@ -423,6 +781,9 @@ struct LanService::Impl
if(std::filesystem::file_size(file)>fileLimit)throw std::runtime_error("File size limit is 16 MiB.");
auto bytes=readFile(file,fileLimit);
payload.insert(payload.end(),bytes.begin(),bytes.end());
lock.lock();
now=GetTickCount64();
checkPeer();
transfers->queue({peer},std::move(payload),"file",now);
return encoded({{"queued",true}});
}
@@ -454,17 +815,24 @@ struct LanService::Impl
}
if(action=="saveFile"||action=="discardFile")
{
auto found=std::find_if(incomingFiles.begin(),incomingFiles.end(),[&](const auto &file){
return file.id==j.at("id").get<std::string>() && file.peer==j.at("peer").get<std::string>();
});
const auto id=j.at("id").get<std::string>(), peer=j.at("peer").get<std::string>();
const auto findFile = [&] {
return std::find_if(incomingFiles.begin(),incomingFiles.end(),[&](const auto &file){
return file.id==id && file.peer==peer;
});
};
auto found=findFile();
if(found==incomingFiles.end())throw std::runtime_error("This file is no longer available.");
if(action=="saveFile")
{
auto start=std::find(found->bytes.begin(),found->bytes.end(),0)+1;
atomicWrite(wide(j.at("path").get<std::string>()),Bytes(start,found->bytes.end()));
const Bytes bytes(start,found->bytes.end());
lock.unlock();
atomicWrite(wide(j.at("path").get<std::string>()),bytes);
lock.lock();
found=findFile();
}
incomingFiles.erase(found);
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),FALSE);
if(found!=incomingFiles.end()) incomingFiles.erase(found);
}
if(action=="position")
{
@@ -510,16 +878,13 @@ struct LanService::Impl
auto peer=j.at("peer").get<std::string>();auto oldTrusted=trusted;auto oldPositions=positions;bool oldSharing=shareInput;
trusted.erase(peer);positions.erase(peer);if(trusted.empty())shareInput=false;
try{save();}catch(...){trusted=std::move(oldTrusted);positions=std::move(oldPositions);shareInput=oldSharing;throw;}
std::erase_if(incomingFiles,[&](const auto &file){return file.peer==peer;});
if(inputWindow)PostMessageW(inputWindow,LanFilesChangedMessage,incomingFiles.size(),FALSE);
if(logDownload && logDownload->peer==peer)logDownload.reset();
if(pending&&pending->peer==peer)pending.reset();
removePeerState(peer);
configureRouter();
status="Pair removed on this computer.";
}
Json result={{"enabled",enabled},{"id",id},{"name",name},{"status",status},{"pending",pending&&!pending->confirmed},{"peers",Json::array()},
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnected.load()},
{"inputStatus",enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}};
{"positions",positions},{"shareInput",shareInput},{"inputPeer",inputPeer},{"controlPeer",router?router->peer():std::string{}},{"inputEdge",inputEdge},{"inputConnected",inputConnectedPeers!=0},
{"inputStatus",inputPaused?"Input processing paused in the tray.":enabled&&shareInput?inputStatus:"Input sharing disabled."},{"inputNeedsHelp",!inputPaused&&enabled&&shareInput&&inputNeedsHelp},{"controlMode",router?int(router->mode()):0}};
{std::lock_guard inputLock(inputMutex);result["inputReady"]=inputReady;}
result["shareLogs"]=shareLogs;
result["files"]=Json::array();
@@ -539,7 +904,7 @@ struct LanService::Impl
if(action=="filesPeers" && !trusted.contains(peer)) continue;
char ip[INET_ADDRSTRLEN]{}; InetNtopA(AF_INET,(void*)&p.address.sin_addr,ip,sizeof(ip));
result["peers"].push_back({{"id",peer},{"name",p.name},{"address",ip},{"paired",trusted.contains(peer)},
{"verified",p.verified && now-p.verified<lan::PeerLifetime},{"online",true},
{"verified",p.present(now)},{"online",true},
{"fileTransfer",transfers->hasSession(peer)},{"filesBrowse",p.files}});
}
for(const auto &[peer,p]:trusted.items()) if(!peers.contains(peer))
@@ -547,9 +912,10 @@ struct LanService::Impl
return encoded(result);
}
};
LanService::LanService(const std::filesystem::path &path,HWND window) : impl(std::make_unique<Impl>(path,window)) {}
LanService::LanService(const std::filesystem::path &path,HWND window,bool paused) : impl(std::make_unique<Impl>(path,window,paused)) {}
LanService::~LanService()=default;
Bytes LanService::command(const Bytes &command) { return impl->command(command); }
void LanService::startClients() { impl->startClients(); }
bool LanService::clipboardEnabled()const
{
std::lock_guard lock(impl->mutex);
@@ -571,7 +937,15 @@ std::vector<LanClipboard> LanService::takeClipboard()
result.push_back({d.peer,impl->trusted.at(d.peer).at("name"),d.app,std::move(d.bytes),d.sequence});
impl->clipboard->deliveries.clear();return result;
}
bool LanService::inputEnabled()const{return impl->enabled&&impl->shareInput;}
bool LanService::inputEnabled()const{return impl->enabled&&impl->shareInput&&!impl->inputPaused;}
void LanService::setInputPaused(bool paused){impl->setInputPaused(paused);}
LanInputConnections LanService::inputConnections()const
{
std::lock_guard lock(impl->mutex);
if(!inputEnabled())return {};
const auto paired=impl->trusted.size();
return {std::min(impl->inputConnectedPeers,paired),std::min(impl->inputOnlinePeers,paired),paired,impl->inputWorkerStopped};
}
bool LanService::tickInput(bool allowEnter){return impl->tickInput(allowEnter);}
bool LanService::keyboard(const KBDLLHOOKSTRUCT &k,bool down){return impl->router&&impl->router->keyboard(k,down,GetTickCount64());}
bool LanService::mouse(UINT message,const MSLLHOOKSTRUCT &m,bool allowEnter){return impl->router&&impl->router->mouse(message,m,GetTickCount64(),allowEnter);}
+13 -2
View File
@@ -5,21 +5,32 @@
namespace ks
{
inline constexpr UINT LanInputReadyMessage=WM_APP+67, LanClipboardReadyMessage=WM_APP+68, LanClipboardPublishMessage=WM_APP+69;
inline constexpr UINT LanFilesChangedMessage=WM_APP+70;
inline constexpr UINT LanUpdateRequestedMessage=WM_APP+90;
inline constexpr UINT LanInputStatusMessage=WM_APP+91;
struct LanClipboard {std::string peer,name,app;Bytes data;DWORD sequence{};};
struct LanInputConnections
{
size_t connected{}, online{}, paired{};
bool stopped{};
bool reconnecting()const{return !stopped&&connected<online;}
bool operator==(const LanInputConnections &) const = default;
};
// Discovery, pairing and optional encrypted input within the resident process.
class LanService
{
struct Impl;
std::unique_ptr<Impl> impl;
public:
explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr);
explicit LanService(const std::filesystem::path &, HWND inputWindow=nullptr, bool inputPaused=false);
~LanService();
Bytes command(const Bytes &);
void startClients();
bool clipboardEnabled() const;
void publishClipboard(Bytes, const std::string &);
std::vector<LanClipboard> takeClipboard();
bool inputEnabled() const;
void setInputPaused(bool);
LanInputConnections inputConnections() const;
bool tickInput(bool allowEnter = true);
bool keyboard(const KBDLLHOOKSTRUCT &, bool down);
bool mouse(UINT, const MSLLHOOKSTRUCT &, bool allowEnter);
+25 -11
View File
@@ -213,6 +213,7 @@ bool InputChannel::adopt(uintptr_t accepted,uint64_t now)
impl->connecting=false;impl->begin(now);impl->socket=SOCKET(accepted);return true;
}
bool InputChannel::ready()const{return impl->authenticated;}
bool InputChannel::handshaking()const{return impl->socket!=INVALID_SOCKET&&!impl->authenticated;}
uint64_t InputChannel::generation()const{return impl->changed;}
std::string InputChannel::status()const{
return impl->lastError.empty() ? impl->state : impl->lastError+" Retrying automatically.";
@@ -221,7 +222,16 @@ void InputChannel::disconnect(){impl->reset(GetTickCount64(),"Input disconnected
std::string InputChannel::transport()const{return impl->reverse?"reverse TCP":"direct TCP";}
struct InputHub::Impl
{
struct Link { InputEndpoint endpoint;std::unique_ptr<InputChannel> channel;std::unique_ptr<InputDatagram> udp;uint64_t generation{},epoch{},since{},failedSince{};bool udpReady{};std::string lastState; };
struct Link
{
InputEndpoint endpoint;
std::unique_ptr<InputChannel> channel;
std::unique_ptr<InputDatagram> udp;
uint64_t generation{},epoch{},since{},failedSince{};
bool udpReady{};
std::string lastState;
bool ready()const{return channel->ready()||udp->ready();}
};
struct Pending {SOCKET socket;uint32_t address;uint64_t since;};
std::string local;uint16_t port;SOCKET listener=INVALID_SOCKET;
std::map<std::string,Link> links;std::vector<Pending> pending;uint64_t epoch{},retry{};
@@ -235,17 +245,18 @@ struct InputHub::Impl
currentTime=now;
for(auto it=links.begin();it!=links.end();){
auto match=std::find_if(endpoints.begin(),endpoints.end(),[&](auto &e){return e.id==it->first&&e.key==it->second.endpoint.key&&e.port==it->second.endpoint.port;});
if(match==endpoints.end())it=links.erase(it);else ++it;
// Discovery gates new attempts. An authenticated connection can outlive discovery.
if(match==endpoints.end()||(!match->discovered&&!it->second.ready()))it=links.erase(it);else ++it;
}
for(auto &e:endpoints)if(e.id!=local&&!links.contains(e.id)){
for(auto &e:endpoints)if(e.discovered&&e.id!=local&&!links.contains(e.id)){
Link link;link.endpoint=e;link.channel=std::make_unique<InputChannel>(local,e.id,e.key,0,e.port,true);
link.udp=std::make_unique<InputDatagram>(local,e.id,e.key);link.since=link.failedSince=now;link.epoch=++epoch;links.emplace(e.id,std::move(link));
}
// Discovery is a hint, not the lifetime of authenticated input sessions.
// Keep the last usable address across missed announcements. A new address
// is used only once a channel is down, never to tear down working input.
for(auto &e:endpoints){if(e.id==local)continue;auto &link=links.at(e.id);
if(e.address&&!link.channel->ready()&&e.address!=link.endpoint.address){
for(auto &e:endpoints){if(!e.discovered||e.id==local)continue;auto &link=links.at(e.id);
if(e.address&&!link.ready()&&e.address!=link.endpoint.address){
link.channel->disconnect();link.endpoint.address=e.address;
}
}
@@ -279,14 +290,16 @@ struct InputHub::Impl
}
for(auto &[id,link]:links){
std::vector<InputFrame> frames,received;for(auto &f:out)if(f.peer==id&&(!f.epoch||f.epoch==link.epoch))enqueueInput(frames,f.frame);
if(sendDatagram&&!link.channel->ready()&&!link.udp->active()&&local<id&&now-link.since>=5000){link.udp->start(now);link.channel->disconnect();frames.clear();}
// Let an in-flight TCP connection finish or hit its own deadline.
// Check before poll() so another TCP retry cannot starve UDP fallback.
if(sendDatagram&&!link.channel->ready()&&!link.channel->handshaking()&&
!link.udp->active()&&local<id&&now-link.since>=5000){link.udp->start(now);frames.clear();}
if(link.udp->active()){
link.udp->poll(frames,received,now,sendDatagram);
if(!link.udp->active()){link.since=now;link.channel->disconnect();received.clear();}
}else link.channel->poll(link.endpoint.address,frames,received,now);
if(link.udpReady!=link.udp->ready()){link.udpReady=link.udp->ready();link.epoch=++epoch;}
bool ready=link.channel->ready()||link.udp->ready();
if(ready)link.failedSince=link.since=now;
if(link.ready())link.failedSince=link.since=now;
auto state=link.udp->ready()?"Input connected via encrypted UDP.":link.udp->active()?"Trying encrypted UDP over discovery...":link.channel->ready()?"Input connected via "+link.channel->transport()+".":link.channel->status();
if(state!=link.lastState){link.lastState=state;log(L"LAN input peer "+wide(id.substr(0,8))+L": "+wide(state));}
if(link.generation!=link.channel->generation()){link.generation=link.channel->generation();link.epoch=++epoch;}
@@ -297,7 +310,8 @@ struct InputHub::Impl
InputHub::InputHub(std::string id,uint16_t port):impl(std::make_unique<Impl>(std::move(id),port)){}
InputHub::~InputHub()=default;
void InputHub::poll(const std::vector<InputEndpoint> &peers,const std::vector<RoutedInput> &out,std::vector<RoutedInput> &in,uint64_t now){impl->poll(peers,out,in,now);}
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> result;for(auto &[id,l]:impl->links)if(l.channel->ready()||l.udp->ready())result[id]=l.epoch;return result;}
std::map<std::string,uint64_t> InputHub::ready()const{std::map<std::string,uint64_t> result;for(auto &[id,l]:impl->links)if(l.ready())result[id]=l.epoch;return result;}
size_t InputHub::onlinePeers()const{return impl->links.size();}
std::string InputHub::status()const{
auto count=ready().size();if(count==impl->links.size()&&count){
std::string routes;for(auto &[id,l]:impl->links){if(!routes.empty())routes+=", ";routes+=id.substr(0,8)+": "+(l.udp->ready()?"encrypted UDP":l.channel->transport());}
@@ -305,7 +319,7 @@ std::string InputHub::status()const{
}
if(needsHelp())return "Automatic connection attempts have not succeeded for every PC. Enable input on both PCs. Open Connection help for firewall commands.";
if(!impl->error.empty())return impl->error;
for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready())return l.lastState;
for(auto &[id,l]:impl->links)if(!l.ready())return l.lastState;
return "Waiting for paired computers...";
}
void InputHub::disconnect(){for(auto &[id,l]:impl->links){l.channel->disconnect();l.udp->reset();l.since=impl->currentTime;}}
@@ -318,7 +332,7 @@ void InputHub::receiveDatagram(const Json &j,uint64_t now){
if(!active&&link.udp->active())link.channel->disconnect();
}
bool InputHub::needsHelp()const{
for(auto &[id,l]:impl->links)if(!l.channel->ready()&&!l.udp->ready()&&impl->currentTime-l.failedSince>=15000)return true;
for(auto &[id,l]:impl->links)if(!l.ready()&&impl->currentTime-l.failedSince>=15000)return true;
return false;
}
}
+9 -1
View File
@@ -55,12 +55,19 @@ class InputChannel
void poll(uint32_t peerAddress,const std::vector<InputFrame> &out,std::vector<InputFrame> &in,uint64_t now);
bool adopt(uintptr_t socket,uint64_t now);
bool ready() const;
bool handshaking() const;
uint64_t generation() const;
std::string status() const;
void disconnect();
std::string transport()const;
};
struct InputEndpoint {std::string id,key;uint32_t address{};uint16_t port=45884;};
struct InputEndpoint
{
std::string id,key;
uint32_t address{};
uint16_t port=45884;
bool discovered=true;
};
struct RoutedInput {std::string peer;InputFrame frame;uint64_t epoch{};};
class InputHub
{
@@ -70,6 +77,7 @@ class InputHub
~InputHub();
void poll(const std::vector<InputEndpoint> &,const std::vector<RoutedInput> &,std::vector<RoutedInput> &,uint64_t now);
std::map<std::string,uint64_t> ready()const;
size_t onlinePeers()const;
std::string status()const;
void disconnect();
using SendDatagram=std::function<void(const std::string &,const Json &)>;
+278
View File
@@ -0,0 +1,278 @@
#pragma once
#include "lan_pairing.h"
#include <bcrypt.h>
#include <sddl.h>
#include <array>
#include <functional>
#include <mutex>
#include <thread>
namespace ks::lan
{
class LanClients
{
struct Handle
{
HANDLE value{};
~Handle() { if (value && value != INVALID_HANDLE_VALUE) CloseHandle(value); }
explicit operator bool() const { return value && value != INVALID_HANDLE_VALUE; }
};
struct ClientImage
{
Handle file;
std::wstring path;
std::string digest;
FILETIME modified{};
explicit ClientImage(const std::wstring &filename)
: file{CreateFileW(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN, nullptr)}
{
if (!file || GetFileType(file.value) != FILE_TYPE_DISK)
throw std::runtime_error("Choose a readable executable.");
wchar_t finalPath[32768];
const auto length = GetFinalPathNameByHandleW(file.value, finalPath, DWORD(std::size(finalPath)), 0);
if (!length || length >= std::size(finalPath) ||
_wcsicmp(std::filesystem::path(std::wstring(finalPath, length)).extension().c_str(), L".exe") ||
!GetFileTime(file.value, nullptr, nullptr, &modified))
throw std::runtime_error("Choose a Windows .exe file.");
path.assign(finalPath, length);
struct Hash
{
BCRYPT_HASH_HANDLE handle{};
~Hash() { if (handle) BCryptDestroyHash(handle); }
} hash;
std::array<unsigned char, 65536> buffer{};
std::array<unsigned char, 32> bytes{};
if (BCryptCreateHash(BCRYPT_SHA256_ALG_HANDLE, &hash.handle, nullptr, 0, nullptr, 0, 0) < 0)
throw std::runtime_error("Could not fingerprint the executable.");
DWORD count{};
do
{
if (!ReadFile(file.value, buffer.data(), DWORD(buffer.size()), &count, nullptr) ||
(count && BCryptHashData(hash.handle, buffer.data(), count, 0) < 0))
throw std::runtime_error("Could not fingerprint the executable.");
} while (count);
if (BCryptFinishHash(hash.handle, bytes.data(), ULONG(bytes.size()), 0) < 0)
throw std::runtime_error("Could not fingerprint the executable.");
for (auto byte : bytes)
{
digest += "0123456789abcdef"[byte >> 4];
digest += "0123456789abcdef"[byte & 15];
}
}
};
const std::filesystem::path store;
mutable std::mutex storeMutex;
Handle stopped{CreateEventW(nullptr, TRUE, FALSE, nullptr)};
std::jthread thread;
bool io(HANDLE pipe, void *buffer, DWORD length, bool write) const
{
auto *cursor = static_cast<unsigned char *>(buffer);
while (length)
{
Handle event{CreateEventW(nullptr, TRUE, FALSE, nullptr)};
if (!event) return false;
OVERLAPPED op{};
op.hEvent = event.value;
DWORD count{};
const auto completed = write ? WriteFile(pipe, cursor, length, &count, &op) :
ReadFile(pipe, cursor, length, &count, &op);
if (!completed && (GetLastError() != ERROR_IO_PENDING || !wait(pipe, op, count, 10000))) return false;
if (!count) return false;
cursor += count;
length -= count;
}
return true;
}
bool wait(HANDLE pipe, OVERLAPPED &op, DWORD &count, DWORD timeout) const
{
const HANDLE events[]{stopped.value, op.hEvent};
if (WaitForMultipleObjects(2, events, FALSE, timeout) != WAIT_OBJECT_0 + 1)
{
CancelIoEx(pipe, &op);
GetOverlappedResult(pipe, &op, &count, TRUE);
return false;
}
return GetOverlappedResult(pipe, &op, &count, FALSE) != FALSE;
}
bool writeFrame(HANDLE pipe, const void *buffer, DWORD length) const
{
return io(pipe, &length, sizeof(length), true) &&
(!length || io(pipe, const_cast<void *>(buffer), length, true));
}
Json clients() const
{
return std::filesystem::exists(store) ? Json::parse(unprotect(readFile(store, 256 * 1024))) : Json::array();
}
using Rule = std::function<void()>;
Rule authorize(HANDLE pipe) const
{
ULONG pid{};
if (!GetNamedPipeClientProcessId(pipe, &pid))
throw std::runtime_error("Could not identify the local client.");
auto process = std::make_shared<Handle>();
process->value = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, FALSE, pid);
wchar_t filename[32768];
DWORD length = DWORD(std::size(filename));
FILETIME started{}, exited{}, kernel{}, user{};
if (!*process || !QueryFullProcessImageNameW(process->value, 0, filename, &length) ||
!GetProcessTimes(process->value, &started, &exited, &kernel, &user))
throw std::runtime_error("Could not identify the local client.");
auto image = std::make_shared<ClientImage>(std::wstring(filename, length));
if (CompareFileTime(&image->modified, &started) > 0)
throw std::runtime_error("Restart the client after replacing its executable.");
Rule check = [this, process, image] {
if (WaitForSingleObject(stopped.value, 0) != WAIT_TIMEOUT ||
WaitForSingleObject(process->value, 0) != WAIT_TIMEOUT)
throw std::runtime_error("The local client disconnected.");
std::lock_guard lock(storeMutex);
for (const auto &entry : clients())
if (!_wcsicmp(wide(entry.at("path").get<std::string>()).c_str(), image->path.c_str()) &&
entry.at("sha256") == image->digest) return;
throw std::runtime_error("Authorize this executable in KSwitcher → Computers → Trusted clients.");
};
check();
return check;
}
struct LocalMemory
{
void *value{};
~LocalMemory() { if (value) LocalFree(value); }
};
using Send = std::function<void(const void *, DWORD)>;
using Route = std::function<void(const Json &, const Rule &, const Send &)>;
void serve(const Route &route, const std::wstring &instance) const
{
HANDLE rawToken{};
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &rawToken)) return;
Handle token{rawToken};
DWORD size{};
GetTokenInformation(token.value, TokenUser, nullptr, 0, &size);
Bytes info(size);
if (!size || !GetTokenInformation(token.value, TokenUser, info.data(), size, &size)) return;
LPWSTR sid{};
if (!ConvertSidToStringSidW(reinterpret_cast<TOKEN_USER *>(info.data())->User.Sid, &sid)) return;
LocalMemory sidOwner{sid};
const auto sddl = std::wstring(L"D:P(A;;GA;;;") + sid + L")";
PSECURITY_DESCRIPTOR descriptor{};
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(), SDDL_REVISION_1, &descriptor, nullptr)) return;
LocalMemory descriptorOwner{descriptor};
SECURITY_ATTRIBUTES security{sizeof(security), descriptor, FALSE};
DWORD session{};
if (!ProcessIdToSessionId(GetCurrentProcessId(), &session)) return;
const auto name = L"\\\\.\\pipe\\KSwitcher.LAN.Clients.v1." + std::to_wstring(session) + instance;
Handle pipe{CreateNamedPipeW(name.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_REJECT_REMOTE_CLIENTS, 1, 65536, 65536, 0, &security)};
if (!pipe) return;
while (WaitForSingleObject(stopped.value, 0) == WAIT_TIMEOUT)
{
Handle event{CreateEventW(nullptr, TRUE, FALSE, nullptr)};
if (!event) return;
OVERLAPPED op{};
op.hEvent = event.value;
DWORD count{};
if (!ConnectNamedPipe(pipe.value, &op))
{
const auto error = GetLastError();
if (error == ERROR_NO_DATA)
{
DisconnectNamedPipe(pipe.value);
continue;
}
if (error != ERROR_PIPE_CONNECTED &&
(error != ERROR_IO_PENDING || !wait(pipe.value, op, count, INFINITE))) return;
}
try
{
DWORD length{};
if (io(pipe.value, &length, sizeof(length), false) && length && length <= 16384)
{
std::string request(length, '\0');
if (io(pipe.value, request.data(), length, false))
{
auto check = authorize(pipe.value);
route(Json::parse(request), check, [&](const void *data, DWORD bytes) {
check();
if (!writeFrame(pipe.value, data, bytes)) throw std::runtime_error("The local client disconnected.");
});
}
}
}
catch (const std::exception &e)
{
const auto error = Json{{"error", e.what()}}.dump(-1, ' ', false, Json::error_handler_t::replace);
writeFrame(pipe.value, error.data(), DWORD(error.size()));
}
// Let the client consume the final response before recycling the pipe.
char acknowledgement{};
io(pipe.value, &acknowledgement, 1, false);
DisconnectNamedPipe(pipe.value);
}
}
public:
explicit LanClients(const std::filesystem::path &root) : store(root / L"lan-clients.bin") {}
~LanClients() { if (stopped) SetEvent(stopped.value); }
void start(Route route, std::wstring instance = {})
{
if (stopped) thread = std::jthread([this, route = std::move(route), instance = std::move(instance)] {
serve(route, instance);
});
}
void stop() { if (stopped) SetEvent(stopped.value); if (thread.joinable()) thread.join(); }
private:
static void editClient(Json &entries, const std::string &action, const Json &request)
{
const auto path = wide(request.at("path").get<std::string>());
if (action == "trustClient")
{
ClientImage image(path);
if (request.contains("sha256") &&
(request.at("sha256") != image.digest || _wcsicmp(image.path.c_str(), path.c_str())))
throw std::runtime_error("The executable changed. Add it again before saving.");
std::erase_if(entries.get_ref<Json::array_t &>(), [&](const auto &entry) {
return !_wcsicmp(wide(entry.at("path").template get<std::string>()).c_str(), image.path.c_str());
});
if (entries.size() >= 64) throw std::runtime_error("The trusted client list is full.");
entries.push_back({{"path", utf8(image.path)}, {"sha256", image.digest}});
}
else
{
std::erase_if(entries.get_ref<Json::array_t &>(), [&](const auto &entry) {
return !_wcsicmp(wide(entry.at("path").template get<std::string>()).c_str(), path.c_str());
});
}
}
void save(const Json &entries) const
{
const auto text = entries.dump();
atomicWrite(store, protect(Bytes(text.begin(), text.end())));
}
public:
Json settings(const std::string &action, const Json &request) const
{
std::lock_guard lock(storeMutex);
if (action == "inspectClient")
{
ClientImage image(wide(request.at("path").get<std::string>()));
return {{"path", utf8(image.path)}, {"sha256", image.digest}};
}
auto entries = clients();
if (action == "trustedClients") return entries;
editClient(entries, action, request);
save(entries);
return entries;
}
void apply(const Json &changes) const
{
std::lock_guard lock(storeMutex);
auto entries = clients();
for (const auto &change : changes)
if (change.at("action") == "removeClient") editClient(entries, "removeClient", change);
for (const auto &change : changes)
if (change.at("action") == "trustClient") editClient(entries, "trustClient", change);
save(entries);
}
};
}
+52 -14
View File
@@ -13,7 +13,20 @@ class ClipboardExchange
{
static constexpr size_t Limit=32*1024*1024, Chunk=480, Window=32;
struct Item {std::string id,app;Bytes bytes;};
struct Sending {std::deque<std::shared_ptr<Item>> queue;size_t ack{};bool begun{};uint64_t last{},progress{};};
struct Sending
{
std::deque<std::shared_ptr<Item>> queue;
size_t ack{}, sentUpTo{};
bool begun{};
uint64_t retryAt{}, progress{};
void reset(uint64_t now)
{
ack=sentUpTo=0;
begun=false;
retryAt=0;
progress=now;
}
};
struct Receiving {std::string id,app;Bytes bytes;size_t size{};uint64_t last{};DWORD sequence{};};
std::string local, type, domain, boot=randomHex(16);
std::map<std::string,std::string> sessions;
@@ -55,12 +68,12 @@ class ClipboardExchange
if(s.queue.empty())return;
bool reset=s.queue.front()->app.starts_with(prefix);
std::erase_if(s.queue,[&](const auto &item){return item->app.starts_with(prefix);});
if(reset){s.ack=0;s.begun=false;s.last=0;s.progress=GetTickCount64();}
if(reset)s.reset(GetTickCount64());
}
void peerSession(const std::string &peer,const std::string &value){
if(!identifier(value))return;
if(sessions.contains(peer)&&sessions.at(peer)!=value){
auto found=sending.find(peer);if(found!=sending.end()){found->second.ack=0;found->second.begun=false;found->second.last=0;}
auto found=sending.find(peer);if(found!=sending.end())found->second.reset(found->second.progress);
if(type!="clipboard"){
auto previous=receiving.find(peer);
if(previous!=receiving.end()){incomingBytes-=previous->second.size;receiving.erase(previous);}
@@ -76,7 +89,7 @@ class ClipboardExchange
for(auto &[peer,s]:sending)for(auto &item:s.queue)if(counted.insert(item.get()).second)total+=item->bytes.size();
if(total>2*Limit)throw std::runtime_error("LAN clipboard queue is full.");
auto item=std::make_shared<Item>(Item{randomHex(16),app.size()>128?std::string("Application"):app,std::move(bytes)});
for(auto &peer:peers){auto &s=sending[peer];if(s.queue.size()>=8){if(type!="clipboard")throw std::runtime_error("LAN transfer queue is full.");continue;}if(s.queue.empty()){s.ack=0;s.begun=false;s.last=0;s.progress=now;}s.queue.push_back(item);}
for(auto &peer:peers){auto &s=sending[peer];if(s.queue.size()>=8){if(type!="clipboard")throw std::runtime_error("LAN transfer queue is full.");continue;}if(s.queue.empty())s.reset(now);s.queue.push_back(item);}
if(!peers.empty())status=type=="clipboard"?"Sending clipboard to "+std::to_string(peers.size())+" paired computers...":"Sending…";
}
template<class Send>void poll(const Json &trusted,uint64_t now,Send send)
@@ -88,14 +101,30 @@ class ClipboardExchange
auto &peer=it->first;auto &s=it->second;
if(!trusted.contains(peer)||s.queue.empty()){it=sending.erase(it);continue;}
if(now-s.progress>30000){status="Transfer timed out.";it=sending.erase(it);continue;}
if(sessions.contains(peer)&&(!s.last||now-s.last>=100))
auto &item=*s.queue.front();
const auto limit=std::min(item.bytes.size(),s.ack+Window*Chunk);
const bool retry=s.retryAt && now>=s.retryAt;
const bool sendBegin=!s.begun && (!s.retryAt || retry);
const bool sendChunks=s.begun && (s.sentUpTo<limit || retry);
if(sessions.contains(peer) && (sendBegin || sendChunks))
{
auto &item=*s.queue.front();auto key=trusted.at(peer).at("key").template get<std::string>();
if(!s.begun)send(peer,seal(peer,key,{{"op","begin"},{"item",item.id},{"size",item.bytes.size()},{"app",item.app}}));
else for(size_t offset=s.ack,n=0;offset<item.bytes.size()&&n<Window;offset+=Chunk,++n)
send(peer,seal(peer,key,{{"op","chunk"},{"item",item.id},{"offset",offset},
{"bytes",Json::binary(Bytes(item.bytes.begin()+offset,item.bytes.begin()+std::min(offset+Chunk,item.bytes.size())))}}));
s.last=now;
auto key=trusted.at(peer).at("key").template get<std::string>();
if(sendBegin)
send(peer,seal(peer,key,{{"op","begin"},{"item",item.id},{"size",item.bytes.size()},{"app",item.app}}));
else
{
// ACKs open new slots. Only a timeout retransmits outstanding chunks.
if(retry) s.sentUpTo=s.ack;
while(s.sentUpTo<limit)
{
const auto offset=s.sentUpTo;
const auto end=std::min(offset+Chunk,item.bytes.size());
send(peer,seal(peer,key,{{"op","chunk"},{"item",item.id},{"offset",offset},
{"bytes",Json::binary(Bytes(item.bytes.begin()+offset,item.bytes.begin()+end))}}));
s.sentUpTo=end;
}
}
if(!s.retryAt || retry) s.retryAt=now+100;
}
++it;
}
@@ -119,10 +148,19 @@ class ClipboardExchange
{
auto found=sending.find(peer);if(found==sending.end()||found->second.queue.empty())return;
auto &s=found->second;auto &item=*s.queue.front();auto offset=body.at("offset").get<size_t>();
if(item.id!=id||offset>item.bytes.size()||offset<s.ack||offset>s.ack+Window*Chunk||(offset!=item.bytes.size()&&offset%Chunk))return;
const auto maxAck=s.begun?s.sentUpTo:Window*Chunk;
if(item.id!=id||offset>item.bytes.size()||offset<s.ack||offset>maxAck||(offset!=item.bytes.size()&&offset%Chunk))return;
if(offset==s.ack&&s.begun)return;
s.begun=true;s.ack=offset;s.progress=now;s.last=0;
if(offset==item.bytes.size()){s.queue.pop_front();s.ack=0;s.begun=false;status=type=="clipboard"?"Clipboard delivered.":"Transfer delivered.";}
s.begun=true;
s.ack=offset;
s.sentUpTo=std::max(s.sentUpTo,offset);
s.progress=now;
s.retryAt=offset<s.sentUpTo?now+100:0;
if(offset==item.bytes.size()){
s.queue.pop_front();
s.reset(now);
status=type=="clipboard"?"Clipboard delivered.":"Transfer delivered.";
}
return;
}
for(auto &done:completed[peer])if(done.first==id){ack(done.second);return;}
+373 -41
View File
@@ -1,12 +1,20 @@
#include "files_powershell.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <shellapi.h>
#include <shlobj.h>
#include <winioctl.h>
#include <atomic>
#include <bcrypt.h>
#include <wincrypt.h>
#include <sddl.h>
#include <winsafer.h>
#include <cstring>
#include <mutex>
#include <thread>
#include "lan_files.h"
#include "lan_channel.h"
#include "lan_network.h"
namespace ks::lan
{
@@ -28,6 +36,17 @@ void checkFileReply(const Json &reply)
if(error) throw std::system_error(static_cast<int>(error),std::system_category());
}
static bool filesPermissionEnabled(const wchar_t *name)
{
DWORD allowed{},size=sizeof(allowed);
return RegGetValueW(HKEY_CURRENT_USER,L"Software\\KSwitcher\\Files",name,
RRF_RT_REG_DWORD,nullptr,&allowed,&size)==ERROR_SUCCESS && allowed==1;
}
bool remoteTerminalAllowed() {return filesPermissionEnabled(remoteTerminalPreference);}
bool remoteHibernateAllowed() {return filesPermissionEnabled(remoteHibernatePreference);}
bool remoteUpdateAllowed() {return filesPermissionEnabled(remoteUpdatePreference);}
bool recycleFile(HWND owner,const fs::path &path)
{
const auto initialized=CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);
@@ -52,30 +71,46 @@ bool recycleFile(HWND owner,const fs::path &path)
namespace
{
constexpr size_t FrameLimit=256*1024;
constexpr DWORD SocketTimeout=5000;
struct WinSocket
DWORD createJunction(const fs::path &name,const fs::path &target)
{
SOCKET value=INVALID_SOCKET;
~WinSocket(){if(value!=INVALID_SOCKET) closesocket(value);}
};
if(!target.is_absolute() || target.root_name().native().size()!=2) return ERROR_INVALID_NAME;
const auto print=target.lexically_normal().native();
const auto substitute=L"\\??\\"+print;
struct MountPointHeader
{
DWORD tag;
WORD dataLength,reserved,substituteOffset,substituteLength,printOffset,printLength;
};
const auto substituteBytes=substitute.size()*sizeof(wchar_t);
const auto printBytes=print.size()*sizeof(wchar_t);
const auto pathBytes=substituteBytes+printBytes+2*sizeof(wchar_t);
if(sizeof(MountPointHeader)+pathBytes>MAXIMUM_REPARSE_DATA_BUFFER_SIZE) return ERROR_FILENAME_EXCED_RANGE;
const MountPointHeader header{IO_REPARSE_TAG_MOUNT_POINT,static_cast<WORD>(8+pathBytes),0,0,
static_cast<WORD>(substituteBytes),static_cast<WORD>(substituteBytes+sizeof(wchar_t)),
static_cast<WORD>(printBytes)};
std::vector<char> buffer(sizeof(header)+pathBytes);
std::memcpy(buffer.data(),&header,sizeof(header));
std::memcpy(buffer.data()+sizeof(header),substitute.c_str(),substituteBytes);
std::memcpy(buffer.data()+sizeof(header)+header.printOffset,print.c_str(),printBytes);
void socketError()
{
throw std::system_error(WSAGetLastError(),std::system_category());
if(!CreateDirectoryW(name.c_str(),nullptr)) return GetLastError();
const auto handle=CreateFileW(name.c_str(),GENERIC_WRITE,0,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr);
DWORD error=ERROR_SUCCESS;
if(handle==INVALID_HANDLE_VALUE) error=GetLastError();
else
{
DWORD returned{};
if(!DeviceIoControl(handle,FSCTL_SET_REPARSE_POINT,buffer.data(),static_cast<DWORD>(buffer.size()),
nullptr,0,&returned,nullptr)) error=GetLastError();
CloseHandle(handle);
}
if(error) RemoveDirectoryW(name.c_str());
return error;
}
struct Network
{
Network()
{
WSADATA data{};
if(const auto error=WSAStartup(MAKEWORD(2,2),&data))
throw std::system_error(error,std::system_category());
}
~Network(){WSACleanup();}
};
constexpr size_t FrameLimit=256*1024;
constexpr DWORD SocketTimeout=5000;
class Wire
{
@@ -182,6 +217,189 @@ struct FileHandle
~FileHandle(){close();}
};
DWORD requestSystemHibernate()
{
wchar_t system[MAX_PATH]{};
const auto length=GetSystemDirectoryW(system,MAX_PATH);
if(!length) return GetLastError();
if(length>=MAX_PATH) return ERROR_INSUFFICIENT_BUFFER;
const auto executable=fs::path(system)/L"shutdown.exe";
wchar_t command[]=L"shutdown.exe /h";
STARTUPINFOW startup{sizeof(startup)};
PROCESS_INFORMATION child{};
if(!CreateProcessW(executable.c_str(),command,nullptr,nullptr,FALSE,CREATE_NO_WINDOW,
nullptr,system,&startup,&child)) return GetLastError();
CloseHandle(child.hThread);
FileHandle process{child.hProcess};
const auto wait=WaitForSingleObject(process.value,3000);
if(wait==WAIT_TIMEOUT) return ERROR_TIMEOUT;
if(wait!=WAIT_OBJECT_0) return GetLastError();
DWORD exitCode{};
return GetExitCodeProcess(process.value,&exitCode)?exitCode:GetLastError();
}
DWORD restrictElevatedCommandToken(HANDLE token,FileHandle &restricted)
{
// A synthetic LUA token made directly from an elevated token can fail to
// initialize KernelBase when the child starts without a console window.
SAFER_LEVEL_HANDLE level{};
if(!SaferCreateLevel(SAFER_SCOPEID_USER,SAFER_LEVELID_NORMALUSER,SAFER_LEVEL_OPEN,&level,nullptr))
return GetLastError();
const auto filtered=SaferComputeTokenFromLevel(level,token,&restricted.value,0,nullptr);
const auto filterError=GetLastError();
SaferCloseLevel(level);
if(!filtered) return filterError;
// Preserve DISABLE_MAX_PRIVILEGE without creating a second filtered token.
LUID changeNotify{};
if(!LookupPrivilegeValueW(nullptr,SE_CHANGE_NOTIFY_NAME,&changeNotify)) return GetLastError();
DWORD size{};
if(!GetTokenInformation(restricted.value,TokenPrivileges,nullptr,0,&size) &&
GetLastError()!=ERROR_INSUFFICIENT_BUFFER) return GetLastError();
std::vector<BYTE> storage(size);
const auto privileges=reinterpret_cast<TOKEN_PRIVILEGES *>(storage.data());
if(!GetTokenInformation(restricted.value,TokenPrivileges,privileges,size,&size)) return GetLastError();
DWORD removed{};
for(DWORD i=0;i<privileges->PrivilegeCount;++i)
{
const auto &luid=privileges->Privileges[i].Luid;
if(luid.LowPart!=changeNotify.LowPart || luid.HighPart!=changeNotify.HighPart)
privileges->Privileges[removed++]={luid,SE_PRIVILEGE_REMOVED};
}
if(!removed) return ERROR_SUCCESS;
privileges->PrivilegeCount=removed;
AdjustTokenPrivileges(restricted.value,FALSE,privileges,0,nullptr,nullptr);
return GetLastError();
}
struct RemoteCommand
{
FileHandle job,process,output;
void stop()
{
job.close();
process.close();
output.close();
}
DWORD start(const fs::path &directory,const std::wstring &command)
{
if(process.value!=INVALID_HANDLE_VALUE) return ERROR_BUSY;
if(command.empty() || command.size()>12000 || command.find(L'\0')!=command.npos) return ERROR_INVALID_PARAMETER;
const auto script=L"$ProgressPreference='SilentlyContinue'; "
L"[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); "
L"$OutputEncoding=[Console]::OutputEncoding;\r\n"+command;
const auto data=reinterpret_cast<const BYTE *>(script.data());
const auto bytes=static_cast<DWORD>(script.size()*sizeof(wchar_t));
constexpr DWORD encoding=CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF;
DWORD length{};
if(!CryptBinaryToStringW(data,bytes,encoding,nullptr,&length)) return GetLastError();
std::wstring encoded(length,L'\0');
if(!CryptBinaryToStringW(data,bytes,encoding,encoded.data(),&length)) return GetLastError();
encoded.resize(length);
// Windows PowerShell serializes its error stream as CLIXML with -EncodedCommand.
// Decode the command inside a fixed text-mode expression instead.
auto arguments=L"powershell.exe -NoLogo -NoProfile -NonInteractive -OutputFormat Text -Command "
L"\"& ([ScriptBlock]::Create([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('"+
encoded+L"'))))\"";
const auto shell=ks::files::windowsPowerShell();
if(shell.empty()) return ERROR_PATH_NOT_FOUND;
FileHandle token,restricted,read,write,input,processJob;
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|
TOKEN_ADJUST_DEFAULT,&token.value)) return GetLastError();
TOKEN_ELEVATION elevation{};
DWORD elevationSize{};
if(!GetTokenInformation(token.value,TokenElevation,&elevation,sizeof(elevation),&elevationSize))
return GetLastError();
if(elevation.TokenIsElevated)
{
if(const auto error=restrictElevatedCommandToken(token.value,restricted)) return error;
}
else if(!CreateRestrictedToken(token.value,DISABLE_MAX_PRIVILEGE|LUA_TOKEN,0,nullptr,0,nullptr,0,nullptr,
&restricted.value)) return GetLastError();
PSID medium{};
if(!ConvertStringSidToSidW(L"S-1-16-8192",&medium)) return GetLastError();
TOKEN_MANDATORY_LABEL label{{medium,SE_GROUP_INTEGRITY}};
const auto limited=SetTokenInformation(restricted.value,TokenIntegrityLevel,&label,
sizeof(label)+GetLengthSid(medium));
const auto tokenError=GetLastError();
LocalFree(medium);
if(!limited) return tokenError;
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
if(!CreatePipe(&read.value,&write.value,&inheritable,0) ||
!SetHandleInformation(read.value,HANDLE_FLAG_INHERIT,0)) return GetLastError();
input.value=CreateFileW(L"NUL",GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&inheritable,
OPEN_EXISTING,0,nullptr);
if(input.value==INVALID_HANDLE_VALUE) return GetLastError();
const auto createdJob=CreateJobObjectW(nullptr,nullptr);
if(!createdJob) return GetLastError();
processJob.value=createdJob;
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if(!SetInformationJobObject(processJob.value,JobObjectExtendedLimitInformation,&limits,sizeof(limits)))
return GetLastError();
SIZE_T attributeBytes{};
InitializeProcThreadAttributeList(nullptr,1,0,&attributeBytes);
std::vector<BYTE> storage(attributeBytes);
const auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
if(!InitializeProcThreadAttributeList(attributes,1,0,&attributeBytes)) return GetLastError();
HANDLE inherited[]{input.value,write.value};
STARTUPINFOEXW startup{};
startup.StartupInfo.cb=sizeof(startup);
startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES;
startup.StartupInfo.hStdInput=input.value;
startup.StartupInfo.hStdOutput=startup.StartupInfo.hStdError=write.value;
startup.lpAttributeList=attributes;
PROCESS_INFORMATION child{};
const auto started=UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
inherited,sizeof(inherited),nullptr,nullptr) &&
CreateProcessAsUserW(restricted.value,shell.c_str(),arguments.data(),nullptr,nullptr,TRUE,
CREATE_SUSPENDED|CREATE_NO_WINDOW|EXTENDED_STARTUPINFO_PRESENT,nullptr,
directory.c_str(),&startup.StartupInfo,&child);
const auto processError=GetLastError();
DeleteProcThreadAttributeList(attributes);
if(!started) return processError;
FileHandle thread{child.hThread},childProcess{child.hProcess};
if(!AssignProcessToJobObject(processJob.value,childProcess.value) || ResumeThread(thread.value)==DWORD(-1))
{
const auto error=GetLastError();
TerminateProcess(childProcess.value,error);
return error;
}
job.value=std::exchange(processJob.value,INVALID_HANDLE_VALUE);
process.value=std::exchange(childProcess.value,INVALID_HANDLE_VALUE);
output.value=std::exchange(read.value,INVALID_HANDLE_VALUE);
return ERROR_SUCCESS;
}
Json poll()
{
if(process.value==INVALID_HANDLE_VALUE) return failure(ERROR_INVALID_HANDLE);
const auto wait=WaitForSingleObject(process.value,0);
if(wait==WAIT_FAILED) return failure();
DWORD available{};
if(!PeekNamedPipe(output.value,nullptr,0,nullptr,&available,nullptr) && GetLastError()!=ERROR_BROKEN_PIPE)
return failure();
Bytes bytes(std::min<DWORD>(available,FileChunk));
DWORD read{};
if(!bytes.empty() && !ReadFile(output.value,bytes.data(),static_cast<DWORD>(bytes.size()),&read,nullptr))
return failure();
bytes.resize(read);
const bool done=wait==WAIT_OBJECT_0 && bytes.empty();
DWORD exitCode{};
if(done)
{
if(!GetExitCodeProcess(process.value,&exitCode)) return failure();
stop();
}
return {{"error",0},{"data",Json::binary(std::move(bytes))},{"done",done},{"exitCode",exitCode}};
}
};
fs::path temporaryFile(const fs::path &target)
{
return target.parent_path()/wide(".kswitcher-"+randomHex(16)+".tmp");
@@ -231,6 +449,9 @@ std::string hashPrefix(HANDLE file,uint64_t size,const FileProgress &progress,ui
class FileOperations
{
FilesListener::TerminalPermission terminalPermission;
FilesListener::HostAction hibernate,update;
RemoteCommand terminal;
bool remote;
HANDLE search=INVALID_HANDLE_VALUE;
WIN32_FIND_DATAW entry{};
@@ -385,7 +606,10 @@ class FileOperations
return reply;
}
public:
explicit FileOperations(bool remote):remote(remote){}
explicit FileOperations(bool remote,FilesListener::TerminalPermission permission={},
FilesListener::HostAction hibernateAction={},FilesListener::HostAction updateAction={}):
terminalPermission(std::move(permission)),hibernate(std::move(hibernateAction)),
update(std::move(updateAction)),remote(remote){}
~FileOperations(){closeSearch();discard();}
Json call(const Json &request,const FileProgress &progress)
{
@@ -399,6 +623,26 @@ public:
Json perform(const Json &request,const FileProgress &progress)
{
const auto action=request.at("action").get<std::string>();
if(action=="hibernate" || action=="update")
{
if(request.size()!=1) return failure(ERROR_INVALID_PARAMETER);
const auto &hostAction=action=="hibernate"?hibernate:update;
if(!remote || !hostAction) return failure(ERROR_ACCESS_DENIED);
const auto error=hostAction();
return error?failure(error):ok();
}
if(action=="terminalRun" || action=="terminalPoll" || action=="terminalCancel")
{
if(!remote || !terminalPermission || !terminalPermission())
{
terminal.stop();
return failure(ERROR_ACCESS_DENIED);
}
if(action=="terminalCancel") {terminal.stop();return ok();}
if(action=="terminalPoll") return terminal.poll();
const auto error=terminal.start(path(request.at("path")),wide(request.at("command").get<std::string>()));
return error?failure(error):ok();
}
if(action=="drives")
{
auto reply=ok();
@@ -449,7 +693,7 @@ public:
discard(true);
return failure(error?error:ERROR_WRITE_FAULT);
}
if(action=="commit")
if(action=="commit" || action=="commitEdit")
{
if(output.value==INVALID_HANDLE_VALUE) return failure(ERROR_INVALID_HANDLE);
LARGE_INTEGER size{};
@@ -459,6 +703,26 @@ public:
const FILETIME time{static_cast<DWORD>(stamp),static_cast<DWORD>(stamp>>32)};
if(!SetFileTime(output.value,nullptr,nullptr,&time) || !FlushFileBuffers(output.value)) return failure();
output.close();
static std::mutex publicationMutex;
const std::lock_guard publication(publicationMutex);
if(action=="commitEdit")
{
WIN32_FILE_ATTRIBUTE_DATA existing{};
if(!GetFileAttributesExW(target.c_str(),GetFileExInfoStandard,&existing) ||
(existing.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_READONLY)) ||
fileSize(existing.nFileSizeHigh,existing.nFileSizeLow)!=request.at("expectedSize").get<uint64_t>() ||
fileSize(existing.ftLastWriteTime.dwHighDateTime,existing.ftLastWriteTime.dwLowDateTime)!=
request.at("expectedModified").get<uint64_t>())
{
discard(true);
return failure(ERROR_FILE_INVALID);
}
const auto attributes=FILE_ATTRIBUTE_ARCHIVE|
(existing.dwFileAttributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM|
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED));
if(!SetFileAttributesW(temporary.c_str(),attributes)) return failure();
return commit(target,true);
}
const auto reply=commit(target,request.at("replace").get<bool>());
if(reply.at("error")==ERROR_SUCCESS) SetFileAttributesW(target.c_str(),FILE_ATTRIBUTE_ARCHIVE);
return reply;
@@ -477,7 +741,8 @@ public:
{
WIN32_FILE_ATTRIBUTE_DATA data{};
if(!GetFileAttributesExW(name.c_str(),GetFileExInfoStandard,&data)) return failure();
return {{"error",0},{"attributes",data.dwFileAttributes},{"size",fileSize(data.nFileSizeHigh,data.nFileSizeLow)},
return {{"error",0},{"attributes",data.dwFileAttributes},{"editCommit",true},
{"size",fileSize(data.nFileSizeHigh,data.nFileSizeLow)},
{"modified",fileSize(data.ftLastWriteTime.dwHighDateTime,data.ftLastWriteTime.dwLowDateTime)}};
}
if(action=="canonical")
@@ -487,6 +752,20 @@ public:
return error?failure(error.value()):Json{{"error",0},{"path",utf8(canonical.native())}};
}
if(action=="mkdir") return CreateDirectoryW(name.c_str(),nullptr)?ok():failure();
if(action=="mkdir-link")
{
const auto target=path(request.at("target"));
if(target.empty()) return failure(ERROR_INVALID_NAME);
const auto kind=request.at("kind").get<std::string>();
if(kind=="junction")
{
const auto error=createJunction(name,target);
return error?failure(error):ok();
}
if(kind!="symlink") return failure(ERROR_INVALID_PARAMETER);
return CreateSymbolicLinkW(name.c_str(),target.c_str(),
SYMBOLIC_LINK_FLAG_DIRECTORY|SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)?ok():failure();
}
if(action=="rmdir") return RemoveDirectoryW(name.c_str())?ok():failure();
if(action=="recycle") return recycleFile(nullptr,name)?ok():failure(ERROR_ACCESS_DENIED);
if(action=="remove")
@@ -644,6 +923,12 @@ struct FilesConnection::Impl
}
};
DWORD hibernateFromPairedPC()
{
if(!remoteHibernateAllowed()) return ERROR_ACCESS_DENIED;
return requestSystemHibernate();
}
FilesConnection::FilesConnection(const FilesPeer *peer):impl(std::make_unique<Impl>(peer)){}
FilesConnection::FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key):
impl(std::make_unique<Impl>())
@@ -667,7 +952,7 @@ Json FilesConnection::call(const Json &request,const FileProgress &progress)
void streamFile(FilesConnection &source,FilesConnection &target,const std::string &sourceId,
const std::filesystem::path &from,const std::filesystem::path &to,uint64_t size,uint64_t modified,
bool replace,bool append,const FileProgress &progress)
bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination)
{
auto openSource=fileRequest("openRead",from);
openSource["size"]=size;
@@ -705,7 +990,13 @@ void streamFile(FilesConnection &source,FilesConnection &target,const std::strin
if(data.empty())
{
if(done!=size) throw std::system_error(ERROR_FILE_INVALID,std::system_category());
checkFileReply(target.call({{"action","commit"},{"replace",replace},{"modified",modified}}));
Json commit{{"action",expectedDestination?"commitEdit":"commit"},{"replace",replace},{"modified",modified}};
if(expectedDestination)
{
commit["expectedSize"]=expectedDestination->size;
commit["expectedModified"]=expectedDestination->modified;
}
checkFileReply(target.call(commit));
checkFileReply(source.call({{"action","closeRead"}}));
return;
}
@@ -723,6 +1014,26 @@ void streamFile(FilesConnection &source,FilesConnection &target,const std::strin
}
}
DWORD runRemoteCommand(FilesConnection &host,const fs::path &directory,std::wstring_view command,
const std::function<void(std::string_view)> &output,std::stop_token stop)
{
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
auto request=fileRequest("terminalRun",directory);
request["command"]=utf8(std::wstring(command));
checkFileReply(host.call(request));
while(!stop.stop_requested())
{
const auto reply=host.call({{"action","terminalPoll"}});
checkFileReply(reply);
const auto &bytes=reply.at("data").get_binary();
if(!bytes.empty()) output({reinterpret_cast<const char *>(bytes.data()),bytes.size()});
if(reply.at("done").get<bool>()) return reply.at("exitCode").get<DWORD>();
if(bytes.empty()) std::this_thread::sleep_for(std::chrono::milliseconds(60));
}
checkFileReply(host.call({{"action","terminalCancel"}}));
throw std::system_error(ERROR_CANCELLED,std::system_category());
}
struct FilesListener::Impl
{
struct Client
@@ -738,29 +1049,47 @@ struct FilesListener::Impl
};
std::string local;
PairKey key;
TerminalPermission terminalPermission;
HostAction hibernate,update;
WinSocket listener;
std::vector<std::unique_ptr<Client>> clients;
uint16_t boundPort{};
Impl(std::string id,PairKey lookup,uint16_t port):local(std::move(id)),key(std::move(lookup))
uint16_t requestedPort{},boundPort{};
ULONGLONG nextBind{};
DWORD lastBindError{};
Impl(std::string id,PairKey lookup,uint16_t port,TerminalPermission permission,HostAction hibernateAction,
HostAction updateAction):
local(std::move(id)),key(std::move(lookup)),terminalPermission(std::move(permission)),
hibernate(std::move(hibernateAction)),update(std::move(updateAction)),requestedPort(port)
{
listener.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(listener.value==INVALID_SOCKET) return;
bindListener();
}
void bindListener()
{
nextBind=GetTickCount64()+1000;
WinSocket candidate{socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)};
BOOL exclusive=TRUE;
u_long mode=1;
sockaddr_in address{};
address.sin_family=AF_INET;
address.sin_port=htons(port);
if(setsockopt(listener.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,reinterpret_cast<const char*>(&exclusive),sizeof(exclusive)) ||
ioctlsocket(listener.value,FIONBIO,&mode) ||
bind(listener.value,reinterpret_cast<sockaddr*>(&address),sizeof(address)) ||
listen(listener.value,8))
address.sin_port=htons(requestedPort);
int length=sizeof(address);
if(candidate.value==INVALID_SOCKET ||
setsockopt(candidate.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,reinterpret_cast<const char*>(&exclusive),sizeof(exclusive)) ||
ioctlsocket(candidate.value,FIONBIO,&mode) ||
bind(candidate.value,reinterpret_cast<sockaddr*>(&address),sizeof(address)) ||
listen(candidate.value,8) ||
getsockname(candidate.value,reinterpret_cast<sockaddr*>(&address),&length))
{
closesocket(std::exchange(listener.value,INVALID_SOCKET));
const auto error=static_cast<DWORD>(WSAGetLastError());
if(requestedPort==FilesPort && lastBindError!=error)
log(L"LAN Files TCP 45885 unavailable; retrying. Windows error "+std::to_wstring(error));
lastBindError=error;
return;
}
int length=sizeof(address);
if(!getsockname(listener.value,reinterpret_cast<sockaddr*>(&address),&length))
boundPort=ntohs(address.sin_port);
listener.value=std::exchange(candidate.value,INVALID_SOCKET);
boundPort=ntohs(address.sin_port);
if(requestedPort==FilesPort) log(L"LAN Files listener ready on TCP 45885.");
lastBindError=0;
}
void serve(SOCKET socket)
{
@@ -776,7 +1105,7 @@ struct FilesListener::Impl
wire.authenticate(secret,peer,local,challenge,nonce,false);
if(wire.read().at("action")!="authenticate") return;
wire.write(ok());
FileOperations operations(true);
FileOperations operations(true,terminalPermission,hibernate,update);
for(;;)
{
const auto request=wire.read(true);
@@ -795,6 +1124,7 @@ struct FilesListener::Impl
void poll()
{
std::erase_if(clients,[](const auto &client){return client->done.load();});
if(listener.value==INVALID_SOCKET && GetTickCount64()>=nextBind) bindListener();
if(listener.value==INVALID_SOCKET || clients.size()>=16) return;
sockaddr_in address{};
int size=sizeof(address);
@@ -817,8 +1147,10 @@ struct FilesListener::Impl
}
};
FilesListener::FilesListener(std::string local,PairKey key,uint16_t port):
impl(std::make_unique<Impl>(std::move(local),std::move(key),port)){}
FilesListener::FilesListener(std::string local,PairKey key,uint16_t port,TerminalPermission terminalPermission,
HostAction hibernate,HostAction update):
impl(std::make_unique<Impl>(std::move(local),std::move(key),port,std::move(terminalPermission),
std::move(hibernate),std::move(update))){}
FilesListener::~FilesListener()=default;
uint16_t FilesListener::port()const{return impl->boundPort;}
void FilesListener::poll(){impl->poll();}
+16 -2
View File
@@ -1,6 +1,7 @@
#pragma once
#include "lan_pairing.h"
#include <functional>
#include <stop_token>
namespace ks::lan
{
@@ -13,6 +14,7 @@ struct FilesPeer
bool filesBrowse{};
};
using FileProgress = std::function<bool(uint64_t, uint64_t)>;
struct FileRevision { uint64_t size, modified; };
inline constexpr size_t FileChunk = 64 * 1024;
// One connection owns its enumeration, file handles and uncommitted upload.
@@ -29,7 +31,9 @@ public:
void streamFile(FilesConnection &source,FilesConnection &target,const std::string &sourceId,
const std::filesystem::path &from,const std::filesystem::path &to,uint64_t size,uint64_t modified,
bool replace,bool append,const FileProgress &progress);
bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination=nullptr);
DWORD runRemoteCommand(FilesConnection &host,const std::filesystem::path &directory,std::wstring_view command,
const std::function<void(std::string_view)> &output,std::stop_token stop={});
class FilesListener
{
@@ -37,7 +41,10 @@ class FilesListener
std::unique_ptr<Impl> impl;
public:
using PairKey = std::function<std::string(const std::string &)>;
FilesListener(std::string local, PairKey key,uint16_t port=FilesPort);
using TerminalPermission = std::function<bool()>;
using HostAction = std::function<DWORD()>;
FilesListener(std::string local, PairKey key,uint16_t port=FilesPort,TerminalPermission terminalPermission={},
HostAction hibernate={},HostAction update={});
uint16_t port() const;
~FilesListener();
void poll();
@@ -47,4 +54,11 @@ Json fileRequest(std::string_view action, const std::filesystem::path &path);
std::filesystem::path filePath(const Json &path);
void checkFileReply(const Json &reply);
bool recycleFile(HWND owner, const std::filesystem::path &path);
inline constexpr wchar_t remoteTerminalPreference[]=L"AllowRemoteTerminal";
bool remoteTerminalAllowed();
inline constexpr wchar_t remoteHibernatePreference[]=L"AllowRemoteHibernate";
bool remoteHibernateAllowed();
DWORD hibernateFromPairedPC();
inline constexpr wchar_t remoteUpdatePreference[]=L"AllowRemoteUpdate";
bool remoteUpdateAllowed();
}
+16 -4
View File
@@ -211,9 +211,18 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
if(!connected||!env.desktop()){cancel(now);return;}
if(f.type==InputType::Enter)
{
if(!f.token||f.a<0||f.a>3||(!multi&&f.a!=(edge^1))||f.b<0||f.b>65535||held()||returning||
mode_==ControlMode::Sending||mode_==ControlMode::Receiving||(mode_==ControlMode::Requesting&&preferLocal))
{post({InputType::Return,f.token,32768});return;}
const wchar_t *declined=nullptr;
if(!f.token||f.a<0||f.a>3||(!multi&&f.a!=(edge^1))||f.b<0||f.b>65535)
declined=L"invalid edge or position";
else if(held())declined=L"a local key or mouse button is held";
else if(returning||mode_==ControlMode::Sending||mode_==ControlMode::Receiving||
(mode_==ControlMode::Requesting&&preferLocal))
declined=L"another handoff is active";
if(declined)
{
log(std::wstring(L"LAN input: declined cursor handoff: ")+declined);
post({InputType::Return,f.token,32768});return;
}
if(mode_==ControlMode::Requesting)cancel(now);
if(multi)edge=f.a^1;
crossEdge=-1;token=f.token;remainderX=remainderY=0;mode(ControlMode::Receiving);
@@ -231,7 +240,10 @@ void InputRouter::receive(const InputFrame &f,uint64_t now)
return;
}
if(f.token!=token||!token)return;
if(f.type==InputType::Return){log(L"LAN input: peer returned control");local(now,std::clamp(f.a,0,65535));return;}
if(f.type==InputType::Return){
log(mode_==ControlMode::Requesting?L"LAN input: peer declined cursor handoff":L"LAN input: peer returned control");
local(now,std::clamp(f.a,0,65535));return;
}
if(mode_!=ControlMode::Receiving)return;
bool ok=true;
if(f.type==InputType::Move)
+1
View File
@@ -50,6 +50,7 @@ class InputMesh
if(!ready.contains(peer)||!positions.contains(peer))return;
if(f.type==InputType::Enter){
if(!allowEnter||f.a<0||f.a>3||(router.mode()!=ControlMode::Local&&active!=peer)){
if(!allowEnter)log(L"LAN input: declined cursor handoff during a local text operation or shortcut capture");
send(peer,{InputType::Return,f.token,32768});return;
}
if(router.mode()==ControlMode::Local)select(peer,f.a^1,now);
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <winsock2.h>
#include <system_error>
namespace ks::lan
{
inline void socketError()
{
throw std::system_error(WSAGetLastError(),std::system_category());
}
struct WinSocket
{
SOCKET value=INVALID_SOCKET;
~WinSocket(){if(value!=INVALID_SOCKET) closesocket(value);}
};
struct Network
{
Network()
{
WSADATA data{};
if(const auto error=WSAStartup(MAKEWORD(2,2),&data))
throw std::system_error(error,std::system_category());
}
~Network(){WSACleanup();}
};
}
+31
View File
@@ -0,0 +1,31 @@
#pragma once
#include <algorithm>
#include <array>
#include <optional>
#include <string>
#include <string_view>
namespace ks::lan
{
inline std::optional<std::array<unsigned char,102>> wakePacket(std::string_view mac)
{
constexpr std::string_view digits="0123456789abcdef";
std::array<unsigned char,6> address{};
if(mac.size()!=2*address.size()) return {};
for(size_t i=0;i<address.size();++i)
{
const auto high=digits.find(mac[2*i]),low=digits.find(mac[2*i+1]);
if(high==digits.npos || low==digits.npos) return {};
address[i]=static_cast<unsigned char>(16*high+low);
}
if((address.front()&1) || std::all_of(address.begin(),address.end(),[](auto byte){return byte==0;}))
return {};
std::array<unsigned char,102> packet{};
std::fill_n(packet.begin(),6,0xff);
for(auto next=packet.begin()+6;next!=packet.end();next+=address.size())
std::copy(address.begin(),address.end(),next);
return packet;
}
void wakeFilesPeer(const std::string &id);
}
+2
View File
@@ -38,6 +38,8 @@ bool shouldElevateOnLaunch()
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int)
{
// Inherited by unattended children such as the LAN PowerShell process.
SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS);
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
int argc{};
auto argv = CommandLineToArgvW(GetCommandLineW(), &argc);
+49 -18
View File
@@ -1,5 +1,6 @@
#include "ocr.h"
#include <memory>
#include <atomic>
#include <roapi.h>
#include <wincodec.h>
#include <winstring.h>
@@ -99,6 +100,38 @@ struct OcrOperation : IInspectable
virtual HRESULT STDMETHODCALLTYPE GetCompleted(IUnknown **) = 0;
virtual HRESULT STDMETHODCALLTYPE Results(OcrResult **) = 0;
};
class OcrCompletion final : public IUnknown
{
// Windows.Foundation.AsyncOperationCompletedHandler<Windows.Media.Ocr.OcrResult>.
static constexpr GUID interfaceId{0x989c1371,0x444a,0x5e7e,{0xb1,0x97,0x9e,0xaa,0xf9,0xd2,0x82,0x9a}};
static constexpr GUID agileId{0x94ea2b94,0xe9cc,0x49e0,{0xc0,0xff,0xee,0x64,0xca,0x8f,0x5b,0x90}};
std::atomic<ULONG> references{1};
public:
const HANDLE event=CreateEventW(nullptr,TRUE,FALSE,nullptr);
~OcrCompletion(){if(event) CloseHandle(event);}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,void **value) override
{
if(!value) return E_POINTER;
*value=nullptr;
if(iid!=IID_IUnknown && iid!=interfaceId && iid!=agileId) return E_NOINTERFACE;
*value=static_cast<IUnknown *>(this);
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE AddRef() override {return ++references;}
ULONG STDMETHODCALLTYPE Release() override
{
const auto count=--references;
if(!count) delete this;
return count;
}
virtual HRESULT STDMETHODCALLTYPE Invoke(OcrOperation *,INT32)
{
return SetEvent(event)?S_OK:HRESULT_FROM_WIN32(GetLastError());
}
};
struct AsyncInfo : IInspectable
{
virtual HRESULT STDMETHODCALLTYPE Id(UINT32 *) = 0;
@@ -253,13 +286,12 @@ std::wstring recognizeText(const Clip &clip)
RoUninitialize();
}
} apartment;
auto pixels = decodeImage(clip);
Com<OcrStatics> ocr;
factory(L"Windows.Media.Ocr.OcrEngine", L"{5bffa85a-3384-3540-9940-699120d428a8}", ocr);
UINT32 max{};
check(ocr->MaxDimension(&max));
if (pixels.width > max || pixels.height > max)
throw std::runtime_error("Image exceeds Windows OCR's maximum dimensions");
if (!max) throw std::runtime_error("Windows OCR reported an invalid image size limit");
auto pixels = decodeImage(clip,max,max);
Com<OcrEngine> engine;
check(ocr->FromProfile(engine.out()));
if (!engine.p)
@@ -282,21 +314,20 @@ std::wstring recognizeText(const Clip &clip)
check(engine->Recognize(bitmap.p, operation.out()));
Com<AsyncInfo> info;
check(operation->QueryInterface(guid(L"{00000036-0000-0000-c000-000000000046}"), (void **)info.out()));
auto deadline = GetTickCount64() + 30000;
INT32 status{};
do
Com<OcrCompletion> completed;
completed.p=new OcrCompletion;
if(!completed->event) check(HRESULT_FROM_WIN32(GetLastError()));
check(operation->PutCompleted(completed.p));
const auto wait=WaitForSingleObject(completed->event,30000);
if(wait!=WAIT_OBJECT_0)
{
check(info->Status(&status));
if (status == 0)
{
if (GetTickCount64() > deadline)
{
info->Cancel();
throw std::runtime_error("Windows OCR timed out");
}
Sleep(20);
}
} while (status == 0);
const auto error=wait==WAIT_FAILED?GetLastError():ERROR_TIMEOUT;
info->Cancel();
if(error==ERROR_TIMEOUT) throw std::runtime_error("Windows OCR timed out");
check(HRESULT_FROM_WIN32(error));
}
INT32 status{};
check(info->Status(&status));
if (status != 1)
{
HRESULT failure{};
@@ -330,7 +361,7 @@ std::filesystem::path tesseractExecutable(const Settings &s)
for (auto relative : {L"Tesseract-OCR/tesseract.exe", L"Programs/Tesseract-OCR/tesseract.exe"})
if (std::filesystem::is_regular_file(root / relative)) return root / relative;
}
throw std::runtime_error("Tesseract was not found. Install the optional 64-bit Tesseract 5 package or select tesseract.exe in OCR options.");
throw std::runtime_error("Tesseract was not found. Install the optional 64-bit Tesseract 5 package or select tesseract.exe in Clipboard > Image text recognition.");
}
std::wstring ocrProfile(const Settings &s)
{
+29 -11
View File
@@ -11,8 +11,19 @@ class PasteProbe
IUIAutomationElement *element{};
IUIAutomationTextPattern *pattern{};
static std::optional<std::wstring> rangeText(IUIAutomationTextRange *range)
{
BSTR value{};
const HRESULT hr = range->GetText(8193, &value);
std::wstring text(value ? value : L"", SysStringLen(value));
SysFreeString(value);
if (FAILED(hr)) return {};
return text;
}
public:
std::wstring status = L"not-requested";
std::optional<std::wstring> precedingCharacter;
PasteProbe(bool enabled, HWND target)
{
if (!enabled)
@@ -48,11 +59,11 @@ class PasteProbe
!pattern)
return;
}
PasteProbe(bool enabled, const std::wstring &original, HWND target = nullptr)
PasteProbe(bool enabled, const std::wstring &original, HWND target = nullptr, bool readPreceding = false)
: PasteProbe(enabled, target)
{
if (!pattern) return;
auto selected = read(1, false);
auto selected = read(1, false, readPreceding);
auto normalize = [](std::wstring value)
{
for (size_t at = 0; (at = value.find(L"\r\n", at)) != value.npos;)
@@ -80,7 +91,7 @@ class PasteProbe
if (automation)
automation->Release();
}
std::optional<std::wstring> read(int characters, bool allowCaret = true)
std::optional<std::wstring> read(int characters, bool allowCaret = true, bool readPreceding = false)
{
if (!pattern)
return {};
@@ -162,19 +173,26 @@ class PasteProbe
if (SUCCEEDED(hr) && moved != -characters)
hr = E_FAIL;
}
BSTR value{};
if (SUCCEEDED(hr))
hr = range->GetText(8193, &value);
auto text = SUCCEEDED(hr) ? rangeText(range) : std::nullopt;
if (readPreceding && text &&
SUCCEEDED(range->MoveEndpointByRange(TextPatternRangeEndpoint_End, range, TextPatternRangeEndpoint_Start)))
{
int moved{};
if (SUCCEEDED(range->MoveEndpointByUnit(TextPatternRangeEndpoint_Start, TextUnit_Character, -1, &moved)))
{
if (moved == 0)
precedingCharacter.emplace();
else if (auto previous = rangeText(range); previous && !previous->empty())
precedingCharacter = std::move(previous);
}
}
range->Release();
if (FAILED(hr))
if (!text)
{
SysFreeString(value);
status = L"range-read-failed";
return {};
}
std::wstring text(value ? value : L"", SysStringLen(value));
SysFreeString(value);
if (text.size() > 8192)
if (text->size() > 8192)
{
status = L"readback-size-limit";
return {};
+76 -23
View File
@@ -12,6 +12,7 @@
#include <set>
#include <shellapi.h>
#include <shlobj.h>
#include <propkey.h>
#include <exdisp.h>
#include <shldisp.h>
#include <tlhelp32.h>
@@ -166,6 +167,35 @@ void showRequestedWindow(HWND window)
if (!IsWindowVisible(window))
ShowWindow(window, SW_SHOW);
}
void setWindowResourceIcons(HWND window, HINSTANCE instance, int iconResource)
{
const auto dpi = GetDpiForWindow(window);
for (int kind : {ICON_SMALL, ICON_BIG})
{
const bool small = kind == ICON_SMALL;
const auto icon = LoadImageW(instance, MAKEINTRESOURCEW(iconResource), IMAGE_ICON,
GetSystemMetricsForDpi(small ? SM_CXSMICON : SM_CXICON, dpi),
GetSystemMetricsForDpi(small ? SM_CYSMICON : SM_CYICON, dpi), LR_SHARED);
if (icon) SendMessageW(window, WM_SETICON, kind, reinterpret_cast<LPARAM>(icon));
}
}
void setWindowTaskbarIdentity(HWND window, int iconResource, const wchar_t *identity)
{
auto icon = identity ? executable() + L",-" + std::to_wstring(iconResource) : std::wstring{};
auto group = identity ? std::wstring(identity) : std::wstring{};
Microsoft::WRL::ComPtr<IPropertyStore> properties;
if (FAILED(SHGetPropertyStoreForWindow(window, IID_PPV_ARGS(&properties)))) return;
PROPVARIANT value{};
if (identity)
{
value.vt = VT_LPWSTR;
value.pwszVal = icon.data();
}
properties->SetValue(PKEY_AppUserModel_RelaunchIconResource, value);
if (identity) value.pwszVal = group.data();
// Set the group ID last so Explorer refreshes the taskbar button.
properties->SetValue(PKEY_AppUserModel_ID, value);
}
void showMenuAccessKeys(HMENU menu)
{
// Mouse-opened popups ignore the owner's keyboard-cue state.
@@ -349,14 +379,18 @@ bool launchThroughExplorer(const std::wstring &path)
SysFreeString(executable);
return SUCCEEDED(hr);
}
Clip readClipboard(HWND window, size_t limit, ClipboardRead mode, std::optional<DWORD> expected)
bool clipboardHasImage()
{
return IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) ||
IsClipboardFormatAvailable(CF_BITMAP) || IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"));
}
Clip readClipboard(HWND window, size_t limit, ClipboardRead mode, std::optional<DWORD> expected,
DWORD *capturedSequence)
{
ClipboardLock lock(window);
if (expected && *expected != GetClipboardSequenceNumber())
throw std::runtime_error("Clipboard changed while taking snapshot");
if (mode == ClipboardRead::WithoutImages &&
(IsClipboardFormatAvailable(CF_DIB) || IsClipboardFormatAvailable(CF_DIBV5) ||
IsClipboardFormatAvailable(CF_BITMAP) || IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"))))
if (mode == ClipboardRead::WithoutImages && clipboardHasImage())
throw std::runtime_error("Clipboard changed to an image");
Clip c;
size_t total = 0;
@@ -392,6 +426,8 @@ Clip readClipboard(HWND window, size_t limit, ClipboardRead mode, std::optional<
total += size;
c.formats.push_back(std::move(format));
}
// Delayed rendering can advance the sequence while this read holds the clipboard open.
if (capturedSequence) *capturedSequence = GetClipboardSequenceNumber();
return c;
}
DWORD writeClipboard(HWND window, const Clip &c) { return writeClipboardGuarded(window, c, {}); }
@@ -490,32 +526,44 @@ INPUT keyboardInput(WORD key, DWORD flags)
return input;
}
bool chord(WORD key, UINT mods)
{
WORD keys[5];
size_t count = 0;
for (auto [modifier, vk] : {std::pair<UINT, WORD>{MOD_CONTROL, VK_CONTROL},
{MOD_ALT, VK_MENU}, {MOD_SHIFT, VK_SHIFT}, {MOD_WIN, VK_LWIN}})
if (mods & modifier)
keys[count++] = vk;
keys[count++] = key;
return chord(std::span<const WORD>(keys, count));
}
bool chord(std::span<const WORD> keys)
{
std::vector<INPUT> inputs;
inputs.reserve(2 * keys.size());
auto add = [&](WORD k, bool up)
{
INPUT i = keyboardInput(k, up ? KEYEVENTF_KEYUP : 0);
if (k >= VK_LSHIFT && k <= VK_RMENU)
{
i.ki.wScan = static_cast<WORD>(MapVirtualKeyW(k, MAPVK_VK_TO_VSC));
i.ki.dwFlags |= KEYEVENTF_SCANCODE;
}
if ((k >= VK_PRIOR && k <= VK_DOWN) || k == VK_INSERT || k == VK_DELETE ||
k == VK_DIVIDE || k == VK_LWIN || k == VK_SNAPSHOT ||
k == VK_DIVIDE || k == VK_LWIN || k == VK_RWIN || k == VK_RMENU ||
k == VK_RCONTROL || k == VK_SNAPSHOT ||
(k >= VK_VOLUME_MUTE && k <= VK_VOLUME_UP))
i.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
inputs.push_back(i);
};
for (auto [m, k] : {std::pair<UINT, WORD>{MOD_CONTROL, VK_CONTROL},
{MOD_ALT, VK_MENU},
{MOD_SHIFT, VK_SHIFT},
{MOD_WIN, VK_LWIN}})
if (mods & m)
add(k, false);
add(key, false);
add(key, true);
for (auto [m, k] : {std::pair<UINT, WORD>{MOD_WIN, VK_LWIN},
{MOD_SHIFT, VK_SHIFT},
{MOD_ALT, VK_MENU},
{MOD_CONTROL, VK_CONTROL}})
if (mods & m)
add(k, true);
return SendInput((UINT)inputs.size(), inputs.data(), sizeof(INPUT)) == inputs.size();
for (WORD key : keys) add(key, false);
for (auto it = keys.rbegin(); it != keys.rend(); ++it) add(*it, true);
const auto sent = SendInput(static_cast<UINT>(inputs.size()), inputs.data(), sizeof(INPUT));
if (sent == inputs.size()) return true;
// Release any keys already pressed if Windows accepted only part of the chord.
const auto pending = std::min<size_t>(sent, inputs.size() - sent);
if (pending)
SendInput(static_cast<UINT>(pending), inputs.data() + inputs.size() - pending, sizeof(INPUT));
return false;
}
std::optional<SystemVolume> changeSystemVolume(MouseActionType action, int step)
{
@@ -738,6 +786,11 @@ namespace
std::recursive_mutex logGate;
bool loggingEnabled = false;
std::wstring logFilename = L"kswitcher.log";
const std::filesystem::path &logDirectory()
{
static const auto directory = dataDirectory();
return directory;
}
DiagnosticBuffer diagnosticBuffer;
}
size_t DiagnosticBuffer::expire(ULONGLONG now)
@@ -778,7 +831,7 @@ void setLoggingEnabled(bool enabled)
std::wstring readDiagnosticLog(bool previous)
{
std::lock_guard lock(logGate);
auto path = dataDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log");
auto path = logDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log");
if (!std::filesystem::exists(path))
return previous ? L"No previous log is available yet." : L"No log yet. Entries will appear when a problem is detected.";
auto bytes = readFile(path, 2 * 1024 * 1024);
@@ -796,7 +849,7 @@ void clearDiagnosticLog(bool previous)
{
// Serialize clearing with writes and rotation. Never delete the other log.
std::lock_guard lock(logGate);
auto path = dataDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log");
auto path = logDirectory() / (previous ? L"kswitcher.log.1" : L"kswitcher.log");
std::filesystem::remove(path);
if (!previous)
diagnosticBuffer.clear();
@@ -845,7 +898,7 @@ void log(const std::wstring &message)
return;
try
{
auto path = dataDirectory() / logFilename;
auto path = logDirectory() / logFilename;
std::error_code ec;
auto size = std::filesystem::file_size(path, ec);
if (!ec && size > 256 * 1024)
+6 -1
View File
@@ -43,6 +43,8 @@ bool switchWindowLayout(HWND, HKL, const std::function<bool()> &valid);
bool activateWindow(HWND);
void showRequestedWindow(HWND);
void showMenuAccessKeys(HMENU);
void setWindowResourceIcons(HWND window, HINSTANCE instance, int iconResource);
void setWindowTaskbarIdentity(HWND window, int iconResource, const wchar_t *identity);
bool ownsClipboard(HWND);
bool webViewDescendant(DWORD owner, DWORD host,
const std::function<std::optional<std::pair<DWORD, std::wstring>>(DWORD)> &read);
@@ -50,12 +52,15 @@ std::wstring processName(HWND);
std::wstring mouseApplicationName(HWND);
bool launchThroughExplorer(const std::wstring &);
enum class ClipboardRead { All, Selection, WithoutImages };
bool clipboardHasImage();
Clip readClipboard(HWND, size_t limit = 32 * 1024 * 1024,
ClipboardRead = ClipboardRead::All, std::optional<DWORD> expected = {});
ClipboardRead = ClipboardRead::All, std::optional<DWORD> expected = {},
DWORD *capturedSequence = nullptr);
DWORD writeClipboard(HWND, const Clip &);
DWORD writeClipboardGuarded(HWND, const Clip &, std::optional<DWORD> expected);
Clip textClip(const std::wstring &);
bool chord(WORD key, UINT modifiers = 0);
bool chord(std::span<const WORD> keys);
struct SystemVolume
{
int percent{};
+324 -96
View File
@@ -1,6 +1,7 @@
#include "screenshot.h"
#include "stroke_improvement.h"
#include "ocr.h"
#include "ui_palette.h"
#include "../resources/resource.h"
#include <algorithm>
#include <cmath>
@@ -55,6 +56,9 @@ bool confirmScreenshotClose(HWND owner)
return SUCCEEDED(result) && button==IDYES;
}
constexpr int ToolIds[]{27,10,11,22,23,24,25,36,37,38,21,19,26,20,12,18,13};
constexpr int EditorStatus = 50, EditorZoom = 51;
constexpr int EditorOptionsTop = 44, EditorPanelHeight = 118, EditorFooterHeight = 30;
constexpr int EditorToolDividers[]{50, 357, 464, 502};
struct Surface
{
HDC dc = CreateCompatibleDC(nullptr);
@@ -84,6 +88,13 @@ struct Surface
Surface(const Surface &) = delete;
Surface &operator=(const Surface &) = delete;
};
struct SavedDc
{
HDC dc;
int level;
explicit SavedDc(HDC value):dc(value),level(SaveDC(value)) {}
~SavedDc() { if(level) RestoreDC(dc,level); }
};
using Mark = ScreenshotMark;
HFONT textFont(const Mark &m)
{
@@ -169,7 +180,9 @@ struct Capture
{
ScreenshotHost &app;
std::unique_ptr<Surface> image;
std::unique_ptr<Surface> dimmed, frame;
std::unique_ptr<Surface> dimmed, frame, rendered;
bool renderedMarksValid{};
RECT dragDamage{};
bool editing{}, dragging{}, arrow{}, owned{}, copied{};
bool autoOpenEditor;
bool highlight{};
@@ -200,7 +213,8 @@ struct Capture
int zoomWheelDelta=0;
std::vector<Mark> marks;
ScreenshotHistory history;
HWND editor{}, inlineText{};
HWND editor{}, inlineText{}, tooltips{};
WindowPalette palette;
HFONT inlineFont{};
Mark textDraft{};
int textIndex=-1;
@@ -213,7 +227,7 @@ struct Capture
std::vector<Mark> beforeDrag;
HFONT font{};
HICON toolIcons[3][15]{};
int iconSize{};
int iconSize{}, fontDpi{};
HCURSOR pencilCursor{};
HCURSOR drawingCursors[std::size(CursorTools)]{};
int pencilCursorSize{};
@@ -249,6 +263,7 @@ struct Capture
void remember(const std::vector<Mark> &previous)
{
copied=false;
renderedMarksValid=false;
history.remember(previous);
syncHistory();
}
@@ -258,10 +273,22 @@ struct Capture
EnableWindow(GetDlgItem(editor,18),history.canRedo());
}
};
void setEditorStatus(Capture &c, std::wstring text)
{
if (text == c.statusText) return;
c.statusText = std::move(text);
const auto status = GetDlgItem(c.editor, EditorStatus);
SetWindowTextW(status, c.statusText.c_str());
if (c.tooltips && status)
{
TOOLINFOW tool{sizeof(tool), TTF_IDISHWND, c.editor, reinterpret_cast<UINT_PTR>(status)};
tool.lpszText = c.statusText.data();
SendMessageW(c.tooltips, TTM_UPDATETIPTEXTW, 0, reinterpret_cast<LPARAM>(&tool));
}
}
void updateStatus(Capture &c)
{
auto status=GetDlgItem(c.editor,50);
if(!status) return;
if (!GetDlgItem(c.editor, EditorStatus)) return;
std::wstring text;
auto part=c.dragging?c.part:c.hoveredPart;
if(c.hoveredTool && !c.dragging) {
@@ -291,13 +318,11 @@ void updateStatus(Capture &c)
else if(c.shape==ScreenshotShape::Arc) text=L"Arc (U): drag to draw a half ellipse | Handles = resize / rotate | V = pointer";
else if(c.arrow) text=L"Drag to draw | Ctrl+drag over objects = linked connector | V = pointer";
else text=L"Number (N): click to add | V = select and edit | Ctrl+C = copy screenshot";
text=L"Zoom: "+std::to_wstring(int(std::lround(100.0*(c.view.right-c.view.left)/c.image->width)))+
L"% (Ctrl +/- / wheel; Ctrl+0: fit; middle drag: pan) | "+text;
if(text!=c.statusText) {
c.statusText=std::move(text);
SendMessageW(status,SB_SETTEXTW,0,(LPARAM)c.statusText.c_str());
SendMessageW(status,SB_SETTIPTEXTW,0,(LPARAM)c.statusText.c_str());
}
const auto zoom = L"Zoom " + std::to_wstring(MulDiv(c.view.right - c.view.left, 100, c.image->width)) + L"%";
wchar_t current[32]{};
GetDlgItemTextW(c.editor, EditorZoom, current, std::size(current));
if (zoom != current) SetDlgItemTextW(c.editor, EditorZoom, zoom.c_str());
setEditorStatus(c, std::move(text));
}
RECT region(POINT a, POINT b)
{
@@ -471,6 +496,76 @@ RECT markBounds(const Mark &m)
}
return r;
}
RECT inkBounds(const Mark &m)
{
auto bounds=markBounds(m);
const auto padding=m.number?std::clamp(m.radius,8,200)+4:
m.isHighlight()?std::clamp(m.thickness,4,100)/2+4:
m.isText()?4:std::clamp(m.thickness,1,30)*5+14;
InflateRect(&bounds,padding,padding);
return bounds;
}
void includeInk(RECT &area,const Mark &m)
{
const auto bounds=inkBounds(m);
UnionRect(&area,&area,&bounds);
if(m.isLine() && !m.label.empty())
{
const auto labelBounds=inkBounds(screenshotArrowLabel(m));
UnionRect(&area,&area,&labelBounds);
}
}
Mark shapePreview(const Capture &c)
{
Mark preview{c.start,c.end,0};
preview.color=c.currentColor;
preview.style=c.lineStyle;
preview.ends=c.straight || c.shape!=ScreenshotShape::None?LineEnds::None:c.arrowEnds;
preview.shape=c.shape;
return preview;
}
RECT dragInk(const Capture &c)
{
RECT area{};
if(c.part!=MarkPart::None)
{
// Moving an attachment can update linked lines and their labels as well.
for(size_t i=0;i<c.marks.size();++i)
{
const auto &mark=c.marks[i];
if(i==static_cast<size_t>(c.selected) || mark.fromLink.target || mark.toLink.target ||
mark.fromNumber || mark.toNumber)
includeInk(area,mark);
}
}
else includeInk(area,(c.highlight || c.freehand)?c.stroke:shapePreview(c));
return area;
}
void invalidateDrag(HWND w,Capture &c,const RECT &before)
{
const auto after=dragInk(c);
RECT affected{};
UnionRect(&affected,&before,&after);
UnionRect(&c.dragDamage,&c.dragDamage,&affected);
const auto x=[&](LONG value) {return c.view.left+MulDiv(value,c.view.right-c.view.left,c.image->width);};
const auto y=[&](LONG value) {return c.view.top+MulDiv(value,c.view.bottom-c.view.top,c.image->height);};
RECT windowArea{x(affected.left),y(affected.top),x(affected.right),y(affected.bottom)};
// Handles and antialiased scaling extend beyond the rasterized ink.
int padding=4;
if(c.part!=MarkPart::None && c.selected>=0 && c.selected<int(c.marks.size()))
{
const auto &selected=c.marks[c.selected];
padding+=std::max(4,c.unit/8);
if(!selected.number && !selected.isHighlight()) padding+=c.unit*2;
}
InflateRect(&windowArea,padding,padding);
RECT visible{};
if(IntersectRect(&visible,&windowArea,&c.canvas)) InvalidateRect(w,&visible,FALSE);
}
std::pair<POINT,POINT> thicknessSegment(const Mark &m)
{
if(m.shape!=ScreenshotShape::None) {
@@ -492,7 +587,8 @@ void drawHighlight(HDC dc,const Mark &m)
r.left=std::max(0L,r.left-radius-1); r.top=std::max(0L,r.top-radius-1);
r.right=std::min(target.dsBm.bmWidth,r.right+radius+2);
r.bottom=std::min(target.dsBm.bmHeight,r.bottom+radius+2);
if(r.right<=r.left || r.bottom<=r.top) return;
RECT clip{};
if(GetClipBox(dc,&clip)==ERROR || !IntersectRect(&r,&r,&clip)) return;
Surface mask(r.right-r.left,r.bottom-r.top);
PatBlt(mask.dc,0,0,mask.width,mask.height,BLACKNESS);
LOGBRUSH white{BS_SOLID,RGB(255,255,255),0};
@@ -519,7 +615,7 @@ void drawHighlight(HDC dc,const Mark &m)
for(int channel=0;channel<3;++channel) at[channel]=static_cast<unsigned char>(at[channel]*(153+channels[channel]*102/255)/255);
}
}
void drawMarks(HDC dc, const std::vector<Mark> &marks, const Mark *preview = nullptr)
void drawMarks(HDC dc,const std::vector<Mark> &marks,const Mark *preview=nullptr,const RECT *damage=nullptr)
{
for(const auto &m:marks) if(m.isHighlight()) drawHighlight(dc,m);
if(preview && preview->isHighlight()) drawHighlight(dc,*preview);
@@ -533,6 +629,12 @@ void drawMarks(HDC dc, const std::vector<Mark> &marks, const Mark *preview = nul
SetTextColor(dc, RGB(255,255,255));
auto draw = [&](const Mark &m)
{
if(damage)
{
const auto bounds=inkBounds(m);
RECT overlap{};
if(!IntersectRect(&overlap,&bounds,damage)) return;
}
auto markPen=CreatePen(PS_SOLID,3,m.color);
auto markBrush=CreateSolidBrush(m.color);
auto previousMarkPen=SelectObject(dc,markPen),previousMarkBrush=SelectObject(dc,markBrush);
@@ -694,39 +796,48 @@ void layout(HWND w, Capture &c)
c.toolIcons[variant][i]=(HICON)LoadImageW(c.app.instance,MAKEINTRESOURCEW(i<9?300+variant*10+i:400+variant*10+i-9),IMAGE_ICON,iconSize,iconSize,0);
}
}
if (c.font) DeleteObject(c.font);
c.font = CreateFontW(-MulDiv(14,dpi,96),0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,CLEARTYPE_QUALITY,DEFAULT_PITCH,L"Segoe UI");
c.unit = std::max(1, MulDiv(44, dpi, 96));
auto status=GetDlgItem(w,50);
SendMessageW(status,WM_SETFONT,(WPARAM)c.font,TRUE);
SendMessageW(status,WM_SIZE,0,0);
RECT statusRect{}; GetWindowRect(status,&statusRect);
c.statusHeight=statusRect.bottom-statusRect.top;
r.bottom-=c.statusHeight;
const int positions[]{8,44,80,116,152,188,224,260,296,332,368,404,440,476,524,560,608};
static_assert(std::size(positions)==std::size(ToolIds));
for (size_t i = 0; i < std::size(ToolIds); ++i)
HFONT previousFont{};
const bool fontChanged = dpi != c.fontDpi || !c.font;
if (fontChanged)
{
SendMessageW(GetDlgItem(w,ToolIds[i]),WM_SETFONT,(WPARAM)c.font,TRUE);
MoveWindow(GetDlgItem(w,ToolIds[i]),MulDiv(positions[i],dpi,96),MulDiv(6,dpi,96),
MulDiv(32,dpi,96),MulDiv(32,dpi,96),TRUE);
c.fontDpi = dpi;
previousFont = c.font;
c.font = CreateFontW(-MulDiv(14,dpi,96),0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,CLEARTYPE_QUALITY,DEFAULT_PITCH,L"Segoe UI");
}
SendDlgItemMessageW(w,28,WM_SETFONT,(WPARAM)c.font,TRUE);
MoveWindow(GetDlgItem(w,28),MulDiv(648,dpi,96),MulDiv(6,dpi,96),
MulDiv(78,dpi,96),MulDiv(32,dpi,96),TRUE);
c.panelHeight=c.unit+MulDiv(80,dpi,96);
for(int id:{30,31,32,33,34,35,41,42,43,44}) SendDlgItemMessageW(w,id,WM_SETFONT,(WPARAM)c.font,TRUE);
MoveWindow(GetDlgItem(w,42),MulDiv(12,dpi,96),c.unit+MulDiv(44,dpi,96),MulDiv(128,dpi,96),MulDiv(24,dpi,96),TRUE);
MoveWindow(GetDlgItem(w,41),MulDiv(142,dpi,96),c.unit+MulDiv(40,dpi,96),MulDiv(200,dpi,96),MulDiv(30,dpi,96),TRUE);
MoveWindow(GetDlgItem(w,43),MulDiv(350,dpi,96),c.unit+MulDiv(44,dpi,96),MulDiv(150,dpi,96),MulDiv(24,dpi,96),TRUE);
MoveWindow(GetDlgItem(w,44),MulDiv(516,dpi,96),c.unit+MulDiv(40,dpi,96),MulDiv(210,dpi,96),MulDiv(30,dpi,96),TRUE);
MoveWindow(GetDlgItem(w,32),MulDiv(12,dpi,96),c.unit+MulDiv(6,dpi,96),MulDiv(64,dpi,96),MulDiv(24,dpi,96),TRUE);
MoveWindow(GetDlgItem(w,30),MulDiv(80,dpi,96),c.unit+MulDiv(2,dpi,96),MulDiv(150,dpi,96),MulDiv(180,dpi,96),TRUE);
MoveWindow(GetDlgItem(w,33),MulDiv(248,dpi,96),c.unit+MulDiv(6,dpi,96),MulDiv(40,dpi,96),MulDiv(24,dpi,96),TRUE);
MoveWindow(GetDlgItem(w,31),MulDiv(294,dpi,96),c.unit+MulDiv(2,dpi,96),MulDiv(170,dpi,96),MulDiv(180,dpi,96),TRUE);
MoveWindow(GetDlgItem(w,34),MulDiv(480,dpi,96),c.unit+MulDiv(2,dpi,96),MulDiv(28,dpi,96),MulDiv(28,dpi,96),TRUE);
MoveWindow(GetDlgItem(w,35),MulDiv(516,dpi,96),c.unit+MulDiv(2,dpi,96),MulDiv(28,dpi,96),MulDiv(28,dpi,96),TRUE);
const auto dip = [dpi](int n) { return MulDiv(n, dpi, 96); };
if (fontChanged) SendMessageW(c.tooltips, TTM_SETMAXTIPWIDTH, 0, dip(530));
const auto place = [&](int id, int x, int y, int width, int height)
{
const auto child = GetDlgItem(w, id);
if (fontChanged || reinterpret_cast<HFONT>(SendMessageW(child, WM_GETFONT, 0, 0)) != c.font)
SendMessageW(child, WM_SETFONT, reinterpret_cast<WPARAM>(c.font), TRUE);
MoveWindow(child, x, y, width, height, TRUE);
};
c.unit = std::max(1, dip(44));
c.statusHeight = dip(EditorFooterHeight);
r.bottom -= c.statusHeight;
place(EditorZoom, dip(16), r.bottom + 1, dip(89), c.statusHeight - 1);
place(EditorStatus, dip(120), r.bottom + 1, std::max(0, static_cast<int>(r.right) - dip(136)), c.statusHeight - 1);
const int positions[]{14,52,86,120,154,188,222,256,290,324,362,396,430,468,506,540};
static_assert(std::size(positions) + 1 == std::size(ToolIds));
for (size_t i = 0; i < std::size(positions); ++i)
place(ToolIds[i], dip(positions[i]), dip(6), dip(32), dip(32));
const int copyLeft = std::max(dip(580), static_cast<int>(r.right) - dip(168));
place(13, copyLeft, dip(6), dip(66), dip(32));
place(28, copyLeft + dip(76), dip(6), dip(76), dip(32));
c.panelHeight = dip(EditorPanelHeight);
place(32, dip(16), dip(53), dip(62), dip(26));
place(30, dip(80), dip(51), dip(150), dip(180));
place(33, dip(246), dip(53), dip(40), dip(26));
place(31, dip(288), dip(51), dip(170), dip(180));
place(34, dip(470), dip(50), dip(28), dip(28));
place(35, dip(506), dip(50), dip(28), dip(28));
place(42, dip(16), dip(84), dip(122), dip(26));
place(41, dip(140), dip(82), dip(198), dip(30));
place(43, dip(350), dip(84), dip(154), dip(26));
place(44, dip(514), dip(82), dip(208), dip(29));
if (previousFont) DeleteObject(previousFont);
syncLineOptions(w,c);
c.canvas={0,c.panelHeight,r.right,std::max(LONG(c.panelHeight+1),r.bottom)};
double ratio = c.zoom*std::min({1.0, double(std::max(1L,r.right-16))/c.image->width,
@@ -928,8 +1039,11 @@ void drawTool(const DRAWITEMSTRUCT &item, const Capture &c)
POINT mouse; GetCursorPos(&mouse); ScreenToClient(item.hwndItem,&mouse);
bool hover=PtInRect(&r,mouse) && !disabled;
bool pressed=item.itemState&ODS_SELECTED;
FillRect(dc,&r,static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
COLORREF fill=pressed?RGB(219,234,254):active?RGB(239,246,255):hover?RGB(241,245,249):RGB(255,255,255);
const bool option = item.CtlID == 34 || item.CtlID == 35;
FillRect(dc, &r, option ? c.palette.brush() : GetSysColorBrush(COLOR_WINDOW));
const COLORREF fill = c.palette.highContrast ? GetSysColor(active || pressed ? COLOR_HIGHLIGHT : COLOR_WINDOW) :
pressed ? RGB(219,234,254) : active ? RGB(232,242,254) : hover ? RGB(241,245,249) :
option ? c.palette.color() : GetSysColor(COLOR_WINDOW);
auto brush=CreateSolidBrush(fill);
auto pen=CreatePen(PS_SOLID,1,fill);
auto oldPen=SelectObject(dc,pen),oldBrush=SelectObject(dc,brush);
@@ -941,14 +1055,36 @@ void drawTool(const DRAWITEMSTRUCT &item, const Capture &c)
if(item.CtlID==36 || item.CtlID==37 || item.CtlID==38) {
int cx=(r.left+r.right)/2,cy=(r.top+r.bottom)/2,s=c.iconSize/2;
auto trianglePen=CreatePen(PS_SOLID,std::max(1,MulDiv(2,GetDpiForWindow(item.hwndItem),96)),
disabled?RGB(148,163,184):active?RGB(37,99,235):RGB(51,65,85));
c.palette.highContrast ? GetSysColor(disabled ? COLOR_GRAYTEXT :
active || pressed ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT) :
disabled ? RGB(148,163,184) : active ? RGB(37,99,235) : RGB(51,65,85));
auto previous=SelectObject(dc,trianglePen);
if(item.CtlID==38) Arc(dc,cx-s,cy-s,cx+s,cy+3*s,cx+s,cy+s,cx-s,cy+s);
else if(item.CtlID==36) { POINT vertices[]{{cx,cy-s},{cx+s,cy+s},{cx-s,cy+s},{cx,cy-s}}; Polyline(dc,vertices,4); }
else { POINT vertices[]{{cx-s/2,cy-s},{cx+s/2,cy-s},{cx+s,cy+s},{cx-s,cy+s},{cx-s/2,cy-s}}; Polyline(dc,vertices,5); }
SelectObject(dc,previous); DeleteObject(trianglePen);
}
if(icon) DrawIconEx(dc,(r.right-c.iconSize)/2,(r.bottom-c.iconSize)/2,icon,c.iconSize,c.iconSize,0,nullptr,DI_NORMAL);
const auto foreground = GetSysColor(disabled ? COLOR_GRAYTEXT : c.palette.highContrast && (active || pressed) ?
COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT);
const auto dpi = GetDpiForWindow(item.hwndItem);
const int iconX = item.CtlID == 13 ? MulDiv(7, dpi, 96) : (r.right - c.iconSize) / 2;
const int iconY = (r.bottom - c.iconSize) / 2;
if (icon && c.palette.highContrast && item.CtlID != 27)
{
const auto brush = CreateSolidBrush(foreground);
DrawStateW(dc, brush, nullptr, reinterpret_cast<LPARAM>(icon), 0, iconX, iconY, c.iconSize, c.iconSize, DST_ICON | DSS_MONO);
DeleteObject(brush);
}
else if (icon) DrawIconEx(dc, iconX, iconY, icon, c.iconSize, c.iconSize, 0, nullptr, DI_NORMAL);
if (item.CtlID == 13)
{
const SavedDc saved(dc);
SelectObject(dc, c.font);
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, foreground);
RECT label{MulDiv(30, dpi, 96), r.top, r.right, r.bottom};
DrawTextW(dc, L"Copy", -1, &label, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX);
}
if(item.CtlID==20) {
auto color=c.selected>=0?c.marks[c.selected].color:c.currentColor;
auto swatch=CreateSolidBrush(color);
@@ -1009,6 +1145,7 @@ void save(HWND w, Capture &c, bool saveAs=false,
{
if(!saveAs && !c.savedPath.empty()) {
saveToFile(w,c,c.savedPath);
setEditorStatus(c, L"Saved: " + c.savedPath.wstring());
return;
}
wchar_t filename[32768]{};
@@ -1038,8 +1175,7 @@ void save(HWND w, Capture &c, bool saveAs=false,
if(lower(std::filesystem::path(filename).extension().wstring())!=L".png")
throw std::runtime_error("Choose a filename ending in .png for the screenshot");
saveToFile(w,c,filename);
c.statusText=L"Saved: "+c.savedPath.wstring();
SendDlgItemMessageW(w,50,SB_SETTEXTW,0,(LPARAM)c.statusText.c_str());
setEditorStatus(c, L"Saved: " + c.savedPath.wstring());
}
void edit(HWND w, Capture &c)
{
@@ -1050,6 +1186,8 @@ void edit(HWND w, Capture &c)
c.image = std::move(cropped);
c.dimmed.reset();
c.frame.reset();
c.rendered.reset();
c.renderedMarksValid=false;
c.editing = true;
if (activeCapture == w) activeCapture = nullptr;
MONITORINFO monitor{sizeof(monitor)};
@@ -1062,10 +1200,14 @@ void edit(HWND w, Capture &c)
SetWindowLongPtrW(w,GWL_STYLE,WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN);
auto title=L"KSwitcher — Screenshot #"+std::to_wstring(nextEditorIndex++);
SetWindowTextW(w,localBuildTitle(title).c_str());
INITCOMMONCONTROLSEX statusControls{sizeof(statusControls),ICC_BAR_CLASSES};
InitCommonControlsEx(&statusControls);
CreateWindowExW(0,STATUSCLASSNAMEW,L"",WS_CHILD|WS_VISIBLE|SBARS_TOOLTIPS,
0,0,0,0,w,(HMENU)50,c.app.instance,nullptr);
setWindowResourceIcons(w, c.app.instance, IDI_KSWITCHER_SCREENSHOT);
setWindowTaskbarIdentity(w, IDI_KSWITCHER_SCREENSHOT, L"HrynCo.KSwitcher.ScreenshotEditor");
c.palette.refresh();
for (int id : {EditorStatus, EditorZoom})
CreateWindowW(L"STATIC", L"", WS_CHILD | WS_VISIBLE | SS_CENTERIMAGE | SS_ENDELLIPSIS | SS_NOTIFY,
0, 0, 0, 0, w, reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)), c.app.instance, nullptr);
INITCOMMONCONTROLSEX bars{sizeof(bars), ICC_BAR_CLASSES};
InitCommonControlsEx(&bars);
const wchar_t *labels[]{L"Pointer (V): select and edit objects", L"Number (N)", L"Arrow (A); Ctrl+drag between objects to link", L"Straight line (L); Ctrl+drag between objects to link", L"Rectangle (R)", L"Circle (O)", L"Ellipse (E)", L"Triangle (G): drag to draw; drag each vertex to reshape", L"Trapezoid (B): drag to draw", L"Arc (U): drag to draw a half ellipse; use handles to resize or rotate", L"Freehand line (F); Shift for 45-degree steps; move >50 px off line to turn; Ctrl to draw over objects", L"Highlight (H); Ctrl+drag to paint over an object",
L"Text (T); double-click or F2 to edit", L"Color — selected object and new objects", L"Undo (Ctrl+Z)", L"Redo (Ctrl+Y / Ctrl+Shift+Z)", L"Copy (Ctrl+C)"};
static_assert(std::size(labels)==std::size(ToolIds));
@@ -1074,11 +1216,19 @@ void edit(HWND w, Capture &c)
SetWindowSubclass(saveButton,toolHover,1,0);
auto tips=CreateWindowExW(WS_EX_TOPMOST,TOOLTIPS_CLASSW,nullptr,WS_POPUP|TTS_ALWAYSTIP|TTS_NOPREFIX,
CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,w,nullptr,c.app.instance,nullptr);
c.tooltips = tips;
for (int id : {EditorStatus, EditorZoom})
{
TOOLINFOW tool{sizeof(tool), TTF_IDISHWND | TTF_SUBCLASS, w,
reinterpret_cast<UINT_PTR>(GetDlgItem(w, id))};
tool.lpszText = const_cast<wchar_t *>(id == EditorZoom ?
L"Ctrl+wheel or Ctrl+plus/minus to zoom. Ctrl+0 to fit. Middle-drag to pan." : L"");
SendMessageW(tips, TTM_ADDTOOLW, 0, reinterpret_cast<LPARAM>(&tool));
}
for (size_t i=0;i<std::size(ToolIds);++i)
{
auto button = CreateWindowW(L"BUTTON",labels[i],WS_CHILD|WS_VISIBLE|BS_OWNERDRAW,
0,0,0,0,w,(HMENU)(INT_PTR)ToolIds[i],c.app.instance,nullptr);
SendMessageW(button, WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), TRUE);
SetWindowSubclass(button,toolHover,1,0);
TOOLINFOW tool{sizeof(tool)};
tool.uFlags=TTF_IDISHWND|TTF_SUBCLASS; tool.hwnd=w; tool.uId=(UINT_PTR)button;
@@ -1086,8 +1236,8 @@ void edit(HWND w, Capture &c)
SendMessageW(tips,TTM_ADDTOOLW,0,(LPARAM)&tool);
}
SendMessageW(GetDlgItem(w,21),BM_SETCHECK,BST_CHECKED,0);
CreateWindowW(L"STATIC",L"Line style",WS_CHILD|WS_VISIBLE,0,0,0,0,w,(HMENU)32,c.app.instance,nullptr);
CreateWindowW(L"STATIC",L"Ends",WS_CHILD|WS_VISIBLE,0,0,0,0,w,(HMENU)33,c.app.instance,nullptr);
CreateWindowW(L"STATIC",L"Line style",WS_CHILD|WS_VISIBLE|SS_CENTERIMAGE,0,0,0,0,w,(HMENU)32,c.app.instance,nullptr);
CreateWindowW(L"STATIC",L"Ends",WS_CHILD|WS_VISIBLE|SS_CENTERIMAGE,0,0,0,0,w,(HMENU)33,c.app.instance,nullptr);
for(int id:{30,31}) CreateWindowW(L"COMBOBOX",L"",WS_CHILD|WS_VISIBLE|CBS_DROPDOWNLIST|WS_VSCROLL,
0,0,0,0,w,(HMENU)(INT_PTR)id,c.app.instance,nullptr);
for(auto text:{L"Solid",L"Dotted",L"Dashed",L"Dash-dot"}) SendDlgItemMessageW(w,30,CB_ADDSTRING,0,(LPARAM)text);
@@ -1102,12 +1252,11 @@ void edit(HWND w, Capture &c)
SetWindowSubclass(labelButton,toolHover,1,0);
fontTip.uId=(UINT_PTR)labelButton; fontTip.lpszText=const_cast<wchar_t *>(L"Arrow label (F2 / double-click); drag label to reposition");
SendMessageW(tips,TTM_ADDTOOLW,0,(LPARAM)&fontTip);
INITCOMMONCONTROLSEX sliders{sizeof(sliders),ICC_BAR_CLASSES}; InitCommonControlsEx(&sliders);
CreateWindowW(TRACKBAR_CLASSW,L"Pencil smoothing",WS_CHILD|WS_VISIBLE|WS_TABSTOP|TBS_NOTICKS,
0,0,0,0,w,(HMENU)41,c.app.instance,nullptr);
SendDlgItemMessageW(w,41,TBM_SETRANGE,TRUE,MAKELPARAM(0,100));
SendDlgItemMessageW(w,41,TBM_SETPAGESIZE,0,10);
for(int id:{42,43}) CreateWindowW(L"STATIC",L"",WS_CHILD|WS_VISIBLE,0,0,0,0,w,(HMENU)(INT_PTR)id,c.app.instance,nullptr);
for(int id:{42,43}) CreateWindowW(L"STATIC",L"",WS_CHILD|WS_VISIBLE|SS_CENTERIMAGE,0,0,0,0,w,(HMENU)(INT_PTR)id,c.app.instance,nullptr);
CreateWindowW(L"BUTTON",L"Apply to all strokes",WS_CHILD|WS_VISIBLE|WS_TABSTOP|BS_PUSHBUTTON,
0,0,0,0,w,(HMENU)44,c.app.instance,nullptr);
c.syncHistory();
@@ -1172,8 +1321,20 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
if((wp>=10 && wp<=13) || (wp>=18 && wp<=27) || wp==34 || wp==35 || wp==36 || wp==37 || wp==38) { drawTool(*reinterpret_cast<DRAWITEMSTRUCT *>(lp),*c); return TRUE; }
break;
case WM_CTLCOLORSTATIC:
SetBkColor((HDC)wp,RGB(255,255,255)); SetTextColor((HDC)wp,RGB(51,65,85));
return (LRESULT)GetStockObject(WHITE_BRUSH);
{
const auto dc = reinterpret_cast<HDC>(wp);
const int id = GetDlgCtrlID(reinterpret_cast<HWND>(lp));
SetBkColor(dc, c->palette.color());
SetTextColor(dc, id == EditorZoom ? GetSysColor(COLOR_WINDOWTEXT) : c->palette.secondaryText());
return reinterpret_cast<LRESULT>(c->palette.brush());
}
case WM_SYSCOLORCHANGE: case WM_SETTINGCHANGE: case WM_DWMCOLORIZATIONCOLORCHANGED:
if (c->editing)
{
c->palette.refresh(msg == WM_DWMCOLORIZATIONCOLORCHANGED ? std::optional<DWORD>(wp) : std::nullopt);
RedrawWindow(w, nullptr, nullptr, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN);
}
break;
case WM_ERASEBKGND: return 1;
case WM_SETCURSOR:
if ((HWND)wp==w && LOWORD(lp)==HTCLIENT) { captureCursor(w,*c); return TRUE; }
@@ -1184,6 +1345,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
bool pencil=c->selected>=0 && c->marks[c->selected].freehand;
if(pencil && c->marks[c->selected].smoothing!=amount) {
if(!c->smoothingDrag) c->remember(c->marks);
c->renderedMarksValid=false;
setScreenshotSmoothing(c->marks[c->selected],amount);
resolveScreenshotLinks(c->marks);
c->smoothingDrag=LOWORD(wp)==TB_THUMBTRACK;
@@ -1296,7 +1458,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
if (LOWORD(wp)==12 || LOWORD(wp)==18)
{
bool changed=LOWORD(wp)==12?c->history.undo(c->marks):c->history.redo(c->marks);
if(changed) { c->copied=false; c->selected=-1; c->selectedLabel=false; c->wheelDelta=0; c->wheelTarget=-1; }
if(changed) { c->copied=false; c->renderedMarksValid=false; c->selected=-1; c->selectedLabel=false; c->wheelDelta=0; c->wheelTarget=-1; }
c->syncHistory();
}
if (LOWORD(wp)==10 || LOWORD(wp)==11 || LOWORD(wp)==19 || LOWORD(wp)==36 || LOWORD(wp)==37 || LOWORD(wp)==38 || (LOWORD(wp)>=21 && LOWORD(wp)<=27))
@@ -1321,6 +1483,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
InvalidateRect(GetDlgItem(w,38),nullptr,FALSE);
}
if(c->dragging) c->renderedMarksValid=false;
SetFocus(w); captureCursor(w,*c); InvalidateRect(w,nullptr,FALSE); return 0;
case WM_KEYDOWN:
if(wp==VK_SHIFT && c->editing && c->dragging && c->freehand && c->part==MarkPart::None && !c->strokeConstrained) {
@@ -1463,6 +1626,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
c->strokeUsedConstraint=(wp&MK_SHIFT)!=0;
}
c->dragging=true; SetCapture(w);
if(c->editing) invalidateDrag(w,*c,{});
}
InvalidateRect(w,nullptr,FALSE); return 0;
}
@@ -1522,7 +1686,18 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
if (c->dragging)
{
POINT p{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
const auto previousSelection=region(c->start,c->end);
const auto previousInk=c->editing && msg==WM_MOUSEMOVE?dragInk(*c):RECT{};
c->end=c->editing?imagePoint(*c,p,c->part!=MarkPart::Thickness && c->part!=MarkPart::Rotation):POINT{std::clamp(p.x,0L,LONG(c->image->width)),std::clamp(p.y,0L,LONG(c->image->height))};
if(!c->editing && msg==WM_MOUSEMOVE)
{
const auto selection=region(c->start,c->end);
RECT dirty{};
if(UnionRect(&dirty,&previousSelection,&selection))
InvalidateRect(w,&dirty,FALSE);
captureCursor(w,*c);
return 0;
}
if(c->editing && c->part==MarkPart::None && c->shape!=ScreenshotShape::None)
c->end=constrainScreenshotShape(c->shape,c->start,c->end,c->image->width,c->image->height);
if(c->editing && (c->highlight || c->freehand) && c->part==MarkPart::None) {
@@ -1593,6 +1768,12 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
c->marks[c->selected]=dragScreenshotMark(c->original,c->part,c->start,c->end,c->image->width,c->image->height,(GetKeyState(VK_SHIFT)&0x8000)!=0);
resolveScreenshotLinks(c->marks);
}
if(c->editing && msg==WM_MOUSEMOVE)
{
invalidateDrag(w,*c,previousInk);
captureCursor(w,*c);
return 0;
}
if (msg==WM_LBUTTONUP)
{
c->dragging=false; ReleaseCapture();
@@ -1675,9 +1856,10 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
c->panning=false;
if(c->dragging && c->part!=MarkPart::None)
{
c->marks=std::move(c->beforeDrag); c->part=MarkPart::None;
c->marks=std::move(c->beforeDrag); c->renderedMarksValid=false; c->part=MarkPart::None;
}
c->dragging=false; InvalidateRect(w,nullptr,FALSE); return 0;
c->dragging=false; c->renderedMarksValid=false; c->dragDamage={};
InvalidateRect(w,nullptr,FALSE); return 0;
case WM_GETMINMAXINFO:
if (c->editing)
{
@@ -1692,6 +1874,7 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
{
auto r=reinterpret_cast<RECT *>(lp);
SetWindowPos(w,nullptr,r->left,r->top,r->right-r->left,r->bottom-r->top,SWP_NOZORDER);
setWindowResourceIcons(w, c->app.instance, IDI_KSWITCHER_SCREENSHOT);
layout(w,*c); positionInlineText(*c);
}
return 0;
@@ -1710,14 +1893,16 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
// Compose the entire frame off screen. Never expose a cleared desktop
// or a partially drawn selection between mouse moves.
auto buffer=c->frame->dc;
BitBlt(buffer,0,0,c->image->width,c->image->height,c->dimmed->dc,0,0,SRCCOPY);
const auto &dirty=ps.rcPaint;
const int width=dirty.right-dirty.left,height=dirty.bottom-dirty.top;
BitBlt(buffer,dirty.left,dirty.top,width,height,c->dimmed->dc,dirty.left,dirty.top,SRCCOPY);
if (c->dragging)
{
auto r=region(c->start,c->end);
BitBlt(buffer,r.left,r.top,r.right-r.left,r.bottom-r.top,c->image->dc,r.left,r.top,SRCCOPY);
FrameRect(buffer,&r,static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
}
BitBlt(dc,0,0,c->image->width,c->image->height,buffer,0,0,SRCCOPY);
BitBlt(dc,dirty.left,dirty.top,width,height,buffer,dirty.left,dirty.top,SRCCOPY);
}
else
{
@@ -1725,38 +1910,81 @@ LRESULT CALLBACK captureProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
if (!c->frame || c->frame->width!=width || c->frame->height!=height)
c->frame=std::make_unique<Surface>(width,height);
auto buffer=c->frame->dc;
FillRect(buffer,&client,GetSysColorBrush(COLOR_APPWORKSPACE));
RECT toolbar{0,0,client.right,c->panelHeight};
FillRect(buffer,&toolbar,static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
auto divider=CreatePen(PS_SOLID,1,RGB(226,232,240));
auto previous=SelectObject(buffer,divider);
MoveToEx(buffer,0,c->panelHeight-1,nullptr); LineTo(buffer,client.right,c->panelHeight-1);
int dpi=GetDpiForWindow(w);
for(int x:{440,524}) {
MoveToEx(buffer,MulDiv(x,dpi,96),MulDiv(13,dpi,96),nullptr);
LineTo(buffer,MulDiv(x,dpi,96),MulDiv(31,dpi,96));
const SavedDc savedFrame(buffer);
const auto &dirty=ps.rcPaint;
IntersectClipRect(buffer,dirty.left,dirty.top,dirty.right,dirty.bottom);
const auto dpi = GetDpiForWindow(w);
const auto dip = [dpi](int n) { return MulDiv(n, dpi, 96); };
const RECT toolbar{0, 0, client.right, dip(EditorOptionsTop)};
const RECT options{0, toolbar.bottom, client.right, c->panelHeight};
const RECT footer{0, c->canvas.bottom, client.right, client.bottom};
FillRect(buffer, &toolbar, GetSysColorBrush(COLOR_WINDOW));
FillRect(buffer, &options, c->palette.brush());
FillRect(buffer, &footer, c->palette.brush());
fillSurface(buffer, c->canvas, c->palette.highContrast ? GetSysColor(COLOR_APPWORKSPACE) : RGB(224, 232, 239));
const auto edge = c->palette.edge();
fillSurface(buffer, {0, options.top, client.right, options.top + 1}, edge);
fillSurface(buffer, {0, options.bottom - 1, client.right, options.bottom}, edge);
fillSurface(buffer, {0, footer.top, client.right, footer.top + 1}, edge);
fillSurface(buffer, {dip(108), footer.top + dip(7), dip(108) + 1, footer.bottom - dip(7)}, edge);
for (int x : EditorToolDividers)
fillSurface(buffer, {dip(x), dip(13), dip(x) + 1, dip(31)}, edge);
const auto preview=shapePreview(*c);
const auto *previewMark=c->dragging && c->part==MarkPart::None?
((c->highlight || c->freehand)?&c->stroke:&preview):nullptr;
const auto *source=c->image.get();
if(!c->marks.empty() || previewMark)
{
const bool inlineEdit=c->inlineText && c->textIndex>=0;
const bool partial=c->renderedMarksValid && !inlineEdit;
if(!c->rendered)
c->rendered=std::make_unique<Surface>(source->width,source->height);
auto &rendered=*c->rendered;
RECT imageArea{0,0,rendered.width,rendered.height}, repaint=imageArea;
if(partial) IntersectRect(&repaint,&imageArea,&c->dragDamage);
if(!IsRectEmpty(&repaint))
{
c->renderedMarksValid=false;
BitBlt(rendered.dc,repaint.left,repaint.top,repaint.right-repaint.left,repaint.bottom-repaint.top,
source->dc,repaint.left,repaint.top,SRCCOPY);
if(inlineEdit)
{
auto visibleMarks=c->marks;
if(c->editingLabel) visibleMarks[c->textIndex].label.clear();
else visibleMarks.erase(visibleMarks.begin()+c->textIndex);
drawMarks(rendered.dc,visibleMarks,previewMark);
}
else if(partial)
{
const SavedDc previousClip(rendered.dc);
IntersectClipRect(rendered.dc,repaint.left,repaint.top,repaint.right,repaint.bottom);
drawMarks(rendered.dc,c->marks,previewMark,&repaint);
}
else drawMarks(rendered.dc,c->marks,previewMark);
c->renderedMarksValid=!inlineEdit;
}
source=&rendered;
}
SelectObject(buffer,previous); DeleteObject(divider);
Surface rendered(c->image->width,c->image->height);
BitBlt(rendered.dc,0,0,rendered.width,rendered.height,c->image->dc,0,0,SRCCOPY);
Mark preview{c->start,c->end,0};
preview.color=c->currentColor;
preview.style=c->lineStyle; preview.ends=c->straight || c->shape!=ScreenshotShape::None?LineEnds::None:c->arrowEnds;
preview.shape=c->shape;
auto visibleMarks=c->marks;
if(c->inlineText && c->textIndex>=0) {
if(c->editingLabel) visibleMarks[c->textIndex].label.clear();
else visibleMarks.erase(visibleMarks.begin()+c->textIndex);
else
{
c->rendered.reset();
c->renderedMarksValid=false;
}
drawMarks(rendered.dc,visibleMarks,c->dragging && c->part==MarkPart::None?((c->highlight || c->freehand)?&c->stroke:&preview):nullptr);
c->dragDamage={};
SetStretchBltMode(buffer,HALFTONE); SetBrushOrgEx(buffer,0,0,nullptr);
int savedCanvas=SaveDC(buffer);
IntersectClipRect(buffer,c->canvas.left,c->canvas.top,c->canvas.right,c->canvas.bottom);
StretchBlt(buffer,c->view.left,c->view.top,c->view.right-c->view.left,c->view.bottom-c->view.top,
rendered.dc,0,0,rendered.width,rendered.height,SRCCOPY);
drawHandles(buffer,*c);
RestoreDC(buffer,savedCanvas);
BitBlt(dc,0,0,width,height,buffer,0,0,SRCCOPY);
{
const SavedDc savedCanvas(buffer);
IntersectClipRect(buffer,c->canvas.left,c->canvas.top,c->canvas.right,c->canvas.bottom);
auto frame = c->view;
InflateRect(&frame, 1, 1);
SetDCBrushColor(buffer, c->palette.highContrast ? GetSysColor(COLOR_WINDOWTEXT) : RGB(155, 174, 191));
FrameRect(buffer, &frame, reinterpret_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
StretchBlt(buffer,c->view.left,c->view.top,c->view.right-c->view.left,c->view.bottom-c->view.top,
source->dc,0,0,source->width,source->height,SRCCOPY);
drawHandles(buffer,*c);
}
BitBlt(dc,dirty.left,dirty.top,dirty.right-dirty.left,dirty.bottom-dirty.top,
buffer,dirty.left,dirty.top,SRCCOPY);
}
}
catch (...) { EndPaint(w,&ps); throw; }
+19 -3
View File
@@ -50,9 +50,25 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
std::wstring token;
bool autoOpenEditor=false, writeLog=false;
int argc{}; auto argv=CommandLineToArgvW(GetCommandLineW(),&argc);
if(argc==3 && std::wstring(argv[1])==L"--clipboard-snapshot") {
std::filesystem::path request=argv[2]; LocalFree(argv);
return ks::runClipboardSnapshot(request);
const bool clipboardSnapshot = argc == 6 && std::wstring_view(argv[1]) == L"--clipboard-snapshot";
const bool historyImageWorker = argc == 5 && std::wstring_view(argv[1]) == L"--history-image-worker";
if (clipboardSnapshot || historyImageWorker)
{
HANDLE handles[4]{};
for (int i = 0; i < argc - 2; ++i)
{
wchar_t *end{};
const auto value=std::wcstoull(argv[i+2],&end,10);
if(!value || *end || value>UINTPTR_MAX) { LocalFree(argv); return 1; }
handles[i]=reinterpret_cast<HANDLE>(static_cast<uintptr_t>(value));
}
LocalFree(argv);
if (clipboardSnapshot) return ks::runClipboardSnapshot(handles[0], handles[1], handles[2], handles[3]);
const auto initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
if(FAILED(initialized)) return 1;
const auto result=ks::runHistoryImageWorker(handles[0],handles[1],handles[2]);
CoUninitialize();
return result;
}
if(argc==3 && (std::wstring(argv[1])==L"--capture-history" || std::wstring(argv[1])==L"--history-ocr")) {
bool ocr=std::wstring(argv[1])==L"--history-ocr";
+296 -109
View File
@@ -28,9 +28,9 @@ std::wstring newSnippetId()
}
namespace
{
Bytes jsonBytes(const Json &j)
Bytes jsonBytes(const Json &j, int indent = 2)
{
auto s = j.dump(2);
auto s = j.dump(indent);
return Bytes(s.begin(), s.end());
}
Json parse(const Bytes &bytes)
@@ -269,8 +269,9 @@ void validateSettings(const Settings &s)
if (alphabet.empty() || words.size() > 10000)
throw std::runtime_error("Invalid personal dictionary language or too many words");
for (const auto &word : words)
if (word.empty() || word.size() > 32 || lower(word).find_first_not_of(alphabet) != word.npos)
throw std::runtime_error("Personal words must contain 1-32 letters of their selected language");
if (!validPersonalWord(word, alphabet))
throw std::runtime_error("Personal words must be 1-32 characters, with letters of the selected language. "
"A hyphen (-) is allowed between letters.");
}
if (s.maxItems < 10 || s.maxItems > 10000 || s.maxMiB < 1 || s.maxMiB > 2048 || s.maxImageMiB < 1 ||
s.maxImageMiB > 64)
@@ -327,7 +328,7 @@ Settings decodeSettings(const Bytes &bytes, const std::vector<Layout> &layouts)
throw std::runtime_error("Not a KSwitcher or Typlo settings file");
s.recent = j.value("convertLastWord", true);
s.switchLayout = j.value("switchSystemLayout", true);
s.writeLog = j.value("writeLog", true);
s.writeLog = j.value("writeLog", s.writeLog);
s.history = j.value("historyEnabled", true);
s.useTesseract = j.value("useTesseract", false);
s.tesseractPath = str(j, "tesseractPath");
@@ -685,7 +686,127 @@ Clip decodeClip(const Bytes &b)
throw std::runtime_error("Trailing clipboard data");
return clip;
}
History::History(const std::filesystem::path &folder) : folder_(folder)
namespace
{
struct ImageWorkerControl
{
static constexpr size_t MaxPath=32768;
wchar_t request[MaxPath];
int result;
};
struct ImageWorkerHandle
{
HANDLE value{};
~ImageWorkerHandle() { reset(); }
void reset()
{
if(value) CloseHandle(std::exchange(value,nullptr));
}
};
template <typename Control>
struct ImageWorkerView
{
Control *control{};
~ImageWorkerView() { reset(); }
void reset()
{
if(control) UnmapViewOfFile(std::exchange(control,nullptr));
}
};
template <typename Control>
struct ImageWorkerChannel
{
ImageWorkerHandle mapping, requestReady, responseReady, process;
ImageWorkerView<Control> view;
~ImageWorkerChannel() { stop(); }
void stop() noexcept
{
if (process.value && WaitForSingleObject(process.value, 0) == WAIT_TIMEOUT)
{
TerminateProcess(process.value, ERROR_CANCELLED);
WaitForSingleObject(process.value, INFINITE);
}
process.reset();
view.reset();
mapping.reset();
requestReady.reset();
responseReady.reset();
}
void open()
{
SECURITY_ATTRIBUTES security{sizeof(security), nullptr, TRUE};
mapping.value = CreateFileMappingW(INVALID_HANDLE_VALUE, &security, PAGE_READWRITE, 0, sizeof(Control), nullptr);
requestReady.value = CreateEventW(&security, FALSE, FALSE, nullptr);
responseReady.value = CreateEventW(&security, FALSE, FALSE, nullptr);
if (!mapping.value || !requestReady.value || !responseReady.value)
throw std::runtime_error("Cannot create image helper channel");
view.control = static_cast<Control *>(MapViewOfFile(mapping.value, FILE_MAP_WRITE, 0, 0, sizeof(Control)));
if (!view.control) throw std::runtime_error("Cannot map image helper channel");
}
void start(std::wstring_view mode, HANDLE parent = nullptr)
{
std::vector<HANDLE> inherited{mapping.value, requestReady.value, responseReady.value};
if (parent) inherited.push_back(parent);
SIZE_T bytes{};
InitializeProcThreadAttributeList(nullptr, 1, 0, &bytes);
Bytes storage(bytes);
auto attributes = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
if (!InitializeProcThreadAttributeList(attributes, 1, 0, &bytes))
throw std::runtime_error("Cannot initialize image helper startup");
struct Attributes
{
LPPROC_THREAD_ATTRIBUTE_LIST value;
~Attributes() { DeleteProcThreadAttributeList(value); }
} cleanup{attributes};
if (!UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
inherited.data(), inherited.size() * sizeof(HANDLE), nullptr, nullptr))
throw std::runtime_error("Cannot configure image helper startup");
const auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
auto command = L"\"" + helper.wstring() + L"\" ";
command += mode;
for (auto handle : inherited) command += L" " + std::to_wstring(reinterpret_cast<uintptr_t>(handle));
STARTUPINFOEXW startup{};
startup.StartupInfo.cb = sizeof(startup);
startup.lpAttributeList = attributes;
PROCESS_INFORMATION child{};
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, TRUE,
CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT, nullptr, helper.parent_path().c_str(),
&startup.StartupInfo, &child))
throw std::runtime_error(utf8(lastError(L"Cannot start image helper")));
process.value = child.hProcess;
CloseHandle(child.hThread);
for (auto handle : inherited) SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
}
DWORD waitForResponse(DWORD timeout) const
{
HANDLE signals[]{responseReady.value, process.value};
return WaitForMultipleObjects(2, signals, FALSE, timeout);
}
};
struct HistoryImageWorker
{
std::timed_mutex mutex;
ImageWorkerChannel<ImageWorkerControl> channel;
int perform(const std::filesystem::path &, const std::function<bool()> &);
};
struct ClipboardSnapshotControl
{
DWORD sequence;
char captureError[256];
};
}
struct HistoryImageWorkers
{
// A slow recognition must not delay history thumbnails.
HistoryImageWorker recognition, thumbnails;
};
History::~History() = default;
History::History(const std::filesystem::path &folder)
: folder_(folder), imageWorkers_(std::make_unique<HistoryImageWorkers>())
{
std::filesystem::create_directories(folder_);
loadIndex();
@@ -724,92 +845,104 @@ void History::loadIndex()
}
entries_ = std::move(loaded);
}
void History::reload() { std::lock_guard lock(mutex_); loadIndex(); }
void ClipboardSnapshot::cleanup() noexcept
void History::reload()
{
if (request_.empty()) return;
std::error_code ignored;
for (const auto *suffix : {L"", L".snapshot", L".result"})
std::filesystem::remove(std::filesystem::path(request_.wstring() + suffix), ignored);
request_.clear();
std::lock_guard writer(indexWriter_);
std::lock_guard lock(mutex_);
loadIndex();
}
ClipboardSnapshot::~ClipboardSnapshot() { cleanup(); }
DWORD ClipboardSnapshot::run(bool restore, DWORD sequence)
struct ClipboardSnapshot::Helper
{
atomicWrite(request_, protect(jsonBytes(Json{{"schema", 1}, {"restore", restore}, {"sequence", sequence}})));
auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
auto command = L"\"" + helper.wstring() + L"\" --clipboard-snapshot \"" + request_.wstring() + L"\"";
STARTUPINFOW startup{sizeof(startup)};
startup.dwFlags = STARTF_USESHOWWINDOW; startup.wShowWindow = SW_HIDE;
PROCESS_INFORMATION process{};
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
nullptr, helper.parent_path().c_str(), &startup, &process))
throw std::runtime_error("Cannot start clipboard snapshot helper");
CloseHandle(process.hThread);
auto wait = WaitForSingleObject(process.hProcess, 10000);
DWORD result = ERROR_GEN_FAILURE;
ImageWorkerChannel<ClipboardSnapshotControl> channel;
};
ClipboardSnapshot::ClipboardSnapshot() = default;
ClipboardSnapshot::~ClipboardSnapshot() = default;
DWORD ClipboardSnapshot::capture(HWND window, DWORD sequence)
{
helper_.reset();
clip_ = {};
if (!clipboardHasImage())
{
clip_ = readClipboard(window, 64 * 1024 * 1024, ClipboardRead::WithoutImages, sequence, &sequence);
return sequence;
}
auto helper = std::make_unique<Helper>();
auto &channel = helper->channel;
channel.open();
channel.view.control->sequence = sequence;
// Let the helper discard its private copy if the resident exits unexpectedly.
ImageWorkerHandle parent;
const auto self = GetCurrentProcess();
if (!DuplicateHandle(self, self, self, &parent.value, SYNCHRONIZE, TRUE, 0))
throw std::runtime_error("Cannot pass resident lifetime to clipboard helper");
channel.start(L"--clipboard-snapshot", parent.value);
const auto wait = channel.waitForResponse(10000);
if (wait == WAIT_TIMEOUT)
throw std::runtime_error("Clipboard snapshot helper timed out during capture");
if (wait == WAIT_FAILED)
throw std::runtime_error(utf8(lastError(L"Cannot wait for clipboard snapshot helper")));
if (wait != WAIT_OBJECT_0)
{
TerminateProcess(process.hProcess, ERROR_TIMEOUT);
WaitForSingleObject(process.hProcess, INFINITE);
const auto &error = channel.view.control->captureError;
if (error[0]) throw std::runtime_error(std::string("Clipboard snapshot capture: ") + error);
DWORD exitCode{};
if (GetExitCodeProcess(channel.process.value, &exitCode))
throw std::runtime_error("Clipboard snapshot helper exited during capture (code " +
std::to_string(exitCode) + ")");
throw std::runtime_error(utf8(lastError(L"Cannot read clipboard snapshot helper exit code")));
}
GetExitCodeProcess(process.hProcess, &result);
CloseHandle(process.hProcess);
if (wait != WAIT_OBJECT_0 || result) throw std::runtime_error("Clipboard snapshot helper failed");
return parse(unprotect(readFile(request_.wstring() + L".result", 4096))).at("sequence").get<DWORD>();
}
void ClipboardSnapshot::capture(HWND window, DWORD sequence)
{
cleanup();
clip_ = {};
if (!IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5) &&
!IsClipboardFormatAvailable(CF_BITMAP) && !IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG")))
{
clip_ = readClipboard(window, 64 * 1024 * 1024, ClipboardRead::WithoutImages, sequence);
return;
}
request_ = std::filesystem::temp_directory_path() / (L"ks-clipboard-" + newSnippetId() + L".request");
try { run(false, sequence); }
catch (...) { cleanup(); throw; }
sequence = channel.view.control->sequence;
helper_ = std::move(helper);
return sequence;
}
DWORD ClipboardSnapshot::restore(HWND window, DWORD sequence)
{
return request_.empty() ? writeClipboardGuarded(window, clip_, sequence) : run(true, sequence);
if (!helper_) return writeClipboardGuarded(window, clip_, sequence);
auto &channel = helper_->channel;
if (!channel.process.value)
throw std::runtime_error("Clipboard snapshot helper is unavailable");
channel.view.control->sequence = sequence;
DWORD result{};
if (!SetEvent(channel.requestReady.value) || WaitForSingleObject(channel.process.value, 10000) != WAIT_OBJECT_0 ||
!GetExitCodeProcess(channel.process.value, &result) || result != 0)
{
channel.stop();
throw std::runtime_error("Clipboard snapshot helper failed to restore");
}
return channel.view.control->sequence;
}
int runClipboardSnapshot(const std::filesystem::path &request)
int runClipboardSnapshot(HANDLE mapping, HANDLE requestReady, HANDLE responseReady, HANDLE parent)
{
ImageWorkerView<ClipboardSnapshotControl> view{static_cast<ClipboardSnapshotControl *>(
MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, sizeof(ClipboardSnapshotControl)))};
if (!view.control) return 1;
try
{
if (!request.is_absolute() || !request.filename().wstring().starts_with(L"ks-clipboard-") ||
request.extension() != L".request") return 1;
auto job = parse(unprotect(readFile(request, 4096)));
if (job.at("schema") != 1) return 1;
auto sequence = job.at("sequence").get<DWORD>();
const auto snapshot = request.wstring() + L".snapshot";
if (job.at("restore").get<bool>())
{
auto clip = decodeClip(unprotect(readFile(snapshot, 70 * 1024 * 1024)));
HWND window = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
if (!window) return 1;
struct WindowCleanup { HWND window; ~WindowCleanup() { DestroyWindow(window); } } cleanup{window};
sequence = writeClipboardGuarded(window, clip, sequence);
}
else
{
auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence);
if (sequence != GetClipboardSequenceNumber()) return 2;
atomicWrite(snapshot, protect(encodeClip(clip)));
}
atomicWrite(request.wstring() + L".result", protect(jsonBytes(Json{{"sequence", sequence}})));
auto &sequence = view.control->sequence;
const auto clip = readClipboard(nullptr, 64 * 1024 * 1024, ClipboardRead::All, sequence, &sequence);
if (!SetEvent(responseReady)) return 1;
// The captured formats stay in this process.
HANDLE signals[]{parent, requestReady};
if (WaitForMultipleObjects(2, signals, FALSE, INFINITE) != WAIT_OBJECT_0 + 1) return 1;
HWND window = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
if (!window) return 1;
struct WindowCleanup { HWND window; ~WindowCleanup() { DestroyWindow(window); } } cleanup{window};
view.control->sequence = writeClipboardGuarded(window, clip, view.control->sequence);
return 0;
}
catch (const std::exception &error)
{
auto &message = view.control->captureError;
strncpy_s(message, error.what(), _TRUNCATE);
return 1;
}
catch (...) { return 1; }
}
bool History::captureImage(DWORD sequence, const std::wstring &app, const Settings &settings)
{
// Serialize helper index changes with all resident history mutations. Only
// metadata is reloaded: GetClipboardData's image allocations die with the child.
std::lock_guard lock(mutex_);
std::lock_guard writer(indexWriter_);
if (sequence != GetClipboardSequenceNumber()) return false;
auto request = std::filesystem::absolute(folder_) / (L"capture-" + newSnippetId() + L".request");
struct Cleanup {
@@ -838,7 +971,10 @@ bool History::captureImage(DWORD sequence, const std::wstring &app, const Settin
}
GetExitCodeProcess(process.hProcess, &result);
CloseHandle(process.hProcess);
loadIndex(); // Also reconcile any completed atomic save before a child failure.
{
std::lock_guard lock(mutex_);
loadIndex(); // Also reconcile any completed atomic save before a child failure.
}
if (wait != WAIT_OBJECT_0) throw std::runtime_error("Image history helper timed out");
if (result == 2) return false;
if (result == 3) throw std::runtime_error("Clipboard exceeds the configured size limit");
@@ -861,9 +997,7 @@ int runImageHistoryCapture(const std::filesystem::path &request)
!IsClipboardFormatAvailable(RegisterClipboardFormatW(L"Clipboard Viewer Ignore"));
};
if (!valid()) return 2;
if (!IsClipboardFormatAvailable(CF_DIB) && !IsClipboardFormatAvailable(CF_DIBV5) &&
!IsClipboardFormatAvailable(CF_BITMAP) &&
!IsClipboardFormatAvailable(RegisterClipboardFormatW(L"PNG"))) return 2;
if (!clipboardHasImage()) return 2;
auto clip = readClipboard(nullptr, size_t(settings.maxImageMiB) * 1024 * 1024);
if (!valid()) return 2;
for (const auto &format : clip.formats)
@@ -893,7 +1027,7 @@ void History::saveIndex()
{"files", e.files}, {"ocrState", e.ocrState}, {"ocrProfile", utf8(e.ocrProfile)},
{"fingerprintVersion", 1}, {"contentHash", e.contentHash},
{"imageHash", e.imageHash}, {"pixelHash", e.pixelHash}});
atomicWrite(folder_ / L"index.dat", protect(jsonBytes(j)));
atomicWrite(folder_ / L"index.dat", protect(jsonBytes(j, -1)));
}
std::vector<Entry> History::entries() const
{
@@ -1007,6 +1141,7 @@ void History::add(const Clip &clip, const std::wstring &app, const Settings &s,
image |= f.id == CF_DIB || f.id == CF_DIBV5 || f.name == L"PNG";
files |= f.id == CF_HDROP;
}
std::lock_guard writer(indexWriter_);
std::lock_guard lock(mutex_);
Entry fingerprints;
fingerprints.contentHash = clipboardHash(data);
@@ -1068,6 +1203,7 @@ void History::add(const Clip &clip, const std::wstring &app, const Settings &s,
}
void History::remove(const std::wstring &id)
{
std::lock_guard writer(indexWriter_);
std::lock_guard lock(mutex_);
if (!validId(id))
return;
@@ -1082,6 +1218,7 @@ void History::remove(const std::wstring &id)
}
void History::pin(const std::wstring &id)
{
std::lock_guard writer(indexWriter_);
std::lock_guard lock(mutex_);
for (auto &e : entries_)
if (e.id == id)
@@ -1090,6 +1227,7 @@ void History::pin(const std::wstring &id)
}
void History::clear()
{
std::lock_guard writer(indexWriter_);
std::lock_guard lock(mutex_);
auto old = entries_;
entries_.clear();
@@ -1101,7 +1239,84 @@ void History::clear()
std::filesystem::remove(folder_ / (e.id + L".ocr"), ec);
}
}
static Bytes historyImageJob(const std::filesystem::path &folder, const std::wstring &id,
namespace
{
int HistoryImageWorker::perform(const std::filesystem::path &request,const std::function<bool()> &cancelled)
{
std::unique_lock lock(mutex,std::defer_lock);
const auto checkCancelled=[&] {
if(cancelled && cancelled()) throw std::runtime_error("History OCR cancelled");
};
while(!lock.try_lock_for(std::chrono::milliseconds(100))) checkCancelled();
checkCancelled();
const auto &path=request.native();
if(path.size()>=ImageWorkerControl::MaxPath)
throw std::runtime_error("History OCR request path is too long");
try
{
for(int attempt=0;attempt<2;++attempt)
{
if(!channel.process.value || WaitForSingleObject(channel.process.value,0)!=WAIT_TIMEOUT)
{
channel.stop();
channel.open();
channel.start(L"--history-image-worker");
}
checkCancelled();
std::copy(path.begin(),path.end(),channel.view.control->request);
channel.view.control->request[path.size()]=L'\0';
if(!SetEvent(channel.requestReady.value)) throw std::runtime_error("Cannot request history OCR");
const auto deadline=GetTickCount64()+60000;
for(;;)
{
const auto wait=channel.waitForResponse(100);
if(wait==WAIT_OBJECT_0)
{
checkCancelled();
return channel.view.control->result;
}
if(wait==WAIT_OBJECT_0+1)
{
DWORD code{};
if(GetExitCodeProcess(channel.process.value,&code) && code==WAIT_TIMEOUT && !attempt) break;
throw std::runtime_error("History OCR helper exited before responding");
}
if(wait!=WAIT_TIMEOUT) throw std::runtime_error("Cannot wait for history OCR helper");
checkCancelled();
if(GetTickCount64()>=deadline) throw std::runtime_error("History OCR helper timed out");
}
channel.stop();
}
}
catch(...)
{
// The child must stop writing before the request and response files are cleaned up.
channel.stop();
throw;
}
throw std::runtime_error("History OCR helper did not accept the request");
}
}
int runHistoryImageWorker(HANDLE mapping,HANDLE requestReady,HANDLE responseReady)
{
ImageWorkerView<ImageWorkerControl> view{static_cast<ImageWorkerControl *>(
MapViewOfFile(mapping,FILE_MAP_WRITE,0,0,sizeof(ImageWorkerControl)))};
if(!view.control) return 1;
for(;;)
{
const auto wait=WaitForSingleObject(requestReady,30000);
if(wait==WAIT_TIMEOUT) return WAIT_TIMEOUT;
if(wait!=WAIT_OBJECT_0) return 1;
const auto &request=view.control->request;
const auto end=std::find(std::begin(request),std::end(request),L'\0');
view.control->result=end==std::end(request)?1:runHistoryOcr(std::wstring(std::begin(request),end));
if(!SetEvent(responseReady)) return 1;
}
}
static Bytes historyImageJob(HistoryImageWorker &worker,const std::filesystem::path &folder,const std::wstring &id,
const Json &job, const std::function<bool()> &cancelled)
{
if (!validId(id)) throw std::runtime_error("Invalid history ID");
@@ -1117,36 +1332,7 @@ static Bytes historyImageJob(const std::filesystem::path &folder, const std::wst
}
} cleanup{request, response};
atomicWrite(request, protect(jsonBytes(job)));
auto helper = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Screenshot.exe";
auto command = L"\"" + helper.wstring() + L"\" --history-ocr \"" + request.wstring() + L"\"";
STARTUPINFOW startup{sizeof(startup)};
startup.dwFlags = STARTF_USESHOWWINDOW; startup.wShowWindow = SW_HIDE;
PROCESS_INFORMATION process{};
if (!CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW,
nullptr, helper.parent_path().c_str(), &startup, &process))
throw std::runtime_error(utf8(lastError(L"Cannot start history OCR helper")));
CloseHandle(process.hThread);
struct Child {
HANDLE handle;
~Child() {
if (WaitForSingleObject(handle, 0) != WAIT_OBJECT_0) {
TerminateProcess(handle, ERROR_CANCELLED);
WaitForSingleObject(handle, INFINITE);
}
CloseHandle(handle);
}
} child{process.hProcess};
auto deadline = GetTickCount64() + 60000;
for (;;) {
auto wait = WaitForSingleObject(child.handle, 100);
if (wait == WAIT_OBJECT_0) break;
if (wait != WAIT_TIMEOUT) throw std::runtime_error("Cannot wait for history OCR helper");
if (cancelled && cancelled()) throw std::runtime_error("History OCR cancelled");
if (GetTickCount64() >= deadline) throw std::runtime_error("History OCR helper timed out");
}
DWORD result{};
if (!GetExitCodeProcess(child.handle, &result) || result)
throw std::runtime_error("History OCR helper failed: " + std::to_string(result));
if(worker.perform(request,cancelled)) throw std::runtime_error("History OCR helper failed");
return unprotect(readFile(response, 8 * 1024 * 1024));
}
std::wstring History::recognizeImage(const std::wstring &id, const Settings &settings,
@@ -1154,14 +1340,14 @@ std::wstring History::recognizeImage(const std::wstring &id, const Settings &set
{
Json job{{"schema", 1}, {"id", utf8(id)}, {"tesseract", settings.useTesseract},
{"path", utf8(settings.tesseractPath)}, {"languages", utf8(settings.tesseractLanguages)}};
auto reply = parse(historyImageJob(folder_, id, job, cancelled));
auto reply = parse(historyImageJob(imageWorkers_->recognition,folder_, id, job, cancelled));
if (reply.at("schema") != 1 || str(reply, "id") != id)
throw std::runtime_error("Invalid history OCR response");
return str(reply, "text");
}
Pixels History::thumbnail(const std::wstring &id, const std::function<bool()> &cancelled) const
{
auto bytes = historyImageJob(folder_, id, Json{{"schema", 1}, {"id", utf8(id)}, {"thumbnail", true}}, cancelled);
auto bytes = historyImageJob(imageWorkers_->thumbnails,folder_, id, Json{{"schema", 1}, {"id", utf8(id)}, {"thumbnail", true}}, cancelled);
size_t at = 0;
auto width = get32(bytes, at), height = get32(bytes, at);
if (!width || !height || width > 208 || height > 128 || bytes.size() - at != width * height * 4)
@@ -1200,6 +1386,7 @@ int runHistoryOcr(const std::filesystem::path &request)
}
bool History::saveOcr(const std::wstring &id, const std::optional<std::wstring> &text, const Settings &settings)
{
std::lock_guard writer(indexWriter_);
std::lock_guard lock(mutex_);
auto it = std::find_if(entries_.begin(), entries_.end(), [&](auto &e) { return e.id == id; });
// A late OCR completion must never recreate a deleted/pruned image.
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff. Show more