Compare commits

...
Author SHA1 Message Date
agrynco 6215675cb4 Release KSwitcher v0.6.92 2026-11-16 01:19:24 +02:00
agrynco 56c6257465 Merge pull request 'Release KSwitcher v0.6.91' (#35)
Release KSwitcher v0.6.91
2026-11-16 01:09:12 +02:00
agrynco 64b03a2168 Release KSwitcher v0.6.91 2026-11-16 01:08:40 +02:00
agrynco 36baeeb081 Merge pull request 'Release KSwitcher v0.6.90' (#34)
Release KSwitcher v0.6.90
2026-11-16 00:46:44 +02:00
agrynco 7698ea040d Release KSwitcher v0.6.90 2026-11-16 00:46:06 +02:00
agrynco 84d911ae9e Merge pull request 'Release KSwitcher v0.6.89' (#33)
Release KSwitcher v0.6.89
2026-11-16 00:31:10 +02:00
21 changed files with 682 additions and 189 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.89 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.92 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
+21
View File
@@ -13,6 +13,15 @@ Far Manager є зразком для оформлення файлового м
Це діє і для вкладених діалогів. Під час файлової операції Cancel спершу
просить підтвердити переривання.
Спільне повідомлення Files підлаштовується під заголовок і кількість рядків.
Висота діалогу залежить від видимого вмісту. Приховані та порожні секції
не займають місця. Перед завершенням змін перевір коротке повідомлення й
повідомлення з кількома рядками, включно з відступами до рамки та кнопок.
Смуга прокрутки з’являється, лише коли текст не вміщується в доступну висоту.
Оформлення, кнопки й необов’язковий прапорець задаються параметрами шаблону.
Підтвердження гібернації та віддаленого оновлення мають червоне оформлення
Warning і початковий фокус на No.
## Скорочення
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
@@ -60,6 +69,9 @@ Far Manager є зразком для оформлення файлового м
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
- Ctrl+C копіює весь введений у командний рядок текст, навіть коли виділено
лише його частину.
- Ctrl+Insert копіює імена позначених файлів і папок активної панелі в порядку
відображення, по одному на рядок. Якщо позначок немає, копіюється ім’я під
курсором. Шляхи й рядок `..` пропускаються.
- Ctrl+E підставляє останню команду. Повторне натискання
підставляє старішу, доки не досягне початку історії. Alt+F8 відкриває історію
@@ -98,6 +110,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** у треї відкриває нове вікно.
@@ -116,6 +132,11 @@ Far Manager є зразком для оформлення файлового м
відкриваються в окремих немодальних вікнах із власними кнопками на панелі
завдань Windows. При повторному відкритті Files пропонує перейти до вже
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
- Коли курсор на папці, F3 у фоні підраховує сумарний розмір файлів у ній
та вкладених папках. Якщо позначено папки, розмір рахується для кожної з
них окремо. Результат видно в колонці Size у широкому режимі та в рядку
стану, коли там увімкнено розмір. Це працює і в LAN-панелі. Посилання й
junction не обходяться. Недоступний вміст позначається як частковий результат.
- F3 і F4 працюють і на панелі LAN. Файл завантажується у тимчасову копію
на диску у фоновому режимі. Збереження передає зміни назад на віддалений ПК.
Якщо розмір або час зміни віддаленого файла відрізняється від відкритої
Binary file not shown.
+18
View File
@@ -1,5 +1,23 @@
# Latest Windows release
## 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.
+1 -1
View File
@@ -1 +1 @@
06d74702f466c8f793fafbbf54942fd1688e36f975b4d709652bbdb023e2fc2f KSwitcher-win-x64.zip
448c242568f80cb07788173b1182f3f5b20cf152290f5de85efa148456406cff KSwitcher-win-x64.zip
+53 -53
View File
@@ -1,136 +1,136 @@
{
"version": "0.6.92",
"schema": 1,
"version": "0.6.89",
"files": [
{
"path": "KSwitcher.exe",
"sha256": "411340c538f2b76424b7e4d228c217ab1b56e059ee640c109888f59115d9d5ec",
"size": 2465792
"size": 2467840,
"sha256": "daaf3c8f0b1090f89416bcc6771985c006e80a40c7027172d20bfbefaba1dde5"
},
{
"path": "KSwitcher.Config.exe",
"sha256": "f48c68669147e32090823465639d8301798f2e4934e160becd1b5fd42d6708bb",
"size": 2445824
"size": 2446848,
"sha256": "eeb98f92a1a6ef53fa86f3b914a0445e03b757832bfde52853740dc7caebd951"
},
{
"path": "KSwitcher.Screenshot.exe",
"sha256": "311ebf1a3d135fe6ce8bfd0978a9552fbb64c7d7f9a791f4aa4c5bd2c439f06f",
"size": 3052544
"size": 3053568,
"sha256": "ed378e0b6868489f05287e34c8d354c5bd7dec887552309aa918beaacd8f3f0a"
},
{
"path": "KSwitcher.Files.exe",
"sha256": "73acd9be067451c3db83706be0164959f2ac130259c41c48841d16d1aa2792d5",
"size": 3671552
"size": 3686912,
"sha256": "78068ae7cf5c645508f8e5bbf9e5d9c7f75501445e5ee5e1b745e6abed387052"
},
{
"path": "WebView2Loader.dll",
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"size": 194912
"size": 194912,
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
},
{
"path": "terminal/addon-fit-LICENSE.txt",
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"size": 1103
"size": 1103,
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
},
{
"path": "terminal/addon-fit.js",
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"size": 1521
"size": 1521,
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
},
{
"path": "terminal/index.html",
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"size": 527
"size": 527,
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
},
{
"path": "terminal/terminal.js",
"sha256": "fb302b2902fea6a815a8266811f350d1e4c108ca88fafd49e6eddcbfff90a5e5",
"size": 4268
"size": 4375,
"sha256": "7a31fe8679b7942775c7a9a3e34e836744111b7337e750d6ec7b21188dc4cd61"
},
{
"path": "terminal/xterm-LICENSE.txt",
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"size": 1261
"size": 1261,
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
},
{
"path": "terminal/xterm.css",
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"size": 7112
"size": 7112,
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
},
{
"path": "terminal/xterm.js",
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"size": 488663
"size": 488663,
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
},
{
"path": "LICENSE",
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"size": 4401
"size": 4401,
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
},
{
"path": "json-LICENSE.txt",
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86",
"size": 1075
"size": 1075,
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86"
},
{
"path": "files-text-license.txt",
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"size": 883
"size": 883,
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
},
{
"path": "README.md",
"sha256": "7b34f2af7341f57d7bac1b5b7e55a40595a6bc20f461f98c0c6320336d0deba7",
"size": 94223
"size": 94223,
"sha256": "7b34f2af7341f57d7bac1b5b7e55a40595a6bc20f461f98c0c6320336d0deba7"
},
{
"path": "LAN-PREVIEW.md",
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada",
"size": 11418
"size": 11418,
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada"
},
{
"path": "dictionaries/en.txt",
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21",
"size": 682867
"size": 682867,
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21"
},
{
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5",
"size": 20138
"size": 20138,
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5"
},
{
"path": "dictionaries/README.md",
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"size": 2265
"size": 2265,
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
},
{
"path": "dictionaries/ru.txt",
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b",
"size": 1060364
"size": 1060364,
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b"
},
{
"path": "dictionaries/sources.json",
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"size": 1280
"size": 1280,
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
},
{
"path": "dictionaries/uk.txt",
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"size": 940799
"size": 940799,
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
},
{
"path": "tools/README.txt",
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"size": 993
"size": 993,
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
},
{
"path": "tools/StayHere.exe",
"sha256": "2b214b0ed2b6f754611f3355ccdcc6797c6bc5c2aac70bd51e060ba25eb4c3a5",
"size": 133120
"size": 133120,
"sha256": "a67a06d20b280c55f02f70b9aae3a967e510bb21d3e1430ef080d628b9e1a484"
},
{
"path": "tools/StayHere-README.md",
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"size": 2796
"size": 2796,
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
}
]
}
+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,89,0
PRODUCTVERSION 0,6,89,0
FILEVERSION 0,6,92,0
PRODUCTVERSION 0,6,92,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.89"
VALUE "FileVersion", "0.6.92"
END
END
BLOCK "VarFileInfo"
+5 -13
View File
@@ -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
+3
View File
@@ -61,6 +61,9 @@ terminal.attachCustomKeyEventHandler(event => {
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 return true;
event.preventDefault();
return false;
+30 -1
View File
@@ -415,16 +415,45 @@ function Write-UpdateJournal([string]$Message) {
[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)) {
if ($process.Path -notmatch $pattern) { continue }
$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 }
+13 -1
View File
@@ -3010,7 +3010,13 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
case LanUpdateRequestedMessage:
if (!lan::remoteUpdateAllowed()) return 0;
if (app->updateRunning)
log(L"LAN update request ignored because an update is already running.");
{
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.");
@@ -3030,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;
+1 -1
View File
@@ -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{};
+356 -97
View File
@@ -247,6 +247,49 @@ DWORD requestElevatedFolder(HWND owner,const fs::path &directory,
}
return ERROR_TIMEOUT;
}
struct FolderSize
{
uint64_t bytes{};
bool partial{};
};
using FolderSizes=std::map<fs::path,FolderSize>;
FolderSize measureFolder(FilesConnection &host,const fs::path &root,std::stop_token stop)
{
FolderSize size;
std::vector<fs::path> pending{root};
while(!pending.empty() && !stop.stop_requested())
{
const auto directory=std::move(pending.back());
pending.pop_back();
try
{
const auto info=statFile(host,directory);
if(!info || !(info->attributes&FILE_ATTRIBUTE_DIRECTORY))
{
size.partial=true;
continue;
}
if(info->attributes&FILE_ATTRIBUTE_REPARSE_POINT)
{
if(directory==root) size.partial=true;
continue;
}
listFiles(host,directory,[&](const fs::path &path,const FileInfo &entry)
{
if(stop.stop_requested()) return false;
if(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT) return true;
if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY) pending.push_back(path);
else if(entry.size>UINT64_MAX-size.bytes) size.partial=true;
else size.bytes+=entry.size;
return true;
});
}
catch(const std::exception &) {size.partial=true;}
}
return size;
}
struct Panel
{
HWND path{}, list{}, heading{};
@@ -274,6 +317,9 @@ struct Panel
std::vector<std::wstring> sizes;
std::vector<bool> dimmed;
std::vector<bool> marked;
FolderSizes folderSizes;
std::future<FolderSizes> folderSizeQuery;
std::stop_source folderSizeStop;
std::set<fs::path> transferResults;
size_t fileExtensionLength{}, folderExtensionLength{};
bool wide{};
@@ -316,6 +362,7 @@ HWND picker{}, pickerFrame{}, menuBar{};
HWND menuItems[5]{};
constexpr std::wstring_view menuAccessKeys=L"LFCOR";
std::vector<size_t> commandAccessPositions;
std::vector<int> commandActions;
int menuIndex{};
bool commandPicker{};
constexpr int defaultSizeWidth=6, defaultFontPoints=110;
@@ -344,8 +391,7 @@ struct DriveChoice { FilesPeer peer; fs::path path; };
std::vector<DriveQuery> driveQueries;
std::map<LRESULT,DriveChoice> remoteDriveRows;
constexpr UINT_PTR driveQueryTimer=3;
bool refreshDriveAddresses{};
ULONGLONG driveOpened{};
ULONGLONG nextDriveRefresh{},driveRefreshDeadline{};
int drivePickerWidth{};
int pickerPanel{};
std::wstring panelSearchPrefix;
@@ -388,8 +434,14 @@ void savePlacement(HWND window)
&placement,sizeof(placement));
}
void chooseDrive(int index, bool fromMenu = false);
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,bool confirm=false,
bool *remember=nullptr,bool warning=false);
enum class FilesNoticeTone { dialog, neutral, warning };
struct FilesNoticeOptions
{
bool confirm{};
bool *remember{};
FilesNoticeTone tone{FilesNoticeTone::dialog};
};
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={});
void openMenu(HWND window, int index);
void showFileDetails(const Panel &panel);
void editOptions(HWND owner);
@@ -898,6 +950,33 @@ LRESULT currentPanelRow(const Panel &panel)
return row>=0 && static_cast<size_t>(row)<panel.rows.size()?row:LB_ERR;
}
std::vector<fs::path> selectedPanelPaths(const Panel &panel)
{
std::vector<fs::path> paths;
for(size_t i=0;i<panel.rows.size();++i)
if(panel.marked[i] && panel.sizes[i]!=L"Up") paths.push_back(panel.rows[i]);
if(paths.empty())
{
const auto row=currentPanelRow(panel);
if(row!=LB_ERR && panel.sizes[row]!=L"Up") paths.push_back(panel.rows[row]);
}
return paths;
}
void copyPanelNames(HWND owner)
{
const auto paths=selectedPanelPaths(panels[active]);
if(paths.empty()) return;
std::wstring names;
for(const auto &path:paths)
{
if(!names.empty()) names+=L"\r\n";
names+=path.filename().native();
}
try { ks::writeClipboard(owner,ks::textClip(names)); }
catch(const std::exception &) { setStatus(L"Could not copy file names."); }
}
std::wstring powerShellPath(const fs::path &path)
{
std::wstring quoted=L"'";
@@ -979,6 +1058,7 @@ bool ensureTerminalView(HWND owner)
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"copy-panel-names") copyPanelNames(owner);
else if(message==L"toggle") showTerminal(owner,!terminalVisible);
else if(!terminalVisible && (message==L"grow" || message==L"shrink"))
{
@@ -1226,7 +1306,11 @@ void showFileDetails(const Panel &panel)
if(statusFields&2)
{
const auto &size=panel.sizes[row];
details+=L" "+(size==L"Folder" || size==L"Up"?size:formatSize(std::stoull(size)));
const auto measured=panel.folderSizes.find(path);
if(size==L"Folder" && measured!=panel.folderSizes.end())
details+=L" "+formatSize(measured->second.bytes)+(measured->second.partial?L" (partial)":L"");
else
details+=L" "+(size==L"Folder" || size==L"Up"?size:formatSize(std::stoull(size)));
}
std::wstring timestamp=date;
if((statusFields&4) && timestamp.size()>=12) details+=timestamp.substr(0,12);
@@ -1279,7 +1363,7 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti
const auto question=L"Windows denied access to this folder.\r\n"+path+
L"\r\n\r\nTry opening as administrator? Windows may still ask for UAC.";
if(rememberElevationApproval || showFilesNotice(owner,question.c_str(),
L"KSwitcher Files",true,&remember)==IDYES)
L"KSwitcher Files",{.confirm=true,.remember=&remember})==IDYES)
{
const auto result=requestElevatedFolder(owner,directory,folders,files,metadata);
SetForegroundWindow(owner);
@@ -1326,6 +1410,12 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti
}
panel.directory = directory;
panel.peer=std::move(peer);
if(!sameDirectory)
{
panel.folderSizeStop.request_stop();
panel.folderSizeQuery={};
panel.folderSizes.clear();
}
if(!sameDirectory || nextWatch.handle!=INVALID_HANDLE_VALUE)
{
panel.watch.reset();
@@ -1409,6 +1499,61 @@ void refreshChangedPanels()
}
}
void calculateFolderSizes(Panel &panel,LRESULT current)
{
if(panel.folderSizeQuery.valid())
{
setStatus(L"Calculating folder sizes...");
return;
}
std::vector<fs::path> folders;
for(size_t i=0;i<panel.rows.size();++i)
if(panel.marked[i] && panel.sizes[i]==L"Folder") folders.push_back(panel.rows[i]);
if(folders.empty()) folders.push_back(panel.rows[current]);
panel.folderSizeStop=std::stop_source{};
std::packaged_task<FolderSizes()> task(
[folders=std::move(folders),peer=panel.peer,stop=panel.folderSizeStop.get_token()]
{
FolderSizes results;
try
{
FilesConnection host(peer?&*peer:nullptr);
for(const auto &folder:folders)
{
if(stop.stop_requested()) break;
results.emplace(folder,measureFolder(host,folder,stop));
}
}
catch(const std::exception &)
{
for(const auto &folder:folders) results.try_emplace(folder,FolderSize{0,true});
}
return results;
});
panel.folderSizeQuery=task.get_future();
try {std::thread(std::move(task)).detach();}
catch(const std::system_error &error)
{
panel.folderSizeQuery={};
setStatus(fileError(error));
return;
}
setStatus(L"Calculating folder sizes...");
}
void collectFolderSizes()
{
for(auto &panel:panels)
{
if(!panel.folderSizeQuery.valid() ||
panel.folderSizeQuery.wait_for(std::chrono::seconds(0))!=std::future_status::ready) continue;
for(const auto &[path,size]:panel.folderSizeQuery.get()) panel.folderSizes.insert_or_assign(path,size);
InvalidateRect(panel.list,nullptr,FALSE);
if(&panel==&panels[active]) showFileDetails(panel);
}
}
void openSelectedText(const Panel &panel, bool edit, bool external);
INT_PTR confirmTextSave(HWND owner);
INT_PTR paintTextDialog(HWND window, UINT message, WPARAM wp, LPARAM lp, const wchar_t *caption);
@@ -1431,7 +1576,8 @@ void runActivePeerAction(HWND owner,bool update)
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)
if(showFilesNotice(owner,question.c_str(),update?L"Update remote KSwitcher":L"Hibernate remote PC",
{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES)
return;
std::packaged_task<std::wstring()> task([peer,update]
@@ -1481,6 +1627,11 @@ void runActivePeerAction(HWND owner,bool update)
void selectDrive()
{
auto row=SendMessageW(picker,LB_GETCURSEL,0,0);
if(commandPicker)
{
if(row<0 || static_cast<size_t>(row)>=commandActions.size() || commandActions[row]<0) return;
row=commandActions[row];
}
if(!commandPicker && (row<0 || static_cast<size_t>(row)==drivePaths.size())) return;
const auto remote=remoteDriveRows.find(row);
if(commandPicker || row<static_cast<LRESULT>(drivePaths.size()) || remote!=remoteDriveRows.end())
@@ -1516,6 +1667,26 @@ void selectDrive()
LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
{
if(commandPicker)
{
const auto separator=[](LRESULT row)
{
return row>=0 && static_cast<size_t>(row)<commandActions.size() && commandActions[row]<0;
};
if(msg==WM_KEYDOWN && (wp==VK_UP || wp==VK_DOWN || wp==VK_PRIOR || wp==VK_NEXT))
{
const auto result=DefSubclassProc(window,msg,wp,lp);
const auto row=SendMessageW(window,LB_GETCURSEL,0,0);
if(separator(row))
SendMessageW(window,LB_SETCURSEL,row+((wp==VK_UP || wp==VK_PRIOR)?-1:1),0);
return result;
}
if(msg==WM_LBUTTONDOWN || msg==WM_LBUTTONDBLCLK || (msg==WM_MOUSEMOVE && (wp&MK_LBUTTON)))
{
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
if(!HIWORD(hit) && separator(LOWORD(hit))) return 0;
}
}
if(!commandPicker && msg==WM_CHAR)
{
const auto key=towupper(static_cast<wchar_t>(wp));
@@ -1679,7 +1850,7 @@ void showRemoteDrives(bool focus=false,int initialRow=0)
add(query.peer.name);
if(query.pending.valid()) add(L" Loading drives...");
else if(!query.error.empty()) add(L" "+query.error);
else if(query.peer.address.empty()) add(refreshDriveAddresses?L" Looking for PC...":L" Offline");
else if(query.peer.address.empty()) add(nextDriveRefresh?L" Looking for PC...":L" Offline");
else if(query.drives.empty()) add(L" No drives");
for(const auto &entry:query.drives)
{
@@ -1706,26 +1877,30 @@ void pollDriveQueries(HWND owner)
return;
}
bool changed=false, pending=false;
if(refreshDriveAddresses && GetTickCount64()-driveOpened>=500)
const auto now=GetTickCount64();
if(nextDriveRefresh && now>=nextDriveRefresh)
{
refreshDriveAddresses=false;
nextDriveRefresh=now<driveRefreshDeadline?now+2000:0;
queryDrivePeers();
for(const auto &peer:drivePeers)
if(std::none_of(driveQueries.begin(),driveQueries.end(),[&](const DriveQuery &query){return query.peer.id==peer.id;}))
{
auto entry=std::find_if(driveQueries.begin(),driveQueries.end(),[&](const DriveQuery &query)
{return query.peer.id==peer.id;});
if(entry==driveQueries.end())
{
auto &query=driveQueries.emplace_back();
query.peer=peer;
startDriveQuery(query);
}
for(auto &query:driveQueries)
if(query.peer.address.empty())
for(const auto &peer:drivePeers)
if(peer.id==query.peer.id && !peer.address.empty())
{
query.peer=peer;
startDriveQuery(query);
break;
}
else if(!entry->pending.valid() && (entry->peer.address!=peer.address ||
entry->peer.address.empty() || !entry->error.empty()))
{
entry->peer=peer;
entry->drives=Json::array();
entry->error.clear();
startDriveQuery(*entry);
}
}
changed=true;
}
for(auto &query:driveQueries)
@@ -1739,7 +1914,8 @@ void pollDriveQueries(HWND owner)
try {query.drives=query.pending.get();}
catch(const std::system_error &e)
{
ks::log(L"LAN Files drive query failed: Windows error "+std::to_wstring(e.code().value()));
ks::log(L"LAN Files drive query for "+query.peer.name+L" ("+ks::wide(query.peer.address)+
L") failed: Windows error "+std::to_wstring(e.code().value()));
if(e.code()==std::error_code(WSAETIMEDOUT,std::system_category()))
query.error=L"Connection timed out";
else
@@ -1752,8 +1928,12 @@ void pollDriveQueries(HWND owner)
}
changed=true;
}
if(!pending && drivePeerLookupError.empty() &&
std::none_of(driveQueries.begin(),driveQueries.end(),[](const DriveQuery &query)
{return query.peer.address.empty() || !query.error.empty();}))
nextDriveRefresh=0;
if(changed) showRemoteDrives();
if(!pending && !refreshDriveAddresses) KillTimer(owner,driveQueryTimer);
if(!pending && !nextDriveRefresh) KillTimer(owner,driveQueryTimer);
}
void chooseDrive(int index,bool fromMenu)
@@ -1773,8 +1953,9 @@ void chooseDrive(int index,bool fromMenu)
query.peer=peer;
startDriveQuery(query);
}
refreshDriveAddresses=true;
driveOpened=GetTickCount64();
const auto now=GetTickCount64();
nextDriveRefresh=now+500;
driveRefreshDeadline=now+20000;
const DWORD disks=GetLogicalDrives();
int selected=0;
int textWidth=0;
@@ -1881,7 +2062,8 @@ void openSelectedText(const Panel &panel, bool edit, bool external)
farDropDownPalette,FilesModalDialog::run,FilesModalDialog::finish,FilesModalDialog::dismissOwned,
[](HWND owner)
{
return showFilesNotice(owner,L"This file is already open. Switch to its window?",L"Files",true)==IDYES;
return showFilesNotice(owner,L"This file is already open. Switch to its window?",L"Files",
{.confirm=true})==IDYES;
}},panel.peer?&*panel.peer:nullptr);
}
@@ -2514,7 +2696,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
if(LOWORD(wp)!=IDOK) return FALSE;
const auto showError=[&](const wchar_t *message)
{
showFilesNotice(dialog,message,L"Error",false,nullptr,true);
showFilesNotice(dialog,message,L"Error",{.tone=FilesNoticeTone::warning});
SetFocus(GetDlgItem(dialog,pathField));
};
try
@@ -2904,11 +3086,55 @@ struct FilesNotice
{
const wchar_t *text;
std::wstring title;
bool confirm;
bool *remember;
bool warning;
FilesNoticeOptions options;
};
void layoutFilesNotice(HWND dialog)
{
const auto &notice=*reinterpret_cast<const FilesNotice *>(GetWindowLongPtrW(dialog,DWLP_USER));
const auto frame=dialogFrameMetrics(GetDpiForWindow(dialog));
const auto inset=frame.content();
const auto top=dialogListInset(frame,textHeight);
const auto field=GetDlgItem(dialog,100);
RECT client{};
GetClientRect(dialog,&client);
const auto contentWidth=std::max(1L,client.right-2*inset);
TEXTMETRICW metrics{};
if(const auto dc=GetDC(field))
{
const auto previous=SelectObject(dc,mono);
GetTextMetricsW(dc,&metrics);
SelectObject(dc,previous);
ReleaseDC(field,dc);
}
const auto lineHeight=std::max(1L,metrics.tmHeight);
const auto place=[&](int id,int y,int height)
{
SetWindowPos(GetDlgItem(dialog,id),nullptr,inset,y,contentWidth,height,SWP_NOZORDER|SWP_NOACTIVATE);
};
constexpr LRESULT maxLines=8;
ShowScrollBar(field,SB_VERT,FALSE);
place(100,top,maxLines*lineHeight);
const auto lines=SendMessageW(field,EM_GETLINECOUNT,0,0);
const bool overflow=lines>maxLines;
const auto height=static_cast<int>(std::clamp<LRESULT>(lines,1,maxLines))*lineHeight;
place(100,top,height);
ShowScrollBar(field,SB_VERT,overflow);
const auto style=GetWindowLongPtrW(field,GWL_STYLE);
SetWindowLongPtrW(field,GWL_STYLE,overflow?style|WS_TABSTOP:style&~WS_TABSTOP);
if(!overflow) SendMessageW(field,EM_LINESCROLL,0,-SendMessageW(field,EM_GETFIRSTVISIBLELINE,0,0));
auto bottom=top+height;
if(notice.options.remember)
{
bottom+=dialogRowGap();
place(101,bottom,textHeight);
bottom+=textHeight;
}
place(102,bottom+dialogRowGap()+4,1);
if(notice.options.confirm) layoutDialogButtons(dialog,102,{IDYES,IDNO});
else layoutDialogButtons(dialog,102,{IDOK});
}
INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
@@ -2916,70 +3142,73 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
SetWindowLongPtrW(window,DWLP_USER,lp);
const auto &notice=*reinterpret_cast<const FilesNotice *>(lp);
prepareTextDialog(window);
SetDlgItemTextW(window,100,notice.text);
if(notice.warning)
const auto field=GetDlgItem(window,100);
SendMessageW(field,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,0);
SetWindowTextW(field,notice.text);
if(notice.options.remember)
{
const auto bounds=dialogControlBounds(window,100);
const auto divider=dialogControlBounds(window,102);
RECT text{0,0,bounds.right-bounds.left,0};
if(const auto dc=GetDC(window))
{
const auto previous=SelectObject(dc,mono);
DrawTextW(dc,notice.text,-1,&text,DT_CALCRECT|DT_WORDBREAK|DT_NOPREFIX);
SelectObject(dc,previous);
ReleaseDC(window,dc);
}
const auto height=std::max<LONG>(text.bottom,textHeight);
SetWindowPos(GetDlgItem(window,100),nullptr,bounds.left,bounds.top,bounds.right-bounds.left,height,
SWP_NOZORDER|SWP_NOACTIVATE);
SetWindowPos(GetDlgItem(window,102),nullptr,divider.left,bounds.top+height+dialogRowGap()+4,0,0,
SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
layoutDialogButtons(window,102,{IDOK});
const auto checkbox=GetDlgItem(window,101);
installFarCheckbox(checkbox,notice.options.tone==FilesNoticeTone::warning?FarCheckboxSurface::warning:
notice.options.tone==FilesNoticeTone::neutral?FarCheckboxSurface::gray:FarCheckboxSurface::dialog);
ShowWindow(checkbox,SW_SHOW);
}
if(notice.remember)
{
const auto field=GetDlgItem(window,100);
RECT bounds{};
GetWindowRect(field,&bounds);
SetWindowPos(field,nullptr,0,0,bounds.right-bounds.left,
(bounds.bottom-bounds.top)*3/4,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
ShowWindow(GetDlgItem(window,101),SW_SHOW);
}
if(notice.confirm)
if(notice.options.confirm)
{
ShowWindow(GetDlgItem(window,IDOK),SW_HIDE);
ShowWindow(GetDlgItem(window,IDYES),SW_SHOW);
ShowWindow(GetDlgItem(window,IDNO),SW_SHOW);
groupDialogButtons(window,{IDYES,IDNO});
}
else if(!notice.warning) groupDialogButtons(window,{IDOK});
const auto defaultButton=notice.confirm?IDNO:IDOK;
RECT caption{},text{};
if(const auto dc=GetDC(window))
{
const auto previous=SelectObject(dc,mono);
DrawTextW(dc,notice.title.c_str(),-1,&caption,DT_CALCRECT|DT_SINGLELINE|DT_NOPREFIX);
DrawTextW(dc,notice.text,-1,&text,DT_CALCRECT|DT_NOPREFIX|DT_EXPANDTABS);
SelectObject(dc,previous);
ReleaseDC(window,dc);
}
const auto inset=dialogFrameMetrics(GetDpiForWindow(window)).content();
const auto minimum=std::max({24L*cellWidth,caption.right+6*cellWidth,
notice.options.remember?30L*cellWidth:0L})+2*inset;
const auto width=std::clamp(text.right+cellWidth+2*inset,minimum,std::max(minimum,60L*cellWidth+2*inset));
SetWindowPos(window,nullptr,0,0,width,1,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
layoutFilesNotice(window);
FilesModalDialog::fitWidthToOwner(window,minimum,layoutFilesNotice);
const auto defaultButton=notice.options.confirm?IDNO:IDOK;
SendMessageW(window,DM_SETDEFID,defaultButton,0);
SetFocus(GetDlgItem(window,defaultButton));
return FALSE;
}
const auto *notice=reinterpret_cast<const FilesNotice *>(GetWindowLongPtrW(window,DWLP_USER));
if(!notice) return FALSE;
if(const auto painted=paintCopyDialog(window,message,wp,lp,notice->title.c_str(),
notice->warning,notice->warning?std::initializer_list<int>{102}:std::initializer_list<int>{},
!notice->warning)) return painted;
const bool warning=notice->options.tone==FilesNoticeTone::warning;
const bool palette=notice->options.tone==FilesNoticeTone::dialog;
if(message==WM_CTLCOLORSTATIC && reinterpret_cast<HWND>(lp)==GetDlgItem(window,100) && !palette)
{
const auto dc=reinterpret_cast<HDC>(wp);
SetTextColor(dc,warning?RGB(255,255,255):RGB(0,0,0));
SetBkColor(dc,warning?RGB(128,0,0):RGB(192,192,192));
return reinterpret_cast<INT_PTR>(warning?warningBrush:GetStockObject(LTGRAY_BRUSH));
}
if(const auto painted=paintCopyDialog(window,message,wp,lp,notice->title.c_str(),warning,{102},palette))
return painted;
const auto command=LOWORD(wp);
if(message==WM_COMMAND && (command==IDOK || command==IDCANCEL || command==IDYES || command==IDNO))
{
if(command==IDYES && notice->remember)
*notice->remember=IsDlgButtonChecked(window,101)==BST_CHECKED;
if(command==IDYES && notice->options.remember)
*notice->options.remember=IsDlgButtonChecked(window,101)==BST_CHECKED;
FilesModalDialog::finish(window,command);
return TRUE;
}
return FALSE;
}
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,bool confirm,bool *remember,bool warning)
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options)
{
const bool createBrush=warning && !warningBrush;
const bool createBrush=options.tone==FilesNoticeTone::warning && !warningBrush;
if(createBrush) warningBrush=CreateSolidBrush(RGB(128,0,0));
FilesNotice notice{text,std::wstring(L" ")+title+L" ",confirm,remember,warning};
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(warning?609:607),owner,filesNoticeDialog,
FilesNotice notice{text,std::wstring(L" ")+title+L" ",options};
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(607),owner,filesNoticeDialog,
reinterpret_cast<LPARAM>(&notice));
if(createBrush)
{
@@ -3442,14 +3671,8 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move)
request.otherDirectory=destination.directory;
request.sourcePeer=source.peer?&*source.peer:nullptr;
request.otherPeer=request.destinationPeer=destination.peer?&*destination.peer:nullptr;
for(size_t i=0;i<source.rows.size();++i)
if(source.marked[i]) request.sources.push_back(source.rows[i]);
if(request.sources.empty())
{
const auto row=SendMessageW(source.list,LB_GETCURSEL,0,0);
if(row<0 || static_cast<size_t>(row)>=source.rows.size() || source.sizes[row]==L"Up") return;
request.sources.push_back(source.rows[row]);
}
request.sources=selectedPanelPaths(source);
if(request.sources.empty()) return;
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(102),owner,copyDialog,
reinterpret_cast<LPARAM>(&request));
if(result==-1) setStatus(L"Could not open the Copy dialog.");
@@ -3753,15 +3976,8 @@ bool pumpDeletion(HWND window,bool &canceled)
void deleteSelection(HWND owner,Panel &panel,bool permanent)
{
if(copyInProgress) return;
std::vector<fs::path> paths;
for(size_t i=0;i<panel.rows.size();++i)
if(panel.marked[i] && panel.sizes[i]!=L"Up") paths.push_back(panel.rows[i]);
if(paths.empty())
{
const auto row=SendMessageW(panel.list,LB_GETCURSEL,0,0);
if(row<0 || static_cast<size_t>(row)>=panel.rows.size() || panel.sizes[row]==L"Up") return;
paths.push_back(panel.rows[row]);
}
auto paths=selectedPanelPaths(panel);
if(paths.empty()) return;
const auto shown=std::min<size_t>(paths.size(),10);
std::wstring entries;
for(size_t i=0;i<shown;++i)
@@ -4092,7 +4308,7 @@ INT_PTR CALLBACK makeFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(command!=IDOK) return FALSE;
const auto error=[&](const wchar_t *text,HWND focus)
{
showFilesNotice(dialog,text,L"Error",false,nullptr,true);
showFilesNotice(dialog,text,L"Error",{.tone=FilesNoticeTone::warning});
SetFocus(focus);
};
const auto entered=dialogFieldText(input);
@@ -4207,11 +4423,22 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
{
if(wp==VK_TAB) { activatePanel(static_cast<int>(1-index)); SetFocus(terminalInput); return 0; }
if (wp == VK_RETURN) { enter(panels[index]); return 0; }
if (wp == VK_F2) { open(panels[index], panels[index].directory); return 0; }
if (wp == VK_F2)
{
auto &panel=panels[index];
panel.folderSizeStop.request_stop();
panel.folderSizeQuery={};
panel.folderSizes.clear();
open(panel,panel.directory);
return 0;
}
if (wp == VK_F10) { SendMessageW(GetParent(window), WM_CLOSE, 0, 0); return 0; }
if (wp == VK_F3 || wp == VK_F4)
{
openSelectedText(panels[index],wp==VK_F4,false);
auto &panel=panels[index];
const auto row=currentPanelRow(panel);
if(wp==VK_F3 && row!=LB_ERR && panel.sizes[row]==L"Folder") calculateFolderSizes(panel,row);
else openSelectedText(panel,wp==VK_F4,false);
return 0;
}
if (wp == VK_F5 || wp == VK_F6)
@@ -4307,15 +4534,23 @@ void openMenu(HWND window, int index)
rows.push_back(L"Update remote KSwitcher");
}
}
commandActions.clear();
if(index==2)
{
commandActions={0,3,-1,1,2,4,5};
if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7});
}
else
for(size_t i=0;i<rows.size();++i) commandActions.push_back(static_cast<int>(i));
std::set<wchar_t> used;
commandAccessPositions.assign(rows.size(),std::wstring::npos);
std::vector<size_t> accessPositions(rows.size(),std::wstring::npos);
const auto reserve=[&](size_t row,wchar_t key)
{
const auto &text=rows[row];
for(size_t pos=0;pos<text.size() && text[pos]!=L'\t';++pos)
if(towupper(text[pos])==key && used.insert(key).second)
{
commandAccessPositions[row]=pos;
accessPositions[row]=pos;
return true;
}
return false;
@@ -4326,14 +4561,19 @@ void openMenu(HWND window, int index)
for(size_t i=0;i<rows.size();++i)
{
const auto &text=rows[i];
if(commandAccessPositions[i]==std::wstring::npos)
if(accessPositions[i]==std::wstring::npos)
for(const auto ch:text)
{
if(ch==L'\t') break;
const auto key=towupper(ch);
if(key>=L'A' && key<=L'Z' && reserve(i,static_cast<wchar_t>(key))) break;
}
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(text.c_str()));
}
commandAccessPositions.clear();
for(const auto action:commandActions)
{
commandAccessPositions.push_back(action<0?std::wstring::npos:accessPositions[action]);
SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(action<0?L"":rows[action].c_str()));
}
RECT anchor{}, client{};
GetWindowRect(menuItems[index],&anchor);
@@ -4344,7 +4584,7 @@ void openMenu(HWND window, int index)
const int x=std::clamp(static_cast<int>(anchor.left)+inset,inset,
std::max(inset,static_cast<int>(client.right)-width-inset));
const int y=anchor.bottom+5;
const int height=static_cast<int>(rows.size())*static_cast<int>(SendMessageW(picker,LB_GETITEMHEIGHT,0,0));
const int height=static_cast<int>(commandActions.size())*static_cast<int>(SendMessageW(picker,LB_GETITEMHEIGHT,0,0));
SetWindowPos(pickerFrame,HWND_TOP,x-inset,y-inset,width+2*inset,height+2*inset,SWP_SHOWWINDOW);
SetWindowPos(picker,HWND_TOP,x,y,width,height,SWP_SHOWWINDOW);
SendMessageW(picker,LB_SETCURSEL,0,0);
@@ -4528,7 +4768,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
updateTerminalOutput();
return 0;
}
if(wp==directoryWatchTimer) { refreshChangedPanels(); return 0; }
if(wp==directoryWatchTimer) { refreshChangedPanels(); collectFolderSizes(); return 0; }
if(wp!=transferHighlightTimer) break;
++transferHighlightPhase;
for(auto &panel:panels)
@@ -4850,6 +5090,15 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
}
auto background=item.CtlType==ODT_BUTTON?Footer:item.hwndItem==picker?Dialog:PanelBlue;
auto foreground=colors[Text];
if(item.hwndItem==picker && commandPicker && item.itemID<commandActions.size() && commandActions[item.itemID]<0)
{
FillRect(item.hDC,&item.rcItem,teal);
const auto y=(item.rcItem.top+item.rcItem.bottom)/2;
const RECT line{item.rcItem.left,y,item.rcItem.right,y+1};
SetDCBrushColor(item.hDC,colors[Frame]);
FillRect(item.hDC,&line,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
return TRUE;
}
if(item.hwndItem==picker && !commandPicker && item.itemID==drivePaths.size())
{
auto row=item.rcItem;
@@ -4995,7 +5244,14 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
paintText(item.hDC,name,text.c_str(),foreground,rowBackground,false,rowFont);
const auto &amount=panel.sizes[item.itemID];
auto visible=amount;
if(amount!=L"Folder" && amount!=L"Up")
const auto measured=folder?panel.folderSizes.find(panel.rows[item.itemID]):panel.folderSizes.end();
if(measured!=panel.folderSizes.end())
{
const auto partial=measured->second.partial;
visible=formatSize(measured->second.bytes,static_cast<size_t>(sizeWidth)-(partial?1:0));
if(partial) visible+=L"+";
}
else if(amount!=L"Folder" && amount!=L"Up")
visible=formatSize(std::stoull(amount),static_cast<size_t>(sizeWidth));
paintText(item.hDC,size,visible.c_str(),foreground,rowBackground,true);
RECT line{size.left,size.top,size.left+1,size.bottom};
@@ -5065,6 +5321,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
DestroyWindow(window);
return 0;
case WM_DESTROY:
for(auto &panel:panels) panel.folderSizeStop.request_stop();
KillTimer(window,terminalTimer);
KillTimer(window,directoryWatchTimer);
for(auto &panel:panels) panel.watch.reset();
@@ -5226,12 +5483,14 @@ 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' || message.wParam==VK_RETURN))
if(ctrl && !shift &&
(message.wParam=='F' || message.wParam=='C' || message.wParam==VK_RETURN || message.wParam==VK_INSERT))
{
if(!(message.lParam & (1LL<<30)))
{
if(message.wParam=='F') insertCurrentPanelPath();
else if(message.wParam==VK_RETURN) insertCurrentPanelPath(true);
else if(message.wParam==VK_INSERT) copyPanelNames(window);
else SendMessageW(terminalInput,WM_COPY,0,0);
}
continue;
+2 -1
View File
@@ -306,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;
}
+7 -3
View File
@@ -305,10 +305,15 @@ struct LanService::Impl
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;
{
@@ -346,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){
+27 -13
View File
@@ -1031,30 +1031,43 @@ struct FilesListener::Impl
HostAction hibernate,update;
WinSocket listener;
std::vector<std::unique_ptr<Client>> clients;
uint16_t boundPort{};
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))
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)
{
@@ -1089,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);
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.89";
inline constexpr wchar_t AppVersion[] = L"0.6.92";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+61
View File
@@ -270,6 +270,67 @@ 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.'
} finally {
if ($process -and !$process.HasExited) {
[void]$process.CloseMainWindow()
+53
View File
@@ -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`tF2|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
@@ -477,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.' }
+21
View File
@@ -133,6 +133,27 @@ int main()
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{};};
{
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{};
+5
View File
@@ -23,10 +23,15 @@ try {
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() }