Compare commits

...
25 changed files with 716 additions and 185 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.94 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.95 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
+14 -1
View File
@@ -24,6 +24,9 @@ Warning і початковий фокус на No.
## Скорочення
- У меню Files і його списках, що випадають, стрілки вгору й вниз
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
- Enter і подвійний клік відкривають папку в поточній панелі, а локальний
документ — у програмі, призначеній для його типу у Windows. EXE запускається
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
@@ -138,10 +141,20 @@ Warning і початковий фокус на No.
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
Помилка збереження залишає відкритим редактор зі змінами.
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
у порядку їх відкриття.
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
діють до виходу з цього режиму. F4 відкриває текст із підсвічуванням Markdown.
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
із підсвічуванням Markdown.
Відносні посилання й зображення відкриваються від каталогу вихідного файла.
Вихідний текст приховано, доки Markdown і Mermaid готують перегляд.
Звичайний клік відкриває внутрішнє посилання в тому самому вікні,
Shift+клік відкриває окреме вікно. Назад і вперед працюють через стрілки
перегляду, бічні кнопки миші й Alt+←/→. Ctrl+W закриває перегляд.
Коли локальний Markdown оновлюється на диску, відкритий перегляд
перерендерюється зі збереженням позиції прокрутки.
Вебпосилання HTTP і HTTPS відкриваються в системному браузері.
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
8 МіБ, F3 відкриває текстовий перегляд.
+2 -1
View File
@@ -144,7 +144,8 @@ in the resident app. Screen capture and all screenshot editors run on demand in
process. Closing the last editor (or cancelling the only selection) exits that process. It does not
load resident settings, dictionaries, clipboard history or keyboard hooks. Editor windows have
stable numbered titles within that process. Keep all three executables together when copying or
updating the application. Close screenshot editors before installing an update.
updating the application. After verifying a new package, the updater closes Files, the text and
screenshot editors, Settings, and bundled StayHere for that installation. Save open work before approving an update.
If settings change in the tray while the configurator is open, a conflicting Save is rejected; reopen
the configurator to load the latest settings.
Updates from v0.3.x–v0.4.1 first install the compatible **v0.4.2 bridge** through
Binary file not shown.
+6
View File
@@ -1,5 +1,11 @@
# Latest Windows release
## v0.6.95 — 2026-11-16
Files shows Markdown after rendering completes, refreshes local previews when the file changes on disk, and opens internal links in the same window. Shift+click opens a separate window. The arrow controls, mouse side buttons and Alt+Left/Right navigate history. Ctrl+W closes the viewer. Ctrl+Tab cycles through Files and its open editors and viewers. Up and Down wrap in Files menus and drop-downs. Manual and LAN updates close Files, editors, Settings and bundled StayHere from the target installation before replacing its files. Save open work before updating. When installing this release with an older updater, close Files and its separate windows first. This release replaces v0.6.94.
**Українською.** Files показує Markdown після рендерингу й автоматично оновлює локальний перегляд після змін на диску. Внутрішні посилання відкриваються в тому самому вікні, Shift+клік — в окремому. Історією керують стрілки перегляду, бічні кнопки миші та Alt+←/→. Ctrl+W закриває перегляд. Ctrl+Tab циклічно перемикає Files та відкриті редактори й переглядачі. Стрілки вгору й вниз циклічно проходять меню та розкривні списки. Ручне оновлення й оновлення через LAN закривають Files, редактори, Settings і вбудований StayHere цільової інсталяції перед заміною файлів. Збережіть відкриті правки перед оновленням. Якщо цей реліз встановлює старий оновлювач, спочатку закрийте Files та його окремі вікна. Цей реліз замінює v0.6.94.
## v0.6.94 — 2026-11-16
In KSwitcher Files, F3 renders Markdown with offline Mermaid diagrams, tables, and interactive task lists. Relative links and images work for local and LAN documents. Checkbox changes last for the current preview. F4 opens the syntax-highlighted text editor and F6 switches between View and Edit in the same window, prompting before leaving unsaved edits.
+1 -1
View File
@@ -1 +1 @@
c6778fa173d439401e75c39b5635dc1534b2c96c3e6598a30966e323b7632d6c KSwitcher-win-x64.zip
22bda6ae5555a48bc23aeda7dafe6b132f22be17f0f4979f5e9cc83b366ea3ea KSwitcher-win-x64.zip
+71 -71
View File
@@ -1,166 +1,166 @@
{
"schema": 1,
"version": "0.6.94",
"files": [
{
"path": "KSwitcher.exe",
"size": 2361856,
"sha256": "4bf90ab90dabc1fbdffc383a29db401857470f3c91e8f2129439caaa18d15da0"
"sha256": "a267d8bd17f0247df78bffccf626919cdd91266f3b338a07f9fc3e7f747b0c5e",
"path": "KSwitcher.exe"
},
{
"path": "KSwitcher.Config.exe",
"size": 2359808,
"sha256": "51f61904ad97074a3bfea848969deb3b720b146d1394bfae0437ea5c103c29a4"
"sha256": "06f4baf81aa8b5f0158468ad51262b78cd75a5730ee8ed731036d11820a6121a",
"path": "KSwitcher.Config.exe"
},
{
"path": "KSwitcher.Screenshot.exe",
"size": 3337216,
"sha256": "1011f160feb47ba2e68676bad657155f92a55f32f721f7ae6267fc6434e08406"
"sha256": "b9523a172b2902e5f8fe80328dd8ccda5f95be54f589d90826864b13fcf03de0",
"path": "KSwitcher.Screenshot.exe"
},
{
"path": "KSwitcher.Files.exe",
"size": 3718144,
"sha256": "b8fb10cb98d759253a98e2b2dfe8946e0fc250c5378009035f0b4c8872d09b1f"
"size": 3736064,
"sha256": "7f7379dc5ad9393aab0de48ba5ad4d5b1161e488a088fb11bac3ddfb1f7cb6d9",
"path": "KSwitcher.Files.exe"
},
{
"path": "WebView2Loader.dll",
"size": 194912,
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6"
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
"path": "WebView2Loader.dll"
},
{
"path": "terminal/addon-fit-LICENSE.txt",
"size": 1103,
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
"sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f",
"path": "terminal/addon-fit-LICENSE.txt"
},
{
"path": "terminal/addon-fit.js",
"size": 1521,
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527"
"sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
"path": "terminal/addon-fit.js"
},
{
"path": "terminal/index.html",
"size": 527,
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef",
"path": "terminal/index.html"
},
{
"path": "terminal/markdown-it-LICENSE.txt",
"size": 1073,
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473",
"path": "terminal/markdown-it-LICENSE.txt"
},
{
"path": "terminal/markdown-it.js",
"size": 100786,
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"path": "terminal/markdown-it.js"
},
{
"path": "terminal/markdown.html",
"size": 1340,
"sha256": "630585882979768edfd889427e8126571be3f5e7d759d04dddf451f5ac730019"
"size": 2212,
"sha256": "27d3c6d39325d4995162911c352a8e20603513445683ceb0409e628949c39237",
"path": "terminal/markdown.html"
},
{
"path": "terminal/markdown.js",
"size": 4624,
"sha256": "a6ef0e5f27f39d2dd9e91472f9b28588a60f8a434780af7109a053f6a9523107"
"size": 6534,
"sha256": "dbf9a062364dcc90b59fd98eb0adb0f153ed95accf26e28f7be9cce8c13ae324",
"path": "terminal/markdown.js"
},
{
"path": "terminal/mermaid-LICENSE.txt",
"size": 1089,
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",
"path": "terminal/mermaid-LICENSE.txt"
},
{
"path": "terminal/mermaid.js",
"size": 5537838,
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3",
"path": "terminal/mermaid.js"
},
{
"path": "terminal/terminal.js",
"size": 4478,
"sha256": "0f3edde02b30e7b0f76d0cc88daae5791d720a4b74cf8b34e7c0b4dbe0cf9c9d"
"sha256": "0f3edde02b30e7b0f76d0cc88daae5791d720a4b74cf8b34e7c0b4dbe0cf9c9d",
"path": "terminal/terminal.js"
},
{
"path": "terminal/xterm-LICENSE.txt",
"size": 1261,
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
"sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd",
"path": "terminal/xterm-LICENSE.txt"
},
{
"path": "terminal/xterm.css",
"size": 7112,
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6"
"sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
"path": "terminal/xterm.css"
},
{
"path": "terminal/xterm.js",
"size": 488663,
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972"
"sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
"path": "terminal/xterm.js"
},
{
"path": "LICENSE",
"size": 4401,
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c"
"sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c",
"path": "LICENSE"
},
{
"path": "json-LICENSE.txt",
"size": 1096,
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831",
"path": "json-LICENSE.txt"
},
{
"path": "files-text-license.txt",
"size": 883,
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625"
"sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625",
"path": "files-text-license.txt"
},
{
"path": "README.md",
"size": 94223,
"sha256": "7b34f2af7341f57d7bac1b5b7e55a40595a6bc20f461f98c0c6320336d0deba7"
"size": 94357,
"sha256": "fca41227e9b38bf061298d69806ea66fb00086ae03aec49665e4f68ed2c3f8e9",
"path": "README.md"
},
{
"path": "LAN-PREVIEW.md",
"size": 11418,
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada"
"sha256": "2c13d3ed4761e679c352fb1ade24a1ec3060ad2862376ede801cdee5fcc3bada",
"path": "LAN-PREVIEW.md"
},
{
"path": "dictionaries/en.txt",
"size": 732485,
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9",
"path": "dictionaries/en.txt"
},
{
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"size": 20566,
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5",
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt"
},
{
"path": "dictionaries/README.md",
"size": 2265,
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311"
"sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311",
"path": "dictionaries/README.md"
},
{
"path": "dictionaries/ru.txt",
"size": 1109134,
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849",
"path": "dictionaries/ru.txt"
},
{
"path": "dictionaries/sources.json",
"size": 1280,
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408"
"sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408",
"path": "dictionaries/sources.json"
},
{
"path": "dictionaries/uk.txt",
"size": 940799,
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf"
"sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf",
"path": "dictionaries/uk.txt"
},
{
"path": "tools/README.txt",
"size": 993,
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a"
"sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a",
"path": "tools/README.txt"
},
{
"path": "tools/StayHere.exe",
"size": 134656,
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376"
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376",
"path": "tools/StayHere.exe"
},
{
"path": "tools/StayHere-README.md",
"size": 2796,
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413"
"sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413",
"path": "tools/StayHere-README.md"
}
]
],
"version": "0.6.95",
"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,94,0
PRODUCTVERSION 0,6,94,0
FILEVERSION 0,6,95,0
PRODUCTVERSION 0,6,95,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.94"
VALUE "FileVersion", "0.6.95"
END
END
BLOCK "VarFileInfo"
+12
View File
@@ -6,7 +6,15 @@
<title>Markdown preview</title>
<style>
:root { color-scheme: light dark; font: 16px/1.55 system-ui, sans-serif; }
:root:not(.rendered) body { visibility: hidden; }
body { max-width: 960px; margin: auto; padding: 20px 28px; overflow-wrap: anywhere; }
nav { position: sticky; top: 0; display: flex; gap: .4em; padding-block: .25em; background: Canvas; }
nav button { appearance: none; border: 0; background: transparent; color: LinkText;
font: 1.35em/1.25 system-ui, sans-serif; min-width: 1.55em; padding: 0; cursor: pointer; }
nav button:disabled { color: GrayText; opacity: .6; cursor: default; }
nav button:hover:not(:disabled) { text-decoration: underline; }
nav button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
:is(h1,h2,h3,h4,h5,h6) { scroll-margin-top: 2.5em; }
h1, h2 { border-bottom: 1px solid GrayText; padding-bottom: .25em; }
a { color: LinkText; }
pre, table, figure { overflow: auto; }
@@ -22,6 +30,10 @@ figure { margin: 1em 0; }
.task { list-style: none; }
.task input { margin-inline: -1.15em .4em; cursor: pointer; }
</style>
<nav aria-label="Document history">
<button id="back" type="button" title="Back (Alt+Left)" aria-label="Back" disabled>←</button>
<button id="forward" type="button" title="Forward (Alt+Right)" aria-label="Forward" disabled>→</button>
</nav>
<main></main>
<script src="markdown-it.js"></script>
<script src="mermaid.js"></script>
+52 -11
View File
@@ -2,6 +2,8 @@
const bridge = window.chrome.webview;
const content = document.querySelector('main');
const back = document.querySelector('#back');
const forward = document.querySelector('#forward');
const markdown = markdownit({ html: false, linkify: true });
let generation = 0;
let images = [];
@@ -45,11 +47,28 @@ function send(action, options = {}) {
}
function scrollToHeading(fragment) {
if (!fragment) { window.scrollTo(0, 0); return; }
try { document.getElementById(decodeURIComponent(fragment))?.scrollIntoView(); } catch {}
}
async function render(text, fragment) {
function restorePosition({ fragment, scroll }) {
if (typeof scroll === 'number') window.scrollTo(0, scroll);
else scrollToHeading(fragment);
}
function navigate(action) {
const button = action === 'back' ? back : forward;
if (!button.disabled) send(action, { scroll: Math.round(window.scrollY) });
}
back.addEventListener('click', () => navigate('back'));
forward.addEventListener('click', () => navigate('forward'));
async function render({ text, fragment, scroll, title, keepPosition }) {
const current = ++generation;
if (keepPosition) scroll = window.scrollY;
document.documentElement.classList.remove('rendered');
document.title = title;
content.innerHTML = markdown.render(text);
const headings = new Set();
for (const heading of content.querySelectorAll('h1,h2,h3,h4,h5,h6')) {
@@ -76,7 +95,9 @@ async function render(text, fragment) {
block.parentElement.before(caption);
}
}
if (fragment) scrollToHeading(fragment);
restorePosition({ fragment, scroll });
document.documentElement.classList.add('rendered');
send('rendered');
}
content.addEventListener('click', event => {
@@ -84,16 +105,26 @@ content.addEventListener('click', event => {
if (!link) return;
event.preventDefault();
const path = link.getAttribute('href');
if (!path) return;
if (path.startsWith('#')) {
scrollToHeading(path.slice(1));
} else if (!link.closest('svg')) {
send('link', { path });
}
if (!path || event.ctrlKey || event.metaKey || link.closest('svg')) return;
send('link', { path, newWindow: event.shiftKey, scroll: Math.round(window.scrollY) });
});
document.addEventListener('pointerup', event => {
if (event.button !== 3 && event.button !== 4) return;
event.preventDefault();
navigate(event.button === 3 ? 'back' : 'forward');
});
document.addEventListener('keydown', event => {
if (event.key === 'F6' || event.key === 'Escape' || event.key === 'F10') {
if (event.ctrlKey && !event.altKey && event.key === 'Tab') {
event.preventDefault();
send('cycle');
} else if ((event.altKey && ['ArrowLeft', 'ArrowRight'].includes(event.key)) ||
['BrowserBack', 'BrowserForward'].includes(event.key)) {
event.preventDefault();
navigate(['ArrowLeft', 'BrowserBack'].includes(event.key) ? 'back' : 'forward');
} else if (event.key === 'F6' || event.key === 'Escape' || event.key === 'F10' ||
(event.ctrlKey && event.key.toLowerCase() === 'w')) {
event.preventDefault();
send(event.key === 'F6' ? 'edit' : 'close');
}
@@ -101,8 +132,18 @@ document.addEventListener('keydown', event => {
bridge.addEventListener('message', ({ data }) => {
const message = JSON.parse(data);
if (message.action === 'render') void render(message.text, message.fragment);
if (message.action === 'anchor') scrollToHeading(message.fragment);
if (message.action === 'clear') {
++generation;
document.documentElement.classList.remove('rendered');
content.replaceChildren();
}
if (message.action === 'render') void render(message).catch(() => send('failed'));
if (message.action === 'anchor') restorePosition(message);
if (message.action === 'back' || message.action === 'forward') navigate(message.action);
if (message.action === 'history') {
back.disabled = !message.back;
forward.disabled = !message.forward;
}
if (message.action === 'image' && message.generation === generation && images[message.index]) {
const image = images[message.index];
if (message.source) image.src = message.source;
+10 -17
View File
@@ -411,7 +411,8 @@ function Write-Result($Value) {
}
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",
$label = if ($Unattended) { 'LAN update' } else { 'Update' }
[IO.File]::AppendAllText($Journal, "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') ${label}: $Message`n",
[Text.UTF8Encoding]::new($false))
}
function Stop-UpdateCompanions([string]$Directory) {
@@ -441,8 +442,8 @@ public static class KSwitcherUpdateProcessImage {
}
$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)) {
$pattern = '^' + $prefix + '(?:\.kswitcher-update-[0-9a-f]{32}\\backup\\)?(?:KSwitcher(?:\.(?:Config|Screenshot|Files))?\.exe|tools\\StayHere\.exe)$'
foreach ($process in @(Get-Process 'KSwitcher','KSwitcher.Config','KSwitcher.Screenshot','KSwitcher.Files','StayHere' -ErrorAction SilentlyContinue)) {
$image = [KSwitcherUpdateProcessImage]::Read($process.Id)
if (!$image -and !$process.HasExited) {
Write-UpdateJournal "Could not identify $($process.ProcessName) (PID $($process.Id))."
@@ -492,19 +493,15 @@ try {
Assert-Checksum $archive $checksum
Show-UpdateProgress 'Preparing installation' 'Validating and unpacking the release files'
Expand-Release $archive $stage (Get-StableVersion $release.version)
$screenshotPath = [IO.Path]::GetFullPath((Join-Path $InstallDirectory 'KSwitcher.Screenshot.exe'))
if (!$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-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 }
Write-UpdateJournal "Closed KSwitcher (PID $ParentProcessId)."
Show-UpdateProgress 'Closing KSwitcher components' 'Closing Files, editors, Settings and StayHere'
Stop-UpdateCompanions $InstallDirectory
Show-UpdateProgress 'Installing update' 'Replacing application files; keeping your personal data'
Install-Files $stage $InstallDirectory $backup $changed
$startedName = 'Local\KSwitcher.Update.Started.'+[guid]::NewGuid().ToString('N')
@@ -513,9 +510,7 @@ try {
$child = Start-Process -FilePath (Join-Path $InstallDirectory 'KSwitcher.exe') -ArgumentList "--update-ready-event=$startedName" -WorkingDirectory $InstallDirectory -WindowStyle Hidden -PassThru
if (!$started.WaitOne(30000) -or $child.HasExited) { throw 'The updated application did not confirm startup.' }
$success = $true
if ($Unattended) {
try { Write-UpdateJournal "Completed $($release.version). KSwitcher restarted." } catch {}
}
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
}
@@ -534,9 +529,7 @@ try {
}
}
Write-Result @{state='error';error=$message}
if ($Unattended) {
try { Write-UpdateJournal "Failed. $($message -replace '[\r\n]+',' ')" } catch {}
}
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
+2 -6
View File
@@ -2942,11 +2942,6 @@ void App::trayMenu()
void App::checkUpdate(bool interactive, bool install, const std::wstring &version)
{
if (updateRunning) return;
if (install && interactive && FindWindowW(L"KSwitcher.Config", nullptr))
{
report(L"Close the configurator before installing an update.");
return;
}
if (install && interactive && busy)
{
report(L"Wait for the current text operation to finish, then select Update again.");
@@ -3048,7 +3043,8 @@ LRESULT CALLBACK App::windowProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
if (result->interactive)
{
auto prompt = L"Install KSwitcher " + result->version +
L"?\n\nThe program will close and restart. Settings, history and existing dictionaries are preserved.";
L"?\n\nKSwitcher will restart after closing Files, editors, Settings and StayHere from this installation. "
L"Save any unsaved work before continuing.";
if (MessageBoxW(hwnd, prompt.c_str(), L"KSwitcher Update", MB_YESNO | MB_ICONQUESTION) == IDYES)
app->checkUpdate(true, true, result->version);
}
+14 -1
View File
@@ -21,6 +21,7 @@
#include <objbase.h>
#include "files_terminal.h"
#include "files_text_window.h"
#include "files_menu_navigation.h"
#include "files_text_preferences.h"
#include "files_menu_paint.h"
#include "files_dropdown_paint.h"
@@ -1686,7 +1687,15 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT
{
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))
if(msg==WM_KEYDOWN && (wp==VK_UP || wp==VK_DOWN))
{
const auto current=SendMessageW(window,LB_GETCURSEL,0,0);
const auto row=ks::files::adjacentMenuRow(current,static_cast<LRESULT>(commandActions.size()),
wp==VK_UP?-1:1,[&](LRESULT candidate){return !separator(candidate);});
if(row!=current) SendMessageW(window,LB_SETCURSEL,row,0);
return 0;
}
if(msg==WM_KEYDOWN && (wp==VK_PRIOR || wp==VK_NEXT))
{
const auto result=DefSubclassProc(window,msg,wp,lp);
const auto row=SendMessageW(window,LB_GETCURSEL,0,0);
@@ -5405,6 +5414,10 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
{
if(GetForegroundWindow()==window || IsChild(window,GetFocus())) restoreCommandFocus();
if(GetMessageW(&message,nullptr,0,0)<=0) break;
if(message.message==WM_KEYDOWN && message.wParam==VK_TAB &&
(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) &&
ks::files::cycleTextWindows(GetAncestor(message.hwnd,GA_ROOT)))
continue;
if(!IsWindow(window) || (message.hwnd && GetAncestor(message.hwnd,GA_ROOTOWNER)!=window))
{
TranslateMessage(&message);
+18
View File
@@ -0,0 +1,18 @@
#pragma once
namespace ks::files
{
template<class Index, class Selectable>
Index adjacentMenuRow(Index current, Index size, int direction, Selectable selectable)
{
auto row=current;
for(Index visited=0;visited<size;++visited)
{
row+=direction;
if(row<0) row=size-1;
if(row>=size) row=0;
if(selectable(row)) return row;
}
return current;
}
}
+2 -1
View File
@@ -175,7 +175,8 @@ public:
COREWEBVIEW2_KEY_EVENT_KIND kind{};
UINT key{};
if(!alive.expired() && SUCCEEDED(args->get_KeyEventKind(&kind)) &&
kind==COREWEBVIEW2_KEY_EVENT_KIND_KEY_DOWN &&
(kind==COREWEBVIEW2_KEY_EVENT_KIND_KEY_DOWN ||
kind==COREWEBVIEW2_KEY_EVENT_KIND_SYSTEM_KEY_DOWN) &&
SUCCEEDED(args->get_VirtualKey(&key)) && handleKey(key))
args->put_Handled(TRUE);
return S_OK;
+19 -3
View File
@@ -147,13 +147,21 @@ uint64_t TextDocument::pages() const
}
uint64_t TextDocument::boundary(uint64_t page) const
{
if (!page) return bom_;
if (page >= pages()) return size_;
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
return boundary(page,source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_);
}
uint64_t TextDocument::boundary(uint64_t page,HANDLE source) const
{
if (!page) return bom_;
if (page >= pages()) return size_;
const auto offset = bom_ + page * pageBytes;
const auto unit = encoding_ == Encoding::utf8 ? 1u : 2u;
const auto sample = read(source_, offset - unit,
const auto sample = read(source, offset - unit,
static_cast<size_t>(std::min<uint64_t>(4096 + unit, size_ - offset + unit)));
const auto getUnit = [&](size_t i) -> unsigned {
const auto first = static_cast<unsigned char>(sample[i]);
@@ -224,8 +232,16 @@ std::string TextDocument::readPage(uint64_t page) const
std::string TextDocument::readOriginal(uint64_t page) const
{
const auto start = boundary(page);
return decode(read(source_, start, static_cast<size_t>(boundary(page + 1) - start)));
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
const auto source=source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_;
const auto start = boundary(page,source);
return decode(read(source, start, static_cast<size_t>(boundary(page + 1,source) - start)));
}
void TextDocument::releaseReadHandle()
{
if(!editable_ && source_!=INVALID_HANDLE_VALUE)
CloseHandle(std::exchange(source_,INVALID_HANDLE_VALUE));
}
bool TextDocument::modifiedWith(uint64_t page, std::string_view current) const
+2
View File
@@ -24,6 +24,7 @@ public:
uint64_t size() const { return size_; }
uint64_t boundary(uint64_t page) const;
std::string readPage(uint64_t page) const;
void releaseReadHandle();
void stage(uint64_t page, std::string_view utf8);
bool modified() const { return !changes_.empty(); }
bool modifiedWith(uint64_t page, std::string_view current) const;
@@ -44,6 +45,7 @@ private:
std::map<uint64_t, Change> changes_;
std::string decode(std::string bytes) const;
uint64_t boundary(uint64_t page,HANDLE source) const;
std::string readOriginal(uint64_t page) const;
std::string encode(std::string_view utf8) const;
};
+354 -40
View File
@@ -1,6 +1,7 @@
#include "files_text_window.h"
#include "files_text_preferences.h"
#include "files_menu_paint.h"
#include "files_menu_navigation.h"
#include "files_history_date.h"
#include "files_text_document.h"
#include "files_text_language.h"
@@ -186,6 +187,7 @@ enum Command : UINT
{
save = 1, close, findText, findNext, previousPage, nextPage, firstPage, lastPage, goToPage,
undo, redo, cut, copy, paste, selectAll, lexerAuto, lexerPlain, options, switchMode,
historyBack, historyForward,
lexerStart = 1000,
};
@@ -328,6 +330,12 @@ struct FarPopup
}
}
void stepMenu(int direction)
{
select(adjacentMenuRow(current,static_cast<int>(rows.size()),direction,
[this](int candidate){return rows[candidate].index>=0;}));
}
void accept()
{
result=rows[current].index;
@@ -439,8 +447,8 @@ LRESULT CALLBACK farPopupWindow(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
case VK_ESCAPE: state->done=true; break;
case VK_RETURN: state->accept(); break;
case VK_UP: state->step(-1); break;
case VK_DOWN: state->step(1); break;
case VK_UP: state->stepMenu(-1); break;
case VK_DOWN: state->stepMenu(1); break;
case VK_PRIOR: state->step(-1,state->visible); break;
case VK_NEXT: state->step(1,state->visible); break;
case VK_HOME: state->step(-1,static_cast<int>(state->rows.size())); break;
@@ -628,6 +636,8 @@ struct RemoteTextFile
class TextWindow;
std::map<HWND,std::shared_ptr<TextWindow>> textWindows;
std::vector<HWND> textWindowOrder;
HWND filesOwner{};
bool textOwnerClosed=false;
constexpr ULONG_PTR openDocumentQuery=0x4B534644;
@@ -724,7 +734,7 @@ public:
HWND window{}, editor{};
bool handleKey(const MSG &message);
void goToFragment(std::string_view fragment);
const std::filesystem::path original;
std::filesystem::path original;
const std::string peerId;
private:
@@ -755,12 +765,34 @@ private:
FilesTerminalView preview;
bool previewWanted{}, previewVisible{};
ULONGLONG previewDeadline{};
ULONGLONG nextFileCheck{};
struct FileStamp
{
uint64_t writeTime, fileIndex, size;
DWORD volume;
bool operator==(const FileStamp &) const = default;
};
std::optional<FileStamp> previewStamp;
std::string previewFragment;
struct PreviewLink
struct PreviewLocation
{
std::filesystem::path path;
std::string fragment;
int scroll{};
};
struct PreviewLink
{
PreviewLocation target;
int direction{}, scroll{};
bool newWindow{};
};
std::vector<PreviewLocation> navigationHistory;
size_t navigationIndex{};
std::optional<size_t> destinationIndex;
PreviewLocation destination;
std::future<std::unique_ptr<RemoteTextFile>> navigation;
std::shared_ptr<std::atomic<bool>> cancelNavigation;
bool restoreScroll{};
std::deque<PreviewLink> previewLinks;
struct ImageRequest
{
@@ -777,9 +809,12 @@ private:
static constexpr UINT_PTR saveTimer = 1;
static constexpr UINT_PTR openTimer = 2;
static constexpr UINT_PTR previewTimer = 3;
static constexpr UINT_PTR navigationTimer = 4;
static constexpr UINT trimUndo = WM_APP + 1;
static constexpr UINT previewFailed = WM_APP + 2;
static constexpr UINT openPreviewLink = WM_APP + 3;
static constexpr UINT previewRendered = WM_APP + 4;
static constexpr UINT cycleWindow = WM_APP + 5;
LRESULT send(UINT message, WPARAM wparam = 0, LPARAM lparam = 0) const
{
@@ -824,9 +859,19 @@ private:
void toggleMode();
void changeMode();
bool needsSave() const;
bool canPreview() const;
void updatePreview();
void stopPreview();
void stopPreview(bool refresh=true,bool keepBrowser=false);
void renderPreview(bool keepPosition=false);
std::optional<FileStamp> previewFileStamp() const;
void refreshPreview();
void cancelPreviewImages();
void previewMessage(const std::wstring &value);
void navigatePreview(PreviewLink request);
void finishNavigation();
void showLocation(std::unique_ptr<RemoteTextFile> fetched);
void syncNavigation();
void updateTitle();
void pollImages();
void focusContent();
void layout();
@@ -868,6 +913,12 @@ void TextWindow::createMenu()
addItem(actions, copy, L"&Copy\tCtrl+C");
addItem(actions, selectAll, L"Select &page\tCtrl+A");
const auto navigation = addGroup(menu, L"&Navigate");
if (!edit)
{
addItem(navigation, historyBack, L"&Back\tAlt+Left");
addItem(navigation, historyForward, L"F&orward\tAlt+Right");
AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr);
}
addItem(navigation, findText, L"&Find on page…\tCtrl+F");
addItem(navigation, findNext, L"Find &next\tF3");
AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr);
@@ -1055,6 +1106,8 @@ void TextWindow::updateMenus()
for (const auto command : {previousPage, firstPage}) enable(command, !busy() && page > 0);
for (const auto command : {nextPage, lastPage}) enable(command, !busy() && page + 1 < pageTotal);
enable(goToPage, !busy() && pageTotal > 1);
enable(historyBack, !navigation.valid() && navigationIndex>0);
enable(historyForward, !navigation.valid() && navigationIndex+1<navigationHistory.size());
}
void TextWindow::installLexer()
@@ -1230,9 +1283,12 @@ void TextWindow::initializeDocument()
{
automatic=detectLanguage(original,document->readPage(0));
language=automatic;
if(canPreview()) ShowWindow(editor,SW_HIDE);
releaseMenu();
createMenu();
installLexer();
loadPage(0);
if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment});
updatePreview();
}
@@ -1339,6 +1395,7 @@ bool TextWindow::needsSave() const
void TextWindow::toggleMode()
{
if(navigation.valid()) return;
if (edit && needsSave())
{
const auto answer = search.style.confirmSave(window);
@@ -1373,58 +1430,95 @@ void TextWindow::changeMode()
const auto caret = send(SCI_GETCURRENTPOS);
document = std::move(replacement);
edit = !edit;
if(canPreview()) ShowWindow(editor,SW_HIDE);
prefs = loadTextPreferences().profiles[edit];
releaseMenu();
createMenu();
installLexer();
loadPage(std::min(page, document->pages() - 1));
send(SCI_GOTOPOS, std::min(caret, send(SCI_GETLENGTH)));
const auto title = std::wstring(edit ? L"Editor — " : L"Viewer — ") +
(remote ? remote->peer.name + L" · " : std::wstring{}) + original.wstring();
SetWindowTextW(window,title.c_str());
updateTitle();
updatePreview();
layout();
focusContent();
}
void TextWindow::updateTitle()
{
const auto title = std::wstring(edit ? L"Editor — " : L"Viewer — ") +
(remote ? remote->peer.name + L" · " : std::wstring{}) + original.wstring();
SetWindowTextW(window,title.c_str());
}
bool TextWindow::canPreview() const
{
return !edit && automatic.lexer=="markdown" && document && document->size()<=TextDocument::editLimit;
}
void TextWindow::updatePreview()
{
if(edit || automatic.lexer!="markdown" || fileSize>TextDocument::editLimit)
if(!canPreview())
{
stopPreview();
stopPreview(true,true);
return;
}
previewWanted=true;
previewDeadline=GetTickCount64()+8000;
previewStamp=previewFileStamp();
nextFileCheck=GetTickCount64()+350;
cancelImages=std::make_shared<std::atomic<bool>>(false);
if(!SetTimer(window,previewTimer,50,nullptr) ||
!preview.create(window,[this](const auto &value){previewMessage(value);},
if(!SetTimer(window,previewTimer,50,nullptr)) { stopPreview(); return; }
if(preview.initialized()) renderPreview();
else if(!preview.create(window,[this](const auto &value){previewMessage(value);},
[this]{PostMessageW(window,previewFailed,0,0);},true,[this](UINT key)
{
if(key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10) return false;
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
if(ctrl && !alt && key==VK_TAB)
{
PostMessageW(window,cycleWindow,0,0);
return true;
}
if(key==VK_BROWSER_BACK || key==VK_BROWSER_FORWARD || (alt && (key==VK_LEFT || key==VK_RIGHT)))
{
PostMessageW(window,WM_COMMAND,key==VK_LEFT || key==VK_BROWSER_BACK?historyBack:historyForward,0);
return true;
}
if(key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false;
PostMessageW(window,WM_COMMAND,key==VK_F6?switchMode:close,0);
return true;
}))
stopPreview();
layout();
}
void TextWindow::stopPreview()
void TextWindow::stopPreview(bool refresh,bool keepBrowser)
{
KillTimer(window,previewTimer);
previewWanted=previewVisible=false;
previewStamp.reset();
cancelPreviewImages();
previewLinks.clear();
if(keepBrowser && preview.initialized()) preview.post(L"{\"action\":\"clear\"}");
else preview.close();
if(refresh)
{
layout();
if(GetForegroundWindow()==window) focusContent();
}
}
void TextWindow::cancelPreviewImages()
{
if(cancelImages) *cancelImages=true;
imageQueue.clear();
previewLinks.clear();
image={};
preview.close();
if(editor) ShowWindow(editor,SW_SHOWNA);
layout();
}
void TextWindow::focusContent()
{
if(previewVisible) preview.focus();
else SetFocus(editor);
else if(!previewWanted) SetFocus(editor);
}
void TextWindow::goToFragment(std::string_view fragment)
@@ -1435,6 +1529,63 @@ void TextWindow::goToFragment(std::string_view fragment)
else previewFragment=fragment;
}
std::optional<TextWindow::FileStamp> TextWindow::previewFileStamp() const
{
if(remote) return {};
const auto file=CreateFileW(original.c_str(),FILE_READ_ATTRIBUTES,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if(file==INVALID_HANDLE_VALUE) return {};
BY_HANDLE_FILE_INFORMATION state{};
const auto found=GetFileInformationByHandle(file,&state);
CloseHandle(file);
if(!found) return {};
const auto combine=[](DWORD high,DWORD low){return (uint64_t{high}<<32)|low;};
return FileStamp{combine(state.ftLastWriteTime.dwHighDateTime,state.ftLastWriteTime.dwLowDateTime),
combine(state.nFileIndexHigh,state.nFileIndexLow),
combine(state.nFileSizeHigh,state.nFileSizeLow),state.dwVolumeSerialNumber};
}
void TextWindow::renderPreview(bool keepPosition)
{
previewDeadline=GetTickCount64()+30000;
std::string text;
for(uint64_t index=0;index<document->pages();++index)
text+=document->readPage(index);
if(!remote) document->releaseReadHandle();
nlohmann::json message{{"action","render"},{"text",std::move(text)},
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
{"keepPosition",keepPosition}};
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
restoreScroll=false;
preview.post(wide(message.dump(-1,' ',false,nlohmann::json::error_handler_t::replace)));
}
void TextWindow::refreshPreview()
{
if(remote || !previewVisible || navigation.valid() || GetTickCount64()<nextFileCheck) return;
nextFileCheck=GetTickCount64()+350;
const auto stamp=previewFileStamp();
if(!stamp || stamp==previewStamp) return;
try
{
auto reopened=std::make_unique<TextDocument>(original,false);
if(!reopened->pages()) return;
document=std::move(reopened);
previewStamp=stamp;
loadPage(std::min(page,document->pages()-1));
if(!canPreview()) { stopPreview(); return; }
cancelPreviewImages();
cancelImages=std::make_shared<std::atomic<bool>>(false);
previewVisible=false;
renderPreview(true);
}
catch(const std::runtime_error &)
{
// The file may be locked or incomplete while another application saves it.
previewStamp.reset();
}
}
void TextWindow::previewMessage(const std::wstring &value)
{
if(!previewWanted) return;
@@ -1442,25 +1593,38 @@ void TextWindow::previewMessage(const std::wstring &value)
{
if(value==L"ready")
{
std::string text;
for(uint64_t index=0;index<document->pages();++index)
text+=document->readPage(index);
nlohmann::json message{{"action","render"},{"text",std::move(text)},
{"fragment",std::exchange(previewFragment,{})}};
preview.post(wide(message.dump(-1,' ',false,nlohmann::json::error_handler_t::replace)));
previewVisible=true;
layout();
if(GetForegroundWindow()==window) focusContent();
renderPreview();
return;
}
const auto message=nlohmann::json::parse(utf8(value));
const auto action=message.at("action").get<std::string>();
if(action=="cycle")
{
PostMessageW(window,cycleWindow,0,0);
return;
}
if(action=="failed")
{
PostMessageW(window,previewFailed,0,0);
return;
}
if(action=="rendered")
{
PostMessageW(window,previewRendered,0,0);
return;
}
// Defer transitions until WebView2 returns from its event callback.
if(action=="edit" || action=="close")
{
PostMessageW(window,WM_COMMAND,action=="edit"?switchMode:close,0);
return;
}
if(action=="back" || action=="forward")
{
previewLinks.push_back({{},action=="back"?-1:1,message.value("scroll",0),false});
PostMessageW(window,openPreviewLink,0,0);
return;
}
if(action!="image" && action!="link") return;
const auto url=message.at("path").get<std::string>();
if(action=="link" && (url.starts_with("https://") || url.starts_with("http://")))
@@ -1468,13 +1632,14 @@ void TextWindow::previewMessage(const std::wstring &value)
ShellExecuteW(window,L"open",wide(url).c_str(),nullptr,nullptr,SW_SHOWNORMAL);
return;
}
const auto target=markdownTarget(original,url);
const auto target=action=="link" && url.starts_with('#') ? original : markdownTarget(original,url);
if(action=="link")
{
if(!target.empty())
{
const auto hash=url.find('#');
previewLinks.push_back({target,hash==url.npos?std::string{}:url.substr(hash+1)});
previewLinks.push_back({{target,hash==url.npos?std::string{}:url.substr(hash+1)},
0,message.value("scroll",0),message.value("newWindow",false)});
PostMessageW(window,openPreviewLink,0,0);
}
}
@@ -1490,8 +1655,96 @@ void TextWindow::previewMessage(const std::wstring &value)
}
}
void TextWindow::syncNavigation()
{
preview.post(wide(nlohmann::json{{"action","history"},{"back",navigationIndex>0},
{"forward",navigationIndex+1<navigationHistory.size()}}.dump()));
}
void TextWindow::navigatePreview(PreviewLink request)
{
if(edit || navigation.valid() || navigationHistory.empty()) return;
if(request.newWindow)
{
openTextWindow(window,request.target.path,false,search.style,remote?&remote->peer:nullptr,
request.target.fragment,true);
return;
}
if((request.direction<0 && navigationIndex==0) ||
(request.direction>0 && navigationIndex+1==navigationHistory.size())) return;
navigationHistory[navigationIndex].scroll=request.scroll;
destinationIndex.reset();
if(request.direction)
{
destinationIndex=request.direction<0 ? navigationIndex-1 : navigationIndex+1;
destination=navigationHistory[*destinationIndex];
}
else destination=std::move(request.target);
if(destination.path==original || !remote) { showLocation(nullptr); return; }
auto cancel=std::make_shared<std::atomic<bool>>(false);
std::packaged_task<std::unique_ptr<RemoteTextFile>()> task(
[peer=remote->peer,path=destination.path,cancel] {
auto file=std::make_unique<RemoteTextFile>(RemoteTextFile{peer,path});
file->download(false,[cancel](uint64_t,uint64_t){return !*cancel;});
return file;
});
if(!SetTimer(window,navigationTimer,75,nullptr))
throw std::runtime_error("Cannot start the LAN navigation timer.");
try
{
auto result=task.get_future();
std::thread(std::move(task)).detach();
navigation=std::move(result);
cancelNavigation=std::move(cancel);
}
catch(...) { KillTimer(window,navigationTimer); throw; }
}
void TextWindow::finishNavigation()
{
if(!navigation.valid() || navigation.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
KillTimer(window,navigationTimer);
showLocation(navigation.get());
}
void TextWindow::showLocation(std::unique_ptr<RemoteTextFile> fetched)
{
const bool sameDocument=destination.path==original;
std::unique_ptr<TextDocument> next;
if(!sameDocument) next=std::make_unique<TextDocument>(fetched?fetched->cache:destination.path,false);
if(destinationIndex) navigationIndex=*destinationIndex;
else if(!sameDocument || navigationHistory[navigationIndex].fragment!=destination.fragment)
{
navigationHistory.resize(navigationIndex+1);
navigationHistory.push_back(destination);
++navigationIndex;
}
if(sameDocument)
{
nlohmann::json message{{"action","anchor"},{"fragment",destination.fragment}};
if(destinationIndex) message["scroll"]=destination.scroll;
preview.post(wide(message.dump()));
syncNavigation();
return;
}
stopPreview(false,true);
document=std::move(next);
if(fetched) remote=std::move(fetched);
original=destination.path;
filename=original.filename().wstring();
previewFragment=destination.fragment;
restoreScroll=destinationIndex.has_value();
initializeDocument();
updateTitle();
layout();
focusContent();
}
void TextWindow::pollImages()
{
refreshPreview();
if(!previewVisible && GetTickCount64()>=previewDeadline)
{
stopPreview();
@@ -1524,8 +1777,8 @@ void TextWindow::layout()
GetClientRect(window, &area);
const auto row = chromeHeight();
MoveWindow(editor, 0, 2 * row, area.right, std::max(0L, area.bottom - 3 * row), TRUE);
preview.layout({0,2*row,area.right,std::max<LONG>(2*row,area.bottom-row)},previewVisible);
ShowWindow(editor,previewVisible?SW_HIDE:SW_SHOWNA);
preview.layout({0,2*row,area.right,std::max<LONG>(2*row,area.bottom-row)},previewWanted);
ShowWindow(editor,document && !previewWanted?SW_SHOWNA:SW_HIDE);
invalidate();
}
@@ -1585,7 +1838,8 @@ void TextWindow::paint()
status += L" │ " + std::to_wstring(fileSize) + L" B";
const auto hints = busy() ? L"Saving…" : insertRejected ? L"Page edit limit: 8 MiB" :
edit ? L"F2 Save F3 Find next F5 Go to page F6 View Ctrl+PgUp/PgDn Pages F10 Close" :
previewVisible ? L"F6 Edit F10 Close" :
previewVisible ? L"F6 Edit Ctrl+W Close" :
previewWanted ? L"Rendering Markdown… Ctrl+W Close" :
L"F3 Find next F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close";
constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX;
top.left += scale(12);
@@ -1646,6 +1900,12 @@ void TextWindow::command(UINT id)
case save: saveFile(false); return;
case close: requestClose(); return;
case switchMode: toggleMode(); return;
case historyBack:
case historyForward:
if(previewVisible)
preview.post(wide(nlohmann::json{{"action",id==historyBack?"back":"forward"}}.dump()));
else navigatePreview({{},id==historyBack?-1:1,0,false});
return;
case previousPage: if (page) go(page - 1); return;
case nextPage: go(page + 1); return;
case firstPage: go(0); return;
@@ -1739,6 +1999,11 @@ bool TextWindow::handleKey(const MSG &message)
if (message.hwnd != editor) return false;
if (message.message == WM_SYSKEYDOWN && (message.lParam & (1LL << 29)))
{
if (!edit && (key==VK_LEFT || key==VK_RIGHT))
{
SendMessageW(window,WM_COMMAND,key==VK_LEFT?historyBack:historyForward,0);
return true;
}
for (size_t index = 0; index < menuBarLabels.size(); ++index)
if (menuBarLabels[index].matches(static_cast<wchar_t>(key)))
{
@@ -1757,7 +2022,9 @@ bool TextWindow::handleKey(const MSG &message)
if (key == VK_F5 || (ctrl && key == 'G')) id = goToPage;
if (key == VK_F6) id = switchMode;
if (key == VK_F9) id = 600;
if (key == VK_ESCAPE || key == VK_F10) id = close;
if (key == VK_ESCAPE || key == VK_F10 || (!edit && ctrl && key=='W')) id = close;
if (!edit && key==VK_BROWSER_BACK) id=historyBack;
if (!edit && key==VK_BROWSER_FORWARD) id=historyForward;
if (ctrl && key == 'F') id = findText;
if (ctrl && key == VK_PRIOR) id = previousPage;
if (ctrl && key == VK_NEXT) id = nextPage;
@@ -1776,6 +2043,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
const auto &state=*static_cast<const std::shared_ptr<TextWindow> *>(create->lpCreateParams);
state->window=window;
textWindows.emplace(window,state);
textWindowOrder.push_back(window);
}
const auto found=textWindows.find(window);
if(found==textWindows.end()) return DefWindowProcW(window,message,wparam,lparam);
@@ -1816,6 +2084,12 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
MSG key{child,msg,wp,lp};
if(state->handleKey(key)) return 0;
}
if(msg==WM_XBUTTONUP && !state->edit)
{
SendMessageW(state->window,WM_COMMAND,
GET_XBUTTON_WPARAM(wp)==XBUTTON1?historyBack:historyForward,0);
return TRUE;
}
return DefSubclassProc(child,msg,wp,lp);
},1,reinterpret_cast<DWORD_PTR>(self.get()));
if(self->remote)
@@ -1831,7 +2105,6 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
}
else self->initializeDocument();
self->layout();
ShowWindow(self->editor,SW_SHOWNA);
return 0;
case WM_ERASEBKGND: return 1;
case WM_PAINT: self->paint(); return 0;
@@ -1846,14 +2119,32 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
return 0;
}
case WM_SETFOCUS: self->focusContent(); return 0;
case cycleWindow: cycleTextWindows(window); return 0;
case WM_KEYDOWN:
if(self->previewWanted && !self->previewVisible)
{
if(wparam==VK_F6) self->toggleMode();
if(wparam==VK_ESCAPE || wparam==VK_F10 ||
(wparam=='W' && (GetKeyState(VK_CONTROL)&0x8000))) self->requestClose();
return 0;
}
break;
case previewFailed: self->stopPreview(); return 0;
case previewRendered:
if(self->previewWanted)
{
self->previewVisible=true;
self->syncNavigation();
self->layout();
if(GetForegroundWindow()==window) self->focusContent();
}
return 0;
case openPreviewLink:
if(!self->previewLinks.empty())
{
const auto target=std::move(self->previewLinks.front());
self->previewLinks.pop_front();
openTextWindow(window,target.path,false,self->search.style,
self->remote?&self->remote->peer:nullptr,target.fragment);
self->navigatePreview(std::move(target));
}
return 0;
case WM_INITMENU: self->updateMenus(); return 0;
@@ -1886,6 +2177,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
if (wparam == saveTimer) self->finishSave();
if (wparam == openTimer) self->finishOpen();
if (wparam == previewTimer) self->pollImages();
if (wparam == navigationTimer) self->finishNavigation();
return 0;
case trimUndo:
if (self->undoBytes >= 32 * TextDocument::pageBytes)
@@ -1897,12 +2189,14 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
}
return 0;
case WM_DESTROY:
self->stopPreview();
if(self->cancelNavigation) *self->cancelNavigation=true;
self->stopPreview(false);
self->releaseMenu();
return 0;
case WM_NCDESTROY:
self->window=nullptr;
textWindows.erase(window);
std::erase(textWindowOrder,window);
if(textOwnerClosed && textWindows.empty()) PostQuitMessage(0);
break;
}
@@ -2018,10 +2312,29 @@ void showFarHistory(HWND dialog,int fieldId,const std::vector<FarHistoryEntry> &
void textWindowOwnerClosed()
{
filesOwner=nullptr;
textOwnerClosed=true;
if(textWindows.empty()) PostQuitMessage(0);
}
bool cycleTextWindows(HWND current)
{
if(!current || (current!=filesOwner && !textWindows.contains(current))) return false;
std::vector<HWND> windows;
if(filesOwner && IsWindowVisible(filesOwner)) windows.push_back(filesOwner);
for(const auto window:textWindowOrder)
if(IsWindowVisible(window)) windows.push_back(window);
if(windows.size()<2) return false;
const auto from=std::find(windows.begin(),windows.end(),current);
if(from==windows.end()) return false;
auto to=std::next(from);
if(to==windows.end()) to=windows.begin();
if(IsIconic(*to)) ShowWindow(*to,SW_RESTORE);
SetForegroundWindow(*to);
if(*to!=filesOwner) SendMessageW(*to,WM_SETFOCUS,0,0);
return true;
}
HWND findOpenDocument(const std::filesystem::path &path,const lan::FilesPeer *peer)
{
const auto identity=documentIdentity(path,peer?peer->id:"");
@@ -2049,14 +2362,15 @@ HWND findOpenDocument(const std::filesystem::path &path,const lan::FilesPeer *pe
}
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer,std::string_view fragment)
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow)
{
try
{
if(!textWindows.contains(owner)) filesOwner=owner;
std::error_code error;
const auto identity=peer?path.lexically_normal():std::filesystem::weakly_canonical(path,error);
const auto &original=error?path:identity;
if(const auto existing=findOpenDocument(original,peer))
if(const auto existing=newWindow?nullptr:findOpenDocument(original,peer))
{
if(dialogs.confirmExisting(owner) && IsWindow(existing))
{
+2 -1
View File
@@ -52,6 +52,7 @@ struct TextDialogs
};
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer=nullptr,std::string_view fragment={});
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false);
void textWindowOwnerClosed();
bool cycleTextWindows(HWND current);
}
+4 -4
View File
@@ -55,12 +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 && expectedVersion.empty())
if (install)
{
command += L" -Unattended -Journal " + quoteArgument((dataDirectory() / L"kswitcher.log").wstring());
command += L" -Journal " + quoteArgument((dataDirectory() / L"kswitcher.log").wstring());
if (expectedVersion.empty()) command += L" -Unattended";
else command += L" -ExpectedVersion " + quoteArgument(expectedVersion);
}
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.94";
inline constexpr wchar_t AppVersion[] = L"0.6.95";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+78 -10
View File
@@ -13,6 +13,21 @@ public static class MarkdownUi {
[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 uint GetWindowThreadProcessId(IntPtr window, out uint pid);
[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);
public static void Activate(IntPtr window) {
if (GetForegroundWindow() == window) return;
keybd_event(0x12,0,0,UIntPtr.Zero);
keybd_event(0x12,0,2,UIntPtr.Zero);
SetForegroundWindow(window);
}
public static void CycleWindow() {
keybd_event(0x11,0,0,UIntPtr.Zero);
keybd_event(0x09,0,0,UIntPtr.Zero);
keybd_event(0x09,0,2,UIntPtr.Zero);
keybd_event(0x11,0,2,UIntPtr.Zero);
}
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id);
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr window, StringBuilder title, int capacity);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
@@ -53,11 +68,17 @@ function Open-File($File, $Key) {
Post $panel 0x100 $Key
}
function Browser($Scenario, $Image = '') {
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port $Scenario $Image
function Browser($Scenario, $Image = '', $Title = '') {
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port $Scenario $Image $Title
if ($LASTEXITCODE) { throw "WebView2 verification failed for $Scenario" }
}
function Wait-Foreground($Window) {
$buffer = [Text.StringBuilder]::new(2048)
[void][MarkdownUi]::GetWindowText($Window,$buffer,$buffer.Capacity)
[void](Wait-For "foreground window $buffer" { [MarkdownUi]::GetForegroundWindow() -eq $Window })
}
function Scintilla($Window) {
[MarkdownUi]::FindWindowEx($Window,0,'Scintilla',[NullString]::Value)
}
@@ -149,15 +170,32 @@ const value = 42;
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $root 'webview'
$process = Start-Process -FilePath (Join-Path $app (Split-Path -Leaf $Executable)) -PassThru -WindowStyle Normal
$main = Wait-For 'Files' { Find-Window 'KSwitcher.Files' }
[MarkdownUi]::Activate($main)
$panel = [MarkdownUi]::GetDlgItem($main,102)
Open-File 'Preview.md' 0x72
$window = Wait-For 'the Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
if ([MarkdownUi]::IsWindowVisible((Scintilla $window))) {
throw 'F3 showed the source text while starting the Markdown preview.'
}
Browser 'render' $Screenshot
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Checking a task modified the read-only file.' }
[IO.File]::WriteAllText($original,($fixture.Replace('Перегляд Markdown','Зміна на диску')))
Browser 'Зміна на диску' '' 'Preview.md'
$replacement = Join-Path $docs 'Preview-replacement.md'
[IO.File]::WriteAllText($replacement,$fixture)
[IO.File]::Move($replacement,$original,$true)
Browser 'Перегляд Markdown' '' 'Preview.md'
if ((Find-Window 'KSwitcher.Files.Text' 'Preview.md') -ne $window) { throw 'Reload changed windows.' }
Browser 'edit'
$editor = Wait-For 'F6 in WebView2 to open the editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
if ($editor -ne $window) { throw 'F6 changed windows.' }
[MarkdownUi]::Activate($window)
Wait-Foreground $window
[MarkdownUi]::CycleWindow()
Wait-Foreground $main
[MarkdownUi]::CycleWindow()
Wait-Foreground $window
$control = Scintilla $window
if ([MarkdownUi]::Send($control,2140,0,0).ToInt64()) { throw 'The editor is read-only.' }
Append-Character $control 'X'
@@ -170,11 +208,36 @@ const value = 42;
Answer-Save 7
Browser 'Перегляд Markdown'
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Discard changed the Markdown file.' }
Browser 'ctrl-follow'
if ((Find-Window 'KSwitcher.Files.Text' 'Preview.md') -ne $window -or (Find-Window 'KSwitcher.Files.Text' 'Other.md')) {
throw 'Ctrl+click navigated without tabs.'
}
Browser 'shift-follow'
$child = Wait-For 'the Shift+click Markdown window' { Find-Window 'KSwitcher.Files.Text' 'Other.md' $window }
Browser 'Linked Markdown' '' 'Other.md'
[MarkdownUi]::Activate($child)
Browser 'cycle' '' 'Other.md'
Wait-Foreground $main
[MarkdownUi]::CycleWindow()
Wait-Foreground $window
Browser 'cycle' '' 'Preview.md'
Wait-Foreground $child
Browser 'close' '' 'Other.md'
[void](Wait-For 'Ctrl+W to close the Shift+click window' { ![MarkdownUi]::IsWindowVisible($child) })
Browser 'follow'
$child = Wait-For 'the linked Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Other.md' $window }
Post $window 0x10 0
Browser 'Linked Markdown'
Post $child 0x10 0
if ((Wait-For 'the in-place Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Other.md' }) -ne $window) {
throw 'A normal click did not stay in the same window.'
}
Browser 'Linked Markdown' '' 'Other.md'
Browser 'mouse-back' '' 'Other.md'
Browser 'Перегляд Markdown' '' 'Preview.md'
Browser 'mouse-forward' '' 'Preview.md'
Browser 'Linked Markdown' '' 'Other.md'
Browser 'back' '' 'Other.md'
Browser 'Перегляд Markdown' '' 'Preview.md'
Browser 'forward' '' 'Preview.md'
Browser 'Linked Markdown' '' 'Other.md'
Browser 'close' '' 'Other.md'
[void](Wait-For 'the Markdown viewers to close' { !(Find-Window 'KSwitcher.Files.Text') })
Open-File 'Preview.md' 0x73
@@ -261,10 +324,15 @@ const value = 42;
Browser 'Перегляд Markdown'
if (![IO.File]::ReadAllText($original).EndsWith('L')) { throw 'F6 rendered before uploading the LAN edit.' }
Browser 'follow'
$child = Wait-For 'the linked LAN Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Other.md' $window }
Post $window 0x10 0
Browser 'Linked Markdown'
Post $child 0x10 0
if ((Wait-For 'the in-place LAN Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Other.md' }) -ne $window) {
throw 'A LAN link did not stay in the same window.'
}
Browser 'Linked Markdown' '' 'Other.md'
Browser 'back' '' 'Other.md'
Browser 'Перегляд Markdown' '' 'Preview.md'
Browser 'forward' '' 'Preview.md'
Browser 'Linked Markdown' '' 'Other.md'
Browser 'close' '' 'Other.md'
if (!$process.WaitForExit(5000) -or $process.ExitCode) { throw 'The LAN fixture did not close normally.' }
Write-Output 'Verified Markdown, Mermaid, relative links/images and F6 saving through an authenticated loopback LAN connection.'
}
+27 -6
View File
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
import { writeFile } from 'node:fs/promises';
import { setTimeout as delay } from 'node:timers/promises';
const [port, scenario, artifact] = process.argv.slice(2);
const [port, scenario, artifact, title] = process.argv.slice(2);
let socket;
const pending = new Map();
let sequence = 0;
@@ -41,7 +41,8 @@ async function evaluate(expression) {
const target = await waitFor(async () => {
const response = await fetch('http://127.0.0.1:' + port + '/json/list').catch(() => null);
if (!response?.ok) return;
return (await response.json()).find(item => item.url === 'https://kswitcher-markdown.invalid/markdown.html');
return (await response.json()).find(item => item.url === 'https://kswitcher-markdown.invalid/markdown.html' &&
(!title || item.title === title));
}, 'the Markdown page in WebView2');
socket = new WebSocket(target.webSocketDebuggerUrl);
socket.addEventListener('message', event => {
@@ -59,9 +60,14 @@ await new Promise((resolve, reject) => {
try {
if (scenario === 'render') {
await waitFor(() => evaluate(`!!document.querySelector('figure svg') &&
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
!!document.querySelector('figure svg') &&
document.querySelector('img')?.naturalWidth === 1`), 'rendered Mermaid SVG and relative image');
assert.equal(await evaluate(`document.querySelector('h1').textContent`), 'Перегляд Markdown');
assert.equal(await evaluate(`[...document.querySelectorAll('nav button')].every(button => {
const style = getComputedStyle(button);
return style.borderTopWidth === '0px' && style.backgroundColor === 'rgba(0, 0, 0, 0)';
})`), true);
assert.equal(await evaluate(`document.querySelector('td').textContent`), 'Cell');
assert.equal(await evaluate(`document.querySelector('figure svg').getBoundingClientRect().height > 0`), true);
assert.equal(await evaluate(`document.querySelector('figure svg').textContent.includes('Render target')`), true);
@@ -81,10 +87,25 @@ try {
}
} else if (scenario === 'edit') {
await command('Input.dispatchKeyEvent', { type: 'keyDown', key: 'F6', code: 'F6', windowsVirtualKeyCode: 117 });
} else if (scenario === 'follow') {
await evaluate(`document.querySelector('a[href^="child/"]').click()`);
} else if (['follow', 'shift-follow', 'ctrl-follow'].includes(scenario)) {
await evaluate(`document.querySelector('a[href^="child/"]').dispatchEvent(new MouseEvent('click', {
bubbles: true, cancelable: true, shiftKey: ${scenario === 'shift-follow'}, ctrlKey: ${scenario === 'ctrl-follow'}
}))`);
} else if (scenario === 'mouse-back' || scenario === 'mouse-forward') {
const button = scenario === 'mouse-back' ? 'back' : 'forward';
await waitFor(() => evaluate(`!document.getElementById('${button}').disabled`), button);
await command('Input.dispatchMouseEvent', {type:'mousePressed', x:15, y:80, button, buttons:button === 'back' ? 8 : 16});
await command('Input.dispatchMouseEvent', {type:'mouseReleased', x:15, y:80, button, buttons:0});
} else if (scenario === 'back' || scenario === 'forward') {
await waitFor(() => evaluate(`!document.getElementById('${scenario}').disabled`), scenario);
await evaluate(`document.getElementById('${scenario}').click()`);
} else if (scenario === 'cycle') {
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'Tab', code:'Tab', modifiers:2, windowsVirtualKeyCode:9});
} else if (scenario === 'close') {
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'w', code:'KeyW', modifiers:2, windowsVirtualKeyCode:87});
} else {
await waitFor(() => evaluate('document.querySelector("h1")?.textContent === ' + JSON.stringify(scenario)), scenario);
await waitFor(() => evaluate('document.documentElement?.classList.contains("rendered") && ' +
'document.querySelector("h1")?.textContent === ' + JSON.stringify(scenario)), scenario);
if (scenario === 'Linked Markdown') {
await waitFor(() => evaluate('scrollY > 0 && document.getElementById("target-heading").getBoundingClientRect().top < innerHeight'),
'the relative heading fragment to scroll into view');
+9 -1
View File
@@ -233,6 +233,10 @@ try {
if (($rows -join '|') -cne "Refresh panel`tCtrl+R|Folder shortcuts||View`tF3|Edit`tF4|View externally`tAlt+F3|Edit externally`tAlt+F4") {
throw 'Commands did not group local actions or showed a LAN-only section.'
}
Post $commandMenu 0x100 38
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq ($count-1) })
Post $commandMenu 0x100 40
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq 0 })
Post $commandMenu 0x100 40
Post $commandMenu 0x100 40
[void](Wait-Until { [SearchArrowTest]::Send($commandMenu,0x188,0,0).ToInt32() -eq 3 })
@@ -348,7 +352,11 @@ try {
Post $selector 0x100 0x73
$popup=Wait-Until { Find-Window 'KSwitcher.Files.DropDown' $process.Id }
Assert-FarDropDown $popup $selector ($arrowBounds.Right-$arrowBounds.Left)
for ($row=0; $row -lt $kind; $row++) { Post $popup 0x100 0x28 }
Post $popup 0x100 0x26
if ($kind -eq 1) {
Post $popup 0x100 0x28
Post $popup 0x100 0x28
}
Post $popup 0x100 13
[void](Wait-Until { ![SearchArrowTest]::IsWindow($popup) })
[void](Wait-Until { [SearchArrowTest]::IsWindowEnabled($targetField) })
+12 -5
View File
@@ -11,6 +11,8 @@ try {
$otherRoot=Join-Path $root 'other-install'
[IO.Directory]::CreateDirectory($companionRoot) | Out-Null
[IO.Directory]::CreateDirectory($otherRoot) | Out-Null
[IO.Directory]::CreateDirectory((Join-Path $companionRoot 'tools')) | Out-Null
[IO.Directory]::CreateDirectory((Join-Path $otherRoot 'tools')) | Out-Null
$companions=@()
$Journal=Join-Path $root 'update.log'
try {
@@ -18,7 +20,10 @@ try {
@{Root=$companionRoot; Name='KSwitcher.Files.exe'},
@{Root=$companionRoot; Name='KSwitcher.Screenshot.exe'},
@{Root=$companionRoot; Name='KSwitcher.Config.exe'},
@{Root=$otherRoot; Name='KSwitcher.Files.exe'})) {
@{Root=$companionRoot; Name='KSwitcher.exe'},
@{Root=$otherRoot; Name='KSwitcher.Files.exe'},
@{Root=$companionRoot; Name='tools/StayHere.exe'},
@{Root=$otherRoot; Name='tools/StayHere.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
@@ -27,11 +32,13 @@ try {
$backup=Join-Path $companionRoot '.kswitcher-update-0123456789abcdef0123456789abcdef/backup'
[IO.Directory]::CreateDirectory($backup) | Out-Null
Move-Item -LiteralPath $oldFiles -Destination $backup
Copy-Item -LiteralPath (Join-Path $backup 'KSwitcher.Files.exe') -Destination $oldFiles
$companions+=Start-Process -FilePath $oldFiles -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'
Assert (@(Get-Content -LiteralPath $Journal | Where-Object { $_ -match 'LAN update: Closed KSwitcher\.' }).Count -eq 3) 'unattended update confirms each companion exited'
Assert (@($companions[0,1,2,3,5,7] | Where-Object HasExited).Count -eq 6) 'update closes resident helpers, both Files processes and bundled StayHere in its installation'
Assert (!$companions[4].HasExited -and !$companions[6].HasExited) 'update leaves Files and StayHere from another installation running'
Assert (@(Get-Content -LiteralPath $Journal | Where-Object { $_ -match 'Update: Closing (KSwitcher|StayHere)' }).Count -eq 6) 'update journals every companion closure'
Assert (@(Get-Content -LiteralPath $Journal | Where-Object { $_ -match 'Update: Closed (KSwitcher|StayHere)' }).Count -eq 6) 'update confirms each companion exited'
} finally {
foreach ($companion in $companions) {
if (!$companion.HasExited) { $companion.Kill(); $companion.WaitForExit() }