Compare commits

...
24 changed files with 470 additions and 102 deletions

No files matched your search

+2 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.87 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.89 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)
+15
View File
@@ -39,10 +39,25 @@ Far Manager є зразком для оформлення файлового м
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+C копіює весь введений у командний рядок текст, навіть коли виділено
лише його частину.
Binary file not shown.
+13
View File
@@ -1,5 +1,18 @@
# Latest Windows release
## 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.
+1 -1
View File
@@ -1 +1 @@
8e69019173d92de7790917573c9e95bb96104994d518170cad320d294fca2153 KSwitcher-win-x64.zip
06d74702f466c8f793fafbbf54942fd1688e36f975b4d709652bbdb023e2fc2f KSwitcher-win-x64.zip
+61 -61
View File
@@ -1,136 +1,136 @@
{
"schema": 1,
"version": "0.6.89",
"files": [
{
"size": 2462208,
"sha256": "fad74ffb05e9c3ce6ada562c610837539809682cef33d0be1e878dc45e4dea9d",
"path": "KSwitcher.exe"
"path": "KSwitcher.exe",
"sha256": "411340c538f2b76424b7e4d228c217ab1b56e059ee640c109888f59115d9d5ec",
"size": 2465792
},
{
"size": 2439168,
"sha256": "8c88bd7f4018d0f400e56f2ae21c63b259f2ab482adfd82bf2e067a48e7eb47a",
"path": "KSwitcher.Config.exe"
"path": "KSwitcher.Config.exe",
"sha256": "f48c68669147e32090823465639d8301798f2e4934e160becd1b5fd42d6708bb",
"size": 2445824
},
{
"size": 3050496,
"sha256": "7d2a3d04436989411e1220569fbfef95a9916696ec97b62963c3c04f128a11ed",
"path": "KSwitcher.Screenshot.exe"
"path": "KSwitcher.Screenshot.exe",
"sha256": "311ebf1a3d135fe6ce8bfd0978a9552fbb64c7d7f9a791f4aa4c5bd2c439f06f",
"size": 3052544
},
{
"size": 3660288,
"sha256": "7a5596ee03cce3000f83f13d8de1113be467590abcf03ef4a2bd8d13f1d3b5fe",
"path": "KSwitcher.Files.exe"
"path": "KSwitcher.Files.exe",
"sha256": "73acd9be067451c3db83706be0164959f2ac130259c41c48841d16d1aa2792d5",
"size": 3671552
},
{
"size": 194912,
"path": "WebView2Loader.dll",
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"path": "WebView2Loader.dll"
"size": 194912
},
{
"size": 1103,
"path": "terminal/addon-fit-LICENSE.txt",
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"path": "terminal/addon-fit-LICENSE.txt"
"size": 1103
},
{
"size": 1521,
"path": "terminal/addon-fit.js",
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"path": "terminal/addon-fit.js"
"size": 1521
},
{
"size": 527,
"path": "terminal/index.html",
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"path": "terminal/index.html"
"size": 527
},
{
"size": 4167,
"sha256": "d60e6ff8948b6616695297695b05ef6e74b497a8e32e6031fc2e4fe2cca39ca7",
"path": "terminal/terminal.js"
"path": "terminal/terminal.js",
"sha256": "fb302b2902fea6a815a8266811f350d1e4c108ca88fafd49e6eddcbfff90a5e5",
"size": 4268
},
{
"size": 1261,
"path": "terminal/xterm-LICENSE.txt",
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"path": "terminal/xterm-LICENSE.txt"
"size": 1261
},
{
"size": 7112,
"path": "terminal/xterm.css",
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"path": "terminal/xterm.css"
"size": 7112
},
{
"size": 488663,
"path": "terminal/xterm.js",
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"path": "terminal/xterm.js"
"size": 488663
},
{
"size": 4401,
"path": "LICENSE",
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"path": "LICENSE"
"size": 4401
},
{
"size": 1075,
"path": "json-LICENSE.txt",
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86",
"path": "json-LICENSE.txt"
"size": 1075
},
{
"size": 883,
"path": "files-text-license.txt",
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"path": "files-text-license.txt"
"size": 883
},
{
"size": 94223,
"path": "README.md",
"sha256": "7b34f2af7341f57d7bac1b5b7e55a40595a6bc20f461f98c0c6320336d0deba7",
"path": "README.md"
"size": 94223
},
{
"size": 11418,
"path": "LAN-PREVIEW.md",
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada",
"path": "LAN-PREVIEW.md"
"size": 11418
},
{
"size": 682867,
"path": "dictionaries/en.txt",
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21",
"path": "dictionaries/en.txt"
"size": 682867
},
{
"size": 20138,
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5",
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
"size": 20138
},
{
"size": 2265,
"path": "dictionaries/README.md",
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"path": "dictionaries/README.md"
"size": 2265
},
{
"size": 1060364,
"path": "dictionaries/ru.txt",
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b",
"path": "dictionaries/ru.txt"
"size": 1060364
},
{
"size": 1280,
"path": "dictionaries/sources.json",
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"path": "dictionaries/sources.json"
"size": 1280
},
{
"size": 940799,
"path": "dictionaries/uk.txt",
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"path": "dictionaries/uk.txt"
"size": 940799
},
{
"size": 993,
"path": "tools/README.txt",
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"path": "tools/README.txt"
"size": 993
},
{
"size": 133120,
"sha256": "759c4ad30bbcf1f99d086dbd88dd2f5c68012d6a793479e8712a6934e17e23f4",
"path": "tools/StayHere.exe"
"path": "tools/StayHere.exe",
"sha256": "2b214b0ed2b6f754611f3355ccdcc6797c6bc5c2aac70bd51e060ba25eb4c3a5",
"size": 133120
},
{
"size": 2796,
"path": "tools/StayHere-README.md",
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"path": "tools/StayHere-README.md"
"size": 2796
}
],
"version": "0.6.87",
"schema": 1
]
}
+3 -3
View File
@@ -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,87,0
PRODUCTVERSION 0,6,87,0
FILEVERSION 0,6,89,0
PRODUCTVERSION 0,6,89,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.87"
VALUE "FileVersion", "0.6.89"
END
END
BLOCK "VarFileInfo"
+2
View File
@@ -115,6 +115,8 @@ BEGIN
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
+3
View File
@@ -58,6 +58,9 @@ 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 return true;
event.preventDefault();
return false;
+39 -5
View File
@@ -4,6 +4,7 @@
[string]$InstallDirectory, [string]$WorkDirectory,
[int]$ParentProcessId, [string]$ReadyEvent,
[switch]$ShowProgress,
[switch]$Unattended, [string]$Journal,
[switch]$Library
)
$ErrorActionPreference = 'Stop'
@@ -408,12 +409,30 @@ 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) {
$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)) {
if ($process.Path -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))." }
}
}
}
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 +445,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 +464,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 +484,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 +505,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 {
+13 -2
View File
@@ -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,16 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
}
switch (msg)
{
case LanUpdateRequestedMessage:
if (!lan::remoteUpdateAllowed()) return 0;
if (app->updateRunning)
log(L"LAN update request ignored because an update is already running.");
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));
+16 -5
View File
@@ -4,17 +4,25 @@
#include <cstring>
namespace ks
{
bool configurationPeer(HWND window, const wchar_t *filename)
namespace
{
std::filesystem::path processImage(HWND window)
{
DWORD pid{};
GetWindowThreadProcessId(window, &pid);
HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!process) return false;
if (!process) return {};
wchar_t path[32768]; DWORD count = std::size(path);
bool ok = QueryFullProcessImageNameW(process, 0, path, &count) != 0;
CloseHandle(process);
auto expected = std::filesystem::path(executable()).parent_path() / filename;
return ok && _wcsicmp(path, expected.c_str()) == 0;
return ok ? std::filesystem::path(path) : std::filesystem::path{};
}
}
bool configurationPeer(HWND window, const wchar_t *filename)
{
const auto expected = std::filesystem::path(executable()).parent_path() / filename;
return _wcsicmp(processImage(window).c_str(), expected.c_str()) == 0;
}
void launchConfiguration(App &app, bool snippets, bool logs)
{
@@ -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;
+24
View File
@@ -1,6 +1,30 @@
#pragma once
#include <windows.h>
#include <filesystem>
#include <string_view>
inline constexpr ULONG_PTR FilesLanPeers = 0x4b53010d;
inline constexpr ULONG_PTR FilesLanPeersReply = 0x4b53010e;
inline constexpr DWORD FilesLanPeersLimit = 64 * 1024;
namespace ks
{
inline bool isFilesPeerImage(const std::filesystem::path &image, const std::filesystem::path &install)
{
if (_wcsicmp(image.filename().c_str(), L"KSwitcher.Files.exe") != 0) return false;
const auto directory = image.parent_path();
if (_wcsicmp(directory.c_str(), install.c_str()) == 0) return true;
// Updating moves a still-running Files executable into the transaction backup.
// Windows then reports the moved path for its process image.
if (_wcsicmp(directory.filename().c_str(), L"backup") != 0) return false;
const auto transaction = directory.parent_path();
if (_wcsicmp(transaction.parent_path().c_str(), install.c_str()) != 0) return false;
constexpr std::wstring_view prefix = L".kswitcher-update-";
const auto name = transaction.filename().wstring();
if (name.size() != prefix.size() + 32 || _wcsnicmp(name.c_str(), prefix.data(), prefix.size()) != 0)
return false;
return std::wstring_view(name).substr(prefix.size()).find_first_not_of(L"0123456789abcdefABCDEF")
== std::wstring_view::npos;
}
}
+86 -6
View File
@@ -332,6 +332,7 @@ HWND drivePeerService{};
bool drivePeerReplyReceived{};
std::wstring drivePeerLookupError;
std::vector<FilesPeer> drivePeers;
std::future<std::wstring> pendingPeerAction;
struct DriveQuery
{
FilesPeer peer;
@@ -909,12 +910,14 @@ std::wstring powerShellPath(const fs::path &path)
return quoted+L"'";
}
void insertCurrentPanelPath()
void insertCurrentPanelPath(bool nameOnly = false)
{
const auto &panel=panels[active];
const auto row=currentPanelRow(panel);
if(row==LB_ERR) return;
const auto &path=panel.rows[row].native();
const auto &item=panel.rows[row];
if(nameOnly && row==0 && panel.directory.has_relative_path()) return;
const auto path=nameOnly?item.filename().native():item.native();
std::wstring quoted;
if(path.find(L' ')!=std::wstring::npos)
{
@@ -974,6 +977,7 @@ bool ensureTerminalView(HWND owner)
if(GetForegroundWindow()==owner) SetFocus(terminalInput);
}
else if(message==L"insert-path") insertCurrentPanelPath();
else if(message==L"insert-name") insertCurrentPanelPath(true);
else if(message==L"copy-command-line") SendMessageW(terminalInput,WM_COPY,0,0);
else if(message==L"toggle") showTerminal(owner,!terminalVisible);
else if(!terminalVisible && (message==L"grow" || message==L"shrink"))
@@ -1415,6 +1419,65 @@ void prepareTextDialog(HWND dialog);
void showTextMessage(HWND owner,const wchar_t *text);
void editTextOptions(HWND owner,bool edit);
void runActivePeerAction(HWND owner,bool update)
{
if(!panels[active].peer) return;
if(pendingPeerAction.valid())
{
setStatus(L"A remote PC request is already in progress.");
return;
}
const auto peer=*panels[active].peer;
const auto question=update
? L"Update KSwitcher on "+peer.name+L"? Open KSwitcher windows there will close if an update is available."
: L"Hibernate "+peer.name+L"?";
if(showFilesNotice(owner,question.c_str(),update?L"Update remote KSwitcher":L"Hibernate remote PC",true)!=IDYES)
return;
std::packaged_task<std::wstring()> task([peer,update]
{
const auto prefix=peer.name+L": ";
const auto unconfirmed=prefix+(update?L"Could not confirm receipt of the update request."
:L"Hibernation could not be confirmed.");
try
{
FilesConnection host(&peer);
checkFileReply(host.call({{"action",update?"update":"hibernate"}}));
return prefix+(update?L"Update requested. See the remote KSwitcher log for the result."
:L"Windows accepted the hibernation request.");
}
catch(const std::system_error &error)
{
switch(error.code().value())
{
case ERROR_ACCESS_DENIED:
return prefix+(update?L"Remote updates are disabled. Check Files settings on this PC."
:L"Hibernation is not allowed. Check the remote Files settings.");
case ERROR_INVALID_FUNCTION:
return prefix+(update?L"This version of KSwitcher cannot accept remote update requests."
:L"Update KSwitcher to enable remote hibernation.");
case ERROR_PRIVILEGE_NOT_HELD:
return prefix+L"Windows denied the hibernation privilege.";
default:
return unconfirmed+L" "+fileError(error);
}
}
catch(const std::exception &)
{
return unconfirmed;
}
});
pendingPeerAction=task.get_future();
try {std::thread(std::move(task)).detach();}
catch(const std::system_error &error)
{
pendingPeerAction={};
setStatus(fileError(error));
return;
}
setStatus((update?L"Requesting a KSwitcher update on ":L"Requesting hibernation for ")+peer.name+L"...");
}
void selectDrive()
{
auto row=SendMessageW(picker,LB_GETCURSEL,0,0);
@@ -1437,6 +1500,7 @@ void selectDrive()
}
else if(menuIndex==2 && row==3) showFolderShortcuts(panels[active],-1);
else if(menuIndex==2 && (row==4 || row==5)) openSelectedText(panels[active],row==5,true);
else if(menuIndex==2 && (row==6 || row==7)) runActivePeerAction(owner,row==7);
else
{
const int command=menuIndex==1?113+static_cast<int>(row):110+static_cast<int>(row);
@@ -4233,8 +4297,16 @@ void openMenu(HWND window, int index)
index==0?L" Change drive\tAlt+F1":L" Change drive\tAlt+F2"};
}
else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10"};
else if(index==2) rows={L"Refresh\tF2",L"View\tF3",L"Edit\tF4",L"Folder shortcuts",
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4"};
else if(index==2)
{
rows={L"Refresh\tF2",L"View\tF3",L"Edit\tF4",L"Folder shortcuts",
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4"};
if(panels[active].peer)
{
rows.push_back(L"Hibernate remote PC");
rows.push_back(L"Update remote KSwitcher");
}
}
std::set<wchar_t> used;
commandAccessPositions.assign(rows.size(),std::wstring::npos);
const auto reserve=[&](size_t row,wchar_t key)
@@ -4448,7 +4520,14 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
}
case WM_TIMER:
if(wp==driveQueryTimer) {pollDriveQueries(window);return 0;}
if(wp==terminalTimer) { updateTerminalOutput(); return 0; }
if(wp==terminalTimer)
{
if(pendingPeerAction.valid() &&
pendingPeerAction.wait_for(std::chrono::seconds(0))==std::future_status::ready)
setStatus(pendingPeerAction.get());
updateTerminalOutput();
return 0;
}
if(wp==directoryWatchTimer) { refreshChangedPanels(); return 0; }
if(wp!=transferHighlightTimer) break;
++transferHighlightPhase;
@@ -5147,11 +5226,12 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
{
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0;
if(ctrl && !shift && (message.wParam=='F' || message.wParam=='C'))
if(ctrl && !shift && (message.wParam=='F' || message.wParam=='C' || message.wParam==VK_RETURN))
{
if(!(message.lParam & (1LL<<30)))
{
if(message.wParam=='F') insertCurrentPanelPath();
else if(message.wParam==VK_RETURN) insertCurrentPanelPath(true);
else SendMessageW(terminalInput,WM_COPY,0,0);
}
continue;
+17 -4
View File
@@ -1,5 +1,5 @@
constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286,
optionsRemoteTerminal=370;
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",
@@ -80,6 +80,8 @@ struct OptionsBaseline
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};
@@ -154,6 +156,8 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
checked(optionsRemoteHibernate)!=base.remoteHibernate ||
checked(optionsRemoteUpdate)!=base.remoteUpdate ||
draft.text!=base.text;
EnableWindow(GetDlgItem(dialog,optionsApply),dirty);
InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE);
@@ -423,7 +427,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,optionsRemoteTerminal};
constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate};
show(commandLineControls,page==CommandLine && section==0);
show(textControls,textOptionsPage(page));
show(editingControls,page==TextEditor);
@@ -519,7 +523,8 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
matches(L"Underline") || matches(L"Strikethrough") || matches(L"Foreground"));
}
else if(page==CommandLine) addSection(L"Command history",0,
matches(L"Previous command") || matches(L"Allow paired PCs to run PowerShell commands here"));
matches(L"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") ||
@@ -584,6 +589,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
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;
@@ -701,6 +708,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
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)
@@ -740,7 +749,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 optionsRemoteTerminal:
case 273: case 274: case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
updateOptionsApply(dialog,*draft);
return TRUE;
case 321: case 323:
@@ -841,6 +850,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
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);
@@ -887,6 +898,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
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);
+6 -1
View File
@@ -295,7 +295,12 @@ 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::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);
+1
View File
@@ -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
+56 -9
View File
@@ -33,13 +33,17 @@ void checkFileReply(const Json &reply)
if(error) throw std::system_error(static_cast<int>(error),std::system_category());
}
bool remoteTerminalAllowed()
static bool filesPermissionEnabled(const wchar_t *name)
{
DWORD allowed{},size=sizeof(allowed);
return RegGetValueW(HKEY_CURRENT_USER,L"Software\\KSwitcher\\Files",remoteTerminalPreference,
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);
@@ -232,6 +236,27 @@ 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;
@@ -403,6 +428,7 @@ 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;
@@ -558,8 +584,10 @@ class FileOperations
return reply;
}
public:
explicit FileOperations(bool remote,FilesListener::TerminalPermission permission={}):
terminalPermission(std::move(permission)),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)
{
@@ -573,6 +601,14 @@ 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())
@@ -865,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>())
@@ -986,11 +1028,14 @@ 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,TerminalPermission permission):
local(std::move(id)),key(std::move(lookup)),terminalPermission(std::move(permission))
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))
{
listener.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(listener.value==INVALID_SOCKET) return;
@@ -1025,7 +1070,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,terminalPermission);
FileOperations operations(true,terminalPermission,hibernate,update);
for(;;)
{
const auto request=wire.read(true);
@@ -1066,8 +1111,10 @@ struct FilesListener::Impl
}
};
FilesListener::FilesListener(std::string local,PairKey key,uint16_t port,TerminalPermission terminalPermission):
impl(std::make_unique<Impl>(std::move(local),std::move(key),port,std::move(terminalPermission))){}
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();}
+8 -1
View File
@@ -42,7 +42,9 @@ class FilesListener
public:
using PairKey = std::function<std::string(const std::string &)>;
using TerminalPermission = std::function<bool()>;
FilesListener(std::string local, PairKey key,uint16_t port=FilesPort,TerminalPermission terminalPermission={});
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();
@@ -54,4 +56,9 @@ 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
View File
@@ -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
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.87";
inline constexpr wchar_t AppVersion[] = L"0.6.89";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+26
View File
@@ -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.'
+44 -1
View File
@@ -1,6 +1,7 @@
#include <winsock2.h>
#include <sddl.h>
#include "lan_files.h"
#include "files_lan_ipc.h"
#include <bit>
#include <atomic>
#include <fstream>
@@ -18,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);
@@ -111,11 +129,16 @@ 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{};};
std::atomic<bool> allowTerminal{};
FilesListener a(first,lookup,0,[&]{return allowTerminal.load();}),b(second,lookup,0);
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)
{
@@ -133,6 +156,26 @@ 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");
+27
View File
@@ -7,6 +7,33 @@ 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
}
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'
} 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'