Compare commits
19
Commits
release-v0.6.85
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ea4f6f914 | ||
|
|
36f0b6ef8e | ||
|
|
3aafc1f937 | ||
|
|
6215675cb4 | ||
|
|
56c6257465 | ||
|
|
64b03a2168 | ||
|
|
36baeeb081 | ||
|
|
7698ea040d | ||
|
|
84d911ae9e | ||
|
|
8dedf30ece | ||
|
|
f11bfff784 | ||
|
|
78aea46fb3 | ||
|
|
1549a89dc3 | ||
|
|
47382cdd86 | ||
|
|
49ae0ad157 | ||
|
|
f8c05fd0ce | ||
|
|
d80fad6e48 | ||
|
|
a504adb22d | ||
|
|
c3fa2af348 |
No files matched your search
+2
-1
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(KSwitcher VERSION 0.6.85 LANGUAGES CXX RC)
|
||||
project(KSwitcher VERSION 0.6.93 LANGUAGES CXX RC)
|
||||
if(NOT WIN32)
|
||||
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
|
||||
endif()
|
||||
@@ -47,6 +47,7 @@ target_link_libraries(KSwitcherFiles PRIVATE kscore)
|
||||
target_include_directories(kscore PUBLIC src PRIVATE vendor)
|
||||
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_compile_definitions(KSwitcher PRIVATE KS_RESIDENT_APP)
|
||||
target_link_libraries(KSwitcher PRIVATE kscore)
|
||||
|
||||
+49
@@ -13,6 +13,15 @@ Far Manager є зразком для оформлення файлового м
|
||||
Це діє і для вкладених діалогів. Під час файлової операції Cancel спершу
|
||||
просить підтвердити переривання.
|
||||
|
||||
Спільне повідомлення Files підлаштовується під заголовок і кількість рядків.
|
||||
Висота діалогу залежить від видимого вмісту. Приховані та порожні секції
|
||||
не займають місця. Перед завершенням змін перевір коротке повідомлення й
|
||||
повідомлення з кількома рядками, включно з відступами до рамки та кнопок.
|
||||
Смуга прокрутки з’являється, лише коли текст не вміщується в доступну висоту.
|
||||
Оформлення, кнопки й необов’язковий прапорець задаються параметрами шаблону.
|
||||
Підтвердження гібернації та віддаленого оновлення мають червоне оформлення
|
||||
Warning і початковий фокус на No.
|
||||
|
||||
## Скорочення
|
||||
|
||||
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
|
||||
@@ -29,12 +38,43 @@ Far Manager є зразком для оформлення файлового м
|
||||
Enter запускає введену команду або відкриває поточний елемент, якщо рядок
|
||||
порожній. Escape очищає рядок.
|
||||
Промпт і текст команди вирівняні по спільній базовій лінії.
|
||||
- У віддаленій панелі Enter запускає введену команду PowerShell на
|
||||
спареному ПК в поточному каталозі цієї панелі. Вивід і код завершення
|
||||
з’являються в терміналі Files як текст. Службовий прогрес PowerShell
|
||||
приховано. Кожна команда запускається окремо,
|
||||
тому змінні середовища й `cd` між командами не зберігаються. Escape
|
||||
в порожньому командному рядку скасовує поточну віддалену команду.
|
||||
- На ПК, який приймає команди, увімкніть **Options → Command line →
|
||||
Command history → Allow paired PCs to run PowerShell commands here**.
|
||||
Дозвіл за замовчуванням вимкнений і діє лише для спарених ПК. Команди
|
||||
запускаються без підвищених прав. Для цієї функції оновіть обидва ПК.
|
||||
- **F9 → Commands → Hibernate remote PC** доступна для активної LAN-панелі.
|
||||
У підтвердженні показується ім’я цільового ПК. На цільовому ПК ввімкніть
|
||||
**Options → Command line → Command history → Allow paired PCs to hibernate this PC**.
|
||||
Дозвіл за замовчуванням вимкнений і діє лише для спарених ПК. Для цієї дії
|
||||
потрібні оновлення на обох ПК і ввімкнена гібернація Windows.
|
||||
- **F9 → Commands → Update remote KSwitcher** запускає штатне оновлення для
|
||||
ПК активної LAN-панелі. Підтвердження з іменем ПК показується у Files
|
||||
відправника. На цільовому ПК потрібен дозвіл **Options → Command line →
|
||||
Command history → Allow paired PCs to update KSwitcher here**. Після
|
||||
перевірки нового стабільного пакета оновлювач без запитань закриває
|
||||
KSwitcher, Files, Config і редактори скриншотів цієї інсталяції.
|
||||
Незбережені зміни у примусово закритих вікнах втрачаються.
|
||||
Закриття процесів і результат записуються до `kswitcher.log`.
|
||||
|
||||
- Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію
|
||||
курсора командного рядка або замінює виділення. Подвійні лапки додаються
|
||||
лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки.
|
||||
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
|
||||
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
|
||||
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
|
||||
зберігаються для наявних елементів, а підраховані через F3 розміри папок
|
||||
скидаються. F2 також виконує цю дію.
|
||||
- Ctrl+C копіює весь введений у командний рядок текст, навіть коли виділено
|
||||
лише його частину.
|
||||
- Ctrl+Insert копіює імена позначених файлів і папок активної панелі в порядку
|
||||
відображення, по одному на рядок. Якщо позначок немає, копіюється ім’я під
|
||||
курсором. Шляхи й рядок `..` пропускаються.
|
||||
|
||||
- Ctrl+E підставляє останню команду. Повторне натискання
|
||||
підставляє старішу, доки не досягне початку історії. Alt+F8 відкриває історію
|
||||
@@ -73,6 +113,10 @@ Far Manager є зразком для оформлення файлового м
|
||||
а Enter відкриває поточний елемент.
|
||||
- F9 перемикає головне меню Files. Після закриття фокус повертається в командний рядок. Коли меню відкрите, Alt з літерою верхнього рівня відкриває відповідний пункт.
|
||||
- Коли головне меню відкрите, L, F, C, O та R відкривають Left, Files, Commands, Options та Right. У підменю підсвічена літера викликає відповідну команду. Літери унікальні в межах поточного рівня. Усталені мнемоніки мають пріоритет, зокрема X для Exit.
|
||||
- У Commands лінії відокремлюють навігацію панелі, перегляд і редагування
|
||||
та керування віддаленим ПК. Остання група з’являється разом зі своїм
|
||||
роздільником лише в активній LAN-панелі. Роздільники пропускаються під
|
||||
час навігації й не реагують на клік.
|
||||
- Глобальне скорочення **Open KSwitcher Files** можна змінити або очистити в налаштуваннях. Для профілю без цього поля пропонується Ctrl+Alt+F, якщо Windows реєструє комбінацію і вона вільна серед прив’язок KSwitcher.
|
||||
- Глобальне скорочення повертає до відкритого вікна Files у поточній сесії Windows або запускає Files, якщо такого вікна немає. Пункт **Files** у треї відкриває нове вікно.
|
||||
|
||||
@@ -91,6 +135,11 @@ Far Manager є зразком для оформлення файлового м
|
||||
відкриваються в окремих немодальних вікнах із власними кнопками на панелі
|
||||
завдань Windows. При повторному відкритті Files пропонує перейти до вже
|
||||
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
|
||||
- Коли курсор на папці, F3 у фоні підраховує сумарний розмір файлів у ній
|
||||
та вкладених папках. Якщо позначено папки, розмір рахується для кожної з
|
||||
них окремо. Результат видно в колонці Size у широкому режимі та в рядку
|
||||
стану, коли там увімкнено розмір. Це працює і в LAN-панелі. Посилання й
|
||||
junction не обходяться. Недоступний вміст позначається як частковий результат.
|
||||
- F3 і F4 працюють і на панелі LAN. Файл завантажується у тимчасову копію
|
||||
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
|
||||
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
|
||||
|
||||
Binary file not shown.
@@ -1,5 +1,54 @@
|
||||
# Latest Windows release
|
||||
|
||||
## v0.6.93 — 2026-11-16
|
||||
|
||||
In Files, Ctrl+R refreshes the active pane as in FAR Manager. The menu and key bar show Ctrl+R. F2 also refreshes the pane. Refresh preserves marks and the cursor where possible, and clears folder sizes calculated with F3.
|
||||
|
||||
**Українською.** У Files Ctrl+R перечитує активну панель, як у FAR Manager. Комбінація показана в меню та рядку клавіш. F2 також перечитує панель. Перечитування зберігає позначки й курсор для наявних елементів і скидає розміри папок, підраховані через F3.
|
||||
|
||||
## v0.6.92 — 2026-11-16
|
||||
|
||||
In Files, F3 on a folder measures file sizes throughout the directory tree. If folders are marked, Files measures each marked folder separately. Results appear in the Size column in Wide mode. F3 on a file opens the viewer even when folders are marked. Folder sizing runs in the background and supports LAN panes.
|
||||
|
||||
**Українською.** У Files F3 на папці підраховує сумарний розмір файлів у всьому дереві. Якщо позначено папки, Files рахує розмір кожної окремо. Результат з’являється в колонці Size у широкому режимі. F3 на файлі відкриває переглядач, навіть коли позначено папки. Підрахунок виконується у фоні й підтримує LAN-панелі.
|
||||
|
||||
## v0.6.91 — 2026-11-16
|
||||
|
||||
Ctrl+Insert copies the marked file and folder names from the active pane, one per line. Without marks, it copies the name under the cursor. LAN Files retries opening TCP 45885 if the port is busy at startup, and Change drive retries failed drive queries. A remote update request waits for an in-progress update check. The updater identifies and closes companion processes from its installation, including Files running from an update backup, and records confirmed exits in the journal.
|
||||
|
||||
**Українською.** Ctrl+Insert копіює імена позначених файлів і папок активної панелі, по одному на рядок. Якщо позначок немає, копіюється ім’я під курсором. LAN Files повторює відкриття TCP 45885, якщо порт зайнятий під час старту, а Change drive повторює невдалі запити дисків. Запит віддаленого оновлення чекає завершення поточної перевірки. Оновлювач визначає й закриває процеси своєї інсталяції, зокрема Files із резервної папки, і записує підтверджене завершення в журнал.
|
||||
|
||||
## v0.6.90 — 2026-11-16
|
||||
|
||||
Files groups Commands into navigation, viewing and editing, and remote PC actions. The remote group appears in an active LAN pane. Shared notices fit their contents and show a scrollbar only when needed. Remote hibernation and update confirmations use a compact red warning with No focused by default.
|
||||
|
||||
**Українською.** Меню Commands у Files групує навігацію, перегляд і редагування та дії для віддаленого ПК. Віддалена група доступна в активній LAN-панелі. Спільні повідомлення підлаштовуються під вміст і показують прокрутку лише за потреби. Гібернація та віддалене оновлення використовують компактне червоне підтвердження з фокусом на No.
|
||||
|
||||
## v0.6.89 — 2026-11-16
|
||||
|
||||
In Files, Commands now offers **Hibernate remote PC** and **Update remote KSwitcher** for the active LAN pane. The target PC has separate, default-off permissions for each action. Unattended updates verify the stable package, close the target installation's Files, Config and screenshot windows, and restart KSwitcher. Forced closure discards unsaved changes. The target journal records closed processes and the update result.
|
||||
|
||||
**Українською.** У меню Commands з’явилися **Hibernate remote PC** і **Update remote KSwitcher** для активної LAN-панелі. На цільовому ПК кожна дія має окремий дозвіл, вимкнений за замовчуванням. Оновлювач перевіряє стабільний пакет, без запитань закриває Files, Config і редактори скриншотів цієї інсталяції та перезапускає KSwitcher. Примусове закриття відкидає незбережені зміни. Журнал цільового ПК фіксує закриті процеси й результат оновлення.
|
||||
|
||||
## v0.6.88 — 2026-11-16
|
||||
|
||||
In Files, Ctrl+Enter inserts the name of the file or folder under the active pane cursor into the command line. An open Files window can still request the LAN peer list after KSwitcher updates and restarts.
|
||||
|
||||
**Українською.** У Files Ctrl+Enter вставляє в командний рядок назву файла або папки під курсором активної панелі. Відкрите вікно Files і далі може отримувати список LAN-комп’ютерів після оновлення та автоматичного перезапуску KSwitcher.
|
||||
|
||||
|
||||
## v0.6.87 — 2026-11-15
|
||||
|
||||
Remote PowerShell in Files now displays errors as text and hides progress metadata. Update the PC that runs the commands to remove raw CLIXML from terminal output. This release supersedes v0.6.86.
|
||||
|
||||
**Українською.** Віддалений PowerShell у Files тепер показує помилки як текст і приховує службові повідомлення прогресу. Щоб прибрати сирий CLIXML із термінала, оновіть ПК, який виконує команди. Цей реліз замінює v0.6.86.
|
||||
|
||||
## v0.6.86 — 2026-11-15
|
||||
|
||||
The Files editor applies its palette before the text area appears. In a LAN pane, enter a PowerShell command to run it in that pane’s directory on the paired PC. The Files terminal displays output and the exit code. On the remote PC, enable **Allow paired PCs to run PowerShell commands here** in **Files → Options → Command line → Command history**. Both PCs need v0.6.86 or later.
|
||||
|
||||
**Українською.** Редактор Files застосовує палітру до появи текстового поля. У панелі LAN введена команда PowerShell виконується в каталозі цієї панелі на спареному ПК. Термінал Files показує вивід і код завершення. На віддаленому ПК увімкніть **Allow paired PCs to run PowerShell commands here** у **Files → Options → Command line → Command history**. На обох ПК потрібен v0.6.86 або новіший.
|
||||
|
||||
## v0.6.85 — 2026-11-15
|
||||
|
||||
Files viewer and editor windows now run independently with separate Windows taskbar buttons. Reopening a file offers to switch to its existing window. F3 and F4 work in LAN panes. The editor downloads files in the background and checks the remote file before replacing it on save. Update KSwitcher on the remote PC for writeback.
|
||||
|
||||
@@ -1 +1 @@
|
||||
658c9098a51408a680156534f9083491f9b9e53d330547a1003cefce23f34f49 KSwitcher-win-x64.zip
|
||||
21b9e32cfbd5e5cc8898d675a3b53e4b510a427dbeb2c26a957d104f1154dc05 KSwitcher-win-x64.zip
|
||||
+60
-60
@@ -1,136 +1,136 @@
|
||||
{
|
||||
"version": "0.6.85",
|
||||
"schema": 1,
|
||||
"files": [
|
||||
{
|
||||
"sha256": "e0b471ca3aef6bf59c76b0554800cc7c0fde74f3aade3b82c0d5df906d7d8b0d",
|
||||
"path": "KSwitcher.exe",
|
||||
"size": 2454528
|
||||
"size": 2467840,
|
||||
"sha256": "3ad872f175c26ec2e9e06f9c5edf54f817fb281174d3be84d3286f9c38796b6e",
|
||||
"path": "KSwitcher.exe"
|
||||
},
|
||||
{
|
||||
"sha256": "5cd5277464d37d8d4ea9141b5283010c3d480422d4c8fecea9b9e7346f9d72ad",
|
||||
"path": "KSwitcher.Config.exe",
|
||||
"size": 2431488
|
||||
"size": 2446848,
|
||||
"sha256": "e7465f15c46278841ed0764f3ac699b95423c3490c375d5481bbf85c100dbf34",
|
||||
"path": "KSwitcher.Config.exe"
|
||||
},
|
||||
{
|
||||
"sha256": "0a3db52490fb1e368ff859f01dd2fd7f49d254b78fd72cae0c79a197e345413d",
|
||||
"path": "KSwitcher.Screenshot.exe",
|
||||
"size": 3050496
|
||||
"size": 3053568,
|
||||
"sha256": "e7b2f32b0138b3a3af7f648c5d6cfb17f952f48440ae69fcf7803a58b0ee32f6",
|
||||
"path": "KSwitcher.Screenshot.exe"
|
||||
},
|
||||
{
|
||||
"sha256": "53fa251679a827a000f3133fff27f26744c57336ab457b4db341221e523b45d5",
|
||||
"path": "KSwitcher.Files.exe",
|
||||
"size": 3635200
|
||||
"size": 3686912,
|
||||
"sha256": "1a570823393e2c3e2198408ab44f83bf4456849b9eaa85a0ca52f63f1cb5326e",
|
||||
"path": "KSwitcher.Files.exe"
|
||||
},
|
||||
{
|
||||
"size": 194912,
|
||||
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
|
||||
"path": "WebView2Loader.dll",
|
||||
"size": 194912
|
||||
"path": "WebView2Loader.dll"
|
||||
},
|
||||
{
|
||||
"size": 1103,
|
||||
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
|
||||
"path": "terminal/addon-fit-LICENSE.txt",
|
||||
"size": 1103
|
||||
"path": "terminal/addon-fit-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"size": 1521,
|
||||
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
|
||||
"path": "terminal/addon-fit.js",
|
||||
"size": 1521
|
||||
"path": "terminal/addon-fit.js"
|
||||
},
|
||||
{
|
||||
"size": 527,
|
||||
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
|
||||
"path": "terminal/index.html",
|
||||
"size": 527
|
||||
"path": "terminal/index.html"
|
||||
},
|
||||
{
|
||||
"sha256": "d60e6ff8948b6616695297695b05ef6e74b497a8e32e6031fc2e4fe2cca39ca7",
|
||||
"path": "terminal/terminal.js",
|
||||
"size": 4167
|
||||
"size": 4478,
|
||||
"sha256": "0f3edde02b30e7b0f76d0cc88daae5791d720a4b74cf8b34e7c0b4dbe0cf9c9d",
|
||||
"path": "terminal/terminal.js"
|
||||
},
|
||||
{
|
||||
"size": 1261,
|
||||
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
|
||||
"path": "terminal/xterm-LICENSE.txt",
|
||||
"size": 1261
|
||||
"path": "terminal/xterm-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"size": 7112,
|
||||
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
|
||||
"path": "terminal/xterm.css",
|
||||
"size": 7112
|
||||
"path": "terminal/xterm.css"
|
||||
},
|
||||
{
|
||||
"size": 488663,
|
||||
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
|
||||
"path": "terminal/xterm.js",
|
||||
"size": 488663
|
||||
"path": "terminal/xterm.js"
|
||||
},
|
||||
{
|
||||
"size": 4401,
|
||||
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
|
||||
"path": "LICENSE",
|
||||
"size": 4401
|
||||
"path": "LICENSE"
|
||||
},
|
||||
{
|
||||
"size": 1075,
|
||||
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86",
|
||||
"path": "json-LICENSE.txt",
|
||||
"size": 1075
|
||||
"path": "json-LICENSE.txt"
|
||||
},
|
||||
{
|
||||
"size": 883,
|
||||
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
|
||||
"path": "files-text-license.txt",
|
||||
"size": 883
|
||||
"path": "files-text-license.txt"
|
||||
},
|
||||
{
|
||||
"size": 94223,
|
||||
"sha256": "7b34f2af7341f57d7bac1b5b7e55a40595a6bc20f461f98c0c6320336d0deba7",
|
||||
"path": "README.md",
|
||||
"size": 94223
|
||||
"path": "README.md"
|
||||
},
|
||||
{
|
||||
"size": 11418,
|
||||
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada",
|
||||
"path": "LAN-PREVIEW.md",
|
||||
"size": 11418
|
||||
"path": "LAN-PREVIEW.md"
|
||||
},
|
||||
{
|
||||
"size": 682867,
|
||||
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21",
|
||||
"path": "dictionaries/en.txt",
|
||||
"size": 682867
|
||||
"path": "dictionaries/en.txt"
|
||||
},
|
||||
{
|
||||
"size": 20138,
|
||||
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5",
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
|
||||
"size": 20138
|
||||
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
|
||||
},
|
||||
{
|
||||
"size": 2265,
|
||||
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
|
||||
"path": "dictionaries/README.md",
|
||||
"size": 2265
|
||||
"path": "dictionaries/README.md"
|
||||
},
|
||||
{
|
||||
"size": 1060364,
|
||||
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b",
|
||||
"path": "dictionaries/ru.txt",
|
||||
"size": 1060364
|
||||
"path": "dictionaries/ru.txt"
|
||||
},
|
||||
{
|
||||
"size": 1280,
|
||||
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
|
||||
"path": "dictionaries/sources.json",
|
||||
"size": 1280
|
||||
"path": "dictionaries/sources.json"
|
||||
},
|
||||
{
|
||||
"size": 940799,
|
||||
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
|
||||
"path": "dictionaries/uk.txt",
|
||||
"size": 940799
|
||||
"path": "dictionaries/uk.txt"
|
||||
},
|
||||
{
|
||||
"size": 993,
|
||||
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
|
||||
"path": "tools/README.txt",
|
||||
"size": 993
|
||||
"path": "tools/README.txt"
|
||||
},
|
||||
{
|
||||
"sha256": "5513e63e0a9c2a0d3bed65dd8add2c46588093e562d26c5fa2a24a421bd31fcb",
|
||||
"path": "tools/StayHere.exe",
|
||||
"size": 133120
|
||||
"size": 133120,
|
||||
"sha256": "db68aff204ab8c69ded43914e397fda151dce4fdc01f8ac1900db07393a97712",
|
||||
"path": "tools/StayHere.exe"
|
||||
},
|
||||
{
|
||||
"size": 2796,
|
||||
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
|
||||
"path": "tools/StayHere-README.md",
|
||||
"size": 2796
|
||||
"path": "tools/StayHere-README.md"
|
||||
}
|
||||
]
|
||||
],
|
||||
"version": "0.6.93"
|
||||
}
|
||||
+3
-3
@@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
|
||||
1 RT_MANIFEST "app.manifest"
|
||||
201 RCDATA "update.ps1"
|
||||
1 VERSIONINFO
|
||||
FILEVERSION 0,6,85,0
|
||||
PRODUCTVERSION 0,6,85,0
|
||||
FILEVERSION 0,6,93,0
|
||||
PRODUCTVERSION 0,6,93,0
|
||||
FILEOS VOS_NT_WINDOWS32
|
||||
FILETYPE VFT_APP
|
||||
BEGIN
|
||||
@@ -20,7 +20,7 @@ BEGIN
|
||||
BEGIN
|
||||
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
|
||||
VALUE "ProductName", "KSwitcher"
|
||||
VALUE "FileVersion", "0.6.85"
|
||||
VALUE "FileVersion", "0.6.93"
|
||||
END
|
||||
END
|
||||
BLOCK "VarFileInfo"
|
||||
|
||||
+8
-13
@@ -47,24 +47,16 @@ BEGIN
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 153, 42, 60, 17
|
||||
END
|
||||
|
||||
607 DIALOGEX 0, 0, 300, 106
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL | WS_TABSTOP, 18, 22, 264, 52
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 120, 80, 60, 17
|
||||
CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 85, 80, 60, 17
|
||||
CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 155, 80, 60, 17
|
||||
AUTOCHECKBOX "&Remember for this session", 101, 18, 63, 264, 13, NOT WS_VISIBLE
|
||||
END
|
||||
|
||||
609 DIALOGEX 0, 0, 185, 57
|
||||
607 DIALOGEX 0, 0, 185, 57
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "", 100, 14, 16, 157, 13, SS_NOPREFIX
|
||||
CONTROL "", 100, "Edit", ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL, 14, 16, 157, 13
|
||||
AUTOCHECKBOX "&Remember for this session", 101, 14, 30, 157, 13, NOT WS_VISIBLE
|
||||
CONTROL "", 102, "Static", NOT WS_VISIBLE, 14, 35, 1, 1
|
||||
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 67, 38, 51, 15
|
||||
CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 36, 38, 51, 15
|
||||
CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 98, 38, 51, 15
|
||||
END
|
||||
|
||||
608 DIALOGEX 0, 0, 220, 67
|
||||
@@ -114,6 +106,9 @@ BEGIN
|
||||
CONTROL "", 321, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 27, 110, 15
|
||||
LTEXT "Open command history", 322, 131, 53, 120, 12
|
||||
CONTROL "", 323, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 50, 110, 15
|
||||
AUTOCHECKBOX "Allow &paired PCs to run PowerShell commands here", 370, 131, 79, 250, 14
|
||||
AUTOCHECKBOX "Allow paired PCs to &hibernate this PC", 371, 131, 95, 250, 14
|
||||
AUTOCHECKBOX "Allow paired PCs to &update KSwitcher here", 372, 131, 111, 250, 14
|
||||
PUSHBUTTON "Reset selected to defaults", 284, 131, 181, 125, 15
|
||||
COMBOBOX 285, 131, 183, 139, 95, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL
|
||||
PUSHBUTTON "Reset property", 286, 278, 183, 108, 15
|
||||
|
||||
@@ -58,6 +58,15 @@ terminal.attachCustomKeyEventHandler(event => {
|
||||
else if (event.code === 'KeyF' || event.code === 'KeyC') {
|
||||
if (!event.repeat) bridge.postMessage(event.code === 'KeyF' ? 'insert-path' : 'copy-command-line');
|
||||
}
|
||||
else if (event.key === 'Enter') {
|
||||
if (!event.repeat) bridge.postMessage('insert-name');
|
||||
}
|
||||
else if (event.key === 'Insert') {
|
||||
if (!event.repeat) bridge.postMessage('copy-panel-names');
|
||||
}
|
||||
else if (event.code === 'KeyR') {
|
||||
if (!event.repeat) bridge.postMessage('refresh-panel');
|
||||
}
|
||||
else return true;
|
||||
event.preventDefault();
|
||||
return false;
|
||||
|
||||
+68
-5
@@ -4,6 +4,7 @@
|
||||
[string]$InstallDirectory, [string]$WorkDirectory,
|
||||
[int]$ParentProcessId, [string]$ReadyEvent,
|
||||
[switch]$ShowProgress,
|
||||
[switch]$Unattended, [string]$Journal,
|
||||
[switch]$Library
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
@@ -408,12 +409,59 @@ function Undo-Files([string]$Target,[string]$Backup,[Collections.Generic.List[st
|
||||
function Write-Result($Value) {
|
||||
$Value | ConvertTo-Json -Compress | Set-Content -LiteralPath (Join-Path $WorkDirectory 'result.json') -Encoding UTF8
|
||||
}
|
||||
function Write-UpdateJournal([string]$Message) {
|
||||
if (!$Journal) { return }
|
||||
[IO.File]::AppendAllText($Journal, "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') LAN update: $Message`n",
|
||||
[Text.UTF8Encoding]::new($false))
|
||||
}
|
||||
function Stop-UpdateCompanions([string]$Directory) {
|
||||
if (!('KSwitcherUpdateProcessImage' -as [type])) {
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
public static class KSwitcherUpdateProcessImage {
|
||||
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
|
||||
[DllImport("kernel32.dll", CharSet=CharSet.Unicode)]
|
||||
static extern bool QueryFullProcessImageName(IntPtr process, int flags, StringBuilder image, ref int length);
|
||||
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
|
||||
|
||||
public static string Read(int pid) {
|
||||
var process = OpenProcess(0x1000, false, pid);
|
||||
if (process == IntPtr.Zero) return null;
|
||||
try {
|
||||
var length = 32768;
|
||||
var image = new StringBuilder(length);
|
||||
return QueryFullProcessImageName(process, 0, image, ref length) ? image.ToString() : null;
|
||||
} finally { CloseHandle(process); }
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
$root = [IO.Path]::GetFullPath($Directory).TrimEnd('\')
|
||||
$prefix = [regex]::Escape($root + '\')
|
||||
$pattern = '^' + $prefix + '(?:\.kswitcher-update-[0-9a-f]{32}\\backup\\)?KSwitcher\.(?:Config|Screenshot|Files)\.exe$'
|
||||
foreach ($process in @(Get-Process 'KSwitcher.Config','KSwitcher.Screenshot','KSwitcher.Files' -ErrorAction SilentlyContinue)) {
|
||||
$image = [KSwitcherUpdateProcessImage]::Read($process.Id)
|
||||
if (!$image -and !$process.HasExited) {
|
||||
Write-UpdateJournal "Could not identify $($process.ProcessName) (PID $($process.Id))."
|
||||
}
|
||||
if ($image -notmatch $pattern) { continue }
|
||||
Write-UpdateJournal "Closing $($process.ProcessName) (PID $($process.Id))."
|
||||
if (!$process.HasExited) {
|
||||
try { $process.Kill() } catch { if (!$process.HasExited) { throw } }
|
||||
if (!$process.WaitForExit(10000)) { throw "Could not close $($process.ProcessName) (PID $($process.Id))." }
|
||||
}
|
||||
Write-UpdateJournal "Closed $($process.ProcessName) (PID $($process.Id))."
|
||||
}
|
||||
}
|
||||
if ($Library) { return }
|
||||
$transaction = $null; $parentProcess = $null; $ready = $null; $started = $null
|
||||
$changed = [Collections.Generic.List[string]]::new()
|
||||
$parentExited = $false; $success = $false; $preserveBackup = $false; $child = $null; $uiFinished = $false
|
||||
try {
|
||||
if ($ShowProgress -or $Mode -eq 'Install') { Start-UpdateProgress }
|
||||
if (!$Unattended -and ($ShowProgress -or $Mode -eq 'Install')) { Start-UpdateProgress }
|
||||
$current = Get-StableVersion $CurrentVersion
|
||||
if (!$current) { throw 'Invalid installed version.' }
|
||||
if ($Mode -eq 'Install') {
|
||||
@@ -426,9 +474,12 @@ try {
|
||||
$metadata = Join-Path $WorkDirectory 'releases.json'
|
||||
Receive-File 'https://gitea.hrynco.com/api/v1/repos/hrynco/hrynco-kswitcher/releases?limit=100' $metadata 2MB
|
||||
$release = Select-Release (Get-Content -LiteralPath $metadata -Raw | ConvertFrom-Json) $current
|
||||
if (!$release) { Write-Result @{state='current'}; exit 0 }
|
||||
if (!$release) {
|
||||
if ($Unattended) { Write-UpdateJournal "No newer stable release is available ($CurrentVersion)." }
|
||||
Write-Result @{state='current'}; exit 0
|
||||
}
|
||||
if ($Mode -eq 'Check') { Write-Result @{state='available';version=$release.version}; exit 0 }
|
||||
if ($ExpectedVersion -ne $release.version) { throw 'Release changed since checking. Please select Update again.' }
|
||||
if (!$Unattended -and $ExpectedVersion -ne $release.version) { throw 'Release changed since checking. Please select Update again.' }
|
||||
Assert-PlainDirectory $InstallDirectory
|
||||
$transaction = Join-Path $InstallDirectory ('.kswitcher-update-'+[guid]::NewGuid().ToString('N'))
|
||||
$stage = Join-Path $transaction 'stage'; $backup = Join-Path $transaction 'backup'
|
||||
@@ -442,12 +493,18 @@ try {
|
||||
Show-UpdateProgress 'Preparing installation' 'Validating and unpacking the release files'
|
||||
Expand-Release $archive $stage (Get-StableVersion $release.version)
|
||||
$screenshotPath = [IO.Path]::GetFullPath((Join-Path $InstallDirectory 'KSwitcher.Screenshot.exe'))
|
||||
if (Get-Process 'KSwitcher.Screenshot' -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $screenshotPath }) { throw 'Close screenshot editors before installing an update.' }
|
||||
if (!$Unattended -and (Get-Process 'KSwitcher.Screenshot' -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $screenshotPath })) {
|
||||
throw 'Close screenshot editors before installing an update.'
|
||||
}
|
||||
if ($Unattended) {
|
||||
Write-UpdateJournal "Verified $($release.version). Closing KSwitcher (PID $ParentProcessId)."
|
||||
}
|
||||
Write-Result @{state='prepared';version=$release.version}
|
||||
Show-UpdateProgress 'Closing KSwitcher' 'Waiting for the running application to exit safely'
|
||||
$ready.Set() | Out-Null
|
||||
if (!$parentProcess.WaitForExit(120000)) { throw 'KSwitcher did not exit; the installed files were not changed.' }
|
||||
$parentExited = $true
|
||||
if ($Unattended) { Stop-UpdateCompanions $InstallDirectory }
|
||||
Show-UpdateProgress 'Installing update' 'Replacing application files; keeping your personal data'
|
||||
Install-Files $stage $InstallDirectory $backup $changed
|
||||
$startedName = 'Local\KSwitcher.Update.Started.'+[guid]::NewGuid().ToString('N')
|
||||
@@ -456,6 +513,9 @@ try {
|
||||
$child = Start-Process -FilePath (Join-Path $InstallDirectory 'KSwitcher.exe') -ArgumentList "--update-ready-event=$startedName" -WorkingDirectory $InstallDirectory -WindowStyle Hidden -PassThru
|
||||
if (!$started.WaitOne(30000) -or $child.HasExited) { throw 'The updated application did not confirm startup.' }
|
||||
$success = $true
|
||||
if ($Unattended) {
|
||||
try { Write-UpdateJournal "Completed $($release.version). KSwitcher restarted." } catch {}
|
||||
}
|
||||
if ($script:progressWindow) {
|
||||
$uiFinished = Complete-UpdateProgress 'Update completed' "KSwitcher $(Get-StableVersion $release.version) is now running." $true
|
||||
}
|
||||
@@ -474,7 +534,10 @@ try {
|
||||
}
|
||||
}
|
||||
Write-Result @{state='error';error=$message}
|
||||
if ($ready -and $ready.WaitOne(0)) {
|
||||
if ($Unattended) {
|
||||
try { Write-UpdateJournal "Failed. $($message -replace '[\r\n]+',' ')" } catch {}
|
||||
}
|
||||
if (!$Unattended -and $ready -and $ready.WaitOne(0)) {
|
||||
if ($script:progressWindow) {
|
||||
$uiFinished = Complete-UpdateProgress 'Update failed' $message $false
|
||||
} else {
|
||||
|
||||
+25
-2
@@ -4,6 +4,7 @@
|
||||
#include "../resources/resource.h"
|
||||
#include "ocr.h"
|
||||
#include "lan_clipboard_image.h"
|
||||
#include "lan_files.h"
|
||||
#include "configuration.h"
|
||||
#include "diagnostics.h"
|
||||
#include "paste_probe.h"
|
||||
@@ -2941,12 +2942,12 @@ void App::trayMenu()
|
||||
void App::checkUpdate(bool interactive, bool install, const std::wstring &version)
|
||||
{
|
||||
if (updateRunning) return;
|
||||
if (install && FindWindowW(L"KSwitcher.Config", nullptr))
|
||||
if (install && interactive && FindWindowW(L"KSwitcher.Config", nullptr))
|
||||
{
|
||||
report(L"Close the configurator before installing an update.");
|
||||
return;
|
||||
}
|
||||
if (install && busy)
|
||||
if (install && interactive && busy)
|
||||
{
|
||||
report(L"Wait for the current text operation to finish, then select Update again.");
|
||||
return;
|
||||
@@ -3006,6 +3007,22 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
switch (msg)
|
||||
{
|
||||
case LanUpdateRequestedMessage:
|
||||
if (!lan::remoteUpdateAllowed()) return 0;
|
||||
if (app->updateRunning)
|
||||
{
|
||||
if (!app->installingUpdate)
|
||||
{
|
||||
app->lanUpdatePending = true;
|
||||
log(L"LAN update queued behind an update check.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
log(L"Starting unattended KSwitcher update requested over LAN.");
|
||||
app->checkUpdate(false, true);
|
||||
}
|
||||
return 0;
|
||||
case UpdateMessage:
|
||||
{
|
||||
std::unique_ptr<UpdateResult> result(reinterpret_cast<UpdateResult *>(lp));
|
||||
@@ -3019,6 +3036,12 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
|
||||
// The helper has verified and staged the package; it waits for process exit.
|
||||
DestroyWindow(hwnd);
|
||||
}
|
||||
else if (std::exchange(app->lanUpdatePending, false) && lan::remoteUpdateAllowed() &&
|
||||
result->state != L"current")
|
||||
{
|
||||
log(L"Starting queued unattended KSwitcher update.");
|
||||
app->checkUpdate(false, true);
|
||||
}
|
||||
else if (result->state == L"available")
|
||||
{
|
||||
app->availableUpdate = result->version;
|
||||
|
||||
@@ -155,7 +155,7 @@ class App
|
||||
std::vector<SyncConflict> pendingSyncConflicts;
|
||||
Bytes syncSnapshot;
|
||||
std::wstring syncStatus = L"Not connected.";
|
||||
bool updateRunning{}, installingUpdate{};
|
||||
bool updateRunning{}, installingUpdate{}, lanUpdatePending{};
|
||||
std::wstring availableUpdate, notifiedUpdate;
|
||||
bool (*updateNotifier)(const std::wstring &){};
|
||||
bool stop{};
|
||||
|
||||
+16
-5
@@ -4,17 +4,25 @@
|
||||
#include <cstring>
|
||||
namespace ks
|
||||
{
|
||||
bool configurationPeer(HWND window, const wchar_t *filename)
|
||||
namespace
|
||||
{
|
||||
std::filesystem::path processImage(HWND window)
|
||||
{
|
||||
DWORD pid{};
|
||||
GetWindowThreadProcessId(window, &pid);
|
||||
HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
|
||||
if (!process) return false;
|
||||
if (!process) return {};
|
||||
wchar_t path[32768]; DWORD count = std::size(path);
|
||||
bool ok = QueryFullProcessImageNameW(process, 0, path, &count) != 0;
|
||||
CloseHandle(process);
|
||||
auto expected = std::filesystem::path(executable()).parent_path() / filename;
|
||||
return ok && _wcsicmp(path, expected.c_str()) == 0;
|
||||
return ok ? std::filesystem::path(path) : std::filesystem::path{};
|
||||
}
|
||||
}
|
||||
|
||||
bool configurationPeer(HWND window, const wchar_t *filename)
|
||||
{
|
||||
const auto expected = std::filesystem::path(executable()).parent_path() / filename;
|
||||
return _wcsicmp(processImage(window).c_str(), expected.c_str()) == 0;
|
||||
}
|
||||
void launchConfiguration(App &app, bool snippets, bool logs)
|
||||
{
|
||||
@@ -35,7 +43,10 @@ void launchConfiguration(App &app, bool snippets, bool logs)
|
||||
LRESULT configurationRequest(App &app, HWND sender, const COPYDATASTRUCT &message)
|
||||
{
|
||||
const bool filesPeers = message.dwData == FilesLanPeers;
|
||||
if (!configurationPeer(sender, filesPeers ? L"KSwitcher.Files.exe" : L"KSwitcher.Config.exe") || message.cbData > ConfigLimit ||
|
||||
const bool knownSender = filesPeers
|
||||
? isFilesPeerImage(processImage(sender), std::filesystem::path(executable()).parent_path())
|
||||
: configurationPeer(sender, L"KSwitcher.Config.exe");
|
||||
if (!knownSender || message.cbData > ConfigLimit ||
|
||||
(message.cbData && !message.lpData)) return FALSE;
|
||||
Bytes reply;
|
||||
bool ok = false;
|
||||
|
||||
@@ -12,7 +12,7 @@ bool validHistoryKeys(const std::array<WORD,2> &keys)
|
||||
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!='V' && key!='X' && key!='A' && key!='Z' && key!='Y') || function;
|
||||
return (letter && key!='C' && key!='F' && key!='R' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y') || function;
|
||||
if(modifiers==HOTKEYF_ALT) return function && key!=VK_F1 && key!=VK_F2 && key!=VK_F4 && key!=VK_F10;
|
||||
return false;
|
||||
});
|
||||
|
||||
@@ -1,6 +1,30 @@
|
||||
#pragma once
|
||||
#include <windows.h>
|
||||
#include <filesystem>
|
||||
#include <string_view>
|
||||
|
||||
inline constexpr ULONG_PTR FilesLanPeers = 0x4b53010d;
|
||||
inline constexpr ULONG_PTR FilesLanPeersReply = 0x4b53010e;
|
||||
inline constexpr DWORD FilesLanPeersLimit = 64 * 1024;
|
||||
|
||||
namespace ks
|
||||
{
|
||||
inline bool isFilesPeerImage(const std::filesystem::path &image, const std::filesystem::path &install)
|
||||
{
|
||||
if (_wcsicmp(image.filename().c_str(), L"KSwitcher.Files.exe") != 0) return false;
|
||||
const auto directory = image.parent_path();
|
||||
if (_wcsicmp(directory.c_str(), install.c_str()) == 0) return true;
|
||||
|
||||
// Updating moves a still-running Files executable into the transaction backup.
|
||||
// Windows then reports the moved path for its process image.
|
||||
if (_wcsicmp(directory.filename().c_str(), L"backup") != 0) return false;
|
||||
const auto transaction = directory.parent_path();
|
||||
if (_wcsicmp(transaction.parent_path().c_str(), install.c_str()) != 0) return false;
|
||||
constexpr std::wstring_view prefix = L".kswitcher-update-";
|
||||
const auto name = transaction.filename().wstring();
|
||||
if (name.size() != prefix.size() + 32 || _wcsnicmp(name.c_str(), prefix.data(), prefix.size()) != 0)
|
||||
return false;
|
||||
return std::wstring_view(name).substr(prefix.size()).find_first_not_of(L"0123456789abcdefABCDEF")
|
||||
== std::wstring_view::npos;
|
||||
}
|
||||
}
|
||||
+556
-116
File diff suppressed because it is too large.
Load diff
+32
-7
@@ -1,4 +1,5 @@
|
||||
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286;
|
||||
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286,
|
||||
optionsRemoteTerminal=370,optionsRemoteHibernate=371,optionsRemoteUpdate=372;
|
||||
enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine, TextViewer, TextEditor, allOptions };
|
||||
constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line",L"Viewer",L"Editor"};
|
||||
constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Popup background",
|
||||
@@ -78,6 +79,9 @@ struct OptionsBaseline
|
||||
std::array<COLORREF,ColorCount> palette=colors;
|
||||
std::vector<FileStyle> styles=fileStyles;
|
||||
std::array<WORD,2> keys=commandHistoryKeys;
|
||||
bool remoteTerminal=ks::lan::remoteTerminalAllowed();
|
||||
bool remoteHibernate=ks::lan::remoteHibernateAllowed();
|
||||
bool remoteUpdate=ks::lan::remoteUpdateAllowed();
|
||||
DWORD width=static_cast<DWORD>(sizeWidth), fields=statusFields;
|
||||
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
|
||||
std::array<bool,2> wide{panels[0].wide,panels[1].wide};
|
||||
@@ -151,7 +155,10 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
|
||||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
|
||||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
|
||||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
|
||||
optionHistoryKeys(dialog)!=base.keys || draft.text!=base.text;
|
||||
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
|
||||
checked(optionsRemoteHibernate)!=base.remoteHibernate ||
|
||||
checked(optionsRemoteUpdate)!=base.remoteUpdate ||
|
||||
draft.text!=base.text;
|
||||
EnableWindow(GetDlgItem(dialog,optionsApply),dirty);
|
||||
InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE);
|
||||
}
|
||||
@@ -299,7 +306,8 @@ void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files
|
||||
[&](const auto &scheme){return sameSchemeName(name,scheme.name.c_str());});
|
||||
if(existing!=settings.schemes.end())
|
||||
{
|
||||
if(showFilesNotice(dialog,L"Replace the saved scheme with the current colors?",L"Save color scheme",true)!=IDYES) return;
|
||||
if(showFilesNotice(dialog,L"Replace the saved scheme with the current colors?",L"Save color scheme",
|
||||
{.confirm=true,.tone=FilesNoticeTone::neutral})!=IDYES) return;
|
||||
existing->colors=profile.colors;
|
||||
profile.scheme=existing->name;
|
||||
}
|
||||
@@ -420,7 +428,7 @@ 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};
|
||||
constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
|
||||
show(commandLineControls,page==CommandLine && section==0);
|
||||
show(textControls,textOptionsPage(page));
|
||||
show(editingControls,page==TextEditor);
|
||||
@@ -515,7 +523,9 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
addSection(L"File type styles",fileStyleSection,extensionMatches || matches(L"System and hidden") ||
|
||||
matches(L"Underline") || matches(L"Strikethrough") || matches(L"Foreground"));
|
||||
}
|
||||
else if(page==CommandLine) addSection(L"Command history",0,matches(L"Previous command"));
|
||||
else if(page==CommandLine) addSection(L"Command history",0,
|
||||
matches(L"Previous command") || matches(L"Allow paired PCs to run PowerShell commands here") ||
|
||||
matches(L"Allow paired PCs to hibernate this PC") || matches(L"Allow paired PCs to update KSwitcher here"));
|
||||
else if(textOptionsPage(page))
|
||||
{
|
||||
const bool propertyMatches=matches(L"Tab width") ||
|
||||
@@ -579,6 +589,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,274,panels[1].wide);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
|
||||
CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed());
|
||||
CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed());
|
||||
filterOptions(dialog,draft);
|
||||
updateOptionsApply(dialog,draft);
|
||||
return TRUE;
|
||||
@@ -692,7 +705,13 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
return TRUE;
|
||||
case optionsReset:
|
||||
if(draft->page==allOptions || draft->page==CommandLine) setOptionHistoryKeys(dialog,defaultHistoryKeys);
|
||||
if(draft->page==allOptions || draft->page==CommandLine)
|
||||
{
|
||||
setOptionHistoryKeys(dialog,defaultHistoryKeys);
|
||||
CheckDlgButton(dialog,optionsRemoteTerminal,BST_UNCHECKED);
|
||||
CheckDlgButton(dialog,optionsRemoteHibernate,BST_UNCHECKED);
|
||||
CheckDlgButton(dialog,optionsRemoteUpdate,BST_UNCHECKED);
|
||||
}
|
||||
if(draft->page==allOptions || draft->page==PanelModes)
|
||||
for(const auto &property:panelProperties)
|
||||
if(draft->section<0 || property.section==draft->section) resetPanelProperty(dialog,property);
|
||||
@@ -731,7 +750,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
case 201:
|
||||
case 202: case 203: case 204: case 205: case 206: case 207: case 208:
|
||||
case 273: case 274:
|
||||
case 273: case 274: case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case 321: case 323:
|
||||
@@ -831,6 +850,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
const auto inputKeys=optionHistoryKeys(dialog);
|
||||
saveChanged(L"PreviousCommandKey",inputKeys[0],base.keys[0]);
|
||||
saveChanged(L"CommandHistoryKey",inputKeys[1],base.keys[1]);
|
||||
saveChanged(ks::lan::remoteTerminalPreference,checked(optionsRemoteTerminal),base.remoteTerminal);
|
||||
saveChanged(ks::lan::remoteHibernatePreference,checked(optionsRemoteHibernate),base.remoteHibernate);
|
||||
saveChanged(ks::lan::remoteUpdatePreference,checked(optionsRemoteUpdate),base.remoteUpdate);
|
||||
saveChanged(L"SizeWidth",width,base.width);
|
||||
saveChanged(L"AlignExtensions",checked(202),base.extensions);
|
||||
saveChanged(L"AlignFolders",checked(204),base.folders);
|
||||
@@ -876,6 +898,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,274,panels[1].wide);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed());
|
||||
CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed());
|
||||
CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed());
|
||||
if(draft->page==PanelColors && draft->section==fileStyleSection)
|
||||
updateFileStyleEditor(dialog,*draft,true);
|
||||
showOptionsPage(dialog,*draft,draft->page,draft->section);
|
||||
|
||||
@@ -1240,8 +1240,10 @@ void TextWindow::paint()
|
||||
RECT client{};
|
||||
GetClientRect(window, &client);
|
||||
const auto row = chromeHeight();
|
||||
SetDCBrushColor(dc, color(TextColor::chromebg));
|
||||
const auto brush = static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
|
||||
SetDCBrushColor(dc, color(TextColor::background));
|
||||
FillRect(dc, &client, brush);
|
||||
SetDCBrushColor(dc, color(TextColor::chromebg));
|
||||
RECT menuBar{0, 0, client.right, row};
|
||||
RECT top{0, row, client.right, 2 * row};
|
||||
RECT bottom{0, client.bottom - row, client.right, client.bottom};
|
||||
@@ -1500,7 +1502,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
identity.data(),static_cast<int>(identity.size()),TRUE)==CSTR_EQUAL;
|
||||
}
|
||||
case WM_CREATE:
|
||||
self->editor = CreateWindowExW(0, L"Scintilla", L"", WS_CHILD | WS_VISIBLE | WS_TABSTOP |
|
||||
self->editor = CreateWindowExW(0, L"Scintilla", L"", WS_CHILD | WS_TABSTOP |
|
||||
WS_VSCROLL | WS_HSCROLL, 0, 0, 0, 0, window, nullptr, GetModuleHandleW(nullptr), nullptr);
|
||||
if (!self->editor) throw std::runtime_error("Cannot create the text control.");
|
||||
self->send(SCI_SETCODEPAGE, SC_CP_UTF8);
|
||||
@@ -1519,6 +1521,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
},1,reinterpret_cast<DWORD_PTR>(self.get()));
|
||||
if(self->remote)
|
||||
{
|
||||
self->applyPreferences();
|
||||
self->send(SCI_SETREADONLY,TRUE);
|
||||
if(!SetTimer(window,openTimer,75,nullptr))
|
||||
throw std::runtime_error("Cannot start the LAN file timer.");
|
||||
@@ -1529,6 +1532,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
}
|
||||
else self->initializeDocument();
|
||||
self->layout();
|
||||
ShowWindow(self->editor,SW_SHOWNA);
|
||||
return 0;
|
||||
case WM_ERASEBKGND: return 1;
|
||||
case WM_PAINT: self->paint(); return 0;
|
||||
|
||||
+12
-3
@@ -295,15 +295,25 @@ struct LanService::Impl
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
return !stopping && trusted.contains(peer)?trusted.at(peer).at("key").get<std::string>():std::string{};
|
||||
},lan::FilesPort,lan::remoteTerminalAllowed,lan::hibernateFromPairedPC,[this]() -> DWORD
|
||||
{
|
||||
if(!lan::remoteUpdateAllowed()) return ERROR_ACCESS_DENIED;
|
||||
if(!inputWindow) return ERROR_INVALID_WINDOW_HANDLE;
|
||||
return PostMessageW(inputWindow,LanUpdateRequestedMessage,0,0)?ERROR_SUCCESS:GetLastError();
|
||||
});
|
||||
hub.datagrams([&](const auto &target,const auto &packet){
|
||||
std::lock_guard lock(mutex);
|
||||
if(shareInput&&trusted.contains(target)&&peers.contains(target))send(socket,peers.at(target).address,packet);
|
||||
});
|
||||
const bool filesListening=files.port()!=0;
|
||||
if(!filesListening) diagnosticEvent(L"LAN Files could not listen on TCP 45885.");
|
||||
bool filesListening=files.port()!=0;
|
||||
while(!stopping)
|
||||
{
|
||||
files.poll();
|
||||
if(filesListening!=(files.port()!=0))
|
||||
{
|
||||
filesListening=files.port()!=0;
|
||||
nextHello=0;
|
||||
}
|
||||
auto now=GetTickCount64();bool clipboardActive=false;
|
||||
std::vector<lan::InputEndpoint> endpoints;
|
||||
{
|
||||
@@ -341,7 +351,6 @@ struct LanService::Impl
|
||||
{std::lock_guard lock(inputMutex);out.swap(inputOut);}
|
||||
if(abortInput.exchange(false)){hub.disconnect();out.clear();}
|
||||
hub.poll(endpoints,out,in,now);
|
||||
files.poll();
|
||||
auto readyPeers=hub.ready();inputConnected=!readyPeers.empty();
|
||||
{std::lock_guard lock(inputMutex);inputReady=std::move(readyPeers);
|
||||
for(auto &frame:in){
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace ks
|
||||
{
|
||||
inline constexpr UINT LanInputReadyMessage=WM_APP+67, LanClipboardReadyMessage=WM_APP+68, LanClipboardPublishMessage=WM_APP+69;
|
||||
inline constexpr UINT LanFilesChangedMessage=WM_APP+70;
|
||||
inline constexpr UINT LanUpdateRequestedMessage=WM_APP+90;
|
||||
struct LanClipboard {std::string peer,name,app;Bytes data;DWORD sequence{};};
|
||||
// Discovery, pairing and optional encrypted input within the resident process.
|
||||
class LanService
|
||||
|
||||
+245
-17
@@ -5,6 +5,8 @@
|
||||
#include <winioctl.h>
|
||||
#include <atomic>
|
||||
#include <bcrypt.h>
|
||||
#include <wincrypt.h>
|
||||
#include <sddl.h>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
@@ -31,6 +33,17 @@ void checkFileReply(const Json &reply)
|
||||
if(error) throw std::system_error(static_cast<int>(error),std::system_category());
|
||||
}
|
||||
|
||||
static bool filesPermissionEnabled(const wchar_t *name)
|
||||
{
|
||||
DWORD allowed{},size=sizeof(allowed);
|
||||
return RegGetValueW(HKEY_CURRENT_USER,L"Software\\KSwitcher\\Files",name,
|
||||
RRF_RT_REG_DWORD,nullptr,&allowed,&size)==ERROR_SUCCESS && allowed==1;
|
||||
}
|
||||
|
||||
bool remoteTerminalAllowed() {return filesPermissionEnabled(remoteTerminalPreference);}
|
||||
bool remoteHibernateAllowed() {return filesPermissionEnabled(remoteHibernatePreference);}
|
||||
bool remoteUpdateAllowed() {return filesPermissionEnabled(remoteUpdatePreference);}
|
||||
|
||||
bool recycleFile(HWND owner,const fs::path &path)
|
||||
{
|
||||
const auto initialized=CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED);
|
||||
@@ -223,6 +236,148 @@ struct FileHandle
|
||||
~FileHandle(){close();}
|
||||
};
|
||||
|
||||
DWORD requestSystemHibernate()
|
||||
{
|
||||
wchar_t system[MAX_PATH]{};
|
||||
const auto length=GetSystemDirectoryW(system,MAX_PATH);
|
||||
if(!length) return GetLastError();
|
||||
if(length>=MAX_PATH) return ERROR_INSUFFICIENT_BUFFER;
|
||||
const auto executable=fs::path(system)/L"shutdown.exe";
|
||||
wchar_t command[]=L"shutdown.exe /h";
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
PROCESS_INFORMATION child{};
|
||||
if(!CreateProcessW(executable.c_str(),command,nullptr,nullptr,FALSE,CREATE_NO_WINDOW,
|
||||
nullptr,system,&startup,&child)) return GetLastError();
|
||||
CloseHandle(child.hThread);
|
||||
FileHandle process{child.hProcess};
|
||||
const auto wait=WaitForSingleObject(process.value,3000);
|
||||
if(wait==WAIT_TIMEOUT) return ERROR_TIMEOUT;
|
||||
if(wait!=WAIT_OBJECT_0) return GetLastError();
|
||||
DWORD exitCode{};
|
||||
return GetExitCodeProcess(process.value,&exitCode)?exitCode:GetLastError();
|
||||
}
|
||||
|
||||
struct RemoteCommand
|
||||
{
|
||||
FileHandle job,process,output;
|
||||
|
||||
void stop()
|
||||
{
|
||||
job.close();
|
||||
process.close();
|
||||
output.close();
|
||||
}
|
||||
|
||||
DWORD start(const fs::path &directory,const std::wstring &command)
|
||||
{
|
||||
if(process.value!=INVALID_HANDLE_VALUE) return ERROR_BUSY;
|
||||
if(command.empty() || command.size()>12000 || command.find(L'\0')!=command.npos) return ERROR_INVALID_PARAMETER;
|
||||
const auto script=L"$ProgressPreference='SilentlyContinue'; "
|
||||
L"[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); "
|
||||
L"$OutputEncoding=[Console]::OutputEncoding;\r\n"+command;
|
||||
const auto data=reinterpret_cast<const BYTE *>(script.data());
|
||||
const auto bytes=static_cast<DWORD>(script.size()*sizeof(wchar_t));
|
||||
constexpr DWORD encoding=CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF;
|
||||
DWORD length{};
|
||||
if(!CryptBinaryToStringW(data,bytes,encoding,nullptr,&length)) return GetLastError();
|
||||
std::wstring encoded(length,L'\0');
|
||||
if(!CryptBinaryToStringW(data,bytes,encoding,encoded.data(),&length)) return GetLastError();
|
||||
encoded.resize(length);
|
||||
// Windows PowerShell serializes its error stream as CLIXML with -EncodedCommand.
|
||||
// Decode the command inside a fixed text-mode expression instead.
|
||||
auto arguments=L"powershell.exe -NoLogo -NoProfile -NonInteractive -OutputFormat Text -Command "
|
||||
L"\"& ([ScriptBlock]::Create([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('"+
|
||||
encoded+L"'))))\"";
|
||||
wchar_t system[MAX_PATH]{};
|
||||
if(!GetSystemDirectoryW(system,MAX_PATH)) return GetLastError();
|
||||
const auto shell=std::wstring(system)+L"\\WindowsPowerShell\\v1.0\\powershell.exe";
|
||||
|
||||
FileHandle token,restricted,read,write,input,processJob;
|
||||
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|
|
||||
TOKEN_ADJUST_DEFAULT,&token.value) ||
|
||||
!CreateRestrictedToken(token.value,DISABLE_MAX_PRIVILEGE|LUA_TOKEN,0,nullptr,0,nullptr,0,nullptr,
|
||||
&restricted.value)) return GetLastError();
|
||||
PSID medium{};
|
||||
if(!ConvertStringSidToSidW(L"S-1-16-8192",&medium)) return GetLastError();
|
||||
TOKEN_MANDATORY_LABEL label{{medium,SE_GROUP_INTEGRITY}};
|
||||
const auto limited=SetTokenInformation(restricted.value,TokenIntegrityLevel,&label,
|
||||
sizeof(label)+GetLengthSid(medium));
|
||||
const auto tokenError=GetLastError();
|
||||
LocalFree(medium);
|
||||
if(!limited) return tokenError;
|
||||
|
||||
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
|
||||
if(!CreatePipe(&read.value,&write.value,&inheritable,0) ||
|
||||
!SetHandleInformation(read.value,HANDLE_FLAG_INHERIT,0)) return GetLastError();
|
||||
input.value=CreateFileW(L"NUL",GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&inheritable,
|
||||
OPEN_EXISTING,0,nullptr);
|
||||
if(input.value==INVALID_HANDLE_VALUE) return GetLastError();
|
||||
const auto createdJob=CreateJobObjectW(nullptr,nullptr);
|
||||
if(!createdJob) return GetLastError();
|
||||
processJob.value=createdJob;
|
||||
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
|
||||
limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
if(!SetInformationJobObject(processJob.value,JobObjectExtendedLimitInformation,&limits,sizeof(limits)))
|
||||
return GetLastError();
|
||||
|
||||
SIZE_T attributeBytes{};
|
||||
InitializeProcThreadAttributeList(nullptr,1,0,&attributeBytes);
|
||||
std::vector<BYTE> storage(attributeBytes);
|
||||
const auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
|
||||
if(!InitializeProcThreadAttributeList(attributes,1,0,&attributeBytes)) return GetLastError();
|
||||
HANDLE inherited[]{input.value,write.value};
|
||||
STARTUPINFOEXW startup{};
|
||||
startup.StartupInfo.cb=sizeof(startup);
|
||||
startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES;
|
||||
startup.StartupInfo.hStdInput=input.value;
|
||||
startup.StartupInfo.hStdOutput=startup.StartupInfo.hStdError=write.value;
|
||||
startup.lpAttributeList=attributes;
|
||||
PROCESS_INFORMATION child{};
|
||||
const auto started=UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
|
||||
inherited,sizeof(inherited),nullptr,nullptr) &&
|
||||
CreateProcessAsUserW(restricted.value,shell.c_str(),arguments.data(),nullptr,nullptr,TRUE,
|
||||
CREATE_SUSPENDED|CREATE_NO_WINDOW|EXTENDED_STARTUPINFO_PRESENT,nullptr,
|
||||
directory.c_str(),&startup.StartupInfo,&child);
|
||||
const auto processError=GetLastError();
|
||||
DeleteProcThreadAttributeList(attributes);
|
||||
if(!started) return processError;
|
||||
FileHandle thread{child.hThread},childProcess{child.hProcess};
|
||||
if(!AssignProcessToJobObject(processJob.value,childProcess.value) || ResumeThread(thread.value)==DWORD(-1))
|
||||
{
|
||||
const auto error=GetLastError();
|
||||
TerminateProcess(childProcess.value,error);
|
||||
return error;
|
||||
}
|
||||
job.value=std::exchange(processJob.value,INVALID_HANDLE_VALUE);
|
||||
process.value=std::exchange(childProcess.value,INVALID_HANDLE_VALUE);
|
||||
output.value=std::exchange(read.value,INVALID_HANDLE_VALUE);
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
Json poll()
|
||||
{
|
||||
if(process.value==INVALID_HANDLE_VALUE) return failure(ERROR_INVALID_HANDLE);
|
||||
const auto wait=WaitForSingleObject(process.value,0);
|
||||
if(wait==WAIT_FAILED) return failure();
|
||||
DWORD available{};
|
||||
if(!PeekNamedPipe(output.value,nullptr,0,nullptr,&available,nullptr) && GetLastError()!=ERROR_BROKEN_PIPE)
|
||||
return failure();
|
||||
Bytes bytes(std::min<DWORD>(available,FileChunk));
|
||||
DWORD read{};
|
||||
if(!bytes.empty() && !ReadFile(output.value,bytes.data(),static_cast<DWORD>(bytes.size()),&read,nullptr))
|
||||
return failure();
|
||||
bytes.resize(read);
|
||||
const bool done=wait==WAIT_OBJECT_0 && bytes.empty();
|
||||
DWORD exitCode{};
|
||||
if(done)
|
||||
{
|
||||
if(!GetExitCodeProcess(process.value,&exitCode)) return failure();
|
||||
stop();
|
||||
}
|
||||
return {{"error",0},{"data",Json::binary(std::move(bytes))},{"done",done},{"exitCode",exitCode}};
|
||||
}
|
||||
};
|
||||
|
||||
fs::path temporaryFile(const fs::path &target)
|
||||
{
|
||||
return target.parent_path()/wide(".kswitcher-"+randomHex(16)+".tmp");
|
||||
@@ -272,6 +427,9 @@ std::string hashPrefix(HANDLE file,uint64_t size,const FileProgress &progress,ui
|
||||
|
||||
class FileOperations
|
||||
{
|
||||
FilesListener::TerminalPermission terminalPermission;
|
||||
FilesListener::HostAction hibernate,update;
|
||||
RemoteCommand terminal;
|
||||
bool remote;
|
||||
HANDLE search=INVALID_HANDLE_VALUE;
|
||||
WIN32_FIND_DATAW entry{};
|
||||
@@ -426,7 +584,10 @@ class FileOperations
|
||||
return reply;
|
||||
}
|
||||
public:
|
||||
explicit FileOperations(bool remote):remote(remote){}
|
||||
explicit FileOperations(bool remote,FilesListener::TerminalPermission permission={},
|
||||
FilesListener::HostAction hibernateAction={},FilesListener::HostAction updateAction={}):
|
||||
terminalPermission(std::move(permission)),hibernate(std::move(hibernateAction)),
|
||||
update(std::move(updateAction)),remote(remote){}
|
||||
~FileOperations(){closeSearch();discard();}
|
||||
Json call(const Json &request,const FileProgress &progress)
|
||||
{
|
||||
@@ -440,6 +601,26 @@ public:
|
||||
Json perform(const Json &request,const FileProgress &progress)
|
||||
{
|
||||
const auto action=request.at("action").get<std::string>();
|
||||
if(action=="hibernate" || action=="update")
|
||||
{
|
||||
if(request.size()!=1) return failure(ERROR_INVALID_PARAMETER);
|
||||
const auto &hostAction=action=="hibernate"?hibernate:update;
|
||||
if(!remote || !hostAction) return failure(ERROR_ACCESS_DENIED);
|
||||
const auto error=hostAction();
|
||||
return error?failure(error):ok();
|
||||
}
|
||||
if(action=="terminalRun" || action=="terminalPoll" || action=="terminalCancel")
|
||||
{
|
||||
if(!remote || !terminalPermission || !terminalPermission())
|
||||
{
|
||||
terminal.stop();
|
||||
return failure(ERROR_ACCESS_DENIED);
|
||||
}
|
||||
if(action=="terminalCancel") {terminal.stop();return ok();}
|
||||
if(action=="terminalPoll") return terminal.poll();
|
||||
const auto error=terminal.start(path(request.at("path")),wide(request.at("command").get<std::string>()));
|
||||
return error?failure(error):ok();
|
||||
}
|
||||
if(action=="drives")
|
||||
{
|
||||
auto reply=ok();
|
||||
@@ -720,6 +901,12 @@ struct FilesConnection::Impl
|
||||
}
|
||||
};
|
||||
|
||||
DWORD hibernateFromPairedPC()
|
||||
{
|
||||
if(!remoteHibernateAllowed()) return ERROR_ACCESS_DENIED;
|
||||
return requestSystemHibernate();
|
||||
}
|
||||
|
||||
FilesConnection::FilesConnection(const FilesPeer *peer):impl(std::make_unique<Impl>(peer)){}
|
||||
FilesConnection::FilesConnection(const FilesPeer &peer,const std::string &local,const std::string &key):
|
||||
impl(std::make_unique<Impl>())
|
||||
@@ -805,6 +992,26 @@ void streamFile(FilesConnection &source,FilesConnection &target,const std::strin
|
||||
}
|
||||
}
|
||||
|
||||
DWORD runRemoteCommand(FilesConnection &host,const fs::path &directory,std::wstring_view command,
|
||||
const std::function<void(std::string_view)> &output,std::stop_token stop)
|
||||
{
|
||||
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
|
||||
auto request=fileRequest("terminalRun",directory);
|
||||
request["command"]=utf8(std::wstring(command));
|
||||
checkFileReply(host.call(request));
|
||||
while(!stop.stop_requested())
|
||||
{
|
||||
const auto reply=host.call({{"action","terminalPoll"}});
|
||||
checkFileReply(reply);
|
||||
const auto &bytes=reply.at("data").get_binary();
|
||||
if(!bytes.empty()) output({reinterpret_cast<const char *>(bytes.data()),bytes.size()});
|
||||
if(reply.at("done").get<bool>()) return reply.at("exitCode").get<DWORD>();
|
||||
if(bytes.empty()) std::this_thread::sleep_for(std::chrono::milliseconds(60));
|
||||
}
|
||||
checkFileReply(host.call({{"action","terminalCancel"}}));
|
||||
throw std::system_error(ERROR_CANCELLED,std::system_category());
|
||||
}
|
||||
|
||||
struct FilesListener::Impl
|
||||
{
|
||||
struct Client
|
||||
@@ -820,29 +1027,47 @@ struct FilesListener::Impl
|
||||
};
|
||||
std::string local;
|
||||
PairKey key;
|
||||
TerminalPermission terminalPermission;
|
||||
HostAction hibernate,update;
|
||||
WinSocket listener;
|
||||
std::vector<std::unique_ptr<Client>> clients;
|
||||
uint16_t boundPort{};
|
||||
Impl(std::string id,PairKey lookup,uint16_t port):local(std::move(id)),key(std::move(lookup))
|
||||
uint16_t requestedPort{},boundPort{};
|
||||
ULONGLONG nextBind{};
|
||||
DWORD lastBindError{};
|
||||
Impl(std::string id,PairKey lookup,uint16_t port,TerminalPermission permission,HostAction hibernateAction,
|
||||
HostAction updateAction):
|
||||
local(std::move(id)),key(std::move(lookup)),terminalPermission(std::move(permission)),
|
||||
hibernate(std::move(hibernateAction)),update(std::move(updateAction)),requestedPort(port)
|
||||
{
|
||||
listener.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
|
||||
if(listener.value==INVALID_SOCKET) return;
|
||||
bindListener();
|
||||
}
|
||||
void bindListener()
|
||||
{
|
||||
nextBind=GetTickCount64()+1000;
|
||||
WinSocket candidate{socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)};
|
||||
BOOL exclusive=TRUE;
|
||||
u_long mode=1;
|
||||
sockaddr_in address{};
|
||||
address.sin_family=AF_INET;
|
||||
address.sin_port=htons(port);
|
||||
if(setsockopt(listener.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,reinterpret_cast<const char*>(&exclusive),sizeof(exclusive)) ||
|
||||
ioctlsocket(listener.value,FIONBIO,&mode) ||
|
||||
bind(listener.value,reinterpret_cast<sockaddr*>(&address),sizeof(address)) ||
|
||||
listen(listener.value,8))
|
||||
address.sin_port=htons(requestedPort);
|
||||
int length=sizeof(address);
|
||||
if(candidate.value==INVALID_SOCKET ||
|
||||
setsockopt(candidate.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE,reinterpret_cast<const char*>(&exclusive),sizeof(exclusive)) ||
|
||||
ioctlsocket(candidate.value,FIONBIO,&mode) ||
|
||||
bind(candidate.value,reinterpret_cast<sockaddr*>(&address),sizeof(address)) ||
|
||||
listen(candidate.value,8) ||
|
||||
getsockname(candidate.value,reinterpret_cast<sockaddr*>(&address),&length))
|
||||
{
|
||||
closesocket(std::exchange(listener.value,INVALID_SOCKET));
|
||||
const auto error=static_cast<DWORD>(WSAGetLastError());
|
||||
if(requestedPort==FilesPort && lastBindError!=error)
|
||||
log(L"LAN Files TCP 45885 unavailable; retrying. Windows error "+std::to_wstring(error));
|
||||
lastBindError=error;
|
||||
return;
|
||||
}
|
||||
int length=sizeof(address);
|
||||
if(!getsockname(listener.value,reinterpret_cast<sockaddr*>(&address),&length))
|
||||
boundPort=ntohs(address.sin_port);
|
||||
listener.value=std::exchange(candidate.value,INVALID_SOCKET);
|
||||
boundPort=ntohs(address.sin_port);
|
||||
if(requestedPort==FilesPort) log(L"LAN Files listener ready on TCP 45885.");
|
||||
lastBindError=0;
|
||||
}
|
||||
void serve(SOCKET socket)
|
||||
{
|
||||
@@ -858,7 +1083,7 @@ struct FilesListener::Impl
|
||||
wire.authenticate(secret,peer,local,challenge,nonce,false);
|
||||
if(wire.read().at("action")!="authenticate") return;
|
||||
wire.write(ok());
|
||||
FileOperations operations(true);
|
||||
FileOperations operations(true,terminalPermission,hibernate,update);
|
||||
for(;;)
|
||||
{
|
||||
const auto request=wire.read(true);
|
||||
@@ -877,6 +1102,7 @@ struct FilesListener::Impl
|
||||
void poll()
|
||||
{
|
||||
std::erase_if(clients,[](const auto &client){return client->done.load();});
|
||||
if(listener.value==INVALID_SOCKET && GetTickCount64()>=nextBind) bindListener();
|
||||
if(listener.value==INVALID_SOCKET || clients.size()>=16) return;
|
||||
sockaddr_in address{};
|
||||
int size=sizeof(address);
|
||||
@@ -899,8 +1125,10 @@ struct FilesListener::Impl
|
||||
}
|
||||
};
|
||||
|
||||
FilesListener::FilesListener(std::string local,PairKey key,uint16_t port):
|
||||
impl(std::make_unique<Impl>(std::move(local),std::move(key),port)){}
|
||||
FilesListener::FilesListener(std::string local,PairKey key,uint16_t port,TerminalPermission terminalPermission,
|
||||
HostAction hibernate,HostAction update):
|
||||
impl(std::make_unique<Impl>(std::move(local),std::move(key),port,std::move(terminalPermission),
|
||||
std::move(hibernate),std::move(update))){}
|
||||
FilesListener::~FilesListener()=default;
|
||||
uint16_t FilesListener::port()const{return impl->boundPort;}
|
||||
void FilesListener::poll(){impl->poll();}
|
||||
|
||||
+14
-1
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
#include "lan_pairing.h"
|
||||
#include <functional>
|
||||
#include <stop_token>
|
||||
|
||||
namespace ks::lan
|
||||
{
|
||||
@@ -31,6 +32,8 @@ public:
|
||||
void streamFile(FilesConnection &source,FilesConnection &target,const std::string &sourceId,
|
||||
const std::filesystem::path &from,const std::filesystem::path &to,uint64_t size,uint64_t modified,
|
||||
bool replace,bool append,const FileProgress &progress,const FileRevision *expectedDestination=nullptr);
|
||||
DWORD runRemoteCommand(FilesConnection &host,const std::filesystem::path &directory,std::wstring_view command,
|
||||
const std::function<void(std::string_view)> &output,std::stop_token stop={});
|
||||
|
||||
class FilesListener
|
||||
{
|
||||
@@ -38,7 +41,10 @@ class FilesListener
|
||||
std::unique_ptr<Impl> impl;
|
||||
public:
|
||||
using PairKey = std::function<std::string(const std::string &)>;
|
||||
FilesListener(std::string local, PairKey key,uint16_t port=FilesPort);
|
||||
using TerminalPermission = std::function<bool()>;
|
||||
using HostAction = std::function<DWORD()>;
|
||||
FilesListener(std::string local, PairKey key,uint16_t port=FilesPort,TerminalPermission terminalPermission={},
|
||||
HostAction hibernate={},HostAction update={});
|
||||
uint16_t port() const;
|
||||
~FilesListener();
|
||||
void poll();
|
||||
@@ -48,4 +54,11 @@ Json fileRequest(std::string_view action, const std::filesystem::path &path);
|
||||
std::filesystem::path filePath(const Json &path);
|
||||
void checkFileReply(const Json &reply);
|
||||
bool recycleFile(HWND owner, const std::filesystem::path &path);
|
||||
inline constexpr wchar_t remoteTerminalPreference[]=L"AllowRemoteTerminal";
|
||||
bool remoteTerminalAllowed();
|
||||
inline constexpr wchar_t remoteHibernatePreference[]=L"AllowRemoteHibernate";
|
||||
bool remoteHibernateAllowed();
|
||||
DWORD hibernateFromPairedPC();
|
||||
inline constexpr wchar_t remoteUpdatePreference[]=L"AllowRemoteUpdate";
|
||||
bool remoteUpdateAllowed();
|
||||
}
|
||||
+6
-1
@@ -55,7 +55,12 @@ UpdateResult runUpdate(bool install, const std::wstring &expectedVersion, bool s
|
||||
L" -CurrentVersion " + quoteArgument(AppVersion) + L" -WorkDirectory " + quoteArgument(work.wstring()) +
|
||||
L" -InstallDirectory " + quoteArgument(std::filesystem::path(executable()).parent_path().wstring()) +
|
||||
L" -ParentProcessId " + std::to_wstring(GetCurrentProcessId()) + L" -ReadyEvent " + quoteArgument(readyName);
|
||||
if (install) command += L" -ExpectedVersion " + quoteArgument(expectedVersion);
|
||||
if (install && expectedVersion.empty())
|
||||
{
|
||||
command += L" -Unattended -Journal " + quoteArgument((dataDirectory() / L"kswitcher.log").wstring());
|
||||
}
|
||||
else if (install)
|
||||
command += L" -ExpectedVersion " + quoteArgument(expectedVersion);
|
||||
if (showProgress) command += L" -ShowProgress";
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
PROCESS_INFORMATION process{};
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
#include "platform.h"
|
||||
namespace ks
|
||||
{
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.85";
|
||||
inline constexpr wchar_t AppVersion[] = L"0.6.93";
|
||||
inline constexpr UINT UpdateMessage = WM_APP + 7;
|
||||
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
|
||||
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
|
||||
|
||||
@@ -20,6 +20,9 @@ public static class FilesActivationUi {
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string type, string title);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr window, IntPtr process);
|
||||
[DllImport("user32.dll")] static extern bool GetGUIThreadInfo(uint thread, ref GuiInfo info);
|
||||
@@ -36,6 +39,14 @@ public static class FilesActivationUi {
|
||||
return info.Focus;
|
||||
}
|
||||
|
||||
public static bool Activate(IntPtr window) {
|
||||
if (GetForegroundWindow() == window) return true;
|
||||
keybd_event(0x12, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(0x12, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
return GetForegroundWindow() == window;
|
||||
}
|
||||
|
||||
public static void ClickRow(IntPtr list, int row, bool doubleClick) {
|
||||
Rect rect;
|
||||
if (SendRect(list, 0x198, new IntPtr(row), out rect).ToInt32() == -1)
|
||||
@@ -179,6 +190,21 @@ try {
|
||||
[FilesActivationUi]::Send($left, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq (Find-Row $left '..')
|
||||
}
|
||||
if ((Read-Text $inputBox) -cne 'draft command') { throw 'Pane navigation changed the command line.' }
|
||||
$shell = New-Object -ComObject WScript.Shell
|
||||
$fileName = [IO.Path]::GetFileName($document)
|
||||
foreach ($name in $fileName, 'Test folder') {
|
||||
$label = if ($name -eq $fileName) { $name } else { "[$name]" }
|
||||
Select-Row $right $label
|
||||
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, 'draft command')
|
||||
[void][FilesActivationUi]::Send($inputBox, 0xB1, [IntPtr]6, [IntPtr]13)
|
||||
Wait-Until 'Files activation for Ctrl+Enter' {
|
||||
[FilesActivationUi]::Activate($window) -and
|
||||
[FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
$shell.SendKeys('^{ENTER}')
|
||||
$expected = 'draft "{0}"' -f $name
|
||||
Wait-Until "Ctrl+Enter inserting $name" { (Read-Text $inputBox) -ceq $expected }
|
||||
}
|
||||
[void][FilesActivationUi]::Write($inputBox, 0x0C, [IntPtr]::Zero, '')
|
||||
Write-Output 'Tab and Down navigated the panes while preserving command-line focus and text.'
|
||||
|
||||
@@ -244,6 +270,79 @@ try {
|
||||
}
|
||||
if ([FilesActivationUi]::Focus($window) -ne $inputBox) { throw 'Deletion moved focus.' }
|
||||
Write-Output 'Both panels refreshed external creation, modification and deletion while preserving focus.'
|
||||
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
$savedClipboard=[Windows.Forms.Clipboard]::GetDataObject()
|
||||
$programName=[IO.Path]::GetFileName($program)
|
||||
$expectedNames="Test folder`r`n$programName"
|
||||
try {
|
||||
Select-Row $left '[Test folder]'
|
||||
[void][FilesActivationUi]::Send($left,0x100,[IntPtr]45,[IntPtr]::Zero)
|
||||
Select-Row $left $programName
|
||||
[void][FilesActivationUi]::Send($left,0x100,[IntPtr]45,[IntPtr]::Zero)
|
||||
Wait-Until 'Files activation for Ctrl+Insert' {
|
||||
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
$shell.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying marked names in panel order' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $expectedNames
|
||||
}
|
||||
Select-Row $right $fileName
|
||||
$shell.SendKeys('^{INSERT}')
|
||||
Wait-Until 'Ctrl+Insert copying the current item in the other pane' {
|
||||
[Windows.Forms.Clipboard]::GetText() -ceq $fileName
|
||||
}
|
||||
Write-Output 'Ctrl+Insert copied marked names in order and used the cursor in the other pane.'
|
||||
} finally {
|
||||
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
|
||||
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
|
||||
else { [Windows.Forms.Clipboard]::Clear() }
|
||||
}
|
||||
}
|
||||
|
||||
$sizeA=Join-Path $rightDir 'Size A'
|
||||
$sizeB=Join-Path $rightDir 'Size B'
|
||||
$sizeC=Join-Path $rightDir 'Size C'
|
||||
New-Item -ItemType Directory -Path "$sizeA\nested", $sizeB, $sizeC | Out-Null
|
||||
[IO.File]::WriteAllBytes("$sizeA\file.bin",[byte[]]::new(4))
|
||||
[IO.File]::WriteAllBytes("$sizeA\nested\file.bin",[byte[]]::new(7))
|
||||
[IO.File]::WriteAllBytes("$sizeB\file.bin",[byte[]]::new(23))
|
||||
[IO.File]::WriteAllBytes("$sizeC\file.bin",[byte[]]::new(31))
|
||||
Select-Row $right '[Size A]'
|
||||
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
|
||||
Wait-Until 'F3 recursive size for the current folder' { (Read-Text $status) -ceq 'Size A 11 B' }
|
||||
foreach($name in 'Size A','Size B'){
|
||||
Select-Row $right "[$name]"
|
||||
[void][FilesActivationUi]::Send($right,0x100,[IntPtr]45,[IntPtr]::Zero)
|
||||
}
|
||||
Select-Row $right '[Size C]'
|
||||
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
|
||||
Wait-Until 'completion of the marked size batch' { (Read-Text $status) -ceq 'Size C Folder' }
|
||||
Select-Row $right '[Size B]'
|
||||
Wait-Until 'F3 size for a marked folder' { (Read-Text $status) -ceq 'Size B 23 B' }
|
||||
Select-Row $right '[Size C]'
|
||||
if ((Read-Text $status) -cne 'Size C Folder') { throw 'F3 measured the unmarked cursor folder.' }
|
||||
Select-Row $right $fileName
|
||||
[void][FilesActivationUi]::PostMessage($right,0x100,[IntPtr]0x72,[IntPtr]::Zero)
|
||||
$viewerTitle='Viewer '+[char]0x2014+" $document"
|
||||
Wait-Until 'F3 opening a file when folders are marked' {
|
||||
[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle) -ne [IntPtr]::Zero
|
||||
}
|
||||
$viewer=[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle)
|
||||
[void][FilesActivationUi]::PostMessage($viewer,0x10,[IntPtr]::Zero,[IntPtr]::Zero)
|
||||
Write-Output 'F3 measured the current folder recursively and measured marked folders without measuring the unmarked cursor folder.'
|
||||
|
||||
Select-Row $right '[Size B]'
|
||||
Wait-Until 'Files activation for Ctrl+R' {
|
||||
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
|
||||
}
|
||||
$shell.SendKeys('^r')
|
||||
Wait-Until 'Ctrl+R clearing the measured size and retaining the current folder' {
|
||||
(Read-Text $status) -ceq 'Size B Folder' -and
|
||||
[FilesActivationUi]::Send($right,0x188,[IntPtr]::Zero,[IntPtr]::Zero).ToInt32() -eq
|
||||
(Find-Row $right '[Size B]')
|
||||
}
|
||||
Write-Output 'Ctrl+R refreshed the active pane and kept its cursor.'
|
||||
} finally {
|
||||
if ($process -and !$process.HasExited) {
|
||||
[void]$process.CloseMainWindow()
|
||||
|
||||
@@ -113,6 +113,28 @@ function Read-Bounds($Window) {
|
||||
if (![SearchArrowTest]::GetWindowRect($Window,[ref]$bounds)) { throw 'Missing window bounds' }
|
||||
$bounds
|
||||
}
|
||||
function Assert-CompactNotice($Dialog, [int]$DefaultButton) {
|
||||
$text=[SearchArrowTest]::GetDlgItem($Dialog,100)
|
||||
if (([SearchArrowTest]::GetWindowStyle($text,-16).ToInt64() -band 0x00200000) -ne 0) {
|
||||
throw 'A short Files notice has a vertical scrollbar.'
|
||||
}
|
||||
$lines=[SearchArrowTest]::Send($text,0xBA,0,0).ToInt32()
|
||||
$body=Read-Bounds $text
|
||||
$button=[SearchArrowTest]::GetDlgItem($Dialog,$DefaultButton)
|
||||
$footer=Read-Bounds $button
|
||||
$lineHeight=($body.Bottom-$body.Top)/$lines
|
||||
$frame=Read-Bounds $Dialog
|
||||
if (($body.Top-$frame.Top) -gt 2*$lineHeight -or
|
||||
($frame.Bottom-$footer.Bottom) -gt $lineHeight) {
|
||||
throw 'A short Files notice has excess space between its content and frame.'
|
||||
}
|
||||
if (($footer.Top-$body.Bottom) -gt $lineHeight -or $footer.Top -le $body.Bottom) {
|
||||
throw 'A short Files notice has incorrect spacing between the text and the buttons.'
|
||||
}
|
||||
if ([SearchArrowTest]::FocusedControl($Dialog) -ne $button) {
|
||||
throw 'A Files notice has the wrong starting focus.'
|
||||
}
|
||||
}
|
||||
function Assert-FarFieldHeight($Dialog, [int[]]$Ids) {
|
||||
$heights=@(foreach ($id in $Ids) {
|
||||
$bounds=Read-Bounds ([SearchArrowTest]::GetDlgItem($Dialog,$id))
|
||||
@@ -197,6 +219,35 @@ $process = Start-Process -FilePath $copy -PassThru -WindowStyle Hidden
|
||||
try {
|
||||
$previousDpi=[SearchArrowTest]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
$main = Wait-Until { Find-Window 'KSwitcher.Files' $process.Id }
|
||||
Post $main 0x111 132
|
||||
$commandMenu=Wait-Until {
|
||||
$list=[SearchArrowTest]::GetDlgItem($main,121)
|
||||
if ([SearchArrowTest]::IsWindowVisible($list)) { $list }
|
||||
}
|
||||
$count=[SearchArrowTest]::Send($commandMenu,0x18B,0,0).ToInt32()
|
||||
$rows=@(for ($i=0; $i -lt $count; $i++) {
|
||||
$label=[Text.StringBuilder]::new(128)
|
||||
[void][SearchArrowTest]::GetText($commandMenu,0x189,$i,$label)
|
||||
$label.ToString()
|
||||
})
|
||||
if (($rows -join '|') -cne "Refresh panel`tCtrl+R|Folder shortcuts||View`tF3|Edit`tF4|View externally`tAlt+F3|Edit externally`tAlt+F4") {
|
||||
throw 'Commands did not group local actions or showed a LAN-only section.'
|
||||
}
|
||||
Post $commandMenu 0x100 40
|
||||
Post $commandMenu 0x100 40
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq 3 })
|
||||
Post $commandMenu 0x100 38
|
||||
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq 1 })
|
||||
$rowHeight=[SearchArrowTest]::Send($commandMenu,0x1A1,0,0).ToInt32()
|
||||
$separatorPoint=((2*$rowHeight+1) -shl 16) -bor 4
|
||||
[void][SearchArrowTest]::Send($commandMenu,0x201,1,$separatorPoint)
|
||||
[void][SearchArrowTest]::Send($commandMenu,0x202,0,$separatorPoint)
|
||||
if ([SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -ne 1) {
|
||||
throw 'A click selected the Commands separator.'
|
||||
}
|
||||
Post $commandMenu 0x100 27
|
||||
[void](Wait-Until { ![SearchArrowTest]::IsWindowVisible($commandMenu) })
|
||||
Write-Output 'Verified Commands grouping, arrow navigation, and inert separators.'
|
||||
$panel = Wait-Until { $handle = [SearchArrowTest]::GetDlgItem($main,102); if ($handle -ne [IntPtr]::Zero) { $handle } }
|
||||
$pathControl = [SearchArrowTest]::GetDlgItem($main,142)
|
||||
$pathText = [Text.StringBuilder]::new(1024)
|
||||
@@ -244,6 +295,7 @@ try {
|
||||
[void][SearchArrowTest]::SendText($nameField,0xC,0,$newFolder)
|
||||
Post $makeDialog 0x111 1
|
||||
$folderError=Wait-Until { Find-Window '#32770' $process.Id 100 }
|
||||
Assert-CompactNotice $folderError 1
|
||||
Post $folderError 0x111 1
|
||||
[void](Wait-Until {
|
||||
![SearchArrowTest]::IsWindow($folderError) -and
|
||||
@@ -459,6 +511,11 @@ try {
|
||||
|
||||
Post $panel 0x100 0x73
|
||||
$editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id }
|
||||
$firstControl=[SearchArrowTest]::FindWindowEx($editor,0,'Scintilla',[System.Management.Automation.Language.NullString]::Value)
|
||||
if ($firstControl -eq [IntPtr]::Zero -or
|
||||
[SearchArrowTest]::Send($firstControl,2482,32,0).ToInt64() -eq 0xFFFFFF) {
|
||||
throw 'The editor is visible with the default white Scintilla background.'
|
||||
}
|
||||
$originalFocus=Wait-Until {
|
||||
$focus=[SearchArrowTest]::FocusedControl($editor)
|
||||
if ($focus -ne [IntPtr]::Zero) { $focus }
|
||||
@@ -472,6 +529,7 @@ try {
|
||||
$notice=[Text.StringBuilder]::new(256)
|
||||
[void][SearchArrowTest]::GetText([SearchArrowTest]::GetDlgItem($existing,100),0xD,$notice.Capacity,$notice)
|
||||
if (!$notice.ToString().Contains('already open')) { throw 'Reopening did not offer to switch to the editor.' }
|
||||
Assert-CompactNotice $existing 7
|
||||
Post $existing 0x111 6
|
||||
[void](Wait-Until { ![SearchArrowTest]::IsWindow($existing) })
|
||||
if (Find-Window 'KSwitcher.Files.Text' $process.Id 0 $editor) { throw 'Duplicate editor opened.' }
|
||||
|
||||
+100
-1
@@ -1,7 +1,9 @@
|
||||
#include <winsock2.h>
|
||||
#include <sddl.h>
|
||||
#include "lan_files.h"
|
||||
#include "files_lan_ipc.h"
|
||||
#include <bit>
|
||||
#include <atomic>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
@@ -17,6 +19,23 @@ void require(bool condition,const char *message)
|
||||
if(!condition) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
void verifyFilesPeerImage()
|
||||
{
|
||||
const fs::path install = LR"(C:\Tools\KSwitcher)";
|
||||
const auto transaction = install / L".kswitcher-update-0123456789abcdef0123456789abcdef";
|
||||
constexpr auto files = L"KSwitcher.Files.exe";
|
||||
require(isFilesPeerImage(install / files, install), "installed Files can request LAN peers");
|
||||
require(isFilesPeerImage(transaction / L"backup" / files, install),
|
||||
"Files open during an update can still request LAN peers");
|
||||
require(!isFilesPeerImage(transaction / L"stage" / files, install), "staged Files image is rejected");
|
||||
require(!isFilesPeerImage(transaction / L"backup" / L"KSwitcher.Config.exe", install),
|
||||
"another executable in the backup is rejected");
|
||||
require(!isFilesPeerImage(install / L".kswitcher-update-invalid" / L"backup" / files, install),
|
||||
"malformed transaction directory is rejected");
|
||||
require(!isFilesPeerImage(install.parent_path() / transaction.filename() / L"backup" / files, install),
|
||||
"backup outside the active installation is rejected");
|
||||
}
|
||||
|
||||
void save(const fs::path &path,const std::string &text)
|
||||
{
|
||||
std::ofstream file(path,std::ios::binary|std::ios::trunc);
|
||||
@@ -110,10 +129,37 @@ int main()
|
||||
int result=0;
|
||||
try
|
||||
{
|
||||
verifyFilesPeerImage();
|
||||
fs::create_directory(root);
|
||||
const auto client=randomHex(16),first=randomHex(16),second=randomHex(16),key=randomHex(32);
|
||||
auto lookup=[&](const std::string &id){return id==client?key:std::string{};};
|
||||
FilesListener a(first,lookup,0),b(second,lookup,0);
|
||||
{
|
||||
auto previous=std::make_unique<FilesListener>(first,lookup,0);
|
||||
const auto port=previous->port();
|
||||
require(port!=0,"old listener bound before restart");
|
||||
FilesListener restarting(first,lookup,port);
|
||||
require(restarting.port()==0,"new listener must not take over an occupied port");
|
||||
previous.reset();
|
||||
const auto deadline=GetTickCount64()+4000;
|
||||
while(!restarting.port() && GetTickCount64()<deadline)
|
||||
{
|
||||
restarting.poll();
|
||||
Sleep(20);
|
||||
}
|
||||
require(restarting.port()==port,"listener automatically recovers after its port becomes available");
|
||||
std::jthread pollingRestarted([&](std::stop_token stop)
|
||||
{
|
||||
while(!stop.stop_requested()){restarting.poll();Sleep(5);}
|
||||
});
|
||||
FilesConnection recovered(FilesPeer{first,"127.0.0.1",L"Recovered",port},client,key);
|
||||
checkFileReply(recovered.call({{"action","drives"}}));
|
||||
}
|
||||
std::atomic<bool> allowTerminal{};
|
||||
std::atomic<unsigned> hibernateRequests{};
|
||||
std::atomic<unsigned> updateRequests{};
|
||||
FilesListener a(first,lookup,0,[&]{return allowTerminal.load();}),
|
||||
b(second,lookup,0,{},[&]{++hibernateRequests;return ERROR_SUCCESS;},
|
||||
[&]{++updateRequests;return ERROR_SUCCESS;});
|
||||
require(a.port() && b.port() && a.port()!=b.port(),"test listeners unavailable");
|
||||
std::jthread polling([&](std::stop_token stop)
|
||||
{
|
||||
@@ -131,6 +177,59 @@ int main()
|
||||
}
|
||||
catch(const std::system_error &){}
|
||||
FilesConnection host(one,client,key);
|
||||
{
|
||||
const Json hibernate={{"action","hibernate"}};
|
||||
FilesConnection target(two,client,key);
|
||||
FilesConnection local;
|
||||
require(local.call(hibernate).at("error")==ERROR_ACCESS_DENIED,
|
||||
"local file operations cannot dispatch the LAN power action");
|
||||
require(host.call(hibernate).at("error")==ERROR_ACCESS_DENIED && hibernateRequests==0,
|
||||
"hibernate requires a separately enabled handler on the target");
|
||||
require(target.call({{"action","hibernate"},{"command","anything"}}).at("error")
|
||||
==ERROR_INVALID_PARAMETER && hibernateRequests==0,"hibernate accepts no extra parameters");
|
||||
require(target.call(hibernate).at("error")==ERROR_SUCCESS && hibernateRequests==1,
|
||||
"hibernate dispatches only to the addressed paired PC");
|
||||
const Json update={{"action","update"}};
|
||||
require(host.call(update).at("error")==ERROR_ACCESS_DENIED && updateRequests==0,
|
||||
"update requires a separate handler on the target");
|
||||
require(target.call({{"action","update"},{"url","https://example.invalid"}}).at("error")
|
||||
==ERROR_INVALID_PARAMETER && updateRequests==0,"update cannot supply an external package");
|
||||
require(target.call(update).at("error")==ERROR_SUCCESS && updateRequests==1 && hibernateRequests==1,
|
||||
"update dispatches to the addressed paired PC without invoking hibernate");
|
||||
}
|
||||
auto deniedCommand=fileRequest("terminalRun",root);
|
||||
deniedCommand["command"]="Write-Output denied";
|
||||
require(host.call(deniedCommand).at("error")==ERROR_ACCESS_DENIED,"remote command allowed without consent");
|
||||
allowTerminal=true;
|
||||
std::string console;
|
||||
const auto exit=runRemoteCommand(host,root,
|
||||
L"[Console]::Out.WriteLine((Get-Location).ProviderPath); "
|
||||
L"[Console]::Error.WriteLine('Тест stderr'); Write-Error 'PowerShell error'; exit 7",
|
||||
[&](std::string_view part){console+=part;});
|
||||
require(exit==7 && console.find(utf8(root.native()))!=console.npos &&
|
||||
console.find(utf8(L"Тест stderr"))!=console.npos,"remote command output or exit code differs");
|
||||
require(console.find("PowerShell error")!=console.npos && console.find("CLIXML")==console.npos,
|
||||
"remote PowerShell errors were not returned as text");
|
||||
console.clear();
|
||||
const auto directoryExit=runRemoteCommand(host,root,
|
||||
L"Write-Progress -Activity 'Hidden progress probe' -Status 'Working'; dir",
|
||||
[&](std::string_view part){console+=part;});
|
||||
require(directoryExit==0 && console.find("CLIXML")==console.npos &&
|
||||
console.find("Hidden progress probe")==console.npos,"remote directory command included progress metadata");
|
||||
std::stop_source cancel;
|
||||
try
|
||||
{
|
||||
runRemoteCommand(host,root,L"[Console]::Out.WriteLine('Ready'); Start-Sleep -Seconds 30",
|
||||
[&](std::string_view){cancel.request_stop();},cancel.get_token());
|
||||
require(false,"remote command cancellation did not stop execution");
|
||||
}
|
||||
catch(const std::system_error &error)
|
||||
{
|
||||
require(error.code().value()==ERROR_CANCELLED,"remote terminal returned the wrong cancellation error");
|
||||
}
|
||||
allowTerminal=false;
|
||||
require(host.call(deniedCommand).at("error")==ERROR_ACCESS_DENIED,"remote command allowed after revocation");
|
||||
std::cout<<"Verified remote PowerShell consent, working directory, streamed output, exit code and cancellation.\n";
|
||||
const auto edited=root/L"edited.txt", serverFile=root/L"server.txt", snapshot=root/L"snapshot.txt";
|
||||
save(serverFile,"original remote content");
|
||||
const auto initial=host.call(fileRequest("stat",serverFile));
|
||||
|
||||
@@ -7,6 +7,38 @@ function Reject([scriptblock]$Action,[string]$Name) { $rejected=$false; try { &
|
||||
$root=Join-Path ([IO.Path]::GetTempPath()) ('KSwitcher-update-tests-'+[guid]::NewGuid().ToString('N'))
|
||||
[IO.Directory]::CreateDirectory($root) | Out-Null
|
||||
try {
|
||||
$companionRoot=Join-Path $root 'companion-install'
|
||||
$otherRoot=Join-Path $root 'other-install'
|
||||
[IO.Directory]::CreateDirectory($companionRoot) | Out-Null
|
||||
[IO.Directory]::CreateDirectory($otherRoot) | Out-Null
|
||||
$companions=@()
|
||||
$Journal=Join-Path $root 'update.log'
|
||||
try {
|
||||
foreach ($fixture in @(
|
||||
@{Root=$companionRoot; Name='KSwitcher.Files.exe'},
|
||||
@{Root=$companionRoot; Name='KSwitcher.Screenshot.exe'},
|
||||
@{Root=$companionRoot; Name='KSwitcher.Config.exe'},
|
||||
@{Root=$otherRoot; Name='KSwitcher.Files.exe'})) {
|
||||
$path=Join-Path $fixture.Root $fixture.Name
|
||||
Copy-Item -LiteralPath (Join-Path ([Environment]::SystemDirectory) 'ping.exe') -Destination $path
|
||||
$companions+=Start-Process -FilePath $path -ArgumentList '-t','127.0.0.1' -WindowStyle Hidden -PassThru
|
||||
}
|
||||
$oldFiles=Join-Path $companionRoot 'KSwitcher.Files.exe'
|
||||
$backup=Join-Path $companionRoot '.kswitcher-update-0123456789abcdef0123456789abcdef/backup'
|
||||
[IO.Directory]::CreateDirectory($backup) | Out-Null
|
||||
Move-Item -LiteralPath $oldFiles -Destination $backup
|
||||
Stop-UpdateCompanions $companionRoot
|
||||
Assert (@($companions[0..2] | Where-Object HasExited).Count -eq 3) 'unattended update closes all companions in its installation'
|
||||
Assert (!$companions[3].HasExited) 'unattended update leaves a companion from another installation running'
|
||||
Assert (@(Get-Content -LiteralPath $Journal | Where-Object { $_ -match 'LAN update: Closing KSwitcher\.' }).Count -eq 3) 'unattended update journals every companion closure'
|
||||
Assert (@(Get-Content -LiteralPath $Journal | Where-Object { $_ -match 'LAN update: Closed KSwitcher\.' }).Count -eq 3) 'unattended update confirms each companion exited'
|
||||
} finally {
|
||||
foreach ($companion in $companions) {
|
||||
if (!$companion.HasExited) { $companion.Kill(); $companion.WaitForExit() }
|
||||
$companion.Dispose()
|
||||
}
|
||||
$Journal=$null
|
||||
}
|
||||
$binaryInfo = [Diagnostics.FileVersionInfo]::GetVersionInfo((Resolve-Path -LiteralPath $Executable).Path)
|
||||
$binaryVersion = Get-StableVersion $binaryInfo.FileVersion
|
||||
Assert ($null -ne $binaryVersion) 'executable has a stable version'
|
||||
|
||||
Reference in new issue
Block a user