Compare commits

...
Author SHA1 Message Date
agrynco ba61c2ee9b Run delayed selection regression independently
Refs #135
2026-11-26 12:33:15 +02:00
agrynco 1d60b3a0b6 Recover recent text selection in Claude and verify hosted editors
Refs #135

Refs #137
2026-11-26 12:30:37 +02:00
agrynco ce36d73b66 Merge pull request 'Show release notes after updating and in Help' (#197) from codex/issue-196-whats-new into prerelease
Show release notes after updating and in Help
2026-11-26 08:20:09 +02:00
agrynco aa90645c98 Show release notes after updating and in Help
Refs #196
2026-11-26 08:18:46 +02:00
agrynco 07646d3642 Merge pull request 'Release KSwitcher v0.8.1' (#195) from codex/release-v0.8.1 into prerelease
Release KSwitcher v0.8.1
2026-11-26 07:52:02 +02:00
agrynco 9a5479b8f9 Release KSwitcher v0.8.1 2026-11-26 07:51:19 +02:00
agrynco 9edb27c765 Merge pull request 'Open Recent folders in the selected file panel' (#194) from codex/recent-folders-in-panel into prerelease
Open Recent folders in the selected file panel
2026-11-26 00:39:09 +02:00
agrynco 5194e2b621 Keep long recent folder names readable and stabilize UI checks
Refs #88
2026-11-26 00:37:46 +02:00
agrynco da914168e8 Open Recent folders in the selected file panel
Refs #88
2026-11-26 00:34:53 +02:00
agrynco 15bf006a19 Merge pull request 'Show SMB connections and shares in the file panel' (#193) from codex/smb-profiles-in-panel into prerelease
Show SMB connections and shares in the file panel
2026-11-26 00:26:50 +02:00
agrynco 9b5cff122d Show SMB connections and shares in the file panel
Refs #109
2026-11-26 00:25:22 +02:00
agrynco 7670616dc4 Merge pull request 'Release KSwitcher v0.8.0' (#192) from codex/release-v0.8.0 into prerelease
Release KSwitcher v0.8.0
2026-11-26 00:02:28 +02:00
agrynco 25acb892d1 Release KSwitcher v0.8.0 2026-11-26 00:01:52 +02:00
agrynco 03a370f445 Merge pull request 'KSwitcher.Files: Add local read-only MCP' (#191) from codex/issue-134-local-files-mcp into prerelease
Refs #134
2026-11-25 23:46:55 +02:00
agrynco e8bef94474 Serve opt-in read-only Files MCP on loopback
Refs #134
2026-11-25 23:46:44 +02:00
agrynco 0f400a58a1 Merge pull request 'KSwitcher.Files: View recent Files diagnostics' (#190) from codex/issue-132-log-view into prerelease
Refs #132
2026-11-25 23:35:29 +02:00
agrynco e852fde4f4 Open recent Files diagnostics in a safe native viewer
Refs #132
2026-11-25 23:35:15 +02:00
agrynco e421c17f2a Merge pull request 'KSwitcher.Files: Add contextual offline help' (#189) from codex/issue-131-context-help into prerelease
Refs #131
2026-11-25 23:29:45 +02:00
agrynco f4dcd0efd9 Add contextual offline help to Files
Refs #131
2026-11-25 23:29:30 +02:00
agrynco a5a5724513 Merge pull request 'KSwitcher.Files: Add independent area scales and system themes' (#188) from codex/issue-130-themes-scale into prerelease
Refs #130
2026-11-25 23:21:17 +02:00
agrynco 040658f350 Add independent Files scales and Windows theme palettes
Refs #130
2026-11-25 23:21:06 +02:00
agrynco 0ac6501b21 Merge pull request 'KSwitcher.Files: Add selective settings import and export' (#187) from codex/issue-129-settings-portability into prerelease
Refs #129
2026-11-25 23:06:54 +02:00
agrynco b6b7164742 Add selective Files settings JSON import and export
Refs #129
2026-11-25 23:06:45 +02:00
agrynco 8870d8c3d9 Merge pull request 'KSwitcher.Files: Add named keyboard schemes' (#185) from codex/issue-128-key-schemes into prerelease
Refs #128
2026-11-25 22:54:36 +02:00
agrynco eb0f6ead72 Add named keyboard schemes for Files commands
Refs #128
2026-11-25 22:54:25 +02:00
agrynco d26eec3c98 Merge pull request 'KSwitcher.Files: Restore local documents and guard external edits' (#183) from codex/issue-127-document-session into prerelease
Refs #127
2026-11-25 22:42:00 +02:00
agrynco 1757450833 Restore local Files documents and guard external edits
Refs #127
2026-11-25 22:41:48 +02:00
agrynco 1066fbeab8 Merge pull request 'KSwitcher.Files: local PNG and JPEG editor' (#182) from codex/issue-126-image-editor into prerelease
Refs #126
2026-11-25 22:25:56 +02:00
agrynco f2dc1f0c78 Add image rotation crop and undo to Files
Refs #126
2026-11-25 22:25:47 +02:00
agrynco 64e741f778 Merge pull request 'KSwitcher.Files: offline HTML and binary Quick View' (#180) from codex/issue-125-quick-preview into prerelease
Refs #125
2026-11-25 22:10:59 +02:00
agrynco 1edd0343ef Add offline HTML and binary Quick View
Refs #125
2026-11-25 22:10:49 +02:00
agrynco 6c0e8f0736 Merge pull request 'KSwitcher.Files: panel swap, marks and layout options' (#179) from codex/issue-124-panel-layout into prerelease
Refs #124
2026-11-25 21:51:08 +02:00
agrynco 934521f404 Add Files panel layout and mouse options
Refs #124
2026-11-25 21:51:02 +02:00
agrynco 2db50fcd0e Merge pull request 'KSwitcher.Files: Copy/Move options and time estimate' (#178) from codex/issue-123-copy-options into prerelease
Refs #123
2026-11-25 21:43:00 +02:00
agrynco dbbc5c138e Add advanced Files copy and move options
Refs #123
2026-11-25 21:42:50 +02:00
agrynco 84385a1eca Merge pull request 'KSwitcher.Files: file operations for trusted LAN clients' (#177) from codex/issue-122-lan-capabilities into prerelease
Refs #122
2026-11-25 21:27:08 +02:00
agrynco f5b7ddfb53 Expose file operations to trusted LAN clients
Refs #122
2026-11-25 21:26:55 +02:00
agrynco 93e672c71d Merge pull request 'KSwitcher.Files: Windows environment variables' (#176) from codex/issue-121-environment-panel into prerelease
Refs #121
2026-11-25 21:08:57 +02:00
agrynco cc6199e9be Inspect and edit Windows environment definitions
Refs #121
2026-11-25 21:08:51 +02:00
agrynco a27ae96842 Merge pull request 'KSwitcher.Files: Stage, Unstage and reviewed local commits' (#175) from codex/issue-120-git-mutations into prerelease
Refs #120
2026-11-25 20:59:44 +02:00
agrynco 9158bf95a6 Stage and commit a reviewed Git index snapshot
Refs #120
2026-11-25 20:59:30 +02:00
agrynco 159b776199 Merge pull request 'KSwitcher.Files: Git branches and commit history' (#174) from codex/issue-119-git-history into prerelease
Refs #119
2026-11-25 20:37:56 +02:00
agrynco ada198db24 Browse Git branches and paged commit history
Refs #119
2026-11-25 20:37:46 +02:00
agrynco fe1f818582 Merge pull request 'KSwitcher.Files: Git Changes and side-by-side diff' (#173) from codex/issue-118-git-changes into prerelease
Refs #118
2026-11-25 20:27:30 +02:00
agrynco 1217887e14 Add read-only Git Changes mode to Files
Refs #118
2026-11-25 20:27:10 +02:00
agrynco 10847244f0 Merge pull request 'KSwitcher.Files: Process panel and locking processes' (#172) from codex/issue-117-process-panel into prerelease
Refs #117
2026-11-25 20:11:25 +02:00
agrynco 82f1179970 Add a process panel and reuse lock searches
Refs #117
2026-11-25 20:11:14 +02:00
agrynco 92bee6bb67 Merge pull request 'KSwitcher.Files: Item properties and Windows attributes' (#171) from codex/issue-116-attributes into prerelease
Refs #116
2026-11-25 20:00:54 +02:00
agrynco e1f45a0098 Show and edit item properties in Files
Refs #116
2026-11-25 20:00:38 +02:00
agrynco bc44e0c1fc Merge pull request 'KSwitcher.Files: Windows Shell context menus' (#170) from codex/issue-115-shell-context into prerelease
Refs #115
2026-11-25 19:43:58 +02:00
agrynco 4992b783bc Add Windows Shell context menus to Files panels
Refs #115
2026-11-25 19:43:40 +02:00
agrynco fe1b114b38 Merge pull request 'KSwitcher.Files: Find files in remote sources' (#169) from codex/issue-114-remote-find into prerelease
Refs #114
2026-11-25 19:30:45 +02:00
agrynco 936c199a43 Search FTP, SFTP and LAN panels while retaining partial results
Refs #114
2026-11-25 19:30:31 +02:00
agrynco d12273da67 Merge pull request 'KSwitcher.Files: Temporary sudo access for SFTP Viewer and Editor' (#168) from codex/issue-113-sftp-sudo into prerelease
Refs #113
2026-11-25 19:11:42 +02:00
agrynco 1a81075763 Add single-operation sudo authorization for SFTP Viewer and Editor
Refs #113
2026-11-25 19:11:30 +02:00
agrynco d5996237c6 Merge pull request 'KSwitcher.Files: SSH terminal and saved jump routes' (#167) from codex/issue-112-files into prerelease
Refs #112
2026-11-25 18:54:01 +02:00
agrynco 4ef30ab5e8 Add routed SSH connections and the Files SSH terminal
Refs #112
2026-11-25 18:53:52 +02:00
agrynco 6279a2ee4f Merge pull request 'KSwitcher.Files: Interactive PowerShell terminal prompt' (#166) from codex/issue-111-terminal-input into prerelease
Refs #111
2026-11-25 18:31:45 +02:00
agrynco e11e19293f Support interactive editing in the Files terminal prompt
Refs #111
2026-11-25 18:31:36 +02:00
agrynco 5729ed2036 Merge pull request 'KSwitcher.Files: SFTP profiles and file operations' (#165) from codex/issue-110-sftp-panels into prerelease
Refs #110
2026-11-25 18:23:48 +02:00
agrynco 94ccb488c1 Add SFTP profiles and shared Files operations
Refs #110
2026-11-25 18:23:38 +02:00
agrynco e24fbc80ba Merge pull request 'KSwitcher.Files: Saved SMB connections and shares' (#164) from codex/issue-109-smb-profiles into prerelease
Refs #109
2026-11-25 17:53:43 +02:00
agrynco c735c21682 Add saved SMB connection profiles and share browsing
Refs #109
2026-11-25 17:53:30 +02:00
agrynco 9bb2221b2b Merge pull request 'KSwitcher.Files: FTP and LAN breadcrumbs and recent folders' (#161) from codex/issue-108-remote-breadcrumbs into prerelease
Refs #108
2026-11-25 17:34:37 +02:00
agrynco 20d95b37aa Add remote folder breadcrumbs and recent locations
Refs #108
2026-11-25 17:34:22 +02:00
agrynco 6467481d2f Merge pull request 'KSwitcher.Files: Restore FTP panels and recover LAN folders' (#160) from codex/issue-107-remote-panel-restore into prerelease
Refs #107
2026-11-25 17:22:57 +02:00
agrynco 7033c1e336 Restore FTP panels and recover interrupted LAN scans
Refs #107
2026-11-25 17:22:44 +02:00
agrynco 03145ae75a Merge pull request 'KSwitcher.Files: Unified diff and context folding' (#159) from codex/issue-106-unified-diff into prerelease
Refs #106
2026-11-25 17:04:17 +02:00
agrynco 9d57568351 Add unified comparison and context folding
Refs #106
2026-11-25 17:04:05 +02:00
agrynco f74b8b2ac0 Merge pull request 'KSwitcher.Files: Apply selected blocks in file comparison' (#158) from codex/issue-105-compare-apply into prerelease
Refs #105
2026-11-25 16:54:38 +02:00
agrynco 5bf2d7ab45 Apply selected blocks in file comparison
Refs #105
2026-11-25 16:54:25 +02:00
agrynco 4ab1f3c950 Merge pull request 'KSwitcher.Files: Збереження чернетки при перемиканні F6' (#157) from codex/issue-104-editor-draft into prerelease
Refs #104
2026-11-25 16:40:35 +02:00
agrynco 872c03823f Keep editor drafts when switching to the saved Viewer
Refs #104
2026-11-25 16:40:26 +02:00
agrynco 0c09fbdb88 Merge pull request 'KSwitcher.Files: Постійні закладки на рядки у Viewer' (#156) from codex/issue-103-viewer-bookmarks into prerelease
Refs #103
2026-11-25 16:32:33 +02:00
agrynco 50010c99ba Persist Viewer bookmarks and reopen files at saved lines
Refs #103
2026-11-25 16:32:23 +02:00
agrynco e92984d124 Merge pull request 'KSwitcher.Files: Hex Viewer для двійкових файлів' (#155) from codex/issue-102-hex-viewer into prerelease
Refs #102
2026-11-25 16:21:03 +02:00
agrynco 6f2f1f38e2 Show original file bytes in Hex Viewer
Refs #102
2026-11-25 16:20:52 +02:00
agrynco dc4e503c84 Merge pull request 'KSwitcher.Files: Перегляд зображень у Viewer та Quick View' (#154) from codex/issue-101-image-viewer into prerelease
Refs #101
2026-11-25 16:12:28 +02:00
agrynco 06c35c893c Preview images in Files Viewer and Quick View
Refs #101
2026-11-25 16:12:12 +02:00
agrynco 74e3248434 Merge pull request 'KSwitcher.Files: Створення й оновлення архівів' (#153) from codex/issue-100-archive-writing into prerelease
Refs #100
2026-11-25 15:56:13 +02:00
agrynco 1f4baed2ed Create and safely update ZIP and 7z archives in Files
Refs #100
2026-11-25 15:56:01 +02:00
agrynco 4147ccc04a Merge pull request 'KSwitcher.Files: Перегляд ZIP і 7z як папок' (#152) from codex/issue-99-archive-browsing into prerelease
Refs #99
2026-11-25 15:43:16 +02:00
agrynco cde7dacffc Browse local ZIP and 7z archives in Files
Refs #99
2026-11-25 15:43:10 +02:00
agrynco f1077909ef Merge pull request 'KSwitcher.Files: Medium, Full and configurable columns' (#151) from codex/issue-98-panel-columns into prerelease
Refs #98
2026-11-25 15:17:42 +02:00
agrynco 3efe108853 Add per-panel modes and customizable columns
Refs #98
2026-11-25 15:17:20 +02:00
agrynco 2348306b81 Merge pull request 'KSwitcher.Files: panel trees and background sizes' (#150) from codex/issue-97-panel-tree into prerelease
Refs #97
2026-11-25 15:03:00 +02:00
agrynco 4b252bd111 Add lazy panel trees and background folder sizes
Refs #97
2026-11-25 15:02:32 +02:00
agrynco 7577d19a84 Merge pull request 'KSwitcher.Files: Sunburst and indexed NTFS analysis' (#149) from codex/issue-96-sunburst-ntfs into prerelease
Refs #96
2026-11-25 14:47:49 +02:00
agrynco 24fbf72d60 Add Sunburst and indexed NTFS volume traversal
Refs #96
2026-11-25 14:47:33 +02:00
agrynco 291d7597e3 Merge pull request 'KSwitcher.Files: volume usage and treemap' (#148) from codex/issue-95-volume-treemap into prerelease
Refs #95
2026-11-25 14:34:22 +02:00
agrynco ea6338e9b9 Analyze volume usage and add a Files treemap
Refs #95
2026-11-25 14:34:06 +02:00
agrynco 5ea222ad8a Merge pull request 'KSwitcher.Files: local Space Analyzer' (#147) from codex/issue-94-space-analyzer into prerelease
Refs #94
2026-11-25 14:20:05 +02:00
agrynco efe7937507 Add a local Space Analyzer to Files
Refs #94
2026-11-25 14:19:47 +02:00
agrynco 30a904b386 Merge pull request 'KSwitcher.Files: per-panel sorting and filters' (#146) from codex/issue-93-panel-sort-filter into prerelease
Refs #93
2026-11-25 14:12:27 +02:00
agrynco 2545886092 Add per-panel sorting and file filters
Refs #93
2026-11-25 14:12:11 +02:00
agrynco 3971cb1871 Merge pull request 'KSwitcher.Files: drag and drop' (#145) from codex/issue-92-drag-drop into prerelease
Refs #92
2026-11-25 14:01:57 +02:00
agrynco 31473baa49 Add Windows file drag and drop to Files
Refs #92
2026-11-25 14:01:43 +02:00
agrynco c7b9ee5cb1 Merge pull request 'KSwitcher.Files: Windows file clipboard' (#144) from codex/issue-91-file-clipboard into prerelease
Refs #91
2026-11-25 13:50:48 +02:00
agrynco 07ed4cf724 Support Windows file clipboard in Files
Refs #91
2026-11-25 13:50:30 +02:00
agrynco 4b5bcd2983 Merge pull request 'KSwitcher.Files: Copy the full path of the current item' (#143) from codex/issue-90-copy-full-path into prerelease
Refs #90
2026-11-25 13:37:07 +02:00
agrynco 2a4df70079 Copy the full path of the current file panel item
Refs #90
2026-11-25 13:36:50 +02:00
agrynco e986dd90e5 Merge pull request 'KSwitcher.Files: Add Quick View for text and Markdown' (#142) from codex/issue-89-quick-view into prerelease
Refs #89
2026-11-25 13:33:28 +02:00
agrynco 3dd4edeb2c Add Quick View for local text and Markdown
Refs #89
2026-11-25 13:33:15 +02:00
agrynco edb259e6bb Merge pull request 'KSwitcher.Files: Add persistent recent folders' (#141) from codex/issue-88-recent-folders into prerelease
Refs #88
2026-11-25 13:20:10 +02:00
agrynco 9e287c3a1d Add persistent recent folders to source menus
Refs #88
2026-11-25 13:19:55 +02:00
agrynco 5eda68a7a2 Merge pull request 'KSwitcher.Files: Add local path breadcrumbs and history' (#140) from codex/issue-87-local-path-navigation into prerelease
Refs #87
2026-11-25 13:14:32 +02:00
agrynco 6cbb0639a1 Add local path breadcrumbs and panel history
Refs #87
2026-11-25 13:14:18 +02:00
agrynco 2a6f9c7841 Merge pull request 'KSwitcher.Files: Enable operations in file search results' (#139) from codex/issue-86-search-operations into prerelease
Refs #86
2026-11-25 12:59:21 +02:00
agrynco 94b22fdd52 Enable file operations in search results
Refs #86
2026-11-25 12:59:04 +02:00
agrynco 0d293429df Merge pull request 'KSwitcher.Files: Add recursive local file search' (#138) from codex/issue-85-find-files into prerelease
Refs #85
2026-11-25 11:54:00 +02:00
agrynco 83a099ab25 Add recursive local file search to KSwitcher Files
Refs #85
2026-11-25 11:53:14 +02:00
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
180 changed files with 32656 additions and 3856 deletions

No files matched your search

+115 -11
View File
@@ -1,18 +1,22 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.120 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.8.1 LANGUAGES C 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 src/files_text_window.cpp
src/files_text_document.cpp src/files_text_language.cpp resources/files.rc)
src/files_text_document.cpp src/files_text_language.cpp src/files_archive.cpp src/files_git_changes.cpp
src/files_mcp.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)
include(cmake/FilesArchiveLibraries.cmake)
include(cmake/FilesSshLibrary.cmake)
include(cmake/FilesImageLibraries.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)
@@ -26,8 +30,13 @@ add_custom_target(check-files-search-arrow
-Executable "$<TARGET_FILE:KSwitcherFiles>"
DEPENDS KSwitcherFiles
VERBATIM)
add_custom_target(check-files-quick-view
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_quick_view.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 wininet)
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet netapi32 mpr userenv KSwitcherFilesImage libssh2::libssh2)
if(MSVC)
target_compile_options(KSwitcherFiles PRIVATE /utf-8)
else()
@@ -47,13 +56,34 @@ foreach(utilityTarget StayHere StayHereTest)
target_link_options(${utilityTarget} PRIVATE -municode -static -static-libgcc -static-libstdc++)
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)
add_library(kscore src/lan_files.cpp src/lan_client_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)
set_property(SOURCE resources/app.rc APPEND PROPERTY OBJECT_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/resources/update.ps1")
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"
"${CMAKE_CURRENT_SOURCE_DIR}/Release/README.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)
@@ -84,7 +114,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)
@@ -128,6 +158,28 @@ if(NOT MSVC)
target_link_options(KSwitcherFilesTextTests PRIVATE -static)
endif()
add_test(NAME files-text-document COMMAND KSwitcherFilesTextTests)
add_executable(KSwitcherFilesArchiveTests tests/files_archive.cpp src/files_archive.cpp)
target_include_directories(KSwitcherFilesArchiveTests PRIVATE src)
target_compile_definitions(KSwitcherFilesArchiveTests PRIVATE NOMINMAX)
target_link_libraries(KSwitcherFilesArchiveTests PRIVATE KSwitcherArchive ole32)
if(MSVC)
set_property(TARGET KSwitcherFilesArchiveTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
target_compile_options(KSwitcherFilesArchiveTests PRIVATE /utf-8)
elseif(MINGW)
target_link_options(KSwitcherFilesArchiveTests PRIVATE -static)
endif()
add_test(NAME files-archive COMMAND KSwitcherFilesArchiveTests)
add_executable(KSwitcherFilesImageTests tests/files_image.cpp)
target_include_directories(KSwitcherFilesImageTests PRIVATE src)
target_compile_definitions(KSwitcherFilesImageTests PRIVATE NOMINMAX)
target_link_libraries(KSwitcherFilesImageTests PRIVATE KSwitcherFilesImage webp)
if(MSVC)
set_property(TARGET KSwitcherFilesImageTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
target_compile_options(KSwitcherFilesImageTests PRIVATE /utf-8)
elseif(MINGW)
target_link_options(KSwitcherFilesImageTests PRIVATE -static)
endif()
add_test(NAME files-image COMMAND KSwitcherFilesImageTests)
add_executable(KSwitcherFilesModalTests tests/files_modal_dialog.cpp)
target_include_directories(KSwitcherFilesModalTests PRIVATE src)
target_link_libraries(KSwitcherFilesModalTests PRIVATE user32 comctl32)
@@ -135,6 +187,16 @@ if(NOT MSVC)
target_link_options(KSwitcherFilesModalTests PRIVATE -static)
endif()
add_test(NAME files-modal-dialog COMMAND KSwitcherFilesModalTests)
add_executable(KSwitcherFilesMcpTests tests/files_mcp.cpp src/files_mcp.cpp)
target_include_directories(KSwitcherFilesMcpTests PRIVATE src)
target_link_libraries(KSwitcherFilesMcpTests PRIVATE kscore)
if(MSVC)
set_property(TARGET KSwitcherFilesMcpTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
else()
target_link_options(KSwitcherFilesMcpTests PRIVATE -static)
endif()
add_test(NAME files-mcp COMMAND KSwitcherFilesMcpTests)
set_tests_properties(files-mcp PROPERTIES TIMEOUT 30)
add_executable(KSwitcherLanTests tests/lan.cpp)
target_link_libraries(KSwitcherLanTests PRIVATE kscore)
if(MSVC)
@@ -143,6 +205,13 @@ 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)
@@ -166,6 +235,21 @@ add_test(NAME files-comparison-splitter
-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)
add_test(NAME files-smb-password
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_smb_password.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-smb-password PROPERTIES RUN_SERIAL TRUE TIMEOUT 30)
add_test(NAME files-recent-folders-panel
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_recent_folders_panel.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-recent-folders-panel PROPERTIES RUN_SERIAL TRUE TIMEOUT 35)
add_test(NAME files-space-analyzer-layout
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_space_analyzer_layout.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>")
set_tests_properties(files-space-analyzer-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 25)
find_program(KSWITCHER_NODE NAMES node)
if(KSWITCHER_NODE)
add_test(NAME files-terminal-enter
@@ -178,7 +262,7 @@ if(KSWITCHER_NODE)
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)
target_link_libraries(KSwitcherFilesMarkdownLanFixture PRIVATE kscore KSwitcherFilesText KSwitcherFilesImage)
add_dependencies(KSwitcherFilesMarkdownLanFixture KSwitcherTerminalAssets)
if(MSVC)
set_property(TARGET KSwitcherFilesMarkdownLanFixture PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
@@ -211,6 +295,7 @@ else()
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)
@@ -268,12 +353,20 @@ 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}")
install(TARGETS KSwitcher KSwitcherConfig KSwitcherScreenshot KSwitcherFiles RUNTIME DESTINATION .)
install(FILES LICENSE vendor/json-LICENSE.txt DESTINATION .)
install(FILES LICENSE vendor/json-LICENSE.txt resources/files-archive-license.txt resources/files-image-license.txt resources/files-sftp-license.txt DESTINATION .)
add_custom_command(TARGET KSwitcher POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/dictionaries" "$<TARGET_FILE_DIR:KSwitcher>/dictionaries")
install(DIRECTORY dictionaries DESTINATION .)
@@ -295,3 +388,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)
+372 -27
View File
@@ -42,6 +42,13 @@ Warning і початковий фокус на No.
Назви файлів і папок передаються в UTF-8. Для старого сервера, який
використовує системну кодову сторінку Windows, увімкни в профілі
**Use Windows encoding for file names** і підключися знову.
Після закриття Files окремо для кожної FTP-панелі зберігаються профіль,
каталог і рядок курсора. При наступному запуску Files відкриває цей каталог
і вибирає попередній рядок, якщо він ще існує. Коли каталог недоступний,
панель показує попередню локальну папку й причину помилки. **Ctrl+R**
повторює підключення. Натискання рядка стану відкриває повну причину
помилки й підтвердження повторної спроби. Вибір іншого джерела скасовує
відновлення.
- F5 копіює поточний або позначені файли й папки між локальною та
підключеною FTP-панелями в обидва боки. Призначенням є каталог іншої
панелі. Для одного елемента можна вказати ім’я копії в цьому каталозі.
@@ -57,20 +64,90 @@ Warning і початковий фокус на No.
підтвердження й видаляє вибрані елементи з FTP-сервера без кошика.
Для непорожньої папки Files окремо підтверджує видалення її вмісту.
- **SFTP** у меню джерел обох панелей відкриває збережені SSH-підключення.
Shift+F4 додає профіль, F4 редагує, Enter підключається. Укажи ім’я
користувача, хост, порт (типово 22) та пароль або повний шлях до ключа.
Поле пароля приймає кодову фразу для ключа. Windows DPAPI захищає
збережений пароль або кодову фразу. Для ключа користувача підходить
незашифрований RSA PEM або ECDSA OpenSSH із файлом .pub поруч.
ECDSA OpenSSH підтримує кодову фразу. Ключ залишається у вказаному файлі.
- У **Test connection** звір SHA‑256-відбиток ключа хоста з адміністратором
сервера та підтвердь довіру. Після цього Files перевіряє вхід. **Save**
зберігає профіль і підтверджений відбиток. Якщо відбиток змінюється,
Files блокує підключення до передачі пароля або підпису.
Для запланованої заміни ключа використовуй **Forget host key**,
а тоді **Test connection** зі звіркою нового відбитка.
- **Jump via** у SFTP-профілі вибирає попередній збережений SSH-профіль
у маршруті. **Direct** підключається напряму. Профіль-посередник може
мати власний **Jump via**. Кожен хост має окремий довірений ключ і
перевіряється до входу. Маршрут підтримує до восьми хостів і перевіряється
на цикли під час збереження. Профіль без доступу до SFTP можна
використовувати для пересилання через SSH.
- На підключеній SFTP-панелі Ctrl+O відкриває інтерактивну SSH-сесію.
Enter після введення команди запускає ту саму сесію з командного рядка.
Після `cd` успішно відкритий каталог відображається в панелі.
Зміна каталогу в панелі також оновлює робочу папку сесії.
Поки команда працює, термінал приймає її інтерактивне введення, зокрема
Ctrl+C. При переході до іншої панелі чи джерела сесія від'єднується.
Для синхронізації потрібні POSIX-оболонка й утиліта `base64` на сервері.
Оболонка та SFTP мають бачити однакові абсолютні шляхи.
- **SFTP server for sudo** у профілі приймає абсолютний шлях до
серверного OpenSSH `sftp-server`. Після відмови в доступі Viewer і
Hex Viewer пропонують один повтор через `sudo` в режимі тільки читання.
F2 в Editor після відмови в доступі до запису показує окремий запит.
Відмова або Esc під час привілейованого запису залишає чернетку в Editor,
якщо заміна файла ще не завершилась. Успішна заміна зберігає POSIX-власника,
групу та біти режиму доступу.
- Серверний адміністратор має окремо дозволити потрібний варіант команди
`sudo -n` для цього облікового запису. Перегляд використовує
`sftp-server -R`, а збереження використовує `sftp-server` без цього
прапорця. Files закриває привілейоване з'єднання після операції, розриву
або тайм-ауту мережевого запиту. Пароль sudo не запитується.
- Для SFTP використовуються ключі хоста ECDSA або RSA з підписом SHA‑2.
F3 і F4 відкривають Viewer та Editor. F2 в Editor перевіряє розмір і час
зміни віддаленого файла перед збереженням. F5 копіює між локальною
та SFTP-панеллю в обидва боки зі спільним прогресом, скасуванням і
підтвердженням конфліктів. Для заміни існуючого файла сервер має
підтримувати атомарне перейменування OpenSSH. Якщо сервер відмовляє
в заміні, Files показує причину й зберігає попередній файл.
- **SMB** у меню джерел показує збережені підключення у вибраній панелі.
**Shift+F4** додає профіль із сервером або повним UNC-шляхом.
**F4** редагує профіль, **F8** запитує підтвердження видалення.
**Enter** або подвійний клік відкриває профіль. Сервер показує видимі
дискові шари в тій самій панелі, а шар або профіль із повним UNC-шляхом
відкриває папку. Відомий прихований шар можна додати як повний UNC-шлях.
**Esc** або рядок `..` повертає зі списку шарів до профілів.
**Esc** зі списку профілів повертає попередню папку.
- Для SMB діють дозволи Windows. **Sign in** у контекстному меню профілю використовує вказаний
обліковий запис. Прапорець **Remember in Windows Credential Manager**
типово вимкнений. Коли його ввімкнено, після успішного підключення Windows
зберігає облікові дані для цього профілю. **Remove** видаляє профіль і
його збережені облікові дані після підтвердження.
- Якщо SMB недоступний, повідомлення показує причину й залишає список
підключень відкритим. **Open** повторює спробу. Коли Windows повідомляє
про наявний сеанс до цього сервера з іншим записом, Files пропонує
вибрати той запис або завершити попередній сеанс у Windows.
- **F9 → Commands → Compare files** порівнює два позначені текстові файли
активної панелі або по одному файлу з кожної панелі. Якщо в панелі немає
позначок, береться файл під курсором. Підтримуються локальні, LAN- та
FTP-файли. Файли показуються поруч із синхронною прокруткою, номерами
рядків і підсвічуванням вставок, видалень і замін. У замінених рядках
виділяється змінений фрагмент. **Previous** (F7) і **Next** (F8)
переходять між блоками змін. Подвійний клік відкриває повний текст пари рядків.
FTP- та SFTP-файли. Файли показуються поруч із синхронною прокруткою, номерами
рядків і підсвічуванням вставок, видалень і замін. **Unified** перемикає
на єдину колонку з номерами рядків обох файлів, видаленнями зі знаком −
і вставками зі знаком +. Перемикання зберігає поточний блок.
**Fold unchanged** згортає довгі незмінені ділянки до рядка з лічильником
і залишає до трьох рядків контексту перед і після кожного блока.
У замінених рядках виділяється змінений фрагмент. **Previous** (F7) і
**Next** (F8) переходять між блоками змін в обох поданнях.
Подвійний клік відкриває повний текст пари рядків.
Лічильник, навігація й перемикач пробілів розміщені в одному компактному
рядку над заголовками файлів. Вікно закривається системним хрестиком або Esc.
Вікно має системну рамку зі зміною розміру й нативний тулбар Windows
зі стрілками переходу, розділювачами та кнопкою-перемикачем пробілів.
Текст файлів і порожня область під ним мають білий фон, рядки
зі змінами виділяються кольором. Область порівняння займає всю ширину вікна.
Центральний розділювач можна перетягнути мишею. Під час зміни розміру
У поданні поруч центральний розділювач можна перетягнути мишею. Під час зміни розміру
вікна пропорція колонок зберігається.
Ctrl+колесо змінює масштаб тексту в поточному вікні.
Порівняння відкривається в окремому вікні із власною іконкою та кнопкою
@@ -79,18 +156,25 @@ Warning і початковий фокус на No.
Shift+F11 відкриває порівняння. Комбінацію можна змінити в тому ж розділі,
і меню Commands показує поточне призначення.
Рядки зіставляються за вмістом. Зміни лише у відступах і кінцевих пробілах
типово пропускаються. Перемикач **Show whitespace changes** показує їх.
типово пропускаються. Перемикач **Show whitespace changes** показує їх
в обох поданнях і враховує під час згортання.
Вставлені й видалені порожні рядки враховуються завжди.
**Apply to left/right** копіює виділений блок у відповідну сторону.
Порівняння перераховується, а змінену сторону позначає зірочка.
**Undo** або **Ctrl+Z** повертає останню незаписану дію.
**Save left/right** зберігає відповідну сторону, **Ctrl+S** зберігає обидві.
Зовнішня зміна цільового файла зупиняє запис і залишає правки для перегляду.
Закриття зі змінами пропонує Save, Discard або Cancel.
Кнопка розгортання в системному заголовку збільшує вікно порівняння
до робочої області екрана. Повторне натискання відновлює попередній розмір.
Вікно працює в режимі перегляду. Підтримуються UTF-8 і UTF-16 з BOM,
до 2 МіБ і 100 000 рядків на файл. Стилі переносу рядків порівнюються
як рівнозначні.
Підтримуються UTF-8 і UTF-16 з BOM, до 2 МіБ і 100 000 рядків на файл.
Стилі переносу рядків порівнюються як рівнозначні. Під час запису
зберігаються кодування, BOM і наявні кінці рядків цільового файла.
- У меню Files і його списках, що випадають, стрілки вгору й вниз
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
У меню джерел горизонтальна лінія відділяє FTP від локальних дисків,
а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP.
а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP, SFTP і SMB.
Літера відкриває локальний диск, цифра 1 відкриває FTP. Для LAN-дисків
і Wake меню показує доступні цифри 2–9 і 0. Призначена цифра зберігається
до закриття меню, навіть коли оновлюється список LAN.
@@ -127,8 +211,12 @@ Warning і початковий фокус на No.
виконує команду одразу. Коли рядок
порожній, Enter відкриває поточний елемент. Якщо панелі приховано,
Enter передає порожній рядок у термінал.
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
командного рядка й виконують відповідну дію за тими самими правилами.
У повноекранному терміналі (Ctrl+O) команда редагується в промпті
під виводом. Клік у терміналі повертає курсор у промпт. Стрілки вгору й
вниз без відкритого списку підказок переглядають спільну історію, а після
останньої команди вниз повертає чернетку. Підказки відкриваються біля
курсора. Ctrl+C перериває поточну команду, а за виділеного тексту виводу
копіює виділення. Escape з порожнім промптом також перериває команду.
Локальна команда запускається в папці активної панелі, яку показано
перед командним рядком. Після перемикання панелі або переходу до іншої
папки наступна команда використовує нову папку навіть у вже відкритому
@@ -167,6 +255,20 @@ Warning і початковий фокус на No.
останніх команд з історії, які починаються з набраного тексту.
Вибір підставляє всю команду. Підказки з історії доступні й у LAN-панелі.
- Правий клік по локальному файлу чи папці відкриває системне контекстне
меню Windows Shell. Правий клік по вільній області відкриває меню
поточної папки. Клавіша Context Menu або Shift+F10 використовує поточний
рядок. Команда з меню оновлює панель і зберігає папку, курсор та
актуальні позначки. Для LAN, FTP, SFTP, UNC та архівів контекстне меню
показує доступні команди Files.
- **Ctrl+A** або **F9 → Files → Properties** показує властивості поточного
файла чи папки. У локальній панелі можна змінити прапорці **Read-only**,
**Hidden**, **System**, **Archive** та **Not indexed**. **Save** застосовує
лише змінені прапорці й перечитує панель. Помилка Windows з’являється
окремим повідомленням. Прапорці папки застосовуються лише до самої папки.
У LAN, FTP, SFTP, UNC та архіві команда **Properties** також є в
контекстному меню й показує доступні метадані без редагування.
Для SFTP власник відображається як числовий UID, якщо сервер його надає.
- **F8 Delete** у нижньому рядку клавіш викликає той самий діалог видалення,
що й клавіша F8.
- У нижньому рядку, як у FAR, позначення клавіш сірі на чорному тлі,
@@ -204,6 +306,17 @@ Warning і початковий фокус на No.
Незбережені зміни у примусово закритих вікнах втрачаються.
Закриття процесів і результат записуються до `kswitcher.log`.
- У файловій панелі Ctrl+C копіює позначені або поточний локальний
елемент у файловий буфер Windows. Ctrl+V вставляє файли й папки в
поточний локальний каталог через звичайний діалог Copy і показує
конфлікти та прогрес. Клік або навігація у файловій панелі вибирають
файловий контекст. Клік у командному рядку або введення тексту
повертають текстовий контекст Ctrl+C / Ctrl+V.
- **Commands → Copy full path** або **Ctrl+Shift+C** копіює повний шлях
файла чи папки під курсором як текст. У LAN- і FTP-панелях текст включає
адресу віддаленого джерела. Для рядка `..` команда не змінює буфер.
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
курсора командного рядка або замінює виділення. Подвійні лапки додаються
лише до шляхів із пробілами. На рядку `..` вставляється шлях папки,
@@ -283,7 +396,7 @@ Warning і початковий фокус на No.
- 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 або клік у Files поза попапом закриває його й повертає фокус до панелі. Commands → Folder shortcuts дає вибрати зайняту цифру й відкрити той самий попап навіть для єдиного запису.
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F12 зарезервовані для інших режимів панелей. Brief і Wide також доступні в меню Left/Right та Options.
- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F9 керують сортуванням і фільтром активної панелі. Ctrl+F10 перемикає List і Tree. Ctrl+F11 перемикає фоновий підрахунок розмірів папок. Brief, Wide, Medium і Full доступні в меню Left/Right та Options → Panel layout.
## Налаштування Files
@@ -300,8 +413,18 @@ Warning і початковий фокус на No.
При повторному відкритті Files пропонує перейти до вже
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
Помилка збереження залишає відкритим редактор зі змінами.
Viewer показує збережену версію, а чернетка зберігається в поточному
вікні з позначкою Draft retained. Повторне F6 повертає правки, сторінку,
виділення й прокрутку.
Для нового файла Viewer показує порожній документ. Закриття вікна
з чернеткою в обох режимах пропонує Save, Discard або Cancel.
- **Shift+F3** або **Commands → View as hex** відкриває файл у Hex Viewer.
**F4** у Viewer перемикає текстовий або форматований перегляд і Hex.
Hex показує 64-бітну адресу, 16 вихідних байтів у рядку й ASCII.
Нульові й недруковані байти видно в hex, а в ASCII їх позначає крапка.
Блоки по 64 КіБ перемикаються через Ctrl+Page Up, Ctrl+Page Down або F5.
Esc повертає до попереднього режиму Viewer або, якщо файл відкрито
напряму в Hex, до файлової панелі.
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному
порядку. Коли відкрито лише Files, активна панель не змінюється.
@@ -331,8 +454,10 @@ Warning і початковий фокус на No.
перерендерюється зі збереженням позиції прокрутки.
Вебпосилання HTTP і HTTPS відкриваються в системному браузері.
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
8 МіБ, F3 відкриває текстовий перегляд.
кліку. Mermaid працює офлайн і завантажується лише для документів із
діаграмами Mermaid. Якщо WebView2 не завершує запуск, Files один раз
повторює спробу в тому самому вікні. Якщо форматований перегляд недоступний
або файл більший за 8 МіБ, F3 відкриває текстовий перегляд.
- F3 у фоні підраховує сумарний розмір файлів у папці та її підпапках.
На рядку `..` F3 рахує всі папки поточного списку, а за наявності
позначених папок в інших рядках рахує позначені папки. Без позначок
@@ -377,6 +502,15 @@ Warning і початковий фокус на No.
Ctrl+Shift+Home/End відкривають першу й останню. Ctrl+F шукає в поточній
сторінці, F3 повторює пошук. Ctrl+A виділяє поточну сторінку.
Історія Undo/Redo діє в межах відкритої сторінки.
- **Ctrl+D** або **Navigate → Add bookmark** у Viewer додає закладку
на рядок локального файла. Номер рахується від початку файла, а назва
необов’язкова. У Markdown номер можна вказати за вихідним текстом.
**Navigate → Bookmarks in this file** і **All bookmarks** відкривають
відповідні списки. **Commands → Viewer bookmarks** у панелях працює,
навіть коли Viewer закрито. Списки зберігаються після перезапуску.
Open переходить до рядка, для Markdown у вихідному тексті. Rename
змінює назву, Remove видаляє закладку. Якщо файл або рядок недоступний,
Files показує повідомлення.
- Початкова сторінка займає близько 1 МіБ файла. Для вставок і редагування
сторінка може вирости до 8 МіБ у UTF-8. Зміни інших сторінок тимчасово
зберігаються на диску. F2 або Ctrl+S потоково записують нову копію в
@@ -427,6 +561,67 @@ Warning і початковий фокус на No.
## Панелі
- **F9 → Commands → Find files** або **Alt+F7** запускає фоновий пошук
файлів у поточній папці та її підпапках. Підтримуються локальні папки,
FTP, SFTP і KSwitcher LAN. Поле приймає повне ім’я або маску без
урахування регістру. `*` відповідає довільній
послідовності символів, `?` — одному символу. Приховані та системні
елементи можна включити прапорцем. У FTP і SFTP це також стосується
імен із крапкою на початку. Пошук не обходить junction та інші посилання
на каталоги, які джерело позначає як посилання. Esc зупиняє обхід.
При скасуванні або втраті з’єднання знайдені файли залишаються в панелі.
Заголовок віддалених результатів показує джерело і початкову папку,
а рядки показують відносний шлях до кожного файла.
Enter або подвійний клік відкриває папку й ставить курсор на файл.
Esc у результатах повертає вихідну папку, курсор і позначки.
У результатах F3/F4 відкривають файл, а F5/F6 працюють із позначеними
або поточним файлом. F5 використовує папку іншої панелі як призначення.
У FTP і SFTP F6 перейменовує один результат у його власній папці.
Меню Files і нижній рядок клавіш враховують джерело, виділення та
можливість копіювання в іншу панель. F8 і Shift+Delete використовують звичайні підтвердження.
Успішно перейменовані, переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук
з тією самою маскою й видимістю прихованих файлів.
- **Left/Right → Tree view** або Ctrl+F10 перемикає вигляд відповідної
панелі незалежно від Brief і Wide. Enter, подвійний клік чи стрілка біля
папки розкриває або згортає гілку. Стрілки вправо й вліво працюють із
гілкою та її батьківською папкою. Вміст гілки читається у фоні під час
розкриття. Позначки згорнутих гілок залишаються доступними для F5, F6 і F8.
Якщо позначено папку та її вміст, команда обробляє їх одним деревом.
Повернення до List відкриває батьківську папку поточного елемента.
- **Background folder sizes** або Ctrl+F11 вмикає вимірювання видимих папок
у фоні для відповідної панелі. Під час оновлення попереднє число лишається
поруч із символом … . Знак + позначає частковий розмір. Error з’являється,
коли вимірювання недоступне. Якщо попереднє число є, позначка ! відрізняє
його від свіжого результату.
- **Commands → Space Analyzer** показує місткість і вільне місце за даними
Windows перед скануванням. Volume вибирає корінь тому, Folder повертає
поточну локальну папку, Start запускає фоновий аналіз тим самим обходом,
що й підрахунок розмірів F3. Посилання на каталоги всередині області
сканування позначаються як link. Stop залишає часткові результати, а
Rescan повторює аналіз із початку.
- Дерево показує логічний розмір, зайняті байти та частку логічного розміру
від батьківської папки. Знак + позначає частковий підрахунок. Зайняті байти
підсумовуються за файловими записами, включно з окремими іменами для
жорстких посилань. Службові дані файлової системи в цей підсумок не входять.
Відсутні дані про зайняті байти позначаються в рядку стану.
- Treemap показує дочірні елементи вибраної папки прямокутниками,
пропорційними до їхнього логічного розміру. Дрібні елементи доступні в
дереві. Клік по плитці відкриває точний елемент у сусідній панелі. Стрілки
переводять фокус між плитками, Enter відкриває плитку у фокусі.
- Sunburst показує до трьох рівнів вкладеності секторами за логічним
розміром. Клік по сектору та Enter у відповідному рядку списку ведуть
до одного елемента. Обраний рядок підсвічує відповідний сектор.
- Під час аналізу всього NTFS-тому Files використовує індекс MFT за
наявності доступу Windows. Звичайний обхід працює без такого доступу.
Обидва режими перераховують доступні записи каталогів, ураховують
жорсткі посилання за їхніми іменами та позначають недоступні гілки.
- View відкриває вибраний файл у спільному переглядачі Files. Show in
other panel відкриває вибрану папку або ставить курсор на файл у сусідній
панелі. Команди роботи з файлами доступні там. Якщо фільтр приховує
вибраний файл, панель показує його до зміни фільтра або переходу в іншу папку.
- Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів
у відкритих локальних папках. Фокус залишається там, де був, а курсор
лишається на поточному елементі, якщо той ще існує.
@@ -443,7 +638,7 @@ Warning і початковий фокус на No.
розміру, а список має однаковий внутрішній відступ зліва і справа.
- Тайм-аут запиту дисків відображається як Connection timed out. Якщо
ввімкнено Write log, Files записує помилки запитів пар і дисків в окремий
журнал `data/kswitcher-files.log`. Системні помилки містять код Windows.
журнал `data/kswitcher-files.log`. Системні помилки містять код Windows. Commands → Files log відкриває до 200 останніх записів поточного або попереднього журналу. Refresh оновлює список. Copy selected або Ctrl+C копіює дату й безпечний опис вибраного запису. Довільні текстові деталі приховано.
- Застосовані налаштування Files одразу підхоплюють інші відкриті вікна.
Apply зберігає поля, змінені в поточній чернетці. Якщо два вікна одночасно
@@ -454,6 +649,11 @@ Warning і початковий фокус на No.
- Меню Change drive показує літеру, тип, загальний обсяг і вільне місце. Відкриття меню запускає нове LAN-виявлення. Секція KSwitcher LAN показує збережені пари, зокрема офлайн. Після кожного відкриття меню асинхронно запитує диски й показує їх під назвою відповідного ПК. Поки триває запит, видно стан завантаження. Якщо запит не вдався, видно помилку. Повторне відкриття запускає новий запит. Кожна панель має власний диск і шлях, а в заголовку віддаленої панелі перед шляхом показано назву ПК.
- Список дисків і файлові операції використовують права облікового запису Windows, під яким працює віддалений KSwitcher. Достатньо спарювання й доступного TCP 45885, спільні папки налаштовувати не потрібно.
- Якщо читання LAN-папки переривається через мережеву помилку, Files
зберігає поточний список і до трьох разів повторює читання того самого
ПК, диска й каталогу. Після відновлення курсор залишається на наявному
рядку. Рядок стану показує причину збою й дію **Ctrl+R** для повторної
спроби. Перехід в інший каталог або джерело скасовує попередню спробу.
- F5, F6, F8 і Shift+Delete у віддалених панелях використовують спільні підтвердження, попередження й прогрес. F5/F6 працюють із файлами та деревами папок між локальними й віддаленими панелями, зокрема між двома різними ПК. Між шляхами одного віддаленого ПК вміст копіюється на ньому. F8 використовує кошик того ПК, на якому лежить файл.
- Після розриву з’єднання повтори F5 або F6 до того самого призначення. Віддалене копіювання відновлюється з підтвердженої позиції, якщо збережені байти відповідають початку вихідного файла. Підтверджене скасування видаляє частковий запис поточного файла. Завершені файли лишаються на місці. Наявний файл призначення замінюється після повного запису, а при переміщенні джерело видаляється після підтвердження запису призначення.
@@ -461,13 +661,76 @@ Warning і початковий фокус на No.
- Process multiple names дозволяє розділити імена комами або крапками з комою. Якщо такий символ є частиною імені, візьми ім’я в подвійні лапки. Діалог створює елементи у поточному каталозі, оновлює панель і ставить курсор на останній створений елемент. При помилці в середині списку вже створені елементи зберігаються.
- Після F5 або F6 успішно оброблені елементи коротко підсвічуються в панелі, що показує папку призначення. Підсвітка тексту відрізняється від курсора й не переносить фокус.
- У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size.
Розділювач Size проходить по одній вертикалі в заголовку та списку, а праві краї підпису й значень вирівняні.
- **Left/Right → Sort by** та Ctrl+F3, Ctrl+F4, Ctrl+F5 і Ctrl+F6 сортують
відповідну панель за іменем, розширенням, розміром і часом зміни.
Повторний вибір того самого стовпця змінює напрямок. Клік по заголовку
Wide виконує ту саму команду. Стрілка показує поточний напрямок.
Ctrl+F7 перемикає пріоритет папок. За вимкненого пріоритету папки й файли
сортуються разом. Рядок `..` лишається першим. Сортування, напрямок і
пріоритет папок зберігаються окремо для кожної панелі.
- Ctrl+F8 відкриває фільтр імен файлів без урахування регістру. Маска
підтримує `*` і `?` так само, як Find files. Папки залишаються доступними
для навігації. Порожнє поле або `*` вимикає фільтр. Позначки повертаються
для прихованих фільтром елементів, які ще є в поточній папці.
Ctrl+F9 перемикає показ прихованих та системних елементів окремо для
кожної панелі. Типово їх видно. Маска діє до закриття вікна.
- Brief показує імена. Medium додає Size. Wide показує також Ext і
Modified. Full додає Allocated, Links і Owner. Для локальних файлів
Allocated показує зайняте місце, Links — кількість жорстких посилань, а
Owner — власника за даними Windows. Для відсутніх метаданих показується —.
Modified показує місцеву дату. Сортування враховує повний час зміни.
- **Left/Right → Columns** налаштовує видимість стовпців і автоматичну
ширину для поточного режиму. Кожна панель зберігає свій режим і
налаштування Medium, Wide та Full. Автоматична ширина враховує вміст.
У вузькій панелі Name має пріоритет. Межі стовпців збігаються в заголовку
та списку. Стрілки, PgUp, PgDn, Home та End керують рядками в усіх режимах.
- Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель.
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
- Поточний шлях відображається по центру верхньої подвійної лінії панелі. Лінію видно з обох боків напису. Бірюзове тло активної панелі охоплює лише напис шляху з невеликими відступами. Довгий шлях скорочується в межах панелі.
- **Commands → Quick View** або **Ctrl+Q** вмикає перегляд локального
тексту, Markdown, HTML, зображень і двійкових файлів у сусідній панелі. Перегляд слідує за курсором активної
панелі. Повторна команда повертає сусідній каталог, курсор і позначки.
Під час перегляду файлові операції з призначенням у сусідній панелі
пропонують спершу закрити Quick View.
- Для локальних HTML-файлів до 8 МіБ Quick View відкриває **Rendered**. **Show Source** показує початковий текст, **Show Rendered** повертає форматований вигляд. F6 перемикає режими, коли фокус у самому перегляді. Quick View відображає статичне форматування й текст локально. Виконання скриптів, перехід за посиланнями і завантаження ресурсів заблоковані. Для зображень HTML показує їхній альтернативний текст. Більші HTML-файли починаються з першої сторінки вихідного тексту.
- Двійковий режим показує до 4096 початкових байтів, зі звичайними символами для друкованих байтів та позначенням `\xNN` для контрольних кодів. Рядки переносяться за шириною панелі. Shift+F3 відкриває повний Hex Viewer.
- **F3** відкриває PNG, JPEG, GIF, WebP і BMP у Viewer. Стрілки вліво й
вправо, Page Up і Page Down та кнопки Previous і Next гортають видимі
зображення в порядку вихідної панелі на момент відкриття Viewer.
- **Options → Viewer → Restore local Viewer and Editor windows after restart** зберігає відкриті локальні вікна під час закриття Files. Під час наступного запуску наявні документи відкриваються в попередньому режимі й положенні. Текст відновлює сторінку, курсор і прокручування, а зображення — масштаб. Відновлення читає збережені файли з диска.
- Локальний Viewer оновлює вміст після зміни файла. Активний Editor пропонує **Reload** або **Keep buffer**. Reload відкриває актуальну версію з диска, Keep buffer залишає відкриті редагування. Збереження після Keep buffer перевіряє початкову версію й зберігає чернетку, якщо файл уже змінився.
- **F4** на локальному PNG або JPEG відкриває редактор зображень. Rotate left і Rotate right повертають зображення на 90°. Crop приймає цілі координати X і Y від нуля, ширину й висоту в пікселях поточного зображення. Undo або Ctrl+Z послідовно скасовує зміни.
- **Save copy** або Ctrl+Shift+S створює окремий PNG чи JPEG. PNG зберігає прозорість, а JPEG використовує біле тло. **Replace** або Ctrl+S просить підтвердження й звіряє версію оригіналу. Якщо зовнішня зміна або помилка заважає запису, редактор зберігає чернетку. Закриття незбереженої чернетки просить підтвердження.
- У Viewer і Quick View коліщатко та кнопки − і + змінюють масштаб,
перетягування мишею панорамує збільшене зображення, Fit підганяє його
під область перегляду, а 100% повертає вихідний масштаб. Клавіші 0 і 1
виконують Fit і 100% у сфокусованому перегляді. GIF та анімований WebP
показують перший кадр. Пошкоджені та надто великі файли показують повідомлення.
- **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує
останні відвідані локальні, FTP, SFTP та LAN-папки у вибраній панелі.
**Enter** або подвійний клік відкриває папку в тій самій панелі.
**Delete** прибирає запис із недавніх. **Esc** повертає попередню папку.
Повторний візит підіймає один запис угору, порядок зберігається після
перезапуску. Віддалені записи містять шлях і ідентифікатор збереженого
FTP- чи SFTP-профілю або спареного ПК. Паролі зберігаються в захищених
налаштуваннях профілів.
- Кнопки ← та → переходять назад і вперед в історії відповідної панелі,
зокрема між локальними, FTP, SFTP та LAN-папками. Стрілка ↑, Alt+↑ та рядок `..`
відкривають безпосередню батьківську папку. На корені стрілка вимкнена,
а рядка немає. Alt+← і Alt+→ працюють з історією активної панелі.
- Сегменти шляху відкривають папки. Якщо шлях не вміщується, ліва
трикрапка відкриває прихованих предків, а права — приховані папки
попередньої гілки. Клік по поточній папці або кнопці редагування та Ctrl+L
відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях,
а Esc повертає до тих самих панелей і курсора.
- У заголовку FTP- чи SFTP-папки клік по назві профілю відкриває збережені
підключення. У LAN-папці клік по назві ПК відкриває спарені комп’ютери
та їхні диски. Поле шляху й доповнення працюють у поточному джерелі.
Для FTP абсолютний шлях починається з /.
## Спільні елементи діалогів
@@ -482,6 +745,13 @@ Warning і початковий фокус на No.
- При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання.
- Для власних діалогів і списків Far використовуй спільні метрики та малювання подвійної рамки. Еталон Delete задає 8 px від краю тла до першої лінії та 14 px від внутрішньої лінії до бічної межі вмісту при 96 DPI. Обидва відступи масштабуються за DPI. Вертикальний відступ враховує висоту заголовка та нижніх підказок. Діалоги й списки зберігають свою палітру та поведінку.
- Commands → Files MCP за замовчуванням зупинений. Start запускає MCP Streamable HTTP на `127.0.0.1` з випадковим портом. Клієнту потрібні Endpoint і `Authorization: Bearer <session token>`. Show token показує токен, Copy token копіює його. Stop і вихід із програми Files відкликають токен. Закриття діалогу залишає сервер активним, і меню показує Files MCP (running). Кожен старт створює новий токен.
- MCP має три інструменти для читання. `get_panels` повертає стан поточних локальних панелей, курсор і сторінку записів. `search_files` фільтрує назви або відносні шляхи поточного списку чи наявних результатів Find. `get_file_metadata` повертає кешовані атрибути, тип, розмір і час зміни для вже показаного елемента. Для продовження списку клієнт передає `nextOffset` як `offset`. Вміст файлів, віддалені панелі, архіви й операції запису не входять до цього API. Запити з браузерним Origin відхиляються.
- F1 відкриває вбудовану офлайн-довідку для панелі, вибраного пункту меню чи поточного діалогу. Пошук фільтрує теми за назвою й текстом. Esc закриває довідку та повертає фокус. У командному рядку з назвою команди F1 зберігає перехід до її довідки Windows. Загальна довідка також доступна через Commands → Help.
- Options → Import JSON / Export JSON переносить вибрані групи збережених параметрів Files. Окремо доступні кольори панелей і порівняння разом зі стилями файлів, режими й компонування панелей та іменовані схеми клавіш. Перед заміною відмінних схем з однаковою назвою Files запитує підтвердження. Імпорт спочатку оновлює чернетку Options. Apply або OK зберігає зміни, Cancel відкидає їх. Формат містить лише ці параметри. Невідомі поля і групи пропускаються.
- Commands → Keyboard shortcuts відкриває іменовані схеми для команд файлових панелей та історії команд. У схемі можна задати кілька клавіш, вибрати основну, вилучити прив’язку, скопіювати схему під новим іменем, перемкнути чи скинути її. OK зберігає активну схему. Меню показує всі прив’язки, нижній ряд і текстові підказки відображають основну. Діалог відхиляє дублікати в контекстах, що перетинаються, і клавіші, зайняті навігацією. Попередні прив’язки історії та порівняння завантажуються як схема Previous settings.
- Масштаб панелей, текстового Viewer, Editor, Markdown, термінала й порівняння зберігається окремо. У Commands є Panel appearance або Terminal appearance залежно від видимої області. Options у Viewer, Editor та Markdown і кнопка Appearance у порівнянні відкривають відповідну сторінку. Значення 100% використовує обраний базовий розмір шрифту.
- Viewer і Editor підтримують колірну схему System (Windows). У Appearance → System themes можна призначити окремі палітри світлому й темному режимам Windows, включно із власними схемами. Rename scheme змінює назву власної схеми у списку, Viewer, Editor і призначеннях світлого та темного режимів.
- 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. Розміри полів і кнопок враховують метрики цього шрифту.
@@ -493,12 +763,55 @@ Warning і початковий фокус на No.
діалог можна скасувати. Помилки шляху показує окремий червоний модальний діалог Far. Після його закриття фокус повертається до поля шляху.
- Помилки копіювання, переміщення й видалення показуються в червоному
модальному діалозі Far із причиною помилки та кнопкою OK.
- Якщо локальне перейменування або видалення заблоковане, кнопка Processes… відкриває
список процесів із назвою та PID. Перевірка папки включає вкладені елементи.
End process завершує вибраний процес після окремого підтвердження, після
чого список оновлюється. Якщо Windows обмежила доступ або перевірку
великої папки завершено частково, про це повідомляється в діалозі.
Операцію можна повторити після звільнення файла чи папки.
- **F9 → Commands → Processes** показує локальні процеси, PID, частку
загальної потужності CPU, робочий набір пам’яті та шлях виконуваного файла.
**Filter** шукає за іменем, шляхом або PID. **Sort** змінює порядок,
**Refresh** робить новий вимір. **Go to file** вибирає виконуваний файл
в активній панелі. **End process** завершує процес лише після підтвердження.
- **F9 → Files → Locking processes** перевіряє поточний локальний елемент або
позначені елементи. Кнопка **Processes…** у повідомленні про заблоковане
перейменування або видалення відкриває той самий список із фільтром за
вихідним шляхом. Для папки перевіряються також її вкладені елементи.
**Go to file** у цьому режимі відкриває виконуваний файл у другій панелі
зі збереженням вихідного файла в першій. Після завершення процесу список
перечитується. Якщо Windows обмежила доступ або перевірка великої папки
завершилася частково, діалог повідомляє про це.
- **F9 → Commands → Git Changes** відкриває зміни Git із кореня або
вкладеної папки локального worktree. Список окремо показує **Staged**,
**Unstaged** та **Untracked**, а сусідня панель відображає diff
вибраного рядка. **Filter** шукає за шляхом. **F3** відкриває поточний
робочий файл у Viewer, **F4** відкриває його в Editor, якщо файл існує.
**Ctrl+R** перечитує Git, **Esc** повертає обидві панелі. Для цього
режиму потрібен Git for Windows. Перегляд залишає Git index без змін.
- У Git Changes кнопка **History** або **F6** відкриває історію. **Branch**
вибирає локальну чи remote-tracking гілку для перегляду. Зірочка
позначає поточну гілку або detached HEAD. Вибір не змінює checkout.
Сусідня панель показує повідомлення коміту та змінені шляхи.
Для merge-коміту список шляхів відповідає різниці з першим батьком.
**More** або **F7** додає наступні 50 комітів, **Ctrl+R** перечитує гілки,
**F6** повертає до Git Changes, а **Esc** повертає до файлових панелей.
- У Git Changes **Stage** та **Unstage** діють на вибраний запис.
Unstage перейменування відновлює обидва індексні шляхи. Якщо шлях уже
має staged-версію, Stage запитує підтвердження заміни.
- **Commit** показує checkout-гілку й усі staged-шляхи, включно з
прихованими фільтром. Якщо гілка, HEAD або staged-вміст змінилися
після перегляду, Files зберігає повідомлення й вимагає нового перегляду.
Після коміту показує хеш і перечитує Git Changes. Для detached HEAD,
розв’язання конфліктів або продовження активної операції використовуй
Git у терміналі.
- Stage використовує clean-фільтри Git. Локальний Commit враховує
**commit.gpgSign** і налаштований засіб підписування. Git hooks для
цих операцій Files вимкнено. Для комітів із hooks або інтерактивним
підписуванням використовуй Git у терміналі.
- **F9 → Commands → Environment Variables** показує області **User**,
**System** і **Process**, джерело, сире та розгорнуте значення.
Process показує середовище поточного процесу Files лише для читання.
**Edit** зберігає тип реєстрового значення. **Copy to User** і
**Copy to System** переносять сире значення та його тип і запитують
підтвердження, якщо визначення існує. Якщо значення змінилося після
відкриття діалогу або Windows відмовила в доступі, Files показує причину.
Запущені сеанси PowerShell зберігають своє середовище. Після зміни
перезапусти Files, щоб вбудований PowerShell успадкував нові значення.
- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення.
- Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
@@ -506,6 +819,25 @@ Warning і початковий фокус на No.
- Розкриті списки й історія Far використовують спільний попап із бірюзовим тлом, світлою рамкою та чорним вибраним рядком. Попап прилягає до обох країв бірюзового поля, стрілка лишається праворуч за межами списку. Історія групується за датами. Довгі списки прокручуються, Enter вибирає рядок, Escape закриває список і повертає фокус до поля.
- Повторно використовуй спільне оформлення. Текст, дії та стан операції передавай із коду конкретної операції. Наприклад, Warning повертає відповідь і стан прапорця, а копіювання вирішує, чи застосувати відповідь до наступних конфліктів.
## Перетягування файлів
- Перетягування з Explorer або іншої локальної панелі відкриває діалог
Drop files із повним шляхом призначення та кнопками Copy, Move і Cancel.
Якщо курсор над папкою, призначенням є ця папка. В інших випадках
призначенням є поточна папка панелі. Cancel або Esc скасовує дію.
- Copy і Move відкривають наявний діалог операції з її параметрами,
перевіркою призначення, розв’язанням конфліктів і прогресом. Віддалені
панелі, результати пошуку й віртуальні елементи Explorer без локального
шляху не підтримують перетягування. Files повідомляє причину в рядку стану.
## Архіви ZIP і 7z
- Enter на локальному архіві відкриває його в поточній панелі. Заголовок панелі починається з Archive і містить ім’я архіву та шлях усередині нього. Enter відкриває папки всередині архіву, а рядок `..`, Alt+Up і Escape піднімають на один рівень. Вихід із кореня повертає курсор на архів.
- F3 відкриває текстовий файл у спільному переглядачі. F5 копіює позначені записи або поточний запис у локальну папку через спільні діалоги Copy, конфлікту та прогресу. F4, F6, F7 і F8 не змінюють вміст архіву.
- Небезпечні шляхи й посилання блокують читання архіву. Для зашифрованих записів та архівів із зашифрованими заголовками Files показує підказку про пароль.
- **Files → Pack files** або **Alt+F5** створює в поточній локальній папці архів із позначених елементів або з поточного елемента. Розширення `.zip` чи `.7z` визначає формат.
- **F5** з локальної панелі в панель архіву та **Ctrl+V** зі списком локальних файлів додають елементи до відкритої папки архіву. Діалог підтвердження попереджає про заміну файлів з однаковими іменами. Скасування або помилка зберігають попередній архів. Режим запису підтримує звичайні ZIP і 7z.
## Діалог Copy
- Вирівнюй підпис Existing files по вертикальному центру списку. Ширше поле списку починається ближче до підпису, а його правий край збігається з правим краєм поля імені.
@@ -521,6 +853,11 @@ Warning і початковий фокус на No.
- Секції поточного файла й загального прогресу мають однаковий вертикальний відступ від вмісту до верхньої та нижньої ліній. Cancel стоїть по центру спільної нижньої секції.
- Обидві шкали займають усю ширину вмісту. Відсотки показуються по центру шкали, а її висота враховує поточний шрифт.
- **Options** у Copy/Move задає маску імен файлів із символами `*` і `?`. Порожня маска або `*` копіює всі файли й порожні папки. З іншою маскою Files зберігає структуру папок із відповідними файлами. У Move файли поза маскою залишаються в джерелі.
- Додаткові папки вводяться абсолютними шляхами, по одному на рядок, на тому самому комп’ютері або підключенні, що й основне призначення. Однакові папки обробляються один раз. У Move джерело видаляється після успішного копіювання елемента в усі вибрані папки. У разі пропуску або збою вже записані копії зберігаються. Підсумок показує кількість повністю скопійованих елементів по всіх призначеннях і загальну кількість записаних файлів.
- **Preserve modification time** зберігає час зміни там, де ціль підтримує його встановлення. Збереження часу підтримують Windows і SFTP. FTP-призначення використовує час сервера. **Preserve Windows permissions** переносить DACL між файловими системами Windows, які підтримують цей тип прав. Наявні папки, у які додаються файли, зберігають власні права й час.
- Оцінка залишку часу в прогресі з’являється після кількох вимірювань швидкості. Довга пауза скидає оцінку. Скасування й конфлікти використовують спільні діалоги.
## Попередження про конфлікт
- Для однойменних файлів Warning показує точний розмір у байтах із розділенням тисяч і місцевий
@@ -538,6 +875,14 @@ Warning і початковий фокус на No.
- F8 переміщує підтверджені елементи в кошик Windows. Shift+Delete видаляє підтверджене дерево від вкладених елементів до батьківської папки. Прогрес і підсумок окремо показують успішні, пропущені й невдалі дії.
- Cancel і Esc у вікні прогресу відкривають спільне червоне підтвердження скасування. Yes зупиняє операцію, а No або Esc у підтвердженні повертає до прогресу. Початковий фокус стоїть на No.
## Обмін і компонування панелей
- **Commands → Swap panels** або **Ctrl+U** міняє панелі місцями. Активна панель, шлях, курсор, прокручування, позначки, поточний режим і Quick View переходять разом.
- **Options → File panel modes → Panel layout** містить незалежні параметри для правої кнопки, кнопок дисків і компактного компонування. За замовчуванням ці параметри вимкнені.
- **Mark items with the right mouse button** перемикає позначку рядка. **Shift+права кнопка**, **Shift+F10** і клавіша **Menu** відкривають контекстне меню. Права кнопка на порожньому місці також відкриває контекстне меню панелі.
- **Show drive buttons** додає наявні локальні диски над панелями. Кнопка відкриває корінь диска в активній панелі. Якщо всі диски не поміщаються, **…** відкриває Change drive.
- **Compact commander layout** скорочує проміжки між шляхом, рядками та станом, зберігаючи розмір шрифту, командний рядок і клавіші дій.
## Перевірка змін
Відкрий Copy і Warning в одній збірці та порівняй висоту нижніх секцій, центрування, повноту підписів і видимість фокуса. Перевір Tab, стрілки й Esc. Після узгодження нового правила онови відповідний розділ цього документа.
+100 -22
View File
@@ -7,21 +7,85 @@ 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 executable, confirm, and click **Save** in Settings.
A newly approved or previously enrolled executable can list pairs, browse
drives and download regular files. For each executable you can separately
enable **Allow write** for creating, editing, renaming, and copying, and
**Allow delete** for the recycle bin and permanent deletion. Move needs both
permissions. The paired computer's Windows access and file-sharing settings
still apply. KSwitcher retains the pairing credentials.
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 and choose **Remove**, or turn off an individual grant,
then click **Save** to revoke access. KSwitcher checks grants again during
streaming and before publication or source removal. Add an updated executable
again because approval covers its path and SHA-256 fingerprint.
### Local trusted-client protocol
The Windows pipe is `\\.\pipe\KSwitcher.LAN.Clients.v1.<session>` and accepts
one request per connection from the resident's user. Send a JSON object in an
unsigned 32-bit little-endian length frame (maximum 16 KiB for the request).
Replies have the same length prefix. After the last reply, send one raw
acknowledgement byte and close. An error reply is a JSON object containing
a string `error`. Existing `peers`, `drives`, `list` and `download` requests
retain their original reply formats.
- `capabilities` optionally takes a `peer`. It returns the broker `protocol`
(2), `hostRevision`, and boolean `write`, `delete`, `move`,
`revisionRead`, `onHostTransfer`, and `localEndpoint` fields. With no peer,
the fields describe the local broker and its grants. With a peer, the flags
also account for its supported protocol. A peer with revision 0 still
supports legacy browsing and downloading.
- `stat` takes `peer` and an absolute `path`. It returns Windows attributes,
byte `size` and `modified` (Windows FILETIME). Preserve 64-bit integers
without rounding. `readFile` takes the same arguments plus an optional
`expected` object with `size` and `modified`. It returns metadata followed
by raw frames up to 64 KiB and a zero-length frame. Require the declared
byte count and the zero-length frame before accepting the download.
- `writeFile` takes `peer`, `path`, and the incoming byte `size`. Omit
`expected` for an exclusive create. Include the original `size` and
`modified` in `expected` for an edit. After the `ready` JSON reply, send
raw frames up to 64 KiB followed by a zero-length frame. The final reply
contains the saved metadata or an error. The host stages bytes until
the upload is complete and checks the revision when publishing an edit.
- `mkdir`, `rename`, `recycle`, and `delete` take `peer` and `path`.
Rename also takes a single new `name` and fails if the destination exists.
Permanent deletion of nonempty directories requires `recursive: true`.
The recycle bin is subject to Windows availability on the paired host.
- `transfer` takes `source` and `target` objects with a `peer` and `path`
each, optional `move` (default false), and a `conflict` policy of `fail`
(default), `skip`, or `replace`. Replace merges directories and replaces
regular files after validating the destination revision. The broker
allows at most one local endpoint, represented by `"peer": null`. For a
local endpoint the client must open the pipe with Windows impersonation
enabled, and local files are accessed using the caller's token.
- Transfer replies are JSON progress frames containing `type: "progress"`,
`phase` (`copy` or `remove`), source `path`, byte `done` and `total` for the current file, and
`completed` and `skipped` item counts. Reply to each progress frame with
a JSON frame containing `continue: true` or `continue: false`. The
final frame has `type: "complete"` and counts, or an error. Transfers
on one paired computer use its own file service even across drives. The
local pipe exchanges only control and status for transfers.
- For a move, the copy phase finishes before source deletion begins.
Skipped items remain at the source. Cancellation or failure can leave
previously completed destination items. Failure during source cleanup
can leave a partially removed source tree. Unpublished file uploads are
discarded. File-tree transfer does not follow junctions or symbolic
links within the tree.
## 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,19 +101,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.
The computer list and pairing controls are on the left, the monitor grid and
input sharing are on the right, and file, log and help actions are below.
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
@@ -59,6 +125,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.
@@ -105,8 +177,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
+138 -45
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,
@@ -185,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
@@ -201,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
@@ -411,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
@@ -433,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**
@@ -461,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
@@ -473,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 підказки відкриваються біля текстового курсора. Якщо редактор не
надає його позицію, введіть повний тригер для розгортання сніпета.
@@ -491,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
@@ -516,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
@@ -538,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
@@ -564,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.
@@ -664,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.
@@ -678,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.
@@ -703,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
@@ -742,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
@@ -832,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
+183 -1
View File
@@ -1,5 +1,187 @@
# Latest Windows release
## v0.8.1 — 2026-11-26
- **SMB.** Saved connections and a server’s shares open in the selected Files panel. Press **Enter** to open a connection or share. **Esc** returns to the previous list or folder. Profile editing and sign-in use their existing dialogs.
- **Recent folders.** The selected panel shows recent local and remote folders. **Enter** opens the entry in that panel, **Delete** removes the history entry, and **Esc** restores the previous folder and cursor.
**Українською.**
- **SMB.** Збережені підключення та спільні ресурси сервера відкриваються у вибраній панелі Files. **Enter** відкриває підключення чи ресурс. **Esc** повертає до попереднього списку або папки. Для редагування профілю та входу використовуються окремі діалоги.
- **Recent folders.** Вибрана панель показує нещодавні локальні й віддалені папки. **Enter** відкриває запис у цій панелі, **Delete** прибирає його з історії, а **Esc** відновлює попередню папку й курсор.
## v0.8.0 — 2026-11-26
- **Files panels and search.** Find files recursively on local, FTP, SFTP and paired LAN panes. Work with results directly, navigate with breadcrumbs and history, recall recent folders, and configure sorting, filters, columns and panel layout. File clipboard and drag and drop integrate with Windows.
- **Storage and transfers.** Inspect folder sizes and disk usage with the tree, treemap and sunburst. Browse, extract, create and update ZIP and 7z archives. Copy and Move provide masks, multiple destinations and preservation options.
- **Viewing and editing.** Quick View supports text, Markdown, offline HTML, symbolic binary and images. Use Hex Viewer, line bookmarks, unified comparison, change-block application and Undo. Edit PNG/JPEG images with rotate and crop, and opt in to restoring local document windows after a restart.
- **Connections and Windows tools.** Browse saved FTP, SFTP and SMB connections, use the SSH terminal and jump hosts, inspect properties and locking processes, review and stage Git changes, commit the reviewed index, and inspect environment variables.
- **Customize and automate.** Use named keyboard schemes, separate area scales, Windows light and dark palettes, selective JSON settings transfer, offline F1 help, and the Files log. The optional loopback MCP exposes pane state, existing Find results and cached metadata with a per-session token.
**Українською.**
- **Панелі та пошук.** Рекурсивний пошук у локальних, FTP, SFTP і спарених LAN-панелях. Результати підтримують файлові операції. Доступні навігаційний шлях, історія, нещодавні папки, сортування, фільтри, колонки й налаштування панелей. Файловий буфер і перетягування працюють із Windows.
- **Сховище й перенесення.** Дерево, карта та сонячна діаграма показують використання диска. ZIP і 7z можна переглядати, розпаковувати, створювати й оновлювати. Копіювання й переміщення підтримують маски, кілька папок призначення та збереження атрибутів за вибором.
- **Перегляд і редагування.** Quick View підтримує текст, Markdown, офлайн-HTML, символьний перегляд бінарних даних і зображення. Доступні Hex Viewer, закладки рядків, об’єднане порівняння, застосування блоків змін і Undo. PNG/JPEG можна повертати й обрізати. Відновлення локальних вікон після перезапуску вмикається в Options.
- **Підключення та інструменти Windows.** Збережені підключення FTP, SFTP і SMB, SSH-термінал і проміжні вузли, властивості файлів, процеси, що їх блокують, Git Changes із підготовкою та комітом змін, перегляд і редагування змінних середовища.
- **Налаштування й автоматизація.** Іменовані схеми клавіш, окремий масштаб областей, світла й темна палітри Windows, вибіркове перенесення налаштувань через JSON, офлайн-довідка F1 і журнал Files. Опційний локальний MCP читає стан панелей, наявні результати Find і кешовані метадані за токеном сесії.
## 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.
@@ -542,6 +724,6 @@ Use **Test mouse buttons here** to check which events Windows delivers. Mouse pr
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 @@
53334ba83a44c69c3acd2aad297db177366fe553fae8813b88b81e0a215c860f KSwitcher-win-x64.zip
4f73fa962a4a84ebb7b564fdb5e8cac6baeeff460d3e7147f09d6ded62553021 KSwitcher-win-x64.zip
+80 -65
View File
@@ -1,166 +1,181 @@
{
"files": [
{
"size": 3193344,
"path": "KSwitcher.exe",
"sha256": "152b41278761439ce5ebe87bca3a4d8a96d89db82264ec0fbb2299e7c207dfb5",
"size": 2372096
"sha256": "ceaeff987356f31cc4e1773b41825fe8bc621d51abd9884964339457b724198f"
},
{
"size": 2892800,
"path": "KSwitcher.Config.exe",
"sha256": "3d44721ba688a6916e393d2b9d9291e38ee063795b54cdae8e78cfd621835619",
"size": 2369536
"sha256": "d2d8fabbe9758d6744b04014cddc96cd7c87710249e025594861ed7bec508b9b"
},
{
"size": 3193344,
"path": "KSwitcher.Screenshot.exe",
"sha256": "81d9fbb770e876937310a0b483e11bd96cdb9e20b0f6baf0fa9927f24965aeeb",
"size": 3348992
"sha256": "b2503e613fa203773a6ead05efaf4430fb297d642569ac64927a77acd78f53a8"
},
{
"size": 5977600,
"path": "KSwitcher.Files.exe",
"sha256": "04c9af5324144a46a5f3cc0d8f2c6912745f8bbad7fbef0576bd52c88b5c5e03",
"size": 4370944
"sha256": "047d8ba01a3a316ca53c609283dee2638474731390dee74427ea881cc71d3617"
},
{
"size": 194912,
"path": "WebView2Loader.dll",
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"size": 194912
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
},
{
"size": 1103,
"path": "terminal/addon-fit-LICENSE.txt",
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"size": 1103
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
},
{
"size": 1521,
"path": "terminal/addon-fit.js",
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"size": 1521
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
},
{
"size": 527,
"path": "terminal/index.html",
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"size": 527
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
},
{
"size": 1073,
"path": "terminal/markdown-it-LICENSE.txt",
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"size": 1073
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
},
{
"size": 100786,
"path": "terminal/markdown-it.js",
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"size": 100786
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
},
{
"size": 3800,
"path": "terminal/markdown.html",
"sha256": "8268f55e8642034efa5a762cbd65d02a1d416aea9e777e0fe30a7e916ae3ee79",
"size": 3635
"sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2"
},
{
"size": 18721,
"path": "terminal/markdown.js",
"sha256": "4c68dff619cf248f6bd32b09a45458675c22341892dc377204e46c2f4fd562f8",
"size": 16944
"sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96"
},
{
"size": 1089,
"path": "terminal/mermaid-LICENSE.txt",
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"size": 1089
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
},
{
"size": 5537838,
"path": "terminal/mermaid.js",
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"size": 5537838
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
},
{
"size": 6627,
"path": "terminal/terminal.js",
"sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b",
"size": 5065
"sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7"
},
{
"size": 1261,
"path": "terminal/xterm-LICENSE.txt",
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"size": 1261
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
},
{
"size": 7112,
"path": "terminal/xterm.css",
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"size": 7112
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
},
{
"size": 488663,
"path": "terminal/xterm.js",
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"size": 488663
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
},
{
"size": 4401,
"path": "LICENSE",
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"size": 4401
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
},
{
"size": 1096,
"path": "json-LICENSE.txt",
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"size": 1096
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
},
{
"size": 883,
"path": "files-text-license.txt",
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"size": 883
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
},
{
"size": 4990,
"path": "files-archive-license.txt",
"sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d"
},
{
"size": 3044,
"path": "files-image-license.txt",
"sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4"
},
{
"size": 2064,
"path": "files-sftp-license.txt",
"sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594"
},
{
"size": 105515,
"path": "README.md",
"sha256": "afc7e78c4c3600888f642692423cd993b4aa431dfa54f752c7ac394de18186c6",
"size": 95354
"sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01"
},
{
"size": 16722,
"path": "LAN-PREVIEW.md",
"sha256": "1233d6a0ed76564dd034f178a9f65db076244a819137f74dc9f2c27df9d3c930",
"size": 11577
"sha256": "917c2f41b3943647fdfafa911d93f72b8c6fb0d08592016ce1a698d256e038bb"
},
{
"size": 732485,
"path": "dictionaries/en.txt",
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"size": 732485
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
},
{
"size": 20566,
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"size": 20566
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
},
{
"size": 2265,
"path": "dictionaries/README.md",
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"size": 2265
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
},
{
"size": 1109134,
"path": "dictionaries/ru.txt",
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"size": 1109134
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
},
{
"size": 1280,
"path": "dictionaries/sources.json",
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"size": 1280
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
},
{
"size": 940799,
"path": "dictionaries/uk.txt",
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"size": 940799
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
},
{
"size": 993,
"path": "tools/README.txt",
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"size": 993
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
},
{
"size": 133120,
"path": "tools/StayHere.exe",
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
"size": 134656
"sha256": "98f657cdd3d5dec5db8b45760edc656e23c362edc9002b6828d2fe4c8b86073b"
},
{
"size": 2796,
"path": "tools/StayHere-README.md",
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"size": 2796
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
}
],
"schema": 1,
"version": "0.6.120"
"version": "0.8.1"
}
+37 -15
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,9 +54,6 @@ 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'
$filesBuild = Join-Path $outDir 'files-cmake'
& cmake -S $root -B $filesBuild -G Ninja "-DCMAKE_CXX_COMPILER=$compiler" -DCMAKE_BUILD_TYPE=MinSizeRel
if ($LASTEXITCODE) { throw 'File manager configuration failed' }
& 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
@@ -63,10 +67,22 @@ try {
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 build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherSettingsMergeTests.exe
& cmake --build $filesBuild --target KSwitcherFilesArchiveTests
if ($LASTEXITCODE) { throw 'Files archive test build failed' }
& (Join-Path $filesBuild 'KSwitcherFilesArchiveTests.exe')
if ($LASTEXITCODE) { throw 'Files archive tests failed' }
& cmake --build $filesBuild --target KSwitcherFilesImageTests
if ($LASTEXITCODE) { throw 'Files image test build failed' }
& (Join-Path $filesBuild 'KSwitcherFilesImageTests.exe')
if ($LASTEXITCODE) { throw 'Files image 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
@@ -95,7 +111,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' }
@@ -103,18 +119,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
@@ -135,7 +157,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')
@@ -161,14 +183,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' }
+22
View File
@@ -0,0 +1,22 @@
# Apply the exec-channel variant of SFTP initialization to the pinned library.
file(REAL_PATH ".." source_parent)
set(patch_file "${CMAKE_CURRENT_BINARY_DIR}/.kswitcher-sftp-command.patch")
configure_file("${PATCH}" "${patch_file}" @ONLY NEWLINE_STYLE LF)
set(patch_git "${CMAKE_COMMAND}" -E env "GIT_CEILING_DIRECTORIES=${source_parent}" "${GIT}")
execute_process(COMMAND ${patch_git} apply --unidiff-zero --check "${patch_file}"
RESULT_VARIABLE can_apply ERROR_QUIET)
if(can_apply EQUAL 0)
execute_process(COMMAND ${patch_git} apply --unidiff-zero "${patch_file}" COMMAND_ERROR_IS_FATAL ANY)
else()
execute_process(COMMAND ${patch_git} apply --unidiff-zero --reverse --check "${patch_file}"
RESULT_VARIABLE already_applied)
if(NOT already_applied EQUAL 0)
message(FATAL_ERROR "Could not apply the SFTP command patch")
endif()
endif()
file(REMOVE "${patch_file}")
file(STRINGS "include/libssh2_sftp.h" exec_api REGEX "^libssh2_sftp_init_command")
if(NOT exec_api)
message(FATAL_ERROR "The SFTP command API is missing after applying the patch")
endif()
+103
View File
@@ -0,0 +1,103 @@
include(ExternalProject)
# Keep these dependencies private to Files. Build codecs before configuring
# libarchive so its feature checks link the exact libraries that Files ships.
set(archive_deps "${CMAKE_CURRENT_BINARY_DIR}/files-archive")
if(CMAKE_CONFIGURATION_TYPES)
set(archive_configs ${CMAKE_CONFIGURATION_TYPES})
elseif(CMAKE_BUILD_TYPE)
set(archive_configs ${CMAKE_BUILD_TYPE})
else()
set(archive_configs Release)
endif()
add_library(KSwitcherArchive INTERFACE)
target_compile_definitions(KSwitcherArchive INTERFACE LIBARCHIVE_STATIC)
function(build_files_archive config)
set(archive_config "${archive_deps}/${config}")
if(config STREQUAL "Debug")
set(debug_suffix d)
set(runtime_suffix Debug)
endif()
set(archive_lib "${archive_config}/lib")
set(archive_include "${archive_config}/include")
set(archive_cmake_args
"-DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER}"
"-DCMAKE_BUILD_TYPE:STRING=${config}"
"-DCMAKE_TRY_COMPILE_CONFIGURATION:STRING=${config}"
"-DCMAKE_INSTALL_PREFIX:PATH=${archive_config}"
"-DCMAKE_INSTALL_LIBDIR:STRING=lib"
"-DCMAKE_INSTALL_INCLUDEDIR:STRING=include"
"-DCMAKE_MSVC_RUNTIME_LIBRARY:STRING=MultiThreaded${runtime_suffix}"
"-DCMAKE_POLICY_DEFAULT_CMP0091:STRING=NEW"
"-DBUILD_SHARED_LIBS:BOOL=OFF")
if(MSVC)
set(zlib_name libzs)
else()
set(zlib_name zs)
endif()
set(archive_zlib "${archive_lib}/${CMAKE_STATIC_LIBRARY_PREFIX}${zlib_name}${debug_suffix}${CMAKE_STATIC_LIBRARY_SUFFIX}")
set(archive_lzma "${archive_lib}/${CMAKE_STATIC_LIBRARY_PREFIX}lzma${CMAKE_STATIC_LIBRARY_SUFFIX}")
set(archive_archive "${archive_lib}/${CMAKE_STATIC_LIBRARY_PREFIX}archive${CMAKE_STATIC_LIBRARY_SUFFIX}")
function(files_archive_dependency name url checksum library)
ExternalProject_Add(${name}_${config}
PREFIX "${archive_config}/${name}"
BINARY_DIR "${archive_config}/build/${name}"
STAMP_DIR "${archive_config}/stamp/${name}"
CMAKE_GENERATOR_PLATFORM "${CMAKE_GENERATOR_PLATFORM}"
CMAKE_GENERATOR_TOOLSET "${CMAKE_GENERATOR_TOOLSET}"
URL "${url}"
URL_HASH "SHA256=${checksum}"
DOWNLOAD_EXTRACT_TIMESTAMP FALSE
CMAKE_ARGS ${archive_cmake_args} ${ARGN}
BUILD_COMMAND "${CMAKE_COMMAND}" --build <BINARY_DIR> --config "${config}"
INSTALL_COMMAND "${CMAKE_COMMAND}" --install <BINARY_DIR> --config "${config}"
BUILD_BYPRODUCTS "${library}"
EXCLUDE_FROM_ALL TRUE
LOG_CONFIGURE TRUE
LOG_BUILD TRUE
LOG_INSTALL TRUE
LOG_OUTPUT_ON_FAILURE TRUE)
endfunction()
files_archive_dependency(files_zlib
https://github.com/madler/zlib/releases/download/v1.4/zlib-1.4.tar.gz
02dd159783677a749c04adbdd02b55b8a2bcc7e054f51b76b549199a916ad584
"${archive_zlib}"
-DZLIB_BUILD_SHARED=OFF -DZLIB_BUILD_TESTING=OFF)
files_archive_dependency(files_xz
https://github.com/tukaani-project/xz/releases/download/v5.8.4/xz-5.8.4.tar.gz
0014c7886930454fe8bd4228665b51af55eeae560ea135c9c4cd33f55b2591d9
"${archive_lzma}"
-DBUILD_TESTING=OFF -DXZ_NLS=OFF -DXZ_TOOL_XZ=OFF -DXZ_TOOL_XZDEC=OFF
-DXZ_TOOL_LZMADEC=OFF -DXZ_TOOL_LZMAINFO=OFF -DXZ_TOOL_SCRIPTS=OFF)
files_archive_dependency(files_libarchive
https://github.com/libarchive/libarchive/releases/download/v3.8.11/libarchive-3.8.11.tar.gz
900fe9fc7237c2b04f090f3c3648de8fe597525771f5035016537ce2d667d12b
"${archive_archive}"
"-DZLIB_INCLUDE_DIR:PATH=${archive_include}" "-DZLIB_LIBRARY:FILEPATH=${archive_zlib}"
"-DLIBLZMA_INCLUDE_DIR:PATH=${archive_include}" "-DLIBLZMA_LIBRARY:FILEPATH=${archive_lzma}"
-DENABLE_TAR=OFF -DENABLE_CPIO=OFF -DENABLE_CAT=OFF -DENABLE_UNZIP=OFF
-DENABLE_TEST=OFF -DENABLE_WERROR=OFF -DENABLE_OPENSSL=OFF -DENABLE_MD=OFF
-DMSVC_USE_STATIC_CRT=ON
-DENABLE_LIBB2=OFF -DENABLE_LZ4=OFF -DENABLE_ZSTD=OFF -DENABLE_BZip2=OFF
-DENABLE_LIBXML2=OFF -DENABLE_EXPAT=OFF -DENABLE_WIN32_XMLLITE=OFF
-DENABLE_PCREPOSIX=OFF -DENABLE_PCRE2POSIX=OFF -DENABLE_ICONV=OFF)
add_dependencies(files_libarchive_${config} files_zlib_${config} files_xz_${config})
add_dependencies(KSwitcherArchive files_libarchive_${config})
if(CMAKE_CONFIGURATION_TYPES)
set(config_matches "$<CONFIG:${config}>")
else()
set(config_matches 1)
endif()
target_include_directories(KSwitcherArchive INTERFACE "$<${config_matches}:${archive_include}>")
target_link_libraries(KSwitcherArchive INTERFACE
"$<${config_matches}:${archive_archive};${archive_zlib};${archive_lzma}>")
endfunction()
foreach(config IN LISTS archive_configs)
build_files_archive("${config}")
endforeach()
target_link_libraries(KSwitcherArchive INTERFACE bcrypt)
target_link_libraries(KSwitcherFiles PRIVATE KSwitcherArchive)
+25
View File
@@ -0,0 +1,25 @@
include(FetchContent)
FetchContent_Declare(files_webp
URL https://storage.googleapis.com/downloads.webmproject.org/releases/webp/libwebp-1.6.0.tar.gz
URL_HASH SHA256=e4ab7009bf0629fd11982d4c2aa83964cf244cffba7347ecd39019a9e38c4564
DOWNLOAD_EXTRACT_TIMESTAMP FALSE
SOURCE_SUBDIR kswitcher-download-only)
FetchContent_MakeAvailable(files_webp)
function(build_files_webp)
set(BUILD_SHARED_LIBS OFF)
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
foreach(component IN ITEMS ANIM_UTILS CWEBP DWEBP GIF2WEBP IMG2WEBP VWEBP WEBPINFO LIBWEBPMUX WEBPMUX EXTRAS)
set(WEBP_BUILD_${component} OFF)
endforeach()
add_subdirectory("${files_webp_SOURCE_DIR}" "${files_webp_BINARY_DIR}" EXCLUDE_FROM_ALL)
endfunction()
build_files_webp()
add_library(KSwitcherFilesImage STATIC src/files_image_decode.cpp src/files_image_edit.cpp src/files_image_view.cpp)
target_compile_definitions(KSwitcherFilesImage PRIVATE NOMINMAX UNICODE _UNICODE _WIN32_WINNT=0x0A00)
target_link_libraries(KSwitcherFilesImage PRIVATE webpdemux windowscodecs msimg32 ole32)
if(MSVC)
set_property(TARGET KSwitcherFilesImage PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
target_compile_options(KSwitcherFilesImage PRIVATE /utf-8)
endif()
+26
View File
@@ -0,0 +1,26 @@
include(FetchContent)
find_package(Git REQUIRED)
set(kswitcher_ssh_patch "${CMAKE_CURRENT_LIST_DIR}/libssh2-sftp-command.patch")
file(SHA256 "${kswitcher_ssh_patch}" kswitcher_ssh_patch_hash)
# This revision includes the published SFTP security fixes after the 1.11.1 release.
FetchContent_Declare(kswitcher_libssh2
URL https://codeload.github.com/libssh2/libssh2/tar.gz/dd1546700d0ed8ff7138bc1ccc288286fb3ab2b4
URL_HASH SHA256=67d20d434055faef76439c6829ab253c892fcdd68d9a9c86cf5824bd8366e6eb
DOWNLOAD_EXTRACT_TIMESTAMP TRUE
PATCH_COMMAND "${CMAKE_COMMAND}" "-DGIT=${GIT_EXECUTABLE}"
"-DPATCH=${kswitcher_ssh_patch}" "-DPATCH_HASH=${kswitcher_ssh_patch_hash}"
-P "${CMAKE_CURRENT_LIST_DIR}/ApplyFilesSshPatch.cmake")
function(kswitcher_add_ssh_library)
set(BUILD_STATIC_LIBS ON)
set(BUILD_SHARED_LIBS OFF)
set(BUILD_EXAMPLES OFF)
set(BUILD_TESTING OFF)
set(LIBSSH2_DISABLE_INSTALL ON)
set(LIBSSH2_BUILD_DOCS OFF)
set(CRYPTO_BACKEND WinCNG)
set(ENABLE_ECDSA_WINCNG ON)
FetchContent_MakeAvailable(kswitcher_libssh2)
endfunction()
kswitcher_add_ssh_library()
+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@"
+35
View File
@@ -0,0 +1,35 @@
diff --git a/include/libssh2_sftp.h b/include/libssh2_sftp.h
--- a/include/libssh2_sftp.h
+++ b/include/libssh2_sftp.h
@@ -226,0 +227,2 @@
+LIBSSH2_API LIBSSH2_SFTP *
+libssh2_sftp_init_command(LIBSSH2_SESSION *session, const char *command);
diff --git a/src/sftp.c b/src/sftp.c
--- a/src/sftp.c
+++ b/src/sftp.c
@@ -758 +758,2 @@
-static LIBSSH2_SFTP *sftp_init(LIBSSH2_SESSION *session)
+static LIBSSH2_SFTP *sftp_init(LIBSSH2_SESSION *session,
+ const char *command)
@@ -811,3 +812,5 @@
- "subsystem",
- sizeof("subsystem") - 1,
- "sftp", sizeof("sftp") - 1);
+ command ? "exec" : "subsystem",
+ command ? 4 : 9,
+ command ? command : "sftp",
+ command ?
+ strlen(command) : 4);
@@ -1011 +1014,2 @@
-LIBSSH2_SFTP *libssh2_sftp_init(LIBSSH2_SESSION *session)
+LIBSSH2_SFTP *libssh2_sftp_init_command(LIBSSH2_SESSION *session,
+ const char *command)
@@ -1024 +1028 @@
- BLOCK_ADJUST_ERRNO(ptr, session, sftp_init(session));
+ BLOCK_ADJUST_ERRNO(ptr, session, sftp_init(session, command));
@@ -1025,0 +1030,5 @@
+}
+
+LIBSSH2_SFTP *libssh2_sftp_init(LIBSSH2_SESSION *session)
+{
+ return libssh2_sftp_init_command(session, NULL);
+4 -1
View File
@@ -12,6 +12,9 @@ Copy-Item -LiteralPath (Join-Path $root 'build\release\terminal') -Destination $
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 'resources\files-archive-license.txt') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'resources\files-image-license.txt') -Destination $destination
Copy-Item -LiteralPath (Join-Path $root 'resources\files-sftp-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
@@ -20,7 +23,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','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 $_ }
$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','WebView2Loader.dll','terminal','LICENSE','json-LICENSE.txt','files-text-license.txt','files-archive-license.txt','files-image-license.txt','files-sftp-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()}
+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,120,0
PRODUCTVERSION 0,6,120,0
FILEVERSION 0,8,1,0
PRODUCTVERSION 0,8,1,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.120"
VALUE "FileVersion", "0.8.1"
END
END
BLOCK "VarFileInfo"
+110
View File
@@ -0,0 +1,110 @@
libarchive 3.8.11
https://www.libarchive.org/
The libarchive distribution as a whole is Copyright by Tim Kientzle
and is subject to the copyright notice reproduced at the bottom of
this file.
Each individual file in this distribution should have a clear
copyright/licensing statement at the beginning of the file. If any do
not, please let me know and I will rectify it. The following is
intended to summarize the copyright status of the individual files;
the actual statements in the files are controlling.
* Except as listed below, all C sources (including .c and .h files)
and documentation files are subject to the copyright notice reproduced
at the bottom of this file.
* The following source files are also subject in whole or in part to
a 3-clause UC Regents copyright; please read the individual source
files for details:
libarchive/archive_read_support_filter_compress.c
libarchive/archive_write_add_filter_compress.c
libarchive/mtree.5
* The following source files are in the public domain:
libarchive/archive_parse_date.c
* The following source files are triple-licensed with the ability to choose
from CC0 1.0 Universal, OpenSSL or Apache 2.0 licenses:
libarchive/archive_blake2.h
libarchive/archive_blake2_impl.h
libarchive/archive_blake2s_ref.c
libarchive/archive_blake2sp_ref.c
* The build files---including Makefiles, configure scripts,
and auxiliary scripts used as part of the compile process---have
widely varying licensing terms. Please check individual files before
distributing them to see if those restrictions apply to you.
I intend for all new source code to use the license below and hope over
time to replace code with other licenses with new implementations that
do use the license below. The varying licensing of the build scripts
seems to be an unavoidable mess.
Copyright (c) 2003-2018 <author(s)>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer
in this position and unchanged.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zlib 1.4
https://zlib.net/
Copyright notice:
(C) 1995-2026 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
[email protected] [email protected]
liblzma from XZ Utils 5.8.4
https://tukaani.org/xz/
Copyright (C) The XZ Utils authors and contributors
Permission to use, copy, modify, and/or distribute this
software for any purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, 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.
+56
View File
@@ -0,0 +1,56 @@
libwebp 1.6.0
https://developers.google.com/speed/webp
Copyright (c) 2010, Google Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Google nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Additional IP Rights Grant (Patents)
------------------------------------
"These implementations" means the copyrightable works that implement the WebM
codecs distributed by Google as part of the WebM Project.
Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge,
royalty-free, irrevocable (except as stated in this section) patent license to
make, have made, use, offer to sell, sell, import, transfer, and otherwise
run, modify and propagate the contents of these implementations of WebM, where
such license applies only to those patent claims, both currently owned by
Google and acquired in the future, licensable by Google that are necessarily
infringed by these implementations of WebM. This grant does not include claims
that would be infringed only as a consequence of further modification of these
implementations. If you or your agent or exclusive licensee institute or order
or agree to the institution of patent litigation or any other patent
enforcement activity against any entity (including a cross-claim or
counterclaim in a lawsuit) alleging that any of these implementations of WebM
or any code incorporated within any of these implementations of WebM
constitute direct or contributory patent infringement, or inducement of
patent infringement, then any patent rights granted to you under this License
for these implementations of WebM shall terminate as of the date such
litigation is filed.
+40
View File
@@ -0,0 +1,40 @@
libssh2
https://libssh2.org/
Upstream revision dd1546700d0ed8ff7138bc1ccc288286fb3ab2b4
/* Copyright (C) 2004-2007 Sara Golemon <[email protected]>
* Copyright (C) 2005,2006 Mikhail Gusarov <[email protected]>
* Copyright (C) 2006-2007 The Written Word, Inc.
* Copyright (C) 2007 Eli Fant <[email protected]>
* Copyright (C) 2009-2023 Daniel Stenberg
* Copyright (C) 2008, 2009 Simon Josefsson
* Copyright (C) 2000 Markus Friedl
* Copyright (C) 2015 Microsoft Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
+405 -21
View File
@@ -100,16 +100,49 @@ BEGIN
CONTROL "&Processes…", 103, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 14, 38, 75, 15
END
609 DIALOGEX 0, 0, 350, 135
613 DIALOGEX 0, 0, 255, 100
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
LTEXT "&Line:", 534, 14, 17, 60, 12
FAR_EDIT(536, ES_NUMBER | WS_BORDER, 75, 16, 166, 14)
LTEXT "&Name (optional):", 537, 14, 37, 227, 12
FAR_EDIT(535, WS_BORDER, 14, 50, 227, 14)
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 76, 60, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 132, 76, 60, 16
END
614 DIALOGEX 0, 0, 418, 166
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "", 541, 14, 16, 390, 12, SS_PATHELLIPSIS | SS_NOPREFIX
LISTBOX 538, 14, 33, 390, 100, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 83, 140, 58, 16
CONTROL "Re&name", 539, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 140, 58, 16
CONTROL "&Remove", 540, "Button", BS_OWNERDRAW | WS_TABSTOP, 211, 140, 58, 16
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 275, 140, 58, 16
END
609 DIALOGEX 0, 0, 430, 204
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "", 430, 16, 15, 398, 13, SS_PATHELLIPSIS | SS_NOPREFIX
LTEXT "&Filter", 440, 16, 33, 38, 13
FAR_EDIT(435, 0, 58, 32, 212, 15)
LTEXT "&Sort", 441, 277, 33, 34, 13
COMBOBOX 436, 312, 32, 102, 92, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
LTEXT "", 439, 17, 51, 397, 13, SS_NOPREFIX
LISTBOX 431, 16, 65, 398, 70, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
LTEXT "E&xecutable", 442, 16, 144, 71, 13
FAR_EDIT(438, ES_READONLY, 89, 143, 325, 15)
LTEXT "", 443, 16, 162, 398, 12, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 432, "Static", NOT WS_VISIBLE, 16, 179, 1, 1
CONTROL "&Go to file", 437, "Button", BS_OWNERDRAW | WS_TABSTOP, 35, 185, 90, 16
CONTROL "&End process", 433, "Button", BS_OWNERDRAW | WS_TABSTOP, 130, 185, 90, 16
CONTROL "&Refresh", 434, "Button", BS_OWNERDRAW | WS_TABSTOP, 225, 185, 78, 16
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 308, 185, 72, 16
END
608 DIALOGEX 0, 0, 220, 67
@@ -123,6 +156,95 @@ BEGIN
PUSHBUTTON "Cancel", IDCANCEL, 162, 44, 50, 14
END
615 DIALOGEX 0, 0, 371, 214
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Keyboard shortcuts"
FONT 9, "Segoe UI"
BEGIN
LTEXT "Active &scheme", -1, 9, 9, 160, 11
COMBOBOX 610, 9, 22, 194, 120, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
PUSHBUTTON "&Copy as…", 611, 211, 22, 69, 15
PUSHBUTTON "Rese&t scheme", 612, 288, 22, 74, 15
LTEXT "&Command", -1, 9, 49, 166, 11
LISTBOX 613, 9, 63, 166, 117, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
LTEXT "", 614, 184, 49, 178, 11
LISTBOX 615, 184, 63, 178, 80, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
CONTROL "", 616, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 184, 152, 74, 15
PUSHBUTTON "&Add", 617, 264, 152, 44, 15
PUSHBUTTON "&Remove", 618, 314, 152, 48, 15
PUSHBUTTON "Make &primary", 619, 184, 172, 75, 15
DEFPUSHBUTTON "OK", IDOK, 250, 192, 52, 15
PUSHBUTTON "Cancel", IDCANCEL, 310, 192, 52, 15
END
616 DIALOGEX 0, 0, 233, 73
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Copy keyboard scheme"
FONT 9, "Segoe UI"
BEGIN
LTEXT "Scheme &name", -1, 9, 9, 214, 11
EDITTEXT 620, 9, 23, 215, 15, ES_AUTOHSCROLL
DEFPUSHBUTTON "Copy", IDOK, 112, 49, 52, 15
PUSHBUTTON "Cancel", IDCANCEL, 172, 49, 52, 15
END
617 DIALOGEX 0, 0, 240, 124
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Files settings"
FONT 9, "Segoe UI"
BEGIN
LTEXT "", 624, 9, 9, 222, 24
AUTOCHECKBOX "Colors and file styles", 621, 9, 39, 222, 13
AUTOCHECKBOX "Panel modes and layout", 622, 9, 55, 222, 13
AUTOCHECKBOX "Keyboard schemes", 623, 9, 71, 222, 13
DEFPUSHBUTTON "Load", IDOK, 118, 99, 52, 15
PUSHBUTTON "Cancel", IDCANCEL, 179, 99, 52, 15
END
618 DIALOGEX 0, 0, 468, 242
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "KSwitcher Files Help"
FONT 9, "Segoe UI"
BEGIN
LTEXT "&Search help", -1, 9, 9, 112, 11
EDITTEXT 670, 9, 23, 145, 15, ES_AUTOHSCROLL
LISTBOX 671, 9, 45, 145, 160, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
LTEXT "", 672, 165, 23, 294, 15
EDITTEXT 673, 165, 45, 294, 160, ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL
DEFPUSHBUTTON "&Close", IDOK, 403, 216, 56, 16
END
619 DIALOGEX 0, 0, 435, 211
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Files log"
FONT 9, "Segoe UI"
BEGIN
LTEXT "&Log", -1, 9, 12, 40, 11
COMBOBOX 680, 51, 9, 115, 70, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "", 681, 9, 31, 415, 28
LISTBOX 682, 9, 62, 417, 117, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP
PUSHBUTTON "&Copy selected", 683, 9, 187, 90, 15
PUSHBUTTON "&Refresh", 684, 107, 187, 66, 15
DEFPUSHBUTTON "Close", IDOK, 370, 187, 56, 15
END
620 DIALOGEX 0, 0, 395, 152
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Files MCP"
FONT 9, "Segoe UI"
BEGIN
LTEXT "", 690, 9, 9, 376, 12
LTEXT "Read-only access to local panes, Find results and file metadata.", -1, 9, 26, 376, 13
LTEXT "&Endpoint", -1, 9, 49, 72, 12
EDITTEXT 691, 83, 46, 302, 15, ES_READONLY | ES_AUTOHSCROLL
LTEXT "Session &token", -1, 9, 72, 72, 12
EDITTEXT 692, 83, 69, 302, 15, ES_READONLY | ES_AUTOHSCROLL
AUTOCHECKBOX "Sho&w token", 694, 83, 94, 81, 13
PUSHBUTTON "&Copy token", 695, 169, 91, 72, 16
PUSHBUTTON "&Start", 693, 9, 126, 64, 16
DEFPUSHBUTTON "Close", IDOK, 329, 126, 56, 16
END
101 DIALOGEX 0, 0, 397, 310
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN
CAPTION "KSwitcher Files Options"
@@ -132,8 +254,14 @@ BEGIN
EDITTEXT 270, 8, 21, 113, 14, ES_AUTOHSCROLL
CONTROL "", 271, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 8, 40, 113, 240
LTEXT "", 272, 131, 8, 253, 12
AUTOCHECKBOX "Left panel: &Wide", 273, 132, 27, 115, 12
AUTOCHECKBOX "Right panel: W&ide", 274, 251, 27, 125, 12
LTEXT "&Left panel", 506, 132, 27, 108, 11
COMBOBOX 273, 132, 40, 108, 74, CBS_DROPDOWNLIST | WS_TABSTOP
LTEXT "&Right panel", 507, 251, 27, 117, 11
COMBOBOX 274, 251, 40, 117, 74, CBS_DROPDOWNLIST | WS_TABSTOP
AUTOCHECKBOX "Mark items with the right mouse button", 520, 132, 64, 245, 13
AUTOCHECKBOX "Show drive buttons", 521, 132, 81, 245, 13
AUTOCHECKBOX "Compact commander layout", 522, 132, 98, 245, 13
LTEXT "Shift+right-click opens the Windows context menu.", 523, 132, 115, 245, 13
GROUPBOX "Wide panel columns", 275, 129, 27, 259, 59
LTEXT "Size column &width (6–16 characters)", 276, 138, 44, 175, 10
EDITTEXT 201, 335, 41, 43, 14, ES_NUMBER | ES_AUTOHSCROLL
@@ -155,10 +283,7 @@ BEGIN
COMBOBOX 305, 311, 51, 56, 125, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "&Row text padding (characters)", 306, 131, 77, 173, 12
COMBOBOX 307, 311, 74, 56, 76, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "Previous command", 320, 131, 30, 120, 12
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
PUSHBUTTON "&Keyboard shortcuts…", 321, 131, 30, 127, 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
@@ -197,6 +322,8 @@ BEGIN
PUSHBUTTON "Change color…", 366, 257, 181, 82, 15
LTEXT "", 367, 345, 184, 45, 12
PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15
PUSHBUTTON "Re&name scheme…", 534, 257, 163, 125, 15
AUTOCHECKBOX "Restore local Viewer and Editor windows after restart", 524, 131, 210, 250, 13
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
@@ -210,8 +337,16 @@ BEGIN
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
PUSHBUTTON "&Keyboard shortcuts…", 415, 131, 127, 127, 15
LTEXT "&Scale", 528, 131, 235, 118, 12
COMBOBOX 529, 257, 232, 125, 98, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "&Light mode palette", 530, 131, 32, 118, 12
COMBOBOX 531, 250, 29, 132, 115, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "&Dark mode palette", 532, 131, 56, 118, 12
COMBOBOX 533, 250, 53, 132, 115, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "Viewer and Editor use these palettes when Color scheme is set to System (Windows).", 535, 131, 80, 250, 28
PUSHBUTTON "&Import JSON…", 525, 8, 289, 70, 14
PUSHBUTTON "&Export JSON…", 526, 84, 289, 70, 14
DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14
PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14
PUSHBUTTON "&Apply", 283, 338, 289, 50, 14
@@ -227,8 +362,9 @@ BEGIN
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
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 42, 92, 86, 18
CONTROL "&Options...", 215, "Button", BS_OWNERDRAW | WS_TABSTOP, 132, 92, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 222, 92, 86, 18
END
103 DIALOGEX 0, 0, 460, 126
@@ -392,11 +528,12 @@ 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
LTEXT "", 400, 4, 50, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 401, 259, 50, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 65, 510, 187
CONTROL "", 407, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 8, 200, 19
LTEXT "", 403, 216, 12, 98, 14
CONTROL "", 408, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 28, 490, 19
END
115 DIALOGEX 0, 0, 290, 58
@@ -404,6 +541,253 @@ STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Compare files"
FONT 10, "Consolas"
BEGIN
LTEXT "Reading and comparing files...", -1, 14, 15, 262, 13
LTEXT "Reading and comparing files...", 548, 14, 15, 262, 13
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 101, 31, 88, 17
END
116 DIALOGEX 0, 0, 300, 98
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Find files"
FONT 10, "Consolas"
BEGIN
LTEXT "File &name or mask", 483, 16, 18, 268, 12
FAR_EDIT(480, 0, 16, 32, 268, 15)
AUTOCHECKBOX "Include &hidden and system files", 481, 16, 53, 268, 12
LTEXT "", 482, 10, 69, 1, 1, NOT WS_VISIBLE
CONTROL "&Find", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 68, 73, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 73, 80, 17
END
117 DIALOGEX 0, 0, 290, 83
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Go to folder"
FONT 10, "Consolas"
BEGIN
LTEXT "Folder &path (Tab completes)", 486, 16, 18, 258, 12
FAR_EDIT(485, 0, 16, 32, 258, 15)
LTEXT "", 487, 10, 54, 1, 1, NOT WS_VISIBLE
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 59, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17
END
118 DIALOGEX 0, 0, 420, 209
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Space Analyzer"
FONT 10, "Consolas"
BEGIN
LTEXT "", 488, 16, 15, 353, 13, SS_PATHELLIPSIS
LTEXT "", 495, 16, 28, 353, 13, SS_ENDELLIPSIS
CONTROL "Vo&lume", 496, "Button", BS_OWNERDRAW | WS_TABSTOP, 16, 43, 64, 16
CONTROL "Tree&map", 497, "Button", BS_OWNERDRAW | WS_TABSTOP, 84, 43, 64, 16
CONTROL "S&unburst", 499, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 43, 64, 16
LTEXT "Sunburst items", 501, 171, 43, 201, 16, NOT WS_VISIBLE
LISTBOX 500, 171, 60, 201, 105, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | NOT WS_VISIBLE
CONTROL "", 498, "Static", SS_OWNERDRAW | SS_NOTIFY | WS_TABSTOP | NOT WS_VISIBLE, 16, 60, 353, 105
CONTROL "", 489, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 16, 32, 353, 131
LTEXT "", 490, 16, 167, 353, 14, SS_ENDELLIPSIS
LTEXT "", 491, 12, 184, 1, 1, NOT WS_VISIBLE
CONTROL "S&top", 492, "Button", BS_OWNERDRAW | WS_TABSTOP, 22, 189, 46, 16
CONTROL "St&art", 493, "Button", BS_OWNERDRAW | WS_TABSTOP, 72, 189, 50, 16
CONTROL "&View", 494, "Button", BS_OWNERDRAW | WS_TABSTOP, 126, 189, 46, 16
CONTROL "&Show in other panel", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 176, 189, 102, 16
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 282, 189, 50, 16
END
119 DIALOGEX 0, 0, 260, 197
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Panel columns"
FONT 10, "Consolas"
BEGIN
AUTOCHECKBOX "E&xtension", 510, 18, 18, 224, 13
AUTOCHECKBOX "Si&ze", 511, 18, 36, 224, 13
AUTOCHECKBOX "&Modified", 512, 18, 54, 224, 13
AUTOCHECKBOX "A&llocated bytes", 513, 18, 72, 224, 13
AUTOCHECKBOX "Link cou&nt", 514, 18, 90, 224, 13
AUTOCHECKBOX "&Owner", 515, 18, 108, 224, 13
AUTOCHECKBOX "Automatic column &widths", 516, 18, 135, 224, 13
LTEXT "", 517, 10, 159, 1, 1, NOT WS_VISIBLE
CONTROL "&Apply", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 20, 168, 62, 17
CONTROL "&Reset", 518, "Button", BS_OWNERDRAW | WS_TABSTOP, 88, 168, 74, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 168, 64, 17
END
120 DIALOGEX 0, 0, 290, 82
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Pack files"
FONT 10, "Consolas"
BEGIN
LTEXT "Archive name (.zip or .7z)", 530, 16, 15, 258, 12
FAR_EDIT(531, 0, 16, 32, 258, 15)
LTEXT "", 532, 10, 54, 1, 1, NOT WS_VISIBLE
CONTROL "&Create", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 59, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17
END
122 DIALOGEX 0, 0, 355, 113
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SMB connection"
FONT 10, "Consolas"
BEGIN
LTEXT "Connection &name", 550, 16, 15, 323, 12
FAR_EDIT(551, 0, 16, 29, 323, 15)
LTEXT "&Server or UNC folder", 552, 16, 52, 323, 12
FAR_EDIT(553, 0, 16, 66, 323, 15)
LTEXT "", 554, 10, 87, 1, 1, NOT WS_VISIBLE
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 92, 93, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 182, 93, 80, 17
END
123 DIALOGEX 0, 0, 355, 153
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SMB sign in"
FONT 10, "Consolas"
BEGIN
LTEXT "", 555, 16, 15, 323, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "&User name", 556, 16, 32, 323, 12
FAR_EDIT(557, 0, 16, 46, 323, 15)
LTEXT "&Password", 558, 16, 69, 323, 12
EDITTEXT 559, 16, 83, 323, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL
AUTOCHECKBOX "&Remember in Windows Credential Manager", 560, 16, 106, 323, 13
LTEXT "", 561, 10, 125, 1, 1, NOT WS_VISIBLE
CONTROL "&Connect", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 92, 132, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 182, 132, 80, 17
END
124 DIALOGEX 0, 0, 420, 207
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "SFTP connection"
FONT 10, "Consolas"
BEGIN
LTEXT "Connection &name", 381, 16, 15, 388, 12
FAR_EDIT(382, 0, 16, 28, 388, 15)
LTEXT "Server &host", 383, 16, 49, 292, 12
LTEXT "P&ort", 384, 328, 49, 76, 12
FAR_EDIT(385, 0, 16, 62, 302, 15)
FAR_EDIT(386, ES_NUMBER, 328, 62, 76, 15)
LTEXT "&User name", 387, 16, 83, 182, 12
FAR_EDIT(388, 0, 16, 96, 182, 15)
LTEXT "&Password or key passphrase", 389, 210, 83, 194, 12
EDITTEXT 390, 210, 96, 194, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL
LTEXT "Private &key file (optional)", 562, 16, 117, 182, 12
FAR_EDIT(563, 0, 16, 130, 182, 15)
LTEXT "SFTP ser&ver for sudo (optional)", 569, 210, 117, 194, 12
FAR_EDIT(570, 0, 210, 130, 194, 15)
LTEXT "", 566, 16, 153, 218, 14, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "&Jump via", 568, 240, 153, 56, 14
COMBOBOX 567, 298, 150, 106, 90, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
LTEXT "", 391, 10, 175, 1, 1, NOT WS_VISIBLE
CONTROL "&Test connection", 564, "Button", BS_OWNERDRAW | WS_TABSTOP, 20, 183, 128, 17
CONTROL "&Forget host key", 565, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 183, 112, 17
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 270, 183, 60, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 336, 183, 67, 17
END
125 DIALOGEX 0, 0, 360, 178
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Properties"
FONT 10, "Consolas"
BEGIN
LTEXT "", 580, 16, 15, 328, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 581, 16, 32, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 582, 16, 45, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 583, 16, 58, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 584, 16, 71, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 585, 16, 84, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 586, 16, 99, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
AUTOCHECKBOX "&Read-only", 587, 16, 114, 106, 13
AUTOCHECKBOX "&Hidden", 588, 128, 114, 106, 13
AUTOCHECKBOX "S&ystem", 589, 240, 114, 104, 13
AUTOCHECKBOX "&Archive", 590, 16, 128, 106, 13
AUTOCHECKBOX "Not &indexed", 591, 128, 128, 106, 13
LTEXT "", 592, 10, 146, 1, 1, NOT WS_VISIBLE
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 95, 153, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 185, 153, 80, 17
END
126 DIALOGEX 0, 0, 420, 213
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Commit staged changes"
FONT 10, "Consolas"
BEGIN
LTEXT "", 594, 16, 15, 388, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 595, 16, 31, 388, 13, SS_NOPREFIX
LISTBOX 596, 16, 45, 388, 61, LBS_NOINTEGRALHEIGHT | WS_TABSTOP
LTEXT "Commit &message", 597, 16, 112, 388, 13
EDITTEXT 598, 16, 127, 388, 39, ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN
LTEXT "", 599, 16, 170, 388, 13, SS_ENDELLIPSIS | SS_NOPREFIX | NOT WS_VISIBLE
LTEXT "", 600, 10, 186, 1, 1, NOT WS_VISIBLE
CONTROL "&Commit", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 125, 193, 80, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 215, 193, 80, 17
END
127 DIALOGEX 0, 0, 458, 224
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Environment Variables"
FONT 10, "Consolas"
BEGIN
LTEXT "&Scope", 610, 16, 16, 58, 13
COMBOBOX 611, 77, 15, 120, 75, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
LTEXT "", 613, 16, 34, 426, 13, SS_PATHELLIPSIS | SS_NOPREFIX
LISTBOX 612, 16, 50, 172, 119, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
LTEXT "", 614, 197, 50, 245, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "Ra&w value", 620, 197, 66, 245, 13
EDITTEXT 615, 197, 80, 245, 30, ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY
LTEXT "E&xpanded value", 621, 197, 115, 245, 13
EDITTEXT 616, 197, 129, 245, 39, ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY
LTEXT "", 617, 16, 174, 426, 24, SS_NOPREFIX
LTEXT "", 618, 10, 199, 1, 1, NOT WS_VISIBLE
CONTROL "&Edit", 622, "Button", BS_OWNERDRAW | WS_TABSTOP, 27, 204, 59, 15
CONTROL "Copy to &User", 623, "Button", BS_OWNERDRAW | WS_TABSTOP, 89, 204, 89, 15
CONTROL "Cop&y to System", 624, "Button", BS_OWNERDRAW | WS_TABSTOP, 181, 204, 100, 15
CONTROL "&Refresh", 625, "Button", BS_OWNERDRAW | WS_TABSTOP, 285, 204, 66, 15
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 354, 204, 65, 15
END
128 DIALOGEX 0, 0, 366, 122
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Edit environment definition"
FONT 10, "Consolas"
BEGIN
LTEXT "", 630, 16, 16, 334, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "Ra&w value", 631, 16, 33, 334, 13
EDITTEXT 632, 16, 47, 334, 42, ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN
LTEXT "", 633, 10, 94, 1, 1, NOT WS_VISIBLE
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 100, 78, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 186, 100, 78, 16
END
129 DIALOGEX 0, 0, 388, 177
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Copy/Move options"
FONT 10, "Consolas"
BEGIN
LTEXT "File &mask", 645, 14, 15, 360, 13
FAR_EDIT(640, 0, 14, 28, 360, 17)
LTEXT "Additional &folders on this computer (one absolute path per line)", 646, 14, 53, 360, 13
EDITTEXT 641, 14, 67, 360, 40, ES_MULTILINE | ES_WANTRETURN | ES_AUTOVSCROLL | WS_VSCROLL
AUTOCHECKBOX "Preserve modification &time", 642, 14, 112, 360, 14
AUTOCHECKBOX "Preserve Windows &permissions", 643, 14, 127, 360, 14
LTEXT "Extra folders use the same destination computer or connection.", 647, 14, 143, 360, 13
LTEXT "", 644, 10, 159, 1, 1, NOT WS_VISIBLE
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 161, 86, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 200, 161, 86, 16
END
130 DIALOGEX 0, 0, 329, 119
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Crop image"
FONT 10, "Consolas"
BEGIN
LTEXT "", 650, 14, 15, 301, 12
LTEXT "&X", 656, 14, 35, 58, 14, SS_CENTERIMAGE
FAR_EDIT(651, ES_NUMBER, 75, 33, 70, 18)
LTEXT "&Y", 657, 173, 35, 58, 14, SS_CENTERIMAGE
FAR_EDIT(652, ES_NUMBER, 244, 33, 70, 18)
LTEXT "&Width", 658, 14, 60, 58, 14, SS_CENTERIMAGE
FAR_EDIT(653, ES_NUMBER, 75, 58, 70, 18)
LTEXT "&Height", 659, 173, 60, 62, 14, SS_CENTERIMAGE
FAR_EDIT(654, ES_NUMBER, 244, 58, 70, 18)
LTEXT "", 655, 10, 86, 1, 1, NOT WS_VISIBLE
CONTROL "&Crop", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 78, 94, 83, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 168, 94, 83, 17
END
+65
View File
@@ -0,0 +1,65 @@
# 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.
After a successful update, What's new shows the installed release notes once. Open Help → What's new from the tray to read current and earlier releases offline or open the full release page in Gitea.
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.
+7
View File
@@ -0,0 +1,7 @@
#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"
IDR_HELP_RELEASES RCDATA "../Release/README.md"
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 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

+10
View File
@@ -4,4 +4,14 @@
#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
#define IDR_HELP_RELEASES 604
+5 -2
View File
@@ -10,6 +10,10 @@
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; }
:root.quick-view body { padding: 8px 12px; }
:root.quick-view nav { display: none; }
:root.quick-view main > :first-child { margin-block-start: 0; }
:root.quick-view h1 { font-size: 1.4em; }
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; }
@@ -23,7 +27,7 @@ nav button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px;
::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; }
a[href] { color: LinkText; }
pre, table, figure { overflow: auto; }
pre, code { background: color-mix(in srgb, CanvasText 8%, Canvas); border-radius: 4px; }
pre { padding: .75em; }
@@ -52,6 +56,5 @@ figure svg .edgeLabel rect { fill: Canvas !important; opacity: 1 !important; str
</nav>
<main></main>
<script src="markdown-it.js"></script>
<script src="mermaid.js"></script>
<script src="markdown.js"></script>
</html>
+59 -19
View File
@@ -18,14 +18,28 @@ let activeMatch = -1;
let taskMarkers = new WeakMap();
let pendingTask;
let previewRevision = 0;
let mermaidReady;
mermaid.initialize({
startOnLoad: false,
securityLevel: 'strict',
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
suppressErrorRendering: true,
flowchart: { htmlLabels: false }
});
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');
@@ -59,7 +73,7 @@ markdown.renderer.rules.image = (tokens, i) => {
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
main mark nav 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 = {
@@ -74,21 +88,25 @@ function relativeResource(path) {
return path && !/^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path) && !/[\u0000-\u001f\u007f]/.test(path);
}
function renderContent(text, canSave) {
function renderContent(text, canSave, html) {
// 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 });
template.innerHTML = html ? text : 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')) {
(tag === 'input' && (html || element.type !== 'checkbox'))) {
element.remove();
continue;
}
const imagePath = tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
const imagePath = !html && tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
if (html && tag === 'img') {
element.replaceWith(document.createTextNode(element.getAttribute('alt') ?? ''));
continue;
}
const task = tag === 'input' && element.getAttribute('data-task');
if (task && task.startsWith(taskKey + ':')) {
const [, line, column] = task.split(':');
@@ -98,7 +116,8 @@ function renderContent(text, 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);
const blockedInHtml = html && (name === 'id' || name === 'class' || name === 'href');
if (blockedInHtml || (!htmlAttributes.has(name) && !tagAttributes[tag]?.includes(name))) element.removeAttribute(name);
}
for (const [name, value] of styles) {
if (value) element.style.setProperty(name, value);
@@ -233,14 +252,22 @@ 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 }) {
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave, compact, html }) {
const current = ++generation;
if (keepPosition) scroll = window.scrollY;
else closeSearch();
document.documentElement.classList.remove('rendered');
document.title = title;
document.documentElement.classList.toggle('quick-view', Boolean(compact));
previewRevision = revision;
renderContent(text, canSave);
renderContent(text, canSave, html);
images = [];
if (html) {
window.scrollTo(0, 0);
document.documentElement.classList.add('rendered');
send('rendered', { revision });
return;
}
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, '-');
@@ -250,11 +277,13 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c
headings.add(id);
}
images = Array.from(content.querySelectorAll('img[data-path]'));
images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current }));
images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current, revision }));
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
for (const [index, block] of blocks.entries()) {
try {
const { svg } = await mermaid.render('diagram-' + current + '-' + index, block.textContent);
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;
@@ -273,7 +302,7 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c
restorePosition({ fragment, scroll });
document.documentElement.classList.add('rendered');
if (!search.hidden) updateSearch(false);
send('rendered');
send('rendered', { revision });
}
content.addEventListener('change', ({ target }) => {
@@ -326,6 +355,17 @@ document.addEventListener('keydown', event => {
}
});
let scrollTimer;
window.addEventListener('scroll', () => {
if (document.documentElement.classList.contains('quick-view')) return;
clearTimeout(scrollTimer);
const revision = previewRevision;
scrollTimer = setTimeout(() => {
if (revision === previewRevision && document.documentElement.classList.contains('rendered'))
send('scroll', { revision, top: Math.round(window.scrollY) });
}, 120);
}, { passive: true });
bridge.addEventListener('message', ({ data }) => {
const message = JSON.parse(data);
if (message.action === 'clear') {
@@ -334,7 +374,7 @@ bridge.addEventListener('message', ({ data }) => {
document.documentElement.classList.remove('rendered');
content.replaceChildren();
}
if (message.action === 'render') void render(message).catch(() => send('failed'));
if (message.action === 'render') void render(message).catch(() => send('failed', { revision: message.revision }));
if (message.action === 'task-result' && message.revision === previewRevision && pendingTask) {
if (!message.saved) pendingTask.target.checked = !pendingTask.checked;
pendingTask = undefined;
+48 -3
View File
@@ -4,12 +4,15 @@ const terminal = new Terminal({
fontSize: 16,
cursorBlink: false,
cursorInactiveStyle: 'none',
disableStdin: true,
theme: { background: '#181818', foreground: '#e8e8e8' },
});
const fit = new FitAddon.FitAddon();
terminal.parser.registerOscHandler(633, data => {
const prefix = 'ks-directory:';
if (data.startsWith('ks-ssh-dir:')) {
bridge.postMessage('ssh-directory:' + data.slice(11));
return true;
}
if (!data.startsWith(prefix)) return false;
try {
bridge.postMessage('directory:' + decodeURIComponent(data.slice(prefix.length)));
@@ -22,7 +25,15 @@ 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 prompt = message => bridge.postMessage('prompt:' + message);
let sshInput = false;
host.addEventListener('pointerup', () => {
if (!sshInput) prompt('focus-input');
}, true);
terminal.onData(text => {
if (sshInput) bridge.postMessage('ssh-input:' + text);
else if (!/[\x00-\x1f\x7f]/u.test(text)) prompt('text:' + text);
});
const screen = host.querySelector('.xterm-screen');
let traceEnabled = false;
let traceBudget = 4096;
@@ -52,9 +63,28 @@ function anchorOutput() {
currentOffset = offset;
trace(2);
}
const promptKeys = new Set([
'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End',
'Tab', 'Escape', 'Delete', 'Backspace', 'F1',
]);
terminal.attachCustomKeyEventHandler(event => {
if (event.isComposing) return true;
if (sshInput) {
if (event.type !== 'keydown' || !event.ctrlKey || event.altKey || event.metaKey) return true;
const copy = event.code === 'KeyC' && terminal.hasSelection();
if (!copy && (event.shiftKey || event.code !== 'KeyO')) return true;
event.preventDefault();
if (!event.repeat) bridge.postMessage(copy ? 'copy-command-line' : 'toggle');
return false;
}
if (event.type === 'keydown' && promptKeys.has(event.key) &&
!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {
prompt(event.key);
event.preventDefault();
return false;
}
if (event.type === 'keydown' && event.key === 'Enter' && !event.ctrlKey && !event.altKey && !event.metaKey) {
if (!event.repeat) bridge.postMessage(event.shiftKey ? 'shift-enter' : 'enter');
if (!event.repeat) prompt(event.shiftKey ? 'shift-enter' : 'enter');
event.preventDefault();
return false;
}
@@ -85,6 +115,21 @@ terminal.onScroll(() => {
anchorOutput();
});
bridge.addEventListener('message', ({ data }) => {
if (data === 'ssh-input:on' || data === 'ssh-input:off') {
sshInput = data === 'ssh-input:on';
terminal.options.cursorBlink = sshInput;
terminal.write(sshInput ? '\x1b[?25h' : '\x1b[?25l');
return;
}
if (data === 'ssh-focus') {
terminal.focus();
return;
}
if (data === 'ssh-reset') {
terminal.reset();
terminal.write('\x1b[?25l');
return;
}
if (data === 'clear-selection') {
terminal.clearSelection();
return;
+570 -137
View File
File diff suppressed because it is too large. Load diff
+22 -5
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{};
@@ -78,10 +78,11 @@ class App
void enqueue(std::function<void()>);
void enqueueHistorySearch(std::function<void()>);
void report(const std::wstring &);
void showWhatsNewAfterUpdate();
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 +106,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,6 +160,7 @@ class App
ULONGLONG nextSync{}, syncRetryAfter{};
SyncResult syncResult;
SyncConfig syncConnection;
std::string syncDriveKey;
SyncConfig conflictConnection;
std::vector<SyncConflict> pendingSyncConflicts;
Bytes syncSnapshot;
@@ -161,14 +171,18 @@ class App
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;
@@ -220,5 +234,8 @@ void showSettings(App &, bool visible = true);
void showLogs(App &);
void showSnippets(App &);
void showShortcuts(App &);
void showHelp(App &);
const wchar_t *whatsNewTitle(LANGID language);
void showWhatsNew(App &, LANGID language);
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; }
+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;
+47 -4
View File
@@ -40,6 +40,34 @@ 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;
@@ -99,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.");
@@ -106,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 &);
}
+170 -60
View File
@@ -319,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()
@@ -377,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)
@@ -423,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;
+11 -1
View File
@@ -5,6 +5,7 @@
#include <optional>
#include <set>
#include <string>
#include <variant>
#include <vector>
#include <windows.h>
@@ -42,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{};
+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.");
}
}
}
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include <windows.h>
#include <array>
#include <cstddef>
#include <cwchar>
namespace ks::files
{
enum class AppearanceArea { panels, viewer, editor, markdown, terminal, comparison, count };
inline constexpr size_t appearanceIndex(AppearanceArea area) { return static_cast<size_t>(area); }
using AppearanceScales=std::array<unsigned,appearanceIndex(AppearanceArea::count)>;
inline constexpr AppearanceScales defaultAppearanceScales{100,100,100,100,100,100};
inline constexpr unsigned minAppearanceScale=75,maxAppearanceScale=200;
inline int scaledAppearanceSize(int size,unsigned percent)
{
return MulDiv(size,static_cast<int>(percent),100);
}
inline bool windowsAppThemeChanged(UINT message,LPARAM parameter)
{
return message==WM_THEMECHANGED || (message==WM_SETTINGCHANGE && parameter &&
std::wcscmp(reinterpret_cast<const wchar_t*>(parameter),L"ImmersiveColorSet")==0);
}
inline bool windowsUsesDarkApps()
{
DWORD light=1,bytes=sizeof(light);
return RegGetValueW(HKEY_CURRENT_USER,L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
L"AppsUseLightTheme",RRF_RT_REG_DWORD,nullptr,&light,&bytes)==ERROR_SUCCESS && !light;
}
}
+523
View File
@@ -0,0 +1,523 @@
#include "files_archive.h"
#include "files_win32_directory.h"
#include "files_win32_replace.h"
#include <objbase.h>
#include <archive.h>
#include <archive_entry.h>
#include <algorithm>
#include <array>
#include <cctype>
#include <memory>
#include <optional>
#include <set>
#include <stdexcept>
#include <string_view>
namespace ks::files
{
namespace fs=std::filesystem;
bool ArchiveNameOrder::operator()(const fs::path &left,const fs::path &right) const
{
return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE)==CSTR_LESS_THAN;
}
bool isArchivePath(const fs::path &path)
{
const auto extension=path.extension();
return CompareStringOrdinal(extension.c_str(),-1,L".zip",-1,TRUE)==CSTR_EQUAL ||
CompareStringOrdinal(extension.c_str(),-1,L".7z",-1,TRUE)==CSTR_EQUAL;
}
namespace
{
using ArchiveReader=std::unique_ptr<archive,decltype(&archive_read_free)>;
using ArchiveWriter=std::unique_ptr<archive,decltype(&archive_write_free)>;
constexpr std::int64_t archiveEpochOffset=11644473600, archiveTicksPerSecond=10000000;
constexpr char unsafePath[]="The archive contains an unsafe or conflicting path.";
constexpr char encryptedArchive[]="This archive requires a password. Password-protected entries cannot be opened in Files.";
uint64_t archiveTime(bool present,int64_t seconds,long nanos)
{
if(!present || seconds < -archiveEpochOffset || seconds>=INT64_MAX/archiveTicksPerSecond-archiveEpochOffset)
return 0;
return static_cast<uint64_t>((seconds+archiveEpochOffset)*archiveTicksPerSecond+nanos/100);
}
struct ArchiveFileHandle
{
HANDLE value=INVALID_HANDLE_VALUE;
explicit ArchiveFileHandle(HANDLE handle) : value(handle)
{
if(value==INVALID_HANDLE_VALUE) throw std::system_error(GetLastError(),std::system_category());
}
ArchiveFileHandle(const ArchiveFileHandle &)=delete;
ArchiveFileHandle &operator=(const ArchiveFileHandle &)=delete;
~ArchiveFileHandle() {CloseHandle(value);}
};
[[noreturn]] void archiveError(archive *reader)
{
const auto *error=archive_error_string(reader);
std::string detail=error?error:"";
std::transform(detail.begin(),detail.end(),detail.begin(),
[](unsigned char ch){return static_cast<char>(std::tolower(ch));});
if(detail.find("password")!=detail.npos || detail.find("passphrase")!=detail.npos ||
detail.find("encrypted")!=detail.npos) throw std::runtime_error(encryptedArchive);
throw std::runtime_error("Could not read the ZIP or 7z archive.");
}
ArchiveReader openArchive(const fs::path &file)
{
ArchiveReader reader(archive_read_new(),archive_read_free);
if(!reader) throw std::runtime_error("Could not create the archive reader.");
if(archive_read_support_format_zip(reader.get())!=ARCHIVE_OK ||
archive_read_support_format_7zip(reader.get())!=ARCHIVE_OK ||
archive_read_open_filename_w(reader.get(),file.c_str(),64*1024)!=ARCHIVE_OK)
archiveError(reader.get());
return reader;
}
std::pair<fs::path,ArchiveEntry> decodeEntry(archive_entry *entry)
{
const auto *wide=archive_entry_pathname_w(entry);
std::wstring name=wide?wide:L"";
if(name.empty() || name.front()==L'/' || name.front()==L'\\')
throw std::runtime_error(unsafePath);
std::replace(name.begin(),name.end(),L'/',L'\\');
const auto type=archive_entry_filetype(entry);
const bool folder=type==AE_IFDIR;
if((!folder && type!=AE_IFREG) || archive_entry_hardlink_w(entry) || archive_entry_symlink_w(entry))
throw std::runtime_error("The archive contains a link or an unsupported entry type.");
fs::path relative;
for(size_t start=0;start<name.size();)
{
const auto end=name.find(L'\\',start);
const auto component=std::wstring_view(name).substr(start,end==name.npos?end:end-start);
if(component!=L".")
{
if(component.size()>255 || !validWindowsFileName(component))
throw std::runtime_error(unsafePath);
relative/=component;
}
if(end==name.npos) break;
start=end+1;
}
if(relative.empty() && !folder) throw std::runtime_error(unsafePath);
const auto size=archive_entry_size(entry);
if(size<0 || (!folder && !archive_entry_size_is_set(entry)))
throw std::runtime_error("The archive entry has an invalid size.");
ArchiveEntry metadata{
static_cast<uint64_t>(size),
archiveTime(archive_entry_mtime_is_set(entry),archive_entry_mtime(entry),archive_entry_mtime_nsec(entry)),
folder,archive_entry_is_encrypted(entry)!=0};
metadata.created=archiveTime(archive_entry_birthtime_is_set(entry),archive_entry_birthtime(entry),
archive_entry_birthtime_nsec(entry));
metadata.accessed=archiveTime(archive_entry_atime_is_set(entry),archive_entry_atime(entry),archive_entry_atime_nsec(entry));
if(const auto *owner=archive_entry_uname_w(entry)) metadata.owner=owner;
return {relative,std::move(metadata)};
}
void registerEntry(ArchiveEntries &entries,const fs::path &path,const ArchiveEntry &entry)
{
if(path.empty()) return;
const auto [existing,inserted]=entries.try_emplace(path,entry);
if(!inserted)
{
if(existing->first.native()!=path.native() || !entry.directory || !existing->second.directory ||
!existing->second.implicit) throw std::runtime_error(unsafePath);
existing->second=entry;
}
for(auto parent=path.parent_path();!parent.empty();parent=parent.parent_path())
{
const auto [item,fresh]=entries.try_emplace(parent,ArchiveEntry{.directory=true,.implicit=true});
if(fresh) continue;
if(!item->second.directory || item->first.native()!=parent.native()) throw std::runtime_error(unsafePath);
break;
}
}
template<class Visit>
ArchiveEntries walkArchive(const fs::path &file,const Visit &visit)
{
auto reader=openArchive(file);
ArchiveEntries entries;
for(;;)
{
archive_entry *raw=nullptr;
const auto status=archive_read_next_header(reader.get(),&raw);
if(status==ARCHIVE_EOF) return entries;
if(status!=ARCHIVE_OK) archiveError(reader.get());
auto [path,entry]=decodeEntry(raw);
registerEntry(entries,path,entry);
if(!visit(reader.get(),raw,path,entry)) throw std::system_error(ERROR_CANCELLED,std::system_category());
}
}
void writeMember(archive *reader,const ArchiveEntry &entry,const fs::path &output,uint64_t limit,
const ArchiveProgress &progress)
{
if(entry.encrypted) throw std::runtime_error(encryptedArchive);
if(entry.size>limit) throw std::runtime_error("The archive entry is too large to preview.");
const ArchiveFileHandle owned(CreateFileW(output.c_str(),GENERIC_WRITE,0,nullptr,CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,nullptr));
std::array<char,64*1024> buffer{};
uint64_t done=0;
for(;;)
{
if(progress && !progress(done,entry.size)) throw std::system_error(ERROR_CANCELLED,std::system_category());
const auto size=archive_read_data(reader,buffer.data(),buffer.size());
if(size<0) archiveError(reader);
if(size==0) break;
if(static_cast<uint64_t>(size)>entry.size-done)
throw std::runtime_error("The archive entry exceeds its declared size.");
DWORD written=0;
if(!WriteFile(owned.value,buffer.data(),static_cast<DWORD>(size),&written,nullptr) ||
written!=static_cast<DWORD>(size))
throw std::system_error(GetLastError(),std::system_category());
done+=written;
}
if(done!=entry.size) throw std::runtime_error("The archive entry is incomplete.");
if(entry.modified)
{
const FILETIME time{static_cast<DWORD>(entry.modified),static_cast<DWORD>(entry.modified>>32)};
if(!SetFileTime(owned.value,nullptr,nullptr,&time))
throw std::system_error(GetLastError(),std::system_category());
}
}
}
ArchiveEntries readArchive(const fs::path &file,std::stop_token stop)
{
return walkArchive(file,[&](auto *,auto *,const auto &,const auto &){return !stop.stop_requested();});
}
ArchiveEntry readArchiveMember(const fs::path &file,const fs::path &member,const fs::path &output,
uint64_t limit,const ArchiveProgress &progress)
{
std::optional<ArchiveEntry> found;
walkArchive(file,[&](archive *reader,archive_entry *,const fs::path &path,const ArchiveEntry &entry)
{
if(progress && !progress(found?found->size:0,found?found->size:0)) return false;
if(!entry.directory && path==member)
{
writeMember(reader,entry,output,limit,progress);
found=entry;
}
return true;
});
if(!found) throw std::runtime_error("The archive entry is no longer available.");
return *found;
}
void extractArchiveSelection(const fs::path &file,const fs::path &directory,const std::vector<fs::path> &selection,
const fs::path &staging,const ArchiveProgress &progress)
{
const std::set<fs::path> selected(selection.begin(),selection.end());
for(const auto &path:selected)
if(path.empty() || path.parent_path()!=directory) throw std::runtime_error(unsafePath);
const auto wanted=[&](const fs::path &path)
{
for(auto item=path;!item.empty() && item!=directory;item=item.parent_path())
if(selected.contains(item)) return true;
return false;
};
const auto entries=walkArchive(file,[&](archive *reader,archive_entry *,const fs::path &path,const ArchiveEntry &entry)
{
if(progress && !progress(0,0)) return false;
if(!wanted(path)) return true;
const auto output=staging/path.lexically_relative(directory);
fs::create_directories(entry.directory?output:output.parent_path());
if(!entry.directory) writeMember(reader,entry,output,UINT64_MAX,progress);
return true;
});
for(const auto &path:selected)
if(!entries.contains(path)) throw std::runtime_error("A selected archive entry is no longer available.");
}
namespace
{
BY_HANDLE_FILE_INFORMATION archiveFileInfo(HANDLE file)
{
BY_HANDLE_FILE_INFORMATION info{};
if(!GetFileInformationByHandle(file,&info)) throw std::system_error(GetLastError(),std::system_category());
return info;
}
uint64_t archiveFileSize(const BY_HANDLE_FILE_INFORMATION &info)
{
return (uint64_t(info.nFileSizeHigh)<<32)|info.nFileSizeLow;
}
bool sameArchiveFile(const BY_HANDLE_FILE_INFORMATION &left,const BY_HANDLE_FILE_INFORMATION &right)
{
return sameFileIdentity(left,right) && archiveFileSize(left)==archiveFileSize(right) &&
CompareFileTime(&left.ftLastWriteTime,&right.ftLastWriteTime)==0;
}
struct ArchiveTemporaryFile
{
fs::path directory, file;
explicit ArchiveTemporaryFile(const fs::path &parent)
{
GUID id{};
wchar_t name[40]{};
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
throw std::runtime_error("Could not prepare a temporary archive.");
directory=parent/(L".ks-files-pack-"+std::wstring(name));
file=directory/L"archive";
if(!fs::create_directory(directory)) throw std::runtime_error("Could not prepare a temporary archive.");
}
~ArchiveTemporaryFile()
{
std::error_code error;
fs::remove(file,error);
fs::remove(directory,error);
}
};
bool isZip(const fs::path &file)
{
return CompareStringOrdinal(file.extension().c_str(),-1,L".zip",-1,TRUE)==CSTR_EQUAL;
}
HANDLE lockArchiveFolder(const fs::path &directory)
{
const auto lock=directory/L".ks-files-archive-write.lock";
const HANDLE handle=CreateFileW(lock.c_str(),GENERIC_WRITE|DELETE,0,nullptr,CREATE_NEW,
FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,nullptr);
if(handle!=INVALID_HANDLE_VALUE) return handle;
const DWORD error=GetLastError();
if(error==ERROR_FILE_EXISTS || error==ERROR_ALREADY_EXISTS || error==ERROR_SHARING_VIOLATION)
throw std::runtime_error("Another archive operation is active in this folder.");
throw std::system_error(error,std::system_category());
}
void checkArchiveWrite(int status)
{
if(status!=ARCHIVE_OK) throw std::runtime_error("Could not create the ZIP or 7z data.");
}
ArchiveWriter openArchiveWriter(const fs::path &file,bool zip)
{
ArchiveWriter writer(archive_write_new(),archive_write_free);
if(!writer) throw std::runtime_error("Could not create the archive writer.");
checkArchiveWrite(zip?archive_write_set_format_zip(writer.get()):archive_write_set_format_7zip(writer.get()));
checkArchiveWrite(archive_write_set_options(writer.get(),zip?"hdrcharset=UTF-8":"compression=lzma2"));
checkArchiveWrite(archive_write_open_filename_w(writer.get(),file.c_str()));
return writer;
}
struct ArchiveInput
{
fs::path source;
BY_HANDLE_FILE_INFORMATION info;
};
using ArchiveInputs=std::map<fs::path,ArchiveInput,ArchiveNameOrder>;
void addArchiveInput(ArchiveInputs &inputs,const fs::path &source,const fs::path &member,const fs::path &target,
const std::function<void()> &checkCanceled)
{
checkCanceled();
if(member.empty() || member.filename().native().size()>255 || !validWindowsFileName(member.filename().native()))
throw std::runtime_error("A selected file has a name that cannot be stored safely in the archive.");
std::error_code error;
if(fs::equivalent(source,target,error)) throw std::runtime_error("The archive cannot contain itself.");
if(fs::equivalent(source,target.parent_path(),error))
throw std::runtime_error("Choose an archive location outside the selected folders.");
const ArchiveFileHandle file(CreateFileW(source.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE,
nullptr,OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr));
const auto info=archiveFileInfo(file.value);
if(info.dwFileAttributes&FILE_ATTRIBUTE_REPARSE_POINT)
throw std::runtime_error("The selection contains a Windows link or reparse point.");
if(!inputs.emplace(member,ArchiveInput{source,info}).second)
throw std::runtime_error("The selection contains conflicting names.");
if(!(info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) return;
for(const auto &child:fs::directory_iterator(source))
addArchiveInput(inputs,child.path(),member/child.path().filename(),target,checkCanceled);
}
template<class Read>
void transferArchiveData(archive *writer,uint64_t size,const Read &read,const std::function<void(uint64_t)> &advance)
{
std::array<char,64*1024> buffer{};
uint64_t bytes=0;
while(bytes<size)
{
const auto count=read(buffer.data(),static_cast<DWORD>(std::min<uint64_t>(size-bytes,buffer.size())));
if(!count) throw std::runtime_error("An archive input ended before its declared size.");
if(archive_write_data(writer,buffer.data(),count)!=static_cast<la_ssize_t>(count))
throw std::runtime_error("Could not write archive contents.");
bytes+=count;
advance(count);
}
if(read(buffer.data(),1)!=0) throw std::runtime_error("An archive input changed size while it was being written.");
checkArchiveWrite(archive_write_finish_entry(writer));
}
void archiveLocalInput(archive *writer,const fs::path &path,const ArchiveInput &input,
const std::function<void(uint64_t)> &advance)
{
const bool folder=(input.info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
std::unique_ptr<archive_entry,decltype(&archive_entry_free)> entry(archive_entry_new(),archive_entry_free);
if(!entry) throw std::runtime_error("Could not create an archive entry.");
const auto name=path.generic_wstring();
archive_entry_copy_pathname_w(entry.get(),name.c_str());
archive_entry_set_filetype(entry.get(),folder?AE_IFDIR:AE_IFREG);
archive_entry_set_perm(entry.get(),folder?0755:0644);
const uint64_t size=folder?0:archiveFileSize(input.info);
archive_entry_set_size(entry.get(),static_cast<la_int64_t>(size));
const auto stamp=(uint64_t(input.info.ftLastWriteTime.dwHighDateTime)<<32)|input.info.ftLastWriteTime.dwLowDateTime;
archive_entry_set_mtime(entry.get(),static_cast<int64_t>(stamp/archiveTicksPerSecond)-archiveEpochOffset,
static_cast<long>((stamp%archiveTicksPerSecond)*100));
if(folder)
{
checkArchiveWrite(archive_write_header(writer,entry.get()));
checkArchiveWrite(archive_write_finish_entry(writer));
return;
}
const ArchiveFileHandle file(CreateFileW(input.source.c_str(),GENERIC_READ,FILE_SHARE_READ,nullptr,OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_SEQUENTIAL_SCAN,nullptr));
const auto current=archiveFileInfo(file.value);
if((current.dwFileAttributes&(FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY)) ||
!sameArchiveFile(input.info,current))
throw std::runtime_error("A selected file changed before it could be added.");
checkArchiveWrite(archive_write_header(writer,entry.get()));
transferArchiveData(writer,size,[&](char *buffer,DWORD goal)
{
DWORD used=0;
if(!ReadFile(file.value,buffer,goal,&used,nullptr))
throw std::system_error(GetLastError(),std::system_category());
return used;
},advance);
}
}
void writeArchive(const fs::path &file,ArchiveWriteMode mode,const fs::path &directory,
const std::vector<fs::path> &sources,const ArchiveProgress &progress)
{
if(!isArchivePath(file)) throw std::runtime_error("Files can write ZIP and 7z archives.");
if(!file.is_absolute() || !validWindowsFileName(file.filename().native()) || sources.empty())
throw std::runtime_error("Select local files and enter a valid archive name.");
for(const auto &part:directory)
if(!validWindowsFileName(part.native())) throw std::runtime_error(unsafePath);
const bool zip=isZip(file);
const bool updating=mode==ArchiveWriteMode::update;
if(!updating && !directory.empty()) throw std::runtime_error("Create a new archive at its root.");
if(!updating && GetFileAttributesW(file.c_str())!=INVALID_FILE_ATTRIBUTES)
throw std::runtime_error("A file or folder with this archive name already exists.");
uint64_t done=0, total=0;
const auto checkCanceled=[&]
{
if(progress && !progress(done,total)) throw std::system_error(ERROR_CANCELLED,std::system_category());
};
const auto advance=[&](uint64_t bytes) {done+=bytes;checkCanceled();};
const auto plan=[&](uint64_t bytes)
{
if(UINT64_MAX-total<bytes) throw std::runtime_error("The selection is too large to archive.");
total+=bytes;
};
ArchiveInputs inputs;
for(const auto &source:sources)
{
if(!source.is_absolute()) throw std::runtime_error("Select files from a local folder.");
addArchiveInput(inputs,source,directory/source.filename(),file,checkCanceled);
}
const ArchiveFileHandle lock(lockArchiveFolder(file.parent_path()));
std::optional<ArchiveFileHandle> original;
BY_HANDLE_FILE_INFORMATION originalInfo{};
ArchiveEntries existing;
if(updating)
{
original.emplace(CreateFileW(file.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT,nullptr));
originalInfo=archiveFileInfo(original->value);
if(originalInfo.dwFileAttributes&(FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_READONLY))
throw std::runtime_error("This archive is read-only or is a Windows link.");
existing=walkArchive(file,[&](archive *reader,archive_entry *,const fs::path &path,const ArchiveEntry &entry)
{
checkCanceled();
const int expected=zip?ARCHIVE_FORMAT_ZIP:ARCHIVE_FORMAT_7ZIP;
if((archive_format(reader)&ARCHIVE_FORMAT_BASE_MASK)!=expected)
throw std::runtime_error("The archive contents do not match its ZIP or 7z extension.");
if(entry.encrypted) throw std::runtime_error("Password-protected archives cannot be updated in Files.");
if(!entry.directory && !inputs.contains(path)) plan(entry.size);
return true;
});
if(!directory.empty())
{
const auto parent=existing.find(directory);
if(parent==existing.end() || !parent->second.directory || parent->first.native()!=directory.native())
throw std::runtime_error("This folder is no longer present in the archive.");
}
}
auto combined=existing;
for(const auto &[path,input]:inputs)
{
checkCanceled();
const bool folder=(input.info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
if(const auto present=combined.find(path);present!=combined.end())
{
if(present->first.native()!=path.native() || present->second.directory!=folder)
throw std::runtime_error(unsafePath);
}
else registerEntry(combined,path,ArchiveEntry{.directory=folder});
if(!folder) plan(archiveFileSize(input.info));
}
checkCanceled();
const ArchiveTemporaryFile temp(file.parent_path());
auto writer=openArchiveWriter(temp.file,zip);
if(updating)
walkArchive(file,[&](archive *reader,archive_entry *raw,const fs::path &path,const ArchiveEntry &entry)
{
checkCanceled();
if(path.empty() || inputs.contains(path)) return true;
const auto name=path.generic_wstring();
archive_entry_copy_pathname_w(raw,name.c_str());
checkArchiveWrite(archive_write_header(writer.get(),raw));
if(entry.directory) checkArchiveWrite(archive_write_finish_entry(writer.get()));
else transferArchiveData(writer.get(),entry.size,[&](char *buffer,DWORD goal)
{
const auto used=archive_read_data(reader,buffer,goal);
if(used<0) archiveError(reader);
return static_cast<DWORD>(used);
},advance);
return true;
});
for(const auto &[path,input]:inputs)
{
checkCanceled();
archiveLocalInput(writer.get(),path,input,advance);
}
checkArchiveWrite(archive_write_close(writer.get()));
writer.reset();
{
const ArchiveFileHandle completed(CreateFileW(temp.file.c_str(),GENERIC_WRITE,FILE_SHARE_READ,nullptr,
OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr));
if(!FlushFileBuffers(completed.value)) throw std::system_error(GetLastError(),std::system_category());
}
if(updating)
{
const ArchiveFileHandle current(CreateFileW(file.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr));
if(!sameArchiveFile(originalInfo,archiveFileInfo(current.value)))
throw std::runtime_error("The archive changed while it was being updated.");
}
checkCanceled();
if(updating)
{
const auto backup=temp.directory/L"original";
if(const auto error=replaceFileWithBackup(file,temp.file,backup))
throw std::system_error(error,std::system_category());
original.reset();
DeleteFileW(backup.c_str());
}
else if(!MoveFileExW(temp.file.c_str(),file.c_str(),MOVEFILE_WRITE_THROUGH))
throw std::system_error(GetLastError(),std::system_category());
}
}
+40
View File
@@ -0,0 +1,40 @@
#pragma once
#include <cstdint>
#include <filesystem>
#include <functional>
#include <map>
#include <stop_token>
#include <string>
#include <vector>
namespace ks::files
{
struct ArchiveNameOrder
{
bool operator()(const std::filesystem::path &left,const std::filesystem::path &right) const;
};
struct ArchiveEntry
{
uint64_t size{}, modified{};
bool directory{}, encrypted{}, implicit{};
uint64_t created{}, accessed{};
std::wstring owner{};
};
using ArchiveEntries=std::map<std::filesystem::path,ArchiveEntry,ArchiveNameOrder>;
using ArchiveProgress=std::function<bool(uint64_t done,uint64_t total)>;
bool isArchivePath(const std::filesystem::path &path);
ArchiveEntries readArchive(const std::filesystem::path &file,std::stop_token stop);
ArchiveEntry readArchiveMember(const std::filesystem::path &file,const std::filesystem::path &member,
const std::filesystem::path &output,uint64_t limit,const ArchiveProgress &progress);
void extractArchiveSelection(const std::filesystem::path &file,const std::filesystem::path &directory,
const std::vector<std::filesystem::path> &selection,const std::filesystem::path &staging,
const ArchiveProgress &progress);
enum class ArchiveWriteMode { create, update };
void writeArchive(const std::filesystem::path &file,ArchiveWriteMode mode,const std::filesystem::path &directory,
const std::vector<std::filesystem::path> &sources,const ArchiveProgress &progress);
}
+154
View File
@@ -0,0 +1,154 @@
INT_PTR CALLBACK archiveNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int field=531, footer=532;
const auto input=GetDlgItem(dialog,field);
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
const auto &name=*reinterpret_cast<const std::wstring *>(lp);
prepareTextDialog(dialog);
fitFarEditToLine(input);
SetWindowTextW(input,name.c_str());
SendMessageW(input,EM_SETLIMITTEXT,255,0);
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(input);
SendMessageW(input,EM_SETSEL,0,static_cast<LPARAM>(name.rfind(L'.')));
return FALSE;
}
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Pack files ",false,{footer}))
return painted;
if(message!=WM_COMMAND) return FALSE;
if(LOWORD(wp)==IDCANCEL)
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(LOWORD(wp)!=IDOK) return FALSE;
auto name=dialogFieldText(input);
if(!ks::files::validWindowsFileName(name) || !ks::files::isArchivePath(fs::path(name)))
{
showFilesNotice(dialog,L"Enter a file name ending in .zip or .7z.",L"Archive format",
{.tone=FilesNoticeTone::warning});
SetFocus(input);
return TRUE;
}
auto &result=*reinterpret_cast<std::wstring *>(GetWindowLongPtrW(dialog,DWLP_USER));
result=std::move(name);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
void performArchiveWrite(HWND owner,Panel &panel,const fs::path &archive,ks::files::ArchiveWriteMode mode,
const fs::path &directory,const std::vector<fs::path> &sources)
{
if(copyInProgress || sources.empty()) return;
const bool updating=mode==ks::files::ArchiveWriteMode::update;
CopyProgress progress;
progress.writingArchive=true;
progress.from=sources.size()==1?sources.front():sources.front().parent_path();
progress.to=archive;
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(103),owner,
copyProgressDialog,reinterpret_cast<LPARAM>(&progress));
progress.window=dialog.window();
if(!progress.window)
{
setStatus(L"Could not open archive progress.");
return;
}
copyInProgress=true;
activeCopy=&progress;
dialog.show();
bool committed=false;
std::wstring failure;
try
{
progress.ui.run(progress.window,progress.canceled,[&] {
ks::files::writeArchive(archive,mode,directory,sources,[&](uint64_t done,uint64_t total) {
progress.totalBytes=total;
reportCopyProgress(progress,done,total);
return !progress.canceled;
});
committed=true;
});
}
catch(const std::system_error &error)
{
if(error.code().value()!=ERROR_CANCELLED) failure=fileError(error);
}
catch(const std::exception &error) {failure=ks::wide(error.what());}
dialog.close();
activeCopy=nullptr;
copyInProgress=false;
if(progress.closeOwner)
{
PostMessageW(owner,WM_CLOSE,0,0);
return;
}
if(committed)
{
if(!updating)
{
open(panel,panel.directory);
selectPanelPath(panel,archive);
}
for(auto &view:panels)
{
std::error_code error;
if(view.archive && fs::equivalent(view.archive->file,archive,error)) refreshArchive(view);
}
setStatus(updating?L"Archive updated.":L"Archive created.");
}
else if(failure.empty()) setStatus(L"Archive operation canceled.");
else
{
showFileOperationError(owner,updating?L"Archive update failed":L"Archive creation failed",failure);
setStatus(failure);
}
}
void createArchive(HWND owner,Panel &panel)
{
if(panel.peer || panel.ftp || panel.archive || !panel.directory.is_absolute())
{
setStatus(L"Open a local folder to create an archive.");
return;
}
if(panel.scanRequest)
{
setStatus(L"Wait for the panel to finish reading.");
return;
}
const auto selection=selectedPanelPaths(panel);
if(selection.empty())
{
setStatus(L"Select files or folders to pack.");
return;
}
auto stem=(selection.size()==1?selection.front().stem():panel.directory.filename()).wstring();
if(stem.empty()) stem=L"Archive";
auto name=stem+L".zip";
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(120),owner,
archiveNameDialog,reinterpret_cast<LPARAM>(&name))!=IDOK) return;
performArchiveWrite(owner,panel,panel.directory/name,ks::files::ArchiveWriteMode::create,{},selection);
}
void addToArchive(HWND owner,Panel &panel,std::vector<fs::path> sources)
{
if(sources.empty())
{
setStatus(L"Select local files or folders to add.");
return;
}
if(panel.scanRequest || !panel.archive)
{
setStatus(L"Wait for the archive panel to finish reading.");
return;
}
const auto file=panel.archive->file;
auto directory=panel.directory.lexically_relative(file);
if(directory==L".") directory.clear();
const auto question=L"Add the selected items to "+file.filename().native()+L"?\r\nMatching files will be replaced.";
if(showFilesNotice(owner,question.c_str(),L"Add to archive",{.confirm=true})!=IDYES) return;
performArchiveWrite(owner,panel,file,ks::files::ArchiveWriteMode::update,directory,sources);
}
+86
View File
@@ -0,0 +1,86 @@
constexpr DWORD columnFileShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
std::optional<FILE_STANDARD_INFO> fileStorageInformation(HANDLE file)
{
FILE_STANDARD_INFO result{};
if(GetFileInformationByHandleEx(file,FileStandardInfo,&result,sizeof(result))) return result;
return {};
}
std::optional<uint64_t> allocatedFileBytes(HANDLE file,DWORD attributes,
const std::optional<FILE_STANDARD_INFO> &metadata)
{
if(attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)) return {};
if(attributes&(FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE))
{
FILE_COMPRESSION_INFO compression{};
if(GetFileInformationByHandleEx(file,FileCompressionInfo,&compression,sizeof(compression)) &&
compression.CompressedFileSize.QuadPart>=0)
return static_cast<uint64_t>(compression.CompressedFileSize.QuadPart);
return {};
}
if(metadata && !metadata->Directory && metadata->AllocationSize.QuadPart>=0)
return static_cast<uint64_t>(metadata->AllocationSize.QuadPart);
return {};
}
std::optional<uint64_t> allocatedFileBytes(const fs::path &path,DWORD attributes)
{
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,columnFileShare,nullptr,
OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return {};
const auto metadata=(attributes&(FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE))?
std::optional<FILE_STANDARD_INFO>{}:fileStorageInformation(file.value);
return allocatedFileBytes(file.value,attributes,metadata);
}
std::wstring localOwnerName(const fs::path &path,std::map<std::wstring,std::wstring> &owners)
{
const Handle file{CreateFileW(path.c_str(),READ_CONTROL,columnFileShare,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return {};
PSECURITY_DESCRIPTOR descriptor=nullptr;
PSID owner=nullptr;
const auto result=GetSecurityInfo(file.value,SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION,&owner,
nullptr,nullptr,nullptr,&descriptor);
const std::unique_ptr<void,decltype(&LocalFree)> security(descriptor,LocalFree);
if(result!=ERROR_SUCCESS || !owner) return {};
wchar_t *sidText=nullptr;
if(!ConvertSidToStringSidW(owner,&sidText)) return {};
const std::unique_ptr<void,decltype(&LocalFree)> sid(sidText,LocalFree);
if(const auto existing=owners.find(sidText);existing!=owners.end()) return existing->second;
wchar_t name[256]{},domain[256]{};
DWORD nameLength=static_cast<DWORD>(std::size(name)),domainLength=static_cast<DWORD>(std::size(domain));
SID_NAME_USE use{};
std::wstring label=sidText;
if(LookupAccountSidW(nullptr,owner,name,&nameLength,domain,&domainLength,&use))
label=*domain?std::wstring(domain)+L"\\"+name:name;
owners.emplace(sidText,label);
return label;
}
void readLocalColumnMetadata(Panel::ScanResult &result,DWORD mask,std::stop_token stop)
{
std::map<std::wstring,std::wstring> owners;
for(const auto &entry:result.ordered)
{
if(stop.stop_requested()) return;
const auto attributes=result.metadata.at(entry.path).attributes;
ColumnMetadata data;
if(mask&(columnMask(allocationColumn)|columnMask(linkColumn)))
{
const Handle file{CreateFileW(entry.path.c_str(),FILE_READ_ATTRIBUTES,columnFileShare,nullptr,
OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value!=INVALID_HANDLE_VALUE)
{
const auto information=fileStorageInformation(file.value);
if((mask&columnMask(linkColumn)) && information) data.links=information->NumberOfLinks;
if(mask&columnMask(allocationColumn)) data.allocated=allocatedFileBytes(file.value,attributes,information);
}
}
if(mask&columnMask(ownerColumn)) data.owner=localOwnerName(entry.path,owners);
if(!data.owner.empty() || data.allocated || data.links)
result.columnMetadata.emplace(entry.path,std::move(data));
}
}
+6 -55
View File
@@ -1,5 +1,3 @@
constexpr std::array<WORD,2> defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MAKEWORD(VK_F8,HOTKEYF_ALT)};
auto commandHistoryKeys=defaultHistoryKeys;
constexpr size_t commandHistoryLimit=1000;
std::wstring commandHistoryLabel(const std::wstring &command)
@@ -19,41 +17,6 @@ std::wstring commandHistoryLabel(const std::wstring &command)
return fs::path(path).is_absolute()?path:command;
}
bool validHistoryKeys(const std::array<WORD,2> &keys)
{
if(keys[0]==keys[1]) return false;
return std::all_of(keys.begin(),keys.end(),[](WORD binding)
{
const auto key=LOBYTE(binding), modifiers=HIBYTE(binding);
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!='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;
});
}
std::array<WORD,2> optionHistoryKeys(HWND dialog)
{
return {static_cast<WORD>(SendDlgItemMessageW(dialog,321,HKM_GETHOTKEY,0,0)),
static_cast<WORD>(SendDlgItemMessageW(dialog,323,HKM_GETHOTKEY,0,0))};
}
void setOptionHistoryKeys(HWND dialog,const std::array<WORD,2> &keys)
{
SendDlgItemMessageW(dialog,321,HKM_SETHOTKEY,keys[0],0);
SendDlgItemMessageW(dialog,323,HKM_SETHOTKEY,keys[1],0);
}
void loadCommandHistoryKeys()
{
const std::array<WORD,2> keys{static_cast<WORD>(preference(L"PreviousCommandKey",defaultHistoryKeys[0])),
static_cast<WORD>(preference(L"CommandHistoryKey",defaultHistoryKeys[1]))};
commandHistoryKeys=validHistoryKeys(keys)?keys:defaultHistoryKeys;
}
void loadCommandHistory()
{
@@ -95,27 +58,15 @@ void rememberCommand(const std::wstring &command)
void recallCommand(size_t index)
{
terminalHistoryIndex=index;
SetWindowTextW(terminalInput,index<terminalHistory.size()?terminalHistory[index].command.c_str():L"");
SetWindowTextW(terminalInput,index<terminalHistory.size()?terminalHistory[index].command.c_str():terminalHistoryDraft.c_str());
SetFocus(terminalInput);
SendMessageW(terminalInput,EM_SETSEL,-2,-1);
suppressCurrentCompletion();
}
void showCommandHistory(HWND owner);
bool handleCommandHistoryKey(HWND window,const MSG &message)
void recallPreviousCommand()
{
if(message.message!=WM_KEYDOWN && message.message!=WM_SYSKEYDOWN) return false;
if((GetKeyState(VK_LWIN)&0x8000) || (GetKeyState(VK_RWIN)&0x8000)) return false;
const BYTE modifiers=((GetKeyState(VK_CONTROL)&0x8000)?HOTKEYF_CONTROL:0) |
((GetKeyState(VK_MENU)&0x8000)?HOTKEYF_ALT:0) | ((GetKeyState(VK_SHIFT)&0x8000)?HOTKEYF_SHIFT:0);
const auto binding=MAKEWORD(message.wParam,modifiers);
if(binding==commandHistoryKeys[0] && (message.hwnd==terminalInput ||
message.hwnd==panels[0].list || message.hwnd==panels[1].list))
{
if(terminalHistoryIndex) recallCommand(terminalHistoryIndex-1);
return true;
}
if(binding!=commandHistoryKeys[1]) return false;
if(!(message.lParam&(1LL<<30))) showCommandHistory(window);
return true;
if(!terminalHistoryIndex) return;
if(terminalHistoryIndex==terminalHistory.size()) terminalHistoryDraft=terminalInputText();
recallCommand(terminalHistoryIndex-1);
}
+595 -176
View File
File diff suppressed because it is too large. Load diff
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include <algorithm>
#include <string>
#include <string_view>
#include <vector>
namespace ks::files
{
enum class ComparisonEnding { absent, crlf, lf, cr };
inline std::wstring_view comparisonEndingText(ComparisonEnding ending)
{
switch(ending)
{
case ComparisonEnding::crlf: return L"\r\n";
case ComparisonEnding::lf: return L"\n";
case ComparisonEnding::cr: return L"\r";
default: return {};
}
}
struct ComparisonText
{
std::vector<std::wstring> lines;
std::vector<ComparisonEnding> endings;
ComparisonEnding preferred=ComparisonEnding::crlf;
std::wstring joined() const
{
std::wstring result;
for(size_t i=0;i<lines.size();++i)
{
result+=lines[i];
if(i+1<lines.size())
result+=comparisonEndingText(endings[i]==ComparisonEnding::absent?preferred:endings[i]);
}
return result;
}
};
inline ComparisonText splitComparisonText(std::wstring_view contents)
{
ComparisonText result;
if(contents.empty()) return result;
size_t start=0;
while(true)
{
const auto end=contents.find_first_of(L"\r\n",start);
result.lines.emplace_back(contents.substr(start,end==contents.npos?end:end-start));
auto ending=ComparisonEnding::absent;
if(end!=contents.npos)
ending=contents[end]==L'\n'?ComparisonEnding::lf:
end+1<contents.size() && contents[end+1]==L'\n'?ComparisonEnding::crlf:ComparisonEnding::cr;
result.endings.push_back(ending);
if(ending==ComparisonEnding::absent) break;
if(result.endings.size()==1) result.preferred=ending;
start=end+(ending==ComparisonEnding::crlf?2:1);
}
return result;
}
struct ComparisonReplace
{
size_t start{}, count{};
std::vector<std::wstring> lines;
std::vector<ComparisonEnding> endings;
};
inline ComparisonReplace replaceComparisonText(ComparisonText &document,const ComparisonReplace &change)
{
const auto first=document.lines.begin()+change.start, last=first+change.count;
const auto firstEnding=document.endings.begin()+change.start, lastEnding=firstEnding+change.count;
ComparisonReplace reverse{change.start,change.lines.size(),{first,last},{firstEnding,lastEnding}};
document.lines.erase(first,last);
document.lines.insert(document.lines.begin()+change.start,change.lines.begin(),change.lines.end());
document.endings.erase(firstEnding,lastEnding);
document.endings.insert(document.endings.begin()+change.start,change.endings.begin(),change.endings.end());
return reverse;
}
}
+218
View File
@@ -0,0 +1,218 @@
struct ContextPopup
{
HMENU handle=CreatePopupMenu();
~ContextPopup(){if(handle) DestroyMenu(handle);}
};
struct ShellMenuMessages
{
Microsoft::WRL::ComPtr<IContextMenu2> second;
Microsoft::WRL::ComPtr<IContextMenu3> third;
};
LRESULT CALLBACK shellMenuMessage(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR data)
{
if(message==WM_INITMENUPOPUP || message==WM_MENUCHAR ||
((message==WM_DRAWITEM || message==WM_MEASUREITEM) && !wp))
{
const auto &menu=*reinterpret_cast<const ShellMenuMessages*>(data);
LRESULT result{};
if(menu.third && menu.third->HandleMenuMsg2(message,wp,lp,&result)==S_OK) return result;
if(menu.second && message!=WM_MENUCHAR && menu.second->HandleMenuMsg(message,wp,lp)==S_OK)
return message==WM_DRAWITEM || message==WM_MEASUREITEM;
}
return DefSubclassProc(window,message,wp,lp);
}
enum class ShellPanelMenuResult { unavailable, canceled, invoked, rename, failed };
ShellPanelMenuResult showShellPanelMenu(HWND owner,const fs::path &directory,const fs::path &item,POINT screen)
{
const auto &path=item.empty()?directory:item;
PIDLIST_ABSOLUTE raw{};
if(FAILED(SHParseDisplayName(path.c_str(),nullptr,&raw,0,nullptr)) || !raw) return ShellPanelMenuResult::unavailable;
const std::unique_ptr<ITEMIDLIST,decltype(&CoTaskMemFree)> id(raw,CoTaskMemFree);
Microsoft::WRL::ComPtr<IShellFolder> folder;
Microsoft::WRL::ComPtr<IContextMenu> menu;
if(item.empty())
{
Microsoft::WRL::ComPtr<IShellFolder> desktop;
if(FAILED(SHGetDesktopFolder(desktop.GetAddressOf())) ||
FAILED(desktop->BindToObject(id.get(),nullptr,IID_PPV_ARGS(folder.GetAddressOf()))) ||
FAILED(folder->CreateViewObject(owner,IID_PPV_ARGS(menu.GetAddressOf()))))
return ShellPanelMenuResult::unavailable;
}
else
{
PCUITEMID_CHILD child{};
if(FAILED(SHBindToParent(id.get(),IID_PPV_ARGS(folder.GetAddressOf()),&child)) ||
FAILED(folder->GetUIObjectOf(owner,1,&child,IID_IContextMenu,nullptr,
reinterpret_cast<void**>(menu.GetAddressOf()))))
return ShellPanelMenuResult::unavailable;
}
ContextPopup popup;
const auto flags=item.empty()?CMF_NORMAL:CMF_NORMAL|CMF_CANRENAME;
constexpr UINT firstCommand=1,lastCommand=0x7fff;
if(!menu || !popup.handle || FAILED(menu->QueryContextMenu(popup.handle,0,firstCommand,lastCommand,flags)) ||
GetMenuItemCount(popup.handle)<=0) return ShellPanelMenuResult::unavailable;
ShellMenuMessages handler;
if(FAILED(menu.As(&handler.third))) menu.As(&handler.second);
constexpr UINT_PTR subclass=27;
if((handler.third || handler.second) &&
!SetWindowSubclass(owner,shellMenuMessage,subclass,reinterpret_cast<DWORD_PTR>(&handler)))
return ShellPanelMenuResult::unavailable;
const auto choice=static_cast<UINT>(TrackPopupMenuEx(popup.handle,TPM_RETURNCMD|TPM_RIGHTBUTTON,
screen.x,screen.y,owner,nullptr));
RemoveWindowSubclass(owner,shellMenuMessage,subclass);
if(choice<firstCommand || choice>lastCommand) return ShellPanelMenuResult::canceled;
const auto verb=choice-firstCommand;
wchar_t name[64]{};
if(SUCCEEDED(menu->GetCommandString(verb,GCS_VERBW,nullptr,reinterpret_cast<LPSTR>(name),std::size(name))))
{
if(!item.empty() && lstrcmpiW(name,L"rename")==0) return ShellPanelMenuResult::rename;
if(item.empty() && lstrcmpiW(name,L"refresh")==0) return ShellPanelMenuResult::invoked;
}
CMINVOKECOMMANDINFOEX request{sizeof(request)};
request.fMask=CMIC_MASK_UNICODE|CMIC_MASK_NOASYNC|CMIC_MASK_PTINVOKE;
request.hwnd=owner;
request.lpVerb=MAKEINTRESOURCEA(verb);
request.lpVerbW=MAKEINTRESOURCEW(verb);
const auto working=item.empty()?directory:item.parent_path();
request.lpDirectoryW=working.c_str();
request.nShow=SW_SHOWNORMAL;
request.ptInvoke=screen;
const auto result=menu->InvokeCommand(reinterpret_cast<LPCMINVOKECOMMANDINFO>(&request));
if(result==E_ABORT || result==HRESULT_FROM_WIN32(ERROR_CANCELLED)) return ShellPanelMenuResult::canceled;
return SUCCEEDED(result)?ShellPanelMenuResult::invoked:ShellPanelMenuResult::failed;
}
void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen)
{
const auto owner=GetParent(panel.list);
ContextPopup popup;
if(!popup.handle) return;
constexpr UINT openItem=1,findItems=2,newProfile=3,properties=4;
const auto add=[&](UINT id,const wchar_t *label){AppendMenuW(popup.handle,MF_STRING,id,label);};
if(recentFolderList(panel))
{
if(row!=LB_ERR)
{
add(openItem,L"Open folder");
add(117,L"Remove from recent");
}
add(110,L"Refresh panel");
}
else if(panel.listing)
{
if(panel.listing->smb->server.empty())
{
if(row!=LB_ERR)
{
add(openItem,L"Connect");
add(112,L"Edit connection");
add(smbSignInCommand,L"Sign in");
add(117,L"Remove connection");
}
add(newProfile,L"New connection");
}
else if(row!=LB_ERR) add(openItem,L"Open share");
add(110,L"Refresh panel");
}
else if(transferProfileList(panel))
{
if(row!=LB_ERR)
{
add(openItem,L"Connect");
add(112,L"Edit connection");
}
add(newProfile,L"New connection");
}
else
{
if(row!=LB_ERR)
{
const bool folder=panel.sizes[row]==L"Folder";
if(folder || panel.findOrigin) add(openItem,folder?L"Open folder":L"Go to file");
if(!folder && remoteSearchActionAvailable(111)) add(111,L"View");
if(!folder && !panel.archive && remoteSearchActionAvailable(112)) add(112,L"Edit");
const auto &other=panels[1-active];
const bool localDestination=!other.peer && !other.ftp && !other.archive && !other.findOrigin;
const bool canCopy=panel.ftp || panel.archive?localDestination:!other.ftp && !other.archive && !other.findOrigin;
if(canCopy && !other.directory.empty() && remoteSearchActionAvailable(113))
add(113,panel.archive?L"Extract":L"Copy");
if(!panel.archive && (panel.ftp || canCopy) && remoteSearchActionAvailable(114))
add(114,panel.ftp?L"Rename":L"Move");
if(!panel.archive && remoteSearchActionAvailable(117)) add(117,L"Delete");
if(panelItemPropertiesAvailable(panel)) add(properties,L"Properties");
}
else if(!panel.findOrigin && !panel.archive && !panel.directory.empty()) add(115,L"Make folder");
if(!panel.archive && !panel.directory.empty()) add(findItems,L"Find files");
add(110,L"Refresh panel");
}
const auto command=static_cast<UINT>(TrackPopupMenuEx(popup.handle,TPM_RETURNCMD|TPM_RIGHTBUTTON,
screen.x,screen.y,owner,nullptr));
if(command==openItem) enter(panel);
else if(command==findItems) findPanelFiles(owner,panel);
else if(command==newProfile)
{
if(panel.listing) editSmbProfile(panel,true);
else editTransferProfile(panel,true);
}
else if(command==properties) showPanelItemProperties(owner,panel);
else if(command) SendMessageW(owner,WM_COMMAND,MAKEWPARAM(command,BN_CLICKED),0);
}
void showPanelContextMenu(HWND list,LPARAM position)
{
const auto index=GetDlgCtrlID(list)-102;
if(index<0 || index>=static_cast<int>(std::size(panels)) || terminalVisible || !IsWindowVisible(list)) return;
const auto owner=GetParent(list);
if(!commandLineAvailable(owner)) return;
auto &panel=panels[index];
RECT bounds{};
GetClientRect(list,&bounds);
POINT client{};
LRESULT hit=LB_ERR;
if(position==-1)
{
hit=currentPanelRow(panel);
RECT rowBounds{};
if(hit!=LB_ERR && SendMessageW(list,LB_GETITEMRECT,hit,reinterpret_cast<LPARAM>(&rowBounds))!=LB_ERR)
client.y=std::clamp(rowBounds.bottom,0L,std::max(0L,bounds.bottom-1));
client.x=std::min(2L*cellWidth,std::max(0L,bounds.right-1));
}
else
{
client={GET_X_LPARAM(position),GET_Y_LPARAM(position)};
ScreenToClient(list,&client);
if(!PtInRect(&bounds,client)) return;
hit=panelRowAt(list,client,SendMessageW(list,LB_GETTOPINDEX,0,0),panel.rows.size());
if(hit!=LB_ERR)
{
const auto previous=currentPanelRow(panel);
SendMessageW(list,LB_SETCURSEL,hit,0);
invalidatePanelCursorChange(list,previous);
}
}
activatePanel(index);
closePanelSearch();
panelClipboardContext=true;
clearTerminalSelection();
SetFocus(list);
POINT screen=client;
ClientToScreen(list,&screen);
const auto row=hit!=LB_ERR && panel.sizes[hit]!=L"Up"?hit:LB_ERR;
const auto directory=panel.directory;
const auto item=row==LB_ERR?fs::path{}:panel.rows[row];
const bool shell=!panel.peer && !panel.ftp && !panel.archive && !directory.empty() &&
!windowsNetworkPath(directory);
const auto result=shell?showShellPanelMenu(owner,directory,item,screen):ShellPanelMenuResult::unavailable;
if(result==ShellPanelMenuResult::unavailable) showFilesPanelContext(panel,row,screen);
else if(result==ShellPanelMenuResult::rename)
copySelection(owner,panel,panel,true,{item},item.parent_path(),true);
else if(result==ShellPanelMenuResult::invoked && IsWindow(owner) && panel.directory==directory &&
!panel.peer && !panel.ftp && !panel.archive) refreshPanel(panel);
else if(result==ShellPanelMenuResult::failed) setStatus(L"Windows could not complete the Shell command.");
if(IsWindow(owner)) restoreCommandFocus();
}
+97
View File
@@ -0,0 +1,97 @@
struct CopyOptionsPrompt
{
CopyOptions value;
bool permissions{}, move{}, unixDest{};
};
INT_PTR CALLBACK copyOptionsDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int mask=640, paths=641, time=642, permissions=643, footer=644, folderLabel=646, hint=647;
if(message==WM_DRAWITEM)
{
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT*>(lp),RGB(192,192,192),RGB(0,0,0),true);
return TRUE;
}
if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Copy/Move options ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
{
const auto &prompt=*reinterpret_cast<const CopyOptionsPrompt*>(lp);
SetWindowLongPtrW(window,DWLP_USER,lp);
prepareCopyDialog(window);
layoutDialogContent(window,645);
fitFarEditToLine(GetDlgItem(window,mask));
installFarCheckbox(GetDlgItem(window,time),FarCheckboxSurface::gray);
installFarCheckbox(GetDlgItem(window,permissions),FarCheckboxSurface::gray);
for(const auto id:{time,permissions})
SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
layoutDialogButtons(window,footer,{IDOK,IDCANCEL});
CheckDlgButton(window,time,prompt.value.preserveTime?BST_CHECKED:BST_UNCHECKED);
CheckDlgButton(window,permissions,prompt.value.preservePermissions?BST_CHECKED:BST_UNCHECKED);
EnableWindow(GetDlgItem(window,permissions),prompt.permissions);
SetDlgItemTextW(window,mask,prompt.value.mask.c_str());
SendDlgItemMessageW(window,mask,EM_SETLIMITTEXT,255,0);
SendDlgItemMessageW(window,paths,EM_SETLIMITTEXT,32767,0);
std::wstring lines;
for(const auto &path:prompt.value.additional)
{
if(!lines.empty()) lines+=L"\r\n";
lines+=path.native();
}
SetDlgItemTextW(window,paths,lines.c_str());
if(prompt.unixDest) SetDlgItemTextW(window,folderLabel,L"Additional &folders on this server (one absolute path per line)");
if(prompt.move) SetDlgItemTextW(window,hint,L"Move keeps the source until every requested copy succeeds.");
SetFocus(GetDlgItem(window,mask));
SendDlgItemMessageW(window,mask,EM_SETSEL,0,-1);
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(window,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &prompt=*reinterpret_cast<CopyOptionsPrompt*>(GetWindowLongPtrW(window,DWLP_USER));
const auto text=[&](int id) {
auto control=GetDlgItem(window,id);
std::wstring value(GetWindowTextLengthW(control)+1,L'\0');
value.resize(GetWindowTextW(control,value.data(),static_cast<int>(value.size())));
return value;
};
auto pattern=text(mask);
if(pattern.find_first_of(L"/\\:")!=pattern.npos)
{
showFilesNotice(window,L"Enter a file name or mask without a path.",L"Copy/Move options");
SetFocus(GetDlgItem(window,mask));
return TRUE;
}
const auto entered=text(paths);
std::vector<fs::path> folders;
for(size_t start=0;start<entered.size();)
{
const auto end=entered.find(L'\n',start);
auto line=std::wstring_view(entered).substr(start,end==entered.npos?end:end-start);
if(!line.empty() && line.back()==L'\r') line.remove_suffix(1);
if(!line.empty())
{
auto path=fs::path(line);
const bool unc=!prompt.unixDest && (line.starts_with(L"\\\\") || line.starts_with(L"//"));
const bool absolute=prompt.unixDest?line.front()==L'/':path.is_absolute() || unc;
if(!absolute || line.find_first_of(L"<>|?*")!=line.npos || line.starts_with(L"\\\\.\\"))
{
showFilesNotice(window,L"Enter one absolute destination folder per line.",L"Copy/Move options");
SetFocus(GetDlgItem(window,paths));
return TRUE;
}
if(!unc) path=path.lexically_normal();
folders.push_back(folderPathWithoutSeparator(std::move(path)));
}
if(end==entered.npos) break;
start=end+1;
}
prompt.value={pattern.empty()?L"*":std::move(pattern),std::move(folders),
IsDlgButtonChecked(window,time)==BST_CHECKED,
prompt.permissions && IsDlgButtonChecked(window,permissions)==BST_CHECKED};
FilesModalDialog::finish(window,IDOK);
return TRUE;
}
+15 -4
View File
@@ -1,3 +1,5 @@
bool handleFilesHelpMessage(const MSG &message);
HWND activeFilesDialog{};
HHOOK filesDialogMouseHook{};
@@ -53,9 +55,10 @@ class FilesModalDialog
{
public:
FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument,
bool watchOutsideClicks=true)
bool watchOutsideClicks=true,bool fitToOwner=true)
: owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument),
watchOutsideClicks_(watchOutsideClicks)
resource_(IS_INTRESOURCE(resource)?static_cast<unsigned>(reinterpret_cast<ULONG_PTR>(resource)):0),
watchOutsideClicks_(watchOutsideClicks),fitToOwner_(fitToOwner)
{
window_=CreateDialogParamW(instance,resource,owner,dispatchDialog,reinterpret_cast<LPARAM>(this));
}
@@ -66,6 +69,12 @@ public:
HWND window() const { return window_; }
static unsigned resourceFor(HWND window)
{
const auto *state=reinterpret_cast<const FilesModalDialog*>(GetPropW(window,stateProperty_));
return state?state->resource_:0;
}
static HWND activeFor(HWND owner)
{
const auto root=GetAncestor(owner,GA_ROOTOWNER);
@@ -111,7 +120,7 @@ public:
activeFilesDialog=window_;
entered_=true;
refreshMouseHook();
if(GetWindowRect(owner_,&ownerBounds_))
if(fitToOwner_ && GetWindowRect(owner_,&ownerBounds_))
{
if(!layout_) captureLayout();
SetWindowSubclass(owner_,trackOwner,reinterpret_cast<UINT_PTR>(this),reinterpret_cast<DWORD_PTR>(this));
@@ -146,6 +155,7 @@ public:
{
if(message.hwnd==dialog || IsChild(dialog,message.hwnd))
{
if(handleFilesHelpMessage(message)) return true;
if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)
{
SendMessageW(dialog,WM_COMMAND,IDCANCEL,0);
@@ -209,7 +219,8 @@ private:
DLGPROC procedure_;
LPARAM argument_;
INT_PTR result_=IDCANCEL;
bool entered_{},finished_{},watchOutsideClicks_;
unsigned resource_{};
bool entered_{},finished_{},watchOutsideClicks_,fitToOwner_;
static void refreshMouseHook()
{
+239
View File
@@ -0,0 +1,239 @@
constexpr UINT panelDropReady=WM_APP+33;
struct PanelDrop
{
HWND source{}, target{};
fs::path directory, destination;
std::vector<fs::path> paths;
};
std::optional<PanelDrop> pendingPanelDrop;
HWND draggingPanel{};
std::optional<POINT> panelDragStart;
bool localDropPanel(const Panel &panel)
{
return !panel.peer && !panel.ftp && !panel.findOrigin && !panel.archive && panel.directory.is_absolute();
}
LRESULT panelRowAt(HWND window,POINT point,LRESULT top,LRESULT count)
{
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,MAKELPARAM(point.x,point.y));
// LB_ITEMFROMPOINT only returns the low 16 bits of the row index.
constexpr LRESULT rowRange=1<<16;
auto row=(top&~(rowRange-1))|LOWORD(hit);
if(row<top) row+=rowRange;
RECT bounds{};
return !HIWORD(hit) && row>=0 && row<count &&
SendMessageW(window,LB_GETITEMRECT,row,reinterpret_cast<LPARAM>(&bounds))!=LB_ERR &&
PtInRect(&bounds,point)?row:LB_ERR;
}
FORMATETC fileDropFormat()
{
return {CF_HDROP,nullptr,DVASPECT_CONTENT,-1,TYMED_HGLOBAL};
}
template<class Interface,class Derived>
class DragInterface : public Interface
{
public:
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,void **out) override
{
if(!out) return E_POINTER;
*out=nullptr;
if(iid!=IID_IUnknown && iid!=__uuidof(Interface)) return E_NOINTERFACE;
*out=static_cast<Interface *>(this);
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE AddRef() override {return ++references;}
ULONG STDMETHODCALLTYPE Release() override
{
const auto count=--references;
if(!count) delete static_cast<Derived *>(this);
return count;
}
private:
ULONG references{1};
};
class PanelDropTarget final : public DragInterface<IDropTarget,PanelDropTarget>
{
public:
explicit PanelDropTarget(HWND window) : target(window) {}
HRESULT STDMETHODCALLTYPE DragEnter(IDataObject *data,DWORD,POINTL,DWORD *effect) override
{
auto format=fileDropFormat();
filesystem=data->QueryGetData(&format)==S_OK;
return updateEffect(effect);
}
HRESULT STDMETHODCALLTYPE DragOver(DWORD,POINTL,DWORD *effect) override
{
return updateEffect(effect);
}
HRESULT STDMETHODCALLTYPE DragLeave() override
{
filesystem=false;
return S_OK;
}
HRESULT STDMETHODCALLTYPE Drop(IDataObject *data,DWORD,POINTL location,DWORD *effect) override
{
updateEffect(effect);
filesystem=false;
if(*effect==DROPEFFECT_NONE) return S_OK;
*effect=DROPEFFECT_NONE;
auto format=fileDropFormat();
STGMEDIUM medium{};
if(FAILED(data->GetData(&format,&medium)))
{
setStatus(L"Could not read local paths from the drop.");
return S_OK;
}
std::vector<fs::path> paths;
try
{
if(medium.tymed==TYMED_HGLOBAL) paths=ks::fileDropPaths(medium.hGlobal);
}
catch(const std::exception &) {}
ReleaseStgMedium(&medium);
if(paths.empty())
{
setStatus(L"The drop contains no usable file or folder paths.");
return S_OK;
}
try
{
const auto &panel=panels[GetDlgCtrlID(target)-102];
POINT point{location.x,location.y};
ScreenToClient(target,&point);
const auto row=panelRowAt(target,point,SendMessageW(target,LB_GETTOPINDEX,0,0),
static_cast<LRESULT>(panel.rows.size()));
const auto &destination=row!=LB_ERR && panel.sizes[row]==L"Folder"?panel.rows[row]:panel.directory;
pendingPanelDrop=PanelDrop{draggingPanel,target,panel.directory,destination,std::move(paths)};
if(PostMessageW(GetParent(target),panelDropReady,0,0))
{
// Files performs the requested move after confirmation.
*effect=DROPEFFECT_COPY;
}
else pendingPanelDrop.reset();
}
catch(const std::exception &)
{
setStatus(L"Could not prepare the drop.");
}
return S_OK;
}
private:
HRESULT updateEffect(DWORD *effect)
{
const auto allowed=*effect;
*effect=DROPEFFECT_NONE;
if(!filesystem || !(allowed&DROPEFFECT_COPY))
setStatus(L"Drag files or folders from a Windows filesystem.");
else if(target==draggingPanel)
setStatus(L"Drop files onto the other panel.");
else if(!localDropPanel(panels[GetDlgCtrlID(target)-102]))
setStatus(L"Open a local folder in the destination panel before dropping files.");
else if(!copyInProgress && !pendingPanelDrop && !FilesModalDialog::activeFor(GetParent(target)))
*effect=DROPEFFECT_COPY;
return S_OK;
}
HWND target;
bool filesystem{};
};
class PanelDragSource final : public DragInterface<IDropSource,PanelDragSource>
{
public:
HRESULT STDMETHODCALLTYPE QueryContinueDrag(BOOL escape,DWORD keys) override
{
if(escape) return DRAGDROP_S_CANCEL;
return keys&MK_LBUTTON?S_OK:DRAGDROP_S_DROP;
}
HRESULT STDMETHODCALLTYPE GiveFeedback(DWORD) override {return DRAGDROP_S_USEDEFAULTCURSORS;}
};
void beginPanelDrag(HWND window)
{
auto &panel=panels[GetDlgCtrlID(window)-102];
if(!localDropPanel(panel))
{
setStatus(L"Drag files or folders from an open local folder.");
return;
}
auto paths=selectedPanelPaths(panel);
if(paths.empty()) return;
std::vector<PCIDLIST_ABSOLUTE> items;
items.reserve(paths.size());
const auto clear=[&](void *){for(auto item:items) CoTaskMemFree(const_cast<PIDLIST_ABSOLUTE>(item));};
const std::unique_ptr<void,decltype(clear)> cleanup(&items,clear);
for(const auto &path:paths)
{
PIDLIST_ABSOLUTE item{};
if(FAILED(SHParseDisplayName(path.c_str(),nullptr,&item,0,nullptr)))
{
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
return;
}
items.push_back(item);
}
IShellItemArray *array{};
if(FAILED(SHCreateShellItemArrayFromIDLists(static_cast<UINT>(items.size()),items.data(),&array)))
{
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
return;
}
IDataObject *data{};
const auto result=array->BindToHandler(nullptr,BHID_DataObject,IID_PPV_ARGS(&data));
array->Release();
if(FAILED(result))
{
setStatus(L"Windows could not prepare the selected files or folders for dragging.");
return;
}
const auto source=new(std::nothrow) PanelDragSource;
if(source)
{
draggingPanel=window;
DWORD effect{};
DoDragDrop(data,source,DROPEFFECT_COPY,&effect);
draggingPanel=nullptr;
source->Release();
}
data->Release();
}
void performPanelDrop(HWND owner)
{
if(!pendingPanelDrop) return;
auto drop=std::move(*pendingPanelDrop);
pendingPanelDrop.reset();
auto index=GetDlgCtrlID(drop.target)-102;
if(index<0 || index>=static_cast<int>(std::size(panels))) return;
auto &panel=panels[index];
if(!localDropPanel(panel) || panel.directory!=drop.directory || !IsWindowVisible(drop.target))
{
setStatus(L"The destination panel changed. Drop the files again.");
return;
}
if(copyInProgress || FilesModalDialog::activeFor(owner))
{
setStatus(L"Finish the current operation before dropping files.");
return;
}
const auto text=L"Destination folder:\r\n"+drop.destination.native();
const auto answer=showFilesNotice(owner,text.c_str(),L"Drop files",
{.tone=FilesNoticeTone::neutral,.chooseTransfer=true});
if(answer!=IDYES && answer!=IDNO) return;
auto &source=drop.source?panels[GetDlgCtrlID(drop.source)-102]:panel;
activatePanel(index);
panelClipboardContext=true;
copySelection(owner,source,panel,answer==IDNO,std::move(drop.paths),std::move(drop.destination));
}
+418
View File
@@ -0,0 +1,418 @@
enum class EnvironmentScope { user, system, process };
constexpr wchar_t userEnvironmentPath[]=L"Environment";
constexpr wchar_t systemEnvironmentPath[]=L"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
constexpr unsigned environmentValueLimit=32767;
const wchar_t *environmentScopeName(EnvironmentScope scope)
{
switch(scope)
{
case EnvironmentScope::user: return L"User";
case EnvironmentScope::system: return L"System";
case EnvironmentScope::process: return L"Process";
}
return L"";
}
std::wstring environmentSource(EnvironmentScope scope)
{
if(scope==EnvironmentScope::process) return L"Current KSwitcher.Files process";
return scope==EnvironmentScope::user?L"HKCU\\"+std::wstring(userEnvironmentPath):
L"HKLM\\"+std::wstring(systemEnvironmentPath);
}
struct EnvironmentKey
{
HKEY value{};
explicit EnvironmentKey(EnvironmentScope scope,bool write=false)
{
const bool user=scope==EnvironmentScope::user;
const auto root=user?HKEY_CURRENT_USER:HKEY_LOCAL_MACHINE;
const auto path=user?userEnvironmentPath:systemEnvironmentPath;
const auto access=KEY_QUERY_VALUE|(write?KEY_SET_VALUE:0);
const auto result=user && write?
RegCreateKeyExW(root,path,0,nullptr,0,access,nullptr,&value,nullptr):
RegOpenKeyExW(root,path,0,access,&value);
if(result!=ERROR_SUCCESS && (result!=ERROR_FILE_NOT_FOUND || !user || write))
throw std::system_error(result,std::system_category(),"Open the environment registry key");
}
EnvironmentKey(const EnvironmentKey &)=delete;
~EnvironmentKey(){if(value) RegCloseKey(value);}
};
struct EnvironmentValue
{
DWORD type{};
std::wstring text;
bool supported{};
bool operator==(const EnvironmentValue &) const = default;
};
struct EnvironmentVariable
{
std::wstring name;
EnvironmentValue value;
};
std::optional<EnvironmentValue> readEnvironmentValue(HKEY key,const std::wstring &name)
{
if(!key) return {};
DWORD size{},type{};
auto result=RegQueryValueExW(key,name.c_str(),nullptr,&type,nullptr,&size);
if(result==ERROR_FILE_NOT_FOUND) return {};
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"Read the environment definition");
for(int attempt=0;attempt<4;++attempt)
{
if(type!=REG_SZ && type!=REG_EXPAND_SZ) return EnvironmentValue{type,{},false};
if(size%sizeof(wchar_t) || size>2*(environmentValueLimit+1))
return EnvironmentValue{type,{},false};
std::wstring text(size/sizeof(wchar_t)+1,L'\0');
result=RegQueryValueExW(key,name.c_str(),nullptr,&type,reinterpret_cast<BYTE*>(text.data()),&size);
if(result==ERROR_FILE_NOT_FOUND) return {};
if(result==ERROR_MORE_DATA) continue;
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"Read the environment definition");
if((type!=REG_SZ && type!=REG_EXPAND_SZ) || size%sizeof(wchar_t))
return EnvironmentValue{type,{},false};
text.resize(size/sizeof(wchar_t));
while(!text.empty() && text.back()==L'\0') text.pop_back();
if(text.find(L'\0')!=text.npos) return EnvironmentValue{type,{},false};
return EnvironmentValue{type,std::move(text),true};
}
throw std::runtime_error("The environment definition changed while Windows was reading it.");
}
std::vector<EnvironmentVariable> readEnvironmentScope(EnvironmentScope scope)
{
std::vector<EnvironmentVariable> entries;
if(scope==EnvironmentScope::process)
{
const auto block=GetEnvironmentStringsW();
if(!block) throw std::system_error(GetLastError(),std::system_category(),"Read the current process environment");
const std::unique_ptr<wchar_t,decltype(&FreeEnvironmentStringsW)> owned(block,FreeEnvironmentStringsW);
for(auto offset=block;*offset;)
{
const std::wstring_view line=offset;
const auto equals=line.find(L'=');
if(equals!=line.npos && equals>0)
entries.push_back({std::wstring(line.substr(0,equals)),{REG_SZ,std::wstring(line.substr(equals+1)),true}});
offset+=line.size()+1;
}
}
else
{
const EnvironmentKey key(scope);
if(!key.value) return {};
std::vector<wchar_t> name(16384);
for(DWORD index=0;;++index)
{
DWORD length=static_cast<DWORD>(name.size());
const auto result=RegEnumValueW(key.value,index,name.data(),&length,nullptr,nullptr,nullptr,nullptr);
if(result==ERROR_NO_MORE_ITEMS) break;
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"List environment definitions");
if(!length) continue;
std::wstring label(name.data(),length);
if(label.find(L'=')!=label.npos) continue;
if(auto value=readEnvironmentValue(key.value,label);value && value->supported)
entries.push_back({std::move(label),std::move(*value)});
}
}
std::sort(entries.begin(),entries.end(),[](const auto &left,const auto &right) {
return CompareStringOrdinal(left.name.c_str(),-1,right.name.c_str(),-1,TRUE)==CSTR_LESS_THAN;
});
return entries;
}
std::wstring expandedEnvironmentValue(EnvironmentScope scope,const EnvironmentValue &value)
{
if(value.type!=REG_EXPAND_SZ) return value.text;
Handle token{};
if(scope==EnvironmentScope::user &&
!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_IMPERSONATE|TOKEN_DUPLICATE,&token.value))
throw std::system_error(GetLastError(),std::system_category(),"Open the current user's environment");
std::wstring expanded(environmentValueLimit+1,L'\0');
if(!ExpandEnvironmentStringsForUserW(token.value,value.text.c_str(),expanded.data(),static_cast<DWORD>(expanded.size())))
throw std::system_error(GetLastError(),std::system_category(),"Expand the environment definition");
expanded.resize(wcslen(expanded.c_str()));
return expanded;
}
void writeEnvironmentValue(EnvironmentScope scope,const std::wstring &name,const EnvironmentValue &replacement,
const std::optional<EnvironmentValue> &expected)
{
if(scope==EnvironmentScope::process) throw std::runtime_error("The current process environment is read-only here.");
if(replacement.text.size()>environmentValueLimit) throw std::runtime_error("The value exceeds the Windows environment limit.");
const EnvironmentKey key(scope,true);
if(readEnvironmentValue(key.value,name)!=expected)
throw std::runtime_error("Windows changed this definition while it was open. Reload and review the current value.");
if(expected==replacement) return;
const auto bytes=static_cast<DWORD>((replacement.text.size()+1)*sizeof(wchar_t));
const auto result=RegSetValueExW(key.value,name.c_str(),0,replacement.type,
reinterpret_cast<const BYTE*>(replacement.text.c_str()),bytes);
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"Save the environment definition");
try
{
std::thread([] {
DWORD_PTR reply{};
SendMessageTimeoutW(HWND_BROADCAST,WM_SETTINGCHANGE,0,reinterpret_cast<LPARAM>(L"Environment"),
SMTO_ABORTIFHUNG,250,&reply);
}).detach();
}
catch(const std::exception &) {}
}
const wchar_t *environmentValueType(const EnvironmentValue &value)
{
return value.type==REG_EXPAND_SZ?L"REG_EXPAND_SZ":L"REG_SZ";
}
struct EnvironmentEdit
{
EnvironmentScope scope;
EnvironmentVariable original;
std::wstring replacement;
};
INT_PTR CALLBACK environmentEditDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int label=630,body=632,footer=633;
if(message==WM_INITDIALOG)
{
const auto &editor=*reinterpret_cast<const EnvironmentEdit *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,label);
const auto title=editor.original.name+L" · "+environmentScopeName(editor.scope)+L" · "+
environmentValueType(editor.original.value);
SetDlgItemTextW(dialog,label,title.c_str());
SendDlgItemMessageW(dialog,body,EM_SETLIMITTEXT,environmentValueLimit,0);
SetDlgItemTextW(dialog,body,editor.original.value.text.c_str());
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(GetDlgItem(dialog,body));
return FALSE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
{
auto &editor=*reinterpret_cast<EnvironmentEdit *>(GetWindowLongPtrW(dialog,DWLP_USER));
editor.replacement=dialogFieldText(GetDlgItem(dialog,body));
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
return paintCopyDialog(dialog,message,wp,lp,L" Edit environment definition ",false,{footer});
}
constexpr int envScope=611,envList=612,envSource=613,envSelected=614,envRaw=615,envExpanded=616,
envStatus=617,envFooter=618,envEdit=622,envCopyUser=623,envCopySystem=624,envRefresh=625;
struct EnvironmentPanel
{
EnvironmentScope scope=EnvironmentScope::user;
std::vector<EnvironmentVariable> entries;
std::wstring readFailure,notice;
};
std::wstring environmentErrorText(const std::exception &error)
{
if(const auto *system=dynamic_cast<const std::system_error *>(&error)) return fileError(*system);
return ks::wide(error.what());
}
const EnvironmentVariable *selectedEnvironmentVariable(HWND dialog,const EnvironmentPanel &panel)
{
const auto row=SendDlgItemMessageW(dialog,envList,LB_GETCURSEL,0,0);
if(row<0) return nullptr;
const auto index=SendDlgItemMessageW(dialog,envList,LB_GETITEMDATA,row,0);
return index>=0 && static_cast<size_t>(index)<panel.entries.size()?&panel.entries[index]:nullptr;
}
void setEnvironmentDetails(HWND dialog,const EnvironmentPanel &panel)
{
const auto *entry=selectedEnvironmentVariable(dialog,panel);
const bool registry=panel.scope!=EnvironmentScope::process;
SetDlgItemTextW(dialog,envSource,environmentSource(panel.scope).c_str());
SetDlgItemTextW(dialog,envSelected,entry?(entry->name+L" · "+
(registry?environmentValueType(entry->value):L"Read-only")).c_str():L"");
SetDlgItemTextW(dialog,envRaw,entry?entry->value.text.c_str():L"");
std::wstring expanded;
if(entry)
{
try {expanded=expandedEnvironmentValue(panel.scope,entry->value);}
catch(const std::exception &error) {expanded=L"Unavailable · "+environmentErrorText(error);}
}
SetDlgItemTextW(dialog,envExpanded,expanded.c_str());
EnableWindow(GetDlgItem(dialog,envEdit),entry && registry);
EnableWindow(GetDlgItem(dialog,envCopyUser),entry && panel.scope!=EnvironmentScope::user);
EnableWindow(GetDlgItem(dialog,envCopySystem),entry && panel.scope!=EnvironmentScope::system);
const auto status=!panel.readFailure.empty()?panel.readFailure:!panel.notice.empty()?panel.notice:
!entry?std::wstring(L"No environment variables in this scope."):
registry?L"Existing PowerShell sessions keep their environment. Restart Files for embedded PowerShell.":
L"These values belong to the running Files process.";
SetDlgItemTextW(dialog,envStatus,status.c_str());
}
void reloadEnvironmentPanel(HWND dialog,EnvironmentPanel &panel,const std::wstring &preferred={})
{
panel.readFailure.clear();
try {panel.entries=readEnvironmentScope(panel.scope);}
catch(const std::exception &error)
{
panel.entries.clear();
panel.readFailure=environmentErrorText(error);
}
const auto list=GetDlgItem(dialog,envList);
SendMessageW(list,WM_SETREDRAW,FALSE,0);
SendMessageW(list,LB_RESETCONTENT,0,0);
LRESULT selected=0;
for(size_t index=0;index<panel.entries.size();++index)
{
const auto &name=panel.entries[index].name;
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(name.c_str()));
if(row<0) continue;
SendMessageW(list,LB_SETITEMDATA,row,index);
if(CompareStringOrdinal(name.c_str(),-1,preferred.c_str(),-1,TRUE)==CSTR_EQUAL) selected=row;
}
if(!panel.entries.empty()) SendMessageW(list,LB_SETCURSEL,selected,0);
SendMessageW(list,WM_SETREDRAW,TRUE,0);
InvalidateRect(list,nullptr,TRUE);
setEnvironmentDetails(dialog,panel);
}
void saveEnvironmentDefinition(HWND dialog,EnvironmentPanel &panel,const EnvironmentVariable &entry,
std::optional<EnvironmentScope> copyTo={})
{
try
{
if(copyTo)
{
const EnvironmentKey key(*copyTo);
const auto previous=readEnvironmentValue(key.value,entry.name);
if(previous && !previous->supported)
throw std::runtime_error("The destination already has a registry value of an unsupported type.");
const auto question=previous?L"Replace "+entry.name+L" in "+environmentScopeName(*copyTo)+L"?":
L"Copy "+entry.name+L" to "+environmentScopeName(*copyTo)+L"?";
if(showFilesNotice(dialog,question.c_str(),L"Copy environment definition",
{.confirm=true,.tone=previous?FilesNoticeTone::warning:FilesNoticeTone::dialog})!=IDYES) return;
if(panel.scope!=EnvironmentScope::process)
{
const EnvironmentKey source(panel.scope);
if(readEnvironmentValue(source.value,entry.name)!=entry.value)
throw std::runtime_error("The source definition changed. Reload and review it before copying.");
}
writeEnvironmentValue(*copyTo,entry.name,entry.value,previous);
panel.scope=*copyTo;
SendDlgItemMessageW(dialog,envScope,CB_SETCURSEL,static_cast<WPARAM>(panel.scope),0);
}
else
{
if(panel.scope==EnvironmentScope::process) return;
EnvironmentEdit editor{panel.scope,entry};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(128),dialog,environmentEditDialog,
reinterpret_cast<LPARAM>(&editor))!=IDOK || editor.replacement==entry.value.text) return;
writeEnvironmentValue(panel.scope,entry.name,{entry.value.type,editor.replacement,true},entry.value);
}
panel.notice=L"Saved. Restart Files for embedded PowerShell to inherit the new value.";
}
catch(const std::exception &error)
{
panel.notice.clear();
const auto details=environmentErrorText(error);
showFilesNotice(dialog,details.c_str(),L"Could not save environment definition",{.tone=FilesNoticeTone::warning});
}
reloadEnvironmentPanel(dialog,panel,entry.name);
}
INT_PTR CALLBACK environmentPanelDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &panel=*reinterpret_cast<EnvironmentPanel *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,610);
const auto scope=GetDlgItem(dialog,envScope);
for(const auto item:{EnvironmentScope::user,EnvironmentScope::system,EnvironmentScope::process})
SendMessageW(scope,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(environmentScopeName(item)));
SendMessageW(scope,CB_SETCURSEL,0,0);
installFarCombo(scope,GetDlgItem(dialog,610));
const auto list=GetDlgItem(dialog,envList);
const auto bounds=dialogControlBounds(dialog,envList);
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,dialog);
layoutDialogButtons(dialog,envFooter,{envEdit,envCopyUser,envCopySystem,envRefresh,IDOK});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
reloadEnvironmentPanel(dialog,panel);
SetFocus(scope);
return FALSE;
}
auto *panel=reinterpret_cast<EnvironmentPanel *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!panel) return FALSE;
if(message==WM_DRAWITEM && wp==envScope)
{
drawFarComboRow(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
}
if(message==WM_CTLCOLORLISTBOX && reinterpret_cast<HWND>(lp)!=GetDlgItem(dialog,envList))
{
const auto dc=reinterpret_cast<HDC>(wp);
SetTextColor(dc,colors[Text]);
SetBkColor(dc,colors[Dialog]);
return reinterpret_cast<INT_PTR>(teal);
}
if(message==WM_COMMAND)
{
const auto id=LOWORD(wp),notification=HIWORD(wp);
if(id==envScope && (notification==CBN_SELENDOK ||
(notification==CBN_SELCHANGE && !SendDlgItemMessageW(dialog,envScope,CB_GETDROPPEDSTATE,0,0))))
{
const auto scope=SendDlgItemMessageW(dialog,envScope,CB_GETCURSEL,0,0);
if(scope>=0 && scope<=static_cast<LRESULT>(EnvironmentScope::process) &&
static_cast<EnvironmentScope>(scope)!=panel->scope)
{
const auto *entry=selectedEnvironmentVariable(dialog,*panel);
const auto selected=entry?entry->name:std::wstring{};
panel->scope=static_cast<EnvironmentScope>(scope);
reloadEnvironmentPanel(dialog,*panel,selected);
}
return TRUE;
}
if(id==envRefresh || (id==envList && notification==LBN_SELCHANGE))
{
if(id==envRefresh)
{
const auto *entry=selectedEnvironmentVariable(dialog,*panel);
const auto name=entry?entry->name:std::wstring{};
reloadEnvironmentPanel(dialog,*panel,name);
}
else setEnvironmentDetails(dialog,*panel);
return TRUE;
}
if(id==envEdit || id==envCopyUser || id==envCopySystem)
{
if(const auto *entry=selectedEnvironmentVariable(dialog,*panel))
saveEnvironmentDefinition(dialog,*panel,EnvironmentVariable(*entry),id==envEdit?std::nullopt:
std::optional(id==envCopyUser?EnvironmentScope::user:EnvironmentScope::system));
return TRUE;
}
if(id==IDOK || id==IDCANCEL)
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
}
if(message==WM_CLOSE) {FilesModalDialog::finish(dialog,IDCANCEL);return TRUE;}
return paintCopyDialog(dialog,message,wp,lp,L" Environment Variables ",false,{envFooter},false,GetDlgItem(dialog,envList));
}
void showEnvironmentPanel(HWND owner)
{
EnvironmentPanel panel;
FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(127),owner,environmentPanelDialog,
reinterpret_cast<LPARAM>(&panel));
}
+119
View File
@@ -0,0 +1,119 @@
constexpr int findMask=480, findHidden=481, findFooter=482, findLabel=483;
struct FileMaskPrompt
{
Panel::FindOptions options;
bool filter{};
};
INT_PTR CALLBACK fileMaskDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_DRAWITEM)
{
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),RGB(192,192,192),RGB(0,0,0),true);
return TRUE;
}
const auto *prompt=reinterpret_cast<const FileMaskPrompt *>(message==WM_INITDIALOG?lp:GetWindowLongPtrW(dialog,DWLP_USER));
const bool filter=prompt && prompt->filter;
const auto title=filter?L" Panel filter ":L" Find files ";
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,title,false,{findFooter}))
return painted;
if(message==WM_INITDIALOG)
{
const auto &options=prompt->options;
SetWindowLongPtrW(dialog,DWLP_USER,lp);
if(filter)
{
SetWindowTextW(dialog,L"Panel filter");
SetDlgItemTextW(dialog,findLabel,L"File &name or mask (blank clears)");
SetDlgItemTextW(dialog,findHidden,L"Show &hidden and system files");
SetDlgItemTextW(dialog,IDOK,L"&Apply");
}
prepareTextDialog(dialog);
layoutDialogContent(dialog,findLabel);
fitFarEditToLine(GetDlgItem(dialog,findMask));
for(const auto id:{IDOK,IDCANCEL})
{
const auto button=GetDlgItem(dialog,id);
SetWindowPos(button,nullptr,0,0,farDialogButtonWidth(button),textHeight,
SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
}
layoutDialogButtons(dialog,findFooter,{IDOK,IDCANCEL});
installFarCheckbox(GetDlgItem(dialog,findHidden),FarCheckboxSurface::gray);
SendDlgItemMessageW(dialog,findMask,EM_SETLIMITTEXT,255,0);
SetDlgItemTextW(dialog,findMask,options.mask.c_str());
CheckDlgButton(dialog,findHidden,options.includeHidden?BST_CHECKED:BST_UNCHECKED);
SetFocus(GetDlgItem(dialog,findMask));
SendDlgItemMessageW(dialog,findMask,EM_SETSEL,0,-1);
return FALSE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
{
auto &options=reinterpret_cast<FileMaskPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER))->options;
wchar_t mask[256]{};
GetDlgItemTextW(dialog,findMask,mask,static_cast<int>(std::size(mask)));
if(std::wstring_view(mask).find_first_of(L"/\\:")!=std::wstring_view::npos)
{
showFilesNotice(dialog,L"Enter a file name or mask without a path.",filter?L"Panel filter":L"Find files");
SetFocus(GetDlgItem(dialog,findMask));
return TRUE;
}
options.mask=*mask?mask:L"*";
options.includeHidden=IsDlgButtonChecked(dialog,findHidden)==BST_CHECKED;
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
return FALSE;
}
void startFileSearch(Panel &panel,Panel::FindOptions options)
{
if(panel.scanRequest) return;
cancelFolderSizes(panel);
panel.remoteRetry.reset();
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.peer=panel.peer,.statusRevision=statusRevision,
.ftp=panel.ftp,.find=std::move(options)};
startDirectoryScan(panel);
}
bool canFindFiles(const Panel &panel)
{
return !panel.archive && !panel.directory.empty() && !transferProfileList(panel);
}
void findPanelFiles(HWND owner,Panel &panel)
{
if(!canFindFiles(panel))
{
setStatus(L"Find files requires an open folder.");
return;
}
if(panel.scanRequest)
{
setStatus(L"Wait for the current scan to finish.");
return;
}
FileMaskPrompt prompt{panel.findOrigin?panel.findOrigin->options:Panel::FindOptions{}};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner,
fileMaskDialog,reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
startFileSearch(panel,std::move(prompt.options));
}
void editPanelFilter(HWND owner,Panel &panel)
{
if(!panelViewAvailable(panel)) return;
FileMaskPrompt prompt{{panel.view.mask,panel.view.showHidden},true};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner,
fileMaskDialog,reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
auto &options=prompt.options;
if(options.mask==L"*") options.mask.clear();
if(panel.view.mask==options.mask && panel.view.showHidden==options.includeHidden) return;
panel.view.mask=std::move(options.mask);
panel.view.showHidden=options.includeHidden;
updatePanelView(panel);
}
+111
View File
@@ -0,0 +1,111 @@
bool matchesFileMask(std::wstring_view name,std::wstring_view mask)
{
size_t fileIndex=0, maskIndex=0, star=mask.npos, afterStar=0;
while(fileIndex<name.size())
{
if(maskIndex<mask.size() && mask[maskIndex]==L'*')
{
star=maskIndex++;
afterStar=fileIndex;
}
else if(maskIndex<mask.size() &&
(mask[maskIndex]==L'?' || CompareStringOrdinal(name.data()+fileIndex,1,
mask.data()+maskIndex,1,TRUE)==CSTR_EQUAL))
{
++fileIndex;
++maskIndex;
}
else if(star!=mask.npos)
{
maskIndex=star+1;
fileIndex=++afterStar;
}
else return false;
}
return mask.find_first_not_of(L'*',maskIndex)==mask.npos;
}
std::unique_ptr<Panel::ScanResult> scanFileMatches(const Panel::ScanRequest &request,
std::atomic_size_t &entriesRead,std::stop_token stop)
{
auto result=std::make_unique<Panel::ScanResult>();
const bool remote=request.peer || request.ftp;
const auto walk=[&](const auto &listDirectory)
{
std::vector<fs::path> pending{request.directory};
size_t visited=0;
while(!pending.empty() && !stop.stop_requested())
{
const auto directory=std::move(pending.back());
pending.pop_back();
try
{
if(!listDirectory(directory,[&](const fs::path &path,const FileInfo &entry)
{
if(stop.stop_requested()) return false;
if(path.parent_path()!=folderPathWithoutSeparator(directory)) return true;
entriesRead.store(++visited,std::memory_order_relaxed);
const auto name=path.filename().native();
if(!request.find->includeHidden &&
((entry.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)) ||
(request.ftp && name.starts_with(L'.')))) return true;
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)
{
if(!(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) pending.push_back(path);
}
else if((!request.ftp || !(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) &&
matchesFileMask(name,request.find->mask) &&
result->metadata.emplace(path,FolderEntryMetadata{
entry.attributes,entry.size,entry.modified}).second)
{
result->files.push_back(path);
if(entry.transfer) result->columnMetadata[path].transfer=entry.transfer;
}
return true;
})) break;
}
catch(const std::system_error &error)
{
if(stop.stop_requested()) break;
const auto code=error.code().value();
if(remote && code!=ERROR_FILE_NOT_FOUND && code!=ERROR_PATH_NOT_FOUND &&
code!=ERROR_ACCESS_DENIED && code!=ERROR_DIRECTORY)
throw;
if(!remote && directory==request.directory)
{
result->failure=L"Cannot search folder: "+directory.native();
return;
}
result->error=ERROR_PARTIAL_COPY;
}
}
};
try
{
if(request.ftp)
{
TransferSession connection(*request.ftp,SftpAccess::normal,stop);
walk([&](const fs::path &directory,const FileVisitor &visit)
{
const auto error=connection.list(directory,visit,stop);
if(error==ERROR_CANCELLED) return false;
requireFileOperation(error==ERROR_SUCCESS || error==ERROR_NO_MORE_FILES,error);
return true;
});
}
else
{
FilesConnection connection(request.peer?&*request.peer:nullptr,stop);
walk([&](const fs::path &directory,const FileVisitor &visit){return listFiles(connection,directory,visit);});
}
}
catch(const std::exception &)
{
if(remote) result->error=ERROR_CONNECTION_ABORTED;
else if(!stop.stop_requested()) result->failure=L"Cannot search folder: "+request.directory.native();
}
if(stop.stop_requested()) result->error=ERROR_CANCELLED;
result->opened=result->failure.empty();
std::sort(result->files.begin(),result->files.end());
return result;
}
+13 -13
View File
@@ -27,25 +27,18 @@ bool saveFolderShortcuts(const FolderShortcuts &shortcuts)
{"name",ks::utf8(entry.peerName)},{"title",ks::utf8(entry.title)}});
groups.push_back(std::move(rows));
}
const auto data=groups.dump();
return data.size()<=1024*1024 &&
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
return writeFilesJsonPreference(folderShortcutsKey,groups);
}
catch(const std::exception &){return false;}
}
void loadFolderShortcuts()
{
DWORD bytes{};
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
!bytes || bytes>1024*1024) return;
std::string data(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
return;
const auto saved=readFilesJsonPreference(folderShortcutsKey);
if(!saved) return;
try
{
const auto groups=Json::parse(data.begin(),data.begin()+bytes);
const auto &groups=*saved;
if(!groups.is_array() || groups.size()!=folderShortcuts.size()) return;
FolderShortcuts loaded;
for(size_t digit=0;digit<loaded.size();++digit)
@@ -72,6 +65,13 @@ struct FolderShortcutEdit
std::optional<size_t> index;
};
std::wstring trimFilesField(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);
}
std::wstring shortcutField(HWND dialog,int id)
{
const auto field=GetDlgItem(dialog,id);
@@ -152,7 +152,7 @@ bool editFolderShortcut(HWND owner,FolderShortcutEdit &edit)
void addFolderShortcut(const Panel &panel,int digit)
{
if(panel.directory.empty() || panel.ftp) return;
if(panel.directory.empty() || panel.ftp || panel.archive) return;
FolderShortcutEdit edit{{panel.directory,panel.peer?panel.peer->id:"",
panel.peer?panel.peer->name:L""},digit,{}};
if(editFolderShortcut(GetParent(panel.list),edit))
@@ -358,7 +358,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
const auto &panel=*view->panel;
FolderShortcutEdit edit{{panel.directory,panel.peer?panel.peer->id:"",
panel.peer?panel.peer->name:L""},view->digit,{}};
if(!panel.directory.empty() && editFolderShortcut(dialog,edit))
if(!panel.directory.empty() && !panel.archive && editFolderShortcut(dialog,edit))
layoutQuickFolders(dialog,*view,static_cast<int>(group.size())-1);
SetFocus(GetDlgItem(dialog,shortcutList));
return TRUE;
+165 -36
View File
@@ -1,17 +1,76 @@
struct FtpProfile
enum class TransferProtocol { ftp, sftp };
constexpr unsigned defaultSftpPort=22;
const wchar_t *transferProtocolName(TransferProtocol protocol)
{
return protocol==TransferProtocol::sftp?L"SFTP":L"FTP";
}
struct TransferProfile
{
std::wstring name, host, user;
INTERNET_PORT port=INTERNET_DEFAULT_FTP_PORT;
ks::Bytes secret;
bool legacyNames{};
std::string id;
TransferProtocol protocol{};
fs::path privateKey;
std::string hostFingerprint;
std::string jumpProfile;
std::wstring sudoSftpServer;
};
std::vector<FtpProfile> ftpProfiles;
bool ftpProfilesLoaded{};
constexpr wchar_t ftpProfilesValue[]=L"FtpProfiles";
constexpr DWORD ftpProfilesMaxBytes=1024*1024;
struct TransferProfiles
{
const wchar_t *preference;
std::vector<TransferProfile> rows;
bool loaded{};
};
TransferProfiles &transferProfiles(TransferProtocol protocol)
{
static TransferProfiles ftp{L"FtpProfiles"},sftp{L"SftpProfiles"};
return protocol==TransferProtocol::sftp?sftp:ftp;
}
std::atomic<std::shared_ptr<const std::vector<TransferProfile>>> sshProfiles;
constexpr size_t sshRouteLimit=8;
std::vector<TransferProfile> sshRoute(const TransferProfile &destination,
const std::vector<TransferProfile> &profiles)
{
std::vector<TransferProfile> route{destination};
std::set<std::string> seen{destination.id};
while(!route.back().jumpProfile.empty())
{
const auto &id=route.back().jumpProfile;
if(!seen.insert(id).second) throw std::runtime_error("The SSH jump route contains a loop.");
if(route.size()>=sshRouteLimit) throw std::runtime_error("An SSH route can contain up to eight hosts.");
const auto hop=std::find_if(profiles.begin(),profiles.end(),
[&id](const auto &profile){return profile.id==id;});
if(hop==profiles.end()) throw std::runtime_error("An SSH jump profile is missing. Edit this connection to update its route.");
route.push_back(*hop);
}
std::reverse(route.begin(),route.end());
return route;
}
bool validSudoSftpServer(std::wstring_view path)
{
constexpr std::wstring_view pathCharacters=L"/-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
return path.empty() || (path.starts_with(L'/') && path.ends_with(L"/sftp-server") &&
path.size()<=255 && path.find_first_not_of(pathCharacters)==path.npos);
}
constexpr DWORD transferProfilesMaxBytes=1024*1024;
const fs::path ftpRoot=L"\\";
bool isFtpFolderPath(const fs::path &path)
{
return path.has_root_directory() && !path.has_root_name();
}
std::wstring ftpPath(const fs::path &path)
{
auto value=path.native();
@@ -19,61 +78,96 @@ std::wstring ftpPath(const fs::path &path)
return value;
}
bool saveFtpProfiles(const std::vector<FtpProfile> &profiles)
bool saveTransferProfiles(TransferProtocol protocol,const std::vector<TransferProfile> &profiles)
{
auto rows=Json::array();
for(const auto &profile:profiles)
rows.push_back({{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)},
{
Json row{{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)},
{"port",profile.port},{"user",ks::utf8(profile.user)},{"secret",profile.secret},
{"legacyNames",profile.legacyNames}});
{"legacyNames",profile.legacyNames},{"id",profile.id}};
if(protocol==TransferProtocol::sftp)
{
row["privateKey"]=ks::utf8(profile.privateKey.native());
row["hostFingerprint"]=profile.hostFingerprint;
row["jumpProfile"]=profile.jumpProfile;
row["sudoSftpServer"]=ks::utf8(profile.sudoSftpServer);
}
rows.push_back(std::move(row));
}
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;
if(data.size()>transferProfilesMaxBytes) return false;
const auto snapshot=protocol==TransferProtocol::sftp?
std::make_shared<const std::vector<TransferProfile>>(profiles):nullptr;
if(RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,transferProfiles(protocol).preference,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))!=ERROR_SUCCESS) return false;
if(snapshot) sshProfiles=snapshot;
return true;
}
bool loadFtpProfiles()
bool loadTransferProfiles(TransferProtocol protocol=TransferProtocol::ftp)
{
if(ftpProfilesLoaded) return true;
auto &settings=transferProfiles(protocol);
if(settings.loaded) return true;
DWORD bytes{};
const auto query=RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,
const auto query=RegGetValueW(HKEY_CURRENT_USER,schemeKey,settings.preference,
RRF_RT_REG_BINARY,nullptr,nullptr,&bytes);
if(query==ERROR_FILE_NOT_FOUND)
{
ftpProfilesLoaded=true;
settings.loaded=true;
return true;
}
if(query!=ERROR_SUCCESS || !bytes || bytes>ftpProfilesMaxBytes) return false;
if(query!=ERROR_SUCCESS || !bytes || bytes>transferProfilesMaxBytes) return false;
std::string data(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,RRF_RT_REG_BINARY,
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,settings.preference,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;
std::vector<TransferProfile> 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")),
TransferProfile 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)};
row.value("legacyNames",false),row.value("id",std::string{}),protocol};
if(profile.id.empty()) profile.id="legacy:"+ks::utf8(profile.name);
if(profile.name.empty() || profile.host.empty()) return false;
if(protocol==TransferProtocol::sftp)
{
profile.privateKey=ks::wide(row.value("privateKey",std::string{}));
profile.hostFingerprint=row.value("hostFingerprint",std::string{});
profile.jumpProfile=row.value("jumpProfile",std::string{});
profile.sudoSftpServer=ks::wide(row.value("sudoSftpServer",std::string{}));
if(!validSudoSftpServer(profile.sudoSftpServer)) return false;
}
profiles.push_back(std::move(profile));
}
ftpProfiles=std::move(profiles);
ftpProfilesLoaded=true;
if(protocol==TransferProtocol::sftp)
sshProfiles=std::make_shared<const std::vector<TransferProfile>>(profiles);
settings.rows=std::move(profiles);
settings.loaded=true;
return true;
}
catch(const std::exception &) {return false;}
}
std::wstring ftpPassword(const FtpProfile &profile)
const TransferProfile *findTransferProfile(std::string_view id,TransferProtocol protocol=TransferProtocol::ftp)
{
const auto &profiles=transferProfiles(protocol).rows;
const auto profile=std::find_if(profiles.begin(),profiles.end(),[&](const auto &entry) {
return entry.id==id;
});
return profile==profiles.end()?nullptr:&*profile;
}
std::wstring transferPassword(const TransferProfile &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");
if(bytes.size()%sizeof(wchar_t)) throw std::runtime_error("Invalid saved transfer 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());
@@ -99,6 +193,41 @@ void checkFileOperation(bool success)
if(!success) requireFileOperation(false,GetLastError());
}
std::wstring ftpFolderError(const std::system_error &error)
{
switch(error.code().value())
{
case ERROR_INTERNET_CANNOT_CONNECT: return L"Cannot reach FTP server.";
case ERROR_INTERNET_NAME_NOT_RESOLVED: return L"FTP host name could not be resolved.";
case ERROR_INTERNET_LOGIN_FAILURE: return L"FTP sign-in failed.";
case ERROR_INTERNET_TIMEOUT: return L"FTP connection timed out.";
default: break;
}
if(error.code().value()==ERROR_INTERNET_EXTENDED_ERROR)
{
DWORD response{},length{};
InternetGetLastResponseInfoW(&response,nullptr,&length);
if(length && length<=2048)
{
std::wstring text(length,L'\0');
if(InternetGetLastResponseInfoW(&response,text.data(),&length))
{
text.resize(length);
text.resize(std::min(text.size(),text.find_first_of(L"\r\n")));
if(!text.empty()) return text;
}
}
return L"The FTP server rejected the request.";
}
wchar_t message[256]{};
const DWORD length=FormatMessageW(FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_IGNORE_INSERTS,
GetModuleHandleW(L"wininet.dll"),error.code().value(),0,message,static_cast<DWORD>(std::size(message)),nullptr);
if(!length) return fileError(error);
std::wstring text(message,length);
while(!text.empty() && (text.back()==L'\r' || text.back()==L'\n')) text.pop_back();
return text;
}
class FtpSession
{
FtpHandle internet_{InternetOpenW(L"KSwitcher Files",INTERNET_OPEN_TYPE_DIRECT,nullptr,nullptr,0)};
@@ -107,7 +236,7 @@ class FtpSession
UINT nameCodePage_;
public:
explicit FtpSession(const FtpProfile &profile):nameCodePage_(profile.legacyNames?GetACP():CP_UTF8)
explicit FtpSession(const TransferProfile &profile):nameCodePage_(profile.legacyNames?GetACP():CP_UTF8)
{
checkFileOperation(internet_.value!=nullptr);
DWORD timeout=10000, retries=1;
@@ -115,7 +244,7 @@ public:
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);
auto password=transferPassword(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);
@@ -201,17 +330,17 @@ DWORD listFtpDirectory(FtpSession &session,const fs::path &directory,const FileV
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))
const auto ftpTime=[](const FILETIME &local) -> uint64_t
{
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;
FILETIME utc{};
if((!local.dwLowDateTime && !local.dwHighDateTime) || !LocalFileTimeToFileTime(&local,&utc)) return 0;
return (uint64_t(utc.dwHighDateTime)<<32)|utc.dwLowDateTime;
};
FileInfo info{entry.dwFileAttributes,(uint64_t(entry.nFileSizeHigh)<<32)|entry.nFileSizeLow,
ftpTime(entry.ftLastWriteTime)};
const TransferItemMetadata details{ftpTime(entry.ftCreationTime),ftpTime(entry.ftLastAccessTime)};
if(details.created || details.accessed) info.transfer=details;
if(!visit(directory/name,info)) return ERROR_CANCELLED;
} while(!stop.stop_requested() && InternetFindNextFileA(search.value,&entry));
return stop.stop_requested()?ERROR_CANCELLED:GetLastError();
}
+45 -50
View File
@@ -1,7 +1,7 @@
FileEntries ftpChildren(FtpSession &session,const fs::path &directory,const std::atomic_bool *canceled=nullptr)
FileEntries transferChildren(TransferSession &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)
const auto error=session.list(directory,[&](const fs::path &path,const FileInfo &info)
{
if(canceled && *canceled) return false;
entries.emplace_back(path,info);
@@ -11,30 +11,23 @@ FileEntries ftpChildren(FtpSession &session,const fs::path &directory,const std:
return entries;
}
std::optional<FileInfo> ftpEntry(const FileEntries &entries,const fs::path &path)
std::optional<FileInfo> transferEntry(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;
std::optional<TransferSession> ftp;
FileOperationElevation *elevation{};
fs::path listedDirectory;
FileEntries listedEntries;
std::optional<bool> copyMetadataSupport;
CopyHost(const FilesPeer *peer,const std::optional<FtpProfile> &profile,FileOperationElevation *admin=nullptr)
CopyHost(const FilesPeer *peer,const std::optional<TransferProfile> &profile,FileOperationElevation *admin=nullptr)
{
if(profile) ftp.emplace(*profile);
else files.emplace(peer);
@@ -50,7 +43,7 @@ struct CopyHost
{
if(path!=listedDirectory)
{
listedEntries=ftpChildren(*ftp,path,&canceled);
listedEntries=transferChildren(*ftp,path,&canceled);
listedDirectory=path;
}
return listedEntries;
@@ -58,7 +51,7 @@ struct CopyHost
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)));
return ftp?transferEntry(ftpListing(path.parent_path(),canceled),path):statFile(request(fileRequest("stat",path)));
}
FileEntries children(const fs::path &path,const std::atomic_bool &canceled)
@@ -75,6 +68,17 @@ struct CopyHost
return entries;
}
bool supportsCopyMetadata()
{
if(!copyMetadataSupport)
{
const auto reply=request(fileRequest("fileCapabilities",L"C:\\"));
if(reply.at("error")!=ERROR_INVALID_FUNCTION) checkFileReply(reply);
copyMetadataSupport=reply.value("copyMetadata",false);
}
return *copyMetadataSupport;
}
void makeDirectory(const fs::path &path)
{
if(!ftp)
@@ -82,8 +86,7 @@ struct CopyHost
checkFileReply(request(fileRequest("mkdir",path)));
return;
}
ftp->setDirectory(path.parent_path());
checkFileOperation(FtpCreateDirectoryA(ftp->handle(),ftp->encodeName(path.filename()).c_str()));
ftp->makeDirectory(path);
listedDirectory.clear();
}
@@ -91,10 +94,7 @@ struct CopyHost
{
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()));
ftp->remove(path,attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY));
return;
}
auto message=fileRequest(permanent?"remove":"recycle",path);
@@ -103,14 +103,10 @@ struct CopyHost
}
};
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,
void downloadTransferFile(TransferSession &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 input=ftp.open(source,false);
auto upload=fileRequest("openWrite",target);
upload["transfer"]=ks::lan::randomHex(32);
upload["size"]=info.size;
@@ -123,8 +119,7 @@ void downloadFtpFile(FtpSession &ftp,FilesConnection &local,const fs::path &sour
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));
const auto read=input.read(bytes.data(),bytes.size());
if(!read)
{
requireFileOperation(done==info.size,ERROR_FILE_INVALID);
@@ -146,9 +141,9 @@ void downloadFtpFile(FtpSession &ftp,FilesConnection &local,const fs::path &sour
}
}
FileInfo uploadFtpFile(FilesConnection &local,FtpSession &ftp,const fs::path &source,const fs::path &target,
FileInfo uploadTransferFile(FilesConnection &local,TransferSession &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 ks::files::RemoteTextRevision *expected=nullptr,bool preserveTime=false)
{
const auto directory=target.parent_path();
const auto temporary=directory/ks::wide("kswitcher-"+ks::lan::randomHex(16)+".partial");
@@ -156,55 +151,55 @@ FileInfo uploadFtpFile(FilesConnection &local,FtpSession &ftp,const fs::path &so
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;
bool staged=false,reading=true;
try
{
uint64_t done=0;
{
FtpHandle output{FtpOpenFileA(ftp.handle(),stage.c_str(),GENERIC_WRITE,ftpCopyFlags,0)};
checkFileOperation(output.value!=nullptr);
auto output=ftp.open(temporary,true);
staged=true;
for(;;)
{
requireFileOperation(progress(done,info.size),ERROR_CANCELLED);
requireFileOperation(!progress || 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();)
for(size_t offset=0;offset<bytes.size();)
{
DWORD written{};
checkFileOperation(InternetWriteFile(output.value,bytes.data()+offset,
static_cast<DWORD>(bytes.size()-offset),&written));
const auto written=output.write(bytes.data()+offset,bytes.size()-offset);
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;
output.close();
}
checkFileReply(local.call({{"action","closeRead"}}));
const auto entries=ftpChildren(ftp,directory);
const auto uploaded=ftpEntry(entries,temporary);
reading=false;
const auto entries=transferChildren(ftp,directory);
const auto uploaded=transferEntry(entries,temporary);
requireFileOperation(uploaded && uploaded->size==done,ERROR_WRITE_FAULT);
const auto existing=ftpEntry(entries,target);
const auto existing=transferEntry(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.");
throw std::runtime_error("The "+ks::utf8(ftp.label())+" 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);
ftp.prepareReplacement(temporary,target);
}
if(preserveTime) ftp.preserveModificationTime(temporary,info.modified);
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
ftp.rename(temporary,target,existing.has_value());
return *uploaded;
}
catch(...)
{
if(staged) FtpDeleteFileA(ftp.handle(),stage.c_str());
if(reading) try {local.call({{"action","closeRead"}});} catch(const std::exception &) {}
if(staged) try {ftp.remove(temporary,false);} catch(const std::exception &) {}
throw;
}
}
+276 -81
View File
@@ -1,76 +1,82 @@
namespace ftpDialog
namespace transferDialog
{
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);
}
constexpr int keyLabel=562,keyFile=563,testConnection=564,forgetKey=565,hostStatus=566,jumpVia=567,jumpLabel=568;
constexpr int sudoLabel=569,sudoServer=570;
struct Edit
{
FtpProfile profile;
TransferProfile profile;
std::optional<size_t> index;
std::wstring pinnedHost;
INTERNET_PORT pinnedPort{};
std::string pin;
std::vector<std::string> jumpChoices;
bool testing{};
std::atomic_bool canceled{};
};
INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
bool sameEndpoint(const Edit &edit,const TransferProfile &profile)
{
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" FTP connection ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
return edit.pinnedPort==profile.port && CompareStringOrdinal(edit.pinnedHost.c_str(),-1,
profile.host.c_str(),-1,TRUE)==CSTR_EQUAL;
}
std::wstring connectionTitle(TransferProtocol protocol)
{
return std::wstring(transferProtocolName(protocol))+L" connection";
}
void showHostStatus(HWND dialog,const Edit &edit)
{
TransferProfile current;
current.host=trimFilesField(shortcutField(dialog,host));
BOOL valid{};
current.port=static_cast<INTERNET_PORT>(GetDlgItemInt(dialog,port,&valid,FALSE));
const bool trusted=valid && !edit.pin.empty() && sameEndpoint(edit,current);
const auto message=trusted?L"Trusted "+ks::wide(edit.pin):std::wstring(L"Host key not verified");
SetDlgItemTextW(dialog,hostStatus,message.c_str());
EnableWindow(GetDlgItem(dialog,forgetKey),trusted && !edit.testing);
}
void addJumpChoice(HWND dialog,Edit &edit,const std::wstring &label,const std::string &id)
{
const auto row=SendDlgItemMessageW(dialog,jumpVia,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
if(row==CB_ERR || row==CB_ERRSPACE) return;
edit.jumpChoices.push_back(id);
if(id==edit.profile.jumpProfile) SendDlgItemMessageW(dialog,jumpVia,CB_SETCURSEL,row,0);
}
void populateJumpChoices(HWND dialog,Edit &edit)
{
addJumpChoice(dialog,edit,L"Direct",{});
for(const auto &profile:transferProfiles(TransferProtocol::sftp).rows)
if(profile.id!=edit.profile.id) addJumpChoice(dialog,edit,profile.name,profile.id);
if(SendDlgItemMessageW(dialog,jumpVia,CB_GETCURSEL,0,0)==CB_ERR)
addJumpChoice(dialog,edit,L"Missing profile",edit.profile.jumpProfile);
}
std::optional<TransferProfile> readProfile(HWND dialog,const Edit &edit)
{
TransferProfile profile;
profile.protocol=edit.profile.protocol;
const bool sftp=profile.protocol==TransferProtocol::sftp;
const auto invalid=[&](int field,const wchar_t *message)->std::optional<TransferProfile>
{
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");
showFilesNotice(dialog,message,connectionTitle(profile.protocol).c_str());
SetFocus(GetDlgItem(dialog,field));
return TRUE;
return {};
};
FtpProfile profile;
profile.legacyNames=IsDlgButtonChecked(dialog,legacy)==BST_CHECKED;
profile.name=trim(shortcutField(dialog,name));
profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16);
profile.legacyNames=!sftp && IsDlgButtonChecked(dialog,legacy)==BST_CHECKED;
profile.name=trimFilesField(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)
const auto &profiles=transferProfiles(profile.protocol).rows;
for(size_t i=0;i<profiles.size();++i)
if(edit.index!=i && CompareStringOrdinal(profiles[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));
profile.host=trimFilesField(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);
@@ -78,52 +84,241 @@ INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
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)
if(profile.user.find_first_of(L"\r\n")!=profile.user.npos || (sftp && profile.user.empty()))
return invalid(user,L"Enter the user name on one line.");
if(sftp)
{
profile.privateKey=trimFilesField(shortcutField(dialog,keyFile));
if(!profile.privateKey.empty() && !profile.privateKey.is_absolute())
return invalid(keyFile,L"Enter the full path of the private key file.");
if(sameEndpoint(edit,profile)) profile.hostFingerprint=edit.pin;
profile.sudoSftpServer=trimFilesField(shortcutField(dialog,sudoServer));
if(!validSudoSftpServer(profile.sudoSftpServer))
return invalid(sudoServer,L"Enter the absolute path to sftp-server, for example /usr/lib/openssh/sftp-server.");
const auto choice=SendDlgItemMessageW(dialog,jumpVia,CB_GETCURSEL,0,0);
if(choice>=0 && static_cast<size_t>(choice)<edit.jumpChoices.size())
profile.jumpProfile=edit.jumpChoices[choice];
try {sshRoute(profile,profiles);}
catch(const std::exception &error)
{
return invalid(jumpVia,ks::wide(error.what()).c_str());
}
}
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));
struct Erase
{
ks::Bytes &bytes;
std::wstring &text;
~Erase()
{
SecureZeroMemory(bytes.data(),bytes.size());
SecureZeroMemory(text.data(),text.size()*sizeof(wchar_t));
}
} erase{bytes,plain};
profile.secret=ks::protect(bytes);
}
return profile;
}
template<class Task>
bool runTest(HWND dialog,Edit &edit,const wchar_t *status,Task task)
{
constexpr int controls[]{name,host,port,user,password,keyFile,jumpVia,sudoServer,testConnection,forgetKey,IDOK};
edit.testing=true;
edit.canceled=false;
for(const auto id:controls) EnableWindow(GetDlgItem(dialog,id),FALSE);
SetFocus(GetDlgItem(dialog,IDCANCEL));
SetDlgItemTextW(dialog,hostStatus,status);
std::wstring error;
try
{
auto plain=shortcutField(dialog,password);
if(!plain.empty())
FileOperationUi worker;
worker.run(dialog,edit.canceled,std::move(task));
}
catch(const std::exception &exception) {error=ks::wide(exception.what());}
edit.testing=false;
for(const auto id:controls) EnableWindow(GetDlgItem(dialog,id),TRUE);
showHostStatus(dialog,edit);
if(edit.canceled) return false;
if(error.empty()) return true;
showFilesNotice(dialog,error.c_str(),L"SFTP connection test",{.tone=FilesNoticeTone::warning});
return false;
}
void testSftp(HWND dialog,Edit &edit,TransferProfile profile)
{
if(profile.hostFingerprint.empty())
{
std::string fingerprint;
if(!runTest(dialog,edit,L"Reading the SSH host key…",[&] {
const SshConnection probe(profile,true);
fingerprint=probe.fingerprint();
})) return;
const auto prompt=profile.host+L":"+std::to_wstring(profile.port)+L"\r\n"+ks::wide(fingerprint)+
L"\r\n\r\nVerify this fingerprint with the server administrator. Trust this SSH host key?";
if(showFilesNotice(dialog,prompt.c_str(),L"Verify SFTP host key",{.confirm=true})!=IDYES) return;
edit.pinnedHost=profile.host;
edit.pinnedPort=profile.port;
profile.hostFingerprint=edit.pin=std::move(fingerprint);
}
fs::path initial;
if(runTest(dialog,edit,L"Testing the SSH login…",[&] {
SshConnection connection(profile);
const SftpSubsystem sftp(libssh2_sftp_init(connection.session()),libssh2_sftp_shutdown);
if(sftp) initial=sftpInitialDirectory(sftp.get());
}))
{
const auto details=L"Connected to "+profile.host+L".\r\n\r\n"+(initial.empty()?
L"SFTP is unavailable. This profile can still be used as an SSH jump host.":
L"Initial folder "+ftpPath(initial)+L".");
showFilesNotice(dialog,details.c_str(),L"SFTP connection test");
}
}
INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
auto *edit=message==WM_INITDIALOG?reinterpret_cast<Edit*>(lp):
reinterpret_cast<Edit*>(GetWindowLongPtrW(dialog,DWLP_USER));
const bool sftp=edit && edit->profile.protocol==TransferProtocol::sftp;
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,sftp?L" SFTP connection ":L" FTP connection ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
const auto &profile=edit->profile;
prepareCopyDialog(dialog);
layoutDialogContent(dialog,381);
for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL,keyLabel,hostStatus,jumpVia,jumpLabel,sudoLabel})
if(const auto control=GetDlgItem(dialog,id)) SendMessageW(control,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());
if(sftp)
{
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());
SendDlgItemMessageW(dialog,keyFile,EM_SETLIMITTEXT,32767,0);
SetDlgItemTextW(dialog,keyFile,profile.privateKey.c_str());
SendDlgItemMessageW(dialog,sudoServer,EM_SETLIMITTEXT,255,0);
SetDlgItemTextW(dialog,sudoServer,profile.sudoSftpServer.c_str());
populateJumpChoices(dialog,*edit);
installFarCombo(GetDlgItem(dialog,jumpVia),GetDlgItem(dialog,keyFile));
showHostStatus(dialog,*edit);
layoutDialogButtons(dialog,footer,{testConnection,forgetKey,IDOK,IDCANCEL});
}
auto updated=ftpProfiles;
if(edit.index) updated[*edit.index]=std::move(profile);
else updated.push_back(std::move(profile));
if(saveFtpProfiles(updated))
else
{
ftpProfiles=std::move(updated);
installFarCheckbox(GetDlgItem(dialog,legacy),FarCheckboxSurface::gray);
CheckDlgButton(dialog,legacy,profile.legacyNames?BST_CHECKED:BST_UNCHECKED);
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
}
try
{
auto secret=transferPassword(profile);
SetDlgItemTextW(dialog,password,secret.c_str());
SecureZeroMemory(secret.data(),secret.size()*sizeof(wchar_t));
}
catch(const std::exception &)
{
SetDlgItemTextW(dialog,389,L"&Secret (re-enter to replace the saved value)");
}
return TRUE;
}
if(!edit) return FALSE;
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
if(edit->testing)
{
edit->canceled=true;
SetDlgItemTextW(dialog,hostStatus,L"Stopping when the current request returns…");
}
else
{
SetDlgItemTextW(dialog,password,L"");
SendDlgItemMessageW(dialog,password,EM_EMPTYUNDOBUFFER,0,0);
FilesModalDialog::finish(dialog,IDCANCEL);
}
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
if(edit->testing) return TRUE;
const auto command=LOWORD(wp);
if(sftp && HIWORD(wp)==EN_CHANGE && (command==host || command==port))
{
showHostStatus(dialog,*edit);
return TRUE;
}
if(sftp && command==forgetKey)
{
if(showFilesNotice(dialog,L"Forget the trusted key for this endpoint? A new key must be verified before signing in.",
L"SFTP host key",{.confirm=true})==IDYES)
{
edit->pin.clear();
showHostStatus(dialog,*edit);
}
return TRUE;
}
if(command!=IDOK && (!sftp || command!=testConnection)) return FALSE;
try
{
auto profile=readProfile(dialog,*edit);
if(!profile) return TRUE;
if(command==testConnection)
{
testSftp(dialog,*edit,std::move(*profile));
return TRUE;
}
auto &settings=transferProfiles(profile->protocol);
auto updated=settings.rows;
if(edit->index) updated[*edit->index]=std::move(*profile);
else updated.push_back(std::move(*profile));
if(saveTransferProfiles(edit->profile.protocol,updated))
{
settings.rows=std::move(updated);
SetDlgItemTextW(dialog,password,L"");
SendDlgItemMessageW(dialog,password,EM_EMPTYUNDOBUFFER,0,0);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
}
catch(const std::exception &) {}
showFilesNotice(dialog,L"Could not save the FTP connection.",L"FTP connection");
const auto title=connectionTitle(edit->profile.protocol);
showFilesNotice(dialog,(L"Could not save the "+title+L".").c_str(),title.c_str());
return TRUE;
}
}
void editFtpProfile(Panel &panel,bool create)
void editTransferProfile(Panel &panel,bool create)
{
ftpDialog::Edit edit;
transferDialog::Edit edit;
const auto protocol=panel.ftp->protocol;
const auto &profiles=transferProfiles(protocol).rows;
edit.profile.protocol=protocol;
if(protocol==TransferProtocol::sftp) edit.profile.port=defaultSftpPort;
if(!create)
{
const auto row=currentPanelRow(panel);
if(row<0 || static_cast<size_t>(row)>=ftpProfiles.size()) return;
if(row<0 || static_cast<size_t>(row)>=profiles.size()) return;
edit.index=static_cast<size_t>(row);
edit.profile=ftpProfiles[*edit.index];
edit.profile=profiles[*edit.index];
edit.pinnedHost=edit.profile.host;
edit.pinnedPort=edit.profile.port;
edit.pin=edit.profile.hostFingerprint;
}
const auto owner=GetParent(panel.list);
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(112),owner,
ftpDialog::procedure,reinterpret_cast<LPARAM>(&edit))!=IDOK) return;
const auto resource=protocol==TransferProtocol::sftp?124:112;
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(resource),owner,
transferDialog::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);
if(!transferProfileList(other) || other.ftp->protocol!=protocol || other.scan.valid()) continue;
const auto selection=&other==&panel?ftpRoot/std::to_wstring(edit.index.value_or(profiles.size()-1)):fs::path{};
showTransferProfiles(other,protocol,selection);
}
}
+740
View File
@@ -0,0 +1,740 @@
#include "files_git_changes.h"
#include "core.h"
#include "windows_command_line.h"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <objbase.h>
#include <optional>
#include <stdexcept>
#include <system_error>
#include <tuple>
#include <utility>
namespace ks::files
{
namespace
{
namespace fs=std::filesystem;
struct GitHandle
{
HANDLE value{};
void close()
{
if(value && value!=INVALID_HANDLE_VALUE) CloseHandle(value);
value=nullptr;
}
~GitHandle(){close();}
};
[[noreturn]] void gitWindowsError(const char *operation)
{
throw std::system_error(GetLastError(),std::system_category(),operation);
}
void makeGitPipe(GitHandle &read,GitHandle &write,SECURITY_ATTRIBUTES &inheritable)
{
if(!CreatePipe(&read.value,&write.value,&inheritable,0) ||
!SetHandleInformation(read.value,HANDLE_FLAG_INHERIT,0))
gitWindowsError("Could not create the Git output pipe");
}
fs::path locateGit()
{
const DWORD size=GetEnvironmentVariableW(L"PATH",nullptr,0);
std::wstring paths(size,L'\0');
if(size)
{
const auto count=GetEnvironmentVariableW(L"PATH",paths.data(),size);
paths.resize(count<size?count:0);
}
std::wstring_view remaining=paths;
while(!remaining.empty())
{
const auto end=remaining.find(L';');
auto directory=remaining.substr(0,end);
if(directory.size()>=2 && directory.front()==L'"' && directory.back()==L'"')
directory=directory.substr(1,directory.size()-2);
const auto path=fs::path(directory);
if(path.is_absolute())
{
const auto candidate=path/L"git.exe";
const auto attributes=GetFileAttributesW(candidate.c_str());
if(attributes!=INVALID_FILE_ATTRIBUTES && !(attributes&FILE_ATTRIBUTE_DIRECTORY)) return candidate;
}
if(end==remaining.npos) break;
remaining.remove_prefix(end+1);
}
for(const auto key:{HKEY_CURRENT_USER,HKEY_LOCAL_MACHINE})
{
wchar_t install[32768]{};
DWORD bytes=sizeof(install);
if(RegGetValueW(key,L"SOFTWARE\\GitForWindows",L"InstallPath",RRF_RT_REG_SZ,nullptr,install,&bytes)!=ERROR_SUCCESS)
continue;
const auto git=fs::path(install)/L"cmd"/L"git.exe";
if(git.is_absolute() && GetFileAttributesW(git.c_str())!=INVALID_FILE_ATTRIBUTES) return git;
}
throw std::runtime_error("Git for Windows was not found. Install it or add git.exe to PATH.");
}
std::vector<wchar_t> gitEnvironment(const fs::path &alternateIndex)
{
const auto environment=GetEnvironmentStringsW();
if(!environment) gitWindowsError("Could not read the environment for Git");
const std::unique_ptr<wchar_t,decltype(&FreeEnvironmentStringsW)> owned(environment,FreeEnvironmentStringsW);
constexpr std::wstring_view overrides[]{
L"GIT_DIR",L"GIT_WORK_TREE",L"GIT_COMMON_DIR",L"GIT_INDEX_FILE",L"GIT_PREFIX",
L"GIT_OBJECT_DIRECTORY",L"GIT_ALTERNATE_OBJECT_DIRECTORIES",L"GIT_NAMESPACE",L"GIT_QUARANTINE_PATH",
L"GIT_CEILING_DIRECTORIES",L"GIT_GLOB_PATHSPECS",L"GIT_NOGLOB_PATHSPECS",L"GIT_ICASE_PATHSPECS"};
std::vector<std::wstring> settings;
for(auto entry=environment;*entry;)
{
const std::wstring_view setting=entry;
const auto name=setting.substr(0,setting.find(L'='));
if(std::none_of(std::begin(overrides),std::end(overrides),[&](std::wstring_view key) {
return name.size()==key.size() &&
CompareStringOrdinal(name.data(),static_cast<int>(name.size()),key.data(),static_cast<int>(key.size()),TRUE)
==CSTR_EQUAL;
}))
settings.emplace_back(setting);
entry+=setting.size()+1;
}
if(!alternateIndex.empty()) settings.push_back(L"GIT_INDEX_FILE="+alternateIndex.native());
std::sort(settings.begin(),settings.end(),[](const auto &left,const auto &right) {
return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE)==CSTR_LESS_THAN;
});
std::vector<wchar_t> result;
for(const auto &setting:settings) result.insert(result.end(),setting.c_str(),setting.c_str()+setting.size()+1);
result.push_back(L'\0');
if(result.size()==1) result.push_back(L'\0');
return result;
}
struct GitProcessAttributes
{
std::vector<std::byte> storage;
LPPROC_THREAD_ATTRIBUTE_LIST list{};
explicit GitProcessAttributes(HANDLE (&inherited)[3])
{
SIZE_T bytes{};
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
storage.resize(bytes);
const auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes))
gitWindowsError("Could not initialize the Git process");
if(!UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,inherited,sizeof(inherited),nullptr,nullptr))
{
const auto error=GetLastError();
DeleteProcThreadAttributeList(attributes);
throw std::system_error(error,std::system_category(),"Could not set Git process handles");
}
list=attributes;
}
~GitProcessAttributes(){DeleteProcThreadAttributeList(list);}
};
struct GitOutput
{
std::string output, error;
DWORD exitCode{};
};
struct GitCommandOptions
{
fs::path index;
std::string_view input;
std::function<void()> afterPrepare;
ULONGLONG timeout=15000;
};
GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector<std::wstring> &arguments,
size_t maximum,std::stop_token stop,const GitCommandOptions &options={})
{
if(stop.stop_requested()) throw std::runtime_error("Git request canceled.");
auto command=quoteWindowsArgument(git.native())+
L" --no-pager --no-optional-locks --literal-pathspecs -c core.fsmonitor=false -c core.quotePath=false -C "+
quoteWindowsArgument(directory.native());
for(const auto &argument:arguments) command+=L' '+quoteWindowsArgument(argument);
auto environment=gitEnvironment(options.index);
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
GitHandle input,writeInput;
if(options.input.empty())
{
input.value=CreateFileW(L"NUL",GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&inheritable,OPEN_EXISTING,0,nullptr);
if(input.value==INVALID_HANDLE_VALUE) gitWindowsError("Could not open Git input");
}
else if(!CreatePipe(&input.value,&writeInput.value,&inheritable,65536) ||
!SetHandleInformation(writeInput.value,HANDLE_FLAG_INHERIT,0))
gitWindowsError("Could not open Git input");
GitHandle out,childOut,error,childError;
makeGitPipe(out,childOut,inheritable);
makeGitPipe(error,childError,inheritable);
HANDLE inherited[]{input.value,childOut.value,childError.value};
GitProcessAttributes attributes(inherited);
STARTUPINFOEXW startup{};
startup.StartupInfo.cb=sizeof(startup);
startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES;
startup.StartupInfo.hStdInput=input.value;
startup.StartupInfo.hStdOutput=childOut.value;
startup.StartupInfo.hStdError=childError.value;
startup.lpAttributeList=attributes.list;
PROCESS_INFORMATION child{};
if(!CreateProcessW(git.c_str(),command.data(),nullptr,nullptr,TRUE,
CREATE_NO_WINDOW|CREATE_SUSPENDED|CREATE_UNICODE_ENVIRONMENT|EXTENDED_STARTUPINFO_PRESENT,
environment.data(),directory.c_str(),&startup.StartupInfo,&child))
gitWindowsError("Could not start Git");
const GitHandle process{child.hProcess},thread{child.hThread};
const GitHandle job{CreateJobObjectW(nullptr,nullptr)};
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if(job.value && SetInformationJobObject(job.value,JobObjectExtendedLimitInformation,&limits,sizeof(limits)))
AssignProcessToJobObject(job.value,process.value);
try
{
if(ResumeThread(thread.value)==DWORD(-1)) gitWindowsError("Could not resume Git");
input.close();
childOut.close();
childError.close();
const auto write=[&](std::string_view payload)
{
DWORD written{};
if(payload.size()>65536 || !WriteFile(writeInput.value,payload.data(),
static_cast<DWORD>(payload.size()),&written,nullptr) || written!=payload.size())
gitWindowsError("Could not send input to Git");
};
if(writeInput.value) write(options.input);
if(!options.afterPrepare) writeInput.close();
GitOutput result;
auto deadline=GetTickCount64()+options.timeout;
const auto read=[&](HANDLE pipe,std::string &data,size_t limit)
{
DWORD waiting{},readBytes{};
char buffer[8192];
if(!PeekNamedPipe(pipe,nullptr,0,nullptr,&waiting,nullptr))
{
if(GetLastError()==ERROR_BROKEN_PIPE) return false;
gitWindowsError("Could not read Git output");
}
if(!waiting) return false;
if(!ReadFile(pipe,buffer,std::min<DWORD>(waiting,sizeof(buffer)),&readBytes,nullptr))
gitWindowsError("Could not read Git output");
if(data.size()+readBytes>limit) throw std::runtime_error("Git output was too large to display.");
data.append(buffer,readBytes);
return readBytes!=0;
};
for(;;)
{
if(stop.stop_requested()) throw std::runtime_error("Git request canceled.");
if(GetTickCount64()>=deadline) throw std::runtime_error("Git did not respond in time.");
const bool readOutput=read(out.value,result.output,maximum);
const bool readErrors=read(error.value,result.error,256*1024);
if(writeInput.value && (result.output.find("prepare: ok\n")!=std::string::npos ||
result.output.find("prepare: ok\r\n")!=std::string::npos))
{
options.afterPrepare();
write("commit\n");
writeInput.close();
deadline=GetTickCount64()+options.timeout;
}
const auto state=WaitForSingleObject(process.value,readOutput || readErrors?0:20);
if(state==WAIT_FAILED) gitWindowsError("Could not wait for Git");
if(state==WAIT_OBJECT_0 && !readOutput && !readErrors)
{
if(read(out.value,result.output,maximum) || read(error.value,result.error,256*1024))
continue;
if(!GetExitCodeProcess(process.value,&result.exitCode)) gitWindowsError("Could not read Git status");
return result;
}
}
}
catch(...)
{
const bool wasWaitingForInput=writeInput.value!=nullptr;
writeInput.close(); // EOF aborts a prepared Git reference transaction.
if(!wasWaitingForInput || WaitForSingleObject(process.value,2000)!=WAIT_OBJECT_0)
TerminateProcess(process.value,ERROR_CANCELLED);
throw;
}
}
void checkGit(const GitOutput &result,const char *operation,bool allowDifference=false)
{
if(!result.exitCode || (allowDifference && result.exitCode==1)) return;
auto detail=result.error;
while(!detail.empty() && (detail.back()=='\r' || detail.back()=='\n')) detail.pop_back();
throw std::runtime_error(detail.empty()?std::string(operation):std::string(operation)+"\r\n"+detail);
}
std::string_view nulField(std::string_view &input)
{
const auto separator=input.find('\0');
if(separator==input.npos) throw std::runtime_error("Git returned incomplete output.");
const auto field=input.substr(0,separator);
input.remove_prefix(separator+1);
return field;
}
std::wstring statusPath(std::string_view value)
{
if(value.empty() || value.starts_with('/') || value.find_first_of("\\:")!=value.npos)
throw std::runtime_error("Git returned an unsupported worktree path.");
for(auto suffix=value;!suffix.empty();)
{
const auto slash=suffix.find('/');
const auto part=suffix.substr(0,slash);
if(part=="." || part==".." || part.empty())
throw std::runtime_error("Git returned an unsupported worktree path.");
if(slash==suffix.npos) break;
suffix.remove_prefix(slash+1);
}
return wide(std::string(value));
}
std::vector<GitChange> parseGitStatus(std::string_view output)
{
std::vector<GitChange> result;
while(!output.empty())
{
const auto row=nulField(output);
if(row.size()<4 || row[2]!=' ') throw std::runtime_error("Git returned an invalid status record.");
const auto code=row.substr(0,2);
const auto path=statusPath(row.substr(3));
std::wstring origin;
if(code.find_first_of("RC")!=code.npos) origin=statusPath(nulField(output));
if(code=="??") result.push_back({GitChangeKind::untracked,path,{},L"?"});
else if(code=="DD" || code=="AA" || code.find('U')!=code.npos)
result.push_back({GitChangeKind::unstaged,path,{},wide(std::string(code))});
else
{
if(code[0]!=' ') result.push_back({GitChangeKind::staged,path,origin,std::wstring(1,code[0])});
if(code[1]!=' ') result.push_back({GitChangeKind::unstaged,path,origin,std::wstring(1,code[1])});
}
}
std::sort(result.begin(),result.end(),[](const auto &left,const auto &right) {
return std::tie(left.kind,left.path)<std::tie(right.kind,right.path);
});
return result;
}
std::wstring gitRevision(std::string_view value)
{
if((value.size()!=40 && value.size()!=64) || value.find_first_not_of("0123456789abcdef")!=value.npos)
throw std::runtime_error("Git returned an invalid object ID.");
return {value.begin(),value.end()};
}
void trimGitLine(std::string &line)
{
while(!line.empty() && (line.back()=='\n' || line.back()=='\r')) line.pop_back();
}
GitCheckout readCheckout(const fs::path &git,const fs::path &root,std::stop_token stop)
{
auto branch=runGit(git,root,{L"symbolic-ref",L"--quiet",L"HEAD"},64*1024,stop);
checkGit(branch,"Could not read the checked-out branch.",true);
auto head=runGit(git,root,{L"rev-parse",L"--verify",L"--quiet",L"HEAD"},64*1024,stop);
checkGit(head,"Could not read Git HEAD.",true);
trimGitLine(branch.output);
trimGitLine(head.output);
return {branch.exitCode?std::wstring{}:wide(branch.output),
head.exitCode?std::wstring{}:gitRevision(head.output)};
}
std::vector<GitChange> readStatus(const fs::path &git,const fs::path &root,std::stop_token stop)
{
const auto status=runGit(git,root,{L"status",L"--porcelain=v1",L"-z",L"--untracked-files=all",L"--renames"},
8*1024*1024,stop);
checkGit(status,"Could not read Git worktree status.");
return parseGitStatus(status.output);
}
struct GitWorktreeFiles
{
fs::path index;
std::vector<std::pair<fs::path,const char *>> operations;
};
GitWorktreeFiles findWorktreeFiles(const GitChanges &worktree,std::stop_token stop)
{
constexpr std::pair<const wchar_t *,const char *> markers[]{
{L"MERGE_HEAD","merge"},{L"CHERRY_PICK_HEAD","cherry-pick"},{L"REVERT_HEAD","revert"},
{L"rebase-merge","rebase"},{L"rebase-apply","rebase or am"},{L"sequencer","sequencer"},
{L"BISECT_START","bisect"}};
std::vector<std::wstring> args{L"rev-parse",L"--path-format=absolute",L"--git-path",L"index"};
for(const auto &[name,operation]:markers)
{
args.push_back(L"--git-path");
args.push_back(name);
}
const auto paths=runGit(worktree.executable,worktree.root,args,256*1024,stop);
checkGit(paths,"Could not find the worktree index.");
std::string_view lines=paths.output;
const auto next=[&]
{
if(lines.empty()) throw std::runtime_error("Git returned incomplete worktree metadata.");
const auto separator=lines.find('\n');
auto line=lines.substr(0,separator);
lines.remove_prefix(separator==lines.npos?lines.size():separator+1);
if(line.ends_with('\r')) line.remove_suffix(1);
auto path=fs::path(wide(std::string(line))).make_preferred();
if(!path.is_absolute()) throw std::runtime_error("Git returned an invalid worktree path.");
return path;
};
GitWorktreeFiles result{next(),{}};
for(const auto &[name,operation]:markers) result.operations.emplace_back(next(),operation);
return result;
}
struct WorktreeIndexLock
{
GitHandle file;
explicit WorktreeIndexLock(const fs::path &index)
{
auto name=index;
name+=L".lock";
file.value=CreateFileW(name.c_str(),GENERIC_WRITE|DELETE,0,nullptr,CREATE_NEW,
FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,nullptr);
if(file.value!=INVALID_HANDLE_VALUE) return;
const auto error=GetLastError();
if(error==ERROR_FILE_EXISTS || error==ERROR_ALREADY_EXISTS || error==ERROR_SHARING_VIOLATION)
throw std::runtime_error("Git index is locked. Finish the other Git operation, then refresh.");
throw std::system_error(error,std::system_category(),"Could not lock the Git index");
}
WorktreeIndexLock(const WorktreeIndexLock &)=delete;
};
struct WorktreeIndexCopy
{
fs::path path;
explicit WorktreeIndexCopy(const fs::path &index)
{
GUID id{};
wchar_t name[40]{};
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,static_cast<int>(std::size(name))))
throw std::runtime_error("Could not name the temporary Git index.");
path=index;
path+=std::wstring(L".kswitcher-")+name;
if(CopyFileW(index.c_str(),path.c_str(),TRUE)) return;
const auto error=GetLastError();
if(error!=ERROR_FILE_NOT_FOUND)
throw std::system_error(error,std::system_category(),"Could not copy the worktree index");
}
WorktreeIndexCopy(const WorktreeIndexCopy &)=delete;
~WorktreeIndexCopy()
{
DeleteFileW(path.c_str());
const auto lock=path.native()+L".lock";
DeleteFileW(lock.c_str());
}
void publish(const fs::path &index) const
{
if(!MoveFileExW(path.c_str(),index.c_str(),MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH))
gitWindowsError("Could not replace the Git index");
}
};
void requireWritableWorktree(const GitChanges &worktree,const GitWorktreeFiles &paths,
const GitCheckout &checkout,std::stop_token stop)
{
if(!checkout.ref.starts_with(L"refs/heads/"))
throw std::runtime_error("This worktree has detached HEAD. Check out a branch before writing Git changes.");
for(const auto &[path,operation]:paths.operations)
{
if(GetFileAttributesW(path.c_str())!=INVALID_FILE_ATTRIBUTES)
throw std::runtime_error(std::string("A Git ")+operation+" is in progress. Finish it before writing changes.");
const auto error=GetLastError();
if(error!=ERROR_FILE_NOT_FOUND && error!=ERROR_PATH_NOT_FOUND)
throw std::system_error(error,std::system_category(),"Could not check for active Git operations");
}
const auto conflicts=runGit(worktree.executable,worktree.root,{L"ls-files",L"--unmerged",L"-z"},2*1024*1024,stop);
checkGit(conflicts,"Could not check Git index conflicts.");
if(!conflicts.output.empty()) throw std::runtime_error("The Git index contains conflicts. Resolve them before writing changes.");
}
GitCommitReview captureGitReview(const GitChanges &worktree,const GitCheckout &checkout,std::stop_token stop,
bool listPaths)
{
GitCommitReview review{worktree.root,checkout,{},{}};
std::vector<std::wstring> args{L"diff",L"--cached",L"--no-color",L"--no-ext-diff",L"--no-textconv",
L"--ita-invisible-in-index",L"-z"};
if(!checkout.revision.empty()) args.push_back(checkout.revision);
args.push_back(L"--");
auto identityArgs=args;
identityArgs.insert(identityArgs.begin()+1,{L"--raw",L"--no-renames",L"--abbrev=64"});
auto identity=runGit(worktree.executable,worktree.root,identityArgs,16*1024*1024,stop);
checkGit(identity,"Could not read the staged snapshot.");
review.stagedIdentity=std::move(identity.output);
if(!listPaths || review.stagedIdentity.empty()) return review;
args.insert(args.begin()+1,{L"--name-status",L"--find-renames"});
const auto changed=runGit(worktree.executable,worktree.root,args,8*1024*1024,stop);
checkGit(changed,"Could not list all staged paths.");
std::string_view records=changed.output;
while(!records.empty())
{
const auto flags=nulField(records);
if(flags.empty()) throw std::runtime_error("Git returned an invalid staged-path record.");
auto path=statusPath(nulField(records));
std::wstring old;
if(flags.front()=='R' || flags.front()=='C')
{
old=std::move(path);
path=statusPath(nulField(records));
}
review.staged.push_back({GitChangeKind::staged,std::move(path),std::move(old),wide(std::string(flags))});
}
return review;
}
}
GitChanges readGitChanges(const std::filesystem::path &directory,std::stop_token stop)
{
GitChanges result;
result.executable=locateGit();
auto root=runGit(result.executable,directory,{L"rev-parse",L"--show-toplevel"},64*1024,stop);
checkGit(root,"This folder is not inside a Git worktree.");
trimGitLine(root.output);
result.root=fs::path(wide(root.output)).make_preferred();
if(!result.root.is_absolute()) throw std::runtime_error("Git returned an invalid worktree root.");
result.checkout=readCheckout(result.executable,result.root,stop);
result.entries=readStatus(result.executable,result.root,stop);
return result;
}
std::string readGitPatch(const std::filesystem::path &git,const std::filesystem::path &root,
const GitChange &change,std::stop_token stop)
{
std::vector<std::wstring> args{L"diff",L"--no-color",L"--no-ext-diff",L"--no-textconv",L"--find-renames"};
const bool untracked=change.kind==GitChangeKind::untracked;
if(untracked) args.push_back(L"--no-index");
if(change.kind==GitChangeKind::staged) args.push_back(L"--cached");
args.push_back(L"--");
if(untracked) args.push_back(L"/dev/null");
else if(!change.oldPath.empty()) args.push_back(change.oldPath);
args.push_back(change.path);
auto patch=runGit(git,root,args,2*1024*1024,stop);
checkGit(patch,"Could not read this Git diff.",untracked);
return std::move(patch.output);
}
std::vector<GitBranch> readGitBranches(const std::filesystem::path &git,const std::filesystem::path &root,
std::stop_token stop)
{
const auto refs=runGit(git,root,{L"for-each-ref",L"--sort=refname",
L"--format=%(objectname)%00%(refname)%00%(HEAD)%00%(symref)",L"refs/heads",L"refs/remotes"},
4*1024*1024,stop);
checkGit(refs,"Could not read Git branches.");
constexpr std::string_view localPrefix="refs/heads/",remotePrefix="refs/remotes/";
std::vector<GitBranch> branches;
bool foundHead=false;
for(std::string_view remaining=refs.output;!remaining.empty();)
{
const auto newline=remaining.find('\n');
auto line=remaining.substr(0,newline);
remaining.remove_prefix(newline==remaining.npos?remaining.size():newline+1);
if(line.ends_with('\r')) line.remove_suffix(1);
if(line.empty()) continue;
const auto revision=gitRevision(nulField(line));
const auto ref=nulField(line);
const bool current=nulField(line)=="*";
if(!line.empty()) continue; // Skip aliases such as origin/HEAD.
const bool remote=ref.starts_with(remotePrefix);
if(!remote && !ref.starts_with(localPrefix)) continue;
const auto branch=wide(std::string(ref.substr(remote?remotePrefix.size():localPrefix.size())));
branches.push_back({wide(std::string(ref)),(current?L"* ":remote?L"Tracking · ":L"Local · ")+branch,
revision,current});
foundHead|=current;
}
if(!foundHead)
{
auto head=runGit(git,root,{L"rev-parse",L"--verify",L"--quiet",L"HEAD"},64*1024,stop);
checkGit(head,"Could not read Git HEAD.",true);
if(!head.exitCode)
{
while(!head.output.empty() && (head.output.back()=='\n' || head.output.back()=='\r')) head.output.pop_back();
branches.insert(branches.begin(),{L"HEAD",L"* Detached HEAD",gitRevision(head.output),true});
}
}
return branches;
}
GitHistoryPage readGitHistory(const std::filesystem::path &git,const std::filesystem::path &root,
const std::wstring &revision,size_t offset,std::stop_token stop)
{
constexpr size_t pageSize=50;
const auto log=runGit(git,root,{L"log",L"--no-decorate",L"--no-notes",L"--no-show-signature",
L"--encoding=UTF-8",L"--date=short",L"--format=%H%x00%h%x00%ad%x00%s",L"-z",
L"--max-count="+std::to_wstring(pageSize+1),L"--skip="+std::to_wstring(offset),revision,L"--"},
2*1024*1024,stop);
checkGit(log,"Could not read Git history.");
GitHistoryPage page;
std::string_view records=log.output;
while(!records.empty() && page.commits.size()<pageSize)
page.commits.push_back({gitRevision(nulField(records)),wide(std::string(nulField(records))),
wide(std::string(nulField(records))),wide(std::string(nulField(records)))});
page.more=!records.empty();
return page;
}
std::string readGitCommit(const std::filesystem::path &git,const std::filesystem::path &root,
const std::wstring &revision,std::stop_token stop)
{
const auto metadata=runGit(git,root,{L"log",L"-1",L"--no-decorate",L"--no-notes",L"--no-show-signature",
L"--encoding=UTF-8",L"--format=%H%x00%an%x00%ae%x00%aI%x00%B",L"-z",revision,L"--"},2*1024*1024,stop);
checkGit(metadata,"Could not read the Git commit.");
std::string_view parts=metadata.output;
const auto id=nulField(parts);
const auto author=nulField(parts);
const auto email=nulField(parts);
const auto date=nulField(parts);
const auto message=nulField(parts);
std::string text="Commit ";
text.append(id).append("\nAuthor ").append(author);
if(!email.empty()) text.append(" <").append(email).push_back('>');
text.append("\nDate ").append(date).append("\n\n").append(message);
while(!text.empty() && (text.back()=='\r' || text.back()=='\n')) text.pop_back();
const auto changes=runGit(git,root,{L"show",L"--no-notes",L"--no-show-signature",L"--format=",L"--name-status",
L"-z",L"--root",L"--diff-merges=first-parent",L"--find-renames",L"--no-ext-diff",L"--no-textconv",
revision,L"--"},2*1024*1024,stop);
checkGit(changes,"Could not read changed paths.");
text+="\n\nChanged paths\n";
if(changes.output.empty()) text+="No changed paths.\n";
std::string_view records=changes.output;
while(!records.empty())
{
const auto code=nulField(records);
if(code.empty()) throw std::runtime_error("Git returned an invalid changed-path record.");
text.append(code).append(" ").append(nulField(records));
if(code.front()=='R' || code.front()=='C')
text.append(" → ").append(nulField(records));
text.push_back('\n');
}
return text;
}
void changeGitIndex(const GitChanges &worktree,const GitChange &entry,bool replaceStaged,std::stop_token stop)
{
const auto paths=findWorktreeFiles(worktree,stop);
const WorktreeIndexLock lock(paths.index);
const auto checkout=readCheckout(worktree.executable,worktree.root,stop);
requireWritableWorktree(worktree,paths,checkout,stop);
if(checkout!=worktree.checkout)
throw std::runtime_error("The checked-out branch or commit changed. Review the refreshed Git changes.");
const auto entries=readStatus(worktree.executable,worktree.root,stop);
if(std::find(entries.begin(),entries.end(),entry)==entries.end())
throw std::runtime_error("The selected change is no longer current. Review the refreshed Git changes.");
const bool stage=entry.kind!=GitChangeKind::staged;
const bool rename=entry.flags.starts_with(L"R") || entry.flags.starts_with(L"C");
const auto overlaps=[&](const GitChange &other)
{
return other.kind==GitChangeKind::staged && (other.path==entry.path || other.oldPath==entry.path ||
(rename && !entry.oldPath.empty() && (other.path==entry.oldPath || other.oldPath==entry.oldPath)));
};
if(stage && !replaceStaged && std::any_of(entries.begin(),entries.end(),overlaps))
throw std::runtime_error("The selected path already has staged changes. Review and confirm the replacement.");
if(stage)
{
const auto attributes=GetFileAttributesW((worktree.root/fs::path(entry.path)).c_str());
if(entry.path.ends_with(L'/') || (attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY)))
{
const auto indexed=runGit(worktree.executable,worktree.root,{L"ls-files",L"--stage",L"--",entry.path},
256*1024,stop);
checkGit(indexed,"Could not identify the selected directory.");
if(!indexed.output.starts_with("160000 "))
throw std::runtime_error("This entry is a directory. Stage individual files or an existing submodule.");
}
}
const WorktreeIndexCopy pending(paths.index);
std::vector<std::wstring> args;
if(stage) args={L"add",L"-A",L"--"};
else if(checkout.revision.empty()) args={L"rm",L"--cached",L"-f",L"--ignore-unmatch",L"--"};
else args={L"restore",L"--staged",L"--source="+checkout.revision,L"--"};
if(rename && !entry.oldPath.empty()) args.push_back(entry.oldPath);
args.push_back(entry.path);
const auto result=runGit(worktree.executable,worktree.root,args,1024*1024,stop,{.index=pending.path});
checkGit(result,stage?"Could not stage the selected path.":"Could not unstage the selected path.");
if(readCheckout(worktree.executable,worktree.root,stop)!=checkout || stop.stop_requested())
throw std::runtime_error("The checkout changed while Git was working. Review the refreshed Git changes.");
requireWritableWorktree(worktree,paths,checkout,stop);
if(stop.stop_requested()) throw std::runtime_error("Git request canceled.");
pending.publish(paths.index);
}
GitCommitReview reviewGitCommit(const GitChanges &worktree,std::stop_token stop)
{
const auto paths=findWorktreeFiles(worktree,stop);
const WorktreeIndexLock lock(paths.index);
const auto checkout=readCheckout(worktree.executable,worktree.root,stop);
requireWritableWorktree(worktree,paths,checkout,stop);
auto review=captureGitReview(worktree,checkout,stop,true);
if(readCheckout(worktree.executable,worktree.root,stop)!=checkout)
throw std::runtime_error("The checkout changed while reading the staged paths. Open a new review.");
if(review.staged.empty()) throw std::runtime_error("Stage at least one change before committing.");
return review;
}
std::wstring createGitCommit(const GitChanges &worktree,const GitCommitReview &review,
const std::wstring &message,std::stop_token stop)
{
if(message.find_first_not_of(L" \t\r\n")==message.npos)
throw std::runtime_error("Enter a commit message.");
if(worktree.root!=review.root || review.stagedIdentity.empty())
throw std::runtime_error("The reviewed worktree changed. Open a new review.");
const auto paths=findWorktreeFiles(worktree,stop);
const WorktreeIndexLock lock(paths.index);
const auto checkout=readCheckout(worktree.executable,worktree.root,stop);
requireWritableWorktree(worktree,paths,checkout,stop);
if(checkout!=review.checkout || captureGitReview(worktree,checkout,stop,false).stagedIdentity!=review.stagedIdentity)
throw std::runtime_error("The checkout or staged changes changed after review. Review them again. The message was kept.");
const WorktreeIndexCopy pending(paths.index);
auto tree=runGit(worktree.executable,worktree.root,{L"write-tree"},64*1024,stop,{.index=pending.path});
checkGit(tree,"Could not write the reviewed Git tree.");
trimGitLine(tree.output);
const auto treeId=gitRevision(tree.output);
auto signing=runGit(worktree.executable,worktree.root,{L"config",L"--type=bool",L"--get",L"commit.gpgSign"},64*1024,stop);
checkGit(signing,"Could not read Git signing settings.",true);
trimGitLine(signing.output);
std::vector<std::wstring> args{L"commit-tree",treeId,L"-F",L"-"};
if(!checkout.revision.empty()) args.insert(args.end(),{L"-p",checkout.revision});
if(signing.output=="true") args.push_back(L"-S");
auto contents=utf8(message);
for(size_t pos=0;(pos=contents.find('\r',pos))!=contents.npos;)
{
if(pos+1<contents.size() && contents[pos+1]=='\n') contents.erase(pos,1);
else contents[pos++]='\n';
}
auto created=runGit(worktree.executable,worktree.root,args,64*1024,stop,{.input=contents,.timeout=120000});
checkGit(created,"Could not create the commit. Check your Git author identity and signing settings.");
trimGitLine(created.output);
const auto commit=gitRevision(created.output);
const auto expected=checkout.revision.empty()?std::string(commit.size(),'0'):utf8(checkout.revision);
const std::string transaction="start\nupdate HEAD "+created.output+" "+expected+"\nprepare\n";
try
{
const auto update=runGit(worktree.executable,worktree.root,
{L"-c",L"core.hooksPath=NUL",L"update-ref",L"-m",L"KSwitcher Files: local commit",L"--stdin"},
64*1024,stop,{.input=transaction,.afterPrepare=[&] {
// Git holds HEAD and its referent after prepare, while the index remains locked by Files.
if(readCheckout(worktree.executable,worktree.root,stop)!=checkout)
throw std::runtime_error("The checkout changed after review. Review it again. The message was kept.");
requireWritableWorktree(worktree,paths,checkout,stop);
}});
checkGit(update,"Could not update the checked-out branch. Refresh and review the staged changes.");
if(update.output.find("commit: ok")==std::string::npos)
throw std::runtime_error("Git did not confirm the branch update.");
}
catch(...)
{
try
{
if(readCheckout(worktree.executable,worktree.root,{})==GitCheckout{checkout.ref,commit}) return commit;
}
catch(const std::exception &) {}
throw;
}
return commit;
}
}
+71
View File
@@ -0,0 +1,71 @@
#pragma once
#include <filesystem>
#include <stop_token>
#include <string>
#include <vector>
namespace ks::files
{
enum class GitChangeKind { staged, unstaged, untracked };
struct GitChange
{
GitChangeKind kind;
std::wstring path;
std::wstring oldPath;
std::wstring flags;
bool operator==(const GitChange &) const = default;
};
struct GitCheckout
{
std::wstring ref, revision;
bool operator==(const GitCheckout &) const = default;
};
struct GitChanges
{
std::filesystem::path executable, root;
std::vector<GitChange> entries;
GitCheckout checkout;
};
struct GitBranch
{
std::wstring ref, label, revision;
bool current{};
};
struct GitCommit
{
std::wstring revision, abbreviated, date, subject;
};
struct GitHistoryPage
{
std::vector<GitCommit> commits;
bool more{};
};
struct GitCommitReview
{
std::filesystem::path root;
GitCheckout checkout;
std::vector<GitChange> staged;
std::string stagedIdentity;
};
GitChanges readGitChanges(const std::filesystem::path &directory,std::stop_token stop);
std::string readGitPatch(const std::filesystem::path &git,const std::filesystem::path &root,
const GitChange &change,std::stop_token stop);
std::vector<GitBranch> readGitBranches(const std::filesystem::path &git,const std::filesystem::path &root,
std::stop_token stop);
GitHistoryPage readGitHistory(const std::filesystem::path &git,const std::filesystem::path &root,
const std::wstring &revision,size_t offset,std::stop_token stop);
std::string readGitCommit(const std::filesystem::path &git,const std::filesystem::path &root,
const std::wstring &revision,std::stop_token stop);
void changeGitIndex(const GitChanges &worktree,const GitChange &entry,bool replaceStaged,std::stop_token stop);
GitCommitReview reviewGitCommit(const GitChanges &worktree,std::stop_token stop);
std::wstring createGitCommit(const GitChanges &worktree,const GitCommitReview &review,
const std::wstring &message,std::stop_token stop);
}
+904
View File
@@ -0,0 +1,904 @@
using ks::files::GitChange;
using ks::files::GitChangeKind;
using ks::files::GitChanges;
using ks::files::GitBranch;
using ks::files::GitCommit;
using ks::files::GitCommitReview;
using ks::files::GitHistoryPage;
struct GitPreview
{
std::wstring heading;
std::variant<GitChange,std::wstring> item;
};
struct GitHistoryUpdate
{
std::optional<std::vector<GitBranch>> branches;
GitHistoryPage page;
size_t branch=0;
};
struct GitChangesView
{
HWND host{},heading{},switchView{},filterLabel{},filter{},branchPicker{},list{},status{},hints{},preview{},moreButton{};
HWND indexButton{},commitButton{};
fs::path folder;
GitChanges data;
std::future<GitChanges> refresh;
std::future<std::string> previewTask;
std::stop_source stopRefresh,stopPreview;
ULONGLONG previewAt{};
std::optional<GitPreview> requested;
std::string failure;
bool historyMode{},moreHistory{};
std::vector<GitBranch> branches;
std::vector<GitCommit> commits;
size_t branchIndex{};
std::future<GitHistoryUpdate> historyTask;
std::stop_source stopHistory;
std::string historyFailure;
std::future<GitCommitReview> commitReview;
std::future<std::wstring> mutation;
std::stop_source stopMutation;
std::wstring commitDraft,operation,writeStatus;
bool promptingWrite{};
};
std::unique_ptr<GitChangesView> gitChangesView;
constexpr wchar_t gitChangesClass[]=L"KSwitcher.Files.GitChanges";
constexpr UINT_PTR gitChangesTimer=1;
constexpr int gitHeading=570,gitFilter=571,gitList=572,gitStatus=573,gitSwitch=574,gitBranch=575,gitMore=576;
constexpr int gitIndexAction=577,gitCommitAction=578;
const wchar_t *gitChangeKindName(GitChangeKind kind)
{
switch(kind)
{
case GitChangeKind::staged: return L"Staged";
case GitChangeKind::unstaged: return L"Unstaged";
case GitChangeKind::untracked: return L"Untracked";
}
return L"";
}
const GitChange *selectedGitChange(const GitChangesView &view)
{
const auto row=SendMessageW(view.list,LB_GETCURSEL,0,0);
if(row==LB_ERR) return nullptr;
const auto index=SendMessageW(view.list,LB_GETITEMDATA,row,0);
return index>=0 && size_t(index)<view.data.entries.size()?&view.data.entries[index]:nullptr;
}
const GitCommit *selectedGitCommit(const GitChangesView &view)
{
const auto row=SendMessageW(view.list,LB_GETCURSEL,0,0);
if(row==LB_ERR) return nullptr;
const auto index=SendMessageW(view.list,LB_GETITEMDATA,row,0);
return index>=0 && size_t(index)<view.commits.size()?&view.commits[index]:nullptr;
}
std::wstring gitChangePathLabel(const GitChange &entry)
{
return entry.oldPath.empty()?entry.path:entry.path+L" ← "+entry.oldPath;
}
std::wstring gitCheckoutLabel(const ks::files::GitCheckout &checkout)
{
constexpr std::wstring_view prefix=L"refs/heads/";
if(!checkout.ref.starts_with(prefix)) return L"Detached HEAD";
auto label=checkout.ref.substr(prefix.size());
if(checkout.revision.empty()) label+=L" (first commit)";
return label;
}
bool gitActionPending(const GitChangesView &view)
{
return view.commitReview.valid() || view.mutation.valid() || view.promptingWrite;
}
void updateGitActionButtons(GitChangesView &view)
{
const bool ready=!view.historyMode && !view.data.root.empty() && !view.refresh.valid() && !gitActionPending(view);
const auto *entry=view.historyMode?nullptr:selectedGitChange(view);
SetWindowTextW(view.indexButton,entry && entry->kind==GitChangeKind::staged?L"Unstage":L"Stage");
EnableWindow(view.indexButton,ready && entry);
EnableWindow(view.commitButton,ready);
EnableWindow(view.switchView,!view.data.root.empty() && !view.refresh.valid() && !gitActionPending(view));
}
void updateGitChangesStatus(GitChangesView &view,LRESULT shown=-1)
{
if(gitActionPending(view)) {SetWindowTextW(view.status,view.operation.c_str());return;}
if(view.refresh.valid()) {SetWindowTextW(view.status,L"Reading Git changes…");return;}
if(!view.failure.empty()) {SetWindowTextW(view.status,L"Could not read Git changes.");return;}
if(shown<0) shown=SendMessageW(view.list,LB_GETCOUNT,0,0);
const auto count=view.data.entries.size();
const std::wstring summary=!count?L"No Git changes.":shown<=0?L"No paths match the filter.":
std::to_wstring(shown)+(static_cast<size_t>(shown)==count?L"":L" of "+std::to_wstring(count))+L" changes";
SetWindowTextW(view.status,(view.writeStatus.empty()?summary:view.writeStatus+L" · "+summary).c_str());
}
std::wstring gitDiffHeading(const GitChange &entry)
{
return std::wstring(gitChangeKindName(entry.kind))+L" diff · "+entry.path;
}
void queueGitPreview(GitChangesView &view)
{
updateGitActionButtons(view);
view.stopPreview.request_stop();
view.previewTask={};
view.previewAt=0;
view.requested.reset();
if(view.historyMode)
{
if(const auto *commit=selectedGitCommit(view))
{
view.requested=GitPreview{L"Commit · "+commit->abbreviated,commit->revision};
view.previewAt=GetTickCount64()+100;
ks::files::previewQuickViewText(view.preview,view.requested->heading+L" · Loading…",{});
}
else if(!view.historyFailure.empty())
ks::files::previewQuickViewText(view.preview,L"Git history failed",view.historyFailure);
else ks::files::previewQuickViewText(view.preview,
view.historyTask.valid()?L"Commit · Reading history…":L"Commit · Select a commit",{});
return;
}
if(view.refresh.valid())
{
ks::files::previewQuickViewText(view.preview,L"Diff · Reading Git changes…",{});
return;
}
if(!view.failure.empty())
{
ks::files::previewQuickViewText(view.preview,L"Git status failed",view.failure);
return;
}
if(const auto *entry=selectedGitChange(view))
{
view.requested=GitPreview{gitDiffHeading(*entry),*entry};
view.previewAt=GetTickCount64()+100;
ks::files::previewQuickViewText(view.preview,view.requested->heading+L" · Loading…",{});
}
else ks::files::previewQuickViewText(view.preview,L"Diff · Select a change",{});
}
void renderGitChanges(GitChangesView &view,std::optional<GitChange> previous={})
{
auto query=dialogFieldText(view.filter);
std::replace(query.begin(),query.end(),L'\\',L'/');
const auto matches=[&](std::wstring_view path)
{
return query.empty() || (!path.empty() && FindNLSStringEx(LOCALE_NAME_INVARIANT,FIND_FROMSTART|NORM_IGNORECASE,
path.data(),static_cast<int>(path.size()),query.data(),static_cast<int>(query.size()),
nullptr,nullptr,nullptr,0)>=0);
};
SendMessageW(view.list,WM_SETREDRAW,FALSE,0);
SendMessageW(view.list,LB_RESETCONTENT,0,0);
LRESULT selected=0,count=0;
for(size_t index=0;index<view.data.entries.size();++index)
{
const auto &entry=view.data.entries[index];
if(!matches(entry.path) && !matches(entry.oldPath)) continue;
auto state=std::wstring(gitChangeKindName(entry.kind));
state.resize(10,L' ');
state+=entry.flags;
state.resize(13,L' ');
const auto label=state+gitChangePathLabel(entry);
const auto row=SendMessageW(view.list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
if(row<0) continue;
++count;
SendMessageW(view.list,LB_SETITEMDATA,row,index);
if(previous && previous->path==entry.path && previous->kind==entry.kind) selected=row;
}
if(count) SendMessageW(view.list,LB_SETCURSEL,selected,0);
SendMessageW(view.list,WM_SETREDRAW,TRUE,0);
InvalidateRect(view.list,nullptr,TRUE);
InvalidateRect(view.host,nullptr,FALSE);
updateGitChangesStatus(view,count);
queueGitPreview(view);
}
void refreshGitChanges(GitChangesView &view)
{
if(view.refresh.valid() || gitActionPending(view)) return;
view.failure.clear();
view.stopRefresh=std::stop_source{};
try
{
std::packaged_task<GitChanges()> task([folder=view.folder,stop=view.stopRefresh.get_token()] {
return ks::files::readGitChanges(folder,stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.refresh=std::move(pending);
updateGitChangesStatus(view);
queueGitPreview(view);
}
catch(const std::exception &)
{
view.failure="Could not start Git.";
renderGitChanges(view);
}
}
struct GitCommitPrompt
{
const GitCommitReview &review;
std::wstring message;
};
INT_PTR CALLBACK gitCommitDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int branch=594,summary=595,staged=596,body=598,feedback=599,footer=600;
if(message==WM_INITDIALOG)
{
auto &prompt=*reinterpret_cast<GitCommitPrompt *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,branch);
SetDlgItemTextW(dialog,branch,(L"Branch "+gitCheckoutLabel(prompt.review.checkout)).c_str());
SetDlgItemTextW(dialog,summary,(std::to_wstring(prompt.review.staged.size())+L" staged changes · all paths").c_str());
const auto list=GetDlgItem(dialog,staged);
for(const auto &entry:prompt.review.staged)
{
const auto label=entry.flags+L" "+gitChangePathLabel(entry);
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
}
const auto bounds=dialogControlBounds(dialog,staged);
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,dialog);
SendDlgItemMessageW(dialog,body,EM_SETLIMITTEXT,16000,0);
SetDlgItemTextW(dialog,body,prompt.message.c_str());
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(GetDlgItem(dialog,body));
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDCANCEL || LOWORD(wp)==IDOK)))
{
auto &prompt=*reinterpret_cast<GitCommitPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
prompt.message=dialogFieldText(GetDlgItem(dialog,body));
const bool submit=message==WM_COMMAND && LOWORD(wp)==IDOK;
if(submit && prompt.message.find_first_not_of(L" \t\r\n")==prompt.message.npos)
{
SetDlgItemTextW(dialog,feedback,L"Enter a commit message.");
ShowWindow(GetDlgItem(dialog,feedback),SW_SHOWNA);
SetFocus(GetDlgItem(dialog,body));
return TRUE;
}
FilesModalDialog::finish(dialog,submit?IDOK:IDCANCEL);
return TRUE;
}
if(message==WM_COMMAND && LOWORD(wp)==body && HIWORD(wp)==EN_CHANGE)
{
ShowWindow(GetDlgItem(dialog,feedback),SW_HIDE);
SetDlgItemTextW(dialog,feedback,L"");
return TRUE;
}
return paintCopyDialog(dialog,message,wp,lp,L" Commit staged changes ",false,{footer},false,GetDlgItem(dialog,staged));
}
GitChanges gitWorktreeTarget(const GitChangesView &view)
{
return {view.data.executable,view.data.root,{},view.data.checkout};
}
bool gitActionAvailable(const GitChangesView &view)
{
return !view.historyMode && !view.refresh.valid() && !gitActionPending(view) && !view.data.root.empty();
}
void showGitWriteError(GitChangesView &view,const std::exception &error)
{
std::wstring detail;
if(const auto *system=dynamic_cast<const std::system_error *>(&error)) detail=fileError(*system);
else
{
try {detail=ks::wide(error.what());}
catch(const std::exception &) {detail=L"Git returned an error in an unsupported encoding.";}
}
view.promptingWrite=true;
updateGitActionButtons(view);
showFilesNotice(GetParent(view.host),detail.c_str(),L"Git operation failed",{.tone=FilesNoticeTone::warning});
view.promptingWrite=false;
view.writeStatus=L"Git operation failed";
refreshGitChanges(view);
}
void runGitMutation(GitChangesView &view,std::wstring operation,
std::function<std::wstring(std::stop_token)> action)
{
view.stopMutation=std::stop_source{};
view.operation=std::move(operation);
try
{
std::packaged_task<std::wstring()> task([action=std::move(action),stop=view.stopMutation.get_token()] {
return action(stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.mutation=std::move(pending);
updateGitActionButtons(view);
updateGitChangesStatus(view);
}
catch(const std::exception &error) {showGitWriteError(view,error);}
}
void changeSelectedGitIndex(GitChangesView &view)
{
if(!gitActionAvailable(view)) return;
const auto *selected=selectedGitChange(view);
if(!selected) return;
const auto entry=*selected;
const bool stage=entry.kind!=GitChangeKind::staged;
const bool replace=stage && std::any_of(view.data.entries.begin(),view.data.entries.end(),[&](const auto &other) {
return other.kind==GitChangeKind::staged && (other.path==entry.path || other.oldPath==entry.path ||
(!entry.oldPath.empty() && (other.path==entry.oldPath || other.oldPath==entry.oldPath)));
});
if(replace)
{
view.promptingWrite=true;
updateGitActionButtons(view);
const auto message=L"Replace the staged version of "+entry.path+L" with the current working version?";
const auto answer=showFilesNotice(GetParent(view.host),message.c_str(),L"Replace staged changes",
{.confirm=true,.tone=FilesNoticeTone::warning});
view.promptingWrite=false;
updateGitActionButtons(view);
if(answer!=IDYES) return;
}
runGitMutation(view,stage?L"Staging the selected path…":L"Unstaging the selected path…",
[worktree=gitWorktreeTarget(view),entry,replace,stage](std::stop_token stop) {
ks::files::changeGitIndex(worktree,entry,replace,stop);
return stage?std::wstring(L"Path staged"):std::wstring(L"Path unstaged");
});
}
void openGitCommitReview(GitChangesView &view)
{
if(!gitActionAvailable(view)) return;
view.stopMutation=std::stop_source{};
view.operation=L"Reading all staged changes…";
try
{
std::packaged_task<GitCommitReview()> task([worktree=gitWorktreeTarget(view),stop=view.stopMutation.get_token()] {
return ks::files::reviewGitCommit(worktree,stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.commitReview=std::move(pending);
updateGitActionButtons(view);
updateGitChangesStatus(view);
}
catch(const std::exception &error) {showGitWriteError(view,error);}
}
void finishGitCommitReview(GitChangesView &view)
{
try
{
auto review=view.commitReview.get();
GitCommitPrompt prompt{review,view.commitDraft};
view.promptingWrite=true;
const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(126),
GetParent(view.host),gitCommitDialog,reinterpret_cast<LPARAM>(&prompt));
view.promptingWrite=false;
view.commitDraft=std::move(prompt.message);
if(answer==IDOK)
runGitMutation(view,L"Creating the reviewed local commit…",
[worktree=gitWorktreeTarget(view),review=std::move(review),message=view.commitDraft](std::stop_token stop) {
return L"Commit "+ks::files::createGitCommit(worktree,review,message,stop).substr(0,12);
});
else
{
updateGitActionButtons(view);
updateGitChangesStatus(view);
}
}
catch(const std::exception &error)
{
view.promptingWrite=false;
showGitWriteError(view,error);
}
}
void finishGitMutation(GitChangesView &view)
{
try
{
view.writeStatus=view.mutation.get();
if(view.writeStatus.starts_with(L"Commit ")) view.commitDraft.clear();
refreshGitChanges(view);
}
catch(const std::exception &error) {showGitWriteError(view,error);}
}
void updateGitHistoryStatus(GitChangesView &view)
{
const auto status=view.historyTask.valid()?std::wstring(L"Reading Git history…"):
!view.historyFailure.empty()?L"Could not read Git history.":
view.commits.empty()?L"No commits yet.":std::to_wstring(view.commits.size())+L" commits";
SetWindowTextW(view.status,status.c_str());
EnableWindow(view.moreButton,view.moreHistory && !view.historyTask.valid());
}
void renderGitHistory(GitChangesView &view,std::wstring_view preserve={},LRESULT top=0)
{
SendMessageW(view.list,WM_SETREDRAW,FALSE,0);
SendMessageW(view.list,LB_RESETCONTENT,0,0);
LRESULT selected=0;
for(size_t i=0;i<view.commits.size();++i)
{
const auto &commit=view.commits[i];
const auto label=commit.date+L" "+commit.abbreviated+L" "+commit.subject;
const auto row=SendMessageW(view.list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
if(row<0) continue;
SendMessageW(view.list,LB_SETITEMDATA,row,i);
if(preserve==commit.revision) selected=row;
}
if(!view.commits.empty())
{
SendMessageW(view.list,LB_SETCURSEL,selected,0);
if(top>0) SendMessageW(view.list,LB_SETTOPINDEX,top,0);
}
SendMessageW(view.list,WM_SETREDRAW,TRUE,0);
InvalidateRect(view.list,nullptr,TRUE);
InvalidateRect(view.host,nullptr,FALSE);
updateGitHistoryStatus(view);
queueGitPreview(view);
}
void loadGitHistory(GitChangesView &view,bool refreshBranches,bool append=false)
{
if(append && (view.historyTask.valid() || !view.moreHistory)) return;
view.stopHistory.request_stop();
view.historyTask={};
view.stopHistory=std::stop_source{};
view.historyFailure.clear();
const auto offset=append?view.commits.size():0;
const auto haveBranch=view.branchIndex<view.branches.size();
const auto branch=haveBranch?view.branches[view.branchIndex]:GitBranch{};
if(!append)
{
view.commits.clear();
view.moreHistory=false;
}
try
{
std::packaged_task<GitHistoryUpdate()> task([git=view.data.executable,root=view.data.root,
refreshBranches,offset,branch,index=view.branchIndex,stop=view.stopHistory.get_token()]
{
GitHistoryUpdate result;
result.branch=index;
auto revision=branch.revision;
if(refreshBranches)
{
result.branches=ks::files::readGitBranches(git,root,stop);
const auto &branches=*result.branches;
if(branches.empty()) return result;
auto chosen=std::find_if(branches.begin(),branches.end(),[&](const auto &entry){return entry.ref==branch.ref;});
if(chosen==branches.end())
chosen=std::find_if(branches.begin(),branches.end(),[](const auto &entry){return entry.current;});
if(chosen==branches.end()) chosen=branches.begin();
result.branch=static_cast<size_t>(chosen-branches.begin());
revision=chosen->revision;
}
if(!revision.empty()) result.page=ks::files::readGitHistory(git,root,revision,offset,stop);
return result;
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.historyTask=std::move(pending);
}
catch(const std::exception &error) {view.historyFailure=error.what();}
if(!append) renderGitHistory(view);
else updateGitHistoryStatus(view);
}
void finishGitHistory(GitChangesView &view)
{
const auto *entry=selectedGitCommit(view);
const auto selected=entry?entry->revision:std::wstring{};
const auto top=SendMessageW(view.list,LB_GETTOPINDEX,0,0);
try
{
auto result=view.historyTask.get();
view.branchIndex=result.branch;
if(result.branches)
{
view.branches=std::move(*result.branches);
SendMessageW(view.branchPicker,CB_RESETCONTENT,0,0);
for(const auto &branch:view.branches)
SendMessageW(view.branchPicker,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(branch.label.c_str()));
if(!view.branches.empty()) SendMessageW(view.branchPicker,CB_SETCURSEL,view.branchIndex,0);
EnableWindow(view.branchPicker,!view.branches.empty());
}
view.commits.insert(view.commits.end(),std::make_move_iterator(result.page.commits.begin()),
std::make_move_iterator(result.page.commits.end()));
view.moreHistory=result.page.more;
}
catch(const std::exception &error) {view.historyFailure=error.what();}
renderGitHistory(view,selected,top);
}
void pollGitChanges(GitChangesView &view)
{
using namespace std::chrono_literals;
if(view.commitReview.valid() && view.commitReview.wait_for(0ms)==std::future_status::ready)
finishGitCommitReview(view);
if(view.mutation.valid() && view.mutation.wait_for(0ms)==std::future_status::ready)
finishGitMutation(view);
if(view.refresh.valid() && view.refresh.wait_for(0ms)==std::future_status::ready)
{
const auto *entry=selectedGitChange(view);
const auto selected=entry?std::optional(*entry):std::nullopt;
try
{
view.data=view.refresh.get();
SetWindowTextW(view.heading,(L"Git Changes · "+view.data.root.native()).c_str());
renderGitChanges(view,selected);
}
catch(const std::exception &error)
{
view.data={};
view.failure=error.what();
renderGitChanges(view);
}
}
if(view.historyTask.valid() && view.historyTask.wait_for(0ms)==std::future_status::ready)
finishGitHistory(view);
if(view.previewAt && GetTickCount64()>=view.previewAt)
{
view.previewAt=0;
view.stopPreview=std::stop_source{};
try
{
std::packaged_task<std::string()> task([git=view.data.executable,root=view.data.root,
item=view.requested->item,stop=view.stopPreview.get_token()] {
if(const auto *change=std::get_if<GitChange>(&item))
return ks::files::readGitPatch(git,root,*change,stop);
return ks::files::readGitCommit(git,root,std::get<std::wstring>(item),stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.previewTask=std::move(pending);
}
catch(const std::exception &)
{
ks::files::previewQuickViewText(view.preview,view.requested->heading,"Could not start the Git preview.");
}
}
if(view.previewTask.valid() && view.previewTask.wait_for(0ms)==std::future_status::ready)
{
try
{
const auto contents=view.previewTask.get();
ks::files::previewQuickViewText(view.preview,view.requested->heading,
contents.empty()?std::string_view("No differences. Refresh if the worktree has changed."):std::string_view(contents),
std::holds_alternative<GitChange>(view.requested->item));
}
catch(const std::exception &error)
{
ks::files::previewQuickViewText(view.preview,view.requested->heading,error.what());
}
}
}
void openGitWorkingFile(GitChangesView &view,bool edit)
{
const auto *entry=selectedGitChange(view);
if(view.historyMode || !entry || view.refresh.valid() || !view.failure.empty() || gitActionPending(view)) return;
auto relative=fs::path(entry->path);
for(const auto &component:relative)
if(!validFileName(component.native()))
{
SetWindowTextW(view.status,L"This path cannot be opened as a Windows file.");
return;
}
auto path=view.data.root/relative.make_preferred();
const auto attributes=GetFileAttributesW(path.c_str());
if(attributes==INVALID_FILE_ATTRIBUTES || (attributes&FILE_ATTRIBUTE_DIRECTORY))
{
SetWindowTextW(view.status,L"No current working file for this change.");
return;
}
const auto owner=GetParent(view.host);
if(!edit && ks::files::isImagePath(path)) ks::files::openImageWindow(owner,{path},path,textWindowDialogs());
else ks::files::openTextWindow(owner,path,edit,textWindowDialogs());
}
void layoutGitChildren(GitChangesView &view)
{
RECT bounds{};
GetClientRect(view.host,&bounds);
const int middle=panelDivider(bounds.right);
const auto place=[](HWND control,int x,int y,int width,int height)
{
SetWindowPos(control,nullptr,x,y,std::max(0,width),std::max(0,height),SWP_NOZORDER|SWP_NOACTIVATE);
};
const int inset=6,top=4,filterLabel=8*cellWidth,buttonWidth=12*cellWidth;
const int filterTop=top+textHeight+6, listTop=filterTop+textHeight+6;
const int bottom=std::max(listTop,static_cast<int>(bounds.bottom)-textHeight-5);
const int leftWidth=std::max(0,middle-2*inset);
place(view.heading,inset,top,leftWidth-buttonWidth-4,textHeight);
place(view.switchView,inset+leftWidth-buttonWidth,top,buttonWidth,textHeight);
place(view.filterLabel,inset,filterTop,filterLabel,textHeight);
place(view.filter,inset+filterLabel,filterTop,leftWidth-filterLabel,textHeight);
place(view.branchPicker,inset+filterLabel,filterTop,leftWidth-filterLabel,11*textHeight);
place(view.list,inset,listTop,leftWidth-scrollBarWidth(view.list),bottom-listTop);
place(view.status,inset,bottom+3,leftWidth-(view.historyMode?1:2)*(buttonWidth+4),textHeight);
place(view.moreButton,inset+leftWidth-buttonWidth,bottom+3,buttonWidth,textHeight);
place(view.indexButton,inset+leftWidth-2*buttonWidth-4,bottom+3,buttonWidth,textHeight);
place(view.commitButton,inset+leftWidth-buttonWidth,bottom+3,buttonWidth,textHeight);
place(view.preview,middle+inset,top,bounds.right-middle-2*inset,bottom-top);
place(view.hints,middle+inset,bottom+3,bounds.right-middle-2*inset,textHeight);
for(const auto control:{view.heading,view.switchView,view.filterLabel,view.filter,view.branchPicker,
view.list,view.status,view.hints,view.moreButton,view.indexButton,view.commitButton})
SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SendMessageW(view.list,LB_SETITEMHEIGHT,0,textHeight);
}
void switchGitView(GitChangesView &view)
{
if(view.data.root.empty() || view.refresh.valid() || gitActionPending(view)) return;
view.historyMode=!view.historyMode;
const auto title=view.historyMode?L"Git History · ":L"Git Changes · ";
SetWindowTextW(view.heading,(title+view.data.root.native()).c_str());
SetWindowTextW(view.switchView,view.historyMode?L"Changes":L"History");
SetWindowTextW(view.filterLabel,view.historyMode?L"Branch":L"Filter");
SetWindowTextW(view.hints,view.historyMode?L"F6 Changes F7 More Ctrl+R Refresh Esc Back":
L"F3 View F4 Edit F6 History Ctrl+R Refresh Esc Back");
ShowWindow(view.filter,view.historyMode?SW_HIDE:SW_SHOWNA);
ShowWindow(view.branchPicker,view.historyMode?SW_SHOWNA:SW_HIDE);
ShowWindow(view.moreButton,view.historyMode?SW_SHOWNA:SW_HIDE);
ShowWindow(view.indexButton,view.historyMode?SW_HIDE:SW_SHOWNA);
ShowWindow(view.commitButton,view.historyMode?SW_HIDE:SW_SHOWNA);
layoutGitChildren(view);
if(view.historyMode)
{
EnableWindow(view.branchPicker,FALSE);
loadGitHistory(view,true);
}
else
{
view.stopHistory.request_stop();
view.historyTask={};
renderGitChanges(view);
}
SetFocus(view.list);
}
LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_NCCREATE)
{
const auto *create=reinterpret_cast<const CREATESTRUCTW *>(lp);
SetWindowLongPtrW(window,GWLP_USERDATA,reinterpret_cast<LONG_PTR>(create->lpCreateParams));
}
const auto view=reinterpret_cast<GitChangesView *>(GetWindowLongPtrW(window,GWLP_USERDATA));
if(!view) return DefWindowProcW(window,message,wp,lp);
switch(message)
{
case WM_CREATE:
{
view->host=window;
const auto make=[&](const wchar_t *type,const wchar_t *text,DWORD style,int id=0)
{
return CreateWindowW(type,text,WS_CHILD|WS_VISIBLE|style,0,0,0,0,window,
reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),GetModuleHandleW(nullptr),nullptr);
};
view->heading=make(L"STATIC",L"Git Changes",SS_PATHELLIPSIS|SS_NOPREFIX,gitHeading);
view->switchView=make(L"BUTTON",L"History",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitSwitch);
view->filterLabel=make(L"STATIC",L"Filter",SS_NOPREFIX);
view->filter=make(farEditClass,L"",ES_MULTILINE|ES_AUTOHSCROLL|WS_TABSTOP,gitFilter);
view->branchPicker=make(L"COMBOBOX",L"",CBS_DROPDOWNLIST|CBS_OWNERDRAWFIXED|CBS_HASSTRINGS|WS_TABSTOP|WS_VSCROLL,
gitBranch);
view->list=make(L"LISTBOX",L"",LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT|LBS_NOTIFY|WS_TABSTOP,gitList);
view->status=make(L"STATIC",L"",SS_ENDELLIPSIS|SS_NOPREFIX,gitStatus);
view->hints=make(L"STATIC",L"F3 View F4 Edit F6 History Ctrl+R Refresh Esc Back",SS_ENDELLIPSIS|SS_NOPREFIX);
view->moreButton=make(L"BUTTON",L"More",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitMore);
view->indexButton=make(L"BUTTON",L"Stage",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitIndexAction);
view->commitButton=make(L"BUTTON",L"Commit",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitCommitAction);
try {view->preview=ks::files::createQuickView(window,textWindowDialogs());}
catch(const std::exception &) {}
if(!view->heading || !view->switchView || !view->filterLabel || !view->filter || !view->branchPicker ||
!view->list || !view->status || !view->hints || !view->moreButton || !view->indexButton ||
!view->commitButton || !view->preview ||
!SetTimer(window,gitChangesTimer,35,nullptr)) return -1;
prepareDialogEdit(view->filter);
SendMessageW(view->filter,EM_SETLIMITTEXT,1024,0);
ShowWindow(view->branchPicker,SW_HIDE);
ShowWindow(view->moreButton,SW_HIDE);
layoutGitChildren(*view);
installFarCombo(view->branchPicker,view->filter);
installScrollBar(view->list,window);
return 0;
}
case WM_SIZE:
if(view->preview) layoutGitChildren(*view);
return 0;
case WM_TIMER:
if(wp==gitChangesTimer) pollGitChanges(*view);
return 0;
case WM_COMMAND:
if(!view->historyMode && view->preview && LOWORD(wp)==gitFilter && HIWORD(wp)==EN_CHANGE)
{
const auto *entry=selectedGitChange(*view);
renderGitChanges(*view,entry?std::optional(*entry):std::nullopt);
}
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_SELCHANGE) queueGitPreview(*view);
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_DBLCLK) openGitWorkingFile(*view,false);
else if(LOWORD(wp)==gitSwitch && HIWORD(wp)==BN_CLICKED) switchGitView(*view);
else if(view->historyMode && LOWORD(wp)==gitMore && HIWORD(wp)==BN_CLICKED) loadGitHistory(*view,false,true);
else if(LOWORD(wp)==gitIndexAction && HIWORD(wp)==BN_CLICKED) changeSelectedGitIndex(*view);
else if(LOWORD(wp)==gitCommitAction && HIWORD(wp)==BN_CLICKED) openGitCommitReview(*view);
else if(view->historyMode && LOWORD(wp)==gitBranch &&
(HIWORD(wp)==CBN_SELENDOK || (HIWORD(wp)==CBN_SELCHANGE &&
!SendMessageW(view->branchPicker,CB_GETDROPPEDSTATE,0,0))))
{
const auto index=SendMessageW(view->branchPicker,CB_GETCURSEL,0,0);
if(index>=0 && size_t(index)<view->branches.size() && size_t(index)!=view->branchIndex)
{
view->branchIndex=static_cast<size_t>(index);
loadGitHistory(*view,false);
}
}
return 0;
case WM_MEASUREITEM:
reinterpret_cast<MEASUREITEMSTRUCT *>(lp)->itemHeight=textHeight;
return TRUE;
case WM_DRAWITEM:
{
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT *>(lp);
if(item.CtlID==gitBranch) {drawFarComboRow(item);return TRUE;}
if(item.CtlType==ODT_BUTTON) {paintDialogButton(item,colors[Dialog],colors[Text]);return TRUE;}
if(item.itemID==static_cast<UINT>(-1)) return TRUE;
const auto count=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0);
if(count<0) return TRUE;
std::wstring label(count+1,L'\0');
if(SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast<LPARAM>(label.data()))==LB_ERR)
return TRUE;
const bool selected=item.itemState&ODS_SELECTED;
paintText(item.hDC,item.rcItem,label.c_str(),colors[Text],colors[selected?PanelCursor:PanelBlue]);
return TRUE;
}
case WM_CTLCOLORSTATIC:
case WM_CTLCOLOREDIT:
case WM_CTLCOLORLISTBOX:
{
const auto dc=reinterpret_cast<HDC>(wp);
const bool input=message==WM_CTLCOLOREDIT ||
(message==WM_CTLCOLORLISTBOX && reinterpret_cast<HWND>(lp)!=view->list);
SetTextColor(dc,colors[Text]);
SetBkColor(dc,colors[input?Dialog:PanelBlue]);
return reinterpret_cast<LRESULT>(input?teal:blue);
}
case WM_PAINT:
{
PAINTSTRUCT paint{};
const auto dc=BeginPaint(window,&paint);
FillRect(dc,&paint.rcPaint,blue);
if(view->list) paintScrollPosition(window,dc,view->list,colors[PanelBlue]);
EndPaint(window,&paint);
return 0;
}
}
return DefWindowProcW(window,message,wp,lp);
}
void layoutGitChanges(HWND window)
{
if(!gitChangesView) return;
RECT bounds{};
GetClientRect(window,&bounds);
SetWindowPos(gitChangesView->host,HWND_TOP,0,0,bounds.right,bounds.bottom,SWP_NOACTIVATE|SWP_SHOWWINDOW);
layoutGitChildren(*gitChangesView);
}
bool showingGitChanges()
{
return static_cast<bool>(gitChangesView);
}
void closeGitChanges(HWND owner,bool restore=true)
{
if(restore && gitChangesView && gitActionPending(*gitChangesView)) return;
auto view=std::move(gitChangesView);
if(!view) return;
view->stopRefresh.request_stop();
view->stopPreview.request_stop();
view->stopHistory.request_stop();
view->stopMutation.request_stop();
if(IsWindow(view->host)) DestroyWindow(view->host);
if(restore)
{
layout(owner);
restoreCommandFocus();
showFileDetails(panels[active]);
}
}
bool gitChangesAvailable(const Panel &panel)
{
return !terminalVisible && !panel.directory.empty() && !panel.ftp && !panel.peer && !panel.archive &&
!windowsNetworkPath(panel.directory);
}
void openGitChanges(HWND owner,const Panel &panel)
{
if(gitChangesView || !gitChangesAvailable(panel)) return;
const auto instance=GetModuleHandleW(nullptr);
static const bool registered=[instance]
{
WNDCLASSW type{};
type.lpfnWndProc=gitChangesProcedure;
type.hInstance=instance;
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
type.lpszClassName=gitChangesClass;
return RegisterClassW(&type)!=0;
}();
if(!registered) return;
auto view=std::make_unique<GitChangesView>();
view->folder=panel.directory;
if(!CreateWindowW(gitChangesClass,L"Git Changes",WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,
0,0,0,0,owner,nullptr,instance,view.get()))
{
setStatus(L"Could not open Git Changes.");
return;
}
gitChangesView=std::move(view);
closePanelSearch();
hideCompletion();
layout(owner);
ShowWindow(gitChangesView->preview,SW_SHOWNA);
SetFocus(gitChangesView->list);
refreshGitChanges(*gitChangesView);
}
bool handleGitChangesKey(HWND owner,const MSG &message)
{
auto &view=*gitChangesView;
if(message.message!=WM_KEYDOWN || FilesModalDialog::activeFor(owner) ||
(message.hwnd!=owner && message.hwnd!=view.host && !IsChild(view.host,message.hwnd))) return false;
const auto key=message.wParam;
const bool control=GetKeyState(VK_CONTROL)&0x8000;
const bool alt=GetKeyState(VK_MENU)&0x8000;
if(alt) return false;
const auto selector=view.historyMode?view.branchPicker:view.filter;
if(view.historyMode && SendMessageW(view.branchPicker,CB_GETDROPPEDSTATE,0,0)) return false;
if(!control && key==VK_ESCAPE) closeGitChanges(owner);
else if(control && key=='R')
{
if(view.historyMode) loadGitHistory(view,true);
else refreshGitChanges(view);
}
else if(control && key=='F') SetFocus(selector);
else if(!control && key==VK_TAB)
{
std::vector<HWND> focusOrder;
for(const auto controlWindow:{view.list,selector,view.indexButton,view.commitButton,view.switchView,view.moreButton})
if(IsWindowVisible(controlWindow) && IsWindowEnabled(controlWindow)) focusOrder.push_back(controlWindow);
const auto current=std::find(focusOrder.begin(),focusOrder.end(),GetFocus());
if(!focusOrder.empty())
{
const bool reverse=GetKeyState(VK_SHIFT)&0x8000;
const auto index=current==focusOrder.end()?0:static_cast<size_t>(current-focusOrder.begin());
const auto next=reverse?focusOrder.size()-1:1;
SetFocus(focusOrder[(index+next)%focusOrder.size()]);
}
}
else if(!control && key==VK_F6) switchGitView(view);
else if(!control && view.historyMode && key==VK_F7) loadGitHistory(view,false,true);
else if(!control && key==VK_RETURN &&
(GetFocus()==view.indexButton || GetFocus()==view.commitButton || GetFocus()==view.switchView || GetFocus()==view.moreButton))
SendMessageW(GetFocus(),BM_CLICK,0,0);
else if(!control && !view.historyMode && (key==VK_F3 || key==VK_F4 || (key==VK_RETURN && GetFocus()==view.list)))
openGitWorkingFile(view,key==VK_F4);
else if(!control && GetFocus()==view.filter &&
(key==VK_UP || key==VK_DOWN || key==VK_PRIOR || key==VK_NEXT))
SendMessageW(view.list,WM_KEYDOWN,key,message.lParam);
else return false;
return true;
}
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <windows.h>
namespace ks::files
{
inline constexpr UINT filesHelpRequest=WM_APP+273;
enum class FilesHelpTopic
{
panels, menus, navigation, find, transfer, deleteFiles, archive, space, properties, connections,
terminal, viewer, editor, markdown, images, comparison, git, environment, options, keys, appearance, portability, log, mcp, count
};
}
+286
View File
@@ -0,0 +1,286 @@
using ks::files::FilesHelpTopic;
constexpr struct
{
const wchar_t *title,*keywords,*body;
} filesHelpTopics[]{
{L"File panels",L"commander left right selection tabs keyboard refresh",
L"Use Tab to switch panes. Enter opens the selected folder or file. Insert marks an item and advances to the next row. The selection summary counts marked items.\r\n\r\n"
L"The command bar shows the primary keys for common actions. The Left and Right menus switch modes, choose drives, sort items, and filter a pane."},
{L"Menus and shortcuts",L"f9 access keys commands actions configuration",
L"Press F9 to show the menu bar. Use the arrow keys to move between categories and entries. Press Enter to run the highlighted command.\r\n\r\n"
L"Press F1 on a menu item for its topic. Commands → Keyboard shortcuts lists the active scheme and lets you assign extra bindings."},
{L"Locations and navigation",L"folder path history breadcrumbs drives recent bookmark directory unc",
L"Use the breadcrumb in a local or remote pane to jump to an ancestor. The folder history keeps earlier locations for that pane. Choose Recent folders in Change drive to see recent locations in that panel. Enter opens the selected folder, Delete removes it from recent folders, and Esc restores the previous folder.\r\n\r\n"
L"Folder shortcuts open frequently used locations. In the default scheme Ctrl+0–9 recalls a digit and Ctrl+Shift+0–9 adds the current folder."},
{L"Find files",L"search filter mask results alt f7 paths subfolders",
L"Find files searches from the active folder, including subfolders. Supply a filename mask such as *.md. The results show their locations and can be opened or used in file operations.\r\n\r\n"
L"Enter visits a result's folder. Esc stops an active search or returns from the results. Use Quick View for a preview of a local result."},
{L"Copy, move and rename",L"transfer destination mask overwrite permissions timestamps clipboard queue",
L"Copy and Move use the selection in the active pane. The destination starts with the other pane. Check the destination and the conflict policy before starting the operation.\r\n\r\n"
L"Copy/Move options can limit the selection by mask, target several folders, and preserve timestamps or supported permissions. The progress dialog shows the active file and an estimate when enough data has transferred."},
{L"Delete and Recycle Bin",L"permanent remove recovery confirmation shift delete",
L"Delete respects the selected items and shows a confirmation. Local files are sent to the Recycle Bin when supported. Check the notice for remote locations or permanent deletion.\r\n\r\n"
L"Shift+Delete requests permanent deletion. Cancel the confirmation to keep the selection without deleting it."},
{L"Archives",L"zip 7z pack extract compression update",
L"Open a ZIP or 7z archive from a local pane to browse its entries. Copy entries out to extract them. Back out through the parent entry or Esc.\r\n\r\n"
L"Use Pack files to create or update a ZIP or 7z archive. Review the destination, compression and conflict choices before saving."},
{L"Space Analyzer",L"storage folder size allocation disk tree treemap sunburst",
L"Open Space Analyzer from Commands for a local folder. The tree and charts show which folders consume space. Select an item to inspect its contribution and choose the display you need.\r\n\r\n"
L"Logical size describes file data. Allocated size describes disk allocation where it can be measured."},
{L"Properties and locking processes",L"context menu windows owner attributes filesystem locks handle",
L"Properties shows available file details and Windows attributes. The Windows context menu exposes actions supplied by the file type and the operating system.\r\n\r\n"
L"Use Locking processes for selected local items to see processes with open handles. Save any work in the owning program before closing it."},
{L"Network connections",L"ftp sftp smb lan ssh host authentication credentials password remote",
L"The drive picker opens FTP, SFTP and SMB connection profiles, as well as paired LAN computers. SMB profiles and server shares appear in the selected file panel. Press Shift+F4 to add a profile or Enter to open the selected profile or share. Press Esc to go back. Sign in is in the profile context menu.\r\n\r\n"
L"Check the remote server identity when connecting. If a listing is interrupted, use the Refresh command shown in the pane's status line to retry."},
{L"Command line and terminal",L"powershell ssh console history windows command f1",
L"Type a PowerShell command and press Enter to run it in the active pane's context. Ctrl+O switches between the file panes and terminal output. Previous command and Command history use the active keyboard scheme.\r\n\r\n"
L"With a command name at the caret, F1 can open its Windows command reference. With an empty command line F1 opens the Files guide."},
{L"Text Viewer and Quick View",L"preview read file html hex bookmark go to search",
L"View opens a separate window. Quick View previews the local selection alongside its pane. View as hex displays binary data. A local Viewer refreshes when its file is changed externally.\r\n\r\n"
L"Use the Viewer menus for Find, page navigation and bookmarks. Options opens the Viewer appearance page."},
{L"Text Editor",L"edit save encoding f2 f4 f6 external changes buffers",
L"Edit opens a text file for changes. The Editor menu provides Save, Find, undo and encoding controls. Switching to Viewer keeps a pending Editor buffer for the open document.\r\n\r\n"
L"When the disk version changes, choose Reload or Keep buffer. Saving checks the disk version again and reports a conflict if the file has changed."},
{L"Markdown preview",L"markdown rendered source local links images search",
L"Open a Markdown file in Viewer to read the rendered document. Use its navigation controls for local links and its search form to find rendered text. Switch back to source for editing.\r\n\r\n"
L"Options opens the Markdown page for width, font and scale. Markdown's scale is separate from the text Viewer and Editor."},
{L"Image Viewer and Editor",L"png jpeg image zoom rotate crop undo save copy",
L"View opens supported images with fit, zoom and navigation controls. Local PNG and JPEG files can be opened with Edit to rotate or crop them.\r\n\r\n"
L"Use Undo to reverse edits and Save Copy to create a new file. Replacing the original requires confirmation and checks for external changes."},
{L"File comparison",L"diff unified changes left right hunk apply undo whitespace",
L"Select the two files and choose Compare files. Previous and Next jump between change blocks. Unified changes the view, and Fold unchanged collapses matching context.\r\n\r\n"
L"Apply to left or right changes that side's draft. Use Undo or save the selected side when ready. Appearance opens the comparison font, colors and scale."},
{L"Git Changes",L"staged unstaged repository status commit branch diff",
L"Open Git Changes in a Git working tree to inspect changes, branches and history. Select an entry to review its diff.\r\n\r\n"
L"Stage the changes you want to include. Commit staged changes shows the items currently in the index before writing the commit."},
{L"Environment Variables",L"user system process path edit windows variables",
L"Environment Variables lists user, system and process scopes. Choose a scope, then review the selected name and value before editing.\r\n\r\n"
L"Changes to the system scope require the appropriate Windows permission. Existing applications may need to reopen before using updated values."},
{L"Files Options",L"preferences settings search apply reset cancel layout font",
L"Search settings by name or choose a section in the tree. Apply saves the draft and refreshes affected windows. Cancel discards the pending changes.\r\n\r\n"
L"Reset selected to defaults applies to the displayed section. Import JSON and Export JSON transfer supported settings groups between profiles."},
{L"Keyboard schemes",L"keys shortcuts multiple primary named duplicate context conflict",
L"Use Commands → Keyboard shortcuts to switch or copy a named scheme. Select a command, enter a key and choose Add. Make primary controls which binding appears in the command bar.\r\n\r\n"
L"Keys already assigned in an overlapping context cannot be added to another command in that context. F1 opens this guide."},
{L"Appearance and scale",L"theme light dark windows appearance font palette size",
L"Panels, Viewer, Editor, Markdown, terminal and comparison each have a saved scale. Use the visible area's Options or Appearance command to open its settings.\r\n\r\n"
L"Viewer and Editor can use System (Windows). Assign either a stock or named palette to each Windows mode under Appearance → System themes."},
{L"Import and export settings",L"json portable backup restore transfer option groups",
L"Select the saved settings groups to include in an export. The supported groups cover colors and file styles, panel layout and keyboard schemes.\r\n\r\n"
L"Import stages chosen groups in Options. Files asks before replacing differing schemes with the same name. Apply saves the new values."},
{L"Files log",L"diagnostic journal error logging rotate copy record",
L"Open Files log from Commands to see recent entries. Switch between the current and previous rotated log, or use Refresh to read newer entries.\r\n\r\n"
L"Select an entry to copy its timestamp and summary. The viewer shows only supported diagnostic details."},
{L"Files MCP",L"local loopback bearer authorization model context protocol read only search token",
L"Open Commands → Files MCP and select Start. Configure the client with the displayed loopback endpoint and use the session token as the bearer credential.\r\n\r\n"
L"The client can read current local panes, search their displayed entries and read cached file metadata. Stop revokes the session token."}
};
static_assert(std::size(filesHelpTopics)==static_cast<size_t>(FilesHelpTopic::count));
constexpr int helpSearch=670,helpTopics=671,helpTitle=672,helpBody=673;
void displayFilesHelpTopic(HWND dialog,int topic)
{
if(topic<0)
{
SetDlgItemTextW(dialog,helpTitle,L"No matching help topics");
SetDlgItemTextW(dialog,helpBody,L"");
return;
}
const auto &entry=filesHelpTopics[topic];
SetDlgItemTextW(dialog,helpTitle,entry.title);
SetDlgItemTextW(dialog,helpBody,entry.body);
SendDlgItemMessageW(dialog,helpBody,EM_SETSEL,0,0);
SendDlgItemMessageW(dialog,helpBody,EM_SCROLLCARET,0,0);
}
void filterFilesHelpTopics(HWND dialog,int previous)
{
wchar_t buffer[129]{};
GetDlgItemTextW(dialog,helpSearch,buffer,std::size(buffer));
std::wistringstream query(ks::lower(buffer));
std::vector<std::wstring> tokens;
for(std::wstring term;query>>term;) tokens.push_back(std::move(term));
const auto list=GetDlgItem(dialog,helpTopics);
SendMessageW(list,LB_RESETCONTENT,0,0);
int displayed=-1;
LRESULT selected=LB_ERR;
for(size_t i=0;i<std::size(filesHelpTopics);++i)
{
const auto &topic=filesHelpTopics[i];
const auto text=ks::lower(std::wstring(topic.title)+L" "+topic.keywords+L" "+topic.body);
if(!std::ranges::all_of(tokens,[&](const auto &word){return text.find(word)!=text.npos;})) continue;
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(topic.title));
if(row<0) continue;
SendMessageW(list,LB_SETITEMDATA,row,i);
if(selected==LB_ERR || static_cast<int>(i)==previous)
{
selected=row;
displayed=static_cast<int>(i);
}
}
if(selected!=LB_ERR) SendMessageW(list,LB_SETCURSEL,selected,0);
displayFilesHelpTopic(dialog,displayed);
}
int selectedFilesHelpTopic(HWND dialog)
{
const auto row=SendDlgItemMessageW(dialog,helpTopics,LB_GETCURSEL,0,0);
return row==LB_ERR?-1:static_cast<int>(SendDlgItemMessageW(dialog,helpTopics,LB_GETITEMDATA,row,0));
}
INT_PTR CALLBACK filesHelpDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SendDlgItemMessageW(dialog,helpSearch,EM_SETLIMITTEXT,128,0);
filterFilesHelpTopics(dialog,static_cast<int>(lp));
SetFocus(GetDlgItem(dialog,helpSearch));
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL)))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
if(LOWORD(wp)==helpSearch && HIWORD(wp)==EN_CHANGE)
filterFilesHelpTopics(dialog,selectedFilesHelpTopic(dialog));
if(LOWORD(wp)==helpTopics && HIWORD(wp)==LBN_SELCHANGE)
displayFilesHelpTopic(dialog,selectedFilesHelpTopic(dialog));
return TRUE;
}
void showFilesHelp(HWND owner,FilesHelpTopic topic)
{
if(!owner || !IsWindow(owner) || FilesModalDialog::resourceFor(owner)==618) return;
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(618),owner,filesHelpDialog,
static_cast<LPARAM>(topic),false,false);
dialog.runModal();
}
FilesHelpTopic filesMenuHelpTopic()
{
if(folderPicker) return FilesHelpTopic::navigation;
if(!commandPicker) return IsWindowVisible(picker)?FilesHelpTopic::connections:FilesHelpTopic::menus;
const auto row=SendMessageW(picker,LB_GETCURSEL,0,0);
if(!selectablePickerRow(row)) return FilesHelpTopic::menus;
const int action=commandActions[row];
if(menuIndex==0 || menuIndex==4) return action==4?FilesHelpTopic::navigation:FilesHelpTopic::panels;
if(menuIndex==1)
{
if(action==4) return FilesHelpTopic::archive;
if(action==5 || action==6) return FilesHelpTopic::properties;
return action<=2?FilesHelpTopic::transfer:FilesHelpTopic::menus;
}
if(menuIndex!=2) return FilesHelpTopic::menus;
switch(action)
{
case 1: case 4: case 10: case 13: case 14: return FilesHelpTopic::viewer;
case 2: case 5: return FilesHelpTopic::editor;
case 3: case 11: return FilesHelpTopic::navigation;
case 6: case 7: return FilesHelpTopic::connections;
case 8: return FilesHelpTopic::comparison;
case 9: return FilesHelpTopic::find;
case 12: return FilesHelpTopic::space;
case 15: return FilesHelpTopic::properties;
case 16: return FilesHelpTopic::git;
case 17: return FilesHelpTopic::environment;
case 19: return FilesHelpTopic::terminal;
case 20: return FilesHelpTopic::keys;
case 21: return FilesHelpTopic::appearance;
case 23: return FilesHelpTopic::log;
case 24: return FilesHelpTopic::mcp;
default: return FilesHelpTopic::menus;
}
}
std::optional<FilesHelpTopic> filesHelpForWindow(HWND root,HWND target)
{
const auto resource=FilesModalDialog::resourceFor(root);
switch(resource)
{
case 618: return {};
case 101:
{
const auto control=GetDlgCtrlID(target);
if(control==optionsImport || control==optionsExport) return FilesHelpTopic::portability;
if(control==321 || control==comparisonKeySchemesButton) return FilesHelpTopic::keys;
if(const auto *option=reinterpret_cast<const OptionsDraft*>(GetWindowLongPtrW(root,DWLP_USER)))
{
if(option->page==Appearance || control==areaScaleControl) return FilesHelpTopic::appearance;
if(option->page==TextViewer && option->section==markdownSection) return FilesHelpTopic::markdown;
if(option->page==PanelModes) return FilesHelpTopic::panels;
if(option->page==CommandLine) return FilesHelpTopic::terminal;
if(option->page==CompareFiles) return FilesHelpTopic::comparison;
}
return FilesHelpTopic::options;
}
case 102: case 103: case 104: case 105: case 108: case 113: case 129: return FilesHelpTopic::transfer;
case 106: case 107: return FilesHelpTopic::deleteFiles;
case 109: case 110: case 117: return FilesHelpTopic::navigation;
case 111: return FilesHelpTopic::terminal;
case 112: case 121: case 122: case 123: case 124: return FilesHelpTopic::connections;
case 114: case 115: return FilesHelpTopic::comparison;
case 116: return FilesHelpTopic::find;
case 118: return FilesHelpTopic::space;
case 119: return FilesHelpTopic::panels;
case 120: return FilesHelpTopic::archive;
case 125: case 609: return FilesHelpTopic::properties;
case 126: return FilesHelpTopic::git;
case 127: case 128: return FilesHelpTopic::environment;
case 130: return FilesHelpTopic::images;
case 602: case 613: case 614: return FilesHelpTopic::viewer;
case 603: case 611: case 612: return FilesHelpTopic::editor;
case 608: return FilesHelpTopic::appearance;
case 615: case 616: return FilesHelpTopic::keys;
case 617: return FilesHelpTopic::portability;
case 619: return FilesHelpTopic::log;
case 620: return FilesHelpTopic::mcp;
case 604: case 607:
if(const auto owner=GetWindow(root,GW_OWNER);owner && owner!=root)
return filesHelpForWindow(owner,owner);
break;
}
if(comparisonWindows.contains(root)) return FilesHelpTopic::comparison;
if(const auto area=ks::files::textWindowAppearanceArea(root))
return *area==AppearanceArea::markdown?FilesHelpTopic::markdown:
*area==AppearanceArea::editor?FilesHelpTopic::editor:FilesHelpTopic::viewer;
wchar_t type[64]{};
GetClassNameW(root,type,std::size(type));
if(std::wstring_view(type)==L"KSwitcherFilesImageViewer") return FilesHelpTopic::images;
if(root!=GetParent(terminalInput)) return resource?std::optional(FilesHelpTopic::options):std::nullopt;
if(gitChangesView && (target==gitChangesView->host || IsChild(gitChangesView->host,target))) return FilesHelpTopic::git;
if(quickImageWindow && (target==quickImageWindow || IsChild(quickImageWindow,target))) return FilesHelpTopic::images;
if(quickViewWindow && (target==quickViewWindow || IsChild(quickViewWindow,target))) return FilesHelpTopic::viewer;
if(IsWindowVisible(menuBar) || IsWindowVisible(picker)) return filesMenuHelpTopic();
if(terminalVisible || target==terminalOutput || IsChild(terminalOutput,target)) return FilesHelpTopic::terminal;
if(target==panels[0].path || target==panels[1].path) return FilesHelpTopic::navigation;
return panels[active].findOrigin?FilesHelpTopic::find:FilesHelpTopic::panels;
}
bool handleFilesHelpMessage(const MSG &message)
{
const bool posted=message.message==ks::files::filesHelpRequest;
if(!message.hwnd || (!posted && (message.message!=WM_KEYDOWN || message.wParam!=VK_F1 ||
((GetKeyState(VK_CONTROL)|GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|
GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)))) return false;
const auto root=GetAncestor(message.hwnd,GA_ROOT);
auto target=message.hwnd;
if(root==target)
if(const auto focus=GetFocus();focus && IsChild(root,focus)) target=focus;
if(FilesModalDialog::resourceFor(root)==618) return true;
const auto topic=posted && message.hwnd==GetParent(terminalInput)?
std::optional(FilesHelpTopic::terminal):filesHelpForWindow(root,target);
if(!topic) return false;
if(!posted)
{
if(message.lParam&(1LL<<30)) return true;
if(target==terminalInput && commandLineAvailable(root) && handleCompletionKey(VK_F1,message.lParam))
return true;
}
showFilesHelp(root,*topic);
return true;
}
+231
View File
@@ -0,0 +1,231 @@
#include "files_image_decode.h"
#include <windows.h>
#include <wincodec.h>
#include <webp/decode.h>
#include <webp/demux.h>
#include <algorithm>
#include <cstring>
#include <fstream>
#include <memory>
#include <stdexcept>
namespace ks::files
{
namespace
{
namespace fs=std::filesystem;
constexpr char invalidImage[]="Could not decode the image. The file may be damaged.";
constexpr char largeImage[]="This image is too large to preview.";
enum class ImageFormat { unknown, png, jpeg, gif, webp, bmp };
ImageFormat imageFormat(const fs::path &path)
{
const auto extension=path.extension();
const auto matches=[&](const wchar_t *suffix)
{
return CompareStringOrdinal(extension.c_str(),-1,suffix,-1,TRUE)==CSTR_EQUAL;
};
if(matches(L".png")) return ImageFormat::png;
if(matches(L".jpg") || matches(L".jpeg") || matches(L".jpe")) return ImageFormat::jpeg;
if(matches(L".gif")) return ImageFormat::gif;
if(matches(L".webp")) return ImageFormat::webp;
if(matches(L".bmp")) return ImageFormat::bmp;
return ImageFormat::unknown;
}
void checkImage(HRESULT result)
{
if(FAILED(result)) throw std::runtime_error(invalidImage);
}
void checkImageDimensions(unsigned width,unsigned height)
{
if(!width || !height) throw std::runtime_error(invalidImage);
if(width>16384 || height>16384 || uint64_t(width)*height>32ULL*1024*1024)
throw std::runtime_error(largeImage);
}
void checkImageStop(std::stop_token stop)
{
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
}
template<class T>
struct ImagingObject
{
T *value{};
~ImagingObject() {if(value) value->Release();}
T *operator->() const {return value;}
};
struct Apartment
{
const HRESULT initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
~Apartment() {if(SUCCEEDED(initialized)) CoUninitialize();}
};
ImageRaster decodeNativeImage(const fs::path &file,ImageFormat format,std::stop_token stop)
{
const Apartment apartment;
if(apartment.initialized!=RPC_E_CHANGED_MODE) checkImage(apartment.initialized);
ImagingObject<IWICImagingFactory> factory;
checkImage(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory.value)));
ImagingObject<IWICStream> stream;
checkImage(factory->CreateStream(&stream.value));
checkImage(stream->InitializeFromFilename(file.c_str(),GENERIC_READ));
const auto &container=format==ImageFormat::png?GUID_ContainerFormatPng:
format==ImageFormat::jpeg?GUID_ContainerFormatJpeg:format==ImageFormat::gif?GUID_ContainerFormatGif:
GUID_ContainerFormatBmp;
ImagingObject<IWICBitmapDecoder> decoder;
checkImage(factory->CreateDecoder(container,nullptr,&decoder.value));
checkImage(decoder->Initialize(stream.value,WICDecodeMetadataCacheOnDemand));
ImagingObject<IWICBitmapFrameDecode> frame;
checkImage(decoder->GetFrame(0,&frame.value));
ImageRaster raster;
checkImage(frame->GetSize(&raster.width,&raster.height));
checkImageDimensions(raster.width,raster.height);
checkImageStop(stop);
ImagingObject<IWICFormatConverter> formatConverter;
checkImage(factory->CreateFormatConverter(&formatConverter.value));
checkImage(formatConverter->Initialize(frame.value,GUID_WICPixelFormat32bppPBGRA,WICBitmapDitherTypeNone,
nullptr,0,WICBitmapPaletteTypeCustom));
raster.pixels.resize(size_t(raster.width)*raster.height);
checkImage(formatConverter->CopyPixels(nullptr,raster.width*sizeof(uint32_t),
static_cast<UINT>(raster.pixels.size()*sizeof(uint32_t)),reinterpret_cast<BYTE *>(raster.pixels.data())));
return raster;
}
ImageRaster decodeWebp(const fs::path &file,size_t size,std::stop_token stop)
{
std::vector<uint8_t> bytes(size);
std::ifstream stream(file,std::ios::binary);
if(!stream.read(reinterpret_cast<char *>(bytes.data()),size)) throw std::runtime_error(invalidImage);
WebPBitstreamFeatures info{};
if(WebPGetFeatures(bytes.data(),bytes.size(),&info)!=VP8_STATUS_OK) throw std::runtime_error(invalidImage);
ImageRaster raster{static_cast<unsigned>(info.width),static_cast<unsigned>(info.height)};
checkImageDimensions(raster.width,raster.height);
checkImageStop(stop);
raster.pixels.resize(size_t(raster.width)*raster.height);
auto *output=reinterpret_cast<uint8_t *>(raster.pixels.data());
const auto outputSize=raster.pixels.size()*sizeof(uint32_t);
if(info.has_animation)
{
WebPAnimDecoderOptions options{};
if(!WebPAnimDecoderOptionsInit(&options)) throw std::runtime_error(invalidImage);
options.color_mode=MODE_bgrA;
const WebPData data{bytes.data(),bytes.size()};
const std::unique_ptr<WebPAnimDecoder,decltype(&WebPAnimDecoderDelete)> decoder(
WebPAnimDecoderNew(&data,&options),WebPAnimDecoderDelete);
uint8_t *frame=nullptr;
int timestamp{};
if(!decoder || !WebPAnimDecoderGetNext(decoder.get(),&frame,&timestamp))
throw std::runtime_error(invalidImage);
std::memcpy(output,frame,outputSize);
}
else
{
WebPDecoderConfig config{};
if(!WebPInitDecoderConfig(&config)) throw std::runtime_error(invalidImage);
config.output.colorspace=MODE_bgrA;
config.output.is_external_memory=1;
config.output.u.RGBA={output,static_cast<int>(raster.width*sizeof(uint32_t)),outputSize};
const auto status=WebPDecode(bytes.data(),bytes.size(),&config);
WebPFreeDecBuffer(&config.output);
if(status!=VP8_STATUS_OK) throw std::runtime_error(invalidImage);
}
return raster;
}
}
bool isImagePath(const std::filesystem::path &path)
{
return imageFormat(path)!=ImageFormat::unknown;
}
bool isEditableImagePath(const std::filesystem::path &path)
{
const auto format=imageFormat(path);
return format==ImageFormat::png || format==ImageFormat::jpeg;
}
void encodeImage(const ImageRaster &raster,const fs::path &contents,const fs::path &name)
{
const auto format=imageFormat(name);
if(format!=ImageFormat::png && format!=ImageFormat::jpeg)
throw std::runtime_error("Choose a PNG or JPEG file.");
checkImageDimensions(raster.width,raster.height);
if(raster.pixels.size()!=size_t(raster.width)*raster.height) throw std::runtime_error(invalidImage);
const auto check=[](HRESULT result) {
if(FAILED(result)) throw std::system_error(static_cast<int>(result),std::system_category(),"Encode image");
};
const Apartment apartment;
if(apartment.initialized!=RPC_E_CHANGED_MODE) check(apartment.initialized);
ImagingObject<IWICImagingFactory> factory;
check(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory.value)));
const bool png=format==ImageFormat::png;
ImagingObject<IWICStream> stream;
check(factory->CreateStream(&stream.value));
check(stream->InitializeFromFilename(contents.c_str(),GENERIC_WRITE));
ImagingObject<IWICBitmapEncoder> encoder;
check(factory->CreateEncoder(png?GUID_ContainerFormatPng:GUID_ContainerFormatJpeg,nullptr,&encoder.value));
check(encoder->Initialize(stream.value,WICBitmapEncoderNoCache));
ImagingObject<IWICBitmapFrameEncode> frame;
ImagingObject<IPropertyBag2> options;
check(encoder->CreateNewFrame(&frame.value,&options.value));
if(!png)
{
wchar_t qualityName[]=L"ImageQuality";
PROPBAG2 property{};
property.pstrName=qualityName;
VARIANT quality{};
quality.vt=VT_R4;
quality.fltVal=0.95f;
check(options->Write(1,&property,&quality));
}
check(frame->Initialize(options.value));
check(frame->SetSize(raster.width,raster.height));
auto pixelFormat=png?GUID_WICPixelFormat32bppBGRA:GUID_WICPixelFormat24bppBGR;
check(frame->SetPixelFormat(&pixelFormat));
auto *pixels=raster.pixels.data();
std::vector<uint32_t> opaque;
if(!png && std::any_of(raster.pixels.begin(),raster.pixels.end(),[](uint32_t pixel){return (pixel>>24)!=255;}))
{
opaque=raster.pixels;
for(auto &pixel:opaque)
{
const auto white=255-(pixel>>24);
const auto gray=white|(white<<8)|(white<<16);
pixel=0xff000000|((pixel&0x00ffffff)+gray);
}
pixels=opaque.data();
}
const auto stride=static_cast<UINT>(raster.width*sizeof(uint32_t));
ImagingObject<IWICBitmap> source;
check(factory->CreateBitmapFromMemory(raster.width,raster.height,GUID_WICPixelFormat32bppPBGRA,stride,
static_cast<UINT>(raster.pixels.size()*sizeof(uint32_t)),
reinterpret_cast<BYTE *>(const_cast<uint32_t *>(pixels)),&source.value));
ImagingObject<IWICFormatConverter> converter;
check(factory->CreateFormatConverter(&converter.value));
check(converter->Initialize(source.value,pixelFormat,WICBitmapDitherTypeNone,nullptr,0,WICBitmapPaletteTypeCustom));
check(frame->WriteSource(converter.value,nullptr));
check(frame->Commit());
check(encoder->Commit());
check(stream->Commit(STGC_DEFAULT));
}
ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop)
{
const auto format=imageFormat(name);
if(format==ImageFormat::unknown) throw std::runtime_error("This image format is not supported.");
checkImageStop(stop);
const auto size=std::filesystem::file_size(contents);
if(size==0) throw std::runtime_error(invalidImage);
if(size>imageSourceLimit) throw std::runtime_error(largeImage);
auto image=format==ImageFormat::webp?decodeWebp(contents,static_cast<size_t>(size),stop):
decodeNativeImage(contents,format,stop);
checkImageStop(stop);
return image;
}
}
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include <cstdint>
#include <filesystem>
#include <stop_token>
#include <vector>
namespace ks::files
{
struct ImageRaster
{
unsigned width{}, height{};
std::vector<uint32_t> pixels; // Premultiplied BGRA.
};
inline constexpr uint64_t imageSourceLimit=96ULL*1024*1024;
bool isImagePath(const std::filesystem::path &path);
bool isEditableImagePath(const std::filesystem::path &path);
void encodeImage(const ImageRaster &raster,const std::filesystem::path &contents,const std::filesystem::path &name);
ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop={});
}
+131
View File
@@ -0,0 +1,131 @@
#include "files_image_edit.h"
#include "files_win32_replace.h"
#include <system_error>
namespace ks::files
{
namespace
{
struct ImageFile
{
HANDLE handle=INVALID_HANDLE_VALUE;
~ImageFile() {if(handle!=INVALID_HANDLE_VALUE) CloseHandle(handle);}
};
struct StagedImage
{
std::filesystem::path path;
~StagedImage() {if(!path.empty()) DeleteFileW(path.c_str());}
};
[[noreturn]] void fail(const char *message,DWORD error=GetLastError())
{
throw std::system_error(static_cast<int>(error),std::system_category(),message);
}
ImageRevision readRevision(HANDLE handle)
{
const auto revision=fileVersion(handle);
if(revision.info.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT))
throw std::runtime_error("Choose a regular local image.");
return revision;
}
bool contains(unsigned width,unsigned height,const ImageRegion &area)
{
return area.width && area.height && area.x<width && area.y<height &&
area.width<=width-area.x && area.height<=height-area.y;
}
}
ImageGeometry cropImage(ImageGeometry geometry,const ImageRegion &area)
{
auto &region=geometry.region;
const bool sideways=(geometry.turns&1)!=0;
if(geometry.turns>=4 || !contains(sideways?region.height:region.width,sideways?region.width:region.height,area))
throw std::runtime_error("The crop rectangle must fit inside the image.");
const auto width=region.width, height=region.height;
switch(geometry.turns)
{
case 0: region.x+=area.x; region.y+=area.y; break;
case 1: region.x+=area.y; region.y+=height-area.x-area.width; break;
case 2: region.x+=width-area.x-area.width; region.y+=height-area.y-area.height; break;
case 3: region.x+=width-area.y-area.height; region.y+=area.x; break;
}
region.width=sideways?area.height:area.width;
region.height=sideways?area.width:area.height;
return geometry;
}
ImageRaster transformImage(const ImageRaster &original,const ImageGeometry &geometry)
{
const auto &region=geometry.region;
if(geometry.turns>=4 || !contains(original.width,original.height,region) ||
original.pixels.size()!=size_t(original.width)*original.height)
throw std::runtime_error("The image edit exceeds the original bounds.");
const bool sideways=geometry.turns&1;
ImageRaster output{sideways?region.height:region.width,sideways?region.width:region.height,{}};
output.pixels.resize(size_t(output.width)*output.height);
for(unsigned y=0;y<output.height;++y)
{
for(unsigned x=0;x<output.width;++x)
{
unsigned fromX{},fromY{};
switch(geometry.turns)
{
case 0: fromX=x; fromY=y; break;
case 1: fromX=y; fromY=region.height-1-x; break;
case 2: fromX=region.width-1-x; fromY=region.height-1-y; break;
case 3: fromX=region.width-1-y; fromY=x; break;
}
output.pixels[size_t(y)*output.width+x]=original.pixels[size_t(region.y+fromY)*original.width+region.x+fromX];
}
}
return output;
}
ImageRevision imageRevision(const std::filesystem::path &path)
{
ImageFile file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.handle==INVALID_HANDLE_VALUE) fail("Open image revision");
return readRevision(file.handle);
}
bool sameImageRevision(const ImageRevision &first,const ImageRevision &second)
{
return first==second;
}
ImageRevision saveImage(const ImageRaster &raster,const std::filesystem::path &path,const ImageRevision *expected)
{
const auto stagedPath=temporaryPath(path.parent_path());
{
ImageFile reserve{CreateFileW(stagedPath.c_str(),GENERIC_WRITE,0,nullptr,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,nullptr)};
if(reserve.handle==INVALID_HANDLE_VALUE) fail("Create image staging file");
}
StagedImage pending{stagedPath};
encodeImage(raster,pending.path,path);
// Keep the saved file's identity through publication, even if the path changes again.
ImageFile saved{CreateFileW(pending.path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(saved.handle==INVALID_HANDLE_VALUE) fail("Track saved image");
if(!expected)
{
if(!MoveFileExW(pending.path.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH)) fail("Publish image copy");
pending.path.clear();
return readRevision(saved.handle);
}
ImageFile current{CreateFileW(path.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,nullptr,
OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(current.handle==INVALID_HANDLE_VALUE) fail("Verify original image");
if(!sameImageRevision(*expected,readRevision(current.handle)))
throw std::runtime_error("The original image changed outside Files. Your edits remain open.");
const auto backup=temporaryPath(path.parent_path());
if(const auto error=replaceFileWithBackup(path,pending.path,backup)) fail("Replace original image",error);
pending.path.clear();
DeleteFileW(backup.c_str());
return readRevision(saved.handle);
}
}
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include "files_image_decode.h"
#include "files_win32_replace.h"
namespace ks::files
{
struct ImageRegion
{
unsigned x{}, y{}, width{}, height{};
bool operator==(const ImageRegion &) const = default;
};
struct ImageGeometry
{
ImageRegion region;
unsigned turns{};
bool operator==(const ImageGeometry &) const = default;
};
using ImageRevision=LocalFileVersion;
ImageGeometry cropImage(ImageGeometry geometry,const ImageRegion &area);
ImageRaster transformImage(const ImageRaster &original,const ImageGeometry &geometry);
ImageRevision imageRevision(const std::filesystem::path &path);
bool sameImageRevision(const ImageRevision &first,const ImageRevision &second);
ImageRevision saveImage(const ImageRaster &raster,const std::filesystem::path &path,const ImageRevision *expected=nullptr);
}
+109
View File
@@ -0,0 +1,109 @@
struct ImageCropPrompt
{
unsigned width,height;
ks::files::ImageRegion result;
};
INT_PTR CALLBACK imageCropDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int hint=650, x=651, y=652, width=653, height=654, footer=655;
if(message==WM_DRAWITEM)
{
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),RGB(192,192,192),RGB(0,0,0),true);
return TRUE;
}
if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Crop image ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
{
auto &prompt=*reinterpret_cast<ImageCropPrompt *>(lp);
SetWindowLongPtrW(window,DWLP_USER,lp);
prepareCopyDialog(window);
layoutDialogContent(window,hint);
layoutDialogButtons(window,footer,{IDOK,IDCANCEL});
const auto description=L"Image: "+std::to_wstring(prompt.width)+L" × "+std::to_wstring(prompt.height)+
L" pixels. X and Y start at zero.";
SetDlgItemTextW(window,hint,description.c_str());
for(const auto id:{x,y,width,height})
{
fitFarEditToLine(GetDlgItem(window,id));
const auto value=id==width?prompt.width:id==height?prompt.height:0;
SetDlgItemInt(window,id,value,FALSE);
}
SetFocus(GetDlgItem(window,x));
SendDlgItemMessageW(window,x,EM_SETSEL,0,-1);
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(window,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &prompt=*reinterpret_cast<ImageCropPrompt *>(GetWindowLongPtrW(window,DWLP_USER));
std::array<unsigned,4> fields{};
for(size_t i=0;i<fields.size();++i)
{
const int id=x+static_cast<int>(i);
BOOL valid{};
fields[i]=GetDlgItemInt(window,id,&valid,FALSE);
if(!valid)
{
showFilesNotice(window,L"Enter a whole number of pixels.",L"Crop image");
SetFocus(GetDlgItem(window,id));
return TRUE;
}
}
const auto [left,top,wide,high]=fields;
if(!wide || !high || left>=prompt.width || top>=prompt.height ||
wide>prompt.width-left || high>prompt.height-top)
{
showFilesNotice(window,L"The crop rectangle must fit inside the image.",L"Crop image");
return TRUE;
}
prompt.result={left,top,wide,high};
FilesModalDialog::finish(window,IDOK);
return TRUE;
}
ks::files::ImageEditDialogs imageEditDialogs()
{
return {
[](HWND owner,unsigned width,unsigned height) -> std::optional<ks::files::ImageRegion>
{
ImageCropPrompt crop{width,height,{}};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(130),owner,
imageCropDialog,reinterpret_cast<LPARAM>(&crop))==IDOK) return crop.result;
return {};
},
[](HWND owner,const fs::path &original) -> fs::path
{
const auto name=original.stem().native()+L" copy"+original.extension().native();
std::array<wchar_t,32768> file{};
wcsncpy_s(file.data(),file.size(),name.c_str(),_TRUNCATE);
auto initial=original.parent_path().native();
OPENFILENAMEW dialog{sizeof(dialog)};
dialog.hwndOwner=owner;
dialog.lpstrTitle=L"Save an image copy";
dialog.lpstrFilter=L"PNG (*.png)\0*.png\0JPEG (*.jpg, *.jpeg)\0*.jpg;*.jpeg\0";
dialog.nFilterIndex=ks::lower(original.extension().native())==L".png"?1:2;
dialog.lpstrFile=file.data();
dialog.nMaxFile=static_cast<DWORD>(file.size());
dialog.lpstrInitialDir=initial.c_str();
dialog.lpstrDefExt=dialog.nFilterIndex==1?L"png":L"jpg";
dialog.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST;
if(GetSaveFileNameW(&dialog)) return file.data();
if(CommDlgExtendedError()) throw std::runtime_error("Could not open the image save dialog.");
return {};
},
[](HWND owner,const std::wstring &text,const wchar_t *title)
{
return showFilesNotice(owner,text.c_str(),title,{.confirm=true,.tone=FilesNoticeTone::warning})==IDYES;
},
[](HWND owner,const wchar_t *text)
{
showFilesNotice(owner,text,L"Image editor",{.tone=FilesNoticeTone::warning});
},
FilesModalDialog::dismissOwned,textWindowDialogs().reloadChanged
};
}
+672
View File
@@ -0,0 +1,672 @@
#include "files_image_view.h"
#include "platform.h"
#include <windowsx.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <cstring>
#include <future>
#include <map>
#include <memory>
#include <thread>
#include <utility>
namespace ks::files
{
namespace
{
namespace fs=std::filesystem;
constexpr wchar_t imageWindowClass[]=L"KSwitcherFilesImageViewer";
constexpr UINT_PTR imageTimer=1, externalImageTimer=2;
enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize,
rotateLeft, rotateRight, crop, undoEdit, saveCopy, replaceOriginal };
void fillImageView(HDC dc,const RECT &rect,COLORREF color)
{
SetDCBrushColor(dc,color);
FillRect(dc,&rect,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
}
struct ImageView
{
HWND window{};
bool embedded{};
ImageViewStyle style;
std::vector<fs::path> images;
size_t position{};
ImageLoad load;
ImageLoadRetry retry;
bool retried{};
std::function<void(HWND)> onClose;
std::array<HWND,replaceOriginal> buttons{};
struct Draft
{
ImageEditDialogs dialogs;
ImageRaster original;
std::optional<ImageRevision> version;
ImageGeometry geometry{}, saved{};
std::vector<ImageGeometry> undo;
bool dirty() const {return geometry!=saved;}
};
std::optional<Draft> draft;
struct Loaded
{
ImageRaster raster;
std::optional<ImageRevision> revision;
};
bool confirmingClose{};
std::optional<ImageRevision> observedVersion;
HFONT font{};
UINT fontDpi{};
int toolbarHeight{};
HBITMAP bitmap{};
unsigned width{},height{};
fs::path requested;
std::wstring error;
std::future<Loaded> reading;
std::stop_source stop;
uint64_t revision{}, started{};
double zoom=1, x{}, y{};
bool fit=true, dragging{};
POINT lastMouse{};
~ImageView()
{
stop.request_stop();
if(bitmap) DeleteObject(bitmap);
if(font) DeleteObject(font);
}
int scale(int pixels) const {return MulDiv(pixels,GetDpiForWindow(window),96);}
RECT viewport() const
{
RECT area{};
GetClientRect(window,&area);
area.top=std::min(area.bottom,static_cast<LONG>(toolbarHeight));
area.bottom=std::max(area.top,area.bottom-scale(27));
return area;
}
void layout()
{
const auto dpi=GetDpiForWindow(window);
if(fontDpi!=dpi)
{
LOGFONTW definition=style.font;
definition.lfHeight=-MulDiv(style.tenthsOfPoint,dpi,720);
if(const auto next=CreateFontIndirectW(&definition))
{
if(font) DeleteObject(font);
font=next;
fontDpi=dpi;
}
}
RECT bounds{};
GetClientRect(window,&bounds);
const int left=scale(4), gap=scale(3), height=scale(27);
const auto place=[&](unsigned first,unsigned last,int y,int preferred) {
const auto count=static_cast<int>(last-first+1);
const auto available=std::max(0,static_cast<int>(bounds.right)-left*2-gap*(count-1));
const auto unit=std::min(scale(preferred),available/count);
int x=left;
for(unsigned id=first;id<=last;++id)
{
SetWindowPos(buttons[id-1],nullptr,x,scale(y),unit,height,SWP_NOZORDER|SWP_NOACTIVATE);
x+=unit+gap;
}
};
place(embedded || draft?zoomOut:previous,actualSize,4,80);
int rows=0;
if(draft)
{
int buttonWidth=scale(80);
if(const auto dc=GetDC(window))
{
const auto previousFont=font?SelectObject(dc,font):nullptr;
for(unsigned id=rotateLeft;id<=replaceOriginal;++id)
{
wchar_t label[32]{};
const auto length=GetWindowTextW(buttons[id-1],label,static_cast<int>(std::size(label)));
SIZE extent{};
if(GetTextExtentPoint32W(dc,label,length,&extent))
buttonWidth=std::max(buttonWidth,static_cast<int>(extent.cx)+scale(8));
}
if(previousFont) SelectObject(dc,previousFont);
ReleaseDC(window,dc);
}
const auto perRow=static_cast<unsigned>(std::max(1,(static_cast<int>(bounds.right)-left*2+gap)/(buttonWidth+gap)));
for(unsigned first=rotateLeft;first<=replaceOriginal;first+=perRow)
place(first,std::min<unsigned>(replaceOriginal,first+perRow-1),35+31*rows++,130);
}
toolbarHeight=scale(35+31*rows);
clampOffset();
InvalidateRect(window,nullptr,FALSE);
}
void updateButtons() const
{
if(!embedded && !draft)
{
EnableWindow(buttons[previous-1],position>0);
EnableWindow(buttons[following-1],position+1<images.size());
}
for(unsigned id=zoomOut;id<=actualSize;++id) EnableWindow(buttons[id-1],bitmap!=nullptr);
if(draft)
{
for(unsigned id=rotateLeft;id<=crop;++id) EnableWindow(buttons[id-1],bitmap!=nullptr);
EnableWindow(buttons[undoEdit-1],!draft->undo.empty());
EnableWindow(buttons[saveCopy-1],bitmap!=nullptr);
EnableWindow(buttons[replaceOriginal-1],draft->version && draft->dirty());
const auto title=L"Editor — "+requested.filename().wstring()+(draft->dirty()?L" *":L"");
SetWindowTextW(window,title.c_str());
}
for(auto button:buttons)
if(button) InvalidateRect(button,nullptr,FALSE);
}
void request(const fs::path &path,bool reload=false)
{
if(requested==path && !reload) return;
requested=path;
++revision;
stop.request_stop();
retried=false;
error.clear();
if(!reload)
{
observedVersion.reset();
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
width=height=0;
fit=true;
x=y=0;
}
if(!embedded && !draft)
{
const auto label=L"Viewer — "+path.filename().wstring();
SetWindowTextW(window,label.c_str());
}
updateButtons();
SetTimer(window,imageTimer,30,nullptr);
InvalidateRect(window,nullptr,FALSE);
}
void show(const ImageRaster &image)
{
BITMAPINFO info{};
info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
info.bmiHeader.biWidth=static_cast<LONG>(image.width);
info.bmiHeader.biHeight=-static_cast<LONG>(image.height);
info.bmiHeader.biPlanes=1;
info.bmiHeader.biBitCount=32;
info.bmiHeader.biCompression=BI_RGB;
void *bits=nullptr;
const auto next=CreateDIBSection(nullptr,&info,DIB_RGB_COLORS,&bits,nullptr,0);
if(!next || !bits)
{
if(next) DeleteObject(next);
throw std::runtime_error("Could not display this image.");
}
std::memcpy(bits,image.pixels.data(),image.pixels.size()*sizeof(uint32_t));
if(const auto old=std::exchange(bitmap,next)) DeleteObject(old);
width=image.width;
height=image.height;
}
void poll()
{
if(reading.valid())
{
if(reading.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
const auto current=revision==started;
if(current) KillTimer(window,imageTimer);
bool retryApproved=false;
try
{
auto image=reading.get();
if(current)
{
show(image.raster);
observedVersion=image.revision;
if(draft)
{
draft->undo.clear();
draft->version=image.revision;
draft->original=std::move(image.raster);
draft->geometry=draft->saved={{0,0,width,height},0};
}
clampOffset();
updateButtons();
}
}
catch(const std::exception &failure)
{
if(current)
{
if(!retried && retry.approve) retryApproved=retry.approve(window,requested,failure);
if(!retryApproved) error=wide(failure.what());
}
}
if(current && !retryApproved)
{
InvalidateRect(window,nullptr,FALSE);
return;
}
if(retryApproved)
{
retried=true;
SetTimer(window,imageTimer,30,nullptr);
}
}
if(requested.empty())
{
KillTimer(window,imageTimer);
return;
}
stop=std::stop_source{};
started=revision;
std::packaged_task<Loaded()> task([path=requested,decoder=retried?retry.load:load,
token=stop.get_token(),watch=!embedded && !load && isLocalDocumentPath(requested),editing=draft.has_value()]
{
if(!watch) return Loaded{decoder?decoder(path,token):decodeImage(path,path,token),{}};
std::optional<ImageRevision> before;
try {before=imageRevision(path);}
catch(const std::exception &) {if(editing) throw;}
auto raster=decodeImage(path,path,token);
if(before && *before!=imageRevision(path))
throw std::runtime_error("The image changed while it was opening. Open it again.");
return Loaded{std::move(raster),before};
});
reading=task.get_future();
try {std::thread(std::move(task)).detach();}
catch(const std::exception &e)
{
reading={};
error=wide(e.what());
KillTimer(window,imageTimer);
InvalidateRect(window,nullptr,FALSE);
}
}
void pollExternal()
{
if(!observedVersion || requested.empty() || reading.valid()) return;
std::optional<ImageRevision> revision;
try {revision=imageRevision(requested);}
catch(const std::exception &) {return;}
if(revision==observedVersion) return;
if(draft && (GetForegroundWindow()!=window || !IsWindowEnabled(window) || !draft->dialogs.reloadChanged)) return;
observedVersion=revision;
if(!draft || draft->dialogs.reloadChanged(window)) request(requested,true);
}
double factor() const
{
if(!fit || !width || !height) return zoom;
const auto area=viewport();
return std::min({1.0,static_cast<double>(std::max(1L,area.right-area.left))/width,
static_cast<double>(std::max(1L,area.bottom-area.top))/height});
}
void clampOffset()
{
const auto area=viewport();
const auto value=factor();
const auto limitX=std::max(0.0,(width*value-(area.right-area.left))/2);
const auto limitY=std::max(0.0,(height*value-(area.bottom-area.top))/2);
x=std::clamp(x,-limitX,limitX);
y=std::clamp(y,-limitY,limitY);
}
void changeZoom(double multiplier,const POINT *anchor=nullptr)
{
if(!bitmap) return;
const auto before=factor();
fit=false;
zoom=std::clamp(before*multiplier,std::min(0.025,before),16.0);
if(anchor)
{
const auto area=viewport();
const double dx=anchor->x-(area.left+area.right)/2.0;
const double dy=anchor->y-(area.top+area.bottom)/2.0;
x=dx+(x-dx)*zoom/before;
y=dy+(y-dy)*zoom/before;
}
clampOffset();
InvalidateRect(window,nullptr,FALSE);
}
void applyEdit(ImageGeometry next,bool undo)
{
if(next==draft->geometry) return;
auto raster=transformImage(draft->original,next);
if(!undo) draft->undo.push_back(draft->geometry);
try {show(raster);}
catch(...)
{
if(!undo) draft->undo.pop_back();
throw;
}
if(undo) draft->undo.pop_back();
draft->geometry=next;
fit=true;
zoom=1;
x=y=0;
updateButtons();
InvalidateRect(window,nullptr,FALSE);
}
void editAction(UINT id)
{
if(!draft || !bitmap) return;
try
{
if(id==rotateLeft || id==rotateRight)
{
auto next=draft->geometry;
next.turns=(next.turns+(id==rotateLeft?3:1))%4;
applyEdit(next,false);
}
else if(id==crop)
{
if(const auto area=draft->dialogs.crop(window,width,height))
applyEdit(cropImage(draft->geometry,*area),false);
}
else if(id==undoEdit && !draft->undo.empty())
applyEdit(draft->undo.back(),true);
else if(id==saveCopy)
{
const auto destination=draft->dialogs.copyPath(window,requested);
if(destination.empty()) return;
saveImage(transformImage(draft->original,draft->geometry),destination);
}
else if(id==replaceOriginal && draft->dirty() && draft->version &&
draft->dialogs.confirm(window,L"Replace the original image?\r\n\r\n"+requested.native(),L"Replace original"))
{
draft->version=saveImage(transformImage(draft->original,draft->geometry),requested,&*draft->version);
observedVersion=draft->version;
draft->saved=draft->geometry;
updateButtons();
}
}
catch(const std::exception &failure)
{
updateButtons();
draft->dialogs.report(window,wide(failure.what()).c_str());
}
}
void action(UINT id)
{
if(id>=rotateLeft && id<=replaceOriginal) editAction(id);
else if(id==previous && position>0) request(images[--position]);
else if(id==following && position+1<images.size()) request(images[++position]);
else if(id==zoomOut || id==zoomIn) changeZoom(id==zoomIn?1.25:0.8);
else if(id==fitImage || id==actualSize)
{
fit=id==fitImage;
zoom=1;
x=y=0;
InvalidateRect(window,nullptr,FALSE);
}
}
void paintButton(const DRAWITEMSTRUCT &item) const
{
const bool enabled=(item.itemState&ODS_DISABLED)==0;
const auto mix=[](BYTE a,BYTE b){return (int(a)+b)/2;};
const auto foreground=enabled?style.toolbarText:RGB(
mix(GetRValue(style.toolbar),GetRValue(style.toolbarText)),
mix(GetGValue(style.toolbar),GetGValue(style.toolbarText)),
mix(GetBValue(style.toolbar),GetBValue(style.toolbarText)));
fillImageView(item.hDC,item.rcItem,(item.itemState&(ODS_FOCUS|ODS_SELECTED))?style.selection:style.toolbar);
SetDCBrushColor(item.hDC,foreground);
FrameRect(item.hDC,&item.rcItem,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
if(font) SelectObject(item.hDC,font);
SetBkMode(item.hDC,TRANSPARENT);
SetTextColor(item.hDC,foreground);
wchar_t label[24]{};
GetWindowTextW(item.hwndItem,label,static_cast<int>(std::size(label)));
auto labelArea=item.rcItem;
InflateRect(&labelArea,-scale(2),0);
DrawTextW(item.hDC,label,-1,&labelArea,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
}
void paint()
{
PAINTSTRUCT repaint{};
const auto dc=BeginPaint(window,&repaint);
RECT all{};
GetClientRect(window,&all);
const auto area=viewport();
fillImageView(dc,all,style.toolbar);
fillImageView(dc,area,style.background);
if(font) SelectObject(dc,font);
SetBkMode(dc,TRANSPARENT);
SetTextColor(dc,style.text);
if(bitmap)
{
if(const auto source=CreateCompatibleDC(dc))
{
const auto old=SelectObject(source,bitmap);
const auto saved=SaveDC(dc);
IntersectClipRect(dc,area.left,area.top,area.right,area.bottom);
const auto displayWidth=std::max(1L,std::lround(width*factor()));
const auto displayHeight=std::max(1L,std::lround(height*factor()));
const auto left=std::lround((area.left+area.right-displayWidth)/2.0+x);
const auto top=std::lround((area.top+area.bottom-displayHeight)/2.0+y);
const double horizontal=double(displayWidth)/width, vertical=double(displayHeight)/height;
const auto clippedSource=[](LONG edge,LONG start,double ratio,unsigned size,bool end)
{
const auto pixel=(edge-start)/ratio;
return static_cast<int>(std::clamp(end?std::ceil(pixel):std::floor(pixel),0.0,double(size)));
};
const int startX=clippedSource(area.left,left,horizontal,width,false);
const int endX=clippedSource(area.right,left,horizontal,width,true);
const int startY=clippedSource(area.top,top,vertical,height,false);
const int endY=clippedSource(area.bottom,top,vertical,height,true);
const auto destX=left+std::lround(startX*horizontal), destY=top+std::lround(startY*vertical);
AlphaBlend(dc,destX,destY,left+std::lround(endX*horizontal)-destX,top+std::lround(endY*vertical)-destY,
source,startX,startY,endX-startX,endY-startY,{AC_SRC_OVER,0,255,AC_SRC_ALPHA});
if(saved) RestoreDC(dc,saved);
SelectObject(source,old);
DeleteDC(source);
}
}
else if(!requested.empty())
{
auto message=area;
InflateRect(&message,-scale(8),0);
DrawTextW(dc,error.empty()?L"Loading image…":error.c_str(),-1,&message,
DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
}
SetTextColor(dc,style.toolbarText);
auto status=requested.filename().wstring();
if(bitmap) status+=L" · "+std::to_wstring(width)+L" × "+std::to_wstring(height)+L" · "+
std::to_wstring(std::lround(factor()*100))+L"%";
RECT footer{scale(8),area.bottom,all.right-scale(8),all.bottom};
DrawTextW(dc,status.c_str(),-1,&footer,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX);
EndPaint(window,&repaint);
}
};
std::map<HWND,std::shared_ptr<ImageView>> imageViews;
LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_NCCREATE)
{
const auto *created=reinterpret_cast<const CREATESTRUCTW *>(lp);
const auto state=*static_cast<std::shared_ptr<ImageView> *>(created->lpCreateParams);
state->window=window;
imageViews.emplace(window,state);
}
const auto found=imageViews.find(window);
if(found==imageViews.end()) return DefWindowProcW(window,message,wp,lp);
const auto state=found->second;
auto &view=*state;
switch(message)
{
case WM_CREATE:
{
constexpr const wchar_t *labels[]{L"Previous",L"Next",L"−",L"+",L"Fit",L"100%",
L"Rotate left",L"Rotate right",L"Crop…",L"Undo",L"Save copy…",L"Replace…"};
const unsigned first=view.embedded || view.draft?zoomOut:previous;
const unsigned last=view.draft?replaceOriginal:actualSize;
for(unsigned id=first;id<=last;++id)
{
view.buttons[id-1]=CreateWindowW(L"BUTTON",labels[id-1],WS_CHILD|WS_VISIBLE|BS_OWNERDRAW,
0,0,0,0,window,reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),GetModuleHandleW(nullptr),nullptr);
if(!view.buttons[id-1]) return -1;
}
view.layout();
view.updateButtons();
if(!view.embedded && !view.load) SetTimer(window,externalImageTimer,500,nullptr);
return 0;
}
case WM_SIZE: view.layout(); return 0;
case WM_DPICHANGED:
if(!view.embedded)
{
const auto &bounds=*reinterpret_cast<const RECT *>(lp);
SetWindowPos(window,nullptr,bounds.left,bounds.top,bounds.right-bounds.left,bounds.bottom-bounds.top,
SWP_NOACTIVATE|SWP_NOZORDER);
}
view.layout();
return 0;
case WM_DPICHANGED_AFTERPARENT: view.layout(); return 0;
case WM_ERASEBKGND: return 1;
case WM_PAINT: view.paint(); return 0;
case WM_DRAWITEM: view.paintButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp)); return TRUE;
case WM_TIMER:
if(wp==imageTimer) view.poll();
if(wp==externalImageTimer) view.pollExternal();
return 0;
case WM_COMMAND:
if(HIWORD(wp)==BN_CLICKED) {view.action(LOWORD(wp)); SetFocus(window);}
return 0;
case WM_LBUTTONDOWN:
{
const auto area=view.viewport();
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
if(view.bitmap && PtInRect(&area,point))
{
SetFocus(window);
view.dragging=true;
view.lastMouse=point;
SetCapture(window);
}
return 0;
}
case WM_MOUSEMOVE:
if(view.dragging)
{
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
view.x+=point.x-view.lastMouse.x;
view.y+=point.y-view.lastMouse.y;
view.lastMouse=point;
view.clampOffset();
InvalidateRect(window,nullptr,FALSE);
}
return 0;
case WM_LBUTTONUP:
if(view.dragging) ReleaseCapture();
return 0;
case WM_CAPTURECHANGED: view.dragging=false; return 0;
case WM_MOUSEWHEEL:
{
POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
ScreenToClient(window,&point);
view.changeZoom(std::pow(1.25,static_cast<double>(GET_WHEEL_DELTA_WPARAM(wp))/WHEEL_DELTA),&point);
return 0;
}
case WM_KEYDOWN:
if(view.draft && (GetKeyState(VK_CONTROL)&0x8000) && wp=='Z') view.action(undoEdit);
else if(view.draft && (GetKeyState(VK_CONTROL)&0x8000) && wp=='S')
view.action((GetKeyState(VK_SHIFT)&0x8000)?saveCopy:replaceOriginal);
else if(wp==VK_ADD || wp==VK_OEM_PLUS) view.action(zoomIn);
else if(wp==VK_SUBTRACT || wp==VK_OEM_MINUS) view.action(zoomOut);
else if(wp=='0') view.action(fitImage);
else if(wp=='1') view.action(actualSize);
else if(!view.embedded && (wp==VK_LEFT || wp==VK_PRIOR)) view.action(previous);
else if(!view.embedded && (wp==VK_RIGHT || wp==VK_NEXT)) view.action(following);
else if(!view.embedded && (wp==VK_ESCAPE || wp==VK_F10)) SendMessageW(window,WM_CLOSE,0,0);
else break;
return 0;
case WM_CLOSE:
if(view.confirmingClose || (view.draft && view.draft->dialogs.dismissOwned(window))) return 0;
view.confirmingClose=true;
if(!view.draft || !view.draft->dirty() ||
view.draft->dialogs.confirm(window,L"Discard unsaved image edits?",L"Image editor"))
DestroyWindow(window);
view.confirmingClose=false;
return 0;
case WM_NCDESTROY:
imageViews.erase(found);
if(view.onClose) view.onClose(window);
break;
}
return DefWindowProcW(window,message,wp,lp);
}
}
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose,ImageLoadRetry retry,
const ImageEditDialogs *editor)
{
const auto instance=GetModuleHandleW(nullptr);
static const bool registered=[instance]
{
WNDCLASSW type{};
type.hInstance=instance;
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
type.lpfnWndProc=imageProcedure;
type.lpszClassName=imageWindowClass;
return RegisterClassW(&type)!=0;
}();
if(!registered) return nullptr;
auto state=std::make_shared<ImageView>();
state->embedded=embedded;
if(editor) state->draft.emplace(ImageView::Draft{*editor});
state->style=style;
state->images=std::move(images);
state->load=std::move(load);
state->retry=std::move(retry);
state->onClose=std::move(onClose);
const auto position=std::find(state->images.begin(),state->images.end(),initial);
if(position!=state->images.end()) state->position=static_cast<size_t>(position-state->images.begin());
RECT bounds{};
if(!embedded) GetWindowRect(owner,&bounds);
const auto window=CreateWindowExW(embedded?0:WS_EX_APPWINDOW,imageWindowClass,embedded?L"Quick View":L"Viewer",
embedded?(WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS):(WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN),
bounds.left,bounds.top,bounds.right-bounds.left,bounds.bottom-bounds.top,
embedded?owner:nullptr,nullptr,instance,&state);
if(window) state->request(initial);
return window;
}
void showImageViewFile(HWND window,const std::filesystem::path &path)
{
if(const auto found=imageViews.find(window);found!=imageViews.end()) found->second->request(path);
}
std::optional<ImageWindowSession> imageWindowSession(HWND window)
{
const auto found=imageViews.find(window);
if(found==imageViews.end()) return {};
const auto &view=*found->second;
if(view.embedded || view.load || !isLocalDocumentPath(view.requested)) return {};
return ImageWindowSession{view.requested,view.draft.has_value(),view.fit,view.zoom,view.x,view.y};
}
void restoreImageWindowSession(HWND window,const ImageWindowSession &state)
{
const auto found=imageViews.find(window);
if(found==imageViews.end()) return;
auto &view=*found->second;
view.fit=state.fit;
view.zoom=std::isfinite(state.zoom)?std::clamp(state.zoom,0.05,32.0):1.0;
view.x=std::isfinite(state.x)?state.x:0;
view.y=std::isfinite(state.y)?state.y:0;
}
}
+51
View File
@@ -0,0 +1,51 @@
#pragma once
#include "files_image_edit.h"
#include <optional>
#include <windows.h>
#include <functional>
#include <exception>
namespace ks::files
{
using ImageLoad=std::function<ImageRaster(const std::filesystem::path &,std::stop_token)>;
struct ImageLoadRetry
{
ImageLoad load;
std::function<bool(HWND,const std::filesystem::path &,const std::exception &)> approve;
};
struct ImageViewStyle
{
LOGFONTW font{};
int tenthsOfPoint{};
COLORREF background{}, text{}, toolbar{}, toolbarText{}, selection{};
};
struct ImageEditDialogs
{
std::function<std::optional<ImageRegion>(HWND,unsigned,unsigned)> crop;
std::function<std::filesystem::path(HWND,const std::filesystem::path &)> copyPath;
std::function<bool(HWND,const std::wstring &,const wchar_t *)> confirm;
std::function<void(HWND,const wchar_t *)> report;
std::function<bool(HWND)> dismissOwned;
std::function<bool(HWND)> reloadChanged;
};
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={},ImageLoadRetry retry={},
const ImageEditDialogs *editor=nullptr);
void showImageViewFile(HWND window,const std::filesystem::path &path);
struct ImageWindowSession
{
std::filesystem::path path;
bool editor{}, fit=true;
double zoom=1, x{}, y{};
RECT bounds{};
bool maximized{};
};
std::optional<ImageWindowSession> imageWindowSession(HWND window);
void restoreImageWindowSession(HWND window,const ImageWindowSession &state);
}
+257
View File
@@ -0,0 +1,257 @@
enum KeyContext : unsigned { panelKeyContext=1, terminalKeyContext=2 };
enum class FilesKey
{
Refresh, View, Edit, Copy, Move, Mkdir, Delete, Exit, Compare, Previous, History,
Pack, Find, ExternalView, ExternalEdit, QuickView, FullPath, HexView, Swap, Properties, Next, Count
};
constexpr size_t keyIndex(FilesKey command) { return static_cast<size_t>(command); }
constexpr unsigned bothKeyContexts=panelKeyContext|terminalKeyContext;
constexpr WORD chord(BYTE key,BYTE modifiers=0) { return MAKEWORD(key,modifiers); }
constexpr BYTE keyCtrl=HOTKEYF_CONTROL,keyShift=HOTKEYF_SHIFT,keyAlt=HOTKEYF_ALT;
constexpr struct
{
const char *id;
const wchar_t *label;
unsigned contexts;
std::array<WORD,2> defaults;
} filesKeyCommands[]{
{"refresh",L"Refresh panel",bothKeyContexts,{chord('R',keyCtrl),chord(VK_F2)}},
{"view",L"View",panelKeyContext,{chord(VK_F3)}},
{"edit",L"Edit",panelKeyContext,{chord(VK_F4)}},
{"copy",L"Copy",panelKeyContext,{chord(VK_F5)}},
{"move",L"Move",panelKeyContext,{chord(VK_F6)}},
{"mkdir",L"Make folder",panelKeyContext,{chord(VK_F7)}},
{"delete",L"Delete to Recycle Bin",panelKeyContext,{chord(VK_F8)}},
{"exit",L"Exit",bothKeyContexts,{chord(VK_F10)}},
{"compare",L"Compare files",panelKeyContext,{chord(VK_F11,keyShift)}},
{"previous",L"Previous command",bothKeyContexts,{chord('E',keyCtrl)}},
{"history",L"Command history",bothKeyContexts,{chord(VK_F8,keyAlt)}},
{"pack",L"Pack files",panelKeyContext,{chord(VK_F5,keyAlt)}},
{"find",L"Find files",panelKeyContext,{chord(VK_F7,keyAlt)}},
{"externalView",L"View externally",panelKeyContext,{chord(VK_F3,keyAlt)}},
{"externalEdit",L"Edit externally",panelKeyContext,{chord(VK_F4,keyAlt)}},
{"quickView",L"Quick View",panelKeyContext,{chord('Q',keyCtrl)}},
{"fullPath",L"Copy full path",panelKeyContext,{chord('C',keyCtrl|keyShift)}},
{"hexView",L"View as hex",panelKeyContext,{chord(VK_F3,keyShift)}},
{"swap",L"Swap panels",panelKeyContext,{chord('U',keyCtrl)}},
{"properties",L"Properties",panelKeyContext,{chord('A',keyCtrl)}},
{"next",L"Next command",terminalKeyContext,{chord(VK_DOWN)}},
};
static_assert(std::size(filesKeyCommands)==keyIndex(FilesKey::Count));
constexpr size_t filesKeySchemeLimit=24,filesKeysPerCommand=8;
constexpr wchar_t filesKeySchemePreference[]=L"KeySchemesV1";
struct FilesKeyScheme
{
std::wstring name;
std::array<std::vector<WORD>,keyIndex(FilesKey::Count)> keys;
bool operator==(const FilesKeyScheme &) const=default;
};
struct FilesKeySettings
{
std::vector<FilesKeyScheme> schemes;
size_t active{};
bool operator==(const FilesKeySettings &) const=default;
};
std::wstring filesKeyLabel(WORD binding)
{
if(!binding) return {};
std::wstring label;
if(HIBYTE(binding)&keyCtrl) label+=L"Ctrl+";
if(HIBYTE(binding)&keyAlt) label+=L"Alt+";
if(HIBYTE(binding)&keyShift) label+=L"Shift+";
const auto key=LOBYTE(binding);
if(key>=VK_F1 && key<=VK_F24) label+=L"F"+std::to_wstring(key-VK_F1+1);
else if(key==VK_DOWN) label+=L"Down";
else label+=static_cast<wchar_t>(key);
return label;
}
FilesKeyScheme defaultFilesKeyScheme(std::wstring name=L"Default")
{
FilesKeyScheme scheme{std::move(name),{}};
for(size_t command=0;command<scheme.keys.size();++command)
for(const auto binding:filesKeyCommands[command].defaults)
if(binding) scheme.keys[command].push_back(binding);
return scheme;
}
FilesKeySettings filesKeySettings{{defaultFilesKeyScheme()},0};
bool sameFilesKeySchemeName(std::wstring_view first,std::wstring_view second)
{
return CompareStringOrdinal(first.data(),static_cast<int>(first.size()),
second.data(),static_cast<int>(second.size()),TRUE)==CSTR_EQUAL;
}
bool validFilesKeySchemeName(std::wstring_view name)
{
return !name.empty() && name.size()<=48 && !iswspace(name.front()) && !iswspace(name.back()) &&
std::ranges::none_of(name,[](wchar_t character){return iswcntrl(character);});
}
unsigned reservedFilesKeyContexts(WORD binding)
{
const auto key=LOBYTE(binding),mods=HIBYTE(binding);
if(key>=VK_F1 && key<=VK_F24)
{
if(mods==keyAlt && key==VK_F4) return terminalKeyContext;
if(!mods && key==VK_F1) return bothKeyContexts;
if((!mods && key==VK_F9) || (mods==keyAlt && (key==VK_F1 || key==VK_F2 || key==VK_F10)) ||
(mods==keyShift && key==VK_F4) || (mods==keyShift && key==VK_F10) ||
(mods==keyCtrl && key<=VK_F12))
return panelKeyContext;
return 0;
}
if(key==VK_DOWN && !mods) return panelKeyContext;
if(key>='A' && key<='Z' && (mods&keyCtrl) && !(mods&keyAlt))
{
constexpr std::wstring_view editing=L"CFOPVXYZ";
if(mods==keyCtrl && editing.find(key)!=editing.npos) return bothKeyContexts;
if((mods==keyCtrl && key=='A') || (mods==(keyCtrl|keyShift) && (key=='C' || key=='V')))
return terminalKeyContext;
return 0;
}
return bothKeyContexts;
}
std::wstring filesKeyConflict(const FilesKeyScheme &scheme,size_t command,WORD binding)
{
if(!binding || (HIBYTE(binding)&~(keyCtrl|keyShift|keyAlt)))
return L"Use a function key or a letter with Ctrl.";
const auto contexts=filesKeyCommands[command].contexts;
if(reservedFilesKeyContexts(binding)&contexts)
return filesKeyLabel(binding)+L" is reserved or unavailable in this context.";
for(size_t i=0;i<scheme.keys.size();++i)
if((filesKeyCommands[i].contexts&contexts) && std::ranges::find(scheme.keys[i],binding)!=scheme.keys[i].end())
return filesKeyLabel(binding)+L" is already assigned to "+filesKeyCommands[i].label+L".";
return {};
}
std::optional<FilesKeySettings> parseFilesKeySettings(const Json &stored)
{
try
{
if(stored.at("version")!=1 || !stored.at("schemes").is_array()) return {};
const auto &rows=stored.at("schemes");
if(rows.empty() || rows.size()>filesKeySchemeLimit) return {};
FilesKeySettings settings;
const auto active=stored.at("active").get<std::string>();
for(const auto &row:rows)
{
auto name=ks::wide(row.at("name").get<std::string>());
if(!validFilesKeySchemeName(name) ||
std::ranges::any_of(settings.schemes,[&](const auto &other)
{ return sameFilesKeySchemeName(other.name,name); })) return {};
FilesKeyScheme scheme{std::move(name),{}};
const auto &commands=row.at("commands");
if(!commands.is_object()) return {};
for(size_t i=0;i<scheme.keys.size();++i)
{
const auto found=commands.find(filesKeyCommands[i].id);
if(found==commands.end()) continue;
if(!found->is_array() || found->size()>filesKeysPerCommand) return {};
for(const auto &entry:*found)
{
if(!entry.is_number_unsigned() || entry>0xffff) return {};
const auto binding=entry.get<WORD>();
if(binding==chord(VK_F1)) continue;
if(!filesKeyConflict(scheme,i,binding).empty()) return {};
scheme.keys[i].push_back(binding);
}
}
for(size_t i=0;i<scheme.keys.size();++i)
if(!commands.contains(filesKeyCommands[i].id))
for(const auto binding:filesKeyCommands[i].defaults)
if(binding && filesKeyConflict(scheme,i,binding).empty()) scheme.keys[i].push_back(binding);
if(active==ks::utf8(scheme.name)) settings.active=settings.schemes.size();
settings.schemes.push_back(std::move(scheme));
}
return settings;
}
catch(const std::exception &) { return {}; }
}
Json serializeFilesKeySettings(const FilesKeySettings &settings)
{
Json schemes=Json::array();
for(const auto &scheme:settings.schemes)
{
Json commands=Json::object();
for(size_t i=0;i<scheme.keys.size();++i) commands[filesKeyCommands[i].id]=scheme.keys[i];
schemes.push_back({{"name",ks::utf8(scheme.name)},{"commands",std::move(commands)}});
}
return {{"version",1},{"active",ks::utf8(settings.schemes[settings.active].name)},{"schemes",std::move(schemes)}};
}
void loadFilesKeySettings()
{
if(const auto json=readFilesJsonPreference(filesKeySchemePreference))
if(auto settings=parseFilesKeySettings(*json))
{
filesKeySettings=std::move(*settings);
return;
}
auto migrated=defaultFilesKeyScheme(L"Previous settings");
constexpr struct { FilesKey command; const wchar_t *name; } legacy[]{
{FilesKey::Previous,L"PreviousCommandKey"},{FilesKey::History,L"CommandHistoryKey"},
{FilesKey::Compare,L"ComparisonShortcut"},
};
for(const auto &item:legacy)
{
const auto index=keyIndex(item.command);
auto &keys=migrated.keys[index];
const auto fallback=filesKeyCommands[index].defaults.front();
const auto binding=static_cast<WORD>(preference(item.name,fallback));
const auto context=filesKeyCommands[index].contexts;
if(binding==fallback || (HIBYTE(binding)&~(keyCtrl|keyShift|keyAlt)) ||
(reservedFilesKeyContexts(binding)&context)) continue;
for(size_t i=0;i<migrated.keys.size();++i)
if(filesKeyCommands[i].contexts&context) std::erase(migrated.keys[i],binding);
keys={binding};
}
filesKeySettings={{defaultFilesKeyScheme()},0};
if(migrated.keys!=filesKeySettings.schemes.front().keys)
{
filesKeySettings.schemes.push_back(std::move(migrated));
filesKeySettings.active=1;
}
}
WORD currentFilesChord(WPARAM key)
{
if(key>0xff || ((GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) return 0;
return chord(static_cast<BYTE>(key),((GetKeyState(VK_CONTROL)&0x8000)?keyCtrl:0) |
((GetKeyState(VK_SHIFT)&0x8000)?keyShift:0) | ((GetKeyState(VK_MENU)&0x8000)?keyAlt:0));
}
std::optional<FilesKey> boundFilesCommand(WORD binding,unsigned context)
{
const auto &keys=filesKeySettings.schemes[filesKeySettings.active].keys;
for(size_t i=0;i<keys.size();++i)
if((filesKeyCommands[i].contexts&context) && std::ranges::find(keys[i],binding)!=keys[i].end())
return static_cast<FilesKey>(i);
return {};
}
std::wstring filesKeyHint(FilesKey command,bool all=false)
{
std::wstring text;
for(const auto binding:filesKeySettings.schemes[filesKeySettings.active].keys[keyIndex(command)])
{
if(!text.empty()) text+=L", ";
text+=filesKeyLabel(binding);
if(!all) break;
}
return text;
}
std::wstring filesKeyMenuLabel(FilesKey command,std::wstring label={})
{
if(label.empty()) label=filesKeyCommands[keyIndex(command)].label;
const auto keys=filesKeyHint(command,true);
if(!keys.empty()) label+=L"\t"+keys;
return label;
}
+228
View File
@@ -0,0 +1,228 @@
constexpr int keySchemeChoice=610,keySchemeCopy=611,keySchemeReset=612,keySchemeCommand=613,
keySchemeContext=614,keySchemeBindings=615,keySchemeCapture=616,keySchemeAdd=617,keySchemeRemove=618,
keySchemePrimary=619,keySchemeName=620;
struct FilesKeySchemeDraft
{
FilesKeySettings base=filesKeySettings,settings=base;
FilesKey initial;
FilesKeySettings *pending{};
};
INT_PTR CALLBACK copyKeySchemeDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
auto &name=*reinterpret_cast<std::wstring*>(lp);
SendDlgItemMessageW(dialog,keySchemeName,EM_SETLIMITTEXT,48,0);
SetDlgItemTextW(dialog,keySchemeName,name.c_str());
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 &name=*reinterpret_cast<std::wstring*>(GetWindowLongPtrW(dialog,DWLP_USER));
wchar_t entry[49]{};
GetDlgItemTextW(dialog,keySchemeName,entry,std::size(entry));
name=entry;
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
void refreshFilesKeyBindings(HWND dialog,const FilesKeyScheme &scheme,size_t command,size_t selection=0)
{
const auto &descriptor=filesKeyCommands[command];
SetDlgItemTextW(dialog,keySchemeContext,
descriptor.contexts==bothKeyContexts?L"Keys · panels and command output":
descriptor.contexts==terminalKeyContext?L"Keys · command output":L"Keys · file panels");
const auto list=GetDlgItem(dialog,keySchemeBindings);
SendMessageW(list,LB_RESETCONTENT,0,0);
const auto &keys=scheme.keys[command];
for(size_t i=0;i<keys.size();++i)
{
auto label=filesKeyLabel(keys[i]);
if(!i) label+=L" (primary)";
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
}
if(!keys.empty()) SendMessageW(list,LB_SETCURSEL,std::min(selection,keys.size()-1),0);
EnableWindow(GetDlgItem(dialog,keySchemeRemove),!keys.empty());
EnableWindow(GetDlgItem(dialog,keySchemePrimary),keys.size()>1 && selection>0 && selection<keys.size());
EnableWindow(GetDlgItem(dialog,keySchemeAdd),keys.size()<filesKeysPerCommand);
}
void refreshFilesKeySchemes(HWND dialog,const FilesKeySettings &settings)
{
const auto choice=GetDlgItem(dialog,keySchemeChoice);
SendMessageW(choice,CB_RESETCONTENT,0,0);
for(const auto &scheme:settings.schemes)
SendMessageW(choice,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(scheme.name.c_str()));
SendMessageW(choice,CB_SETCURSEL,settings.active,0);
EnableWindow(GetDlgItem(dialog,keySchemeCopy),settings.schemes.size()<filesKeySchemeLimit);
}
std::wstring filesKeyBarLabel(FilesKey command,const wchar_t *action)
{
return filesKeyHint(command)+L" "+action;
}
void refreshFilesKeyBar()
{
for(size_t i=0;i<std::size(keyBar);++i)
{
SetWindowTextW(commands[i],filesKeyBarLabel(keyBar[i].command,keyBar[i].label).c_str());
InvalidateRect(commands[i],nullptr,FALSE);
}
}
INT_PTR CALLBACK filesKeySchemesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &draft=*reinterpret_cast<FilesKeySchemeDraft*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
refreshFilesKeySchemes(dialog,draft.settings);
for(const auto &item:filesKeyCommands)
SendDlgItemMessageW(dialog,keySchemeCommand,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(item.label));
const auto index=keyIndex(draft.initial);
SendDlgItemMessageW(dialog,keySchemeCommand,LB_SETCURSEL,index,0);
refreshFilesKeyBindings(dialog,draft.settings.schemes[draft.settings.active],index);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
auto &draft=*reinterpret_cast<FilesKeySchemeDraft*>(GetWindowLongPtrW(dialog,DWLP_USER));
auto &settings=draft.settings;
auto &scheme=settings.schemes[settings.active];
const auto row=SendDlgItemMessageW(dialog,keySchemeCommand,LB_GETCURSEL,0,0);
if(row==LB_ERR) return FALSE;
const auto command=static_cast<size_t>(row);
const auto position=static_cast<size_t>(SendDlgItemMessageW(dialog,keySchemeBindings,LB_GETCURSEL,0,0));
auto &keys=scheme.keys[command];
switch(LOWORD(wp))
{
case keySchemeChoice:
if(HIWORD(wp)==CBN_SELCHANGE)
{
const auto chosen=SendDlgItemMessageW(dialog,keySchemeChoice,CB_GETCURSEL,0,0);
if(chosen!=CB_ERR) settings.active=static_cast<size_t>(chosen);
refreshFilesKeyBindings(dialog,settings.schemes[settings.active],command);
}
return TRUE;
case keySchemeCommand:
if(HIWORD(wp)==LBN_SELCHANGE) refreshFilesKeyBindings(dialog,scheme,command);
return TRUE;
case keySchemeBindings:
if(HIWORD(wp)==LBN_SELCHANGE)
EnableWindow(GetDlgItem(dialog,keySchemePrimary),position>0 && position<keys.size());
return TRUE;
case keySchemeCopy:
{
if(settings.schemes.size()>=filesKeySchemeLimit) return TRUE;
std::wstring name=scheme.name.substr(0,43)+L" copy";
FilesModalDialog copyName(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(616),dialog,
copyKeySchemeDialog,reinterpret_cast<LPARAM>(&name),false);
if(copyName.runModal()!=IDOK) return TRUE;
if(!validFilesKeySchemeName(name) || std::ranges::any_of(settings.schemes,[&](const auto &other)
{ return sameFilesKeySchemeName(other.name,name); }))
{
showFilesNotice(dialog,L"Enter a unique name with no leading or trailing spaces.",L"Keyboard shortcuts");
return TRUE;
}
auto copy=scheme;
copy.name=std::move(name);
settings.schemes.push_back(std::move(copy));
settings.active=settings.schemes.size()-1;
refreshFilesKeySchemes(dialog,settings);
refreshFilesKeyBindings(dialog,settings.schemes.back(),command);
return TRUE;
}
case keySchemeReset:
{
FilesNoticeOptions notice;
notice.confirm=true;
notice.accept=L"&Reset";
const auto prompt=L"Reset all keys in “"+scheme.name+L"” to defaults?";
if(showFilesNotice(dialog,prompt.c_str(),L"Keyboard shortcuts",notice)!=IDYES) return TRUE;
scheme=defaultFilesKeyScheme(scheme.name);
refreshFilesKeyBindings(dialog,scheme,command);
return TRUE;
}
case keySchemeAdd:
{
if(keys.size()>=filesKeysPerCommand) return TRUE;
const auto binding=static_cast<WORD>(SendDlgItemMessageW(dialog,keySchemeCapture,HKM_GETHOTKEY,0,0));
if(const auto conflict=filesKeyConflict(scheme,command,binding);!conflict.empty())
{
showFilesNotice(dialog,conflict.c_str(),L"Keyboard shortcuts");
SetFocus(GetDlgItem(dialog,keySchemeCapture));
return TRUE;
}
keys.push_back(binding);
SendDlgItemMessageW(dialog,keySchemeCapture,HKM_SETHOTKEY,0,0);
refreshFilesKeyBindings(dialog,scheme,command,keys.size()-1);
return TRUE;
}
case keySchemeRemove:
if(position<keys.size())
{
keys.erase(keys.begin()+position);
refreshFilesKeyBindings(dialog,scheme,command,position<keys.size()?position:0);
}
return TRUE;
case keySchemePrimary:
if(position>0 && position<keys.size())
{
std::rotate(keys.begin(),keys.begin()+position,keys.begin()+position+1);
refreshFilesKeyBindings(dialog,scheme,command);
}
return TRUE;
case IDOK:
if(draft.pending) *draft.pending=settings;
else if(settings!=draft.base)
{
const OptionsWriteLock writeLock;
if(!writeLock.acquired())
{
showFilesNotice(dialog,L"Another window is saving Files settings. Try again.",L"Keyboard shortcuts");
return TRUE;
}
loadFilesKeySettings();
if(filesKeySettings!=draft.base && filesKeySettings!=settings)
{
showFilesNotice(dialog,L"Keyboard schemes were changed in another window. Reopen this dialog.",
L"Keyboard shortcuts");
return TRUE;
}
if(!writeFilesJsonPreference(filesKeySchemePreference,serializeFilesKeySettings(settings)))
{
showFilesNotice(dialog,L"Could not save the keyboard schemes.",L"Keyboard shortcuts");
return TRUE;
}
filesKeySettings=settings;
refreshFilesKeyBar();
showFileDetails(panels[active]);
notifyFilesPreferences(GetAncestor(dialog,GA_ROOTOWNER));
}
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
return FALSE;
}
void editFilesKeySchemes(HWND owner,FilesKey initial,FilesKeySettings *pending)
{
if(!pending) loadFilesKeySettings();
const auto &base=pending?*pending:filesKeySettings;
FilesKeySchemeDraft draft{base,base,initial,pending};
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(615),owner,
filesKeySchemesDialog,reinterpret_cast<LPARAM>(&draft),false);
dialog.runModal();
}
+338 -97
View File
@@ -12,15 +12,9 @@ DWORD probeDeleteAccess(const fs::path &path)
return probe.value==INVALID_HANDLE_VALUE?GetLastError():ERROR_SUCCESS;
}
struct LockProcess
{
DWORD pid;
FILETIME started{};
std::wstring name;
};
struct LockScan
{
std::vector<LockProcess> processes;
std::set<DWORD> pids;
bool incomplete{};
};
@@ -30,7 +24,6 @@ LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token st
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);
@@ -63,7 +56,7 @@ LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token st
}
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));
result.pids.insert(static_cast<DWORD>(pid));
};
auto remaining=8192u;
const auto deadline=GetTickCount64()+4000;
@@ -90,162 +83,410 @@ LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token st
}
if(error) result.incomplete=true;
}
for(const auto pid:pids)
return result;
}
struct ProcessIdentity
{
DWORD pid{};
uint64_t started{};
bool operator==(const ProcessIdentity &) const = default;
};
struct ProcessEntry
{
ProcessIdentity identity;
std::wstring name;
fs::path image;
std::optional<uint64_t> workingSet;
std::optional<double> cpu;
};
struct ProcessScan
{
std::vector<ProcessEntry> entries;
bool incomplete{};
};
constexpr uint64_t processTimeTicks(const FILETIME &time)
{
return (uint64_t(time.dwHighDateTime)<<32)|time.dwLowDateTime;
}
struct ProcessTimes
{
uint64_t started, busy;
std::chrono::steady_clock::time_point measured;
};
std::optional<ProcessTimes> readProcessTimes(HANDLE process)
{
FILETIME started{},exited{},kernel{},user{};
if(!GetProcessTimes(process,&started,&exited,&kernel,&user)) return {};
return ProcessTimes{processTimeTicks(started),processTimeTicks(kernel)+processTimeTicks(user),
std::chrono::steady_clock::now()};
}
ProcessScan scanProcesses(const std::vector<fs::path> &files,std::stop_token stop)
{
ProcessScan result;
LockScan locks;
if(!files.empty())
{
Handle process{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,pid)};
LockProcess entry{pid};
if(process.value)
locks=scanLockProcesses(files,stop);
result.incomplete=locks.incomplete;
if(locks.pids.empty() || stop.stop_requested()) return result;
}
const Handle snapshot{CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0)};
if(snapshot.value==INVALID_HANDLE_VALUE)
throw std::system_error(GetLastError(),std::system_category());
PROCESSENTRY32W process{sizeof(PROCESSENTRY32W)};
if(!Process32FirstW(snapshot.value,&process))
throw std::system_error(GetLastError(),std::system_category());
do
{
const auto pid=process.th32ProcessID;
if(files.empty() || locks.pids.contains(pid))
result.entries.push_back({{pid},process.szExeFile});
} while(!stop.stop_requested() && Process32NextW(snapshot.value,&process));
if(!stop.stop_requested() && GetLastError()!=ERROR_NO_MORE_FILES) result.incomplete=true;
std::map<DWORD,ProcessTimes> initial;
for(const auto &entry:result.entries)
{
if(stop.stop_requested()) return {};
const Handle handle{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,entry.identity.pid)};
if(handle.value)
if(const auto time=readProcessTimes(handle.value)) initial.emplace(entry.identity.pid,*time);
}
if(!initial.empty()) std::this_thread::sleep_for(std::chrono::milliseconds(350));
const auto logicalCpus=std::max(1ul,static_cast<unsigned long>(GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)));
std::array<wchar_t,32768> image;
for(auto &entry:result.entries)
{
if(stop.stop_requested()) return {};
const Handle handle{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,entry.identity.pid)};
if(!handle.value) continue;
const auto current=readProcessTimes(handle.value);
const auto before=initial.find(entry.identity.pid);
if(current && before!=initial.end() && current->started!=before->second.started) continue;
if(current)
{
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();
entry.identity.started=current->started;
if(before!=initial.end() && current->busy>=before->second.busy)
{
const auto elapsed=std::chrono::duration<double>(current->measured-before->second.measured).count();
if(elapsed>0)
entry.cpu=std::clamp((current->busy-before->second.busy)*0.00001/(elapsed*logicalCpus),0.0,100.0);
}
}
if(entry.name.empty()) entry.name=L"Unknown process";
result.processes.push_back(std::move(entry));
DWORD count=image.size();
if(QueryFullProcessImageNameW(handle.value,0,image.data(),&count))
entry.image=std::wstring_view(image.data(),count);
PROCESS_MEMORY_COUNTERS memory{sizeof(memory)};
if(K32GetProcessMemoryInfo(handle.value,&memory,sizeof(memory))) entry.workingSet=memory.WorkingSetSize;
}
return result;
}
struct LockDialog
constexpr int processScope=430,processList=431,processDivider=432,processEnd=433,processRefresh=434,
processFilter=435,processSort=436,processReveal=437,processImage=438,processColumns=439,processStatus=443;
constexpr UINT_PTR processScanTimer=1;
enum class ProcessOrder { pid, cpu, memory, name, image };
struct ProcessDialog
{
std::vector<fs::path> paths;
std::vector<LockProcess> processes;
std::future<LockScan> scan;
std::vector<fs::path> files;
std::vector<ProcessEntry> entries;
std::future<ProcessScan> scan;
std::stop_source stop;
std::wstring failure;
fs::path reveal;
bool incomplete{};
};
constexpr UINT_PTR lockScanTimer=1;
const ProcessEntry *selectedProcess(HWND dialog,const ProcessDialog &state)
{
const auto row=SendDlgItemMessageW(dialog,processList,LB_GETCURSEL,0,0);
if(row==LB_ERR) return nullptr;
const auto index=SendDlgItemMessageW(dialog,processList,LB_GETITEMDATA,row,0);
return index>=0 && size_t(index)<state.entries.size()?&state.entries[index]:nullptr;
}
void refreshLockProcesses(HWND window,LockDialog &state,std::shared_ptr<Handle> terminated={})
bool mayEndProcess(ProcessIdentity identity)
{
return identity.pid && identity.pid!=GetCurrentProcessId() && identity.started;
}
void updateSelectedProcess(HWND dialog,const ProcessDialog &state)
{
const auto *entry=selectedProcess(dialog,state);
const bool hasImage=entry && !entry->image.empty();
SetDlgItemTextW(dialog,processImage,hasImage?entry->image.c_str():entry?L"Unavailable":L"");
EnableWindow(GetDlgItem(dialog,processReveal),!state.scan.valid() && hasImage);
EnableWindow(GetDlgItem(dialog,processEnd),!state.scan.valid() && entry && mayEndProcess(entry->identity));
}
std::wstring processColumnsText(std::wstring_view pid,std::wstring_view cpu,std::wstring_view memory,
std::wstring_view name)
{
std::wostringstream fields;
fields<<std::right<<std::setw(10)<<pid<<L" "<<std::setw(7)<<cpu<<L" "<<std::setw(12)<<memory<<L" "<<name;
return fields.str();
}
int compareProcessNames(const std::wstring &left,const std::wstring &right)
{
return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE);
}
void renderProcessList(HWND dialog,const ProcessDialog &state,std::optional<ProcessIdentity> preferred={})
{
const auto field=GetDlgItem(dialog,processFilter);
std::wstring query(GetWindowTextLengthW(field)+1,L'\0');
query.resize(GetWindowTextW(field,query.data(),static_cast<int>(query.size())));
const auto contains=[&](std::wstring_view value)
{
return query.empty() || (!value.empty() && FindNLSStringEx(LOCALE_NAME_INVARIANT,FIND_FROMSTART|NORM_IGNORECASE,
value.data(),static_cast<int>(value.size()),query.c_str(),static_cast<int>(query.size()),nullptr,
nullptr,nullptr,0)>=0);
};
std::vector<size_t> rows;
for(size_t i=0;i<state.entries.size();++i)
{
const auto &entry=state.entries[i];
if(contains(entry.name) || contains(entry.image.native()) || contains(std::to_wstring(entry.identity.pid)))
rows.push_back(i);
}
const auto order=static_cast<ProcessOrder>(SendDlgItemMessageW(dialog,processSort,CB_GETCURSEL,0,0));
std::sort(rows.begin(),rows.end(),[&](size_t a,size_t b)
{
const auto &left=state.entries[a],&right=state.entries[b];
if(order==ProcessOrder::cpu && left.cpu!=right.cpu) return left.cpu>right.cpu;
if(order==ProcessOrder::memory && left.workingSet!=right.workingSet) return left.workingSet>right.workingSet;
if(order==ProcessOrder::name || order==ProcessOrder::image)
{
const auto names=order==ProcessOrder::name?compareProcessNames(left.name,right.name):
compareProcessNames(left.image.native(),right.image.native());
if(names!=CSTR_EQUAL) return names==CSTR_LESS_THAN;
}
return left.identity.pid<right.identity.pid;
});
const auto list=GetDlgItem(dialog,processList);
SendMessageW(list,WM_SETREDRAW,FALSE,0);
SendMessageW(list,LB_RESETCONTENT,0,0);
LRESULT selected=0;
for(const auto index:rows)
{
const auto &entry=state.entries[index];
wchar_t cpu[16]=L"—";
if(entry.cpu) swprintf_s(cpu,L"%.1f%%",*entry.cpu);
const auto text=processColumnsText(std::to_wstring(entry.identity.pid),cpu,
entry.workingSet?formatSize(*entry.workingSet):L"—",entry.name);
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(text.c_str()));
if(row<0) continue;
SendMessageW(list,LB_SETITEMDATA,row,index);
if(preferred==entry.identity) selected=row;
}
if(!rows.empty()) SendMessageW(list,LB_SETCURSEL,selected,0);
SendMessageW(list,WM_SETREDRAW,TRUE,0);
InvalidateRect(list,nullptr,TRUE);
updateSelectedProcess(dialog,state);
std::wstring status;
if(state.scan.valid()) status=state.files.empty()?L"Sampling processes…":L"Checking files for locking processes…";
else if(!state.failure.empty()) status=state.failure;
else if(state.entries.empty()) status=state.files.empty()?L"No processes found.":L"No locking processes found.";
else if(rows.empty()) status=L"No processes match the filter.";
else status=std::to_wstring(rows.size())+(query.empty()?L"":L" of "+std::to_wstring(state.entries.size()))+L" shown";
if(state.incomplete && !state.scan.valid() && state.failure.empty()) status+=L" Some items could not be checked.";
SetDlgItemTextW(dialog,processStatus,status.c_str());
}
void refreshProcesses(HWND dialog,ProcessDialog &state,std::shared_ptr<Handle> ended={})
{
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…");
const auto *entry=selectedProcess(dialog,state);
const auto selected=entry?std::optional(entry->identity):std::nullopt;
state.failure.clear();
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);
std::packaged_task<ProcessScan()> task([files=state.files,stop=state.stop.get_token(),ended=std::move(ended)] {
if(ended) WaitForSingleObject(ended->value,2500);
return scanProcesses(files,stop);
});
auto future=task.get_future();
if(!SetTimer(window,lockScanTimer,50,nullptr))
if(!SetTimer(dialog,processScanTimer,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.");
KillTimer(dialog,processScanTimer);
state.failure=L"Could not start the process scan.";
}
EnableWindow(GetDlgItem(dialog,processRefresh),!state.scan.valid());
renderProcessList(dialog,state,selected);
}
void endLockProcess(HWND window,LockDialog &state)
void endFileProcess(HWND dialog,ProcessDialog &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});
const auto *entry=selectedProcess(dialog,state);
if(state.scan.valid() || !entry || !mayEndProcess(entry->identity)) return;
const auto error=[&](const wchar_t *message)
{
showFilesNotice(dialog,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{};
const auto process=std::make_shared<Handle>();
process->value=OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,entry->identity.pid);
const auto current=process->value?readProcessTimes(process->value):std::nullopt;
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)
if(!current || current->started!=entry->identity.started ||
!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)+
const auto question=L"End "+entry->name+L" (PID "+std::to_wstring(entry->identity.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)
if(showFilesNotice(dialog,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 alive=WaitForSingleObject(process->value,0);
if(alive!=WAIT_OBJECT_0 && (alive!=WAIT_TIMEOUT || !TerminateProcess(process->value,1)))
{
const auto message=ks::lastError(L"Could not end the process");
error(message.c_str());
const auto reason=ks::lastError(L"Could not end the process");
error(reason.c_str());
return;
}
refreshLockProcesses(window,state,std::move(process));
refreshProcesses(dialog,state,process);
}
INT_PTR CALLBACK lockProcessesDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
INT_PTR CALLBACK processesDialog(HWND dialog,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);
auto &state=*reinterpret_cast<ProcessDialog *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,processScope);
if(state.files.empty()) SetDlgItemTextW(dialog,processScope,L"This PC");
else
{
auto scope=L"Locks for "+state.files.front().native();
if(state.files.size()>1) scope+=L" (+"+std::to_wstring(state.files.size()-1)+L" more)";
SetDlgItemTextW(dialog,processScope,scope.c_str());
}
const auto filterField=GetDlgItem(dialog,processFilter);
SendMessageW(filterField,EM_SETLIMITTEXT,1024,0);
const auto sortField=GetDlgItem(dialog,processSort);
for(const auto name:{L"PID",L"CPU",L"Memory",L"Name",L"Executable"})
SendMessageW(sortField,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
SendMessageW(sortField,CB_SETCURSEL,1,0);
installFarCombo(sortField,filterField);
SetDlgItemTextW(dialog,processColumns,processColumnsText(L"PID",L"CPU",L"Working set",L"Process").c_str());
const auto list=GetDlgItem(dialog,processList);
const auto bounds=dialogControlBounds(dialog,processList);
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));
installScrollBar(list,dialog);
layoutDialogButtons(dialog,processDivider,{processReveal,processEnd,processRefresh,IDOK});
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(filterField);
refreshProcesses(dialog,state);
return FALSE;
}
auto *data=reinterpret_cast<LockDialog *>(GetWindowLongPtrW(window,DWLP_USER));
auto *data=reinterpret_cast<ProcessDialog *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!data) return FALSE;
auto &state=*data;
if(message==WM_TIMER && wp==lockScanTimer)
if(message==WM_TIMER && wp==processScanTimer)
{
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);
KillTimer(dialog,processScanTimer);
EnableWindow(GetDlgItem(dialog,processRefresh),TRUE);
const auto *entry=selectedProcess(dialog,state);
const auto selected=entry?std::optional(entry->identity):std::nullopt;
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);
}
state.entries=std::move(result.entries);
state.incomplete=result.incomplete;
}
catch(const std::exception &) {SetDlgItemTextW(window,430,L"Could not check for locking processes.");}
catch(const std::system_error &e) {state.failure=fileError(e);}
catch(const std::exception &) {state.failure=L"Could not read the process list.";}
renderProcessList(dialog,state,selected);
return TRUE;
}
if(message==WM_DRAWITEM && wp==processSort)
{
drawFarComboRow(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
}
if(message==WM_CTLCOLORLISTBOX && reinterpret_cast<HWND>(lp)!=GetDlgItem(dialog,processList))
{
const auto dc=reinterpret_cast<HDC>(wp);
SetTextColor(dc,colors[Text]);
SetBkColor(dc,colors[Dialog]);
return reinterpret_cast<INT_PTR>(teal);
}
if(message==WM_COMMAND)
{
switch(LOWORD(wp))
const auto id=LOWORD(wp),notification=HIWORD(wp);
if((id==processFilter && notification==EN_CHANGE) || (id==processSort && notification==CBN_SELCHANGE))
{
case 433: endLockProcess(window,state); return TRUE;
case 434: refreshLockProcesses(window,state); return TRUE;
const auto *entry=selectedProcess(dialog,state);
renderProcessList(dialog,state,entry?std::optional(entry->identity):std::nullopt);
return TRUE;
}
if(id==processList && notification==LBN_SELCHANGE)
{
updateSelectedProcess(dialog,state);
return TRUE;
}
if(id==processReveal || (id==processList && notification==LBN_DBLCLK))
{
const auto *entry=selectedProcess(dialog,state);
if(!state.scan.valid() && entry && !entry->image.empty())
{
state.reveal=entry->image;
FilesModalDialog::finish(dialog,processReveal);
}
return TRUE;
}
switch(id)
{
case processEnd: endFileProcess(dialog,state); return TRUE;
case processRefresh: refreshProcesses(dialog,state); return TRUE;
case IDOK:
case IDCANCEL: FilesModalDialog::finish(window,IDCANCEL); return TRUE;
case IDCANCEL: FilesModalDialog::finish(dialog,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));
if(message==WM_CLOSE) {FilesModalDialog::finish(dialog,IDCANCEL);return TRUE;}
const auto title=state.files.empty()?L" Processes ":L" Locking processes ";
return paintCopyDialog(dialog,message,wp,lp,title,false,{processDivider},false,GetDlgItem(dialog,processList));
}
void showLockProcesses(HWND owner,std::vector<fs::path> paths)
void showProcesses(HWND owner,std::vector<fs::path> paths)
{
LockDialog state{std::move(paths)};
FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(609),owner,lockProcessesDialog,
const auto source=active;
ProcessDialog state{std::move(paths)};
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(609),owner,processesDialog,
reinterpret_cast<LPARAM>(&state));
state.stop.request_stop();
if(result!=processReveal) return;
const auto destination=state.files.empty()?source:1-source;
if(quickViewWindow && destination!=quickViewSource) toggleQuickView(owner);
revealLocalFile(panels[destination],state.reveal);
}
bool panelLockSearchAvailable(const Panel &panel)
{
return !terminalVisible && panelItemPropertiesAvailable(panel) && !panel.ftp && !panel.peer &&
!panel.archive && !windowsNetworkPath(panel.directory);
}
void showPanelLockProcesses(HWND owner,Panel &panel)
{
if(panelLockSearchAvailable(panel)) showProcesses(owner,selectedPanelPaths(panel));
}
+177
View File
@@ -0,0 +1,177 @@
constexpr int filesLogSource=680,filesLogStatus=681,filesLogEntries=682,filesLogCopy=683,filesLogRefresh=684;
constexpr size_t filesLogEntryLimit=200,filesLogReadLimit=256*1024;
std::optional<unsigned> filesLogError(std::string_view message,std::string_view marker)
{
const auto last=message.rfind(marker);
if(last==message.npos) return {};
const auto value=message.substr(last+marker.size());
unsigned error{};
const auto parsed=std::from_chars(value.data(),value.data()+value.size(),error);
if(parsed.ec!=std::errc{} || parsed.ptr!=value.data()+value.size()) return {};
return error;
}
std::wstring safeFilesLogEntry(std::string_view line)
{
if(line.ends_with('\r')) line.remove_suffix(1);
std::wstring stamp;
constexpr std::string_view format="0000-00-00 00:00:00 ";
if(line.size()>=format.size())
{
bool valid=true;
for(size_t i=0;i<format.size();++i)
valid&=format[i]=='0'?(line[i]>='0' && line[i]<='9'):line[i]==format[i];
if(valid)
{
stamp=ks::wide(std::string(line.substr(0,format.size()-1)))+L" · ";
line.remove_prefix(format.size());
}
}
// Only fixed descriptions and numeric Windows result codes cross into the UI or clipboard.
std::wstring text;
std::optional<unsigned> error;
if(line=="LAN Files peer lookup failed: local KSwitcher window not found")
text=L"LAN peer lookup failed. KSwitcher is unavailable.";
else if(line.starts_with("LAN Files peer lookup failed: delivered="))
{
text=L"LAN peer lookup failed";
error=filesLogError(line,", Windows error=");
}
else if(line=="LAN Files drive query failed: unexpected error")
text=L"LAN drive query failed. Unexpected error.";
else if(line.starts_with("LAN Files drive query for "))
{
text=L"LAN drive query failed";
error=filesLogError(line,") failed: Windows error ");
if(error==WSAETIMEDOUT) text=L"LAN drive query timed out";
}
else text=L"Diagnostic entry · details hidden";
if(error && *error) text+=L" (Windows error "+std::to_wstring(*error)+L")";
return stamp+text;
}
std::vector<std::wstring> recentFilesLogEntries(const ks::Bytes &bytes)
{
std::vector<std::wstring> entries;
if(bytes.empty()) return entries;
const std::string_view text(reinterpret_cast<const char*>(bytes.data()),bytes.size());
auto end=text.size();
while(end && entries.size()<filesLogEntryLimit)
{
if(text[end-1]=='\n') --end;
const auto split=end?text.rfind('\n',end-1):text.npos;
const auto begin=split==text.npos?0:split+1;
const auto row=text.substr(begin,end-begin);
if(!row.empty() && row!="\r") entries.push_back(safeFilesLogEntry(row));
end=begin;
}
return entries;
}
struct FilesLogDraft
{
std::vector<std::wstring> entries;
};
void refreshFilesLog(HWND dialog,FilesLogDraft &draft)
{
const bool previous=SendDlgItemMessageW(dialog,filesLogSource,CB_GETCURSEL,0,0)==1;
const auto list=GetDlgItem(dialog,filesLogEntries);
SendMessageW(list,LB_RESETCONTENT,0,0);
SendMessageW(list,LB_SETHORIZONTALEXTENT,0,0);
draft.entries.clear();
try
{
if(const auto data=ks::readActiveLogTail(previous,filesLogReadLimit))
{
draft.entries=recentFilesLogEntries(*data);
SetDlgItemTextW(dialog,filesLogStatus,draft.entries.empty()?L"The Files log has no entries.":
L"Most recent first. Select an entry to copy its timestamp and description.");
}
else SetDlgItemTextW(dialog,filesLogStatus,previous?L"No previous Files log is available yet.":
L"No Files log yet. Entries appear when Write log is enabled and Files records a problem.");
}
catch(const std::exception &)
{
SetDlgItemTextW(dialog,filesLogStatus,L"Could not read the Files log. Use Refresh to try again.");
}
int width=0;
const auto dc=GetDC(list);
const auto font=reinterpret_cast<HFONT>(SendMessageW(list,WM_GETFONT,0,0));
const auto oldFont=dc && font?SelectObject(dc,font):nullptr;
for(const auto &entry:draft.entries)
{
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(entry.c_str()));
if(dc)
{
SIZE extent{};
GetTextExtentPoint32W(dc,entry.c_str(),static_cast<int>(entry.size()),&extent);
width=std::max(width,static_cast<int>(extent.cx)+12);
}
}
if(oldFont) SelectObject(dc,oldFont);
if(dc) ReleaseDC(list,dc);
if(width) SendMessageW(list,LB_SETHORIZONTALEXTENT,width,0);
if(!draft.entries.empty()) SendMessageW(list,LB_SETCURSEL,0,0);
EnableWindow(GetDlgItem(dialog,filesLogCopy),!draft.entries.empty());
}
LRESULT CALLBACK filesLogListKeys(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_KEYDOWN && wp=='C' && (GetKeyState(VK_CONTROL)&0x8000) &&
!((GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
{
if(!(lp&(1LL<<30))) SendMessageW(GetParent(list),WM_COMMAND,MAKEWPARAM(filesLogCopy,BN_CLICKED),0);
return 0;
}
return DefSubclassProc(list,message,wp,lp);
}
INT_PTR CALLBACK filesLogDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &draft=*reinterpret_cast<FilesLogDraft*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
for(const auto name:{L"Current",L"Previous"})
SendDlgItemMessageW(dialog,filesLogSource,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
SendDlgItemMessageW(dialog,filesLogSource,CB_SETCURSEL,0,0);
SetWindowSubclass(GetDlgItem(dialog,filesLogEntries),filesLogListKeys,1,0);
refreshFilesLog(dialog,draft);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL)))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
auto &draft=*reinterpret_cast<FilesLogDraft*>(GetWindowLongPtrW(dialog,DWLP_USER));
if(LOWORD(wp)==filesLogRefresh || (LOWORD(wp)==filesLogSource && HIWORD(wp)==CBN_SELCHANGE))
{
refreshFilesLog(dialog,draft);
return TRUE;
}
if(LOWORD(wp)==filesLogCopy)
{
const auto row=SendDlgItemMessageW(dialog,filesLogEntries,LB_GETCURSEL,0,0);
if(row>=0 && static_cast<size_t>(row)<draft.entries.size())
{
if(copyFilesText(dialog,draft.entries[row],L"Could not copy the Files log entry."))
SetDlgItemTextW(dialog,filesLogStatus,L"Entry copied.");
else SetDlgItemTextW(dialog,filesLogStatus,L"Could not copy the Files log entry.");
}
return TRUE;
}
return FALSE;
}
void showFilesLog(HWND owner)
{
FilesLogDraft draft;
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(619),owner,filesLogDialog,
reinterpret_cast<LPARAM>(&draft),false,false);
dialog.runModal();
}
+3135 -720
View File
File diff suppressed because it is too large. Load diff
+384
View File
@@ -0,0 +1,384 @@
#include "lan_network.h"
#include "files_mcp.h"
#include "lan_pairing.h"
#include <algorithm>
#include <atomic>
#include <charconv>
#include <chrono>
#include <future>
#include <map>
#include <mutex>
#include <optional>
#include <thread>
namespace ks::files
{
namespace
{
using Json=FilesMcpServer::Json;
using Clock=std::chrono::steady_clock;
using namespace std::chrono_literals;
constexpr size_t maxHeaders=8192,maxRequest=16*1024,maxResponse=512*1024;
constexpr std::string_view latestProtocol="2025-11-25";
bool supportedProtocol(std::string_view version)
{
return version==latestProtocol || version=="2025-06-18" || version=="2025-03-26";
}
bool readySocket(SOCKET socket,bool write,std::stop_token stop,Clock::time_point deadline)
{
while(!stop.stop_requested() && Clock::now()<deadline)
{
fd_set ready;
FD_ZERO(&ready);
FD_SET(socket,&ready);
timeval wait{0,50000};
const auto result=select(0,write?nullptr:&ready,write?&ready:nullptr,nullptr,&wait);
if(result) return result>0;
}
return false;
}
bool appendSocket(SOCKET socket,std::string &data,std::stop_token stop,Clock::time_point deadline)
{
char buffer[4096];
if(!readySocket(socket,false,stop,deadline)) return false;
const auto count=recv(socket,buffer,sizeof(buffer),0);
if(count<=0) return false;
data.append(buffer,count);
return true;
}
void sendSocket(SOCKET socket,std::string_view bytes,std::stop_token stop)
{
const auto deadline=Clock::now()+2s;
while(!bytes.empty() && readySocket(socket,true,stop,deadline))
{
const auto count=send(socket,bytes.data(),static_cast<int>(bytes.size()),0);
if(count<=0) return;
bytes.remove_prefix(count);
}
}
std::string lowerAscii(std::string_view text)
{
std::string result(text);
for(auto &ch:result)
if(ch>='A' && ch<='Z') ch=static_cast<char>(ch-'A'+'a');
return result;
}
std::string_view trimHeader(std::string_view text)
{
const auto first=text.find_first_not_of(" \t");
return first==text.npos?std::string_view{}:text.substr(first,text.find_last_not_of(" \t")-first+1);
}
struct HttpRequest
{
std::string_view method,path;
std::map<std::string,std::string_view,std::less<>> headers;
std::string_view header(std::string_view field) const
{
const auto found=headers.find(field);
return found==headers.end()?std::string_view{}:found->second;
}
};
std::optional<HttpRequest> parseHeaders(std::string_view data)
{
HttpRequest request;
auto end=data.find("\r\n");
const auto line=data.substr(0,end);
const auto first=line.find(' '),second=first==line.npos?line.npos:line.find(' ',first+1);
if(end==data.npos || !first || second==line.npos || line.substr(second+1)!="HTTP/1.1") return {};
request.method=line.substr(0,first);
request.path=line.substr(first+1,second-first-1);
data.remove_prefix(end+2);
while(!data.empty())
{
end=data.find("\r\n");
const auto header=data.substr(0,end);
const auto colon=header.find(':');
if(!colon || colon==header.npos) return {};
const auto name=lowerAscii(header.substr(0,colon));
const auto value=trimHeader(header.substr(colon+1));
if(!std::ranges::all_of(name,[](char ch)
{return (ch>='a' && ch<='z') || (ch>='0' && ch<='9') || ch=='-' || ch=='_';}) ||
!std::ranges::all_of(value,[](unsigned char ch){return ch=='\t' || (ch>=32 && ch<127);}) ||
!request.headers.emplace(name,value).second)
return {};
if(end==data.npos) break;
data.remove_prefix(end+2);
}
return request;
}
bool hasSessionToken(std::string_view authorization,std::string_view token)
{
if(authorization.size()!=token.size()+7 || lowerAscii(authorization.substr(0,7))!="bearer ") return false;
unsigned difference=0;
for(size_t i=0;i<token.size();++i)
difference|=static_cast<unsigned char>(authorization[i+7]^token[i]);
return difference==0;
}
struct HttpReply
{
const char *status;
std::string body;
const char *headers="";
};
HttpReply jsonReply(const char *status,Json body)
{
return {status,body.dump(-1,' ',false,Json::error_handler_t::replace)};
}
HttpReply rpcError(const char *status,const Json &id,int code,const char *message)
{
return jsonReply(status,{{"jsonrpc","2.0"},{"id",id},{"error",{{"code",code},{"message",message}}}});
}
const Json &mcpTools()
{
static const auto tools=Json::parse(R"({"tools":[
{"name":"get_panels","description":"Read the two Files panes and their current local listings, selections and Find state.",
"inputSchema":{"type":"object","properties":{"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":50}},"additionalProperties":false},
"annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}},
{"name":"search_files","description":"Search the current local listing or existing Find results by name or relative path.",
"inputSchema":{"type":"object","properties":{"side":{"type":"string","enum":["active","left","right"]},"query":{"type":"string","minLength":1,"maxLength":128},"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":50}},"required":["query"],"additionalProperties":false},
"annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}},
{"name":"get_file_metadata","description":"Read cached metadata for a relative path already listed in a current local pane.",
"inputSchema":{"type":"object","properties":{"side":{"type":"string","enum":["active","left","right"]},"path":{"type":"string","minLength":1,"maxLength":2048}},"required":["path"],"additionalProperties":false},
"annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}}
]})");
return tools;
}
Json toolResult(const Json &data,bool error=false)
{
const auto text=error?data.get<std::string>():data.dump(-1,' ',false,Json::error_handler_t::replace);
Json result{{"content",Json::array({{{"type","text"},{"text",text}}})},{"isError",error}};
if(!error) result["structuredContent"]=data;
return result;
}
template<class Read>
HttpReply handleRpc(std::string_view body,const Read &read)
{
Json message,id;
try
{
message=Json::parse(body,[](int depth,Json::parse_event_t,Json &)
{
if(depth>24) throw std::runtime_error("Request nesting limit");
return true;
});
}
catch(const std::exception &) {return rpcError("400 Bad Request",nullptr,-32700,"Invalid JSON");}
if(!message.is_object() || message.value("jsonrpc",Json())!="2.0" ||
!message.contains("method") || !message["method"].is_string())
return rpcError("400 Bad Request",nullptr,-32600,"Invalid request");
const auto &method=message["method"].get_ref<const std::string &>();
if(!message.contains("id"))
{
if(method=="notifications/initialized" || method=="notifications/cancelled") return {"202 Accepted",{}};
return rpcError("400 Bad Request",nullptr,-32600,"Unsupported notification");
}
id=message["id"];
if(!id.is_number_integer() && (!id.is_string() || id.get_ref<const std::string &>().size()>256))
return rpcError("400 Bad Request",nullptr,-32600,"Invalid request id");
auto params=message.value("params",Json::object());
if(!params.is_object()) return rpcError("200 OK",id,-32602,"Invalid parameters");
Json result;
if(method=="initialize")
{
if(!params.contains("protocolVersion") || !params["protocolVersion"].is_string())
return rpcError("200 OK",id,-32602,"Protocol version is required");
const auto version=params["protocolVersion"].get<std::string>();
result={{"protocolVersion",supportedProtocol(version)?version:std::string(latestProtocol)},
{"capabilities",{{"tools",Json::object()}}},
{"serverInfo",{{"name","kswitcher-files"},{"version","1.0.0"}}},
{"instructions","Inspect the current local listings and cached metadata. Search uses the Files panels' current results."}};
}
else if(method=="ping") result=Json::object();
else if(method=="tools/list") result=mcpTools();
else if(method=="tools/call")
{
if(!params.contains("name") || !params["name"].is_string())
return rpcError("200 OK",id,-32602,"Tool name is required");
const auto &name=params["name"].get_ref<const std::string &>();
const auto args=params.value("arguments",Json::object());
if(!args.is_object() || !std::ranges::any_of(mcpTools()["tools"],[&](const auto &tool)
{return tool["name"]==name;}))
return rpcError("200 OK",id,-32602,"Unknown tool or invalid arguments");
auto data=read(name,args);
const auto failed=data.contains("error");
result=failed?toolResult(data.at("error"),true):toolResult(data);
}
else return rpcError("200 OK",id,-32601,"Method not found");
auto answer=jsonReply("200 OK",{{"jsonrpc","2.0"},{"id",id},{"result",std::move(result)}});
return answer.body.size()<=maxResponse?std::move(answer):rpcError("200 OK",id,-32603,"Response is too large");
}
template<class Read>
HttpReply handleHttp(SOCKET socket,unsigned port,std::string_view token,std::stop_token stop,const Read &read)
{
std::string bytes;
const auto deadline=Clock::now()+2s;
size_t end{};
while((end=bytes.find("\r\n\r\n"))==bytes.npos)
{
if(bytes.size()>=maxHeaders) return {"431 Request Header Fields Too Large",{}};
if(!appendSocket(socket,bytes,stop,deadline)) return {"408 Request Timeout",{}};
}
if(end+4>maxHeaders) return {"431 Request Header Fields Too Large",{}};
// Header fields refer into bytes. Parse before appending any further data.
const auto request=parseHeaders(std::string_view(bytes).substr(0,end+2));
if(!request) return {"400 Bad Request",{}};
if(request->headers.contains("origin") || request->header("host")!="127.0.0.1:"+std::to_string(port))
return {"403 Forbidden",{}};
if(!hasSessionToken(request->header("authorization"),token))
return {"401 Unauthorized",{},"WWW-Authenticate: Bearer\r\n"};
if(request->path!="/mcp") return {"404 Not Found",{}};
if(request->method!="POST") return {"405 Method Not Allowed",{},"Allow: POST\r\n"};
if(request->headers.contains("transfer-encoding") ||
(request->headers.contains("mcp-protocol-version") && !supportedProtocol(request->header("mcp-protocol-version"))))
return {"400 Bad Request",{}};
const auto type=request->header("content-type");
if(lowerAscii(trimHeader(type.substr(0,type.find(';'))))!="application/json") return {"415 Unsupported Media Type",{}};
const auto length=request->header("content-length");
size_t count{};
if(length.empty()) return {"411 Length Required",{}};
const auto converted=std::from_chars(length.data(),length.data()+length.size(),count);
if(converted.ec!=std::errc{} || converted.ptr!=length.data()+length.size()) return {"400 Bad Request",{}};
if(count>maxRequest) return {"413 Content Too Large",{}};
const auto start=end+4;
while(bytes.size()-start<count)
if(!appendSocket(socket,bytes,stop,deadline)) return {"408 Request Timeout",{}};
if(bytes.size()-start!=count) return {"400 Bad Request",{}};
return handleRpc(std::string_view(bytes).substr(start,count),read);
}
}
struct FilesMcpServer::Session
{
struct Query
{
std::string name;
Json arguments;
std::promise<Json> result;
std::atomic_bool cancelled{};
};
lan::Network network;
lan::WinSocket listener;
unsigned port{};
std::string token=lan::randomHex(32);
HWND owner{};
std::mutex gate;
std::shared_ptr<Query> pending;
std::jthread worker;
explicit Session(HWND window):owner(window)
{
listener.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
BOOL exclusive=TRUE;
u_long nonblocking=1;
sockaddr_in address{};
address.sin_family=AF_INET;
address.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
int size=sizeof(address);
if(listener.value==INVALID_SOCKET || setsockopt(listener.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,
reinterpret_cast<const char*>(&exclusive),sizeof(exclusive)) ||
ioctlsocket(listener.value,FIONBIO,&nonblocking) ||
bind(listener.value,reinterpret_cast<const sockaddr *>(&address),sizeof(address)) ||
listen(listener.value,4) || getsockname(listener.value,reinterpret_cast<sockaddr *>(&address),&size))
lan::socketError();
port=ntohs(address.sin_port);
worker=std::jthread([this](std::stop_token stop){run(stop);});
}
~Session()
{
worker.request_stop();
if(worker.joinable()) worker.join();
SecureZeroMemory(token.data(),token.size());
}
Json requestUi(std::string_view name,const Json &arguments,std::stop_token stop)
{
auto query=std::make_shared<Query>();
query->name=name;
query->arguments=arguments;
auto result=query->result.get_future();
{
std::lock_guard lock(gate);
pending=query;
}
const auto deadline=Clock::now()+2s;
if(PostMessageW(owner,filesMcpQueryMessage,0,0))
while(!stop.stop_requested() && Clock::now()<deadline)
if(result.wait_for(25ms)==std::future_status::ready) return result.get();
query->cancelled=true;
std::lock_guard lock(gate);
if(pending==query) pending.reset();
return {{"error","Files did not answer in time."}};
}
void run(std::stop_token stop)
{
while(!stop.stop_requested())
{
if(!readySocket(listener.value,false,stop,Clock::now()+100ms)) continue;
sockaddr_in peer{};
int peerSize=sizeof(peer);
lan::WinSocket client;
client.value=accept(listener.value,reinterpret_cast<sockaddr *>(&peer),&peerSize);
u_long nonblocking=1;
if(client.value==INVALID_SOCKET || peer.sin_family!=AF_INET ||
peer.sin_addr.s_addr!=htonl(INADDR_LOOPBACK) || ioctlsocket(client.value,FIONBIO,&nonblocking))
continue;
HttpReply reply{"500 Internal Server Error",{}};
try
{
reply=handleHttp(client.value,port,token,stop,[&](std::string_view name,const Json &params)
{return requestUi(name,params,stop);});
}
catch(const std::exception &) {}
const auto header=std::string("HTTP/1.1 ")+reply.status+"\r\nConnection: close\r\n"
"Cache-Control: no-store\r\nContent-Type: application/json\r\n"+reply.headers+
"Content-Length: "+std::to_string(reply.body.size())+"\r\n\r\n";
sendSocket(client.value,header+reply.body,stop);
}
}
};
FilesMcpServer::FilesMcpServer()=default;
FilesMcpServer::~FilesMcpServer()=default;
void FilesMcpServer::start(HWND owner)
{
if(!session) session=std::make_unique<Session>(owner);
}
void FilesMcpServer::stop() {session.reset();}
unsigned FilesMcpServer::port() const {return session?session->port:0;}
std::string_view FilesMcpServer::token() const {return session?std::string_view(session->token):std::string_view{};}
void FilesMcpServer::answer(const ReadTool &read)
{
if(!session) return;
std::shared_ptr<Session::Query> query;
{
std::lock_guard lock(session->gate);
query=std::exchange(session->pending,{});
}
if(!query || query->cancelled) return;
try {query->result.set_value(read(query->name,query->arguments));}
catch(const std::exception &) {query->result.set_value({{"error","Files could not read the requested state."}});}
}
}
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include "../vendor/json.hpp"
#include <windows.h>
#include <functional>
#include <memory>
#include <string_view>
namespace ks::files
{
inline constexpr UINT filesMcpQueryMessage=WM_APP+274;
class FilesMcpServer
{
public:
using Json=nlohmann::json;
using ReadTool=std::function<Json(std::string_view,const Json &)>;
FilesMcpServer();
~FilesMcpServer();
FilesMcpServer(const FilesMcpServer &)=delete;
FilesMcpServer &operator=(const FilesMcpServer &)=delete;
void start(HWND owner);
void stop();
unsigned port() const;
std::string_view token() const;
void answer(const ReadTool &read);
private:
struct Session;
std::unique_ptr<Session> session;
};
}
+223
View File
@@ -0,0 +1,223 @@
ks::files::FilesMcpServer filesMcp;
constexpr int filesMcpStatus=690,filesMcpEndpoint=691,filesMcpToken=692,filesMcpToggle=693,
filesMcpShowToken=694,filesMcpCopyToken=695;
constexpr size_t maxMcpRows=50,maxMcpSearchScan=10000;
std::string mcpSide(int side) {return side==0?"left":"right";}
bool mcpLocalPanel(const Panel &panel)
{
return !panel.peer && !panel.ftp && !panel.archive && ks::files::isLocalDocumentPath(panel.directory);
}
std::optional<std::wstring> mcpRelativePath(const Panel &panel,size_t row)
{
if(row>=panel.rows.size() || row>=panel.sizes.size() || panel.sizes[row]==L"Up") return {};
const auto relative=panel.rows[row].lexically_relative(panel.directory);
if(relative.empty() || relative.has_root_path()) return {};
for(const auto &part:relative)
if(!ks::files::validWindowsFileName(part.native())) return {};
const auto path=relative.generic_wstring();
if(path.size()>2048) return {};
return path;
}
Json mcpFileItem(const Panel &panel,size_t row,const std::wstring &relative)
{
Json item{{"path",ks::utf8(relative)},{"marked",row<panel.marked.size() && panel.marked[row]}};
const auto found=panel.metadata.find(panel.rows[row]);
if(found==panel.metadata.end())
{
item["metadataAvailable"]=false;
return item;
}
const auto &info=found->second;
const bool directory=(info.attributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
item["metadataAvailable"]=true;
item["kind"]=directory?"directory":"file";
item["attributes"]=info.attributes;
item["reparsePoint"]=(info.attributes&FILE_ATTRIBUTE_REPARSE_POINT)!=0;
if(!directory) item["sizeBytes"]=info.size;
if(info.modified)
{
const FILETIME time{static_cast<DWORD>(info.modified),static_cast<DWORD>(info.modified>>32)};
SYSTEMTIME utc{};
if(FileTimeToSystemTime(&time,&utc))
{
wchar_t date[32]{};
swprintf_s(date,L"%04u-%02u-%02uT%02u:%02u:%02uZ",utc.wYear,utc.wMonth,utc.wDay,
utc.wHour,utc.wMinute,utc.wSecond);
item["modifiedUtc"]=ks::utf8(date);
}
}
return item;
}
std::optional<size_t> mcpPageValue(const Json &args,const char *key,size_t fallback,size_t maximum)
{
if(!args.contains(key)) return fallback;
const auto &value=args.at(key);
if(!value.is_number_unsigned() || value>maximum) return {};
return value.get<size_t>();
}
bool mcpArgumentNames(const Json &arguments,std::initializer_list<std::string_view> accepted)
{
for(auto field=arguments.begin();field!=arguments.end();++field)
if(std::ranges::find(accepted,std::string_view(field.key()))==accepted.end()) return false;
return true;
}
std::optional<int> mcpArgumentSide(const Json &arguments)
{
if(!arguments.contains("side") || arguments.at("side")=="active") return active;
if(arguments.at("side")=="left") return 0;
if(arguments.at("side")=="right") return 1;
return {};
}
Json mcpPanelPage(const Panel &panel,size_t offset,size_t limit,std::wstring_view query={})
{
Json entries=Json::array();
size_t row=std::min(offset,panel.rows.size());
const auto scannedEnd=row+std::min(maxMcpSearchScan,panel.rows.size()-row);
for(;row<scannedEnd && entries.size()<limit;++row)
if(const auto relative=mcpRelativePath(panel,row))
if(query.empty() || ks::lower(*relative).find(query)!=std::wstring::npos)
entries.push_back(mcpFileItem(panel,row,*relative));
return {{"entries",std::move(entries)},{"nextOffset",row<panel.rows.size()?Json(row):Json(nullptr)}};
}
Json mcpPanelState(int side,size_t offset,size_t limit)
{
const auto &panel=panels[side];
Json result{{"side",mcpSide(side)},{"available",mcpLocalPanel(panel)},
{"visible",IsWindowVisible(panel.list)!=FALSE}};
if(!result.at("available").get<bool>()) return result;
result["directory"]=ks::utf8(panel.directory.native());
result["mode"]=ks::utf8(panelModeNames[static_cast<size_t>(panel.mode)]);
result["scanning"]=panel.scanRequest.has_value();
const auto selected=currentPanelRow(panel);
if(selected!=LB_ERR)
if(const auto path=mcpRelativePath(panel,static_cast<size_t>(selected))) result["cursor"]=ks::utf8(*path);
const auto *pending=panel.scanRequest && panel.scanRequest->find?&*panel.scanRequest->find:nullptr;
if(pending || panel.findOrigin)
{
const auto &find=pending?*pending:panel.findOrigin->options;
result["find"]={{"mask",ks::utf8(find.mask)},{"includeHidden",find.includeHidden},
{"running",pending!=nullptr},{"error",pending?0:panel.findOrigin->error}};
}
result.update(mcpPanelPage(panel,offset,limit));
return result;
}
Json readFilesMcpTool(std::string_view tool,const Json &arguments)
{
const auto offset=mcpPageValue(arguments,"offset",0,2147483647);
const auto limit=mcpPageValue(arguments,"limit",25,maxMcpRows);
if(!offset || !limit || !*limit) return {{"error","Invalid page offset or limit."}};
if(tool=="get_panels")
{
if(!mcpArgumentNames(arguments,{"offset","limit"})) return {{"error","Unknown pane argument."}};
return {{"active",mcpSide(active)},{"panels",Json::array(
{mcpPanelState(0,*offset,*limit),mcpPanelState(1,*offset,*limit)})}};
}
const auto side=mcpArgumentSide(arguments);
if(!side) return {{"error","Choose an active, left or right pane."}};
const auto &panel=panels[*side];
if(!mcpLocalPanel(panel)) return {{"error","This pane is not a local filesystem listing."}};
if(tool=="search_files")
{
if(!mcpArgumentNames(arguments,{"side","query","offset","limit"}) || !arguments.contains("query") ||
!arguments["query"].is_string() || arguments["query"].get_ref<const std::string &>().size()>512)
return {{"error","Enter a search query of 1 to 128 characters."}};
auto query=ks::wide(arguments["query"].get_ref<const std::string &>());
if(query.empty() || query.size()>128 || query.find_first_of(L"\r\n")!=query.npos ||
query.find(L'\0')!=query.npos) return {{"error","Enter a search query of 1 to 128 characters."}};
auto result=mcpPanelPage(panel,*offset,*limit,ks::lower(std::move(query)));
result["side"]=mcpSide(*side);
result["scope"]=panel.findOrigin?"find-results":"current-listing";
return result;
}
if(tool!="get_file_metadata" || !mcpArgumentNames(arguments,{"side","path"}) ||
!arguments.contains("path") || !arguments["path"].is_string() ||
arguments["path"].get_ref<const std::string &>().size()>8192)
return {{"error","Choose a relative path from the current pane."}};
auto relative=fs::path(ks::wide(arguments["path"].get_ref<const std::string &>()));
if(relative.empty() || relative.has_root_path() || relative.native().size()>2048)
return {{"error","Choose a relative path from the current pane."}};
for(const auto &part:relative)
if(!ks::files::validWindowsFileName(part.native()))
return {{"error","Choose a relative path from the current pane."}};
relative.make_preferred();
const auto path=panel.directory/relative;
const auto found=std::ranges::find(panel.rows,path);
if(found==panel.rows.end()) return {{"error","The file is not in the current pane."}};
const auto row=static_cast<size_t>(found-panel.rows.begin());
const auto listed=mcpRelativePath(panel,row);
if(!listed) return {{"error","The file is not in the current pane."}};
return mcpFileItem(panel,row,*listed);
}
void updateFilesMcpDialog(HWND dialog)
{
const auto port=filesMcp.port();
const auto endpoint=port?L"http://127.0.0.1:"+std::to_wstring(port)+L"/mcp":L"";
SetDlgItemTextW(dialog,filesMcpEndpoint,endpoint.c_str());
SetDlgItemTextW(dialog,filesMcpToggle,port?L"&Stop":L"&Start");
EnableWindow(GetDlgItem(dialog,filesMcpShowToken),port!=0);
EnableWindow(GetDlgItem(dialog,filesMcpCopyToken),port!=0);
if(!port) CheckDlgButton(dialog,filesMcpShowToken,BST_UNCHECKED);
const auto token=port && IsDlgButtonChecked(dialog,filesMcpShowToken)==BST_CHECKED?
ks::wide(std::string(filesMcp.token())):L"";
SetDlgItemTextW(dialog,filesMcpToken,token.c_str());
SetDlgItemTextW(dialog,filesMcpStatus,port?
L"Running on this computer. Stop to revoke the session token.":L"Stopped.");
}
INT_PTR CALLBACK filesMcpDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
updateFilesMcpDialog(dialog);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL)))
{
SetDlgItemTextW(dialog,filesMcpToken,L"");
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
switch(LOWORD(wp))
{
case filesMcpToggle:
try
{
if(filesMcp.port()) filesMcp.stop();
else filesMcp.start(reinterpret_cast<HWND>(GetWindowLongPtrW(dialog,DWLP_USER)));
updateFilesMcpDialog(dialog);
}
catch(const std::exception &)
{
SetDlgItemTextW(dialog,filesMcpStatus,L"Could not start the local MCP listener.");
}
return TRUE;
case filesMcpShowToken:
updateFilesMcpDialog(dialog);
return TRUE;
case filesMcpCopyToken:
if(filesMcp.port() && copyFilesText(dialog,ks::wide(std::string(filesMcp.token())),L"Could not copy the token."))
SetDlgItemTextW(dialog,filesMcpStatus,L"Session token copied.");
return TRUE;
}
return FALSE;
}
void showFilesMcp(HWND owner)
{
FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(620),owner,filesMcpDialog,
reinterpret_cast<LPARAM>(owner),false,false);
dialog.runModal();
}
+192
View File
@@ -0,0 +1,192 @@
constexpr DWORD spaceFileShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE;
bool sameVolumeRoot(const fs::path &directory,const fs::path &root)
{
if(root.empty()) return false;
const auto comparable=[](const fs::path &path) {
auto value=std::wstring_view(path.native());
if(!value.empty() && (value.back()==L'\\' || value.back()==L'/')) value.remove_suffix(1);
return value;
};
const auto left=comparable(directory),right=comparable(root);
return !left.empty() && !right.empty() && CompareStringOrdinal(left.data(),static_cast<int>(left.size()),
right.data(),static_cast<int>(right.size()),TRUE)==CSTR_EQUAL;
}
bool isNtfsVolume(const fs::path &root)
{
wchar_t filesystem[16]{};
return GetVolumeInformationW(root.c_str(),nullptr,0,nullptr,nullptr,nullptr,filesystem,
static_cast<DWORD>(std::size(filesystem))) && std::wstring_view(filesystem)==L"NTFS";
}
using NtfsDirectoryIds=std::set<uint64_t>;
bool appendMftDirectories(std::span<const unsigned char> records,NtfsDirectoryIds &directories)
{
struct UsnRow
{
DWORD length;
WORD major,minor;
DWORDLONG id,parent;
USN usn;
LARGE_INTEGER time;
DWORD reason,source,security,attributes;
WORD nameLength,nameOffset;
};
constexpr auto header=offsetof(UsnRow,nameOffset)+sizeof(WORD);
static_assert(header==60);
while(!records.empty())
{
if(records.size()<header) return false;
UsnRow row{};
memcpy(&row,records.data(),header);
if(row.major!=2 || row.length<header || row.length>records.size()) return false;
if((row.attributes&FILE_ATTRIBUTE_DIRECTORY) && !(row.attributes&FILE_ATTRIBUTE_REPARSE_POINT))
directories.insert(row.id);
records=records.subspan(row.length);
}
return true;
}
bool isExpectedNtfsDirectory(HANDLE handle,const fs::path &directory)
{
std::wstring name(MAX_PATH,L'\0');
const auto getName=[&] {
return GetFinalPathNameByHandleW(handle,name.data(),static_cast<DWORD>(name.size()),
FILE_NAME_OPENED|VOLUME_NAME_DOS);
};
auto length=getName();
if(length>=name.size())
{
name.resize(length+1);
length=getName();
}
if(!length || length>=name.size()) return false;
name.resize(length);
constexpr std::wstring_view devicePrefix=LR"(\\?\)";
const auto &expected=directory.native();
std::wstring_view actual(name);
if(actual.starts_with(devicePrefix) && !std::wstring_view(expected).starts_with(devicePrefix))
actual.remove_prefix(devicePrefix.size());
return CompareStringOrdinal(actual.data(),static_cast<int>(actual.size()),expected.data(),
static_cast<int>(expected.size()),TRUE)==CSTR_EQUAL;
}
bool readMftDirectoryIds(const fs::path &root,NtfsDirectoryIds &directories,std::stop_token stop)
{
wchar_t name[64]{};
if(!GetVolumeNameForVolumeMountPointW(root.c_str(),name,static_cast<DWORD>(std::size(name)))) return false;
const auto length=wcslen(name);
if(!length || name[length-1]!=L'\\') return false;
name[length-1]=L'\0';
const Handle volume{CreateFileW(name,GENERIC_READ,spaceFileShare,nullptr,OPEN_EXISTING,0,nullptr)};
if(volume.value==INVALID_HANDLE_VALUE) return false;
struct Enumeration {DWORDLONG first; USN low,high;};
static_assert(sizeof(Enumeration)==24);
Enumeration request{0,0,std::numeric_limits<USN>::max()};
auto buffer=std::vector<unsigned char>(512*1024);
while(!stop.stop_requested())
{
DWORD bytes{};
if(!DeviceIoControl(volume.value,FSCTL_ENUM_USN_DATA,&request,sizeof(request),buffer.data(),
static_cast<DWORD>(buffer.size()),&bytes,nullptr))
return GetLastError()==ERROR_HANDLE_EOF && !directories.empty();
DWORDLONG next{};
if(bytes<sizeof(next) || bytes>buffer.size()) return false;
memcpy(&next,buffer.data(),sizeof(next));
if(next<=request.first) return false;
if(!appendMftDirectories(std::span<const unsigned char>(buffer).subspan(sizeof(next),bytes-sizeof(next)),
directories)) return false;
request.first=next;
}
return false;
}
class NtfsSpaceWalk
{
public:
NtfsSpaceWalk(const fs::path &root,const fs::path &mount,std::stop_token stop) : root(root),
volumeHint{CreateFileW(root.c_str(),FILE_READ_ATTRIBUTES,spaceFileShare,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,nullptr)}
{
if(volumeHint.value!=INVALID_HANDLE_VALUE)
{
try {indexed=readMftDirectoryIds(mount,mft,stop);}
catch(const std::exception &) {}
}
if(!indexed) mft.clear();
}
bool usedMft() const { return usedIndex; }
bool list(const fs::path &directory,const FileVisitor &visit,std::stop_token stop,FilesConnection &fallback)
{
const bool atRoot=directory==root;
const auto known=byPath.extract(directory);
constexpr DWORD openFlags=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT;
Handle handle{INVALID_HANDLE_VALUE};
if(known && mft.contains(known.mapped()))
{
FILE_ID_DESCRIPTOR id{};
id.dwSize=sizeof(id);
id.Type=FileIdType;
id.FileId.QuadPart=static_cast<LONGLONG>(known.mapped());
handle.value=OpenFileById(volumeHint.value,&id,FILE_LIST_DIRECTORY|FILE_READ_ATTRIBUTES,
spaceFileShare,nullptr,openFlags);
if(handle.value!=INVALID_HANDLE_VALUE)
{
if(isExpectedNtfsDirectory(handle.value,directory)) usedIndex=true;
else
{
CloseHandle(handle.value);
handle.value=INVALID_HANDLE_VALUE;
}
}
}
if(handle.value==INVALID_HANDLE_VALUE)
handle.value=CreateFileW(directory.c_str(),FILE_LIST_DIRECTORY|FILE_READ_ATTRIBUTES,
spaceFileShare,nullptr,OPEN_EXISTING,atRoot?FILE_FLAG_BACKUP_SEMANTICS:openFlags,nullptr);
if(handle.value==INVALID_HANDLE_VALUE) return false;
FILE_ATTRIBUTE_TAG_INFO tag{};
if(!GetFileInformationByHandleEx(handle.value,FileAttributeTagInfo,&tag,sizeof(tag)) ||
!(tag.FileAttributes&FILE_ATTRIBUTE_DIRECTORY) ||
(!atRoot && (tag.FileAttributes&FILE_ATTRIBUTE_REPARSE_POINT))) return false;
bool emitted=false;
const auto status=ks::files::visitDirectoryRecords(handle.value,[&](const FILE_ID_BOTH_DIR_INFO &row,
std::wstring_view name) -> DWORD
{
if(stop.stop_requested()) return ERROR_CANCELLED;
const auto path=directory/name;
const auto attributes=row.FileAttributes;
const auto directoryEntry=(attributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
if(directoryEntry && !(attributes&FILE_ATTRIBUTE_REPARSE_POINT) && indexed)
{
const auto id=static_cast<uint64_t>(row.FileId.QuadPart);
if(mft.contains(id)) byPath.try_emplace(path,id);
}
FileInfo entry{attributes,static_cast<uint64_t>(row.EndOfFile.QuadPart),
static_cast<uint64_t>(row.LastWriteTime.QuadPart)};
if(!(attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT|
FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE)) && row.AllocationSize.QuadPart>=0)
entry.allocated=static_cast<uint64_t>(row.AllocationSize.QuadPart);
emitted=true;
return visit(path,entry)?ERROR_SUCCESS:ERROR_CANCELLED;
});
if(!emitted && (status==ERROR_NOT_SUPPORTED || status==ERROR_INVALID_PARAMETER || status==ERROR_INVALID_FUNCTION))
{
if(atRoot) return !stop.stop_requested() && listFiles(fallback,directory,visit);
return listMeasuredDirectory(fallback,directory,visit,stop);
}
return status==ERROR_SUCCESS;
}
private:
fs::path root;
Handle volumeHint;
NtfsDirectoryIds mft;
std::map<fs::path,uint64_t> byPath;
bool indexed{}, usedIndex{};
};
+311 -101
View File
@@ -1,28 +1,34 @@
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286,
optionsImport=525,optionsExport=526,
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;
comparisonChooseColor=412,comparisonColorValue=413,comparisonKeySchemesButton=415;
constexpr int comparisonControls[]{comparisonFontLabel,comparisonChooseFont,410,comparisonColorCombo,
comparisonChooseColor,comparisonColorValue,414,comparisonShortcutControl};
comparisonChooseColor,comparisonColorValue,comparisonKeySchemesButton};
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 };
constexpr const wchar_t *panelSectionNames[]{L"Panel layout",L"Wide panel columns",L"Status line columns"};
constexpr int panelLayoutControls[]{273,274};
constexpr int rightClickMarksControl=520, driveButtonsControl=521, compactLayoutControl=522;
constexpr int panelLayoutControls[]{506,273,507,274,rightClickMarksControl,driveButtonsControl,compactLayoutControl,523};
constexpr int wideColumnControls[]{275,276,201,202,204};
constexpr int statusColumnControls[]{277,203,205,206,207,208};
constexpr int colorOptionControls[]{279,280};
constexpr int appearanceControls[]{281,282};
enum AppearanceSection { Font, DialogFrame };
enum AppearanceSection { Font, DialogFrame, SystemThemes };
constexpr int terminalScaleSection=1,areaScaleLabel=528,areaScaleControl=529;
constexpr int systemLightChoice=531,systemDarkChoice=533;
constexpr int systemThemeControls[]{530,systemLightChoice,532,systemDarkChoice,535};
constexpr int outerFramePadding=303,innerFramePadding=305,rowTextPadding=307;
constexpr int dialogFrameControls[]{302,outerFramePadding,304,innerFramePadding,306,rowTextPadding};
constexpr int restoreDocumentsControl=524;
constexpr int textTabWidth=357,textLineEnding=359,
textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368;
textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368,textRenameScheme=534;
constexpr int textControls[]{350,351,352,353,356,textTabWidth,
362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme};
362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme,textRenameScheme};
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};
@@ -51,7 +57,7 @@ constexpr struct
{innerFramePadding,&DialogFramePadding::inner,maxDialogFramePadding},
{rowTextPadding,&DialogFramePadding::rowText,maxDialogRowTextPadding}};
enum class OptionsAnchor { StretchWidth, StretchHeight, BottomRight };
enum class OptionsAnchor { StretchWidth, StretchHeight, BottomRight, BottomLeft };
struct OptionsControl
{
int id;
@@ -66,7 +72,10 @@ struct PanelProperty
DWORD defaultValue;
};
constexpr PanelProperty panelProperties[]{
{PanelLayout,273,L"Left panel: Wide",defaultWide},{PanelLayout,274,L"Right panel: Wide",defaultWide},
{PanelLayout,273,L"Left panel mode",defaultWide?1u:0u},{PanelLayout,274,L"Right panel mode",defaultWide?1u:0u},
{PanelLayout,rightClickMarksControl,L"Mark items with the right mouse button",0},
{PanelLayout,driveButtonsControl,L"Show drive buttons",0},
{PanelLayout,compactLayoutControl,L"Compact commander layout",0},
{WideColumns,201,L"Size column width",defaultSizeWidth},
{WideColumns,202,L"Align file extensions",defaultAlignExtensions},
{WideColumns,204,L"Align folder extensions",defaultAlignFolders},
@@ -76,9 +85,24 @@ constexpr PanelProperty panelProperties[]{
void resetPanelProperty(HWND dialog,const PanelProperty &property)
{
if(property.control==201) SetDlgItemInt(dialog,property.control,property.defaultValue,FALSE);
else if(property.control==273 || property.control==274)
SendDlgItemMessageW(dialog,property.control,CB_SETCURSEL,property.defaultValue,0);
else CheckDlgButton(dialog,property.control,property.defaultValue);
}
PanelMode panelModeOption(HWND dialog,int index)
{
const auto selection=SendDlgItemMessageW(dialog,273+index,CB_GETCURSEL,0,0);
return selection>=0 && static_cast<size_t>(selection)<std::size(panelModeNames)?
static_cast<PanelMode>(selection):PanelMode::brief;
}
void showPanelModeOptions(HWND dialog)
{
for(int index=0;index<2;++index)
SendDlgItemMessageW(dialog,273+index,CB_SETCURSEL,static_cast<WPARAM>(panels[index].mode),0);
}
struct OptionsBaseline
{
LOGFONTW font=displayFont;
@@ -86,16 +110,18 @@ struct OptionsBaseline
DialogFramePadding padding=dialogFramePadding;
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};
bool mouseMarks=rightClickMarks, drives=showDriveButtons, compact=compactLayout;
bool restoreLocal=restoreDocuments;
std::array<PanelMode,2> modes{panels[0].mode,panels[1].mode};
ks::files::TextSettings text=ks::files::loadTextPreferences();
ComparisonAppearance comparison=readComparisonAppearance();
WORD compareShortcut=comparisonShortcut;
FilesKeySettings keySettings=filesKeySettings;
ks::files::AppearanceScales scales=readAreaScales();
};
struct OptionsDraft
@@ -103,6 +129,8 @@ struct OptionsDraft
OptionsBaseline baseline;
ks::files::TextSettings text=baseline.text;
ComparisonAppearance comparison=baseline.comparison;
FilesKeySettings keySettings=baseline.keySettings;
ks::files::AppearanceScales scales=baseline.scales;
HWND filesWindow{};
LOGFONTW font=displayFont;
int points=fontPoints;
@@ -118,13 +146,14 @@ struct OptionsDraft
HTREEITEM wideColumnsNode{},markdownNode{};
RECT initialClient{};
UINT initialDpi=96;
OptionsControl controls[8]{
OptionsControl controls[10]{
{optionsTree,OptionsAnchor::StretchHeight},
{optionsTitle,OptionsAnchor::StretchWidth},
{275,OptionsAnchor::StretchWidth},{277,OptionsAnchor::StretchWidth},
{281,OptionsAnchor::StretchWidth},
{IDOK,OptionsAnchor::BottomRight},{IDCANCEL,OptionsAnchor::BottomRight},
{optionsApply,OptionsAnchor::BottomRight}};
{optionsApply,OptionsAnchor::BottomRight},
{optionsImport,OptionsAnchor::BottomLeft},{optionsExport,OptionsAnchor::BottomLeft}};
};
@@ -142,19 +171,6 @@ bool optionsFontChanged(const OptionsDraft &draft)
_wcsicmp(pending.lfFaceName,applied.lfFaceName)!=0;
}
struct OptionsWriteLock
{
HANDLE mutex=CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.OptionsWrite");
DWORD result=mutex?WaitForSingleObject(mutex,2000):WAIT_FAILED;
bool acquired() const { return result==WAIT_OBJECT_0 || result==WAIT_ABANDONED; }
~OptionsWriteLock()
{
if(acquired()) ReleaseMutex(mutex);
if(mutex) CloseHandle(mutex);
}
};
void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
{
BOOL valid{};
@@ -164,15 +180,17 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
for(int i=0;i<4;++i) if(checked(205+i)) fields|=1u<<i;
const auto &base=draft.baseline;
const bool dirty=!valid || draft.markdownError || width!=base.width ||
checked(273)!=base.wide[0] || checked(274)!=base.wide[1] ||
panelModeOption(dialog,0)!=base.modes[0] || panelModeOption(dialog,1)!=base.modes[1] ||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
checked(rightClickMarksControl)!=base.mouseMarks || checked(driveButtonsControl)!=base.drives ||
checked(compactLayoutControl)!=base.compact || checked(restoreDocumentsControl)!=base.restoreLocal ||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
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;
draft.text!=base.text || draft.comparison!=base.comparison || draft.keySettings!=base.keySettings ||
draft.scales!=base.scales;
EnableWindow(GetDlgItem(dialog,optionsApply),dirty);
InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE);
}
@@ -230,6 +248,7 @@ void layoutOptions(HWND dialog,const OptionsDraft &draft)
case OptionsAnchor::StretchWidth: width+=dx;break;
case OptionsAnchor::StretchHeight: height+=dy;break;
case OptionsAnchor::BottomRight: x+=dx;y+=dy;break;
case OptionsAnchor::BottomLeft: y+=dy;break;
}
SetWindowPos(GetDlgItem(dialog,control.id),nullptr,x,y,width,height,
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOREDRAW);
@@ -265,19 +284,22 @@ void populateTextSchemes(HWND dialog,const ks::files::TextSettings &settings)
};
add(L"Custom");
for(const auto name:ks::files::textPaletteNames) add(name);
add(L"System (Windows)");
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)
const auto presets=std::size(ks::files::textPalettes);
if(profile.scheme==ks::files::systemTextScheme) return presets+1;
for(size_t index=0;index<presets;++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 presets+index+2;
}
return 0;
}
@@ -288,6 +310,13 @@ INT_PTR CALLBACK schemeNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
SendDlgItemMessageW(dialog,100,EM_SETLIMITTEXT,ks::files::maxTextPaletteName,0);
const auto &name=*reinterpret_cast<const std::wstring*>(lp);
if(!name.empty())
{
SetWindowTextW(dialog,L"Rename color scheme");
SetDlgItemTextW(dialog,100,name.c_str());
SetDlgItemTextW(dialog,IDOK,L"Rename");
}
groupDialogButtons(dialog,{IDOK,IDCANCEL},true);
return TRUE;
}
@@ -305,13 +334,22 @@ INT_PTR CALLBACK schemeNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
}
void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files::TextPreferences &profile)
bool reservedTextSchemeName(const std::wstring &name)
{
return sameSchemeName(name,L"Custom") || sameSchemeName(name,L"System (Windows)") ||
sameSchemeName(name,ks::files::systemTextScheme) ||
std::any_of(std::begin(ks::files::textPaletteNames),std::end(ks::files::textPaletteNames),
[&](const wchar_t *preset){return sameSchemeName(name,preset);});
}
void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,bool edit)
{
auto &profile=settings.profiles[edit];
const auto palette=ks::files::resolvedTextProfile(settings,edit).colors;
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);}))
if(reservedTextSchemeName(name))
{
showFilesNotice(dialog,L"Choose a different name for your color scheme.",L"Save color scheme");
return;
@@ -322,7 +360,7 @@ void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files
{
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;
existing->colors=palette;
profile.scheme=existing->name;
}
else
@@ -332,18 +370,44 @@ void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files
showFilesNotice(dialog,L"The color scheme list is full.",L"Save color scheme");
return;
}
settings.schemes.push_back({name,profile.colors});
settings.schemes.push_back({name,palette});
profile.scheme=std::move(name);
}
profile.colors=palette;
populateTextSchemes(dialog,settings);
}
void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
void renameTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,const ks::files::TextPreferences &profile)
{
const auto scheme=std::ranges::find_if(settings.schemes,[&](const auto &candidate)
{ return sameSchemeName(profile.scheme,candidate.name.c_str()); });
if(scheme==settings.schemes.end()) return;
auto name=scheme->name;
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(608),dialog,schemeNameDialog,
reinterpret_cast<LPARAM>(&name))!=IDOK || name==scheme->name) return;
if(reservedTextSchemeName(name) || std::ranges::any_of(settings.schemes,[&](const auto &candidate)
{return &candidate!=&*scheme && sameSchemeName(name,candidate.name.c_str());}))
{
showFilesNotice(dialog,L"Choose a unique name for the color scheme.",L"Rename color scheme");
return;
}
for(auto &document:settings.profiles)
if(sameSchemeName(document.scheme,scheme->name.c_str())) document.scheme=name;
for(auto &role:settings.systemThemes)
if(sameSchemeName(role,scheme->name.c_str())) role=name;
scheme->name=std::move(name);
populateTextSchemes(dialog,settings);
}
void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,bool edit)
{
const auto profile=ks::files::resolvedTextProfile(settings,edit);
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);
const auto selected=currentTextScheme(settings,profile);
SendDlgItemMessageW(dialog,textTheme,CB_SETCURSEL,selected,0);
EnableWindow(GetDlgItem(dialog,textRenameScheme),selected>=std::size(ks::files::textPalettes)+2);
refreshTextColor(dialog,profile);
}
@@ -378,12 +442,20 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
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==textSaveScheme) saveTextSchemeDraft(dialog,draft.text,draft.page==TextEditor);
else if(id==textRenameScheme) renameTextSchemeDraft(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());
{
auto palette=ks::files::resolvedTextProfile(draft.text,draft.page==TextEditor).colors;
if(choosePanelColor(dialog,palette[index],draft.custom.data()))
{
profile.colors=palette;
profile.scheme.clear();
}
}
}
else if(HIWORD(command)==CBN_SELCHANGE)
{
@@ -395,15 +467,20 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
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();
if(selected==0)
{
profile.colors=ks::files::resolvedTextProfile(draft.text,draft.page==TextEditor).colors;
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 if(scheme==std::size(ks::files::textPalettes)) profile.scheme=ks::files::systemTextScheme;
else
{
const auto index=scheme-std::size(ks::files::textPalettes);
const auto index=scheme-std::size(ks::files::textPalettes)-1;
if(index>=draft.text.schemes.size()) return false;
profile.scheme=draft.text.schemes[index].name;
profile.colors=draft.text.schemes[index].colors;
@@ -413,7 +490,7 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command)
}
}
else return false;
showTextOptions(dialog,draft.text,profile);
showTextOptions(dialog,draft.text,draft.page==TextEditor);
updateOptionsApply(dialog,draft);
return true;
}
@@ -432,6 +509,65 @@ void showComparisonOptions(HWND dialog,const ComparisonAppearance &appearance)
SetDlgItemTextW(dialog,comparisonColorValue,hex);
}
std::optional<AppearanceArea> optionsScaleArea(int page,int section)
{
if(page==Appearance && section==Font) return AppearanceArea::panels;
if(page==CommandLine && section==terminalScaleSection) return AppearanceArea::terminal;
if(page==TextViewer) return section==markdownSection?AppearanceArea::markdown:AppearanceArea::viewer;
if(page==TextEditor) return AppearanceArea::editor;
if(page==CompareFiles) return AppearanceArea::comparison;
return {};
}
void showAreaScale(HWND dialog,const OptionsDraft &draft,std::optional<AppearanceArea> area)
{
const auto label=GetDlgItem(dialog,areaScaleLabel);
const auto field=GetDlgItem(dialog,areaScaleControl);
ShowWindow(label,area?SW_SHOW:SW_HIDE);
ShowWindow(field,area?SW_SHOW:SW_HIDE);
if(!area) return;
const auto index=ks::files::appearanceIndex(*area);
constexpr const wchar_t *labels[]{L"&Panel scale",L"&Viewer scale",L"&Editor scale",L"&Markdown scale",
L"&Terminal scale",L"&Comparison scale"};
constexpr int top[]{77,232,232,124,29,155};
SetWindowTextW(label,labels[index]);
RECT labelBox{131,top[index]+3,0,0},fieldBox{257,top[index],0,0};
MapDialogRect(dialog,&labelBox);
MapDialogRect(dialog,&fieldBox);
const auto flags=SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE;
SetWindowPos(label,nullptr,labelBox.left,labelBox.top,0,0,flags);
SetWindowPos(field,nullptr,fieldBox.left,fieldBox.top,0,0,flags);
SendMessageW(field,CB_RESETCONTENT,0,0);
const auto selected=draft.scales[index];
for(unsigned percent=ks::files::minAppearanceScale;percent<=ks::files::maxAppearanceScale;++percent)
{
if(percent%5 && percent!=selected) continue;
const auto caption=std::to_wstring(percent)+L"%";
const auto row=SendMessageW(field,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(caption.c_str()));
if(row<0) continue;
SendMessageW(field,CB_SETITEMDATA,row,percent);
if(percent==selected) SendMessageW(field,CB_SETCURSEL,row,0);
}
}
void showSystemThemeRoles(HWND dialog,const ks::files::TextSettings &settings)
{
constexpr int controls[]{systemLightChoice,systemDarkChoice};
for(size_t role=0;role<std::size(controls);++role)
{
const auto control=GetDlgItem(dialog,controls[role]);
SendMessageW(control,CB_RESETCONTENT,0,0);
const auto add=[&](const wchar_t *name)
{
const auto row=SendMessageW(control,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
if(row>=0 && sameSchemeName(settings.systemThemes[role],name))
SendMessageW(control,CB_SETCURSEL,row,0);
};
for(const auto name:ks::files::textPaletteNames) add(name);
for(const auto &scheme:settings.schemes) add(scheme.name.c_str());
}
}
void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
{
draft.page=page;
@@ -446,7 +582,8 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
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";
page==CommandLine?(section==terminalScaleSection?L"Terminal appearance":L"Command history"):
section==SystemThemes?L"System themes":section==DialogFrame?L"Dialog frame":L"Font";
}
SetDlgItemTextW(dialog,optionsTitle,title);
const auto show=[&](auto &controls,bool visible)
@@ -474,6 +611,9 @@ 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(systemThemeControls,page==Appearance && section==SystemThemes);
if(page==Appearance && section==SystemThemes) showSystemThemeRoles(dialog,draft.text);
showAreaScale(dialog,draft,optionsScaleArea(page,section));
show(comparisonControls,page==CompareFiles);
if(page==CompareFiles) showComparisonOptions(dialog,draft.comparison);
show(dialogFrameControls,page==Appearance && section==DialogFrame);
@@ -482,17 +622,19 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
for(const auto &option:frameOptions)
SendDlgItemMessageW(dialog,option.id,CB_SETCURSEL,draft.framePadding.*option.value,0);
}
constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
constexpr int commandLineControls[]{321,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
show(commandLineControls,page==CommandLine && section==0);
show(markdownControls,markdown);
show(textControls,textOptionsPage(page) && !markdown);
ShowWindow(GetDlgItem(dialog,restoreDocumentsControl),page==TextViewer && !markdown?SW_SHOW:SW_HIDE);
show(editingControls,page==TextEditor);
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]);
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,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);
const auto preview=GetDlgItem(dialog,fileStylePreview);
ShowWindow(preview,page>=0 && page<CommandLine && section>=0?SW_SHOW:SW_HIDE);
const bool panelPreview=page>=0 && page<CommandLine && section>=0 && !(page==Appearance && section==SystemThemes);
ShowWindow(preview,panelPreview?SW_SHOW:SW_HIDE);
layoutOptionsPreview(dialog);
RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
show(colorOptionControls,page==PanelColors && section>=0 && !fileTypes);
@@ -585,27 +727,35 @@ 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") || 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==CommandLine)
{
addSection(L"Command history",0,matches(L"Previous command") || matches(L"Keyboard shortcuts") ||
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"));
addSection(L"Terminal appearance",terminalScaleSection,matches(L"Terminal scale"));
}
else if(page==CompareFiles)
addSection(L"Font and colors",0,matches(L"Compare files shortcut") || std::any_of(std::begin(comparisonColorNames),
addSection(L"Font and colors",0,matches(L"Comparison scale") || matches(L"Compare files shortcut") || matches(L"Keyboard shortcuts") || 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") ||
matches(L"Color scheme") || matches(L"Save scheme") || matches(L"Rename scheme") || matches(L"Customize colors") ||
matches(page==TextEditor?L"Editor scale":L"Viewer scale") ||
(page==TextEditor && matches(L"Line endings for new lines")) ||
(page==TextViewer && matches(L"Restore local Viewer and Editor windows after restart")) ||
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"));
matches(L"Maximum width") || matches(L"Full window") || matches(L"Font family") || matches(L"Font size") ||
matches(L"Markdown scale"));
}
else
{
addSection(L"Font",Font,matches(L"Display font"));
addSection(L"Font",Font,matches(L"Display font") || matches(L"Panel scale"));
addSection(L"System themes",SystemThemes,matches(L"Light mode palette") || matches(L"Dark mode palette"));
addSection(L"Dialog frame",DialogFrame,
matches(L"Outer padding") || matches(L"Inner padding") || matches(L"Row text padding"));
}
@@ -616,6 +766,8 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
if(!first) SetDlgItemTextW(dialog,optionsTitle,L"No matching settings");
}
#include "files_options_transfer.inl"
INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
@@ -636,6 +788,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
SetDlgItemInt(dialog,201,sizeWidth,FALSE);
SendDlgItemMessageW(dialog,201,EM_SETLIMITTEXT,2,0);
for(const auto id:{273,274})
for(const auto mode:panelModeNames)
SendDlgItemMessageW(dialog,id,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(mode));
SendDlgItemMessageW(dialog,markdownWidth,EM_SETLIMITTEXT,6,0);
SendDlgItemMessageW(dialog,markdownSize,EM_SETLIMITTEXT,2,0);
SendDlgItemMessageW(dialog,markdownFamily,EM_SETLIMITTEXT,LF_FACESIZE-1,0);
@@ -643,8 +798,6 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
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)
@@ -661,10 +814,12 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
CheckDlgButton(dialog,273,panels[0].wide);
CheckDlgButton(dialog,274,panels[1].wide);
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments);
showPanelModeOptions(dialog);
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());
@@ -722,6 +877,29 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
case optionsSearch:
if(HIWORD(wp)==EN_CHANGE) filterOptions(dialog,*draft);
return TRUE;
case areaScaleControl:
if(HIWORD(wp)==CBN_SELCHANGE)
if(const auto area=optionsScaleArea(draft->page,draft->section))
{
const auto row=SendDlgItemMessageW(dialog,areaScaleControl,CB_GETCURSEL,0,0);
if(row>=0)
{
const auto percent=SendDlgItemMessageW(dialog,areaScaleControl,CB_GETITEMDATA,row,0);
if(percent>=ks::files::minAppearanceScale && percent<=ks::files::maxAppearanceScale)
draft->scales[ks::files::appearanceIndex(*area)]=static_cast<unsigned>(percent);
}
updateOptionsApply(dialog,*draft);
}
return TRUE;
case systemLightChoice: case systemDarkChoice:
if(HIWORD(wp)==CBN_SELCHANGE)
{
wchar_t name[ks::files::maxTextPaletteName+1]{};
GetDlgItemTextW(dialog,LOWORD(wp),name,std::size(name));
if(ks::files::namedTextPalette(draft->text,name)) draft->text.systemThemes[LOWORD(wp)==systemDarkChoice]=name;
updateOptionsApply(dialog,*draft);
}
return TRUE;
case 279:
if(draft->page==PanelColors && draft->section>=0 && draft->section<ColorCount)
{
@@ -829,14 +1007,15 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
return TRUE;
case optionsReset:
if(draft->page==allOptions) draft->scales=ks::files::defaultAppearanceScales;
else if(const auto area=optionsScaleArea(draft->page,draft->section))
draft->scales[ks::files::appearanceIndex(*area)]=100;
if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==SystemThemes)))
draft->text.systemThemes=ks::files::TextSettings{}.systemThemes;
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);
@@ -851,13 +1030,15 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(draft->page==allOptions || (draft->page==PanelColors &&
(draft->section<0 || draft->section==fileStyleSection)))
draft->styles=defaultFileStyles;
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=DialogFrame))
if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==Font)))
{
draft->font=defaultFilesFont();
draft->points=defaultFontPoints;
}
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=Font))
if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==DialogFrame)))
draft->framePadding=defaultDialogFramePadding;
if(draft->page==allOptions || (draft->page==TextViewer && draft->section!=markdownSection))
CheckDlgButton(dialog,restoreDocumentsControl,BST_UNCHECKED);
if(draft->page==allOptions || textOptionsPage(draft->page))
for(int page=TextViewer;page<=TextEditor;++page)
if(draft->page==allOptions || (draft->page==page && draft->section!=markdownSection))
@@ -881,25 +1062,21 @@ 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 optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
case 273: case 274: case rightClickMarksControl: case driveButtonsControl: case compactLayoutControl:
case restoreDocumentsControl:
case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
updateOptionsApply(dialog,*draft);
return TRUE;
case 321: case 323: case comparisonShortcutControl:
case 321: case comparisonKeySchemesButton:
editFilesKeySchemes(dialog,LOWORD(wp)==321?FilesKey::Previous:FilesKey::Compare,&draft->keySettings);
updateOptionsApply(dialog,*draft);
return TRUE;
case optionsImport: case optionsExport:
transferFilesOptions(dialog,*draft,LOWORD(wp)==optionsImport);
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"");
@@ -927,6 +1104,14 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
}
const auto &base=draft->baseline;
const bool keysChanged=draft->keySettings!=base.keySettings;
loadFilesKeySettings();
if(keysChanged && filesKeySettings!=base.keySettings && filesKeySettings!=draft->keySettings)
{
showFilesNotice(dialog,L"Keyboard schemes changed in another window. Reopen Options before editing them again.",
L"Keyboard shortcuts");
return TRUE;
}
const auto storedComparison=readComparisonAppearance();
const bool comparisonChanged=draft->comparison!=base.comparison;
if(comparisonChanged && storedComparison!=base.comparison && storedComparison!=draft->comparison)
@@ -936,7 +1121,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
}
const bool textChanged=draft->text!=base.text;
auto textSettings=ks::files::loadTextPreferences();
const auto storedText=ks::files::loadTextPreferences();
auto textSettings=storedText;
if(draft->text.markdown!=base.text.markdown)
{
if(textSettings.markdown!=base.text.markdown && textSettings.markdown!=draft->text.markdown)
@@ -968,14 +1154,15 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
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))
if(draft->text.systemThemes!=base.text.systemThemes)
{
showFilesNotice(dialog,L"Choose distinct shortcuts using Ctrl or Alt that are free in Files.",L"Command history");
return TRUE;
if(textSettings.systemThemes!=base.text.systemThemes && textSettings.systemThemes!=draft->text.systemThemes)
{
showFilesNotice(dialog,L"System theme choices changed in another window. Reopen Options before editing them again.",
L"System themes");
return TRUE;
}
textSettings.systemThemes=draft->text.systemThemes;
}
const bool stylesChanged=draft->styles!=base.styles;
loadFileStyles();
@@ -1017,15 +1204,22 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return TRUE;
}
}
if(keysChanged && !writeFilesJsonPreference(filesKeySchemePreference,serializeFilesKeySettings(draft->keySettings)))
{
if(textChanged)
try {ks::files::saveTextPreferences(storedText);}
catch(const std::exception &) {setStatus(L"Could not restore earlier text settings.",true);}
if(comparisonChanged) saveComparisonAppearance(storedComparison);
if(fontChanged) applyFont(owner,base.font,base.points);
if(stylesChanged) saveFileStyles(fileStyles);
showFilesNotice(dialog,L"Could not save the keyboard schemes.",L"Keyboard shortcuts");
return TRUE;
}
const auto saveChanged=[](const wchar_t *name,DWORD value,DWORD initial)
{
if(value!=initial) savePreference(name,value);
};
const auto checked=[&](int id){return IsDlgButtonChecked(dialog,id)==BST_CHECKED;};
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);
@@ -1033,6 +1227,10 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
saveChanged(L"AlignExtensions",checked(202),base.extensions);
saveChanged(L"AlignFolders",checked(204),base.folders);
saveChanged(L"ShowDetails",checked(203),base.details);
saveChanged(rightClickMarksKey,checked(rightClickMarksControl),base.mouseMarks);
saveChanged(driveButtonsKey,checked(driveButtonsControl),base.drives);
saveChanged(compactLayoutKey,checked(compactLayoutControl),base.compact);
saveChanged(restoreDocumentsKey,checked(restoreDocumentsControl),base.restoreLocal);
DWORD fields=preference(L"StatusFields",defaultStatusFields)&15;
const auto initialFields=fields;
for(int i=0;i<4;++i)
@@ -1046,14 +1244,19 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
saveChanged(dialogFrameOuterKey,draft->framePadding.outer,base.padding.outer);
saveChanged(dialogFrameInnerKey,draft->framePadding.inner,base.padding.inner);
saveChanged(dialogRowTextKey,draft->framePadding.rowText,base.padding.rowText);
for(size_t i=0;i<draft->scales.size();++i) saveChanged(areaScaleKeys[i],draft->scales[i],base.scales[i]);
if(fontChanged)
{
savePreference(L"FontPoints",fontPoints);
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,L"DisplayFont",REG_BINARY,&displayFont,sizeof(displayFont));
}
saveChanged(L"LeftWide",checked(273),base.wide[0]);
saveChanged(L"RightWide",checked(274),base.wide[1]);
for(int index=0;index<2;++index)
{
const auto mode=panelModeOption(dialog,index);
if(mode!=base.modes[index]) savePanelMode(index,mode);
}
loadFilesPreferences(owner);
refreshFilesKeyBar();
notifyFilesPreferences(owner);
const auto dialogOwner=GetWindow(dialog,GW_OWNER);
if(dialogOwner!=owner)
@@ -1061,6 +1264,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
draft->baseline=OptionsBaseline{};
draft->text=draft->baseline.text;
draft->comparison=draft->baseline.comparison;
draft->keySettings=draft->baseline.keySettings;
draft->scales=draft->baseline.scales;
showMarkdownOptions(dialog,draft->text.markdown);
populateTextSchemes(dialog,draft->text);
draft->font=displayFont;
@@ -1072,11 +1277,12 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
CheckDlgButton(dialog,273,panels[0].wide);
CheckDlgButton(dialog,274,panels[1].wide);
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments);
showPanelModeOptions(dialog);
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());
@@ -1094,12 +1300,13 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
return FALSE;
}
void runOptions(HWND owner,int page)
void runOptions(HWND owner,int page,int section=0,bool restoreLocation=true)
{
loadFilesKeySettings();
OptionsDraft draft;
draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER);
const DWORD initial=static_cast<DWORD>((page<<8)|1);
const auto saved=preference(optionsLocationKey,initial);
const DWORD initial=static_cast<DWORD>((page<<8)|(section+1));
const auto saved=restoreLocation?preference(optionsLocationKey,initial):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;
@@ -1116,7 +1323,10 @@ void editOptions(HWND owner)
SetFocus(panels[active].list);
}
void editTextOptions(HWND owner,bool edit)
void editFilesAppearance(HWND owner,AppearanceArea area)
{
runOptions(owner,edit?TextEditor:TextViewer);
constexpr int pages[]{Appearance,TextViewer,TextEditor,TextViewer,CommandLine,CompareFiles};
constexpr int sections[]{Font,0,0,markdownSection,terminalScaleSection,0};
const auto index=ks::files::appearanceIndex(area);
runOptions(owner,pages[index],sections[index],false);
}
+2 -1
View File
@@ -7,7 +7,8 @@ void paintOptionsPreview(HWND dialog,const DRAWITEMSTRUCT &item,const OptionsDra
const auto dpi=GetDpiForWindow(item.hwndItem);
const auto px=[&](int value){return MulDiv(value,dpi,96);};
auto font=draft.font;
font.lfHeight=-MulDiv(draft.points,dpi,720);
const auto panelScale=draft.scales[ks::files::appearanceIndex(AppearanceArea::panels)];
font.lfHeight=-MulDiv(ks::files::scaledAppearanceSize(draft.points,panelScale),dpi,720);
font.lfWidth=0;
const auto previewFont=CreateFontIndirectW(&font);
SelectObject(dc,previewFont?previewFont:mono);
+275
View File
@@ -0,0 +1,275 @@
constexpr struct
{
const char *id;
const wchar_t *label;
int control;
} filesTransferGroups[]{
{"colors",L"&Colors and file styles",621},
{"panels",L"&Panel modes and layout",622},
{"keys",L"&Keyboard schemes",623},
};
constexpr struct
{
const char *id;
int control;
bool OptionsBaseline::*value;
} transferablePanelChecks[]{
{"alignFileExtensions",202,&OptionsBaseline::extensions},
{"alignFolderExtensions",204,&OptionsBaseline::folders},
{"showDetails",203,&OptionsBaseline::details},
{"rightClickMarks",rightClickMarksControl,&OptionsBaseline::mouseMarks},
{"driveButtons",driveButtonsControl,&OptionsBaseline::drives},
{"compactLayout",compactLayoutControl,&OptionsBaseline::compact},
};
struct FilesTransferDraft
{
bool importing{};
Json groups=Json::object();
std::array<bool,std::size(filesTransferGroups)> chosen{};
};
INT_PTR CALLBACK filesTransferDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &draft=*reinterpret_cast<FilesTransferDraft*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
SetWindowTextW(dialog,draft.importing?L"Import Files settings":L"Export Files settings");
SetDlgItemTextW(dialog,624,draft.importing?
L"Choose groups to load into Options. Apply saves the changes.":
L"Choose groups to export from your saved Files settings.");
SetDlgItemTextW(dialog,IDOK,draft.importing?L"&Load":L"&Export");
for(const auto &group:filesTransferGroups)
{
const bool available=draft.groups.contains(group.id);
const auto control=GetDlgItem(dialog,group.control);
SetWindowTextW(control,group.label);
ShowWindow(control,available?SW_SHOW:SW_HIDE);
CheckDlgButton(dialog,group.control,available?BST_CHECKED:BST_UNCHECKED);
}
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND) return FALSE;
auto &draft=*reinterpret_cast<FilesTransferDraft*>(GetWindowLongPtrW(dialog,DWLP_USER));
for(size_t i=0;i<draft.chosen.size();++i)
{
const auto &group=filesTransferGroups[i];
draft.chosen[i]=draft.groups.contains(group.id) && IsDlgButtonChecked(dialog,group.control)==BST_CHECKED;
}
const bool any=std::ranges::any_of(draft.chosen,[](bool chosen){return chosen;});
if(LOWORD(wp)==IDOK && any) FilesModalDialog::finish(dialog,IDOK);
else EnableWindow(GetDlgItem(dialog,IDOK),any);
return TRUE;
}
fs::path chooseFilesTransferPath(HWND owner,bool importing)
{
std::array<wchar_t,32768> file{};
if(!importing) wcscpy_s(file.data(),file.size(),L"KSwitcher.Files.settings.json");
OPENFILENAMEW pick{sizeof(pick)};
pick.hwndOwner=owner;
pick.lpstrTitle=importing?L"Open Files settings JSON":L"Save Files settings JSON";
pick.lpstrFilter=L"JSON files (*.json)\0*.json\0All files (*.*)\0*.*\0";
pick.lpstrFile=file.data();
pick.nMaxFile=static_cast<DWORD>(file.size());
pick.lpstrDefExt=L"json";
pick.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|
(importing?OFN_FILEMUSTEXIST:OFN_OVERWRITEPROMPT);
if(importing?GetOpenFileNameW(&pick):GetSaveFileNameW(&pick)) return file.data();
if(CommDlgExtendedError()) throw std::runtime_error("Could not open the file picker.");
return {};
}
Json exportFilesOptionGroups(const OptionsBaseline &saved)
{
Json colors{{"panels",saved.palette},{"comparison",saved.comparison.palette},{"fileStyles",serializeFileStyles(saved.styles)}};
Json panels{{"leftMode",static_cast<DWORD>(saved.modes[0])},
{"rightMode",static_cast<DWORD>(saved.modes[1])},{"sizeWidth",saved.width},{"statusFields",saved.fields}};
for(const auto &check:transferablePanelChecks) panels[check.id]=saved.*check.value;
return {{"colors",std::move(colors)},{"panels",std::move(panels)},{"keys",serializeFilesKeySettings(saved.keySettings)}};
}
template<typename Palette>
void importFilesColors(const Json &value,Palette &palette)
{
if(!value.is_array()) throw std::runtime_error("Expected an array of colors.");
for(size_t i=0;i<std::min(value.size(),palette.size());++i)
{
if(!value[i].is_number_unsigned() || value[i]>0xffffff)
throw std::runtime_error("A color is outside the RGB range.");
palette[i]=value[i].template get<COLORREF>();
}
}
DWORD importFilesOptionNumber(const Json &value,DWORD minimum,DWORD maximum)
{
if(!value.is_number_unsigned() || value<minimum || value>maximum)
throw std::runtime_error("A panel setting is outside its supported range.");
return value.get<DWORD>();
}
std::optional<FilesKeySettings> mergeImportedFilesKeySchemes(HWND owner,const FilesKeySettings &local,const Json &value)
{
const auto imported=parseFilesKeySettings(value);
if(!imported) throw std::runtime_error("The keyboard schemes contain invalid or conflicting bindings.");
auto result=local;
size_t replacements{};
for(size_t i=0;i<imported->schemes.size();++i)
{
const auto &scheme=imported->schemes[i];
const auto existing=std::ranges::find_if(result.schemes,[&](const auto &candidate)
{ return sameFilesKeySchemeName(candidate.name,scheme.name); });
const auto position=static_cast<size_t>(existing-result.schemes.begin());
if(i==imported->active) result.active=position;
if(existing==result.schemes.end()) result.schemes.push_back(scheme);
else if(existing->keys!=scheme.keys)
{
++replacements;
auto name=existing->name;
*existing=scheme;
existing->name=std::move(name);
}
}
if(result.schemes.size()>filesKeySchemeLimit)
throw std::runtime_error("The imported keyboard schemes exceed the number Files can store.");
if(replacements)
{
const auto prompt=L"Replace "+std::to_wstring(replacements)+
(replacements==1?L" keyboard scheme with the same name?":L" keyboard schemes with the same names?");
if(showFilesNotice(owner,prompt.c_str(),L"Import Files settings",
{.confirm=true,.accept=L"&Replace"})!=IDYES) return {};
}
return result;
}
void stageImportedFilesOptions(HWND dialog,OptionsDraft &draft,const Json &groups)
{
auto palette=draft.palette;
auto comparison=draft.comparison.palette;
auto styles=draft.styles;
auto options=OptionsBaseline{};
options.modes={panelModeOption(dialog,0),panelModeOption(dialog,1)};
options.width=GetDlgItemInt(dialog,201,nullptr,FALSE);
options.fields=0;
for(int i=0;i<4;++i)
if(IsDlgButtonChecked(dialog,205+i)==BST_CHECKED) options.fields|=1u<<i;
for(const auto &check:transferablePanelChecks)
options.*check.value=IsDlgButtonChecked(dialog,check.control)==BST_CHECKED;
const auto colorGroup=groups.find("colors");
if(colorGroup!=groups.end())
{
if(!colorGroup->is_object()) throw std::runtime_error("Invalid colors group.");
if(colorGroup->contains("panels")) importFilesColors(colorGroup->at("panels"),palette);
if(colorGroup->contains("comparison")) importFilesColors(colorGroup->at("comparison"),comparison);
if(colorGroup->contains("fileStyles"))
{
auto parsed=parseFileStyles(colorGroup->at("fileStyles"));
if(!parsed) throw std::runtime_error("Invalid file styles.");
styles=std::move(*parsed);
}
}
const auto panelGroup=groups.find("panels");
if(panelGroup!=groups.end())
{
if(!panelGroup->is_object()) throw std::runtime_error("Invalid panel modes and layout group.");
for(const auto &check:transferablePanelChecks)
if(panelGroup->contains(check.id)) options.*check.value=panelGroup->at(check.id).get<bool>();
constexpr const char *modeKeys[]{"leftMode","rightMode"};
for(size_t i=0;i<options.modes.size();++i)
if(panelGroup->contains(modeKeys[i]))
options.modes[i]=static_cast<PanelMode>(importFilesOptionNumber(
panelGroup->at(modeKeys[i]),0,std::size(panelModeNames)-1));
if(panelGroup->contains("sizeWidth"))
options.width=importFilesOptionNumber(panelGroup->at("sizeWidth"),6,16);
if(panelGroup->contains("statusFields"))
options.fields=importFilesOptionNumber(panelGroup->at("statusFields"),0,15);
}
if(groups.contains("keys"))
{
auto keys=mergeImportedFilesKeySchemes(dialog,draft.keySettings,groups.at("keys"));
if(!keys) return;
draft.keySettings=std::move(*keys);
}
if(colorGroup!=groups.end())
{
draft.palette=palette;
draft.comparison.palette=comparison;
draft.styles=std::move(styles);
}
if(panelGroup!=groups.end())
{
if(panelGroup->contains("sizeWidth")) SetDlgItemInt(dialog,201,options.width,FALSE);
for(int index=0;index<2;++index)
SendDlgItemMessageW(dialog,273+index,CB_SETCURSEL,static_cast<WPARAM>(options.modes[index]),0);
for(const auto &check:transferablePanelChecks)
CheckDlgButton(dialog,check.control,options.*check.value?BST_CHECKED:BST_UNCHECKED);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,options.fields&(1u<<i)?BST_CHECKED:BST_UNCHECKED);
}
if(draft.page==PanelColors && draft.section==fileStyleSection) updateFileStyleEditor(dialog,draft,true);
showOptionsPage(dialog,draft,draft.page,draft.section);
updateOptionsApply(dialog,draft);
}
void transferFilesOptions(HWND dialog,OptionsDraft &options,bool importing)
{
try
{
FilesTransferDraft transfer{.importing=importing};
if(importing)
{
const auto path=chooseFilesTransferPath(dialog,true);
if(path.empty()) return;
const auto data=ks::readFile(path,maxFilesJsonBytes);
const auto document=Json::parse(data,[](int depth,Json::parse_event_t,Json &)
{
if(depth>32) throw std::runtime_error("The JSON contains too many nested levels.");
return true;
});
if(document.value("format",std::string{})!="kswitcher-files-settings" || document.at("version")!=1)
throw std::runtime_error("This Files settings format or version is unsupported.");
const auto &groups=document.at("groups");
if(!groups.is_object()) throw std::runtime_error("The document does not contain settings groups.");
for(const auto &group:filesTransferGroups)
if(groups.contains(group.id)) transfer.groups[group.id]=groups.at(group.id);
if(transfer.groups.empty()) throw std::runtime_error("The file does not contain any supported settings groups.");
}
else transfer.groups=exportFilesOptionGroups(options.baseline);
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(617),dialog,filesTransferDialog,
reinterpret_cast<LPARAM>(&transfer))!=IDOK) return;
for(size_t i=0;i<transfer.chosen.size();++i)
if(!transfer.chosen[i]) transfer.groups.erase(filesTransferGroups[i].id);
if(importing) stageImportedFilesOptions(dialog,options,transfer.groups);
else
{
const auto path=chooseFilesTransferPath(dialog,false);
if(path.empty()) return;
const auto output=Json{{"format","kswitcher-files-settings"},{"version",1},
{"groups",std::move(transfer.groups)}}.dump(2)+"\n";
const auto temporary=ks::files::temporaryPath(path.parent_path());
const bool replace=GetFileAttributesW(path.c_str())!=INVALID_FILE_ATTRIBUTES;
ks::atomicWrite(temporary,ks::Bytes(output.begin(),output.end()));
if(!MoveFileExW(temporary.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH|(replace?MOVEFILE_REPLACE_EXISTING:0)))
{
DeleteFileW(temporary.c_str());
throw std::runtime_error("Could not publish the settings file.");
}
}
}
catch(const Json::exception &)
{
showFilesNotice(dialog,L"The JSON is damaged or contains an invalid value.",L"Files settings");
}
catch(const std::exception &error)
{
const auto message=ks::wide(error.what());
showFilesNotice(dialog,message.c_str(),L"Files settings");
}
}
+78
View File
@@ -0,0 +1,78 @@
constexpr int panelColumnFirst=510,panelColumnAuto=516,panelColumnFooter=517,panelColumnReset=518;
void setColumnControls(HWND dialog,DWORD columns,bool automatic)
{
for(size_t i=1;i<panelColumnCount;++i)
CheckDlgButton(dialog,panelColumnFirst+static_cast<int>(i)-1,columns&(1u<<i)?BST_CHECKED:BST_UNCHECKED);
CheckDlgButton(dialog,panelColumnAuto,automatic?BST_CHECKED:BST_UNCHECKED);
}
struct PanelColumnPrompt
{
ColumnSettings draft;
PanelMode mode;
};
INT_PTR CALLBACK panelColumnsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
const auto &prompt=*reinterpret_cast<const PanelColumnPrompt *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,panelColumnFirst);
for(int id=panelColumnFirst;id<=panelColumnAuto;++id)
installFarCheckbox(GetDlgItem(dialog,id),FarCheckboxSurface::gray);
layoutDialogButtons(dialog,panelColumnFooter,{IDOK,panelColumnReset,IDCANCEL});
setColumnControls(dialog,prompt.draft.visibility,prompt.draft.automatic);
return TRUE;
}
if(message==WM_COMMAND)
{
const auto command=LOWORD(wp);
auto *prompt=reinterpret_cast<PanelColumnPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!prompt) return FALSE;
if(command==panelColumnReset)
{
setColumnControls(dialog,defaultVisibleColumns(prompt->mode),true);
return TRUE;
}
if(command==IDOK)
{
auto &draft=prompt->draft;
draft.visibility=0;
for(size_t i=1;i<panelColumnCount;++i)
if(IsDlgButtonChecked(dialog,panelColumnFirst+static_cast<int>(i)-1)==BST_CHECKED)
draft.visibility|=1u<<i;
draft.automatic=IsDlgButtonChecked(dialog,panelColumnAuto)==BST_CHECKED;
draft.customized=draft.visibility!=defaultVisibleColumns(prompt->mode);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
return paintCopyDialog(dialog,message,wp,lp,L" Panel columns ",false,{panelColumnFooter});
}
void editPanelColumns(HWND owner,Panel &panel)
{
if(!hasPanelColumns(panel) || !panelViewAvailable(panel)) return;
auto &settings=panel.columns[static_cast<size_t>(panel.mode)];
auto draft=settings;
if(!draft.customized) draft.visibility=defaultVisibleColumns(panel.mode);
PanelColumnPrompt prompt{draft,panel.mode};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(119),owner,
panelColumnsDialog,reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
if(prompt.draft.visibility==draft.visibility && prompt.draft.automatic==draft.automatic) return;
settings=prompt.draft;
savePanelColumns(static_cast<int>(&panel-panels),panel.mode);
notifyFilesPreferences(owner);
if((draft.visibility^settings.visibility)&extendedColumnMask) refreshPanelColumnData(panel);
InvalidateRect(panel.heading,nullptr,FALSE);
InvalidateRect(panel.list,nullptr,TRUE);
InvalidateRect(owner,nullptr,FALSE);
}
+49
View File
@@ -0,0 +1,49 @@
std::wstring_view directoryRowName(const fs::path &path)
{
const auto name=std::wstring_view(path.native());
const auto slash=name.find_last_of(L"/\\");
return slash==name.npos?name:name.substr(slash+1);
}
std::wstring_view directoryRowExtension(std::wstring_view name)
{
const auto dot=name.find_last_of(L'.');
return dot==name.npos || dot==0?std::wstring_view{}:name.substr(dot+1);
}
int compareDirectoryText(std::wstring_view left,std::wstring_view right)
{
if(left.empty() || right.empty()) return static_cast<int>(!left.empty())-static_cast<int>(!right.empty());
return CompareStringOrdinal(left.data(),static_cast<int>(left.size()),right.data(),static_cast<int>(right.size()),TRUE)
- CSTR_EQUAL;
}
void orderDirectoryRows(Panel::ScanResult &result,const PanelView &view)
{
auto &rows=result.ordered;
if(view.showHidden && view.mask.empty()) rows.reserve(result.folders.size()+result.files.size());
const auto append=[&](std::vector<fs::path> &paths,bool folder)
{
for(auto &path:paths)
{
const auto &metadata=result.metadata.at(path);
const uint64_t value=view.sort==PanelSort::modified?metadata.modified:
view.sort==PanelSort::size?metadata.size:0;
if(visibleToPanelView(view,path,metadata)) rows.push_back({std::move(path),value,folder});
}
};
append(result.folders,true);
append(result.files,false);
std::sort(rows.begin(),rows.end(),[&](const DirectoryRow &left,const DirectoryRow &right)
{
if(view.foldersFirst && left.folder!=right.folder) return left.folder;
const auto leftName=directoryRowName(left.path), rightName=directoryRowName(right.path);
int order=0;
if(view.sort==PanelSort::extension)
order=compareDirectoryText(directoryRowExtension(leftName),directoryRowExtension(rightName));
else if(left.value!=right.value) order=left.value<right.value?-1:1;
if(!order) order=compareDirectoryText(leftName,rightName);
if(!order) order=leftName.compare(rightName);
return view.descending?order>0:order<0;
});
}
+172
View File
@@ -0,0 +1,172 @@
constexpr std::array<ULONGLONG,3> lanRetryDelays{1200,2500,5000};
constexpr const wchar_t *ftpPanelLocationKeys[]{L"LeftFtpLocation",L"RightFtpLocation"};
constexpr DWORD maxFtpLocationBytes=256*1024;
FilesPeerLookup lookupFilesPeers(HWND owner);
bool transientLanError(DWORD code)
{
switch(code)
{
case WSAENETDOWN:
case WSAENETUNREACH:
case WSAENETRESET:
case WSAECONNABORTED:
case WSAECONNRESET:
case WSAECONNREFUSED:
case WSAETIMEDOUT:
case WSAEHOSTDOWN:
case WSAEHOSTUNREACH:
case ERROR_CONNECTION_ABORTED:
case ERROR_NETNAME_DELETED:
case ERROR_NETWORK_UNREACHABLE:
case ERROR_SEM_TIMEOUT:
return true;
default:
return false;
}
}
bool retryRemotePanel(Panel &panel,bool automatic,const fs::path &fallback)
{
if(!panel.remoteRetry) return false;
auto &retry=*panel.remoteRetry;
auto location=retry.location;
const auto attempt=automatic?retry.reconnectAttempt+1:0;
if(location.peer)
{
const auto lookup=lookupFilesPeers(GetParent(panel.list));
const auto peer=std::find_if(lookup.peers.begin(),lookup.peers.end(),[&](const auto &entry) {
return entry.id==location.peer->id && !entry.address.empty();
});
if(peer!=lookup.peers.end()) location.peer=*peer;
openOn(panel,location.directory,false,std::move(location.peer),location.cursor,
{},{},location.navigationPosition,{},attempt);
return true;
}
const bool loaded=loadTransferProfiles(location.protocol);
const auto *profile=loaded?findTransferProfile(location.ftpProfile,location.protocol):nullptr;
if(!profile)
{
retry.failure=std::wstring(loaded?L"The saved connection is missing. Select a profile in Change drive → ":
L"Could not load the saved connections for ")+transferProtocolName(location.protocol)+L".";
if(&panel==&panels[active] && !panel.scan.valid()) showFileDetails(panel);
return true;
}
openOn(panel,location.directory,false,{},location.cursor,fallback,*profile,location.navigationPosition,{},0,
fallback.empty()?fs::path{}:savedPanelPath(panelCursorKeys[&panel-panels]));
return true;
}
void openFolderLocation(Panel &panel,const FolderLocation &location,std::optional<size_t> position={},fs::path selection={})
{
if(location.directory.empty()) return;
if(location.provider==FolderProvider::local)
{
openOn(panel,location.directory,true,{},std::move(selection),{},{},position);
return;
}
if(location.sameSource(folderLocation(panel,panel.directory)))
{
openOn(panel,location.directory,false,panel.peer,std::move(selection),{},panel.ftp,position);
return;
}
RemotePanelLocation remote{location.directory,std::move(selection),{},{},position};
if(isTransferFolder(location.provider))
{
remote.ftpProfile=location.id;
remote.protocol=folderTransferProtocol(location.provider);
}
else remote.peer=FilesPeer{location.id,{},location.label.empty()?L"LAN peer":location.label};
panel.remoteRetry=Panel::RemoteRetry{std::move(remote),L"Could not restore the remote folder."};
retryRemotePanel(panel);
}
void pollRemotePanels()
{
const auto now=GetTickCount64();
for(auto &panel:panels)
if(!panel.scan.valid() && panel.remoteRetry && panel.remoteRetry->retryAt &&
now>=panel.remoteRetry->retryAt)
retryRemotePanel(panel,true);
}
std::optional<RemotePanelLocation> savedFtpPanelLocation(int index)
{
DWORD size{};
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpPanelLocationKeys[index],RRF_RT_REG_BINARY,nullptr,
nullptr,&size)!=ERROR_SUCCESS || !size || size>maxFtpLocationBytes) return {};
std::string data(size,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpPanelLocationKeys[index],RRF_RT_REG_BINARY,nullptr,
data.data(),&size)!=ERROR_SUCCESS) return {};
try
{
const auto saved=Json::parse(data.begin(),data.begin()+size);
RemotePanelLocation location{fs::path(ks::wide(saved.at("directory"))),fs::path(ks::wide(saved.at("cursor"))),
saved.at("profile").get<std::string>()};
if(!isFtpFolderPath(location.directory) || location.ftpProfile.empty()) return {};
if(!location.cursor.empty() && !isFtpFolderPath(location.cursor)) location.cursor.clear();
return location;
}
catch(const std::exception &) {return {};}
}
void saveFtpPanelLocation(const Panel &panel,int index)
{
RemotePanelLocation location;
if(panel.ftp && panel.ftp->protocol==TransferProtocol::ftp && !panel.ftp->id.empty())
{
const auto row=currentPanelRow(panel);
location={panel.directory,row<0?fs::path{}:panel.rows[row],panel.ftp->id};
}
else if(panel.remoteRetry && panel.remoteRetry->location.protocol==TransferProtocol::ftp &&
!panel.remoteRetry->location.ftpProfile.empty())
location=panel.remoteRetry->location;
else if(panel.scanRequest && panel.scanRequest->ftp && panel.scanRequest->ftp->protocol==TransferProtocol::ftp)
location={panel.scanRequest->directory,panel.scanRequest->selection,panel.scanRequest->ftp->id};
else if(panel.listing && !panel.navigation.history.empty())
{
const auto &previous=panel.navigation.history[panel.navigation.current];
if(previous.provider==FolderProvider::ftp)
location={previous.directory,panel.listing->returnSelection,previous.id};
}
const auto key=ftpPanelLocationKeys[index];
if(location.ftpProfile.empty() || !isFtpFolderPath(location.directory))
{
RegDeleteKeyValueW(HKEY_CURRENT_USER,schemeKey,key);
return;
}
try
{
const auto data=Json{{"profile",location.ftpProfile},{"directory",ks::utf8(location.directory.native())},
{"cursor",ks::utf8(location.cursor.native())}}.dump();
if(data.size()<=maxFtpLocationBytes)
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,key,REG_BINARY,data.data(),static_cast<DWORD>(data.size()));
}
catch(const std::exception &) {}
}
fs::path systemPanelRoot()
{
wchar_t system[MAX_PATH]{};
GetWindowsDirectoryW(system,MAX_PATH);
return fs::path(system).root_path();
}
void restorePanelLocation(Panel &panel,int index)
{
const auto root=systemPanelRoot();
const auto saved=savedPanelPath(panelPathKeys[index]);
const auto local=saved.is_absolute()?saved:root;
auto remote=savedFtpPanelLocation(index);
if(remote)
{
panel.remoteRetry=Panel::RemoteRetry{std::move(*remote),L"Could not restore the saved FTP folder."};
retryRemotePanel(panel,false,local);
if(panel.scan.valid()) return;
}
auto retry=std::move(panel.remoteRetry);
openOn(panel,local,false,{},savedPanelPath(panelCursorKeys[index]),local!=root?root:fs::path{});
panel.remoteRetry=std::move(retry);
}
+130
View File
@@ -0,0 +1,130 @@
class PanelRowsUpdate
{
public:
PanelRowsUpdate(Panel &panel,size_t count) : panel(panel),visible(IsWindowVisible(panel.list)),
locationList(panelListsLocations(panel))
{
if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0);
panel.rows.clear();
panel.sizes.clear();
panel.dimmed.clear();
panel.marked.clear();
panel.fileExtensionLength=panel.folderExtensionLength=0;
panel.longestColumn.fill(0);
panel.rows.reserve(count);
panel.sizes.reserve(count);
panel.dimmed.reserve(count);
panel.marked.reserve(count);
SendMessageW(panel.list,LB_RESETCONTENT,0,0);
SendMessageW(panel.list,LB_INITSTORAGE,count,0);
}
~PanelRowsUpdate() {finish();}
bool add(const fs::path &path,const std::wstring &label,bool folder,bool marked,bool up=false)
{
if(SendMessageW(panel.list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()))<0) return false;
panel.rows.push_back(path);
if(!up)
{
const auto extension=path.extension().native();
auto &longest=folder?panel.folderExtensionLength:panel.fileExtensionLength;
if(extension.size()>1) longest=std::max(longest,extension.size()-1);
}
panel.marked.push_back(!up && marked);
const auto found=panel.metadata.find(path);
const auto entry=up || locationList || found==panel.metadata.end()?FolderEntryMetadata{}:found->second;
panel.dimmed.push_back((entry.attributes&(FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))!=0);
panel.sizes.push_back(up?L"Up":locationList?L"":folder?L"Folder":std::to_wstring(entry.size));
if(!up && !locationList)
{
auto &longest=panel.longestColumn;
longest[sizeColumn]=std::max(longest[sizeColumn],panel.sizes.back().size());
if(const auto extra=panel.columnMetadata.find(path);extra!=panel.columnMetadata.end())
{
longest[ownerColumn]=std::max(longest[ownerColumn],extra->second.owner.size());
if(extra->second.links)
longest[linkColumn]=std::max(longest[linkColumn],std::to_wstring(*extra->second.links).size());
if(extra->second.allocated)
longest[allocationColumn]=std::max(longest[allocationColumn],std::to_wstring(*extra->second.allocated).size());
}
}
return true;
}
void finish()
{
if(visible)
{
SendMessageW(panel.list,WM_SETREDRAW,TRUE,0);
visible=false;
}
}
private:
Panel &panel;
bool visible,locationList;
};
bool treePanelActive(const Panel &panel)
{
return panel.view.tree && !panel.findOrigin && !panel.tree.root.empty();
}
void markPanelRow(Panel &panel,size_t row,bool mark)
{
if(row>=panel.rows.size() || panel.sizes[row]==L"Up") return;
panel.marked[row]=mark;
if(!treePanelActive(panel)) return;
const auto &path=panel.rows[row];
if(mark) panel.tree.marks.insert(path);
else panel.tree.marks.erase(path);
}
const FolderEntryMetadata *treePanelEntry(const Panel &panel,const fs::path &path)
{
const auto branch=panel.tree.branches.find(path.parent_path());
if(branch==panel.tree.branches.end()) return nullptr;
const auto item=branch->second.metadata.find(path);
return item==branch->second.metadata.end()?nullptr:&item->second;
}
bool matchesFileMask(std::wstring_view name,std::wstring_view mask);
bool visibleToPanelView(const PanelView &view,const fs::path &path,const FolderEntryMetadata &metadata)
{
if(path==view.revealedFile) return true;
return (view.showHidden || !(metadata.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM))) &&
((metadata.attributes&FILE_ATTRIBUTE_DIRECTORY) || view.mask.empty() ||
matchesFileMask(path.filename().native(),view.mask));
}
template<class Visitor>
void visitPanelMarks(const Panel &panel,const Visitor &visit)
{
if(treePanelActive(panel))
{
for(const auto &path:panel.tree.marks)
{
const auto entry=treePanelEntry(panel,path);
if(!entry || !visibleToPanelView(panel.view,path,*entry)) continue;
auto directory=path.parent_path();
while(directory!=panel.tree.root)
{
const auto parent=treePanelEntry(panel,directory);
const auto ancestor=directory.parent_path();
if(!parent || ancestor==directory || !visibleToPanelView(panel.view,directory,*parent)) break;
directory=ancestor;
}
if(directory==panel.tree.root) visit(path,*entry);
}
return;
}
if(panelListsLocations(panel)) return;
for(size_t i=0;i<panel.rows.size();++i)
{
if(!panel.marked[i] || panel.sizes[i]==L"Up") continue;
if(const auto item=panel.metadata.find(panel.rows[i]);item!=panel.metadata.end())
visit(item->first,item->second);
}
}
+234
View File
@@ -0,0 +1,234 @@
void stopTreeBranches(Panel &panel)
{
for(auto &[path,branch]:panel.tree.branches) branch.stop.request_stop();
panel.tree={};
}
bool canExpandTreeEntry(const FolderEntryMetadata &entry)
{
return (entry.attributes&FILE_ATTRIBUTE_DIRECTORY) && !(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT);
}
void startPendingTreeScans(Panel &panel)
{
if(!treePanelActive(panel)) return;
auto running=std::count_if(panel.tree.branches.begin(),panel.tree.branches.end(),
[](const auto &item){return item.second.scan.valid();});
for(auto &[path,branch]:panel.tree.branches)
{
if(running>=2) break;
if(!branch.expanded || !branch.needsScan || branch.scan.valid() || path==panel.tree.root) continue;
branch.needsScan=false;
const auto entry=treePanelEntry(panel,path);
if(!entry || !canExpandTreeEntry(*entry)) continue;
branch.stop=std::stop_source{};
Panel::ScanRequest request{.directory=path,.peer=panel.peer,.ftp=panel.ftp};
try
{
branch.scan=scanDirectoryInBackground(GetParent(panel.list),std::move(request),panel.view,
effectivePanelColumns(panel)&extendedColumnMask,std::make_shared<std::atomic_size_t>(0),branch.stop.get_token());
++running;
}
catch(const std::exception &) {branch.failed=true;}
}
}
void refreshTreeBranches(Panel &panel)
{
if(!treePanelActive(panel)) return;
for(auto &[path,branch]:panel.tree.branches)
if(branch.expanded && path!=panel.tree.root) branch.needsScan=true;
startPendingTreeScans(panel);
}
void replaceTreeRoot(Panel &panel,Panel::ScanResult &scan,bool sameDirectory,const std::set<fs::path> &marks)
{
auto directory=folderPathWithoutSeparator(panel.directory);
if(!sameDirectory || panel.tree.root!=directory) stopTreeBranches(panel);
panel.tree.root=std::move(directory);
auto &root=panel.tree.branches[panel.tree.root];
root.expanded=root.loaded=true;
root.ordered=std::move(scan.ordered);
root.metadata=std::move(scan.metadata);
root.columnMetadata=std::move(scan.columnMetadata);
panel.tree.marks.insert(marks.begin(),marks.end());
if(scan.error!=ERROR_CANCELLED)
std::erase_if(panel.tree.marks,[&](const auto &path) {
return path.parent_path()==panel.tree.root && !root.metadata.contains(path);
});
refreshTreeBranches(panel);
}
void pruneTreeMarks(Panel &panel,const std::set<fs::path> &removed)
{
if(!treePanelActive(panel) || removed.empty()) return;
std::erase_if(panel.tree.marks,[&](auto path) {
for(;path!=panel.tree.root && path!=path.parent_path();path=path.parent_path())
if(removed.contains(path)) return true;
return false;
});
}
std::wstring treeRowPrefix(const Panel &panel,const fs::path &path,bool folder)
{
const auto depth=panel.tree.depths.find(path);
if(depth==panel.tree.depths.end()) return {};
std::wstring prefix(2*std::min<size_t>(depth->second,40),L' ');
if(!folder) return prefix+L" ";
const auto branch=panel.tree.branches.find(path);
if(branch!=panel.tree.branches.end())
{
if(branch->second.scan.valid() || branch->second.needsScan) return prefix+L"… ";
if(branch->second.expanded) return prefix+(branch->second.failed?L"! ":L"▾ ");
}
if(const auto entry=treePanelEntry(panel,path);entry && canExpandTreeEntry(*entry)) return prefix+L"▸ ";
return prefix+L" ";
}
void appendTreeRows(Panel &panel,PanelRowsUpdate &rows)
{
panel.tree.depths.clear();
panel.metadata.clear();
panel.columnMetadata.clear();
struct BranchRows {const Panel::TreeBranch *branch; size_t next;};
std::vector<BranchRows> stack{{&panel.tree.branches.at(panel.tree.root),0}};
while(!stack.empty())
{
auto &current=stack.back();
if(current.next==current.branch->ordered.size())
{
stack.pop_back();
continue;
}
const auto &entry=current.branch->ordered[current.next++];
const auto &path=entry.path;
panel.tree.depths.emplace(path,stack.size()-1);
const auto metadata=current.branch->metadata.find(path);
if(metadata==current.branch->metadata.end() || !visibleToPanelView(panel.view,path,metadata->second)) continue;
panel.metadata.emplace(path,metadata->second);
if(const auto extra=current.branch->columnMetadata.find(path);extra!=current.branch->columnMetadata.end())
panel.columnMetadata.emplace(path,extra->second);
const auto label=treeRowPrefix(panel,path,entry.folder)+path.filename().native();
rows.add(path,label,entry.folder,panel.tree.marks.contains(path));
const auto child=panel.tree.branches.find(path);
if(entry.folder && child!=panel.tree.branches.end() && child->second.expanded && child->second.loaded)
stack.push_back({&child->second,0});
}
}
void redrawTreeRows(Panel &panel)
{
if(!treePanelActive(panel)) return;
const auto current=SendMessageW(panel.list,LB_GETCURSEL,0,0);
const auto top=SendMessageW(panel.list,LB_GETTOPINDEX,0,0);
auto selected=current>=0 && static_cast<size_t>(current)<panel.rows.size()?panel.rows[current]:fs::path{};
const auto parent=panelParentPath(panel.directory,!panel.peer && !panel.ftp);
PanelRowsUpdate rows(panel,panel.rows.size());
if(!parent.empty()) rows.add(parent,L"..",true,false,true);
appendTreeRows(panel,rows);
auto position=std::find(panel.rows.begin(),panel.rows.end(),selected);
while(position==panel.rows.end() && !selected.empty() && selected!=panel.tree.root)
{
const auto next=selected.parent_path();
if(next==selected) break;
selected=next;
position=std::find(panel.rows.begin(),panel.rows.end(),selected);
}
if(!panel.rows.empty())
{
SendMessageW(panel.list,LB_SETTOPINDEX,top,0);
SendMessageW(panel.list,LB_SETCURSEL,position==panel.rows.end()?
std::clamp<LRESULT>(current,0,panel.rows.size()-1):position-panel.rows.begin(),0);
}
rows.finish();
InvalidateRect(panel.list,nullptr,FALSE);
InvalidateRect(panel.heading,nullptr,FALSE);
updateSelectionSummary(panel);
refreshQuickView(panel);
}
void collectTreeBranches()
{
for(auto &panel:panels)
{
if(!treePanelActive(panel)) continue;
bool updated=false;
for(auto &[path,branch]:panel.tree.branches)
{
if(!branch.scan.valid() || branch.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready) continue;
updated=true;
try
{
auto scan=branch.scan.get();
const auto error=scan->error;
branch.failed=!scan->opened || !scan->failure.empty() ||
(error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND);
if(scan->opened && scan->failure.empty())
{
branch.loaded=true;
branch.ordered=std::move(scan->ordered);
branch.metadata=std::move(scan->metadata);
branch.columnMetadata=std::move(scan->columnMetadata);
if(!branch.failed) std::erase_if(panel.tree.marks,[&](const auto &marked) {
return marked.parent_path()==path && !branch.metadata.contains(marked);
});
}
}
catch(const std::exception &) {branch.failed=true;}
if(branch.failed && &panel==&panels[active] && branch.expanded)
setStatus(L"Could not read tree folder: "+path.native());
}
if(updated)
{
startPendingTreeScans(panel);
redrawTreeRows(panel);
queueAutomaticPanelSizes(panel);
}
}
}
bool toggleTreeRow(Panel &panel,size_t row,std::optional<bool> expanded={})
{
if(!treePanelActive(panel) || row>=panel.rows.size() || panel.sizes[row]!=L"Folder") return false;
const auto path=panel.rows[row];
const auto entry=treePanelEntry(panel,path);
if(!entry || !canExpandTreeEntry(*entry)) return false;
auto &branch=panel.tree.branches[path];
const auto next=expanded.value_or(!branch.expanded);
if(next==branch.expanded) return false;
branch.expanded=next;
if(next)
{
branch.needsScan=true;
startPendingTreeScans(panel);
}
else branch.needsScan=false;
redrawTreeRows(panel);
if(&panel==&panels[active])
{
if(next && branch.scan.valid()) setStatus(L"Reading tree folder: "+path.native());
else showFileDetails(panel);
}
return true;
}
bool moveTreeCursor(Panel &panel,bool forward)
{
if(!treePanelActive(panel)) return false;
const auto position=SendMessageW(panel.list,LB_GETCURSEL,0,0);
if(position<0 || static_cast<size_t>(position)>=panel.rows.size() || panel.sizes[position]==L"Up") return false;
if(toggleTreeRow(panel,static_cast<size_t>(position),forward)) return true;
const auto &path=panel.rows[position];
if(forward)
{
if(static_cast<size_t>(position+1)<panel.rows.size() && panel.rows[position+1].parent_path()==path)
SendMessageW(panel.list,LB_SETCURSEL,position+1,0);
}
else
{
const auto parent=std::find(panel.rows.begin(),panel.rows.end(),path.parent_path());
if(parent!=panel.rows.end()) SendMessageW(panel.list,LB_SETCURSEL,parent-panel.rows.begin(),0);
}
invalidatePanelCursorChange(panel.list,position);
return true;
}
+493
View File
@@ -0,0 +1,493 @@
bool pathNavigationAvailable(const Panel &panel)
{
return !transferProfileList(panel) && !panel.findOrigin && !panel.archive && !panel.directory.empty();
}
enum class PathAction { back, forward, up, edit, source, ancestors, previous, folder };
void navigatePanelPath(Panel &panel,const fs::path &path)
{
if(path.empty()) return;
const auto current=folderLocation(panel,panel.directory);
auto target=folderLocation(panel,path);
if(sameFolderLocation(current,target)) return;
closePanelSearch();
openFolderLocation(panel,target);
}
void navigatePanelHistory(Panel &panel,int direction)
{
if(const auto next=panel.navigation.neighbor(direction))
{
closePanelSearch();
openFolderLocation(panel,panel.navigation.history[*next],next);
}
}
struct PathPart
{
PathAction action{};
std::wstring label;
fs::path target;
std::vector<fs::path> hidden;
RECT rect{};
bool current{}, dim{}, enabled=true;
};
std::wstring pathSegmentLabel(const fs::path &path,FolderProvider provider)
{
if(isTransferFolder(provider) && path==ftpRoot) return L"/";
return panelParentPath(path,provider==FolderProvider::local).empty()?path.native():path.filename().native();
}
LONG segmentWidth(const fs::path &path,FolderProvider provider)
{
return static_cast<LONG>(pathSegmentLabel(path,provider).size()+2)*cellWidth;
}
std::vector<PathPart> panelPathParts(const Panel &panel,RECT bounds)
{
const LONG total=bounds.right-bounds.left;
if(total<=0) return {};
const LONG width=std::max(1L,std::min(2L*cellWidth,total/7));
std::vector<PathPart> parts;
const auto add=[&](PathPart part,LONG length)
{
if(length<=0 || bounds.left>=bounds.right) return;
part.rect={bounds.left,bounds.top,std::min(bounds.right,bounds.left+length),bounds.bottom};
bounds.left=part.rect.right;
parts.push_back(std::move(part));
};
const auto location=folderLocation(panel,panel.directory);
const auto provider=location.provider;
const auto local=provider==FolderProvider::local;
const auto parent=panelParentPath(panel.directory,local);
add({.action=PathAction::back,.label=L"←",.enabled=panel.navigation.neighbor(-1).has_value()},width);
add({.action=PathAction::forward,.label=L"→",.enabled=panel.navigation.neighbor(1).has_value()},width);
add({.action=PathAction::up,.label=L"↑",.target=parent,.enabled=!parent.empty()},width);
add({.action=PathAction::edit,.label=L"✎"},width);
if(!local)
{
const auto available=std::max(1L,(bounds.right-bounds.left)/2);
const auto sourceWidth=std::min(available,static_cast<LONG>(location.label.size()+2)*cellWidth);
add({.action=PathAction::source,.label=location.label},sourceWidth);
}
std::vector<fs::path> ancestors, previous;
for(auto path=parent;!path.empty();path=panelParentPath(path,local)) ancestors.push_back(path);
std::reverse(ancestors.begin(),ancestors.end());
if(inFolderBranch(panel.directory,panel.navigation.previousBranch,provider))
{
for(auto path=panel.navigation.previousBranch;!sameFolderPath(path,panel.directory,provider);
path=panelParentPath(path,local))
previous.push_back(path);
std::reverse(previous.begin(),previous.end());
}
const LONG room=bounds.right-bounds.left;
LONG required=segmentWidth(panel.directory,provider);
for(const auto &path:ancestors) required+=segmentWidth(path,provider);
for(const auto &path:previous) required+=segmentWidth(path,provider);
size_t firstAncestor=0,visiblePrevious=previous.size();
LONG currentWidth=segmentWidth(panel.directory,provider);
if(required>room)
{
const LONG reserved=(!ancestors.empty()?width:0)+(!previous.empty()?width:0);
currentWidth=std::min(currentWidth,std::max(1L,room-reserved));
LONG remaining=room-currentWidth-reserved;
firstAncestor=ancestors.size();
while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1],provider))
remaining-=segmentWidth(ancestors[--firstAncestor],provider);
visiblePrevious=0;
while(visiblePrevious<previous.size() && remaining>=segmentWidth(previous[visiblePrevious],provider))
remaining-=segmentWidth(previous[visiblePrevious++],provider);
}
if(firstAncestor)
add({.action=PathAction::ancestors,.label=L"…",
.hidden={ancestors.begin(),ancestors.begin()+firstAncestor}},width);
for(size_t i=firstAncestor;i<ancestors.size();++i)
add({.action=PathAction::folder,.label=pathSegmentLabel(ancestors[i],provider),.target=ancestors[i]},
segmentWidth(ancestors[i],provider));
add({.action=PathAction::edit,.label=pathSegmentLabel(panel.directory,provider),.current=true},currentWidth);
for(size_t i=0;i<visiblePrevious;++i)
add({.action=PathAction::folder,.label=pathSegmentLabel(previous[i],provider),.target=previous[i],.dim=true},
segmentWidth(previous[i],provider));
if(visiblePrevious<previous.size())
add({.action=PathAction::previous,.label=L"…",
.hidden={previous.begin()+visiblePrevious,previous.end()},.dim=true},width);
return parts;
}
void paintPanelPath(HDC dc,RECT bounds,const Panel &panel,bool activePanel)
{
const int saved=SaveDC(dc);
SelectObject(dc,mono);
SetBkMode(dc,TRANSPARENT);
for(const auto &part:panelPathParts(panel,bounds))
{
const bool current=activePanel && part.current;
FillRect(dc,&part.rect,current?teal:blue);
SetTextColor(dc,!part.enabled || part.dim?RGB(160,170,190):colors[current?Text:Frame]);
auto text=part.rect;
DrawTextW(dc,part.label.c_str(),static_cast<int>(part.label.size()),&text,
DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
}
if(saved) RestoreDC(dc,saved);
}
constexpr int addressField=485,addressLabel=486,addressFooter=487;
struct PathPrompt
{
fs::path base, result;
std::optional<FilesPeer> peer;
std::optional<TransferProfile> ftp;
std::wstring completionInput;
std::future<std::wstring> completion;
};
constexpr UINT addressComplete=WM_APP+29;
constexpr UINT_PTR addressCompletionTimer=1;
fs::path enteredPanelPath(const fs::path &base,std::wstring text,bool ftp)
{
if(text.size()>=2 && text.front()==L'"' && text.back()==L'"')
text=text.substr(1,text.size()-2);
if(ftp && text.find_first_of(L":\r\n")!=text.npos) return {};
auto path=fs::path(std::move(text));
if(ftp)
{
if(path.has_root_name()) return {};
return (path.has_root_directory()?path:base/path).lexically_normal();
}
return path.is_absolute()?path:base/path;
}
std::wstring panelPathCompletion(const fs::path &base,const std::wstring &text,
const std::optional<FilesPeer> &peer,const std::optional<TransferProfile> &ftp)
{
const auto path=enteredPanelPath(base,text,ftp.has_value());
if(path.empty()) return {};
const auto directory=path.has_filename()?path.parent_path():path;
const auto prefix=path.filename().native();
fs::path best;
const auto accept=[&](const fs::path &candidate)
{
const auto name=candidate.filename().native();
if(name.size()<prefix.size() || (!prefix.empty() && CompareStringOrdinal(name.data(),
static_cast<int>(prefix.size()),prefix.data(),static_cast<int>(prefix.size()),ftp?FALSE:TRUE)!=CSTR_EQUAL))
return;
if(best.empty() || candidate<best) best=candidate;
};
const auto visit=[&](const fs::path &candidate,const FileInfo &info)
{
if(info.attributes&FILE_ATTRIBUTE_DIRECTORY) accept(candidate);
return true;
};
if(peer)
{
FilesConnection host(&*peer);
listFiles(host,directory,visit);
}
else if(ftp)
{
TransferSession host(*ftp);
host.list(directory,visit);
}
else
{
std::error_code error;
for(fs::directory_iterator it(directory,error),end;!error && it!=end;it.increment(error))
{
std::error_code typeError;
if(it->is_directory(typeError)) accept(it->path());
}
}
if(best.empty()) return {};
return ftp?ftpPath(best)+L"/":best.native()+L"\\";
}
LRESULT CALLBACK addressFieldKeys(HWND field,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_GETDLGCODE)
{
const auto *key=reinterpret_cast<const MSG *>(lp);
if(key && key->wParam==VK_TAB && !(GetKeyState(VK_SHIFT)&0x8000))
return DefSubclassProc(field,message,wp,lp)|DLGC_WANTTAB;
}
if(message==WM_KEYDOWN && wp==VK_TAB && !(GetKeyState(VK_SHIFT)&0x8000))
{
SendMessageW(GetParent(field),addressComplete,0,0);
return 0;
}
if(message==WM_CHAR && wp==VK_TAB) return 0;
return DefSubclassProc(field,message,wp,lp);
}
INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_DRAWITEM)
{
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),RGB(192,192,192),RGB(0,0,0),true);
return TRUE;
}
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Go to folder ",false,{addressFooter}))
return painted;
if(message==WM_INITDIALOG)
{
auto &prompt=*reinterpret_cast<PathPrompt *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,addressLabel);
layoutDialogButtons(dialog,addressFooter,{IDOK,IDCANCEL});
const auto field=GetDlgItem(dialog,addressField);
SendMessageW(field,EM_SETLIMITTEXT,32767,0);
const auto initial=prompt.base/fs::path{};
SetWindowTextW(field,(prompt.ftp?ftpPath(initial):initial.native()).c_str());
SetWindowSubclass(field,addressFieldKeys,4,0);
SetFocus(field);
SendMessageW(field,EM_SETSEL,0,-1);
return FALSE;
}
if(message==addressComplete)
{
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(prompt.completion.valid()) return TRUE;
prompt.completionInput=shortcutField(dialog,addressField);
std::packaged_task<std::wstring()> task([base=prompt.base,text=prompt.completionInput,
peer=prompt.peer,ftp=prompt.ftp]
{
return panelPathCompletion(base,text,peer,ftp);
});
if(!SetTimer(dialog,addressCompletionTimer,30,nullptr)) return TRUE;
prompt.completion=task.get_future();
std::thread(std::move(task)).detach();
return TRUE;
}
if(message==WM_TIMER && wp==addressCompletionTimer)
{
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!prompt.completion.valid() ||
prompt.completion.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return TRUE;
KillTimer(dialog,addressCompletionTimer);
try
{
const auto value=prompt.completion.get();
if(!value.empty() && shortcutField(dialog,addressField)==prompt.completionInput)
{
const auto field=GetDlgItem(dialog,addressField);
SetWindowTextW(field,value.c_str());
SendMessageW(field,EM_SETSEL,value.size(),value.size());
SendMessageW(field,EM_SCROLLCARET,0,0);
}
}
catch(const std::exception &) {}
return TRUE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
{
auto &prompt=*reinterpret_cast<PathPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
auto path=enteredPanelPath(prompt.base,shortcutField(dialog,addressField),prompt.ftp.has_value()).lexically_normal();
if(prompt.ftp?!isFtpFolderPath(path):!path.is_absolute())
{
showFilesNotice(dialog,L"Enter a folder path.",L"Go to folder");
return TRUE;
}
if(!path.has_filename() && path.has_relative_path()) path=path.parent_path();
prompt.result=std::move(path);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
return FALSE;
}
void editPanelPath(Panel &panel)
{
PathPrompt prompt{panel.directory,{},panel.peer,panel.ftp};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(117),GetParent(panel.list),
editPathDialog,reinterpret_cast<LPARAM>(&prompt))==IDOK)
navigatePanelPath(panel,prompt.result);
}
void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector<FolderLocation> locations,
RECT anchor)
{
hidePicker();
showMenu(false);
commandPicker=false;
pickerPanel=side;
folderPicker=FolderPicker{caption,std::move(locations)};
SendMessageW(picker,LB_RESETCONTENT,0,0);
size_t longest=wcslen(caption);
for(const auto &location:folderPicker->locations)
{
auto label=isTransferFolder(location.provider)?ftpPath(location.directory):location.directory.native();
longest=std::max(longest,label.size());
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
}
RECT client{};
GetClientRect(owner,&client);
const int inset=dialogFrameMetrics(GetDpiForWindow(owner)).content();
const int width=std::max(1,std::min(static_cast<int>(client.right)-2*inset,static_cast<int>(longest+3)*cellWidth));
const int x=std::clamp(static_cast<int>(anchor.left),inset,std::max(inset,static_cast<int>(client.right)-width-inset));
const int y=anchor.bottom+inset;
const int row=std::max(1,static_cast<int>(SendMessageW(picker,LB_GETITEMHEIGHT,0,0)));
RECT input{};
GetWindowRect(terminalInput,&input);
MapWindowPoints(nullptr,owner,reinterpret_cast<POINT *>(&input),2);
const int bottom=std::min(client.bottom,input.top);
const int shown=std::clamp((bottom-y-inset)/row,1,static_cast<int>(folderPicker->locations.size()));
showFramedList(picker,pickerFrame,x,y,width,row*shown,inset);
SendMessageW(picker,LB_SETCURSEL,0,0);
SetFocus(picker);
}
void showRecentFolders(Panel &panel)
{
PanelListing listing;
listing.recent=readRecentFolders();
listing.rows.reserve(listing.recent.size());
for(size_t i=0;i<listing.recent.size();++i)
{
auto &location=listing.recent[i];
auto label=location.directory.native();
if(location.provider!=FolderProvider::local)
{
const wchar_t *kind=L"LAN";
if(isTransferFolder(location.provider))
{
const auto protocol=folderTransferProtocol(location.provider);
kind=transferProtocolName(protocol);
if(loadTransferProfiles(protocol))
if(const auto *profile=findTransferProfile(location.id,protocol)) location.label=profile->name;
label=ftpPath(location.directory);
}
if(!location.label.empty()) label=location.label+L" · "+label;
label=std::wstring(kind)+L" · "+label;
}
listing.rows.emplace_back(std::to_wstring(i),std::move(label));
}
openPanelListing(panel,std::move(listing));
}
void openRecentFolder(Panel &panel)
{
const auto row=currentPanelRow(panel);
if(row!=LB_ERR && !panel.scan.valid())
openFolderLocation(panel,panel.listing->recent[row]);
}
void removeRecentFolder(Panel &panel)
{
const auto row=currentPanelRow(panel);
if(row==LB_ERR || panel.scan.valid()) return;
if(!updateRecentFolders(panel.listing->recent[row],false))
{
setStatus(L"Could not remove the recent folder.");
return;
}
for(auto &other:panels)
if(recentFolderList(other) && !other.scan.valid()) showRecentFolders(other);
}
void showHiddenPathParts(HWND window,int side,const PathPart &part)
{
const auto owner=GetParent(window);
auto anchor=part.rect;
MapWindowPoints(window,owner,reinterpret_cast<POINT*>(&anchor),2);
std::vector<FolderLocation> locations;
locations.reserve(part.hidden.size());
for(const auto &path:part.hidden) locations.push_back(folderLocation(panels[side],path));
showFolderPicker(owner,side,part.action==PathAction::ancestors?L"Parent folders":L"Previous path",
std::move(locations),anchor);
}
LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_LBUTTONDOWN)
{
SetCapture(window);
return 0;
}
if(message==WM_LBUTTONUP && GetCapture()==window)
{
ReleaseCapture();
const int index=GetDlgCtrlID(window)-142;
if(index<0 || index>=2) return 0;
panelClipboardContext=true;
auto &panel=panels[index];
if(!pathNavigationAvailable(panel))
{
selectPanelEdge(panel,true);
return 0;
}
activatePanel(index);
RECT bounds{};
GetClientRect(window,&bounds);
const POINT mouse{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
const auto parts=panelPathParts(panel,bounds);
for(const auto &part:parts)
{
if(!part.enabled || !PtInRect(&part.rect,mouse)) continue;
switch(part.action)
{
case PathAction::back: navigatePanelHistory(panel,-1); break;
case PathAction::forward: navigatePanelHistory(panel,1); break;
case PathAction::up: case PathAction::folder: navigatePanelPath(panel,part.target); break;
case PathAction::edit: editPanelPath(panel); break;
case PathAction::source:
if(panel.peer) chooseDrive(index,false,true);
else
{
const auto protocol=panel.ftp->protocol;
const auto *profile=findTransferProfile(panel.ftp->id,protocol);
showTransferProfiles(panel,protocol,profile?
ftpRoot/std::to_wstring(profile-transferProfiles(protocol).rows.data()):fs::path{});
}
break;
case PathAction::ancestors: case PathAction::previous: showHiddenPathParts(window,index,part); break;
}
break;
}
return 0;
}
return DefSubclassProc(window,message,wp,lp);
}
bool handlePanelPathKey(HWND owner,const MSG &message)
{
if(!commandLineAvailable(owner) || terminalVisible ||
(message.hwnd!=terminalInput && message.hwnd!=panels[active].list) ||
((GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) return false;
auto &panel=panels[active];
if(panel.archive)
{
if(message.message!=WM_SYSKEYDOWN || message.wParam!=VK_UP ||
!(message.lParam&(1LL<<29)) || (GetKeyState(VK_CONTROL)&0x8000)) return false;
if(!(message.lParam&(1LL<<30))) parentArchive(panel);
return true;
}
if(!pathNavigationAvailable(panel)) return false;
if(message.message==WM_KEYDOWN && message.wParam=='L' &&
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000))
{
if(!(message.lParam&(1LL<<30))) editPanelPath(panel);
return true;
}
if(message.message!=WM_SYSKEYDOWN || !(message.lParam&(1LL<<29)) ||
(GetKeyState(VK_CONTROL)&0x8000)) return false;
if(message.wParam==VK_UP)
navigatePanelPath(panel,panelParentPath(panel.directory,!panel.peer && !panel.ftp));
else if(message.wParam==VK_LEFT || message.wParam==VK_RIGHT)
navigatePanelHistory(panel,message.wParam==VK_LEFT?-1:1);
else return false;
return true;
}
+244
View File
@@ -0,0 +1,244 @@
constexpr int propertiesName=580, propertiesFirstDetail=581, propertiesOtherFlags=586;
constexpr int propertiesFirstFlag=587, propertiesDivider=592;
constexpr DWORD propertyOpenFlags=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT;
constexpr DWORD editablePropertyFlags[]{
FILE_ATTRIBUTE_READONLY,FILE_ATTRIBUTE_HIDDEN,FILE_ATTRIBUTE_SYSTEM,FILE_ATTRIBUTE_ARCHIVE,
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED};
struct FilePropertyFlag
{
DWORD flag;
const wchar_t *name;
};
std::wstring propertyFlagNames(DWORD flags)
{
constexpr FilePropertyFlag names[]{
{FILE_ATTRIBUTE_READONLY,L"Read-only"},{FILE_ATTRIBUTE_HIDDEN,L"Hidden"},
{FILE_ATTRIBUTE_SYSTEM,L"System"},{FILE_ATTRIBUTE_DIRECTORY,L"Directory"},
{FILE_ATTRIBUTE_ARCHIVE,L"Archive"},{FILE_ATTRIBUTE_NORMAL,L"Normal"},
{FILE_ATTRIBUTE_TEMPORARY,L"Temporary"},{FILE_ATTRIBUTE_SPARSE_FILE,L"Sparse"},
{FILE_ATTRIBUTE_REPARSE_POINT,L"Reparse point"},{FILE_ATTRIBUTE_COMPRESSED,L"Compressed"},
{FILE_ATTRIBUTE_OFFLINE,L"Offline"},{FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,L"Not indexed"},
{FILE_ATTRIBUTE_ENCRYPTED,L"Encrypted"},{FILE_ATTRIBUTE_INTEGRITY_STREAM,L"Integrity stream"},
{FILE_ATTRIBUTE_NO_SCRUB_DATA,L"No scrub"},{FILE_ATTRIBUTE_PINNED,L"Pinned"},
{FILE_ATTRIBUTE_UNPINNED,L"Unpinned"}};
std::wstring text;
const auto append=[&](std::wstring_view name)
{
if(!text.empty()) text+=L", ";
text+=name;
};
for(const auto &[flag,name]:names)
if(flags&flag)
{
append(name);
flags&=~flag;
}
if(flags)
{
wchar_t number[16]{};
swprintf_s(number,L"0x%08lX",static_cast<unsigned long>(flags));
append(number);
}
return text.empty()?L"—":text;
}
std::wstring propertyDate(uint64_t ticks)
{
const auto time=localFileTime(ticks);
if(!time) return L"—";
wchar_t label[32]{};
swprintf_s(label,L"%04u-%02u-%02u %02u:%02u:%02u",unsigned(time->wYear),unsigned(time->wMonth),
unsigned(time->wDay),unsigned(time->wHour),unsigned(time->wMinute),unsigned(time->wSecond));
return label;
}
struct ItemProperties
{
std::wstring name, owner;
uint64_t created{}, modified{}, accessed{}, changed{};
DWORD flags{}, requested{};
std::vector<std::wstring> details(bool includeMissing) const
{
std::vector<std::wstring> rows;
if(includeMissing || !owner.empty()) rows.push_back(L"Owner "+(owner.empty()?L"—":owner));
const auto date=[&](const wchar_t *label,uint64_t value)
{
if(includeMissing || value) rows.push_back(label+propertyDate(value));
};
date(L"Created ",created);
date(L"Modified ",modified);
date(L"Accessed ",accessed);
date(L"Changed ",changed);
return rows;
}
};
INT_PTR CALLBACK itemPropertiesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &properties=*reinterpret_cast<ItemProperties*>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
layoutDialogContent(dialog,propertiesName);
SetDlgItemTextW(dialog,propertiesName,properties.name.c_str());
const auto details=properties.details(true);
for(size_t index=0;index<details.size();++index)
SetDlgItemTextW(dialog,propertiesFirstDetail+static_cast<int>(index),details[index].c_str());
auto other=properties.flags&~FILE_ATTRIBUTE_NORMAL;
for(size_t index=0;index<std::size(editablePropertyFlags);++index)
{
const auto flag=editablePropertyFlags[index];
const auto id=propertiesFirstFlag+static_cast<int>(index);
installFarCheckbox(GetDlgItem(dialog,id),FarCheckboxSurface::gray);
CheckDlgButton(dialog,id,(properties.flags&flag)?BST_CHECKED:BST_UNCHECKED);
other&=~flag;
}
SetDlgItemTextW(dialog,propertiesOtherFlags,(L"Other flags "+propertyFlagNames(other)).c_str());
layoutDialogButtons(dialog,propertiesDivider,{IDOK,IDCANCEL});
return TRUE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
{
auto &properties=*reinterpret_cast<ItemProperties*>(GetWindowLongPtrW(dialog,DWLP_USER));
for(size_t index=0;index<std::size(editablePropertyFlags);++index)
if(IsDlgButtonChecked(dialog,propertiesFirstFlag+static_cast<int>(index))==BST_CHECKED)
properties.requested|=editablePropertyFlags[index];
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
return paintCopyDialog(dialog,message,wp,lp,L" Properties ",false,{propertiesDivider});
}
void showReadOnlyProperties(HWND owner,const ItemProperties &properties,const std::wstring &attributes)
{
auto text=properties.name+L"\r\n\r\n";
for(const auto &line:properties.details(false)) text+=line+L"\r\n";
text+=attributes;
showFilesNotice(owner,text.c_str(),L"Properties",{.tone=FilesNoticeTone::neutral});
}
bool panelItemPropertiesAvailable(const Panel &panel)
{
const auto row=currentPanelRow(panel);
return row!=LB_ERR && panel.sizes[row]!=L"Up" && !panelListsLocations(panel);
}
void showSourceItemProperties(HWND owner,const Panel &panel,const fs::path &path,ItemProperties properties)
{
const auto found=panel.metadata.find(path);
if(found==panel.metadata.end()) return;
const auto &entry=found->second;
properties.modified=entry.modified;
if(panel.peer)
{
showReadOnlyProperties(owner,properties,L"Attributes "+propertyFlagNames(entry.attributes));
return;
}
auto attributes=(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)?std::wstring(L"Folder"):
(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)?std::wstring(L"Special file"):std::wstring(L"File");
if(panel.archive && panel.archive->entries)
{
const auto &members=*panel.archive->entries;
if(const auto member=members.find(path.lexically_relative(panel.archive->file));member!=members.end())
{
properties.owner=member->second.owner;
properties.created=member->second.created;
properties.accessed=member->second.accessed;
if(member->second.encrypted) attributes+=L", Encrypted";
}
}
else if(const auto extra=panel.columnMetadata.find(path);
extra!=panel.columnMetadata.end() && extra->second.transfer)
{
const auto &details=*extra->second.transfer;
properties.created=details.created;
properties.accessed=details.accessed;
if(details.owner) properties.owner=L"UID "+std::to_wstring(*details.owner);
if(details.permissions)
{
wchar_t mode[12]{};
swprintf_s(mode,L"%04o",static_cast<unsigned>(*details.permissions));
attributes+=std::wstring(L"\r\nPermissions ")+mode;
}
}
if(panel.ftp && panel.ftp->protocol==TransferProtocol::ftp)
{
const auto flags=entry.attributes&~(FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_DIRECTORY);
if(flags) attributes+=L"\r\nAttributes "+propertyFlagNames(flags);
}
showReadOnlyProperties(owner,properties,L"Type "+attributes);
}
DWORD changeItemProperties(const fs::path &path,HANDLE original,const ItemProperties &properties)
{
DWORD editable{};
for(const auto flag:editablePropertyFlags) editable|=flag;
const DWORD changed=(properties.flags^properties.requested)&editable;
if(!changed) return ERROR_SUCCESS;
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES,columnFileShare,nullptr,
OPEN_EXISTING,propertyOpenFlags,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return GetLastError();
BY_HANDLE_FILE_INFORMATION before{},current{};
if(!GetFileInformationByHandle(original,&before) || !GetFileInformationByHandle(file.value,&current))
return GetLastError();
if(!ks::files::sameFileIdentity(before,current)) return ERROR_FILE_INVALID;
FILE_BASIC_INFO latest{};
if(!GetFileInformationByHandleEx(file.value,FileBasicInfo,&latest,sizeof(latest))) return GetLastError();
if(!((latest.FileAttributes^properties.requested)&changed)) return ERROR_SUCCESS;
FILE_BASIC_INFO update{};
update.FileAttributes=(latest.FileAttributes&~(changed|FILE_ATTRIBUTE_NORMAL))|(properties.requested&changed);
if(!update.FileAttributes) update.FileAttributes=FILE_ATTRIBUTE_NORMAL;
if(!SetFileInformationByHandle(file.value,FileBasicInfo,&update,sizeof(update))) return GetLastError();
return ERROR_SUCCESS;
}
void showPanelItemProperties(HWND owner,Panel &panel)
{
if(!panelItemPropertiesAvailable(panel)) return;
const auto path=panel.rows[currentPanelRow(panel)];
ItemProperties properties{path.filename().native()};
if(panel.ftp || panel.peer || panel.archive)
{
showSourceItemProperties(owner,panel,path,std::move(properties));
return;
}
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,columnFileShare,nullptr,OPEN_EXISTING,
propertyOpenFlags,nullptr)};
FILE_BASIC_INFO info{};
if(file.value==INVALID_HANDLE_VALUE || !GetFileInformationByHandleEx(file.value,FileBasicInfo,&info,sizeof(info)))
{
const auto error=GetLastError();
refreshPanel(panel);
showFileOperationError(owner,L"Could not read properties",fileError({static_cast<int>(error),std::system_category()}));
return;
}
std::map<std::wstring,std::wstring> owners;
properties.owner=localOwnerName(path,owners);
properties.created=info.CreationTime.QuadPart;
properties.modified=info.LastWriteTime.QuadPart;
properties.accessed=info.LastAccessTime.QuadPart;
properties.changed=info.ChangeTime.QuadPart;
properties.flags=info.FileAttributes;
if(windowsNetworkPath(path))
{
showReadOnlyProperties(owner,properties,L"Attributes "+propertyFlagNames(properties.flags));
return;
}
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(125),owner,itemPropertiesDialog,
reinterpret_cast<LPARAM>(&properties))!=IDOK) return;
const auto error=changeItemProperties(path,file.value,properties);
refreshPanel(panel);
if(error!=ERROR_SUCCESS)
showFileOperationError(owner,L"Could not save attributes",error==ERROR_FILE_INVALID?
L"The item was replaced while the properties were open.":
fileError({static_cast<int>(error),std::system_category()}));
}
+78
View File
@@ -0,0 +1,78 @@
constexpr wchar_t recentFoldersKey[]=L"RecentFolders";
constexpr size_t recentFoldersLimit=100;
std::optional<FolderLocation> readRecentFolder(const Json &entry)
{
FolderLocation location;
if(entry.is_string()) location.directory=filePath(entry);
else if(entry.is_object())
{
const auto source=entry.value("source",std::string{});
if(source=="ftp") location.provider=FolderProvider::ftp;
else if(source=="sftp") location.provider=FolderProvider::sftp;
else if(source=="lan") location.provider=FolderProvider::lan;
else return {};
location.id=entry.at("id").get<std::string>();
if(location.id.empty()) return {};
location.label=ks::wide(entry.value("label",std::string{}));
location.directory=filePath(entry.at("path"));
}
else return {};
const auto &path=location.directory;
if(path.native().find(L'\0')!=std::wstring::npos) return {};
if(isTransferFolder(location.provider))
{
if(!isFtpFolderPath(path)) return {};
}
else if(!path.is_absolute()) return {};
return location;
}
std::vector<FolderLocation> readRecentFolders()
{
const auto saved=readFilesJsonPreference(recentFoldersKey);
std::vector<FolderLocation> folders;
if(!saved || !saved->is_array()) return folders;
for(const auto &entry:*saved)
{
try
{
auto location=readRecentFolder(entry);
if(location && std::none_of(folders.begin(),folders.end(),
[&](const auto &known){return sameFolderLocation(*location,known);}))
folders.push_back(std::move(*location));
}
catch(const std::exception &) {}
if(folders.size()==recentFoldersLimit) break;
}
return folders;
}
bool updateRecentFolders(const FolderLocation &location,bool remember)
{
const Handle lock{CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.RecentFolders")};
if(!lock.value) return false;
const auto wait=WaitForSingleObject(lock.value,100);
if(wait!=WAIT_OBJECT_0 && wait!=WAIT_ABANDONED) return false;
bool saved=false;
try
{
auto folders=readRecentFolders();
std::erase_if(folders,[&](const auto &known){return sameFolderLocation(location,known);});
if(remember) folders.insert(folders.begin(),location);
if(folders.size()>recentFoldersLimit) folders.resize(recentFoldersLimit);
auto data=Json::array();
for(const auto &folder:folders)
{
const auto path=ks::utf8(folder.directory.native());
if(folder.provider==FolderProvider::local) data.push_back(path);
else data.push_back({{"source",folder.provider==FolderProvider::ftp?"ftp":
folder.provider==FolderProvider::sftp?"sftp":"lan"},{"id",folder.id},
{"label",ks::utf8(folder.label)},{"path",path}});
}
saved=writeFilesJsonPreference(recentFoldersKey,data);
}
catch(const std::exception &) {}
ReleaseMutex(lock.value);
return saved;
}
+25
View File
@@ -0,0 +1,25 @@
constexpr DWORD maxFilesJsonBytes=1024*1024;
std::optional<Json> readFilesJsonPreference(const wchar_t *key)
{
DWORD bytes{};
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,key,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
!bytes || bytes>maxFilesJsonBytes) return {};
std::string data(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,key,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
return {};
try {return Json::parse(data.begin(),data.begin()+bytes);}
catch(const std::exception &) {return {};}
}
bool writeFilesJsonPreference(const wchar_t *key,const Json &value)
{
try
{
const auto data=value.dump();
return data.size()<=maxFilesJsonBytes &&
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,key,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
}
catch(const std::exception &) {return false;}
}
+460
View File
@@ -0,0 +1,460 @@
constexpr long sftpTimeoutMs=10000;
void initializeSsh()
{
static const auto initialized=libssh2_init(0);
if(initialized) throw std::runtime_error("Could not initialize the SSH client.");
}
void connectSshSocket(ks::lan::WinSocket &connection,const TransferProfile &profile)
{
ADDRINFOW query{};
query.ai_socktype=SOCK_STREAM;
query.ai_protocol=IPPROTO_TCP;
ADDRINFOW *addresses{};
const auto service=std::to_wstring(profile.port);
if(const auto error=GetAddrInfoW(profile.host.c_str(),service.c_str(),&query,&addresses))
throw std::system_error(error,std::system_category());
const std::unique_ptr<ADDRINFOW,decltype(&FreeAddrInfoW)> resolved(addresses,FreeAddrInfoW);
DWORD lastError=WSAEHOSTUNREACH;
const auto deadline=GetTickCount64()+sftpTimeoutMs;
for(auto *address=addresses;address;address=address->ai_next)
{
ks::lan::WinSocket socket{::socket(address->ai_family,address->ai_socktype,address->ai_protocol)};
if(socket.value==INVALID_SOCKET) {lastError=WSAGetLastError();continue;}
u_long nonblocking=1;
if(ioctlsocket(socket.value,FIONBIO,&nonblocking)==SOCKET_ERROR)
{lastError=WSAGetLastError();continue;}
if(::connect(socket.value,address->ai_addr,static_cast<int>(address->ai_addrlen))==SOCKET_ERROR)
{
lastError=WSAGetLastError();
if(lastError!=WSAEWOULDBLOCK) continue;
const auto now=GetTickCount64();
if(now>=deadline) {lastError=WSAETIMEDOUT;break;}
const auto left=deadline-now;
timeval timeout{static_cast<long>(left/1000),static_cast<long>(left%1000)*1000};
fd_set writable{},failed{};
FD_SET(socket.value,&writable);
FD_SET(socket.value,&failed);
const auto ready=select(0,nullptr,&writable,&failed,&timeout);
if(ready==SOCKET_ERROR) {lastError=WSAGetLastError();continue;}
if(!ready) {lastError=WSAETIMEDOUT;break;}
int error{},length=sizeof(error);
if(getsockopt(socket.value,SOL_SOCKET,SO_ERROR,reinterpret_cast<char*>(&error),&length)==SOCKET_ERROR)
{lastError=WSAGetLastError();continue;}
if(error) {lastError=error;continue;}
}
nonblocking=0;
if(ioctlsocket(socket.value,FIONBIO,&nonblocking)==SOCKET_ERROR)
{lastError=WSAGetLastError();continue;}
connection.value=std::exchange(socket.value,INVALID_SOCKET);
return;
}
throw std::system_error(lastError,std::system_category());
}
using SshChannel=std::unique_ptr<LIBSSH2_CHANNEL,decltype(&libssh2_channel_free)>;
class SshConnection
{
struct Tunnel
{
SshChannel channel;
LIBSSH2_SESSION *parent;
struct Nonblocking
{
LIBSSH2_SESSION *parent;
int previous;
explicit Nonblocking(LIBSSH2_SESSION *session):
parent(session),previous(libssh2_session_get_blocking(parent))
{
libssh2_session_set_blocking(parent,0);
}
~Nonblocking(){libssh2_session_set_blocking(parent,previous);}
};
};
struct Hop
{
std::unique_ptr<Tunnel> tunnel;
std::unique_ptr<LIBSSH2_SESSION,decltype(&libssh2_session_free)> session{nullptr,libssh2_session_free};
};
ks::lan::Network network_;
ks::lan::WinSocket socket_;
std::optional<std::stop_callback<std::function<void()>>> stopConnection_;
std::vector<Hop> hops_;
std::string fingerprint_;
static LIBSSH2_SEND_FUNC(sendThroughJump)
{
const auto &tunnel=*static_cast<Tunnel*>(*abstract);
// Channel writes drain incoming packets first. A nested transport must
// report when that drain would block so it can still send its own data.
const Tunnel::Nonblocking nonblocking(tunnel.parent);
const auto result=libssh2_channel_write(tunnel.channel.get(),static_cast<const char*>(buffer),length);
return result>=0?result:result==LIBSSH2_ERROR_EAGAIN?-EAGAIN:-EIO;
}
static LIBSSH2_RECV_FUNC(receiveThroughJump)
{
const auto &tunnel=*static_cast<Tunnel*>(*abstract);
const Tunnel::Nonblocking nonblocking(tunnel.parent);
auto *channel=tunnel.channel.get();
const auto result=libssh2_channel_read(channel,static_cast<char*>(buffer),length);
if(result>0) return result;
if(result==0 && libssh2_channel_eof(channel)) return 0;
return result==0 || result==LIBSSH2_ERROR_EAGAIN?-EAGAIN:-EIO;
}
[[noreturn]] void sshError(const char *operation) const
{
char *message{};
int length{};
libssh2_session_last_error(session(),&message,&length,0);
throw std::runtime_error(std::string(operation)+(message && length>0?": "+std::string(message,length):""));
}
void authenticate(const TransferProfile &profile)
{
auto wideSecret=transferPassword(profile);
struct EraseWide
{
std::wstring &text;
~EraseWide(){if(!text.empty()) SecureZeroMemory(text.data(),text.size()*sizeof(wchar_t));}
} eraseWide{wideSecret};
auto secret=ks::utf8(wideSecret);
struct EraseText
{
std::string &text;
~EraseText(){if(!text.empty()) SecureZeroMemory(text.data(),text.size());}
} eraseSecret{secret};
const auto user=ks::utf8(profile.user);
int result{};
if(profile.privateKey.empty())
result=libssh2_userauth_password_ex(session(),user.c_str(),static_cast<unsigned>(user.size()),
secret.c_str(),static_cast<unsigned>(secret.size()),nullptr);
else
{
auto key=ks::readFile(profile.privateKey,1024*1024);
struct EraseKey
{
ks::Bytes &bytes;
~EraseKey(){if(!bytes.empty()) SecureZeroMemory(bytes.data(),bytes.size());}
} eraseKey{key};
if(key.empty()) throw std::runtime_error("Could not read the SFTP private key file.");
auto publicPath=profile.privateKey;
publicPath+=L".pub";
ks::Bytes publicKey;
std::error_code error;
if(fs::exists(publicPath,error)) publicKey=ks::readFile(publicPath,64*1024);
result=libssh2_userauth_publickey_frommemory(session(),user.c_str(),user.size(),
publicKey.empty()?nullptr:reinterpret_cast<const char*>(publicKey.data()),publicKey.size(),
reinterpret_cast<const char*>(key.data()),key.size(),secret.c_str());
}
if(result) sshError(profile.privateKey.empty()?"SFTP password authentication failed":
"SFTP key authentication failed (use RSA PEM without a passphrase, or ECDSA OpenSSH with its .pub file)");
}
void connectHop(const TransferProfile &profile,bool probeOnly,std::stop_token stop)
{
if(!probeOnly && profile.hostFingerprint.empty())
throw std::runtime_error("The SFTP host key is untrusted. Edit the profile and use Test connection to verify it.");
Hop hop;
if(hops_.empty())
{
connectSshSocket(socket_,profile);
if(stop.stop_possible()) stopConnection_.emplace(stop,[handle=socket_.value] {shutdown(handle,SD_BOTH);});
}
else
{
const auto host=ks::utf8(profile.host);
SshChannel channel(libssh2_channel_direct_tcpip(session(),host.c_str(),profile.port),libssh2_channel_free);
if(!channel) sshError("Could not open an SSH jump tunnel");
hop.tunnel=std::make_unique<Tunnel>(Tunnel{std::move(channel),session()});
}
hop.session.reset(libssh2_session_init_ex(nullptr,nullptr,nullptr,hop.tunnel.get()));
if(!hop.session) throw std::runtime_error("Could not create an SSH session.");
hops_.push_back(std::move(hop));
if(hops_.back().tunnel)
{
libssh2_session_callback_set2(session(),LIBSSH2_CALLBACK_SEND,
reinterpret_cast<libssh2_cb_generic*>(sendThroughJump));
libssh2_session_callback_set2(session(),LIBSSH2_CALLBACK_RECV,
reinterpret_cast<libssh2_cb_generic*>(receiveThroughJump));
}
libssh2_session_set_timeout(session(),sftpTimeoutMs);
libssh2_session_set_read_timeout(session(),sftpTimeoutMs/1000);
if(libssh2_session_method_pref(session(),LIBSSH2_METHOD_HOSTKEY,
"ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,rsa-sha2-512,rsa-sha2-256") ||
libssh2_session_handshake(session(),socket_.value))
sshError("Could not negotiate an SSH connection");
const auto digest=reinterpret_cast<const BYTE*>(libssh2_hostkey_hash(session(),LIBSSH2_HOSTKEY_HASH_SHA256));
if(!digest) throw std::runtime_error("The server did not provide a verifiable SSH host key.");
char fingerprint[64]{};
DWORD length=static_cast<DWORD>(std::size(fingerprint));
checkFileOperation(CryptBinaryToStringA(digest,32,CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF,fingerprint,&length));
auto encoded=std::string(fingerprint);
while(encoded.ends_with('=')) encoded.pop_back();
fingerprint_="SHA256:"+encoded;
if(probeOnly) return;
if(!ks::lan::equal(fingerprint_,profile.hostFingerprint))
throw std::runtime_error("The SFTP host key changed. Connection blocked before authentication. Received "+fingerprint_+".");
authenticate(profile);
}
void close() noexcept
{
if(socket_.value!=INVALID_SOCKET) shutdown(socket_.value,SD_BOTH);
while(!hops_.empty())
{
auto &hop=hops_.back();
libssh2_session_set_blocking(hop.session.get(),1);
hop.session.reset();
hops_.pop_back();
}
}
public:
explicit SshConnection(const TransferProfile &destination,bool probeOnly=false,std::stop_token stop={})
{
initializeSsh();
const auto profiles=sshProfiles.load();
static const std::vector<TransferProfile> empty;
const auto route=sshRoute(destination,profiles?*profiles:empty);
try
{
for(size_t i=0;i<route.size();++i)
{
requireFileOperation(!stop.stop_requested(),ERROR_CANCELLED);
const auto &profile=route[i];
try {connectHop(profile,probeOnly && i+1==route.size(),stop);}
catch(const std::exception &error)
{
if(route.size()==1) throw;
throw std::runtime_error(ks::utf8(profile.name)+": "+error.what());
}
}
}
catch(...) {close();throw;}
}
~SshConnection(){close();}
LIBSSH2_SESSION *session() const {return hops_.back().session.get();}
const std::string &fingerprint() const {return fingerprint_;}
void nonblocking()
{
for(const auto &hop:hops_) libssh2_session_set_blocking(hop.session.get(),0);
}
[[noreturn]] void operationError(const char *operation) const {sshError(operation);}
};
struct SftpFile
{
LIBSSH2_SFTP_HANDLE *handle{};
explicit SftpFile(LIBSSH2_SFTP_HANDLE *value):handle(value){}
SftpFile(const SftpFile &)=delete;
SftpFile(SftpFile &&other) noexcept:handle(std::exchange(other.handle,nullptr)){}
~SftpFile(){if(handle) libssh2_sftp_close_handle(handle);}
};
using SftpSubsystem=std::unique_ptr<LIBSSH2_SFTP,decltype(&libssh2_sftp_shutdown)>;
fs::path sftpInitialDirectory(LIBSSH2_SFTP *sftp)
{
std::array<char,32768> path{};
const auto length=libssh2_sftp_realpath(sftp,".",path.data(),path.size());
if(length<=0) return {};
auto value=fs::path(ks::wide(std::string(path.data(),length))).lexically_normal();
if(!isFtpFolderPath(value)) throw std::runtime_error("The server returned an invalid SFTP folder path.");
return value;
}
enum class SftpAccess { normal, sudoRead, sudoWrite };
class SftpSession
{
SshConnection connection_;
const SftpAccess access_;
SftpSubsystem sftp_{nullptr,libssh2_sftp_shutdown};
static std::string encode(const fs::path &path) {return ks::utf8(ftpPath(path));}
void requireWriteAccess() const
{
if(access_==SftpAccess::sudoRead)
throw std::system_error(ERROR_ACCESS_DENIED,std::system_category(),"The sudo SFTP session is read-only");
}
public:
explicit SftpSession(const TransferProfile &profile,SftpAccess access=SftpAccess::normal,
std::stop_token stop={}):connection_(profile,false,stop),access_(access)
{
if(access==SftpAccess::normal)
{
sftp_.reset(libssh2_sftp_init(connection_.session()));
if(!sftp_) connection_.operationError("Could not start the SFTP subsystem");
return;
}
if(profile.sudoSftpServer.empty() || !validSudoSftpServer(profile.sudoSftpServer))
throw std::runtime_error("Configure the absolute sftp-server path for sudo in this SFTP profile.");
const auto command="sudo -n -- "+ks::utf8(profile.sudoSftpServer)+(access==SftpAccess::sudoRead?" -R":"");
sftp_.reset(libssh2_sftp_init_command(connection_.session(),command.c_str()));
if(!sftp_) connection_.operationError("Could not start sudo SFTP. Verify the sftp-server path and the server's sudo authorization");
}
[[noreturn]] void operationError(const char *operation) const
{
if(libssh2_session_last_errno(connection_.session())==LIBSSH2_ERROR_SFTP_PROTOCOL)
{
const auto status=libssh2_sftp_last_error(sftp_.get());
if(status==LIBSSH2_FX_PERMISSION_DENIED)
throw ks::files::RemoteAccessDenied(operation);
if(status==LIBSSH2_FX_NO_SUCH_FILE || status==LIBSSH2_FX_NO_SUCH_PATH)
throw std::system_error(ERROR_FILE_NOT_FOUND,std::system_category(),operation);
if(status==LIBSSH2_FX_FILE_ALREADY_EXISTS)
throw std::system_error(ERROR_ALREADY_EXISTS,std::system_category(),operation);
if(status==LIBSSH2_FX_OP_UNSUPPORTED)
throw std::system_error(ERROR_NOT_SUPPORTED,std::system_category(),operation);
}
connection_.operationError(operation);
}
fs::path initialDirectory() const
{
auto path=sftpInitialDirectory(sftp_.get());
if(path.empty()) operationError("Could not resolve the initial SFTP folder");
return path;
}
DWORD list(const fs::path &directory,const FileVisitor &visit,std::stop_token stop={}) const
{
if(stop.stop_requested()) return ERROR_CANCELLED;
const auto path=encode(directory);
const SftpFile folder(libssh2_sftp_open_ex(sftp_.get(),path.c_str(),static_cast<unsigned>(path.size()),
0,0,LIBSSH2_SFTP_OPENDIR));
if(!folder.handle) operationError("Could not open the SFTP folder");
std::array<char,32768> name{};
while(!stop.stop_requested())
{
LIBSSH2_SFTP_ATTRIBUTES attrs{};
const auto length=libssh2_sftp_readdir_ex(folder.handle,name.data(),name.size(),nullptr,0,&attrs);
if(length==0) return ERROR_NO_MORE_FILES;
if(length<0) operationError("Could not read the SFTP folder");
const auto child=ks::wide(std::string(name.data(),length));
if(child.empty() || child==L"." || child==L".." || child.find_first_of(L"/\\:\r\n")!=child.npos ||
child.find(L'\0')!=child.npos) continue;
DWORD attributes=FILE_ATTRIBUTE_NORMAL;
if((attrs.flags&LIBSSH2_SFTP_ATTR_PERMISSIONS)!=0)
{
if(LIBSSH2_SFTP_S_ISDIR(attrs.permissions)) attributes=FILE_ATTRIBUTE_DIRECTORY;
else if(!LIBSSH2_SFTP_S_ISREG(attrs.permissions)) attributes=FILE_ATTRIBUTE_REPARSE_POINT;
if(!(attrs.permissions&0222)) attributes|=FILE_ATTRIBUTE_READONLY;
}
const auto sftpTime=[](unsigned long seconds){return (uint64_t(seconds)+11644473600ULL)*10000000ULL;};
FileInfo info{attributes,attrs.filesize,0};
TransferItemMetadata details;
if(attrs.flags&LIBSSH2_SFTP_ATTR_ACMODTIME)
{
info.modified=sftpTime(attrs.mtime);
details.accessed=sftpTime(attrs.atime);
}
if(attrs.flags&LIBSSH2_SFTP_ATTR_UIDGID) details.owner=attrs.uid;
if(attrs.flags&LIBSSH2_SFTP_ATTR_PERMISSIONS) details.permissions=attrs.permissions&07777;
if(details.accessed || details.owner || details.permissions) info.transfer=details;
if(!visit(directory/child,info)) return ERROR_CANCELLED;
}
return ERROR_CANCELLED;
}
SftpFile open(const fs::path &path,bool write) const
{
if(write) requireWriteAccess();
const auto name=encode(path);
const auto flags=write?LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_EXCL:LIBSSH2_FXF_READ;
SftpFile file(libssh2_sftp_open_ex(sftp_.get(),name.c_str(),static_cast<unsigned>(name.size()),
flags,0600,LIBSSH2_SFTP_OPENFILE));
if(!file.handle) operationError(write?"Could not create the staged SFTP file":"Could not open the SFTP file");
return file;
}
void makeDirectory(const fs::path &path) const
{
requireWriteAccess();
const auto name=encode(path);
if(libssh2_sftp_mkdir(sftp_.get(),name.c_str(),0755)) operationError("Could not create the SFTP folder");
}
void preserveModificationTime(const fs::path &path,uint64_t modified) const
{
constexpr uint64_t ticks=10000000, windowsEpoch=11644473600;
if(modified/ticks<windowsEpoch || modified/ticks-windowsEpoch>UINT32_MAX) return;
requireWriteAccess();
const auto name=encode(path);
LIBSSH2_SFTP_ATTRIBUTES attributes{};
if(libssh2_sftp_lstat(sftp_.get(),name.c_str(),&attributes))
operationError("Could not read the staged file timestamps");
const auto seconds=static_cast<unsigned long>(modified/ticks-windowsEpoch);
if(!(attributes.flags&LIBSSH2_SFTP_ATTR_ACMODTIME)) attributes.atime=seconds;
attributes.flags=LIBSSH2_SFTP_ATTR_ACMODTIME;
attributes.mtime=seconds;
if(libssh2_sftp_setstat(sftp_.get(),name.c_str(),&attributes) &&
libssh2_sftp_last_error(sftp_.get())!=LIBSSH2_FX_OP_UNSUPPORTED)
operationError("Could not preserve the SFTP modification time");
}
void remove(const fs::path &path,bool directory) const
{
requireWriteAccess();
const auto name=encode(path);
const auto result=directory?libssh2_sftp_rmdir(sftp_.get(),name.c_str()):libssh2_sftp_unlink(sftp_.get(),name.c_str());
if(result) operationError("Could not remove the SFTP entry");
}
void prepareReplacement(const fs::path &staged,const fs::path &existing) const
{
if(access_!=SftpAccess::sudoWrite) return;
const auto source=encode(existing),target=encode(staged);
LIBSSH2_SFTP_ATTRIBUTES attributes{};
if(libssh2_sftp_lstat(sftp_.get(),source.c_str(),&attributes))
operationError("Could not read the file ownership and permissions");
constexpr auto metadata=LIBSSH2_SFTP_ATTR_UIDGID|LIBSSH2_SFTP_ATTR_PERMISSIONS;
if((attributes.flags&metadata)!=metadata || !LIBSSH2_SFTP_S_ISREG(attributes.permissions))
throw std::runtime_error("The server did not supply the file ownership and permissions. The original was kept.");
const auto original=attributes;
attributes.flags=LIBSSH2_SFTP_ATTR_UIDGID;
if(libssh2_sftp_setstat(sftp_.get(),target.c_str(),&attributes))
operationError("Could not preserve the file ownership");
attributes.flags=LIBSSH2_SFTP_ATTR_PERMISSIONS;
attributes.permissions=original.permissions&07777;
if(libssh2_sftp_setstat(sftp_.get(),target.c_str(),&attributes))
operationError("Could not preserve the file permissions");
if(libssh2_sftp_lstat(sftp_.get(),target.c_str(),&attributes))
operationError("Could not verify the staged file permissions");
if((attributes.flags&metadata)!=metadata || attributes.uid!=original.uid ||
attributes.gid!=original.gid || (attributes.permissions&07777)!=(original.permissions&07777))
throw std::runtime_error("The server did not preserve ownership and permissions. The original was kept.");
}
void rename(const fs::path &from,const fs::path &to,bool replace) const
{
requireWriteAccess();
const auto source=encode(from),target=encode(to);
if(replace)
{
const auto result=libssh2_sftp_posix_rename_ex(sftp_.get(),source.c_str(),source.size(),
target.c_str(),target.size());
if(result && (result==LIBSSH2_ERROR_METHOD_NOT_SUPPORTED ||
libssh2_sftp_last_error(sftp_.get())==LIBSSH2_FX_OP_UNSUPPORTED))
throw std::runtime_error("The SFTP server does not support atomic replacement. The original file was kept.");
if(result) operationError("Could not replace the SFTP file");
return;
}
if(libssh2_sftp_rename_ex(sftp_.get(),source.c_str(),static_cast<unsigned>(source.size()),
target.c_str(),static_cast<unsigned>(target.size()),0))
operationError("Could not rename the SFTP entry");
}
};
+596
View File
@@ -0,0 +1,596 @@
namespace smb
{
constexpr wchar_t profilesKey[]=L"SmbProfiles";
constexpr DWORD shareTypeMask=0xff;
constexpr int nameLabel=550,nameField=551,addressLabel=552,addressField=553,editFooter=554;
constexpr int loginLabel=555,userLabel=556,userField=557,passwordLabel=558,passwordField=559,rememberField=560,loginFooter=561;
struct Target
{
std::wstring server;
fs::path share,folder;
};
std::optional<Target> parseTarget(std::wstring address)
{
address=trimFilesField(std::move(address));
std::replace(address.begin(),address.end(),L'/',L'\\');
if(address.starts_with(L"\\\\")) address.erase(0,2);
while(address.ends_with(L"\\")) address.pop_back();
if(address.empty() || address.size()>=MAX_PATH-2) return {};
const auto separator=address.find(L'\\');
const auto host=address.substr(0,separator);
if(host.empty() || host==L"." || host==L".." || host.find_first_of(L" \t\r\n@<>:\"|?*")!=host.npos ||
std::any_of(host.begin(),host.end(),[](auto c){return c<L' ';})) return {};
Target target{L"\\\\"+host};
if(separator==address.npos) return target;
const auto relative=address.substr(separator+1);
if(relative.empty() || relative.front()==L'\\' || relative.find(L"\\\\")!=relative.npos ||
relative.find_first_of(L"<>:\"|?*")!=relative.npos ||
std::any_of(relative.begin(),relative.end(),[](auto c){return c<L' ';})) return {};
const fs::path components(relative);
for(const auto &part:components)
if(part==L"." || part==L".." || part.native().back()==L' ' || part.native().back()==L'.')
return {};
target.share=fs::path(target.server+L"\\"+components.begin()->native());
target.folder=fs::path(target.server+L"\\"+relative);
return target;
}
struct Profile
{
std::string id;
std::wstring name;
Target target;
};
std::wstring profileAddress(const Profile &profile)
{
return profile.target.folder.empty()?profile.target.server:profile.target.folder.native();
}
std::vector<Profile> readProfiles()
{
std::vector<Profile> profiles;
const auto saved=readFilesJsonPreference(profilesKey);
if(!saved || !saved->is_array()) return profiles;
for(const auto &row:*saved)
{
try
{
const auto id=row.at("id").get<std::string>();
auto name=ks::wide(row.at("name"));
auto target=parseTarget(ks::wide(row.at("path")));
if(ks::lan::identifier(id) && !name.empty() && target &&
std::none_of(profiles.begin(),profiles.end(),[&](const auto &entry){return entry.id==id;}))
profiles.push_back({id,std::move(name),std::move(*target)});
}
catch(const std::exception &) {}
}
return profiles;
}
struct ProfilesLock
{
Handle handle{CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.SmbProfiles")};
bool locked{};
ProfilesLock()
{
if(!handle.value) return;
const auto wait=WaitForSingleObject(handle.value,100);
locked=wait==WAIT_OBJECT_0 || wait==WAIT_ABANDONED;
}
~ProfilesLock() {if(locked) ReleaseMutex(handle.value);}
};
bool sameServer(const Profile &a,const Profile &b)
{
return CompareStringOrdinal(a.target.server.c_str(),-1,b.target.server.c_str(),-1,TRUE)==CSTR_EQUAL;
}
template<class Change>
std::optional<std::vector<Profile>> updateProfiles(Change change)
{
const ProfilesLock lock;
if(!lock.locked) return {};
std::optional<std::vector<Profile>> result;
try
{
auto profiles=readProfiles();
if(change(profiles))
{
auto data=Json::array();
for(const auto &entry:profiles)
data.push_back({{"id",entry.id},{"name",ks::utf8(entry.name)},{"path",ks::utf8(profileAddress(entry))}});
if(writeFilesJsonPreference(profilesKey,data)) result=std::move(profiles);
}
}
catch(const std::exception &) {}
return result;
}
std::wstring credentialTarget(const Profile &profile)
{
auto host=profile.target.server.substr(2);
for(auto &letter:host)
if(letter>=L'A' && letter<=L'Z') letter+=L'a'-L'A';
return L"KSwitcher.Files/SMB/"+ks::wide(profile.id)+L"/"+host;
}
DWORD deleteCredential(const Profile &profile)
{
if(CredDeleteW(credentialTarget(profile).c_str(),CRED_TYPE_GENERIC,0)) return ERROR_SUCCESS;
const auto error=GetLastError();
return error==ERROR_NOT_FOUND?ERROR_SUCCESS:error;
}
struct Credentials
{
std::wstring user;
std::vector<wchar_t> password;
bool remember{};
Credentials()=default;
Credentials(const Credentials &)=delete;
Credentials &operator=(const Credentials &)=delete;
~Credentials()
{
if(!password.empty()) SecureZeroMemory(password.data(),password.size()*sizeof(wchar_t));
}
};
DWORD loadCredential(const Profile &profile,Credentials &login)
{
struct Allocation
{
PCREDENTIALW data{};
~Allocation()
{
if(!data) return;
if(data->CredentialBlobSize) SecureZeroMemory(data->CredentialBlob,data->CredentialBlobSize);
CredFree(data);
}
} response;
if(!CredReadW(credentialTarget(profile).c_str(),CRED_TYPE_GENERIC,0,&response.data))
{
const auto error=GetLastError();
return error==ERROR_NOT_FOUND?ERROR_SUCCESS:error;
}
const auto &credential=*response.data;
if(!credential.UserName || !*credential.UserName || credential.CredentialBlobSize%sizeof(wchar_t))
return ERROR_INVALID_DATA;
login.user=credential.UserName;
login.password.resize(credential.CredentialBlobSize/sizeof(wchar_t)+1);
if(credential.CredentialBlobSize)
std::memcpy(login.password.data(),credential.CredentialBlob,credential.CredentialBlobSize);
return ERROR_SUCCESS;
}
DWORD saveCredential(const Profile &profile,const Credentials &login)
{
const ProfilesLock lock;
if(!lock.locked) return ERROR_BUSY;
const auto profiles=readProfiles();
if(std::none_of(profiles.begin(),profiles.end(),[&](const auto &entry) {
return entry.id==profile.id && sameServer(profile,entry);
})) return ERROR_NOT_FOUND;
auto target=credentialTarget(profile);
CREDENTIALW credential{};
credential.Type=CRED_TYPE_GENERIC;
credential.TargetName=target.data();
credential.Persist=CRED_PERSIST_LOCAL_MACHINE;
credential.UserName=const_cast<wchar_t*>(login.user.c_str());
credential.CredentialBlobSize=static_cast<DWORD>((login.password.size()-1)*sizeof(wchar_t));
credential.CredentialBlob=reinterpret_cast<LPBYTE>(const_cast<wchar_t*>(login.password.data()));
return CredWriteW(&credential,0)?ERROR_SUCCESS:GetLastError();
}
std::wstring errorText(DWORD error)
{
if(error==ERROR_SESSION_CREDENTIAL_CONFLICT)
return L"Windows already has a session to this server with another account. Use that account or disconnect that session in Windows before trying again.";
return fileError(std::system_error(error,std::system_category()));
}
struct Connection
{
fs::path folder;
std::vector<std::wstring> shares;
DWORD error{},credentialError{};
};
Connection connect(const Profile &profile,const Credentials *explicitLogin,const std::atomic_bool &canceled)
{
Connection result;
Credentials stored;
auto login=explicitLogin;
if(!login)
{
result.error=loadCredential(profile,stored);
if(result.error) return result;
if(!stored.user.empty()) login=&stored;
}
if(login && !canceled)
{
auto resource=profile.target.share.empty()?profile.target.server+L"\\IPC$":profile.target.share.native();
NETRESOURCEW endpoint{};
endpoint.dwType=profile.target.share.empty()?RESOURCETYPE_ANY:RESOURCETYPE_DISK;
endpoint.lpRemoteName=resource.data();
result.error=WNetAddConnection2W(&endpoint,login->password.data(),login->user.c_str(),CONNECT_TEMPORARY);
if(result.error) return result;
}
if(canceled) return result;
if(!profile.target.folder.empty())
{
WIN32_FIND_DATAW first{};
const auto listing=FindFirstFileW((profile.target.folder/L"*").c_str(),&first);
if(listing!=INVALID_HANDLE_VALUE) FindClose(listing);
else
{
const auto error=GetLastError();
if(error!=ERROR_FILE_NOT_FOUND && error!=ERROR_NO_MORE_FILES) result.error=error;
}
if(!result.error) result.folder=profile.target.folder;
}
else
{
auto server=profile.target.server;
DWORD resume{};
do
{
struct Buffer { BYTE *data{}; ~Buffer(){if(data) NetApiBufferFree(data);} } buffer;
DWORD read{},total{};
const auto previous=resume;
result.error=NetShareEnum(server.data(),1,&buffer.data,MAX_PREFERRED_LENGTH,&read,&total,&resume);
if(result.error!=NERR_Success && result.error!=ERROR_MORE_DATA) return result;
const auto rows=reinterpret_cast<const SHARE_INFO_1*>(buffer.data);
for(DWORD i=0;i<read && !canceled;++i)
{
const auto &row=rows[i];
const std::wstring_view name=row.shi1_netname?row.shi1_netname:L"";
if(!name.empty() && (row.shi1_type&shareTypeMask)==STYPE_DISKTREE &&
!(row.shi1_type&STYPE_SPECIAL) && name.back()!=L'$' &&
name.find_first_of(L"/\\") == name.npos)
result.shares.emplace_back(name);
}
if(result.error==ERROR_MORE_DATA && previous==resume) return result;
} while(result.error==ERROR_MORE_DATA && !canceled);
std::sort(result.shares.begin(),result.shares.end(),[](const auto &a,const auto &b) {
return CompareStringOrdinal(a.c_str(),-1,b.c_str(),-1,TRUE)==CSTR_LESS_THAN;
});
}
if(!result.error && !canceled && explicitLogin && explicitLogin->remember)
result.credentialError=saveCredential(profile,*explicitLogin);
return result;
}
bool closeRequest(UINT message,WPARAM command)
{
return message==WM_CLOSE || (message==WM_COMMAND && LOWORD(command)==IDCANCEL);
}
struct EditProfile
{
Profile profile;
std::optional<std::vector<Profile>> saved;
};
INT_PTR CALLBACK editDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" SMB connection ",false,{editFooter}))
return painted;
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
const auto &edit=*reinterpret_cast<EditProfile*>(lp);
prepareCopyDialog(dialog);
layoutDialogContent(dialog,nameLabel);
for(const auto id:{nameLabel,addressLabel})
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SendDlgItemMessageW(dialog,nameField,EM_SETLIMITTEXT,255,0);
SendDlgItemMessageW(dialog,addressField,EM_SETLIMITTEXT,MAX_PATH-1,0);
SetDlgItemTextW(dialog,nameField,edit.profile.name.c_str());
SetDlgItemTextW(dialog,addressField,profileAddress(edit.profile).c_str());
layoutDialogButtons(dialog,editFooter,{IDOK,IDCANCEL});
return TRUE;
}
if(closeRequest(message,wp))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &edit=*reinterpret_cast<EditProfile*>(GetWindowLongPtrW(dialog,DWLP_USER));
auto name=trimFilesField(shortcutField(dialog,nameField));
auto target=parseTarget(shortcutField(dialog,addressField));
const bool validName=!name.empty() && name.find_first_of(L"\r\n\t")==name.npos;
if(!validName || !target)
{
showFilesNotice(dialog,!validName?L"Enter a connection name on one line.":
L"Enter a server name or a UNC folder such as \\\\server\\share.",L"SMB connection");
SetFocus(GetDlgItem(dialog,validName?addressField:nameField));
return TRUE;
}
const bool creating=edit.profile.id.empty();
Profile next{creating?ks::lan::randomHex(16):edit.profile.id,std::move(name),std::move(*target)};
DWORD error=ERROR_SUCCESS;
edit.saved=updateProfiles([&](auto &profiles) {
const auto previous=std::find_if(profiles.begin(),profiles.end(),[&](const auto &entry){return entry.id==next.id;});
if(std::any_of(profiles.begin(),profiles.end(),[&](const auto &entry) {
return entry.id!=next.id && CompareStringOrdinal(entry.name.c_str(),-1,next.name.c_str(),-1,TRUE)==CSTR_EQUAL;
}))
{
error=ERROR_ALREADY_EXISTS;
return false;
}
if(creating) profiles.push_back(next);
else
{
if(previous==profiles.end()) {error=ERROR_NOT_FOUND;return false;}
if(!sameServer(*previous,next) && (error=deleteCredential(*previous))) return false;
*previous=next;
}
return true;
});
if(!edit.saved)
{
const auto detail=error==ERROR_ALREADY_EXISTS?L"A connection with this name already exists.":
error?errorText(error):L"Could not save the SMB connection.";
showFilesNotice(dialog,detail.c_str(),L"SMB connection");
return TRUE;
}
edit.profile=std::move(next);
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
struct LoginPrompt
{
const Profile &profile;
Credentials &login;
};
INT_PTR CALLBACK loginDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" SMB sign in ",false,{loginFooter}))
return painted;
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
const auto &prompt=*reinterpret_cast<LoginPrompt*>(lp);
prepareCopyDialog(dialog);
layoutDialogContent(dialog,loginLabel);
for(const auto id:{loginLabel,userLabel,passwordLabel,rememberField})
SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SetDlgItemTextW(dialog,loginLabel,(L"Server "+prompt.profile.target.server).c_str());
SendDlgItemMessageW(dialog,userField,EM_SETLIMITTEXT,256,0);
SendDlgItemMessageW(dialog,passwordField,EM_SETLIMITTEXT,CRED_MAX_CREDENTIAL_BLOB_SIZE/sizeof(wchar_t),0);
installFarCheckbox(GetDlgItem(dialog,rememberField),FarCheckboxSurface::gray);
layoutDialogButtons(dialog,loginFooter,{IDOK,IDCANCEL});
return TRUE;
}
const auto clearPassword=[&]
{
SetDlgItemTextW(dialog,passwordField,L"");
SendDlgItemMessageW(dialog,passwordField,EM_EMPTYUNDOBUFFER,0,0);
};
if(closeRequest(message,wp))
{
clearPassword();
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &login=reinterpret_cast<LoginPrompt*>(GetWindowLongPtrW(dialog,DWLP_USER))->login;
auto user=trimFilesField(shortcutField(dialog,userField));
if(user.empty())
{
showFilesNotice(dialog,L"Enter the SMB account name.",L"SMB sign in");
SetFocus(GetDlgItem(dialog,userField));
return TRUE;
}
login.user=std::move(user);
const auto field=GetDlgItem(dialog,passwordField);
const auto length=GetWindowTextLengthW(field);
login.password.resize(static_cast<size_t>(length)+1);
GetWindowTextW(field,login.password.data(),length+1);
login.remember=IsDlgButtonChecked(dialog,rememberField)==BST_CHECKED;
clearPassword();
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
struct PendingConnection
{
Profile profile;
std::atomic_bool canceled{};
std::promise<Connection> result;
std::future<Connection> completion=result.get_future();
};
std::optional<Profile> findProfile(const fs::path &id)
{
const auto profiles=readProfiles();
const auto match=std::find_if(profiles.begin(),profiles.end(),[&](const auto &profile) {
return ks::wide(profile.id)==id.native();
});
return match==profiles.end()?std::nullopt:std::optional{*match};
}
std::optional<Profile> selectedProfile(const Panel &panel)
{
if(!panel.listing || !panel.listing->smb || !panel.listing->smb->server.empty() || panel.scan.valid() || panel.smbPending) return {};
const auto row=currentPanelRow(panel);
return row==LB_ERR?std::nullopt:findProfile(panel.rows[row]);
}
void showProfiles(Panel &panel,const std::vector<Profile> &profiles,fs::path selection={})
{
PanelListing listing{SmbListing{}};
listing.rows.reserve(profiles.size());
for(const auto &profile:profiles)
listing.rows.emplace_back(ks::wide(profile.id),profile.name+L" · "+profileAddress(profile));
openPanelListing(panel,std::move(listing),std::move(selection));
}
void refreshProfiles(Panel &panel,const std::vector<Profile> &profiles,fs::path selection={})
{
for(auto &other:panels)
if(other.listing && other.listing->smb && other.listing->smb->server.empty() && !other.smbPending && !other.scan.valid())
showProfiles(other,profiles,&other==&panel?selection:fs::path{});
}
void openProfile(Panel &panel,Profile profile,bool withLogin)
{
if(panel.smbPending || panel.scan.valid()) return;
const auto owner=GetParent(panel.list);
std::shared_ptr<Credentials> login;
if(withLogin)
{
login=std::make_shared<Credentials>();
LoginPrompt prompt{profile,*login};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(123),owner,loginDialog,
reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
}
auto pending=std::make_shared<PendingConnection>();
pending->profile=std::move(profile);
try
{
std::thread([pending,login=std::move(login),owner] {
Connection connection;
try {connection=connect(pending->profile,login.get(),pending->canceled);}
catch(const std::exception &) {connection.error=ERROR_GEN_FAILURE;}
pending->result.set_value(std::move(connection));
PostMessageW(owner,directoryScanReady,0,0);
}).detach();
}
catch(const std::system_error &error)
{
setStatus(L"Could not start SMB connection: "+fileError(error));
return;
}
panel.smbPending=std::move(pending);
if(&panel==&panels[active]) showFileDetails(panel);
}
}
void cancelSmbConnection(Panel &panel)
{
if(auto pending=std::exchange(panel.smbPending,{})) pending->canceled=true;
}
void showSmbProfiles(Panel &panel)
{
smb::showProfiles(panel,smb::readProfiles());
}
void refreshSmbPanel(Panel &panel)
{
if(panel.scan.valid() || panel.smbPending) return;
if(panel.listing->smb->server.empty()) showSmbProfiles(panel);
else if(auto profile=smb::findProfile(ks::wide(panel.listing->smb->serverId));profile && profile->target.folder.empty())
smb::openProfile(panel,std::move(*profile),false);
else showSmbProfiles(panel);
}
void backSmbPanel(Panel &panel)
{
if(panel.smbPending)
{
cancelSmbConnection(panel);
setStatus(L"SMB connection canceled.");
}
else if(!panel.listing->smb->server.empty())
smb::showProfiles(panel,smb::readProfiles(),ks::wide(panel.listing->smb->serverId));
else closePanelListing(panel);
}
void enterSmbPanel(Panel &panel)
{
if(panel.scan.valid() || panel.smbPending) return;
if(panel.listing->smb->server.empty())
{
if(auto profile=smb::selectedProfile(panel)) smb::openProfile(panel,std::move(*profile),false);
return;
}
const auto row=currentPanelRow(panel);
if(row==LB_ERR) return;
const auto &name=panel.rows[row];
if(name==L"..") backSmbPanel(panel);
else openOn(panel,fs::path(panel.listing->smb->server+L"\\"+name.native()),false,{});
}
void editSmbProfile(Panel &panel,bool create)
{
if(!panel.listing || !panel.listing->smb || !panel.listing->smb->server.empty() || panel.smbPending || panel.scan.valid()) return;
const auto profile=create?std::optional{smb::Profile{}}:smb::selectedProfile(panel);
if(!profile) return;
smb::EditProfile edit{*profile};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(122),GetParent(panel.list),smb::editDialog,
reinterpret_cast<LPARAM>(&edit))==IDOK)
smb::refreshProfiles(panel,*edit.saved,ks::wide(edit.profile.id));
}
void removeSmbProfile(Panel &panel)
{
const auto selected=smb::selectedProfile(panel);
if(!selected) return;
const auto owner=GetParent(panel.list);
const auto detail=L"Remove "+selected->name+L" and its saved credentials?";
if(showFilesNotice(owner,detail.c_str(),L"Remove SMB connection",{.confirm=true})!=IDYES) return;
DWORD error=ERROR_SUCCESS;
const auto updated=smb::updateProfiles([&](auto &profiles) {
const auto entry=std::find_if(profiles.begin(),profiles.end(),[&](const auto &profile){return profile.id==selected->id;});
if(entry==profiles.end()) return true;
if((error=smb::deleteCredential(*entry))) return false;
profiles.erase(entry);
return true;
});
if(updated) smb::refreshProfiles(panel,*updated);
else
{
const auto failure=error?smb::errorText(error):L"Could not remove the saved connection.";
showFilesNotice(owner,failure.c_str(),L"Remove SMB connection");
}
}
void signInSmbProfile(Panel &panel)
{
if(auto profile=smb::selectedProfile(panel)) smb::openProfile(panel,std::move(*profile),true);
}
void collectSmbConnections(HWND owner)
{
for(auto &panel:panels)
{
if(!panel.smbPending || panel.smbPending->completion.wait_for(std::chrono::seconds(0))!=std::future_status::ready)
continue;
auto pending=std::exchange(panel.smbPending,{});
const auto result=pending->completion.get();
const auto &profile=pending->profile;
if(result.error)
{
auto detail=smb::profileAddress(profile)+L"\r\n\r\n"+smb::errorText(result.error);
if(result.error==ERROR_ACCESS_DENIED || result.error==ERROR_LOGON_FAILURE ||
result.error==ERROR_INVALID_PASSWORD || result.error==ERROR_BAD_USERNAME)
detail+=L"\r\n\r\nUse Sign in to try a different account.";
showFilesNotice(owner,detail.c_str(),L"Could not open SMB connection",{.tone=FilesNoticeTone::warning});
if(&panel==&panels[active]) showFileDetails(panel);
continue;
}
if(result.credentialError)
{
const auto detail=L"Connected, but Windows Credential Manager did not save the account.\r\n\r\n"+
smb::errorText(result.credentialError);
showFilesNotice(owner,detail.c_str(),L"SMB sign in",{.tone=FilesNoticeTone::warning});
}
if(!result.folder.empty()) openOn(panel,result.folder,false,{});
else
{
PanelListing listing{SmbListing{profile.id,profile.target.server}};
listing.rows.emplace_back(L"..",L"..");
for(const auto &share:result.shares) listing.rows.emplace_back(share,L"["+share+L"]");
const auto selectFirst=profile.id!=panel.listing->smb->serverId && !result.shares.empty();
openPanelListing(panel,std::move(listing),selectFirst?fs::path(result.shares.front()):fs::path{});
}
}
}
+635
View File
@@ -0,0 +1,635 @@
constexpr int spacePath=488,spaceTree=489,spaceStatus=490,spaceFooter=491;
constexpr int spaceStop=492,spaceRescan=493,spaceView=494;
constexpr int spaceCapacity=495,spaceScope=496,spaceMapButton=497,spaceMap=498;
constexpr int spaceSunburstButton=499,spaceSunburstList=500,spaceSunburstLabel=501;
constexpr UINT_PTR spaceUpdateTimer=1;
constexpr UINT_PTR spaceVolumeTimer=2;
constexpr size_t spaceBatchSize=256;
constexpr std::initializer_list<int> spaceFooterButtons{spaceStop,spaceRescan,spaceView,IDOK,IDCANCEL};
struct SpaceVolume
{
fs::path root;
std::optional<std::pair<uint64_t,uint64_t>> capacity;
};
std::future<SpaceVolume> readSpaceVolume(const fs::path &folder)
{
std::packaged_task<SpaceVolume()> task([folder] {
SpaceVolume result;
std::wstring root(32768,L'\0');
if(GetVolumePathNameW(folder.c_str(),root.data(),static_cast<DWORD>(root.size())))
{
root.resize(wcslen(root.c_str()));
result.root=fs::path(std::move(root));
}
ULARGE_INTEGER total{},free{};
if(GetDiskFreeSpaceExW(result.root.empty()?folder.c_str():result.root.c_str(),&free,&total,nullptr))
result.capacity=std::pair{total.QuadPart,free.QuadPart};
return result;
});
auto result=task.get_future();
std::thread(std::move(task)).detach();
return result;
}
struct SpaceAllocation
{
FolderSize known;
size_t measured{}, unavailable{};
void add(std::optional<uint64_t> size)
{
if(size)
{
++measured;
known.add(*size);
}
else ++unavailable;
}
};
struct SpaceTile
{
RECT box;
size_t node;
};
#include "files_ntfs_space.inl"
struct SpaceSector
{
size_t node;
unsigned ring;
double start,end;
};
enum class SpaceDisplay { tree, treemap, sunburst };
struct SpaceEvent
{
fs::path path;
std::optional<FileInfo> item;
std::optional<uint64_t> allocated;
};
struct SpaceRun
{
std::stop_source stop;
std::mutex mutex;
std::deque<std::vector<SpaceEvent>> pending;
FolderSize result;
bool finished{}, stopped{}, indexed{};
};
std::shared_ptr<SpaceRun> startSpaceRun(const fs::path &root,const fs::path &mount)
{
auto run=std::make_shared<SpaceRun>();
std::thread([run,root,mount] {
std::vector<SpaceEvent> batch;
auto lastUpdate=GetTickCount64();
const auto publish=[&] {
if(batch.empty()) return;
std::lock_guard lock(run->mutex);
run->pending.push_back(std::move(batch));
batch.clear();
lastUpdate=GetTickCount64();
};
FolderSize total;
const auto stop=run->stop.get_token();
try
{
FilesConnection host(nullptr);
const bool volume=!mount.empty();
std::optional<NtfsSpaceWalk> ntfs;
if(volume && isNtfsVolume(mount)) ntfs.emplace(root,mount,stop);
bool indexReported=false;
total=measureFolder(root,stop,[&](const fs::path &directory,const FileVisitor &visit) {
if(ntfs)
{
const auto result=ntfs->list(directory,visit,stop,host);
if(!indexReported && ntfs->usedMft())
{
std::lock_guard lock(run->mutex);
run->indexed=indexReported=true;
}
return result;
}
if(volume && directory==root) return !stop.stop_requested() && listFiles(host,directory,visit);
return listMeasuredDirectory(host,directory,visit,stop);
},[&](const fs::path &path,const FileInfo *info) {
const auto allocate=info && !(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT));
const auto allocation=allocate?(info->allocated?info->allocated:allocatedFileBytes(path,info->attributes)):
std::nullopt;
batch.push_back({path,info?std::optional<FileInfo>(*info):std::nullopt,allocation});
if(batch.size()>=spaceBatchSize || GetTickCount64()-lastUpdate>=80) publish();
});
publish();
}
catch(const std::exception &) {total.partial=true;}
std::lock_guard lock(run->mutex);
run->result=total;
run->stopped=stop.stop_requested();
run->finished=true;
}).detach();
return run;
}
struct SpaceNode
{
fs::path path;
FolderSize size;
SpaceAllocation allocated;
size_t parent{};
std::vector<size_t> children;
HTREEITEM item{};
bool folder{}, link{}, expanded{};
};
struct SpaceAnalyzer
{
fs::path folder, root, selected;
SpaceVolume volume;
std::future<SpaceVolume> pendingVolume;
bool selectedFolder{}, volumeScope{};
SpaceDisplay display{SpaceDisplay::tree};
std::shared_ptr<SpaceRun> run;
std::vector<SpaceNode> nodes;
std::map<fs::path,size_t> directories;
size_t files{}, mapFolder{}, selectedTile{};
std::vector<SpaceTile> tiles;
std::vector<SpaceSector> sectors;
ULONGLONG lastMapUpdate{};
bool scanning{}, hasResults{};
};
void layoutSpaceAnalyzer(HWND dialog)
{
RECT bounds{};
GetClientRect(dialog,&bounds);
const auto frame=dialogFrameMetrics(GetDpiForWindow(dialog));
const auto inset=frame.content();
const auto width=std::max(1L,bounds.right-2*inset);
const auto place=[&](int id,int top,int height) {
SetWindowPos(GetDlgItem(dialog,id),nullptr,inset,top,width,height,SWP_NOZORDER|SWP_NOACTIVATE);
};
auto top=dialogListInset(frame,textHeight);
place(spacePath,top,textHeight);
top+=textHeight;
place(spaceCapacity,top,textHeight);
top+=textHeight+dialogRowGap();
const auto buttonHeight=textHeight;
auto x=inset;
for(const auto id:{spaceScope,spaceMapButton,spaceSunburstButton})
{
const auto button=GetDlgItem(dialog,id);
const auto width=std::max(12L*cellWidth,farDialogButtonWidth(button));
SetWindowPos(button,nullptr,x,top,width,buttonHeight,SWP_NOZORDER|SWP_NOACTIVATE);
x+=width+dialogColumnGap();
}
top+=buttonHeight+dialogRowGap();
place(spaceTree,top,9*textHeight);
const auto state=reinterpret_cast<const SpaceAnalyzer *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(state && state->display==SpaceDisplay::sunburst)
{
const auto graphWidth=width*3/5;
const auto gap=dialogColumnGap();
SetWindowPos(GetDlgItem(dialog,spaceSunburstLabel),nullptr,inset+graphWidth,top-textHeight-dialogRowGap(),
width-graphWidth,textHeight,SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(GetDlgItem(dialog,spaceMap),nullptr,inset,top,graphWidth-gap,9*textHeight,
SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(GetDlgItem(dialog,spaceSunburstList),nullptr,inset+graphWidth,top,width-graphWidth,
9*textHeight,SWP_NOZORDER|SWP_NOACTIVATE);
}
else place(spaceMap,top,9*textHeight);
top+=9*textHeight+dialogRowGap();
place(spaceStatus,top,textHeight);
place(spaceFooter,top+textHeight+dialogRowGap(),1);
layoutDialogButtons(dialog,spaceFooter,spaceFooterButtons);
}
HTREEITEM insertSpaceNode(HWND tree,SpaceAnalyzer &state,size_t index)
{
auto &node=state.nodes[index];
TVINSERTSTRUCTW insert{};
insert.hParent=index?state.nodes[node.parent].item:TVI_ROOT;
insert.hInsertAfter=TVI_LAST;
insert.item.mask=TVIF_TEXT|TVIF_PARAM|TVIF_CHILDREN;
insert.item.pszText=LPSTR_TEXTCALLBACKW;
insert.item.lParam=static_cast<LPARAM>(index);
insert.item.cChildren=node.folder && !node.link?I_CHILDRENCALLBACK:0;
node.item=TreeView_InsertItem(tree,&insert);
return node.item;
}
void expandSpaceNode(HWND tree,SpaceAnalyzer &state,size_t index)
{
auto &node=state.nodes[index];
if(node.expanded) return;
node.expanded=true;
for(auto child:node.children) insertSpaceNode(tree,state,child);
}
void addSpaceEvent(HWND tree,SpaceAnalyzer &state,SpaceEvent event)
{
if(!event.item)
{
const auto directory=state.directories.find(event.path);
if(directory==state.directories.end()) return;
for(auto i=directory->second;;i=state.nodes[i].parent)
{
state.nodes[i].size.partial=true;
if(!i) break;
}
return;
}
const auto parent=state.directories.find(event.path.parent_path());
if(parent==state.directories.end()) return;
const auto index=state.nodes.size();
const bool folder=(event.item->attributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
const bool link=(event.item->attributes&FILE_ATTRIBUTE_REPARSE_POINT)!=0;
const auto bytes=folder || link?0:event.item->size;
if(folder) state.directories.emplace(event.path,index);
else ++state.files;
state.nodes.push_back({.path=std::move(event.path),.size={bytes,false},.parent=parent->second,
.folder=folder,.link=link});
if(!folder && !link) state.nodes[index].allocated.add(event.allocated);
auto &parentNode=state.nodes[parent->second];
parentNode.children.push_back(index);
if(parentNode.item && parentNode.expanded)
{
insertSpaceNode(tree,state,index);
if(parentNode.children.size()==1) TreeView_Expand(tree,parentNode.item,TVE_EXPAND);
}
for(auto i=parent->second;;i=state.nodes[i].parent)
{
state.nodes[i].size.add(bytes);
if(!folder && !link) state.nodes[i].allocated.add(event.allocated);
if(!i) break;
}
}
std::wstring spaceLogicalSize(const SpaceNode &node)
{
return formatSize(node.size.bytes)+(node.size.partial?L"+ logical":L" logical");
}
std::wstring spaceAllocatedSize(const SpaceNode &node)
{
const auto &allocation=node.allocated;
if(!allocation.measured && allocation.unavailable) return L"— on disk";
auto result=formatSize(allocation.known.bytes);
if(allocation.unavailable || allocation.known.partial || node.size.partial) result+=L"+";
return result+L" on disk";
}
std::wstring spaceNodeText(const SpaceAnalyzer &state,size_t index)
{
const auto &node=state.nodes[index];
const auto &parent=state.nodes[node.parent];
auto name=node.path.filename().native();
if(name.empty()) name=node.path.native();
if(name.size()>196)
{
name.resize(196);
if(name.back()>=0xD800 && name.back()<=0xDBFF) name.pop_back();
name+=L"…";
}
if(!state.hasResults) return name;
if(node.link) return name+L" [link]";
auto result=name+L" — "+spaceLogicalSize(node)+L" · "+spaceAllocatedSize(node);
if(parent.size.bytes)
{
wchar_t share[48]{};
swprintf_s(share,L" (%.1f%%)",100.0*static_cast<double>(node.size.bytes)/static_cast<double>(parent.size.bytes));
result+=share;
}
return result;
}
std::optional<size_t> selectedSpaceNode(HWND tree,const SpaceAnalyzer &state)
{
TVITEMW item{};
item.mask=TVIF_PARAM;
item.hItem=TreeView_GetSelection(tree);
if(item.hItem && TreeView_GetItem(tree,&item) && static_cast<size_t>(item.lParam)<state.nodes.size())
return static_cast<size_t>(item.lParam);
return {};
}
#include "files_space_map.inl"
void updateSpaceTree(HWND dialog,SpaceAnalyzer &state)
{
const auto tree=GetDlgItem(dialog,spaceTree);
const auto budget=GetTickCount64()+15;
bool finished=false,stopped=false,changed=false,indexed=false;
do
{
std::vector<SpaceEvent> batch;
{
std::lock_guard lock(state.run->mutex);
indexed=state.run->indexed;
if(!state.run->pending.empty())
{
batch=std::move(state.run->pending.front());
state.run->pending.pop_front();
}
else if(state.run->finished)
{
finished=true;
stopped=state.run->stopped;
state.nodes[0].size.partial|=state.run->result.partial;
}
}
if(batch.empty()) break;
if(!changed) SendMessageW(tree,WM_SETREDRAW,FALSE,0);
changed=true;
for(auto &event:batch) addSpaceEvent(tree,state,std::move(event));
} while(GetTickCount64()<budget);
if(finished) state.scanning=false;
if(changed) SendMessageW(tree,WM_SETREDRAW,TRUE,0);
if(state.display!=SpaceDisplay::tree && (finished || (changed && GetTickCount64()-state.lastMapUpdate>=200)))
refreshSpaceChart(GetDlgItem(dialog,spaceMap),state);
if(changed || finished) InvalidateRect(tree,nullptr,FALSE);
const bool stopping=state.run->stop.stop_requested();
auto status=finished?(stopped?L"Stopped · partial":state.nodes[0].size.partial?L"Partial results":L"Complete"):
stopping?L"Stopping…":L"Scanning…";
const auto &allocation=state.nodes[0].allocated;
auto label=std::wstring(status)+L" · "+std::to_wstring(state.files)+L" files";
if(indexed) label+=L" · NTFS index";
if(allocation.unavailable || allocation.known.partial) label+=L" · on-disk sizes partial";
else label+=state.display==SpaceDisplay::treemap?L" · logical size by area":
state.display==SpaceDisplay::sunburst?L" · logical size by angle":L" · logical shares of parent";
SetDlgItemTextW(dialog,spaceStatus,label.c_str());
if(finished)
{
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE);
EnableWindow(GetDlgItem(dialog,spaceScope),!state.volume.root.empty() &&
!sameVolumeRoot(state.folder,state.volume.root));
KillTimer(dialog,spaceUpdateTimer);
}
}
void resetSpaceResults(HWND dialog,SpaceAnalyzer &state,bool scanning)
{
const auto tree=GetDlgItem(dialog,spaceTree);
TreeView_DeleteAllItems(tree);
state.nodes.clear();
state.nodes.push_back({.path=state.root,.folder=true,.expanded=true});
state.directories.clear();
state.directories.emplace(state.root,0);
state.files=0;
state.mapFolder=0;
state.tiles.clear();
state.sectors.clear();
state.selectedTile=0;
state.scanning=scanning;
state.hasResults=scanning;
TreeView_SelectItem(tree,insertSpaceNode(tree,state,0));
if(state.display!=SpaceDisplay::tree) refreshSpaceChart(GetDlgItem(dialog,spaceMap),state);
EnableWindow(GetDlgItem(dialog,spaceView),FALSE);
EnableWindow(GetDlgItem(dialog,IDOK),state.display==SpaceDisplay::tree);
}
void prepareSpaceScope(HWND dialog,SpaceAnalyzer &state)
{
state.run.reset();
const auto scope=state.volumeScope?state.volume.root:state.folder;
state.root=folderPathWithoutSeparator(scope);
SetDlgItemTextW(dialog,spacePath,scope.c_str());
SetDlgItemTextW(dialog,spaceScope,state.volumeScope?L"&Folder":L"Vo&lume");
SetDlgItemTextW(dialog,spaceRescan,L"St&art");
SetDlgItemTextW(dialog,spaceStatus,L"Ready to scan");
EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE);
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
resetSpaceResults(dialog,state,false);
layoutSpaceAnalyzer(dialog);
}
void updateSpaceVolume(HWND dialog,SpaceAnalyzer &state)
{
if(!state.pendingVolume.valid() ||
state.pendingVolume.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
try {state.volume=state.pendingVolume.get();}
catch(const std::exception &) {}
KillTimer(dialog,spaceVolumeTimer);
std::wstring caption=L"Volume capacity unavailable";
if(const auto capacity=state.volume.capacity)
{
caption=L"Capacity "+formatSize(capacity->first)+L" · Free "+formatSize(capacity->second);
if(!state.volume.root.empty()) caption+=L" · "+state.volume.root.native();
}
SetDlgItemTextW(dialog,spaceCapacity,caption.c_str());
EnableWindow(GetDlgItem(dialog,spaceScope),
!state.volume.root.empty() && !sameVolumeRoot(state.folder,state.volume.root));
prepareSpaceScope(dialog,state);
}
void rescanSpace(HWND dialog,SpaceAnalyzer &state)
{
resetSpaceResults(dialog,state,true);
SetDlgItemTextW(dialog,spaceRescan,L"&Rescan");
EnableWindow(GetDlgItem(dialog,spaceRescan),FALSE);
EnableWindow(GetDlgItem(dialog,spaceScope),FALSE);
try
{
const bool volume=state.volumeScope || sameVolumeRoot(state.root,state.volume.root);
state.run=startSpaceRun(state.root,volume?state.volume.root:fs::path{});
EnableWindow(GetDlgItem(dialog,spaceStop),TRUE);
SetTimer(dialog,spaceUpdateTimer,60,nullptr);
updateSpaceTree(dialog,state);
}
catch(const std::exception &)
{
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE);
state.scanning=false;
EnableWindow(GetDlgItem(dialog,spaceScope),!state.volume.root.empty() &&
!sameVolumeRoot(state.folder,state.volume.root));
SetDlgItemTextW(dialog,spaceStatus,L"Could not start space analysis.");
}
}
INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
auto &state=*reinterpret_cast<SpaceAnalyzer *>(lp);
SetWindowLongPtrW(dialog,DWLP_USER,lp);
prepareTextDialog(dialog);
SetDlgItemTextW(dialog,spacePath,state.folder.c_str());
SetDlgItemTextW(dialog,spaceCapacity,L"Reading volume capacity…");
const auto tree=GetDlgItem(dialog,spaceTree);
SetWindowSubclass(GetDlgItem(dialog,spaceMap),spaceMapInput,1,reinterpret_cast<DWORD_PTR>(&state));
SetWindowSubclass(GetDlgItem(dialog,spaceSunburstList),spaceSunburstListKeys,1,reinterpret_cast<DWORD_PTR>(&state));
TreeView_SetBkColor(tree,RGB(255,255,255));
TreeView_SetTextColor(tree,RGB(0,0,0));
layoutSpaceAnalyzer(dialog);
const auto inset=dialogFrameMetrics(GetDpiForWindow(dialog)).content();
// Rescan is one character wider than the initial Start label.
const auto minimum=dialogButtonGroupWidth(dialog,spaceFooterButtons)+cellWidth+2*inset;
FilesModalDialog::fitWidthToOwner(dialog,minimum,layoutSpaceAnalyzer);
SendMessageW(dialog,DM_SETDEFID,IDCANCEL,0);
resetSpaceResults(dialog,state,false);
EnableWindow(GetDlgItem(dialog,spaceScope),FALSE);
EnableWindow(GetDlgItem(dialog,spaceRescan),FALSE);
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
try
{
state.pendingVolume=readSpaceVolume(state.folder);
SetTimer(dialog,spaceVolumeTimer,60,nullptr);
updateSpaceVolume(dialog,state);
}
catch(const std::exception &)
{
SetDlgItemTextW(dialog,spaceCapacity,L"Volume capacity unavailable");
prepareSpaceScope(dialog,state);
}
SetFocus(tree);
return FALSE;
}
const auto state=reinterpret_cast<SpaceAnalyzer *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!state) return FALSE;
const auto tree=GetDlgItem(dialog,spaceTree);
if(message==WM_DRAWITEM && wp==spaceMap)
{
const auto &paint=*reinterpret_cast<const DRAWITEMSTRUCT *>(lp);
if(state->display==SpaceDisplay::sunburst) paintSunburst(paint,*state);
else paintSpaceMap(paint,*state);
return TRUE;
}
if(message==WM_TIMER && wp==spaceVolumeTimer)
{
updateSpaceVolume(dialog,*state);
return TRUE;
}
if(message==WM_TIMER && wp==spaceUpdateTimer)
{
updateSpaceTree(dialog,*state);
return TRUE;
}
if(message==WM_NOTIFY)
{
const auto *notification=reinterpret_cast<const NMHDR *>(lp);
if(notification->hwndFrom==tree)
{
if(notification->code==TVN_GETDISPINFOW)
{
auto &item=reinterpret_cast<NMTVDISPINFOW *>(lp)->item;
const auto index=static_cast<size_t>(item.lParam);
if(index>=state->nodes.size()) return TRUE;
const auto &node=state->nodes[index];
if(item.mask&TVIF_CHILDREN) item.cChildren=node.folder && !node.link &&
(state->scanning || !node.children.empty())?1:0;
if((item.mask&TVIF_TEXT) && item.pszText && item.cchTextMax>0)
{
const auto text=spaceNodeText(*state,index);
lstrcpynW(item.pszText,text.c_str(),item.cchTextMax);
}
return TRUE;
}
if(notification->code==TVN_ITEMEXPANDINGW)
{
const auto &item=*reinterpret_cast<const NMTREEVIEWW *>(lp);
const auto index=static_cast<size_t>(item.itemNew.lParam);
if(item.action==TVE_EXPAND && index<state->nodes.size()) expandSpaceNode(tree,*state,index);
}
if(notification->code==TVN_SELCHANGEDW)
{
const auto selected=selectedSpaceNode(tree,*state);
if(state->display==SpaceDisplay::tree)
{
EnableWindow(GetDlgItem(dialog,spaceView),selected && !state->nodes[*selected].folder);
EnableWindow(GetDlgItem(dialog,IDOK),selected.has_value());
}
}
}
}
if(message==WM_COMMAND)
{
const auto command=LOWORD(wp);
if(command==spaceStop && IsWindowEnabled(GetDlgItem(dialog,spaceStop)))
{
state->run->stop.request_stop();
EnableWindow(GetDlgItem(dialog,spaceStop),FALSE);
updateSpaceTree(dialog,*state);
return TRUE;
}
if(command==spaceScope && IsWindowEnabled(GetDlgItem(dialog,spaceScope)))
{
state->volumeScope=!state->volumeScope;
prepareSpaceScope(dialog,*state);
return TRUE;
}
if(command==spaceMapButton || command==spaceSunburstButton)
{
const auto chart=command==spaceMapButton?SpaceDisplay::treemap:SpaceDisplay::sunburst;
setSpaceDisplay(dialog,*state,state->display==chart?SpaceDisplay::tree:chart);
if(state->run) updateSpaceTree(dialog,*state);
return TRUE;
}
if(command==spaceSunburstList && state->display==SpaceDisplay::sunburst)
{
updateSunburstSelection(dialog,*state);
if(HIWORD(wp)==LBN_DBLCLK)
if(const auto selected=sunburstSelection(dialog,*state))
finishSpaceSelection(dialog,*state,*selected,IDOK);
return TRUE;
}
if(command==spaceRescan && IsWindowEnabled(GetDlgItem(dialog,spaceRescan)))
{
rescanSpace(dialog,*state);
return TRUE;
}
if(command==IDOK || command==spaceView)
{
const auto selected=state->display==SpaceDisplay::sunburst?sunburstSelection(dialog,*state):
state->display==SpaceDisplay::tree?selectedSpaceNode(tree,*state):std::nullopt;
if(selected) finishSpaceSelection(dialog,*state,*selected,command);
return TRUE;
}
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(dialog,IDCANCEL);
return TRUE;
}
if(message==WM_DESTROY)
{
if(state->run) state->run->stop.request_stop();
KillTimer(dialog,spaceUpdateTimer);
KillTimer(dialog,spaceVolumeTimer);
}
return paintCopyDialog(dialog,message,wp,lp,L" Space Analyzer ",false,{spaceFooter});
}
void openSpaceAnalyzer(HWND owner,Panel &panel)
{
if(panel.peer || panel.ftp || panel.archive || panel.directory.empty())
{
setStatus(L"Space Analyzer requires an open local folder.");
return;
}
const auto origin=static_cast<int>(&panel-panels);
SpaceAnalyzer state{.folder=folderPathWithoutSeparator(panel.directory),.root=folderPathWithoutSeparator(panel.directory)};
const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(118),owner,
spaceAnalyzerDialog,reinterpret_cast<LPARAM>(&state));
if(answer==spaceView)
{
ks::files::openTextWindow(owner,state.selected,false,textWindowDialogs(),nullptr);
return;
}
if(answer!=IDOK) return;
if(quickViewWindow) toggleQuickView(owner);
if(terminalVisible) showTerminal(owner,false);
const auto index=1-origin;
auto &other=panels[index];
activatePanel(index);
panelClipboardContext=true;
if(state.selectedFolder) openOn(other,state.selected,true,{});
else revealLocalFile(other,state.selected);
}
+236
View File
@@ -0,0 +1,236 @@
void finishSpaceSelection(HWND dialog,SpaceAnalyzer &state,size_t selected,int action)
{
if(selected>=state.nodes.size()) return;
const auto &node=state.nodes[selected];
if(action==spaceView && node.folder) return;
state.selected=node.path;
state.selectedFolder=node.folder;
FilesModalDialog::finish(dialog,action);
}
void divideSpaceTiles(std::span<const size_t> nodes,std::span<const long double> prefix,RECT bounds,
LONG margin,std::vector<SpaceTile> &tiles)
{
const auto width=bounds.right-bounds.left, height=bounds.bottom-bounds.top;
if(width<margin || height<margin || nodes.empty()) return;
if(nodes.size()==1)
{
tiles.push_back({bounds,nodes.front()});
return;
}
const auto total=prefix.back()-prefix.front();
if(total<=0) return;
const auto middle=prefix.front()+total/2;
auto pivot=std::lower_bound(prefix.begin()+1,prefix.end()-1,middle);
if(pivot==prefix.end()-1 ||
(pivot>prefix.begin()+1 && middle-pivot[-1]<*pivot-middle)) --pivot;
const auto offset=static_cast<size_t>(pivot-prefix.begin());
const auto share=(*pivot-prefix.front())/total;
auto first=bounds, second=bounds;
if(width>=height)
{
const auto split=bounds.left+std::clamp(static_cast<LONG>(width*share+0.5L),1L,width-1);
first.right=second.left=split;
}
else
{
const auto split=bounds.top+std::clamp(static_cast<LONG>(height*share+0.5L),1L,height-1);
first.bottom=second.top=split;
}
divideSpaceTiles(nodes.first(offset),prefix.first(offset+1),first,margin,tiles);
divideSpaceTiles(nodes.subspan(offset),prefix.subspan(offset),second,margin,tiles);
}
void layoutSpaceMap(HWND map,SpaceAnalyzer &state)
{
state.lastMapUpdate=GetTickCount64();
const auto previous=state.selectedTile<state.tiles.size()?
state.tiles[state.selectedTile].node:std::numeric_limits<size_t>::max();
state.tiles.clear();
state.selectedTile=0;
if(state.mapFolder>=state.nodes.size()) return;
std::vector<size_t> items;
for(auto index:state.nodes[state.mapFolder].children)
if(state.nodes[index].size.bytes) items.push_back(index);
std::sort(items.begin(),items.end(),[&](size_t left,size_t right) {
const auto a=state.nodes[left].size.bytes, b=state.nodes[right].size.bytes;
return a!=b?a>b:left<right;
});
std::vector<long double> prefix{0};
prefix.reserve(items.size()+1);
for(auto index:items) prefix.push_back(prefix.back()+state.nodes[index].size.bytes);
RECT bounds{};
GetClientRect(map,&bounds);
const auto minimum=std::max(4,MulDiv(8,GetDpiForWindow(map),96));
divideSpaceTiles(items,prefix,bounds,minimum,state.tiles);
for(size_t index=0;index<state.tiles.size();++index)
if(state.tiles[index].node==previous)
{
state.selectedTile=index;
break;
}
InvalidateRect(map,nullptr,FALSE);
}
constexpr COLORREF spaceChartColors[]{RGB(158,203,218),RGB(167,205,172),RGB(230,198,142),
RGB(197,179,211),RGB(226,178,173),RGB(177,190,225)};
void paintEmptySpaceChart(const DRAWITEMSTRUCT &paint)
{
auto bounds=paint.rcItem;
SelectObject(paint.hDC,mono);
SetBkMode(paint.hDC,TRANSPARENT);
SetTextColor(paint.hDC,RGB(15,27,35));
DrawTextW(paint.hDC,L"No measured space to display",-1,&bounds,DT_CENTER|DT_VCENTER|DT_SINGLELINE);
}
void paintSpaceMap(const DRAWITEMSTRUCT &paint,const SpaceAnalyzer &state)
{
FillRect(paint.hDC,&paint.rcItem,GetSysColorBrush(COLOR_WINDOW));
SelectObject(paint.hDC,mono);
SetBkMode(paint.hDC,TRANSPARENT);
SetTextColor(paint.hDC,RGB(15,27,35));
if(state.tiles.empty())
{
paintEmptySpaceChart(paint);
return;
}
const auto brush=static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
const auto focused=GetFocus()==paint.hwndItem;
for(size_t index=0;index<state.tiles.size();++index)
{
const auto &tile=state.tiles[index];
if(!RectVisible(paint.hDC,&tile.box)) continue;
const auto &node=state.nodes[tile.node];
auto bounds=tile.box;
SetDCBrushColor(paint.hDC,spaceChartColors[index%std::size(spaceChartColors)]);
FillRect(paint.hDC,&bounds,brush);
FrameRect(paint.hDC,&bounds,GetSysColorBrush(COLOR_WINDOW));
if(focused && index==state.selectedTile)
{
InflateRect(&bounds,-2,-2);
DrawFocusRect(paint.hDC,&bounds);
bounds=tile.box;
}
InflateRect(&bounds,-std::max(3,cellWidth/2),-2);
if(bounds.right-bounds.left>=3*cellWidth && bounds.bottom-bounds.top>=textHeight)
{
const auto name=node.path.filename().native();
DrawTextW(paint.hDC,name.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
bounds.top+=textHeight;
if(bounds.bottom-bounds.top>=textHeight)
{
const auto logical=spaceLogicalSize(node);
DrawTextW(paint.hDC,logical.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
bounds.top+=textHeight;
if(bounds.bottom-bounds.top>=textHeight)
{
const auto allocated=spaceAllocatedSize(node);
DrawTextW(paint.hDC,allocated.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
}
}
}
}
}
#include "files_space_sunburst.inl"
void refreshSpaceChart(HWND map,SpaceAnalyzer &state)
{
if(state.display==SpaceDisplay::sunburst) layoutSunburst(map,state);
else layoutSpaceMap(map,state);
}
LRESULT CALLBACK spaceSunburstListKeys(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR payload)
{
auto &state=*reinterpret_cast<SpaceAnalyzer *>(payload);
if(message==WM_GETDLGCODE && lp && wp==VK_RETURN)
return DefSubclassProc(list,message,wp,lp)|DLGC_WANTMESSAGE;
if(message==WM_KEYDOWN && wp==VK_RETURN)
{
const auto dialog=GetParent(list);
if(const auto selected=sunburstSelection(dialog,state)) finishSpaceSelection(dialog,state,*selected,IDOK);
return 0;
}
return DefSubclassProc(list,message,wp,lp);
}
LRESULT CALLBACK spaceMapInput(HWND map,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR payload)
{
auto &state=*reinterpret_cast<SpaceAnalyzer *>(payload);
if(message==WM_SIZE && state.display!=SpaceDisplay::tree) refreshSpaceChart(map,state);
if(message==WM_SETFOCUS || message==WM_KILLFOCUS) InvalidateRect(map,nullptr,FALSE);
if(message==WM_LBUTTONDOWN)
{
SetFocus(map);
return 0;
}
if(message==WM_LBUTTONUP)
{
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
if(state.display==SpaceDisplay::sunburst)
{
if(const auto hit=hitSunburst(map,state,point))
finishSpaceSelection(GetParent(map),state,state.sectors[*hit].node,IDOK);
return 0;
}
for(const auto &tile:state.tiles)
if(PtInRect(&tile.box,point))
{
finishSpaceSelection(GetParent(map),state,tile.node,IDOK);
break;
}
return 0;
}
if(message==WM_GETDLGCODE)
{
const auto *key=reinterpret_cast<const MSG *>(lp);
return DLGC_WANTARROWS|(key && key->message==WM_KEYDOWN && wp==VK_RETURN?DLGC_WANTMESSAGE:0);
}
if(message==WM_KEYDOWN && state.display==SpaceDisplay::treemap && !state.tiles.empty())
{
if(wp==VK_RETURN)
{
finishSpaceSelection(GetParent(map),state,state.tiles[state.selectedTile].node,IDOK);
return 0;
}
if(wp==VK_DOWN || wp==VK_RIGHT || wp==VK_UP || wp==VK_LEFT)
{
auto &index=state.selectedTile;
if(wp==VK_DOWN || wp==VK_RIGHT) index=(index+1)%state.tiles.size();
else index=index?index-1:state.tiles.size()-1;
InvalidateRect(map,nullptr,FALSE);
return 0;
}
}
return DefSubclassProc(map,message,wp,lp);
}
void setSpaceDisplay(HWND dialog,SpaceAnalyzer &state,SpaceDisplay display)
{
const auto tree=GetDlgItem(dialog,spaceTree), map=GetDlgItem(dialog,spaceMap);
const auto list=GetDlgItem(dialog,spaceSunburstList);
const bool showTree=display==SpaceDisplay::tree, showSunburst=display==SpaceDisplay::sunburst;
const auto selection=selectedSpaceNode(tree,state);
if(state.display==SpaceDisplay::tree && !showTree)
{
const auto index=selection.value_or(0);
const auto &node=state.nodes[index];
state.mapFolder=node.folder && !node.link?index:node.parent;
}
state.display=display;
SetDlgItemTextW(dialog,spaceMapButton,display==SpaceDisplay::treemap?L"Tr&ee":L"Tree&map");
SetDlgItemTextW(dialog,spaceSunburstButton,showSunburst?L"Tr&ee":L"S&unburst");
layoutSpaceAnalyzer(dialog);
ShowWindow(tree,showTree?SW_SHOW:SW_HIDE);
ShowWindow(map,showTree?SW_HIDE:SW_SHOW);
ShowWindow(GetDlgItem(dialog,spaceSunburstLabel),showSunburst?SW_SHOW:SW_HIDE);
ShowWindow(list,showSunburst?SW_SHOW:SW_HIDE);
if(!showSunburst)
{
EnableWindow(GetDlgItem(dialog,spaceView),showTree && selection && !state.nodes[*selection].folder);
EnableWindow(GetDlgItem(dialog,IDOK),showTree && selection.has_value());
}
if(!showTree) refreshSpaceChart(map,state);
SetFocus(showTree?tree:showSunburst?list:map);
}
+149
View File
@@ -0,0 +1,149 @@
constexpr double fullCircle=2*std::numbers::pi_v<double>;
constexpr unsigned sunburstRings=3;
double sunburstRingWidth(const RECT &bounds)
{
return std::max(0L,std::min(bounds.right-bounds.left,bounds.bottom-bounds.top)-4)/
(2.0*(sunburstRings+0.5));
}
void addSunburstRing(SpaceAnalyzer &state,size_t folder,unsigned ring,double start,double end)
{
if(ring>=sunburstRings || end-start<0.02) return;
const auto &parent=state.nodes[folder];
double total=0;
for(auto index:parent.children) total+=static_cast<double>(state.nodes[index].size.bytes);
if(total<=0) return;
const auto span=end-start;
auto cursor=start;
for(auto index:parent.children)
{
const auto &item=state.nodes[index];
if(!item.size.bytes) continue;
const auto next=std::min(end,cursor+span*static_cast<double>(item.size.bytes)/total);
if(next-cursor>=0.02)
{
state.sectors.push_back({index,ring,cursor,next});
if(item.folder) addSunburstRing(state,index,ring+1,cursor,next);
}
cursor=next;
}
}
std::optional<size_t> sunburstSelectedSector(HWND dialog,const SpaceAnalyzer &state)
{
const auto row=SendDlgItemMessageW(dialog,spaceSunburstList,LB_GETCURSEL,0,0);
if(row==LB_ERR) return {};
const auto sector=SendDlgItemMessageW(dialog,spaceSunburstList,LB_GETITEMDATA,row,0);
if(sector==LB_ERR || static_cast<size_t>(sector)>=state.sectors.size()) return {};
return static_cast<size_t>(sector);
}
std::optional<size_t> sunburstSelection(HWND dialog,const SpaceAnalyzer &state)
{
const auto sector=sunburstSelectedSector(dialog,state);
return sector?std::optional<size_t>(state.sectors[*sector].node):std::nullopt;
}
void updateSunburstSelection(HWND dialog,SpaceAnalyzer &state)
{
state.selectedTile=sunburstSelectedSector(dialog,state).value_or(state.sectors.size());
const auto selected=sunburstSelection(dialog,state);
EnableWindow(GetDlgItem(dialog,spaceView),selected && !state.nodes[*selected].folder);
EnableWindow(GetDlgItem(dialog,IDOK),selected.has_value());
InvalidateRect(GetDlgItem(dialog,spaceMap),nullptr,FALSE);
}
void layoutSunburst(HWND map,SpaceAnalyzer &state)
{
const auto dialog=GetParent(map);
const auto list=GetDlgItem(dialog,spaceSunburstList);
const auto selected=sunburstSelection(dialog,state);
state.lastMapUpdate=GetTickCount64();
state.sectors.clear();
state.selectedTile=0;
if(state.mapFolder<state.nodes.size())
addSunburstRing(state,state.mapFolder,0,0,fullCircle);
SendMessageW(list,WM_SETREDRAW,FALSE,0);
SendMessageW(list,LB_RESETCONTENT,0,0);
SendMessageW(list,LB_INITSTORAGE,state.sectors.size(),0);
LRESULT selection=0;
size_t longest=0;
for(size_t i=0;i<state.sectors.size();++i)
{
const auto &sector=state.sectors[i];
const auto &node=state.nodes[sector.node];
const auto &root=state.nodes[state.mapFolder];
const auto name=node.path.lexically_relative(root.path).native();
const auto line=name+L" — "+spaceLogicalSize(node);
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(line.c_str()));
if(row>=0)
{
SendMessageW(list,LB_SETITEMDATA,row,i);
if(selected==sector.node) selection=row;
longest=std::max(longest,line.size());
}
}
SendMessageW(list,LB_SETHORIZONTALEXTENT,(longest+1)*cellWidth,0);
if(!state.sectors.empty()) SendMessageW(list,LB_SETCURSEL,selection,0);
SendMessageW(list,WM_SETREDRAW,TRUE,0);
InvalidateRect(list,nullptr,FALSE);
updateSunburstSelection(dialog,state);
}
std::optional<size_t> hitSunburst(HWND map,const SpaceAnalyzer &state,POINT point)
{
RECT bounds{};
GetClientRect(map,&bounds);
const auto width=sunburstRingWidth(bounds);
if(width<=0) return {};
const auto x=point.x-(bounds.left+bounds.right)/2.0;
const auto y=point.y-(bounds.top+bounds.bottom)/2.0;
const auto radius=std::hypot(x,y)/width-0.5;
if(radius<0 || radius>=sunburstRings) return {};
const auto ring=static_cast<unsigned>(radius);
auto angle=std::atan2(x,-y);
if(angle<0) angle+=fullCircle;
for(size_t i=0;i<state.sectors.size();++i)
{
const auto &sector=state.sectors[i];
if(sector.ring==ring && angle>=sector.start && angle<sector.end) return i;
}
return {};
}
void paintSunburst(const DRAWITEMSTRUCT &paint,const SpaceAnalyzer &state)
{
auto bounds=paint.rcItem;
FillRect(paint.hDC,&bounds,GetSysColorBrush(COLOR_WINDOW));
if(state.sectors.empty())
{
paintEmptySpaceChart(paint);
return;
}
const auto width=sunburstRingWidth(bounds);
const auto x=(bounds.left+bounds.right)/2.0, y=(bounds.top+bounds.bottom)/2.0;
const auto point=[&](double angle,double radius) {
return POINT{std::lround(x+radius*std::sin(angle)),std::lround(y-radius*std::cos(angle))};
};
const auto oldBrush=SelectObject(paint.hDC,GetStockObject(DC_BRUSH));
const auto oldPen=SelectObject(paint.hDC,GetStockObject(DC_PEN));
for(size_t i=0;i<state.sectors.size();++i)
{
const auto &sector=state.sectors[i];
const auto segments=std::clamp(static_cast<int>((sector.end-sector.start)*26),2,164);
const auto inner=(sector.ring+0.5)*width, outer=inner+width;
std::array<POINT,330> points;
for(int segment=0;segment<=segments;++segment)
{
const auto angle=sector.start+(sector.end-sector.start)*segment/segments;
points[segment]=point(angle,outer);
points[2*segments+1-segment]=point(angle,inner);
}
SetDCPenColor(paint.hDC,i==state.selectedTile?RGB(35,48,62):RGB(255,255,255));
SetDCBrushColor(paint.hDC,spaceChartColors[i%std::size(spaceChartColors)]);
Polygon(paint.hDC,points.data(),2*(segments+1));
}
SelectObject(paint.hDC,oldPen);
SelectObject(paint.hDC,oldBrush);
}
+150
View File
@@ -0,0 +1,150 @@
bool panelMatchesSshPrompt()
{
const auto &panel=panels[active];
return sshPrompt && sshPrompt->panel==active && panel.ftp &&
panel.ftp->protocol==TransferProtocol::sftp && panel.ftp->id==sshPrompt->profile;
}
void closeSshPrompt(HWND owner)
{
if(!sshPrompt) return;
clearTerminalSelection();
sshPrompt.reset();
sshTerminal.stop();
sshView.post(L"ssh-input:off");
layout(owner);
}
bool startSshTerminal(HWND owner,const Panel &panel)
{
if(panelMatchesSshPrompt() && !sshPrompt->finished) return true;
if(sshTerminal.running())
{
setStatus(L"The previous SSH session is closing. Try again when it has disconnected.");
return false;
}
if(!ensureTerminalView(owner,true)) return false;
try
{
auto token=ks::lan::randomHex(16);
sshTerminal.start(*panel.ftp,panel.directory,token,sshSize);
clearTerminalSelection();
sshPrompt=SshPrompt{active,panel.ftp->id,std::move(token),panel.directory};
}
catch(const std::exception &error) {setStatus(ks::wide(error.what()));return false;}
sshView.post(L"ssh-reset");
if(!terminalVisible) terminalRows=std::max(terminalRows,5);
layout(owner);
return true;
}
bool sendSshCommand(HWND owner,const fs::path &directory,const std::wstring &value)
{
const auto text=ks::utf8(value);
const auto command=directory==sshPrompt->shellDirectory?text:
"if "+sshChangeDirectory(directory)+"; then eval "+sshShellQuote(text)+"; fi";
if(!sshTerminal.write(command+"\r"))
{
setStatus(L"Could not send input to the SSH terminal.");
return false;
}
sshPrompt->panelDirectory=directory;
sshPrompt->waiting=true;
sshPrompt->raw=true;
sshView.post(L"ssh-input:on");
if(GetForegroundWindow()==owner)
{
sshView.focus();
sshView.post(L"ssh-focus");
}
return true;
}
bool submitSshCommand(HWND owner,const Panel &panel,const std::wstring &value)
{
if(!startSshTerminal(owner,panel)) return false;
if(!sshPrompt->waiting) return sendSshCommand(owner,panel.directory,value);
if(sshPrompt->shellDirectory.empty() && !sshPrompt->startupCommand)
{
sshPrompt->startupCommand=value;
return true;
}
setStatus(L"The SSH prompt is busy.");
return false;
}
std::optional<fs::path> sshReportedDirectory(std::wstring_view encoded)
{
if(encoded.empty() || encoded.size()>49152) return {};
DWORD length{};
if(!CryptStringToBinaryW(encoded.data(),static_cast<DWORD>(encoded.size()),CRYPT_STRING_BASE64|CRYPT_STRING_STRICT,
nullptr,&length,nullptr,nullptr) || !length) return {};
auto bytes=std::string(length,'\0');
if(!CryptStringToBinaryW(encoded.data(),static_cast<DWORD>(encoded.size()),CRYPT_STRING_BASE64|CRYPT_STRING_STRICT,
reinterpret_cast<BYTE*>(bytes.data()),&length,nullptr,nullptr) || bytes.front()!='/' ||
bytes.find_first_of("\\:\r\n")!=bytes.npos || bytes.find('\0')!=bytes.npos) return {};
auto path=fs::path(ks::wide(bytes)).lexically_normal();
return isFtpFolderPath(path)?std::optional(std::move(path)):std::nullopt;
}
void acceptSshDirectory(HWND owner,std::wstring_view message)
{
if(!panelMatchesSshPrompt() || sshPrompt->finished || message.size()<33 || message[32]!=L':' ||
message.substr(0,32)!=ks::wide(sshPrompt->token)) return;
const auto reported=sshReportedDirectory(message.substr(33));
if(!reported) return;
auto &panel=panels[active];
auto &prompt=*sshPrompt;
const bool initial=prompt.shellDirectory.empty();
const bool command=std::exchange(prompt.raw,false);
prompt.shellDirectory=*reported;
prompt.waiting=false;
if(command)
{
sshView.post(L"ssh-input:off");
if(GetForegroundWindow()==owner) restoreCommandFocus();
}
if(prompt.startupCommand)
{
const auto pending=std::exchange(prompt.startupCommand,{});
if(!sendSshCommand(owner,prompt.panelDirectory,*pending) && !GetWindowTextLengthW(terminalInput))
SetWindowTextW(terminalInput,pending->c_str());
return;
}
if(panel.scan.valid() || panel.directory!=prompt.panelDirectory || panel.directory==*reported) return;
if(initial || command)
{
prompt.panelDirectory=*reported;
open(panel,*reported,false);
}
else setStatus(L"The SSH shell could not enter the panel folder.");
}
void updateSshTerminal(HWND owner)
{
if(!sshPrompt) return;
if(!panelMatchesSshPrompt()) {closeSshPrompt(owner);return;}
if(!sshView.initialized()) return;
const auto output=sshTerminal.takeOutput();
if(!output.empty()) sshView.send(output);
auto &prompt=*sshPrompt;
if(!sshTerminal.running() && !prompt.finished)
{
auto reason=sshTerminal.takeError();
if(reason.empty()) reason=L"SSH session disconnected.";
sshView.send(ks::utf8(L"\r\n["+reason+L"]\r\n"));
if(prompt.startupCommand && !GetWindowTextLengthW(terminalInput))
SetWindowTextW(terminalInput,prompt.startupCommand->c_str());
prompt.finished=true;
prompt.raw=false;
sshView.post(L"ssh-input:off");
setStatus(reason);
if(GetForegroundWindow()==owner) restoreCommandFocus();
return;
}
const auto &panel=panels[active];
if(prompt.finished || prompt.waiting || panel.scan.valid() || panel.directory==prompt.panelDirectory) return;
prompt.panelDirectory=panel.directory;
if(panel.directory!=prompt.shellDirectory && sshTerminal.write(sshChangeDirectory(panel.directory)+"\r"))
prompt.waiting=true;
}
+164
View File
@@ -0,0 +1,164 @@
std::string sshShellQuote(std::string_view text)
{
std::string quoted="'";
for(const auto character:text)
if(character=='\'') quoted+="'\\''";
else quoted+=character;
return quoted+"'";
}
std::string sshChangeDirectory(const fs::path &path)
{
return "cd "+sshShellQuote(ks::utf8(ftpPath(path)));
}
class FilesSshTerminal
{
std::mutex mutex_;
std::string input_,output_;
std::wstring error_;
COORD size_{};
std::atomic_bool running_{};
std::jthread worker_;
void run(const TransferProfile &profile,const fs::path &directory,const std::string &token,
COORD terminalSize,std::stop_token stop)
{
SshConnection connection(profile);
if(stop.stop_requested()) return;
SshChannel channel(libssh2_channel_open_session(connection.session()),libssh2_channel_free);
if(!channel) connection.operationError("Could not open the SSH terminal");
if(libssh2_channel_request_pty_ex(channel.get(),"xterm-256color",14,nullptr,0,
terminalSize.X,terminalSize.Y,0,0)) connection.operationError("Could not allocate the SSH terminal");
// Expand the prompt after every command so panel navigation can follow even scripted directory changes.
const auto report="printf '\\033]633;ks-ssh-dir:"+token+
":%s\\007' \"$(printf '%s' \"$(pwd -P)\" | base64 | tr -d '\\r\\n')\"";
const auto command=sshChangeDirectory(directory)+
" || exit; command -v base64 >/dev/null 2>&1 || { echo 'SSH directory sync requires base64.'; exit 1; }; "
"if command -v bash >/dev/null 2>&1; then exec env PS1='' PS2='> ' PROMPT_COMMAND="+
sshShellQuote(report)+" bash --noprofile --norc -i; else exec env ENV=/dev/null PS2='> ' PS1="+
sshShellQuote("$("+report+")")+" /bin/sh -i; fi";
if(libssh2_channel_exec(channel.get(),command.c_str()))
connection.operationError("Could not start the SSH shell");
connection.nonblocking();
auto buffer=std::array<char,32768>{};
std::string pending;
size_t offset{};
std::optional<COORD> resize;
while(!stop.stop_requested())
{
{
const std::lock_guard lock(mutex_);
if(pending.empty()) pending.swap(input_);
if(!resize && (terminalSize.X!=size_.X || terminalSize.Y!=size_.Y)) resize=size_;
}
bool progressed=false;
if(resize)
{
const auto result=libssh2_channel_request_pty_size(channel.get(),resize->X,resize->Y);
if(result!=LIBSSH2_ERROR_EAGAIN)
{
terminalSize=*resize;
resize.reset();
}
}
if(!pending.empty())
{
const auto count=libssh2_channel_write(channel.get(),pending.data()+offset,pending.size()-offset);
if(count<0 && count!=LIBSSH2_ERROR_EAGAIN) connection.operationError("Could not send SSH terminal input");
if(count>0)
{
offset+=count;
if(offset==pending.size()) {pending.clear();offset=0;}
progressed=true;
}
}
for(int stream:{0,SSH_EXTENDED_DATA_STDERR})
{
const auto count=libssh2_channel_read_ex(channel.get(),stream,buffer.data(),buffer.size());
if(count<0 && count!=LIBSSH2_ERROR_EAGAIN) connection.operationError("Could not read SSH terminal output");
if(count>0)
{
const std::lock_guard lock(mutex_);
output_.append(buffer.data(),count);
constexpr size_t limit=1024*1024;
if(output_.size()>limit) output_.erase(0,output_.size()-limit);
progressed=true;
}
}
if(!progressed)
{
if(libssh2_channel_eof(channel.get())) break;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
// The connection owns all channels. Its teardown also handles a channel blocked in a nonblocking request.
channel.release();
}
public:
bool running() const {return running_;}
void start(TransferProfile profile,fs::path directory,std::string token,COORD size)
{
{
const std::lock_guard lock(mutex_);
input_.clear();
output_.clear();
error_.clear();
size_=size;
}
running_=true;
try
{
worker_=std::jthread([this,profile=std::move(profile),directory=std::move(directory),
token=std::move(token),size](std::stop_token stop)
{
try {run(profile,directory,token,size,stop);}
catch(const std::exception &error)
{
const std::lock_guard lock(mutex_);
error_=ks::wide(error.what());
}
running_=false;
});
}
catch(...)
{
running_=false;
throw;
}
}
void stop() {worker_.request_stop();}
bool write(std::string_view input)
{
if(!running_) return false;
const std::lock_guard lock(mutex_);
constexpr size_t limit=256*1024;
if(input.size()>limit-input_.size()) return false;
input_+=input;
return true;
}
void resize(COORD size)
{
const std::lock_guard lock(mutex_);
size_=size;
}
std::string takeOutput()
{
const std::lock_guard lock(mutex_);
return std::exchange(output_,{});
}
std::wstring takeError()
{
const std::lock_guard lock(mutex_);
return std::exchange(error_,{});
}
};
+31 -34
View File
@@ -48,60 +48,54 @@ bool sameFileExtension(std::wstring_view left,std::wstring_view right)
right.data(),static_cast<int>(right.size()),TRUE)==CSTR_EQUAL;
}
void loadFileStyles()
std::optional<std::vector<FileStyle>> parseFileStyles(const Json &rows)
{
DWORD bytes{};
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
!bytes || bytes>256*1024) return;
std::string data(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS)
return;
try
{
const auto rows=Json::parse(data.begin(),data.begin()+bytes);
if(!rows.is_array() || rows.size()>64) return;
if(!rows.is_array() || rows.size()>64) return {};
std::vector<FileStyle> parsed;
for(const auto &row:rows)
{
FileStyle style{ks::wide(row.at("extension").get<std::string>())};
if(style.extension!=L"@system-hidden" && fileStyleExtension(style.extension)!=style.extension) return;
if(std::any_of(parsed.begin(),parsed.end(),[&](const auto &existing){return existing.extension==style.extension;}))
return;
const auto color=[&](const char *key)->std::optional<COLORREF>
if(style.extension!=L"@system-hidden" && fileStyleExtension(style.extension)!=style.extension) return {};
if(std::ranges::any_of(parsed,[&](const auto &existing){return existing.extension==style.extension;}))
return {};
const auto color=[](const Json &entry,const char *key)->std::optional<COLORREF>
{
if(!row.contains(key)) return {};
const auto value=row.at(key).get<DWORD>();
if(value>0xffffff) throw std::runtime_error("Invalid file style color");
return value;
if(!entry.contains(key)) return {};
const auto &value=entry.at(key);
if(!value.is_number_unsigned() || value>0xffffff) throw std::runtime_error("Invalid file style color");
return value.get<DWORD>();
};
style.foreground=color("foreground");
style.background=color("background");
style.foreground=color(row,"foreground");
style.background=color(row,"background");
style.underline=row.value("underline",false);
style.strikeout=row.value("strikeout",false);
if(row.contains("states"))
{
const auto &states=row.at("states");
if(!states.is_array() || states.size()!=style.states.size()) return;
if(!states.is_array() || states.size()!=style.states.size()) return {};
for(size_t i=0;i<style.states.size();++i)
{
const auto read=[&](const char *key)->std::optional<COLORREF>
{
if(!states[i].contains(key)) return {};
const auto value=states[i].at(key).get<DWORD>();
if(value>0xffffff) throw std::runtime_error("Invalid state color");
return value;
};
style.states[i]={read("foreground"),read("background")};
if(!states[i].is_object()) return {};
style.states[i]={color(states[i],"foreground"),color(states[i],"background")};
}
}
parsed.push_back(std::move(style));
}
fileStyles=std::move(parsed);
return parsed;
}
catch(const std::exception &) {}
catch(const std::exception &) {return {};}
}
bool saveFileStyles(const std::vector<FileStyle> &styles)
void loadFileStyles()
{
fileStyles=defaultFileStyles;
if(const auto rows=readFilesJsonPreference(fileStyleKey))
if(auto parsed=parseFileStyles(*rows)) fileStyles=std::move(*parsed);
}
Json serializeFileStyles(const std::vector<FileStyle> &styles)
{
auto rows=Json::array();
for(const auto &style:styles)
@@ -119,9 +113,12 @@ bool saveFileStyles(const std::vector<FileStyle> &styles)
}
rows.push_back(std::move(row));
}
const auto data=rows.dump();
return RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,REG_BINARY,data.data(),
static_cast<DWORD>(data.size()))==ERROR_SUCCESS;
return rows;
}
bool saveFileStyles(const std::vector<FileStyle> &styles)
{
return writeFilesJsonPreference(fileStyleKey,serializeFileStyles(styles));
}
struct FileRowStyle
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff. Show more