Compare commits

...
Author SHA1 Message Date
agrynco abaf73a050 Release KSwitcher v0.6.94
Refs #38
2026-11-16 10:18:44 +02:00
agrynco b16e50bee9 Render Markdown and Mermaid in KSwitcher Files
Refs #38
2026-11-16 10:13:42 +02:00
agrynco 3ed17fa6e8 Merge pull request 'Release KSwitcher v0.6.93' (#37)
Release KSwitcher v0.6.93
2026-11-16 01:26:42 +02:00
agrynco a1df56177d Release KSwitcher v0.6.93 2026-11-16 01:26:12 +02:00
agrynco 09db0e1051 Merge pull request 'Release KSwitcher v0.6.92' (#36)
Release KSwitcher v0.6.92
2026-11-16 01:19:49 +02:00
21 changed files with 1145 additions and 73 deletions

No files matched your search

+22 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.92 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.94 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
@@ -149,6 +149,27 @@ add_test(NAME files-activation-and-refresh
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_activation.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Fixture "$<TARGET_FILE:KSwitcherFilesActivationFixture>")
set_tests_properties(files-activation-and-refresh PROPERTIES RUN_SERIAL TRUE TIMEOUT 120)
find_program(KSWITCHER_NODE NAMES node)
if(KSWITCHER_NODE)
add_executable(KSwitcherFilesMarkdownLanFixture WIN32 tests/files_markdown_lan.cpp
src/files_text_window.cpp src/files_text_document.cpp src/files_text_language.cpp)
target_include_directories(KSwitcherFilesMarkdownLanFixture PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
target_link_libraries(KSwitcherFilesMarkdownLanFixture PRIVATE kscore KSwitcherFilesText)
add_dependencies(KSwitcherFilesMarkdownLanFixture KSwitcherTerminalAssets)
if(MSVC)
set_property(TARGET KSwitcherFilesMarkdownLanFixture PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
target_compile_options(KSwitcherFilesMarkdownLanFixture PRIVATE /utf-8)
else()
target_link_options(KSwitcherFilesMarkdownLanFixture PRIVATE -municode -static)
endif()
add_test(NAME files-markdown-viewer
COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass
-File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_markdown.ps1"
-Executable "$<TARGET_FILE:KSwitcherFiles>" -Node "${KSWITCHER_NODE}"
-LanFixture "$<TARGET_FILE:KSwitcherFilesMarkdownLanFixture>")
set_tests_properties(files-markdown-viewer PROPERTIES RUN_SERIAL TRUE TIMEOUT 120)
endif()
add_executable(KSwitcherLanInputTests tests/lan_input.cpp)
target_link_libraries(KSwitcherLanInputTests PRIVATE kscore)
if(MSVC)
+13
View File
@@ -67,6 +67,9 @@ Warning і початковий фокус на No.
лише до шляхів із пробілами. Для `..` вставляється шлях батьківської папки.
- Ctrl+Enter вставляє лише назву файла або папки під курсором активної панелі
за тими ж правилами вставлення й лапок. Рядок `..` пропускається.
- Ctrl+R перечитує поточну папку активної панелі. Позиція курсора й позначки
зберігаються для наявних елементів, а підраховані через F3 розміри папок
скидаються. F2 також виконує цю дію.
- Ctrl+C копіює весь введений у командний рядок текст, навіть коли виділено
лише його частину.
- Ctrl+Insert копіює імена позначених файлів і папок активної панелі в порядку
@@ -132,6 +135,16 @@ Warning і початковий фокус на No.
відкриваються в окремих немодальних вікнах із власними кнопками на панелі
завдань Windows. При повторному відкритті Files пропонує перейти до вже
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
Помилка збереження залишає відкритим редактор зі змінами.
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
діють до виходу з цього режиму. F4 відкриває текст із підсвічуванням Markdown.
Відносні посилання й зображення відкриваються від каталогу вихідного файла.
Для LAN зображення завантажуються у фоні, а файли за посиланнями — після
кліку. Mermaid працює офлайн. Якщо WebView2 недоступний або файл більший за
8 МіБ, F3 відкриває текстовий перегляд.
- Коли курсор на папці, F3 у фоні підраховує сумарний розмір файлів у ній
та вкладених папках. Якщо позначено папки, розмір рахується для кожної з
них окремо. Результат видно в колонці Size у широкому режимі та в рядку
+12
View File
@@ -1,5 +1,17 @@
# Latest Windows release
## 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.
**Українською.** У KSwitcher Files клавіша F3 відкриває форматований Markdown із діаграмами Mermaid, таблицями та інтерактивними списками завдань. Mermaid працює офлайн. Відносні посилання й зображення працюють для локальних і LAN-файлів. Відмітки чекбоксів діють у поточному сеансі перегляду. F4 відкриває редактор із підсвічуванням синтаксису, а F6 перемикає перегляд і редагування в тому самому вікні. Якщо є незбережені зміни, Files пропонує їх зберегти.
## v0.6.93 — 2026-11-16
In Files, Ctrl+R refreshes the active pane as in FAR Manager. The menu and key bar show Ctrl+R. F2 also refreshes the pane. Refresh preserves marks and the cursor where possible, and clears folder sizes calculated with F3.
**Українською.** У Files Ctrl+R перечитує активну панель, як у FAR Manager. Комбінація показана в меню та рядку клавіш. F2 також перечитує панель. Перечитування зберігає позначки й курсор для наявних елементів і скидає розміри папок, підраховані через F3.
## v0.6.92 — 2026-11-16
In Files, F3 on a folder measures file sizes throughout the directory tree. If folders are marked, Files measures each marked folder separately. Results appear in the Size column in Wide mode. F3 on a file opens the viewer even when folders are marked. Folder sizing runs in the background and supports LAN panes.
+1 -1
View File
@@ -1 +1 @@
448c242568f80cb07788173b1182f3f5b20cf152290f5de85efa148456406cff KSwitcher-win-x64.zip
c6778fa173d439401e75c39b5635dc1534b2c96c3e6598a30966e323b7632d6c KSwitcher-win-x64.zip
+51 -21
View File
@@ -1,26 +1,26 @@
{
"version": "0.6.92",
"schema": 1,
"version": "0.6.94",
"files": [
{
"path": "KSwitcher.exe",
"size": 2467840,
"sha256": "daaf3c8f0b1090f89416bcc6771985c006e80a40c7027172d20bfbefaba1dde5"
"size": 2361856,
"sha256": "4bf90ab90dabc1fbdffc383a29db401857470f3c91e8f2129439caaa18d15da0"
},
{
"path": "KSwitcher.Config.exe",
"size": 2446848,
"sha256": "eeb98f92a1a6ef53fa86f3b914a0445e03b757832bfde52853740dc7caebd951"
"size": 2359808,
"sha256": "51f61904ad97074a3bfea848969deb3b720b146d1394bfae0437ea5c103c29a4"
},
{
"path": "KSwitcher.Screenshot.exe",
"size": 3053568,
"sha256": "ed378e0b6868489f05287e34c8d354c5bd7dec887552309aa918beaacd8f3f0a"
"size": 3337216,
"sha256": "1011f160feb47ba2e68676bad657155f92a55f32f721f7ae6267fc6434e08406"
},
{
"path": "KSwitcher.Files.exe",
"size": 3686912,
"sha256": "78068ae7cf5c645508f8e5bbf9e5d9c7f75501445e5ee5e1b745e6abed387052"
"size": 3718144,
"sha256": "b8fb10cb98d759253a98e2b2dfe8946e0fc250c5378009035f0b4c8872d09b1f"
},
{
"path": "WebView2Loader.dll",
@@ -42,10 +42,40 @@
"size": 527,
"sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef"
},
{
"path": "terminal/markdown-it-LICENSE.txt",
"size": 1073,
"sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473"
},
{
"path": "terminal/markdown-it.js",
"size": 100786,
"sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e"
},
{
"path": "terminal/markdown.html",
"size": 1340,
"sha256": "630585882979768edfd889427e8126571be3f5e7d759d04dddf451f5ac730019"
},
{
"path": "terminal/markdown.js",
"size": 4624,
"sha256": "a6ef0e5f27f39d2dd9e91472f9b28588a60f8a434780af7109a053f6a9523107"
},
{
"path": "terminal/mermaid-LICENSE.txt",
"size": 1089,
"sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80"
},
{
"path": "terminal/mermaid.js",
"size": 5537838,
"sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3"
},
{
"path": "terminal/terminal.js",
"size": 4375,
"sha256": "7a31fe8679b7942775c7a9a3e34e836744111b7337e750d6ec7b21188dc4cd61"
"size": 4478,
"sha256": "0f3edde02b30e7b0f76d0cc88daae5791d720a4b74cf8b34e7c0b4dbe0cf9c9d"
},
{
"path": "terminal/xterm-LICENSE.txt",
@@ -69,8 +99,8 @@
},
{
"path": "json-LICENSE.txt",
"size": 1075,
"sha256": "c0d068392ea65358b798b8c165103560f06e9e3b38c4ab4e2d8810a7b931af86"
"size": 1096,
"sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831"
},
{
"path": "files-text-license.txt",
@@ -89,13 +119,13 @@
},
{
"path": "dictionaries/en.txt",
"size": 682867,
"sha256": "5f267c141c3d6837870e1c098f86b89a113ba300343119432644ead88f720c21"
"size": 732485,
"sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9"
},
{
"path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt",
"size": 20138,
"sha256": "28a9529c7d0bb4dc51f4bf5c116a3d16ef247a052f7591466768ddf563fd1cf5"
"size": 20566,
"sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5"
},
{
"path": "dictionaries/README.md",
@@ -104,8 +134,8 @@
},
{
"path": "dictionaries/ru.txt",
"size": 1060364,
"sha256": "9ef922c7699569304a428f6aba0fd13a21341c0d0cb9561f37ef83c41577a28b"
"size": 1109134,
"sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849"
},
{
"path": "dictionaries/sources.json",
@@ -124,8 +154,8 @@
},
{
"path": "tools/StayHere.exe",
"size": 133120,
"sha256": "a67a06d20b280c55f02f70b9aae3a967e510bb21d3e1430ef080d628b9e1a484"
"size": 134656,
"sha256": "6ef5cf64708d62b7fc63c3c793cc99188a513433ff4774cae01dc014f6664376"
},
{
"path": "tools/StayHere-README.md",
+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,92,0
PRODUCTVERSION 0,6,92,0
FILEVERSION 0,6,94,0
PRODUCTVERSION 0,6,94,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.92"
VALUE "FileVersion", "0.6.94"
END
END
BLOCK "VarFileInfo"
+29
View File
@@ -0,0 +1,29 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'">
<title>Markdown preview</title>
<style>
:root { color-scheme: light dark; font: 16px/1.55 system-ui, sans-serif; }
body { max-width: 960px; margin: auto; padding: 20px 28px; overflow-wrap: anywhere; }
h1, h2 { border-bottom: 1px solid GrayText; padding-bottom: .25em; }
a { color: LinkText; }
pre, table, figure { overflow: auto; }
pre, code { background: color-mix(in srgb, CanvasText 8%, Canvas); border-radius: 4px; }
pre { padding: .75em; }
code { padding: .1em .25em; }
pre code { padding: 0; background: none; }
blockquote { margin-left: 0; padding-left: 1em; border-left: 3px solid GrayText; }
table { display: block; border-collapse: collapse; }
th, td { border: 1px solid GrayText; padding: .3em .65em; }
img, svg { max-width: 100%; height: auto; }
figure { margin: 1em 0; }
.task { list-style: none; }
.task input { margin-inline: -1.15em .4em; cursor: pointer; }
</style>
<main></main>
<script src="markdown-it.js"></script>
<script src="mermaid.js"></script>
<script src="markdown.js"></script>
</html>
+112
View File
@@ -0,0 +1,112 @@
'use strict';
const bridge = window.chrome.webview;
const content = document.querySelector('main');
const markdown = markdownit({ html: false, linkify: true });
let generation = 0;
let images = [];
mermaid.initialize({
startOnLoad: false,
securityLevel: 'strict',
theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default',
suppressErrorRendering: true,
flowchart: { htmlLabels: false }
});
markdown.core.ruler.after('inline', 'task_lists', ({ tokens }) => {
for (let i = 2; i < tokens.length; ++i) {
const token = tokens[i];
if (token.type !== 'inline' || tokens[i - 1].type !== 'paragraph_open' ||
tokens[i - 2].type !== 'list_item_open') continue;
const text = token.children[0];
const marker = text?.type === 'text' && /^\[([ xX])\][ \t]+/.exec(text.content);
if (!marker) continue;
text.content = text.content.slice(marker[0].length);
const box = new text.constructor('task_checkbox', '', 0);
box.checked = marker[1] !== ' ';
box.content = token.content.slice(marker[0].length);
token.children.unshift(box);
tokens[i - 2].attrJoin('class', 'task');
}
});
markdown.renderer.rules.task_checkbox = (tokens, i) =>
'<input type="checkbox" aria-label="' + markdown.utils.escapeHtml(tokens[i].content) + '"' +
(tokens[i].checked ? ' checked' : '') + '>';
markdown.renderer.rules.image = (tokens, i) => {
const token = tokens[i];
const alt = markdown.renderer.renderInlineAsText(token.children, markdown.options, {});
const escape = markdown.utils.escapeHtml;
return '<img alt="' + escape(alt) + '" data-path="' + escape(token.attrGet('src')) + '">';
};
function send(action, options = {}) {
bridge.postMessage(JSON.stringify({ action, ...options }));
}
function scrollToHeading(fragment) {
try { document.getElementById(decodeURIComponent(fragment))?.scrollIntoView(); } catch {}
}
async function render(text, fragment) {
const current = ++generation;
content.innerHTML = markdown.render(text);
const headings = new Set();
for (const heading of content.querySelectorAll('h1,h2,h3,h4,h5,h6')) {
const base = heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
let id = base;
for (let n = 1; headings.has(id); ++n) id = base + '-' + n;
heading.id = id;
headings.add(id);
}
images = Array.from(content.querySelectorAll('img[data-path]'));
images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current }));
const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid'));
for (const [index, block] of blocks.entries()) {
try {
const { svg } = await mermaid.render('diagram-' + current + '-' + index, block.textContent);
if (current !== generation) return;
const figure = document.createElement('figure');
figure.innerHTML = svg;
block.parentElement.replaceWith(figure);
} catch {
if (current !== generation) return;
const caption = document.createElement('div');
caption.textContent = 'Invalid Mermaid diagram';
block.parentElement.before(caption);
}
}
if (fragment) scrollToHeading(fragment);
}
content.addEventListener('click', event => {
const link = event.target.closest('a');
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 });
}
});
document.addEventListener('keydown', event => {
if (event.key === 'F6' || event.key === 'Escape' || event.key === 'F10') {
event.preventDefault();
send(event.key === 'F6' ? 'edit' : 'close');
}
});
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 === 'image' && message.generation === generation && images[message.index]) {
const image = images[message.index];
if (message.source) image.src = message.source;
else image.title = 'Image unavailable';
}
});
bridge.postMessage('ready');
+3
View File
@@ -64,6 +64,9 @@ terminal.attachCustomKeyEventHandler(event => {
else if (event.key === 'Insert') {
if (!event.repeat) bridge.postMessage('copy-panel-names');
}
else if (event.code === 'KeyR') {
if (!event.repeat) bridge.postMessage('refresh-panel');
}
else return true;
event.preventDefault();
return false;
+1 -1
View File
@@ -12,7 +12,7 @@ bool validHistoryKeys(const std::array<WORD,2> &keys)
const bool function=key>=VK_F1 && key<=VK_F12;
if(!letter && !function) return false;
if(modifiers==HOTKEYF_CONTROL)
return (letter && key!='C' && key!='F' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y') || function;
return (letter && key!='C' && key!='F' && key!='R' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y') || function;
if(modifiers==HOTKEYF_ALT) return function && key!=VK_F1 && key!=VK_F2 && key!=VK_F4 && key!=VK_F10;
return false;
});
+21 -10
View File
@@ -889,10 +889,14 @@ void layout(HWND window)
ShowWindow(terminalOutput,showOutput?SW_SHOWNA:SW_HIDE);
ShowWindow(status,terminalVisible?SW_HIDE:SW_SHOWNA);
terminalView.layout(terminalOutput,showOutput,terminalBottom-4);
constexpr int refreshExtra=4;
for (int i = 0; i < static_cast<int>(std::size(commands)); ++i)
{
const int count=static_cast<int>(std::size(commands));
place(commands[i],i*width/count,height-textHeight,(i+1)*width/count-i*width/count,textHeight);
constexpr int unit=10;
const int total=static_cast<int>(std::size(commands))*unit+refreshExtra;
const int left=i?(i*unit+refreshExtra)*width/total:0;
const int right=((i+1)*unit+refreshExtra)*width/total;
place(commands[i],left,height-textHeight,right-left,textHeight);
}
if(IsWindowVisible(panelSearchPopup)) placePanelSearch(window);
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
@@ -977,6 +981,14 @@ void copyPanelNames(HWND owner)
catch(const std::exception &) { setStatus(L"Could not copy file names."); }
}
void refreshPanel(Panel &panel)
{
panel.folderSizeStop.request_stop();
panel.folderSizeQuery={};
panel.folderSizes.clear();
open(panel,panel.directory,false);
}
std::wstring powerShellPath(const fs::path &path)
{
std::wstring quoted=L"'";
@@ -1059,6 +1071,7 @@ bool ensureTerminalView(HWND owner)
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"refresh-panel") refreshPanel(panels[active]);
else if(message==L"toggle") showTerminal(owner,!terminalVisible);
else if(!terminalVisible && (message==L"grow" || message==L"shrink"))
{
@@ -4425,11 +4438,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
if (wp == VK_RETURN) { enter(panels[index]); return 0; }
if (wp == VK_F2)
{
auto &panel=panels[index];
panel.folderSizeStop.request_stop();
panel.folderSizeQuery={};
panel.folderSizes.clear();
open(panel,panel.directory);
refreshPanel(panels[index]);
return 0;
}
if (wp == VK_F10) { SendMessageW(GetParent(window), WM_CLOSE, 0, 0); return 0; }
@@ -4526,7 +4535,7 @@ void openMenu(HWND window, int index)
else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10"};
else if(index==2)
{
rows={L"Refresh\tF2",L"View\tF3",L"Edit\tF4",L"Folder shortcuts",
rows={L"Refresh panel\tCtrl+R",L"View\tF3",L"Edit\tF4",L"Folder shortcuts",
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4"};
if(panels[active].peer)
{
@@ -4820,7 +4829,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
SetTimer(window,directoryWatchTimer,200,nullptr);
if (!mono || !blue || !teal || !menuBar || !picker || !pickerFrame || !status || !panelSearchPopup) return -1;
SendMessageW(status, WM_SETFONT, reinterpret_cast<WPARAM>(mono), FALSE);
const wchar_t *labels[]{L"F2 Refresh", L"F3 View", L"F4 Edit", L"F5 Copy", L"F6 Move", L"F7 Mkdir", L"F10 Exit"};
const wchar_t *labels[]{L"Ctrl+R Refresh", L"F3 View", L"F4 Edit", L"F5 Copy", L"F6 Move", L"F7 Mkdir", L"F10 Exit"};
for (int i = 0; i < static_cast<int>(std::size(commands)); ++i)
commands[i] = CreateWindowW(L"BUTTON", labels[i], WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
0, 0, 0, 0, window, reinterpret_cast<HMENU>(110 + static_cast<INT_PTR>(i)), instance, nullptr);
@@ -5484,11 +5493,13 @@ 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 || message.wParam==VK_INSERT))
(message.wParam=='F' || message.wParam=='C' || message.wParam=='R' ||
message.wParam==VK_RETURN || message.wParam==VK_INSERT))
{
if(!(message.lParam & (1LL<<30)))
{
if(message.wParam=='F') insertCurrentPanelPath();
else if(message.wParam=='R') refreshPanel(panels[active]);
else if(message.wParam==VK_RETURN) insertCurrentPanelPath(true);
else if(message.wParam==VK_INSERT) copyPanelNames(window);
else SendMessageW(terminalInput,WM_COPY,0,0);
+61 -21
View File
@@ -8,8 +8,10 @@ __CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler, 0x6c4
__CRT_UUID_DECL(ICoreWebView2WebMessageReceivedEventHandler, 0x57213f19, 0x00e6, 0x49fa, 0x8e, 0x07, 0x89, 0x8e, 0xa0, 0x1e, 0xcb, 0xd2)
__CRT_UUID_DECL(ICoreWebView2NewWindowRequestedEventHandler, 0xd4c185fe, 0xc81c, 0x4989, 0x97, 0xaf, 0x2d, 0x3f, 0xa7, 0xab, 0x56, 0x51)
__CRT_UUID_DECL(ICoreWebView2NavigationStartingEventHandler, 0x9adbe429, 0xf36d, 0x432b, 0x9d, 0xdc, 0xf8, 0x88, 0x1f, 0xbd, 0x76, 0xe3)
__CRT_UUID_DECL(ICoreWebView2AcceleratorKeyPressedEventHandler, 0xb29c7e28, 0xfa79, 0x41a8, 0x8e, 0x44, 0x65, 0x81, 0x1c, 0x76, 0xdc, 0xb2)
#endif
#include <wrl/client.h>
#include <filesystem>
#include <functional>
#include <memory>
#include <utility>
@@ -50,11 +52,20 @@ class FilesTerminalView
{
Microsoft::WRL::ComPtr<ICoreWebView2Controller> controller;
Microsoft::WRL::ComPtr<ICoreWebView2> web;
HMODULE loader{};
std::shared_ptr<int> lifetime;
RECT bounds{};
bool ready{};
bool visible{};
int viewportHeight{};
public:
~FilesTerminalView() { close(); }
void focus()
{
if(controller) controller->MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC);
}
void post(const std::wstring &message)
{
if(ready) web->PostWebMessageAsString(message.c_str());
}
bool initialized() const { return ready; }
void enableTrace(bool output)
{
@@ -70,12 +81,16 @@ public:
}
void layout(HWND host,bool show,int fullHeight)
{
RECT area{};
GetClientRect(host,&area);
area.top=area.bottom-fullHeight;
layout(area,show);
}
void layout(RECT area,bool show)
{
bounds=area;
visible=show;
viewportHeight=fullHeight;
if(!controller) return;
RECT bounds{};
GetClientRect(host,&bounds);
bounds.top=bounds.bottom-viewportHeight;
RECT current{};
if(FAILED(controller->get_Bounds(&current)) || !EqualRect(&current,&bounds))
controller->put_Bounds(bounds);
@@ -85,6 +100,7 @@ public:
}
void close()
{
lifetime.reset();
if(controller) controller->Close();
web.Reset();
controller.Reset();
@@ -103,12 +119,13 @@ public:
}
return SUCCEEDED(web->PostWebMessageAsString(message.c_str()));
}
bool create(HWND host,std::function<void(const std::wstring&)> receive,std::function<void()> failed)
bool create(HWND host,std::function<void(const std::wstring&)> receive,std::function<void()> failed,
bool markdown=false,std::function<bool(UINT)> handleKey={})
{
wchar_t exe[MAX_PATH]{};
if(!GetModuleFileNameW(nullptr,exe,MAX_PATH)) return false;
const auto folder=std::filesystem::path(exe).parent_path();
loader=LoadLibraryExW((folder/L"WebView2Loader.dll").c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32);
static const auto loader=LoadLibraryExW((folder/L"WebView2Loader.dll").c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32);
if(!loader) return false;
using Create=HRESULT (STDAPICALLTYPE*)(PCWSTR,PCWSTR,ICoreWebView2EnvironmentOptions*,
ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*);
@@ -118,23 +135,28 @@ public:
wchar_t local[MAX_PATH]{};
const auto length=GetEnvironmentVariableW(L"LOCALAPPDATA",local,MAX_PATH);
if(!length || length>=MAX_PATH) return false;
const auto profile=std::filesystem::path(local)/L"KSwitcher"/L"TerminalWebView";
const auto profile=std::filesystem::path(local)/L"KSwitcher"/(markdown?L"MarkdownWebView":L"TerminalWebView");
const auto origin=markdown?L"kswitcher-markdown.invalid":L"kswitcher-terminal.invalid";
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":L"/index.html");
const auto assets=folder/L"terminal";
if(markdown && !std::filesystem::exists(assets/L"markdown.html")) return false;
lifetime=std::make_shared<int>(0);
const std::weak_ptr<int> alive=lifetime;
auto environment=terminalCallback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler,
HRESULT,ICoreWebView2Environment*>([=,this](HRESULT hr,ICoreWebView2Environment *env)
{
if(!IsWindow(host)) return S_OK;
if(alive.expired()) return S_OK;
if(FAILED(hr) || !env) { failed(); return S_OK; }
auto completed=terminalCallback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler,
HRESULT,ICoreWebView2Controller*>([=,this](HRESULT result,ICoreWebView2Controller *view)
{
if(!IsWindow(host)) return S_OK;
if(alive.expired()) return S_OK;
if(FAILED(result) || !view) { failed(); return S_OK; }
controller=view;
view->get_CoreWebView2(&web);
Microsoft::WRL::ComPtr<ICoreWebView2_3> mapped;
if(!web || FAILED(web.As(&mapped)) || FAILED(mapped->SetVirtualHostNameToFolderMapping(
L"kswitcher-terminal.invalid",assets.c_str(),COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_DENY)))
origin,assets.c_str(),COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_DENY)))
{ failed(); return S_OK; }
Microsoft::WRL::ComPtr<ICoreWebView2Settings> settings;
if(SUCCEEDED(web->get_Settings(&settings)))
@@ -144,14 +166,31 @@ public:
settings->put_AreHostObjectsAllowed(FALSE);
}
EventRegistrationToken token{};
auto navigation=terminalCallback<ICoreWebView2NavigationStartingEventHandler,
ICoreWebView2*,ICoreWebView2NavigationStartingEventArgs*>([](auto*,auto *args)
if(handleKey)
{
PWSTR uri{};
if(SUCCEEDED(args->get_Uri(&uri)))
auto accelerator=terminalCallback<ICoreWebView2AcceleratorKeyPressedEventHandler,
ICoreWebView2Controller*,ICoreWebView2AcceleratorKeyPressedEventArgs*>(
[alive,handleKey](auto*,auto *args)
{
COREWEBVIEW2_KEY_EVENT_KIND kind{};
UINT key{};
if(!alive.expired() && SUCCEEDED(args->get_KeyEventKind(&kind)) &&
kind==COREWEBVIEW2_KEY_EVENT_KIND_KEY_DOWN &&
SUCCEEDED(args->get_VirtualKey(&key)) && handleKey(key))
args->put_Handled(TRUE);
return S_OK;
});
if(FAILED(view->add_AcceleratorKeyPressed(accelerator.Get(),&token)))
{ failed(); return S_OK; }
}
auto navigation=terminalCallback<ICoreWebView2NavigationStartingEventHandler,
ICoreWebView2*,ICoreWebView2NavigationStartingEventArgs*>([uri](auto*,auto *args)
{
PWSTR address{};
if(SUCCEEDED(args->get_Uri(&address)))
{
args->put_Cancel(wcscmp(uri,L"https://kswitcher-terminal.invalid/index.html")!=0);
CoTaskMemFree(uri);
args->put_Cancel(uri!=address);
CoTaskMemFree(address);
}
return S_OK;
});
@@ -161,9 +200,10 @@ public:
auto messages=terminalCallback<ICoreWebView2WebMessageReceivedEventHandler,
ICoreWebView2*,ICoreWebView2WebMessageReceivedEventArgs*>([=,this](auto*,auto *args)
{
if(alive.expired()) return S_OK;
PWSTR source{}, value{};
if(SUCCEEDED(args->get_Source(&source)) &&
wcscmp(source,L"https://kswitcher-terminal.invalid/index.html")==0 &&
uri==source &&
SUCCEEDED(args->TryGetWebMessageAsString(&value)))
{
if(wcscmp(value,L"ready")==0) ready=true;
@@ -176,9 +216,9 @@ public:
if(FAILED(web->add_NavigationStarting(navigation.Get(),&token)) ||
FAILED(web->add_NewWindowRequested(newWindow.Get(),&token)) ||
FAILED(web->add_WebMessageReceived(messages.Get(),&token)) ||
FAILED(web->Navigate(L"https://kswitcher-terminal.invalid/index.html")))
FAILED(web->Navigate(uri.c_str())))
failed();
layout(host,visible,viewportHeight);
layout(bounds,visible);
return S_OK;
});
if(FAILED(env->CreateCoreWebView2Controller(host,completed.Get()))) failed();
+324 -11
View File
@@ -4,6 +4,7 @@
#include "files_history_date.h"
#include "files_text_document.h"
#include "files_text_language.h"
#include "files_terminal_view.h"
#include "platform.h"
#include "lan_files.h"
@@ -14,6 +15,7 @@
#include <atomic>
#include <windowsx.h>
#include <commdlg.h>
#include <wincrypt.h>
#include <Scintilla.h>
#include <ILexer.h>
#include <Lexilla.h>
@@ -26,6 +28,8 @@
#include <cwctype>
#include <deque>
#include <future>
#include <fstream>
#include <thread>
#include <map>
#include <stdexcept>
#include <string_view>
@@ -181,7 +185,7 @@ void drawMenuTitle(HDC dc, RECT bounds, const MenuLabel &label, COLORREF accessI
enum Command : UINT
{
save = 1, close, findText, findNext, previousPage, nextPage, firstPage, lastPage, goToPage,
undo, redo, cut, copy, paste, selectAll, lexerAuto, lexerPlain, options,
undo, redo, cut, copy, paste, selectAll, lexerAuto, lexerPlain, options, switchMode,
lexerStart = 1000,
};
@@ -558,6 +562,7 @@ struct RemoteTextFile
lan::FilesPeer peer;
std::filesystem::path original,cache;
lan::FileRevision revision{};
bool editable{};
~RemoteTextFile()
{
@@ -574,7 +579,7 @@ struct RemoteTextFile
return {reply.at("size").get<uint64_t>(),reply.at("modified").get<uint64_t>()};
}
void download(bool edit,const lan::FileProgress &progress)
void download(bool edit,const lan::FileProgress &progress,uint64_t sizeLimit=UINT64_MAX)
{
GUID id{};
wchar_t name[40]{};
@@ -587,11 +592,14 @@ struct RemoteTextFile
lan::FilesConnection source(&peer),target;
const auto info=source.call(lan::fileRequest("stat",original));
lan::checkFileReply(info);
editable=info.value("editCommit",false) &&
!(info.at("attributes").get<DWORD>()&FILE_ATTRIBUTE_READONLY);
if(edit && !info.value("editCommit",false))
throw std::runtime_error("Update KSwitcher on the remote computer to edit this file.");
if(edit && (info.at("attributes").get<DWORD>()&FILE_ATTRIBUTE_READONLY))
throw std::runtime_error("The remote file is read-only.");
revision={info.at("size"),info.at("modified")};
if(revision.size>sizeLimit) throw std::runtime_error("The image is too large to preview.");
try
{
lan::streamFile(source,target,peer.id,original,cache,revision.size,revision.modified,false,false,progress);
@@ -628,12 +636,76 @@ std::wstring documentIdentity(const std::filesystem::path &path,std::string_view
return wide(std::string(peer))+L"\n"+path.native();
}
std::filesystem::path markdownTarget(const std::filesystem::path &document,std::string_view url)
{
url=url.substr(0,url.find_first_of("?#"));
std::string decoded;
const auto hex=[](char c) {
if(c>='0' && c<='9') return c-'0';
if(c>='a' && c<='f') return c-'a'+10;
if(c>='A' && c<='F') return c-'A'+10;
return -1;
};
for(size_t i=0;i<url.size();++i)
{
if(url[i]!='%') { decoded+=url[i]; continue; }
if(i+2>=url.size()) return {};
const auto high=hex(url[i+1]), low=hex(url[i+2]);
if(high<0 || low<0) return {};
decoded+=static_cast<char>(16*high+low);
i+=2;
}
if(decoded.empty() || decoded.find_first_of(":\0",0,2)!=decoded.npos) return {};
const std::filesystem::path relative(wide(decoded));
if(relative.has_root_path()) return {};
return (document.parent_path()/relative).lexically_normal();
}
std::string markdownImage(const std::filesystem::path &path,const lan::FilesPeer *peer,
const std::shared_ptr<std::atomic<bool>> &cancel)
{
auto extension=path.extension().wstring();
std::transform(extension.begin(),extension.end(),extension.begin(),::towlower);
const std::map<std::wstring,std::string> types{
{L".png","png"},{L".jpg","jpeg"},{L".jpeg","jpeg"},{L".gif","gif"},
{L".webp","webp"},{L".bmp","bmp"},{L".svg","svg+xml"},{L".avif","avif"}
};
const auto type=types.find(extension);
if(type==types.end()) return {};
constexpr uint64_t limit=16*1024*1024;
auto source=path;
std::optional<RemoteTextFile> fetched;
if(peer)
{
if(*cancel) return {};
fetched.emplace(RemoteTextFile{*peer,path});
fetched->download(false,[&](uint64_t,uint64_t){return !*cancel;},limit);
source=fetched->cache;
}
if(*cancel) return {};
std::ifstream input(source,std::ios::binary|std::ios::ate);
const auto size=input.tellg();
if(size<=0 || static_cast<uint64_t>(size)>limit) return {};
std::string bytes(static_cast<size_t>(size),'\0');
if(!input.seekg(0).read(bytes.data(),bytes.size())) return {};
constexpr auto flags=CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF;
DWORD length{};
const auto data=reinterpret_cast<const BYTE *>(bytes.data());
if(!CryptBinaryToStringA(data,static_cast<DWORD>(bytes.size()),flags,nullptr,&length)) return {};
std::string encoded(length,'\0');
if(!CryptBinaryToStringA(data,static_cast<DWORD>(bytes.size()),flags,encoded.data(),&length)) return {};
encoded.resize(length);
return "data:image/"+type->second+";base64,"+encoded;
}
class TextWindow
{
public:
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const lan::FilesPeer *peer)
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const lan::FilesPeer *peer,
std::string_view fragment)
: original(std::move(path)), peerId(peer?peer->id:""), filename(original.filename().wstring()),
edit(editable), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()), search{dialogs}
edit(editable), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
search{dialogs}, previewFragment(fragment)
{
if (peer) remote=std::make_unique<RemoteTextFile>(RemoteTextFile{*peer,original});
else document=std::make_unique<TextDocument>(original,edit);
@@ -651,6 +723,7 @@ public:
static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM wparam, LPARAM lparam);
HWND window{}, editor{};
bool handleKey(const MSG &message);
void goToFragment(std::string_view fragment);
const std::filesystem::path original;
const std::string peerId;
@@ -678,12 +751,35 @@ private:
int pageEol = SC_EOL_CRLF;
size_t undoBytes{};
bool uploadPending{};
bool switchAfterSave{};
FilesTerminalView preview;
bool previewWanted{}, previewVisible{};
ULONGLONG previewDeadline{};
std::string previewFragment;
struct PreviewLink
{
std::filesystem::path path;
std::string fragment;
};
std::deque<PreviewLink> previewLinks;
struct ImageRequest
{
std::filesystem::path path;
uint64_t index{}, generation{};
};
std::deque<ImageRequest> imageQueue;
std::future<std::string> image;
ImageRequest activeImage;
std::shared_ptr<std::atomic<bool>> cancelImages;
std::atomic<bool> cancelOpen{};
std::future<void> opening;
std::future<bool> saving;
static constexpr UINT_PTR saveTimer = 1;
static constexpr UINT_PTR openTimer = 2;
static constexpr UINT_PTR previewTimer = 3;
static constexpr UINT trimUndo = WM_APP + 1;
static constexpr UINT previewFailed = WM_APP + 2;
static constexpr UINT openPreviewLink = WM_APP + 3;
LRESULT send(UINT message, WPARAM wparam = 0, LPARAM lparam = 0) const
{
@@ -725,6 +821,14 @@ private:
void saveFile(bool closeWhenDone);
void finishSave();
void requestClose();
void toggleMode();
void changeMode();
bool needsSave() const;
void updatePreview();
void stopPreview();
void previewMessage(const std::wstring &value);
void pollImages();
void focusContent();
void layout();
void paint();
void command(UINT id);
@@ -750,6 +854,7 @@ void TextWindow::createMenu()
const auto menu = CreateMenu();
const auto file = addGroup(menu, L"&File");
if (edit) addItem(file, save, L"&Save\tF2");
addItem(file, switchMode, edit ? L"&View\tF6" : L"&Edit\tF6");
addItem(file, close, L"&Close\tF10");
const auto actions = addGroup(menu, edit ? L"&Edit" : L"&Selection");
if (edit)
@@ -1128,6 +1233,7 @@ void TextWindow::initializeDocument()
createMenu();
installLexer();
loadPage(0);
updatePreview();
}
void TextWindow::finishOpen()
@@ -1156,6 +1262,7 @@ void TextWindow::saveFile(bool closeWhenDone)
if (!stagedDirty && !uploadPending)
{
if (closeWhenDone) DestroyWindow(window);
else if (std::exchange(switchAfterSave, false)) changeMode();
return;
}
pendingCaret = send(SCI_GETCURRENTPOS);
@@ -1190,6 +1297,7 @@ void TextWindow::finishSave()
if (!busy() || saving.wait_for(std::chrono::milliseconds(0)) != std::future_status::ready) return;
KillTimer(window, saveTimer);
send(SCI_SETREADONLY, !edit);
const auto change = std::exchange(switchAfterSave, false);
const auto reopened = saving.get();
stagedDirty = false;
if (!reopened)
@@ -1199,6 +1307,7 @@ void TextWindow::finishSave()
return;
}
if (closeAfterSave) { DestroyWindow(window); return; }
if (change) { changeMode(); return; }
if (pageTotal == 1 && document->pages() == 1)
{
fileSize = document->size();
@@ -1213,7 +1322,7 @@ void TextWindow::requestClose()
{
if (opening.valid()) { cancelOpen=true; return; }
if (busy()) return;
if (uploadPending || (currentChanged() ? document->modifiedWith(page, pageText()) : stagedDirty))
if (needsSave())
{
const auto answer = search.style.confirmSave(window);
if (answer == IDCANCEL) return;
@@ -1223,6 +1332,191 @@ void TextWindow::requestClose()
DestroyWindow(window);
}
bool TextWindow::needsSave() const
{
return uploadPending || (currentChanged() ? document->modifiedWith(page, pageText()) : stagedDirty);
}
void TextWindow::toggleMode()
{
if (edit && needsSave())
{
const auto answer = search.style.confirmSave(window);
if (answer == IDYES)
{
switchAfterSave = true;
try { saveFile(false); }
catch (...) { switchAfterSave = false; throw; }
return;
}
if (answer != IDNO) return;
// The local LAN cache may already contain changes from a failed upload.
if (uploadPending)
{
auto refreshed = std::make_unique<RemoteTextFile>(RemoteTextFile{remote->peer,original});
refreshed->download(false,{});
auto replacement = std::make_unique<TextDocument>(refreshed->cache,false);
document.reset();
remote = std::move(refreshed);
document = std::move(replacement);
uploadPending = false;
}
}
changeMode();
}
void TextWindow::changeMode()
{
if (!edit && remote && !remote->editable)
throw std::runtime_error("The remote file does not support editing.");
auto replacement = std::make_unique<TextDocument>(remote ? remote->cache : original, !edit);
const auto caret = send(SCI_GETCURRENTPOS);
document = std::move(replacement);
edit = !edit;
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());
updatePreview();
layout();
focusContent();
}
void TextWindow::updatePreview()
{
if(edit || automatic.lexer!="markdown" || fileSize>TextDocument::editLimit)
{
stopPreview();
return;
}
previewWanted=true;
previewDeadline=GetTickCount64()+8000;
cancelImages=std::make_shared<std::atomic<bool>>(false);
if(!SetTimer(window,previewTimer,50,nullptr) ||
!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;
PostMessageW(window,WM_COMMAND,key==VK_F6?switchMode:close,0);
return true;
}))
stopPreview();
}
void TextWindow::stopPreview()
{
KillTimer(window,previewTimer);
previewWanted=previewVisible=false;
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);
}
void TextWindow::goToFragment(std::string_view fragment)
{
if(fragment.empty()) return;
if(previewVisible)
preview.post(wide(nlohmann::json{{"action","anchor"},{"fragment",fragment}}.dump()));
else previewFragment=fragment;
}
void TextWindow::previewMessage(const std::wstring &value)
{
if(!previewWanted) return;
try
{
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();
return;
}
const auto message=nlohmann::json::parse(utf8(value));
const auto action=message.at("action").get<std::string>();
// 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!="image" && action!="link") return;
const auto url=message.at("path").get<std::string>();
if(action=="link" && (url.starts_with("https://") || url.starts_with("http://")))
{
ShellExecuteW(window,L"open",wide(url).c_str(),nullptr,nullptr,SW_SHOWNORMAL);
return;
}
const auto target=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)});
PostMessageW(window,openPreviewLink,0,0);
}
}
else if(imageQueue.size()<256)
{
imageQueue.push_back({target,message.at("index").get<uint64_t>(),message.at("generation").get<uint64_t>()});
}
}
catch(const std::exception &error)
{
if(!previewVisible) PostMessageW(window,previewFailed,0,0);
else log(L"Markdown preview message: "+wide(error.what()));
}
}
void TextWindow::pollImages()
{
if(!previewVisible && GetTickCount64()>=previewDeadline)
{
stopPreview();
return;
}
if(image.valid())
{
if(image.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
std::string source;
try { source=image.get(); } catch(const std::exception &) {}
const nlohmann::json message{{"action","image"},{"index",activeImage.index},
{"generation",activeImage.generation},{"source",std::move(source)}};
preview.post(wide(message.dump()));
}
if(imageQueue.empty()) return;
activeImage=std::move(imageQueue.front());
imageQueue.pop_front();
std::packaged_task<std::string()> task(
[path=activeImage.path,peer=remote?std::optional(remote->peer):std::nullopt,cancel=cancelImages] {
return markdownImage(path,peer?&*peer:nullptr,cancel);
});
image=task.get_future();
std::thread(std::move(task)).detach();
}
void TextWindow::layout()
{
if (!editor) return;
@@ -1230,6 +1524,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);
invalidate();
}
@@ -1288,8 +1584,9 @@ void TextWindow::paint()
L" @ " + std::to_wstring(pageOffset);
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 Ctrl+PgUp/PgDn Pages F10 Close" :
L"F3 Find next F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close";
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" :
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);
top.right -= scale(12);
@@ -1348,6 +1645,7 @@ void TextWindow::command(UINT id)
{
case save: saveFile(false); return;
case close: requestClose(); return;
case switchMode: toggleMode(); return;
case previousPage: if (page) go(page - 1); return;
case nextPage: go(page + 1); return;
case firstPage: go(0); return;
@@ -1457,6 +1755,7 @@ bool TextWindow::handleKey(const MSG &message)
if (key == VK_F2 || (ctrl && key == 'S')) id = save;
if (key == VK_F3) id = findNext;
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 (ctrl && key == 'F') id = findText;
@@ -1546,7 +1845,17 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
self->layout();
return 0;
}
case WM_SETFOCUS: SetFocus(self->editor); return 0;
case WM_SETFOCUS: self->focusContent(); return 0;
case previewFailed: self->stopPreview(); 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);
}
return 0;
case WM_INITMENU: self->updateMenus(); return 0;
case WM_MENUCHAR: return self->menuKey(reinterpret_cast<HMENU>(lparam), LOWORD(wparam));
case WM_MEASUREITEM:
@@ -1576,6 +1885,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
case WM_TIMER:
if (wparam == saveTimer) self->finishSave();
if (wparam == openTimer) self->finishOpen();
if (wparam == previewTimer) self->pollImages();
return 0;
case trimUndo:
if (self->undoBytes >= 32 * TextDocument::pageBytes)
@@ -1587,6 +1897,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
}
return 0;
case WM_DESTROY:
self->stopPreview();
self->releaseMenu();
return 0;
case WM_NCDESTROY:
@@ -1738,7 +2049,7 @@ 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)
const lan::FilesPeer *peer,std::string_view fragment)
{
try
{
@@ -1751,6 +2062,8 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
{
if(IsIconic(existing)) ShowWindowAsync(existing,SW_RESTORE);
SetForegroundWindow(existing);
if(const auto open=textWindows.find(existing); open!=textWindows.end())
open->second->goToFragment(fragment);
}
return;
}
@@ -1767,7 +2080,7 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
return Scintilla_RegisterClasses(instance) && RegisterClassW(&type);
}();
if(!registered) throw std::runtime_error("Cannot register the text window.");
auto state=std::make_shared<TextWindow>(original,edit,dialogs,peer);
auto state=std::make_shared<TextWindow>(original,edit,dialogs,peer,fragment);
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
(peer?peer->name+L" · ":std::wstring{})+path.wstring();
RECT bounds{};
@@ -1790,7 +2103,7 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
properties->Release();
}
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
SetFocus(state->editor);
SendMessageW(window,WM_SETFOCUS,0,0);
}
catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());}
}
+2 -1
View File
@@ -2,6 +2,7 @@
#include <windows.h>
#include <filesystem>
#include <string_view>
#include <vector>
namespace ks::lan { struct FilesPeer; }
@@ -51,6 +52,6 @@ struct TextDialogs
};
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer=nullptr);
const lan::FilesPeer *peer=nullptr,std::string_view fragment={});
void textWindowOwnerClosed();
}
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.92";
inline constexpr wchar_t AppVersion[] = L"0.6.94";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+12
View File
@@ -331,6 +331,18 @@ try {
$viewer=[FilesActivationUi]::FindWindowEx([IntPtr]::Zero,[IntPtr]::Zero,'KSwitcher.Files.Text',$viewerTitle)
[void][FilesActivationUi]::PostMessage($viewer,0x10,[IntPtr]::Zero,[IntPtr]::Zero)
Write-Output 'F3 measured the current folder recursively and measured marked folders without measuring the unmarked cursor folder.'
Select-Row $right '[Size B]'
Wait-Until 'Files activation for Ctrl+R' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
$shell.SendKeys('^r')
Wait-Until 'Ctrl+R clearing the measured size and retaining the current folder' {
(Read-Text $status) -ceq 'Size B Folder' -and
[FilesActivationUi]::Send($right,0x188,[IntPtr]::Zero,[IntPtr]::Zero).ToInt32() -eq
(Find-Row $right '[Size B]')
}
Write-Output 'Ctrl+R refreshed the active pane and kept its cursor.'
} finally {
if ($process -and !$process.HasExited) {
[void]$process.CloseMainWindow()
+298
View File
@@ -0,0 +1,298 @@
param(
[Parameter(Mandatory)][string]$Executable,
[string]$Screenshot,
[string]$Node = 'node',
[string]$LanFixture
)
$ErrorActionPreference = 'Stop'
Add-Type @"
using System;
using System.Text;
using System.Runtime.InteropServices;
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 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);
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr SendText(IntPtr window, uint msg, IntPtr w, string l);
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
}
"@
function Wait-For([string]$Name, [scriptblock]$Check) {
for ($i=0; $i -lt 150; $i++) {
$value = & $Check
if ($value) { return $value }
Start-Sleep -Milliseconds 100
}
throw "Timed out waiting for $Name"
}
function Find-Window([string]$Class, [string]$Title = '', [IntPtr]$Except = 0) {
$window = [IntPtr]::Zero
while (($window = [MarkdownUi]::FindWindowEx(0,$window,$Class,[NullString]::Value)) -ne [IntPtr]::Zero) {
[uint32]$pidFound = 0
[void][MarkdownUi]::GetWindowThreadProcessId($window,[ref]$pidFound)
if ($pidFound -ne $process.Id -or $window -eq $Except -or ![MarkdownUi]::IsWindowVisible($window)) { continue }
$buffer = [Text.StringBuilder]::new(2048)
[void][MarkdownUi]::GetWindowText($window,$buffer,$buffer.Capacity)
if ($buffer.ToString() -like "*$Title*") { return $window }
}
}
function Post($Window, $Message, $Key) {
if (![MarkdownUi]::PostMessage($Window,$Message,$Key,0)) { throw 'Could not drive the Files window.' }
}
function Open-File($File, $Key) {
$row = [MarkdownUi]::SendText($panel,0x1A2,-1,$File)
if ($row.ToInt64() -lt 0) { throw "Missing row $File" }
[void][MarkdownUi]::Send($panel,0x186,$row,0)
Post $panel 0x100 $Key
}
function Browser($Scenario, $Image = '') {
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port $Scenario $Image
if ($LASTEXITCODE) { throw "WebView2 verification failed for $Scenario" }
}
function Scintilla($Window) {
[MarkdownUi]::FindWindowEx($Window,0,'Scintilla',[NullString]::Value)
}
function Append-Character($Control, [char]$Character) {
[void][MarkdownUi]::Send($Control,2318,0,0)
[void][MarkdownUi]::Send($Control,0x102,[int]$Character,0)
}
function Answer-Save($Button) {
$dialog = Wait-For 'the save confirmation' {
$candidate = Find-Window '#32770'
if ($candidate -and [MarkdownUi]::GetDlgItem($candidate,7) -ne [IntPtr]::Zero) { $candidate }
}
Post $dialog 0x111 $Button
[void](Wait-For 'the save confirmation to close' { ![MarkdownUi]::IsWindowVisible($dialog) })
}
$source = Split-Path (Resolve-Path -LiteralPath $Executable)
$root = Join-Path ([IO.Path]::GetTempPath()) ('ks-markdown-test-' + [Guid]::NewGuid().ToString('N'))
$app = Join-Path $root 'app'
$docs = Join-Path $root 'docs'
$profileCaptured = $false
$profile = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$saved = @{}
$profileValues = 'LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement'
$process = $null
$flags = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
$data = $env:WEBVIEW2_USER_DATA_FOLDER
try {
New-Item -ItemType Directory -Path $app,$docs,"$docs\child","$docs\images" | Out-Null
Copy-Item -LiteralPath $Executable,"$source\WebView2Loader.dll","$source\terminal" -Destination $app -Recurse
$fixture = @'
# Перегляд Markdown
| Header |
| ------ |
| Cell |
- [ ] Pending
- [x] Complete
![Relative image](images/tiny%20image.png)
![Missing image](images/missing.png)
[Child](child/Other.md#target-heading)
~~~mermaid
flowchart TD
A[Render target] --> B[Result]
~~~
~~~mermaid
this is not a diagram
~~~
~~~js
const value = 42;
~~~
<iframe src="https://example.invalid">Raw HTML</iframe>
'@
$original = Join-Path $docs 'Preview.md'
[IO.File]::WriteAllText($original,$fixture)
$childText = '# Linked Markdown' + "`n`n" + (("Filler paragraph.`n`n") * 60) + '## Target heading'
[IO.File]::WriteAllText("$docs\child\Other.md",$childText)
[IO.File]::WriteAllText("$docs\Plain.txt",'Plain text')
$largeFile = [IO.File]::Create("$docs\Large.md")
try {
$line = [Text.Encoding]::UTF8.GetBytes(("# Large Markdown file`n" * 1024))
while ($largeFile.Length -le 8MB) { $largeFile.Write($line,0,$line.Length) }
} finally { $largeFile.Dispose() }
[IO.File]::WriteAllBytes("$docs\images\tiny image.png",[Convert]::FromBase64String(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jBo0AAAAASUVORK5CYII='))
foreach ($name in $profileValues) {
if ($name -in $profile.GetValueNames()) {
$saved[$name] = @($profile.GetValue($name),$profile.GetValueKind($name))
}
}
$profileCaptured = $true
$profile.SetValue('LeftPath',$docs)
$profile.SetValue('RightPath',$docs)
foreach ($name in 'LeftCursor','RightCursor','WindowPlacement') { $profile.DeleteValue($name,$false) }
$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$listener.Start()
$port = $listener.LocalEndpoint.Port
$listener.Stop()
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = "--remote-debugging-port=$port --disable-background-networking"
$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' }
$panel = [MarkdownUi]::GetDlgItem($main,102)
Open-File 'Preview.md' 0x72
$window = Wait-For 'the Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
Browser 'render' $Screenshot
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Checking a task modified the read-only file.' }
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.' }
$control = Scintilla $window
if ([MarkdownUi]::Send($control,2140,0,0).ToInt64()) { throw 'The editor is read-only.' }
Append-Character $control 'X'
Post $control 0x100 0x75
Answer-Save 2
if ((Find-Window 'KSwitcher.Files.Text' 'Editor') -ne $window -or ![MarkdownUi]::Send($control,2159,0,0).ToInt64()) {
throw 'Cancel lost unsaved changes.'
}
Post $control 0x100 0x75
Answer-Save 7
Browser 'Перегляд Markdown'
if ([IO.File]::ReadAllText($original) -cne $fixture) { throw 'Discard changed the Markdown file.' }
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
[void](Wait-For 'the Markdown viewers to close' { !(Find-Window 'KSwitcher.Files.Text') })
Open-File 'Preview.md' 0x73
$window = Wait-For 'F4 to open the Markdown editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
$control = Scintilla $window
Append-Character $control 'Y'
Post $control 0x100 0x75
Answer-Save 6
Browser 'Перегляд Markdown'
if (![IO.File]::ReadAllText($original).EndsWith('Y')) { throw 'F6 rendered before saving.' }
Post $window 0x10 0
[void](Wait-For 'the saved Markdown viewer to close' { !(Find-Window 'KSwitcher.Files.Text') })
Open-File 'Preview.md' 0x73
$window = Wait-For 'the editor before a save conflict' { Find-Window 'KSwitcher.Files.Text' 'Editor' }
$control = Scintilla $window
Append-Character $control 'Z'
[IO.File]::Move($original,"$docs\replaced.md")
[IO.File]::WriteAllText($original,'An external replacement')
Post $control 0x100 0x75
Answer-Save 6
$errorDialog = Wait-For 'a save conflict error' {
$candidate = Find-Window '#32770'
if ($candidate -and [MarkdownUi]::GetDlgItem($candidate,1) -ne [IntPtr]::Zero) { $candidate }
}
Post $errorDialog 0x111 1
if ((Find-Window 'KSwitcher.Files.Text' 'Editor') -ne $window -or
[MarkdownUi]::Send($control,2140,0,0).ToInt64() -or
[IO.File]::ReadAllText($original) -cne 'An external replacement') {
throw 'The failed save left editing mode or overwrote an externally replaced file.'
}
Post $control 0x100 0x75
Answer-Save 7
Post $window 0x10 0
[void](Wait-For 'the conflict fixture to close' { !(Find-Window 'KSwitcher.Files.Text') })
Open-File 'Plain.txt' 0x72
$window = Wait-For 'plain-text viewer' { Find-Window 'KSwitcher.Files.Text' 'Viewer' }
$control = Scintilla $window
[void](Wait-For 'plain-text read-only view' { [MarkdownUi]::Send($control,2140,0,0).ToInt64() })
Post $control 0x100 0x75
[void](Wait-For 'F6 plain-text editor' { !( [MarkdownUi]::Send($control,2140,0,0).ToInt64() ) })
Post $control 0x100 0x75
[void](Wait-For 'F6 plain-text viewer' { [MarkdownUi]::Send($control,2140,0,0).ToInt64() })
Post $window 0x10 0
[void](Wait-For 'plain-text viewer to close' { !(Find-Window 'KSwitcher.Files.Text') })
Open-File 'Large.md' 0x72
$window = Wait-For 'large Markdown text fallback' { Find-Window 'KSwitcher.Files.Text' 'Large.md' }
$control = Scintilla $window
if (![MarkdownUi]::IsWindowVisible($control) -or ![MarkdownUi]::Send($control,2140,0,0).ToInt64()) {
throw 'Large Markdown did not open in the text viewer.'
}
Post $window 0x10 0
[void](Wait-For 'large-file viewer to close' { !(Find-Window 'KSwitcher.Files.Text') })
$previewPage = Join-Path $app 'terminal\markdown.html'
[IO.File]::Move($previewPage,"$previewPage.disabled")
try {
Open-File 'Preview.md' 0x72
$window = Wait-For 'text fallback without preview assets' { Find-Window 'KSwitcher.Files.Text' 'Preview.md' }
$control = Scintilla $window
if (![MarkdownUi]::IsWindowVisible($control) -or ![MarkdownUi]::Send($control,2140,0,0).ToInt64()) {
throw 'Markdown did not open in the text viewer when preview assets were missing.'
}
} finally { [IO.File]::Move("$previewPage.disabled",$previewPage) }
Write-Output 'Verified Markdown rendering, Mermaid, task checkboxes, local relative resources, F3/F4, F6 Save/Discard/Cancel/save failure and text fallback.'
if ($LanFixture) {
Post $window 0x10 0
Post $main 0x10 0
if (!$process.WaitForExit(5000)) { throw 'Files did not close before the LAN check.' }
[IO.File]::WriteAllText($original,$fixture)
$lanExe = Join-Path $app 'KSwitcherFilesMarkdownLanFixture.exe'
Copy-Item -LiteralPath $LanFixture -Destination $lanExe
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $root 'lan-webview'
$process = Start-Process -FilePath $lanExe -ArgumentList ('"{0}"' -f $original) -PassThru -WindowStyle Normal
$window = Wait-For 'the LAN Markdown viewer' { Find-Window 'KSwitcher.Files.Text' 'Loopback peer' }
Browser 'render'
Browser 'edit'
if ((Wait-For 'LAN F6 editor' { Find-Window 'KSwitcher.Files.Text' 'Editor' }) -ne $window) {
throw 'LAN F6 changed windows.'
}
$control = Scintilla $window
Append-Character $control 'L'
Post $control 0x100 0x75
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 (!$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.'
}
} finally {
if ($process -and !$process.HasExited) {
Stop-Process -Id $process.Id
[void]$process.WaitForExit(5000)
}
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = $flags
$env:WEBVIEW2_USER_DATA_FOLDER = $data
if ($profileCaptured) {
foreach ($name in $profileValues) {
if ($saved.ContainsKey($name)) { $profile.SetValue($name,$saved[$name][0],$saved[$name][1]) }
else { $profile.DeleteValue($name,$false) }
}
}
$profile.Dispose()
if (Test-Path -LiteralPath $root) {
$resolved = (Resolve-Path -LiteralPath $root).Path
$temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
if ((Split-Path -Parent $resolved) -eq $temp -and (Split-Path -Leaf $resolved) -like 'ks-markdown-test-*') {
for ($attempt=0; $attempt -lt 40 -and (Test-Path -LiteralPath $resolved); ++$attempt) {
try { Remove-Item -LiteralPath $resolved -Recurse -Force }
catch {
if ($attempt -eq 39) { throw }
Start-Sleep -Milliseconds 250
}
}
}
}
}
+95
View File
@@ -0,0 +1,95 @@
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);
let socket;
const pending = new Map();
let sequence = 0;
async function waitFor(callback, label) {
for (let i = 0; i < 150; ++i) {
const result = await callback();
if (result) return result;
await delay(100);
}
throw new Error('Timed out waiting for ' + label);
}
function command(method, params = {}) {
const id = ++sequence;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error('DevTools timed out on ' + method));
}, 5000);
pending.set(id, reply => {
clearTimeout(timer);
if (reply.error) reject(new Error(reply.error.message));
else resolve(reply.result);
});
socket.send(JSON.stringify({ id, method, params }));
});
}
async function evaluate(expression) {
const reply = await command('Runtime.evaluate', { expression, returnByValue: true });
if (reply.exceptionDetails) throw new Error(reply.exceptionDetails.exception.description);
return reply.result.value;
}
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');
}, 'the Markdown page in WebView2');
socket = new WebSocket(target.webSocketDebuggerUrl);
socket.addEventListener('message', event => {
const reply = JSON.parse(event.data);
const callback = pending.get(reply.id);
if (callback) {
pending.delete(reply.id);
callback(reply);
}
});
await new Promise((resolve, reject) => {
socket.addEventListener('open', resolve, { once: true });
socket.addEventListener('error', reject, { once: true });
});
try {
if (scenario === 'render') {
await waitFor(() => evaluate(`!!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.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);
assert.equal(await evaluate(`!!document.querySelector('pre code.language-mermaid') &&
document.querySelector('main').textContent.includes('Invalid Mermaid diagram')`), true);
assert.equal(await evaluate(`!!document.querySelector('pre code.language-js') && !document.querySelector('iframe')`), true);
assert.equal(await evaluate(`performance.getEntriesByType('resource')
.every(entry => entry.name.startsWith(location.origin + '/') || entry.name.startsWith('data:'))`), true);
await waitFor(() => evaluate(`document.querySelector('img[alt="Missing image"]')?.title === 'Image unavailable'`),
'missing image feedback');
assert.deepEqual(await evaluate(`[...document.querySelectorAll('input')].map(box => box.checked)`), [false, true]);
assert.deepEqual(await evaluate(`[...document.querySelectorAll('input')].map(box => { box.click(); return box.checked; })`), [true, false]);
assert.deepEqual(await evaluate(`[...document.querySelectorAll('input')].map(box => { box.click(); return box.checked; })`), [false, true]);
if (artifact) {
const { data } = await command('Page.captureScreenshot');
await writeFile(artifact, Buffer.from(data, 'base64'));
}
} 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 {
await waitFor(() => evaluate('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');
}
}
} finally {
socket.close();
}
+80
View File
@@ -0,0 +1,80 @@
#include <winsock2.h>
#include "files_text_window.h"
#include "lan_files.h"
#include "platform.h"
#include <shellapi.h>
#include <thread>
int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
{
int count{};
auto args=CommandLineToArgvW(GetCommandLineW(),&count);
if(!args || count!=2)
{
if(args) LocalFree(args);
return 1;
}
const std::filesystem::path document=args[1];
LocalFree(args);
if(FAILED(CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED))) return 1;
WSADATA network{};
if(WSAStartup(MAKEWORD(2,2),&network))
{
CoUninitialize();
return 1;
}
int result=0;
try
{
using namespace ks;
using namespace ks::lan;
const auto serverId=randomHex(16), clientId=randomHex(16), key=randomHex(32);
FilesListener listener(serverId,[&](const auto &id){return id==clientId?key:std::string{};},0);
if(!listener.port()) throw std::runtime_error("Could not bind the LAN test listener.");
const auto pairing=Json{{"enabled",true},{"id",clientId},
{"trusted",{{serverId,{{"key",key}}}}}}.dump();
atomicWrite(dataDirectory()/L"lan-pairing.bin",protect(Bytes(pairing.begin(),pairing.end())));
const FilesPeer peer{serverId,"127.0.0.1",L"Loopback peer",listener.port()};
std::jthread server([&](std::stop_token stop) {
while(!stop.stop_requested()) { listener.poll(); Sleep(5); }
});
WNDCLASSW type{};
type.hInstance=instance;
type.lpszClassName=L"KSwitcher.Files.MarkdownFixture";
type.lpfnWndProc=[](HWND window,UINT message,WPARAM wparam,LPARAM lparam)->LRESULT {
if(message==WM_DESTROY) { files::textWindowOwnerClosed(); return 0; }
return DefWindowProcW(window,message,wparam,lparam);
};
if(!RegisterClassW(&type)) throw std::runtime_error("Could not register the LAN fixture.");
const auto owner=CreateWindowW(type.lpszClassName,L"LAN Markdown fixture",WS_OVERLAPPEDWINDOW,
20,20,960,720,nullptr,nullptr,instance,nullptr);
if(!owner) throw std::runtime_error("Could not open the LAN fixture.");
files::TextDialogs dialogs{};
dialogs.readFont=[] {
files::TextWindowFont font{};
wcscpy_s(font.font.lfFaceName,L"Consolas");
font.tenthsOfPoint=100;
return font;
};
dialogs.confirmExisting=[](HWND){return true;};
dialogs.confirmSave=[](HWND)->INT_PTR {return IDYES;};
dialogs.message=[](HWND,const wchar_t *message){log(message);};
dialogs.dismissOwned=[](HWND){return false;};
files::openTextWindow(owner,document,false,dialogs,&peer);
DestroyWindow(owner);
MSG message{};
while(GetMessageW(&message,nullptr,0,0)>0)
{
TranslateMessage(&message);
DispatchMessageW(&message);
}
}
catch(const std::exception &error)
{
ks::log(L"LAN Markdown fixture: "+ks::wide(error.what()));
result=1;
}
WSACleanup();
CoUninitialize();
return result;
}
+1 -1
View File
@@ -230,7 +230,7 @@ try {
[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") {
if (($rows -join '|') -cne "Refresh panel`tCtrl+R|Folder shortcuts||View`tF3|Edit`tF4|View externally`tAlt+F3|Edit externally`tAlt+F4") {
throw 'Commands did not group local actions or showed a LAN-only section.'
}
Post $commandMenu 0x100 40
+3 -1
View File
@@ -10,7 +10,9 @@ if (!(Test-Path "$deps/sdk/build/native/include/WebView2.h")) {
$assets = New-Item -ItemType Directory -Force (Join-Path $Destination 'terminal')
foreach ($package in @(
@{ Name='xterm'; Spec='@xterm/[email protected]'; Archive='xterm-xterm-6.0.0.tgz'; Files=@{'lib/xterm.js'='xterm.js'; 'css/xterm.css'='xterm.css'; 'LICENSE'='xterm-LICENSE.txt'} },
@{ Name='fit'; Spec='@xterm/[email protected]'; Archive='xterm-addon-fit-0.11.0.tgz'; Files=@{'lib/addon-fit.js'='addon-fit.js'; 'LICENSE'='addon-fit-LICENSE.txt'} }
@{ Name='fit'; Spec='@xterm/[email protected]'; Archive='xterm-addon-fit-0.11.0.tgz'; Files=@{'lib/addon-fit.js'='addon-fit.js'; 'LICENSE'='addon-fit-LICENSE.txt'} },
@{ Name='markdown-it'; Spec='[email protected]'; Archive='markdown-it-15.0.3.tgz'; Files=@{'dist/browser/markdown-it.umd.min.js'='markdown-it.js'; 'LICENSE'='markdown-it-LICENSE.txt'} },
@{ Name='mermaid'; Spec='[email protected]'; Archive='mermaid-12.3.0.tgz'; Files=@{'dist/mermaid.min.js'='mermaid.js'; 'LICENSE'='mermaid-LICENSE.txt'} }
)) {
if (!(Test-Path "$deps/$($package.Archive)")) {
& npm.cmd pack $package.Spec --pack-destination $deps.FullName --silent | Out-Host