Compare commits

..
29 changed files with 2121 additions and 249 deletions

No files matched your search

+20 -1
View File
@@ -686,13 +686,19 @@ Warning і початковий фокус на No.
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
- **Commands → Quick View** або **Ctrl+Q** вмикає перегляд локального
тексту, Markdown і зображень у сусідній панелі. Перегляд слідує за курсором активної
тексту, Markdown, HTML, зображень і двійкових файлів у сусідній панелі. Перегляд слідує за курсором активної
панелі. Повторна команда повертає сусідній каталог, курсор і позначки.
Під час перегляду файлові операції з призначенням у сусідній панелі
пропонують спершу закрити Quick View.
- Для локальних HTML-файлів до 8 МіБ Quick View відкриває **Rendered**. **Show Source** показує початковий текст, **Show Rendered** повертає форматований вигляд. F6 перемикає режими, коли фокус у самому перегляді. Quick View відображає статичне форматування й текст локально. Виконання скриптів, перехід за посиланнями і завантаження ресурсів заблоковані. Для зображень HTML показує їхній альтернативний текст. Більші HTML-файли починаються з першої сторінки вихідного тексту.
- Двійковий режим показує до 4096 початкових байтів, зі звичайними символами для друкованих байтів та позначенням `\xNN` для контрольних кодів. Рядки переносяться за шириною панелі. Shift+F3 відкриває повний Hex Viewer.
- **F3** відкриває PNG, JPEG, GIF, WebP і BMP у Viewer. Стрілки вліво й
вправо, Page Up і Page Down та кнопки Previous і Next гортають видимі
зображення в порядку вихідної панелі на момент відкриття Viewer.
- **Options → Viewer → Restore local Viewer and Editor windows after restart** зберігає відкриті локальні вікна під час закриття Files. Під час наступного запуску наявні документи відкриваються в попередньому режимі й положенні. Текст відновлює сторінку, курсор і прокручування, а зображення — масштаб. Відновлення читає збережені файли з диска.
- Локальний Viewer оновлює вміст після зміни файла. Активний Editor пропонує **Reload** або **Keep buffer**. Reload відкриває актуальну версію з диска, Keep buffer залишає відкриті редагування. Збереження після Keep buffer перевіряє початкову версію й зберігає чернетку, якщо файл уже змінився.
- **F4** на локальному PNG або JPEG відкриває редактор зображень. Rotate left і Rotate right повертають зображення на 90°. Crop приймає цілі координати X і Y від нуля, ширину й висоту в пікселях поточного зображення. Undo або Ctrl+Z послідовно скасовує зміни.
- **Save copy** або Ctrl+Shift+S створює окремий PNG чи JPEG. PNG зберігає прозорість, а JPEG використовує біле тло. **Replace** або Ctrl+S просить підтвердження й звіряє версію оригіналу. Якщо зовнішня зміна або помилка заважає запису, редактор зберігає чернетку. Закриття незбереженої чернетки просить підтвердження.
- У Viewer і Quick View коліщатко та кнопки − і + змінюють масштаб,
перетягування мишею панорамує збільшене зображення, Fit підганяє його
під область перегляду, а 100% повертає вихідний масштаб. Клавіші 0 і 1
@@ -836,6 +842,11 @@ Warning і початковий фокус на No.
- Секції поточного файла й загального прогресу мають однаковий вертикальний відступ від вмісту до верхньої та нижньої ліній. Cancel стоїть по центру спільної нижньої секції.
- Обидві шкали займають усю ширину вмісту. Відсотки показуються по центру шкали, а її висота враховує поточний шрифт.
- **Options** у Copy/Move задає маску імен файлів із символами `*` і `?`. Порожня маска або `*` копіює всі файли й порожні папки. З іншою маскою Files зберігає структуру папок із відповідними файлами. У Move файли поза маскою залишаються в джерелі.
- Додаткові папки вводяться абсолютними шляхами, по одному на рядок, на тому самому комп’ютері або підключенні, що й основне призначення. Однакові папки обробляються один раз. У Move джерело видаляється після успішного копіювання елемента в усі вибрані папки. У разі пропуску або збою вже записані копії зберігаються. Підсумок показує кількість повністю скопійованих елементів по всіх призначеннях і загальну кількість записаних файлів.
- **Preserve modification time** зберігає час зміни там, де ціль підтримує його встановлення. Збереження часу підтримують Windows і SFTP. FTP-призначення використовує час сервера. **Preserve Windows permissions** переносить DACL між файловими системами Windows, які підтримують цей тип прав. Наявні папки, у які додаються файли, зберігають власні права й час.
- Оцінка залишку часу в прогресі з’являється після кількох вимірювань швидкості. Довга пауза скидає оцінку. Скасування й конфлікти використовують спільні діалоги.
## Попередження про конфлікт
- Для однойменних файлів Warning показує точний розмір у байтах із розділенням тисяч і місцевий
@@ -853,6 +864,14 @@ Warning і початковий фокус на No.
- F8 переміщує підтверджені елементи в кошик Windows. Shift+Delete видаляє підтверджене дерево від вкладених елементів до батьківської папки. Прогрес і підсумок окремо показують успішні, пропущені й невдалі дії.
- Cancel і Esc у вікні прогресу відкривають спільне червоне підтвердження скасування. Yes зупиняє операцію, а No або Esc у підтвердженні повертає до прогресу. Початковий фокус стоїть на No.
## Обмін і компонування панелей
- **Commands → Swap panels** або **Ctrl+U** міняє панелі місцями. Активна панель, шлях, курсор, прокручування, позначки, поточний режим і Quick View переходять разом.
- **Options → File panel modes → Panel layout** містить незалежні параметри для правої кнопки, кнопок дисків і компактного компонування. За замовчуванням ці параметри вимкнені.
- **Mark items with the right mouse button** перемикає позначку рядка. **Shift+права кнопка**, **Shift+F10** і клавіша **Menu** відкривають контекстне меню. Права кнопка на порожньому місці також відкриває контекстне меню панелі.
- **Show drive buttons** додає наявні локальні диски над панелями. Кнопка відкриває корінь диска в активній панелі. Якщо всі диски не поміщаються, **…** відкриває Change drive.
- **Compact commander layout** скорочує проміжки між шляхом, рядками та станом, зберігаючи розмір шрифту, командний рядок і клавіші дій.
## Перевірка змін
Відкрий Copy і Warning в одній збірці та порівняй висоту нижніх секцій, центрування, повноту підписів і видимість фокуса. Перевір Tab, стрілки й Esc. Після узгодження нового правила онови відповідний розділ цього документа.
+1 -1
View File
@@ -16,7 +16,7 @@ function(build_files_webp)
endfunction()
build_files_webp()
add_library(KSwitcherFilesImage STATIC src/files_image_decode.cpp src/files_image_view.cpp)
add_library(KSwitcherFilesImage STATIC src/files_image_decode.cpp src/files_image_edit.cpp src/files_image_view.cpp)
target_compile_definitions(KSwitcherFilesImage PRIVATE NOMINMAX UNICODE _UNICODE _WIN32_WINNT=0x0A00)
target_link_libraries(KSwitcherFilesImage PRIVATE webpdemux windowscodecs msimg32 ole32)
if(MSVC)
+44 -2
View File
@@ -169,6 +169,10 @@ BEGIN
COMBOBOX 273, 132, 40, 108, 74, CBS_DROPDOWNLIST | WS_TABSTOP
LTEXT "&Right panel", 507, 251, 27, 117, 11
COMBOBOX 274, 251, 40, 117, 74, CBS_DROPDOWNLIST | WS_TABSTOP
AUTOCHECKBOX "Mark items with the right mouse button", 520, 132, 64, 245, 13
AUTOCHECKBOX "Show drive buttons", 521, 132, 81, 245, 13
AUTOCHECKBOX "Compact commander layout", 522, 132, 98, 245, 13
LTEXT "Shift+right-click opens the Windows context menu.", 523, 132, 115, 245, 13
GROUPBOX "Wide panel columns", 275, 129, 27, 259, 59
LTEXT "Size column &width (6–16 characters)", 276, 138, 44, 175, 10
EDITTEXT 201, 335, 41, 43, 14, ES_NUMBER | ES_AUTOHSCROLL
@@ -232,6 +236,7 @@ BEGIN
PUSHBUTTON "Change color…", 366, 257, 181, 82, 15
LTEXT "", 367, 345, 184, 45, 12
PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15
AUTOCHECKBOX "Restore local Viewer and Editor windows after restart", 524, 131, 210, 250, 13
LTEXT "Maximum &width (px, 0 = full window)", 373, 131, 31, 184, 12
EDITTEXT 374, 318, 28, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
LTEXT "Font &family (blank = system default)", 375, 131, 54, 250, 12
@@ -262,8 +267,9 @@ BEGIN
LTEXT "Existing files:", 212, 14, 57, 122, 14, SS_CENTERIMAGE
COMBOBOX 213, 140, 57, 196, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP
AUTOCHECKBOX "Also ask on read-only files", 214, 14, 77, 322, 14
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 92, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 92, 86, 18
CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 42, 92, 86, 18
CONTROL "&Options...", 215, "Button", BS_OWNERDRAW | WS_TABSTOP, 132, 92, 86, 18
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 222, 92, 86, 18
END
103 DIALOGEX 0, 0, 460, 126
@@ -671,3 +677,39 @@ BEGIN
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 100, 78, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 186, 100, 78, 16
END
129 DIALOGEX 0, 0, 388, 177
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Copy/Move options"
FONT 10, "Consolas"
BEGIN
LTEXT "File &mask", 645, 14, 15, 360, 13
FAR_EDIT(640, 0, 14, 28, 360, 17)
LTEXT "Additional &folders on this computer (one absolute path per line)", 646, 14, 53, 360, 13
EDITTEXT 641, 14, 67, 360, 40, ES_MULTILINE | ES_WANTRETURN | ES_AUTOVSCROLL | WS_VSCROLL
AUTOCHECKBOX "Preserve modification &time", 642, 14, 112, 360, 14
AUTOCHECKBOX "Preserve Windows &permissions", 643, 14, 127, 360, 14
LTEXT "Extra folders use the same destination computer or connection.", 647, 14, 143, 360, 13
LTEXT "", 644, 10, 159, 1, 1, NOT WS_VISIBLE
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 161, 86, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 200, 161, 86, 16
END
130 DIALOGEX 0, 0, 329, 119
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
CAPTION "Crop image"
FONT 10, "Consolas"
BEGIN
LTEXT "", 650, 14, 15, 301, 12
LTEXT "&X", 656, 14, 35, 58, 14, SS_CENTERIMAGE
FAR_EDIT(651, ES_NUMBER, 75, 33, 70, 18)
LTEXT "&Y", 657, 173, 35, 58, 14, SS_CENTERIMAGE
FAR_EDIT(652, ES_NUMBER, 244, 33, 70, 18)
LTEXT "&Width", 658, 14, 60, 58, 14, SS_CENTERIMAGE
FAR_EDIT(653, ES_NUMBER, 75, 58, 70, 18)
LTEXT "&Height", 659, 173, 60, 62, 14, SS_CENTERIMAGE
FAR_EDIT(654, ES_NUMBER, 244, 58, 70, 18)
LTEXT "", 655, 10, 86, 1, 1, NOT WS_VISIBLE
CONTROL "&Crop", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 78, 94, 83, 17
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 168, 94, 83, 17
END
+1 -1
View File
@@ -27,7 +27,7 @@ nav button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px;
::highlight(markdown-search-active) { background: #ffab45; color: #171717; }
: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; }
a[href] { color: LinkText; }
pre, table, figure { overflow: auto; }
pre, code { background: color-mix(in srgb, CanvasText 8%, Canvas); border-radius: 4px; }
pre { padding: .75em; }
+31 -8
View File
@@ -73,7 +73,7 @@ markdown.renderer.rules.image = (tokens, i) => {
const htmlTags = new Set(`a abbr address article aside b blockquote br caption code col colgroup dd del
details div dl dt em figcaption figure footer h1 h2 h3 h4 h5 h6 header hr i img input ins kbd li
mark ol p pre s samp section small span strong sub summary sup table tbody td tfoot th thead time
main mark nav ol p pre s samp section small span strong sub summary sup table tbody td tfoot th thead time
tr u ul var wbr`.split(/\s+/));
const htmlAttributes = new Set(['id', 'class', 'title', 'lang', 'dir', 'aria-label']);
const tagAttributes = {
@@ -88,21 +88,25 @@ function relativeResource(path) {
return path && !/^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path) && !/[\u0000-\u001f\u007f]/.test(path);
}
function renderContent(text, canSave) {
function renderContent(text, canSave, html) {
// Parse in an inert template and allow only document markup before attaching it to the preview.
const template = document.createElement('template');
const taskKey = [...crypto.getRandomValues(new Uint32Array(4))].join('-');
taskMarkers = new WeakMap();
pendingTask = undefined;
template.innerHTML = markdown.render(text, { taskKey });
template.innerHTML = html ? text : markdown.render(text, { taskKey });
for (const element of template.content.querySelectorAll('*')) {
const tag = element.localName;
if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !htmlTags.has(tag) ||
(tag === 'input' && element.type !== 'checkbox')) {
(tag === 'input' && (html || element.type !== 'checkbox'))) {
element.remove();
continue;
}
const imagePath = tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
const imagePath = !html && tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
if (html && tag === 'img') {
element.replaceWith(document.createTextNode(element.getAttribute('alt') ?? ''));
continue;
}
const task = tag === 'input' && element.getAttribute('data-task');
if (task && task.startsWith(taskKey + ':')) {
const [, line, column] = task.split(':');
@@ -112,7 +116,8 @@ function renderContent(text, canSave) {
const styles = element.hasAttribute('style')
? inlineStyles.map(name => [name, element.style.getPropertyValue(name)]) : [];
for (const { name } of [...element.attributes]) {
if (!htmlAttributes.has(name) && !tagAttributes[tag]?.includes(name)) element.removeAttribute(name);
const blockedInHtml = html && (name === 'id' || name === 'class' || name === 'href');
if (blockedInHtml || (!htmlAttributes.has(name) && !tagAttributes[tag]?.includes(name))) element.removeAttribute(name);
}
for (const [name, value] of styles) {
if (value) element.style.setProperty(name, value);
@@ -247,7 +252,7 @@ searchPrevious.addEventListener('click', () => stepSearch(-1));
searchNext.addEventListener('click', () => stepSearch(1));
content.addEventListener('toggle', () => { if (!search.hidden) updateSearch(false); }, true);
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave, compact }) {
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave, compact, html }) {
const current = ++generation;
if (keepPosition) scroll = window.scrollY;
else closeSearch();
@@ -255,7 +260,14 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c
document.title = title;
document.documentElement.classList.toggle('quick-view', Boolean(compact));
previewRevision = revision;
renderContent(text, canSave);
renderContent(text, canSave, html);
images = [];
if (html) {
window.scrollTo(0, 0);
document.documentElement.classList.add('rendered');
send('rendered', { revision });
return;
}
const headings = new Set();
for (const heading of content.querySelectorAll('h1,h2,h3,h4,h5,h6')) {
const base = heading.id || heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
@@ -343,6 +355,17 @@ document.addEventListener('keydown', event => {
}
});
let scrollTimer;
window.addEventListener('scroll', () => {
if (document.documentElement.classList.contains('quick-view')) return;
clearTimeout(scrollTimer);
const revision = previewRevision;
scrollTimer = setTimeout(() => {
if (revision === previewRevision && document.documentElement.classList.contains('rendered'))
send('scroll', { revision, top: Math.round(window.scrollY) });
}, 120);
}, { passive: true });
bridge.addEventListener('message', ({ data }) => {
const message = JSON.parse(data);
if (message.action === 'clear') {
+97
View File
@@ -0,0 +1,97 @@
struct CopyOptionsPrompt
{
CopyOptions value;
bool permissions{}, move{}, unixDest{};
};
INT_PTR CALLBACK copyOptionsDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int mask=640, paths=641, time=642, permissions=643, footer=644, folderLabel=646, hint=647;
if(message==WM_DRAWITEM)
{
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT*>(lp),RGB(192,192,192),RGB(0,0,0),true);
return TRUE;
}
if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Copy/Move options ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
{
const auto &prompt=*reinterpret_cast<const CopyOptionsPrompt*>(lp);
SetWindowLongPtrW(window,DWLP_USER,lp);
prepareCopyDialog(window);
layoutDialogContent(window,645);
fitFarEditToLine(GetDlgItem(window,mask));
installFarCheckbox(GetDlgItem(window,time),FarCheckboxSurface::gray);
installFarCheckbox(GetDlgItem(window,permissions),FarCheckboxSurface::gray);
for(const auto id:{time,permissions})
SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
layoutDialogButtons(window,footer,{IDOK,IDCANCEL});
CheckDlgButton(window,time,prompt.value.preserveTime?BST_CHECKED:BST_UNCHECKED);
CheckDlgButton(window,permissions,prompt.value.preservePermissions?BST_CHECKED:BST_UNCHECKED);
EnableWindow(GetDlgItem(window,permissions),prompt.permissions);
SetDlgItemTextW(window,mask,prompt.value.mask.c_str());
SendDlgItemMessageW(window,mask,EM_SETLIMITTEXT,255,0);
SendDlgItemMessageW(window,paths,EM_SETLIMITTEXT,32767,0);
std::wstring lines;
for(const auto &path:prompt.value.additional)
{
if(!lines.empty()) lines+=L"\r\n";
lines+=path.native();
}
SetDlgItemTextW(window,paths,lines.c_str());
if(prompt.unixDest) SetDlgItemTextW(window,folderLabel,L"Additional &folders on this server (one absolute path per line)");
if(prompt.move) SetDlgItemTextW(window,hint,L"Move keeps the source until every requested copy succeeds.");
SetFocus(GetDlgItem(window,mask));
SendDlgItemMessageW(window,mask,EM_SETSEL,0,-1);
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(window,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &prompt=*reinterpret_cast<CopyOptionsPrompt*>(GetWindowLongPtrW(window,DWLP_USER));
const auto text=[&](int id) {
auto control=GetDlgItem(window,id);
std::wstring value(GetWindowTextLengthW(control)+1,L'\0');
value.resize(GetWindowTextW(control,value.data(),static_cast<int>(value.size())));
return value;
};
auto pattern=text(mask);
if(pattern.find_first_of(L"/\\:")!=pattern.npos)
{
showFilesNotice(window,L"Enter a file name or mask without a path.",L"Copy/Move options");
SetFocus(GetDlgItem(window,mask));
return TRUE;
}
const auto entered=text(paths);
std::vector<fs::path> folders;
for(size_t start=0;start<entered.size();)
{
const auto end=entered.find(L'\n',start);
auto line=std::wstring_view(entered).substr(start,end==entered.npos?end:end-start);
if(!line.empty() && line.back()==L'\r') line.remove_suffix(1);
if(!line.empty())
{
auto path=fs::path(line);
const bool unc=!prompt.unixDest && (line.starts_with(L"\\\\") || line.starts_with(L"//"));
const bool absolute=prompt.unixDest?line.front()==L'/':path.is_absolute() || unc;
if(!absolute || line.find_first_of(L"<>|?*")!=line.npos || line.starts_with(L"\\\\.\\"))
{
showFilesNotice(window,L"Enter one absolute destination folder per line.",L"Copy/Move options");
SetFocus(GetDlgItem(window,paths));
return TRUE;
}
if(!unc) path=path.lexically_normal();
folders.push_back(folderPathWithoutSeparator(std::move(path)));
}
if(end==entered.npos) break;
start=end+1;
}
prompt.value={pattern.empty()?L"*":std::move(pattern),std::move(folders),
IsDlgButtonChecked(window,time)==BST_CHECKED,
prompt.permissions && IsDlgButtonChecked(window,permissions)==BST_CHECKED};
FilesModalDialog::finish(window,IDOK);
return TRUE;
}
+14 -1
View File
@@ -25,6 +25,7 @@ struct CopyHost
FileOperationElevation *elevation{};
fs::path listedDirectory;
FileEntries listedEntries;
std::optional<bool> copyMetadataSupport;
CopyHost(const FilesPeer *peer,const std::optional<TransferProfile> &profile,FileOperationElevation *admin=nullptr)
{
@@ -67,6 +68,17 @@ struct CopyHost
return entries;
}
bool supportsCopyMetadata()
{
if(!copyMetadataSupport)
{
const auto reply=request(fileRequest("fileCapabilities",L"C:\\"));
if(reply.at("error")!=ERROR_INVALID_FUNCTION) checkFileReply(reply);
copyMetadataSupport=reply.value("copyMetadata",false);
}
return *copyMetadataSupport;
}
void makeDirectory(const fs::path &path)
{
if(!ftp)
@@ -131,7 +143,7 @@ void downloadTransferFile(TransferSession &ftp,FilesConnection &local,const fs::
FileInfo uploadTransferFile(FilesConnection &local,TransferSession &ftp,const fs::path &source,const fs::path &target,
const FileInfo &info,bool replace,const ks::lan::FileProgress &progress,
const ks::files::RemoteTextRevision *expected=nullptr)
const ks::files::RemoteTextRevision *expected=nullptr,bool preserveTime=false)
{
const auto directory=target.parent_path();
const auto temporary=directory/ks::wide("kswitcher-"+ks::lan::randomHex(16)+".partial");
@@ -179,6 +191,7 @@ FileInfo uploadTransferFile(FilesConnection &local,TransferSession &ftp,const fs
ERROR_ALREADY_EXISTS);
ftp.prepareReplacement(temporary,target);
}
if(preserveTime) ftp.preserveModificationTime(temporary,info.modified);
requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED);
ftp.rename(temporary,target,existing.has_value());
return *uploaded;
+79 -5
View File
@@ -3,6 +3,7 @@
#include <wincodec.h>
#include <webp/decode.h>
#include <webp/demux.h>
#include <algorithm>
#include <cstring>
#include <fstream>
#include <memory>
@@ -58,13 +59,14 @@ struct ImagingObject
T *operator->() const {return value;}
};
struct Apartment
{
const HRESULT initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
~Apartment() {if(SUCCEEDED(initialized)) CoUninitialize();}
};
ImageRaster decodeNativeImage(const fs::path &file,ImageFormat format,std::stop_token stop)
{
struct Apartment
{
const HRESULT initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED);
~Apartment() {if(SUCCEEDED(initialized)) CoUninitialize();}
};
const Apartment apartment;
if(apartment.initialized!=RPC_E_CHANGED_MODE) checkImage(apartment.initialized);
ImagingObject<IWICImagingFactory> factory;
@@ -141,6 +143,78 @@ bool isImagePath(const std::filesystem::path &path)
return imageFormat(path)!=ImageFormat::unknown;
}
bool isEditableImagePath(const std::filesystem::path &path)
{
const auto format=imageFormat(path);
return format==ImageFormat::png || format==ImageFormat::jpeg;
}
void encodeImage(const ImageRaster &raster,const fs::path &contents,const fs::path &name)
{
const auto format=imageFormat(name);
if(format!=ImageFormat::png && format!=ImageFormat::jpeg)
throw std::runtime_error("Choose a PNG or JPEG file.");
checkImageDimensions(raster.width,raster.height);
if(raster.pixels.size()!=size_t(raster.width)*raster.height) throw std::runtime_error(invalidImage);
const auto check=[](HRESULT result) {
if(FAILED(result)) throw std::system_error(static_cast<int>(result),std::system_category(),"Encode image");
};
const Apartment apartment;
if(apartment.initialized!=RPC_E_CHANGED_MODE) check(apartment.initialized);
ImagingObject<IWICImagingFactory> factory;
check(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory.value)));
const bool png=format==ImageFormat::png;
ImagingObject<IWICStream> stream;
check(factory->CreateStream(&stream.value));
check(stream->InitializeFromFilename(contents.c_str(),GENERIC_WRITE));
ImagingObject<IWICBitmapEncoder> encoder;
check(factory->CreateEncoder(png?GUID_ContainerFormatPng:GUID_ContainerFormatJpeg,nullptr,&encoder.value));
check(encoder->Initialize(stream.value,WICBitmapEncoderNoCache));
ImagingObject<IWICBitmapFrameEncode> frame;
ImagingObject<IPropertyBag2> options;
check(encoder->CreateNewFrame(&frame.value,&options.value));
if(!png)
{
wchar_t qualityName[]=L"ImageQuality";
PROPBAG2 property{};
property.pstrName=qualityName;
VARIANT quality{};
quality.vt=VT_R4;
quality.fltVal=0.95f;
check(options->Write(1,&property,&quality));
}
check(frame->Initialize(options.value));
check(frame->SetSize(raster.width,raster.height));
auto pixelFormat=png?GUID_WICPixelFormat32bppBGRA:GUID_WICPixelFormat24bppBGR;
check(frame->SetPixelFormat(&pixelFormat));
auto *pixels=raster.pixels.data();
std::vector<uint32_t> opaque;
if(!png && std::any_of(raster.pixels.begin(),raster.pixels.end(),[](uint32_t pixel){return (pixel>>24)!=255;}))
{
opaque=raster.pixels;
for(auto &pixel:opaque)
{
const auto white=255-(pixel>>24);
const auto gray=white|(white<<8)|(white<<16);
pixel=0xff000000|((pixel&0x00ffffff)+gray);
}
pixels=opaque.data();
}
const auto stride=static_cast<UINT>(raster.width*sizeof(uint32_t));
ImagingObject<IWICBitmap> source;
check(factory->CreateBitmapFromMemory(raster.width,raster.height,GUID_WICPixelFormat32bppPBGRA,stride,
static_cast<UINT>(raster.pixels.size()*sizeof(uint32_t)),
reinterpret_cast<BYTE *>(const_cast<uint32_t *>(pixels)),&source.value));
ImagingObject<IWICFormatConverter> converter;
check(factory->CreateFormatConverter(&converter.value));
check(converter->Initialize(source.value,pixelFormat,WICBitmapDitherTypeNone,nullptr,0,WICBitmapPaletteTypeCustom));
check(frame->WriteSource(converter.value,nullptr));
check(frame->Commit());
check(encoder->Commit());
check(stream->Commit(STGC_DEFAULT));
}
ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop)
{
const auto format=imageFormat(name);
+3 -1
View File
@@ -10,10 +10,12 @@ namespace ks::files
struct ImageRaster
{
unsigned width{}, height{};
std::vector<uint32_t> pixels;
std::vector<uint32_t> pixels; // Premultiplied BGRA.
};
inline constexpr uint64_t imageSourceLimit=96ULL*1024*1024;
bool isImagePath(const std::filesystem::path &path);
bool isEditableImagePath(const std::filesystem::path &path);
void encodeImage(const ImageRaster &raster,const std::filesystem::path &contents,const std::filesystem::path &name);
ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop={});
}
+131
View File
@@ -0,0 +1,131 @@
#include "files_image_edit.h"
#include "files_win32_replace.h"
#include <system_error>
namespace ks::files
{
namespace
{
struct ImageFile
{
HANDLE handle=INVALID_HANDLE_VALUE;
~ImageFile() {if(handle!=INVALID_HANDLE_VALUE) CloseHandle(handle);}
};
struct StagedImage
{
std::filesystem::path path;
~StagedImage() {if(!path.empty()) DeleteFileW(path.c_str());}
};
[[noreturn]] void fail(const char *message,DWORD error=GetLastError())
{
throw std::system_error(static_cast<int>(error),std::system_category(),message);
}
ImageRevision readRevision(HANDLE handle)
{
const auto revision=fileVersion(handle);
if(revision.info.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT))
throw std::runtime_error("Choose a regular local image.");
return revision;
}
bool contains(unsigned width,unsigned height,const ImageRegion &area)
{
return area.width && area.height && area.x<width && area.y<height &&
area.width<=width-area.x && area.height<=height-area.y;
}
}
ImageGeometry cropImage(ImageGeometry geometry,const ImageRegion &area)
{
auto &region=geometry.region;
const bool sideways=(geometry.turns&1)!=0;
if(geometry.turns>=4 || !contains(sideways?region.height:region.width,sideways?region.width:region.height,area))
throw std::runtime_error("The crop rectangle must fit inside the image.");
const auto width=region.width, height=region.height;
switch(geometry.turns)
{
case 0: region.x+=area.x; region.y+=area.y; break;
case 1: region.x+=area.y; region.y+=height-area.x-area.width; break;
case 2: region.x+=width-area.x-area.width; region.y+=height-area.y-area.height; break;
case 3: region.x+=width-area.y-area.height; region.y+=area.x; break;
}
region.width=sideways?area.height:area.width;
region.height=sideways?area.width:area.height;
return geometry;
}
ImageRaster transformImage(const ImageRaster &original,const ImageGeometry &geometry)
{
const auto &region=geometry.region;
if(geometry.turns>=4 || !contains(original.width,original.height,region) ||
original.pixels.size()!=size_t(original.width)*original.height)
throw std::runtime_error("The image edit exceeds the original bounds.");
const bool sideways=geometry.turns&1;
ImageRaster output{sideways?region.height:region.width,sideways?region.width:region.height,{}};
output.pixels.resize(size_t(output.width)*output.height);
for(unsigned y=0;y<output.height;++y)
{
for(unsigned x=0;x<output.width;++x)
{
unsigned fromX{},fromY{};
switch(geometry.turns)
{
case 0: fromX=x; fromY=y; break;
case 1: fromX=y; fromY=region.height-1-x; break;
case 2: fromX=region.width-1-x; fromY=region.height-1-y; break;
case 3: fromX=region.width-1-y; fromY=x; break;
}
output.pixels[size_t(y)*output.width+x]=original.pixels[size_t(region.y+fromY)*original.width+region.x+fromX];
}
}
return output;
}
ImageRevision imageRevision(const std::filesystem::path &path)
{
ImageFile file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.handle==INVALID_HANDLE_VALUE) fail("Open image revision");
return readRevision(file.handle);
}
bool sameImageRevision(const ImageRevision &first,const ImageRevision &second)
{
return first==second;
}
ImageRevision saveImage(const ImageRaster &raster,const std::filesystem::path &path,const ImageRevision *expected)
{
const auto stagedPath=temporaryPath(path.parent_path());
{
ImageFile reserve{CreateFileW(stagedPath.c_str(),GENERIC_WRITE,0,nullptr,CREATE_NEW,FILE_ATTRIBUTE_NORMAL,nullptr)};
if(reserve.handle==INVALID_HANDLE_VALUE) fail("Create image staging file");
}
StagedImage pending{stagedPath};
encodeImage(raster,pending.path,path);
// Keep the saved file's identity through publication, even if the path changes again.
ImageFile saved{CreateFileW(pending.path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(saved.handle==INVALID_HANDLE_VALUE) fail("Track saved image");
if(!expected)
{
if(!MoveFileExW(pending.path.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH)) fail("Publish image copy");
pending.path.clear();
return readRevision(saved.handle);
}
ImageFile current{CreateFileW(path.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,nullptr,
OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(current.handle==INVALID_HANDLE_VALUE) fail("Verify original image");
if(!sameImageRevision(*expected,readRevision(current.handle)))
throw std::runtime_error("The original image changed outside Files. Your edits remain open.");
const auto backup=temporaryPath(path.parent_path());
if(const auto error=replaceFileWithBackup(path,pending.path,backup)) fail("Replace original image",error);
pending.path.clear();
DeleteFileW(backup.c_str());
return readRevision(saved.handle);
}
}
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include "files_image_decode.h"
#include "files_win32_replace.h"
namespace ks::files
{
struct ImageRegion
{
unsigned x{}, y{}, width{}, height{};
bool operator==(const ImageRegion &) const = default;
};
struct ImageGeometry
{
ImageRegion region;
unsigned turns{};
bool operator==(const ImageGeometry &) const = default;
};
using ImageRevision=LocalFileVersion;
ImageGeometry cropImage(ImageGeometry geometry,const ImageRegion &area);
ImageRaster transformImage(const ImageRaster &original,const ImageGeometry &geometry);
ImageRevision imageRevision(const std::filesystem::path &path);
bool sameImageRevision(const ImageRevision &first,const ImageRevision &second);
ImageRevision saveImage(const ImageRaster &raster,const std::filesystem::path &path,const ImageRevision *expected=nullptr);
}
+109
View File
@@ -0,0 +1,109 @@
struct ImageCropPrompt
{
unsigned width,height;
ks::files::ImageRegion result;
};
INT_PTR CALLBACK imageCropDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
constexpr int hint=650, x=651, y=652, width=653, height=654, footer=655;
if(message==WM_DRAWITEM)
{
paintDialogButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp),RGB(192,192,192),RGB(0,0,0),true);
return TRUE;
}
if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Crop image ",false,{footer}))
return painted;
if(message==WM_INITDIALOG)
{
auto &prompt=*reinterpret_cast<ImageCropPrompt *>(lp);
SetWindowLongPtrW(window,DWLP_USER,lp);
prepareCopyDialog(window);
layoutDialogContent(window,hint);
layoutDialogButtons(window,footer,{IDOK,IDCANCEL});
const auto description=L"Image: "+std::to_wstring(prompt.width)+L" × "+std::to_wstring(prompt.height)+
L" pixels. X and Y start at zero.";
SetDlgItemTextW(window,hint,description.c_str());
for(const auto id:{x,y,width,height})
{
fitFarEditToLine(GetDlgItem(window,id));
const auto value=id==width?prompt.width:id==height?prompt.height:0;
SetDlgItemInt(window,id,value,FALSE);
}
SetFocus(GetDlgItem(window,x));
SendDlgItemMessageW(window,x,EM_SETSEL,0,-1);
return FALSE;
}
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(window,IDCANCEL);
return TRUE;
}
if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE;
auto &prompt=*reinterpret_cast<ImageCropPrompt *>(GetWindowLongPtrW(window,DWLP_USER));
std::array<unsigned,4> fields{};
for(size_t i=0;i<fields.size();++i)
{
const int id=x+static_cast<int>(i);
BOOL valid{};
fields[i]=GetDlgItemInt(window,id,&valid,FALSE);
if(!valid)
{
showFilesNotice(window,L"Enter a whole number of pixels.",L"Crop image");
SetFocus(GetDlgItem(window,id));
return TRUE;
}
}
const auto [left,top,wide,high]=fields;
if(!wide || !high || left>=prompt.width || top>=prompt.height ||
wide>prompt.width-left || high>prompt.height-top)
{
showFilesNotice(window,L"The crop rectangle must fit inside the image.",L"Crop image");
return TRUE;
}
prompt.result={left,top,wide,high};
FilesModalDialog::finish(window,IDOK);
return TRUE;
}
ks::files::ImageEditDialogs imageEditDialogs()
{
return {
[](HWND owner,unsigned width,unsigned height) -> std::optional<ks::files::ImageRegion>
{
ImageCropPrompt crop{width,height,{}};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(130),owner,
imageCropDialog,reinterpret_cast<LPARAM>(&crop))==IDOK) return crop.result;
return {};
},
[](HWND owner,const fs::path &original) -> fs::path
{
const auto name=original.stem().native()+L" copy"+original.extension().native();
std::array<wchar_t,32768> file{};
wcsncpy_s(file.data(),file.size(),name.c_str(),_TRUNCATE);
auto initial=original.parent_path().native();
OPENFILENAMEW dialog{sizeof(dialog)};
dialog.hwndOwner=owner;
dialog.lpstrTitle=L"Save an image copy";
dialog.lpstrFilter=L"PNG (*.png)\0*.png\0JPEG (*.jpg, *.jpeg)\0*.jpg;*.jpeg\0";
dialog.nFilterIndex=ks::lower(original.extension().native())==L".png"?1:2;
dialog.lpstrFile=file.data();
dialog.nMaxFile=static_cast<DWORD>(file.size());
dialog.lpstrInitialDir=initial.c_str();
dialog.lpstrDefExt=dialog.nFilterIndex==1?L"png":L"jpg";
dialog.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST;
if(GetSaveFileNameW(&dialog)) return file.data();
if(CommDlgExtendedError()) throw std::runtime_error("Could not open the image save dialog.");
return {};
},
[](HWND owner,const std::wstring &text,const wchar_t *title)
{
return showFilesNotice(owner,text.c_str(),title,{.confirm=true,.tone=FilesNoticeTone::warning})==IDYES;
},
[](HWND owner,const wchar_t *text)
{
showFilesNotice(owner,text,L"Image editor",{.tone=FilesNoticeTone::warning});
},
FilesModalDialog::dismissOwned,textWindowDialogs().reloadChanged
};
}
+233 -35
View File
@@ -17,8 +17,9 @@ namespace
{
namespace fs=std::filesystem;
constexpr wchar_t imageWindowClass[]=L"KSwitcherFilesImageViewer";
constexpr UINT_PTR imageTimer=1;
enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize };
constexpr UINT_PTR imageTimer=1, externalImageTimer=2;
enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize,
rotateLeft, rotateRight, crop, undoEdit, saveCopy, replaceOriginal };
void fillImageView(HDC dc,const RECT &rect,COLORREF color)
{
@@ -37,14 +38,32 @@ struct ImageView
ImageLoadRetry retry;
bool retried{};
std::function<void(HWND)> onClose;
std::array<HWND,6> buttons{};
std::array<HWND,replaceOriginal> buttons{};
struct Draft
{
ImageEditDialogs dialogs;
ImageRaster original;
std::optional<ImageRevision> version;
ImageGeometry geometry{}, saved{};
std::vector<ImageGeometry> undo;
bool dirty() const {return geometry!=saved;}
};
std::optional<Draft> draft;
struct Loaded
{
ImageRaster raster;
std::optional<ImageRevision> revision;
};
bool confirmingClose{};
std::optional<ImageRevision> observedVersion;
HFONT font{};
UINT fontDpi{};
int toolbarHeight{};
HBITMAP bitmap{};
unsigned width{},height{};
fs::path requested;
std::wstring error;
std::future<ImageRaster> reading;
std::future<Loaded> reading;
std::stop_source stop;
uint64_t revision{}, started{};
double zoom=1, x{}, y{};
@@ -64,7 +83,7 @@ struct ImageView
{
RECT area{};
GetClientRect(window,&area);
area.top=std::min(area.bottom,static_cast<LONG>(scale(35)));
area.top=std::min(area.bottom,static_cast<LONG>(toolbarHeight));
area.bottom=std::max(area.top,area.bottom-scale(27));
return area;
}
@@ -86,45 +105,83 @@ struct ImageView
RECT bounds{};
GetClientRect(window,&bounds);
const int left=scale(4), gap=scale(3), height=scale(27);
const int count=embedded?4:6;
const int available=std::max(0,static_cast<int>(bounds.right)-left*2-gap*(count-1));
const int unit=std::min(scale(80),available/count);
int x=left;
for(auto button:buttons)
const auto place=[&](unsigned first,unsigned last,int y,int preferred) {
const auto count=static_cast<int>(last-first+1);
const auto available=std::max(0,static_cast<int>(bounds.right)-left*2-gap*(count-1));
const auto unit=std::min(scale(preferred),available/count);
int x=left;
for(unsigned id=first;id<=last;++id)
{
SetWindowPos(buttons[id-1],nullptr,x,scale(y),unit,height,SWP_NOZORDER|SWP_NOACTIVATE);
x+=unit+gap;
}
};
place(embedded || draft?zoomOut:previous,actualSize,4,80);
int rows=0;
if(draft)
{
if(!button) continue;
SetWindowPos(button,nullptr,x,scale(4),unit,height,SWP_NOZORDER|SWP_NOACTIVATE);
x+=unit+gap;
int buttonWidth=scale(80);
if(const auto dc=GetDC(window))
{
const auto previousFont=font?SelectObject(dc,font):nullptr;
for(unsigned id=rotateLeft;id<=replaceOriginal;++id)
{
wchar_t label[32]{};
const auto length=GetWindowTextW(buttons[id-1],label,static_cast<int>(std::size(label)));
SIZE extent{};
if(GetTextExtentPoint32W(dc,label,length,&extent))
buttonWidth=std::max(buttonWidth,static_cast<int>(extent.cx)+scale(8));
}
if(previousFont) SelectObject(dc,previousFont);
ReleaseDC(window,dc);
}
const auto perRow=static_cast<unsigned>(std::max(1,(static_cast<int>(bounds.right)-left*2+gap)/(buttonWidth+gap)));
for(unsigned first=rotateLeft;first<=replaceOriginal;first+=perRow)
place(first,std::min<unsigned>(replaceOriginal,first+perRow-1),35+31*rows++,130);
}
toolbarHeight=scale(35+31*rows);
clampOffset();
InvalidateRect(window,nullptr,FALSE);
}
void updateButtons() const
{
if(!embedded)
if(!embedded && !draft)
{
EnableWindow(buttons[previous-1],position>0);
EnableWindow(buttons[following-1],position+1<images.size());
}
for(unsigned id=zoomOut;id<=actualSize;++id) EnableWindow(buttons[id-1],bitmap!=nullptr);
if(draft)
{
for(unsigned id=rotateLeft;id<=crop;++id) EnableWindow(buttons[id-1],bitmap!=nullptr);
EnableWindow(buttons[undoEdit-1],!draft->undo.empty());
EnableWindow(buttons[saveCopy-1],bitmap!=nullptr);
EnableWindow(buttons[replaceOriginal-1],draft->version && draft->dirty());
const auto title=L"Editor — "+requested.filename().wstring()+(draft->dirty()?L" *":L"");
SetWindowTextW(window,title.c_str());
}
for(auto button:buttons)
if(button) InvalidateRect(button,nullptr,FALSE);
}
void request(const fs::path &path)
void request(const fs::path &path,bool reload=false)
{
if(requested==path) return;
if(requested==path && !reload) return;
requested=path;
++revision;
stop.request_stop();
retried=false;
error.clear();
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
width=height=0;
fit=true;
x=y=0;
if(!embedded)
if(!reload)
{
observedVersion.reset();
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
width=height=0;
fit=true;
x=y=0;
}
if(!embedded && !draft)
{
const auto label=L"Viewer — "+path.filename().wstring();
SetWindowTextW(window,label.c_str());
@@ -134,7 +191,7 @@ struct ImageView
InvalidateRect(window,nullptr,FALSE);
}
void show(ImageRaster image)
void show(const ImageRaster &image)
{
BITMAPINFO info{};
info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
@@ -144,12 +201,16 @@ struct ImageView
info.bmiHeader.biBitCount=32;
info.bmiHeader.biCompression=BI_RGB;
void *bits=nullptr;
bitmap=CreateDIBSection(nullptr,&info,DIB_RGB_COLORS,&bits,nullptr,0);
if(!bitmap || !bits) throw std::runtime_error("Could not display this image.");
const auto next=CreateDIBSection(nullptr,&info,DIB_RGB_COLORS,&bits,nullptr,0);
if(!next || !bits)
{
if(next) DeleteObject(next);
throw std::runtime_error("Could not display this image.");
}
std::memcpy(bits,image.pixels.data(),image.pixels.size()*sizeof(uint32_t));
if(const auto old=std::exchange(bitmap,next)) DeleteObject(old);
width=image.width;
height=image.height;
updateButtons();
}
void poll()
@@ -163,7 +224,20 @@ struct ImageView
try
{
auto image=reading.get();
if(current) show(std::move(image));
if(current)
{
show(image.raster);
observedVersion=image.revision;
if(draft)
{
draft->undo.clear();
draft->version=image.revision;
draft->original=std::move(image.raster);
draft->geometry=draft->saved={{0,0,width,height},0};
}
clampOffset();
updateButtons();
}
}
catch(const std::exception &failure)
{
@@ -191,9 +265,17 @@ struct ImageView
}
stop=std::stop_source{};
started=revision;
std::packaged_task<ImageRaster()> task([path=requested,decoder=retried?retry.load:load,token=stop.get_token()]
std::packaged_task<Loaded()> task([path=requested,decoder=retried?retry.load:load,
token=stop.get_token(),watch=!embedded && !load && isLocalDocumentPath(requested),editing=draft.has_value()]
{
return decoder?decoder(path,token):decodeImage(path,path,token);
if(!watch) return Loaded{decoder?decoder(path,token):decodeImage(path,path,token),{}};
std::optional<ImageRevision> before;
try {before=imageRevision(path);}
catch(const std::exception &) {if(editing) throw;}
auto raster=decodeImage(path,path,token);
if(before && *before!=imageRevision(path))
throw std::runtime_error("The image changed while it was opening. Open it again.");
return Loaded{std::move(raster),before};
});
reading=task.get_future();
try {std::thread(std::move(task)).detach();}
@@ -206,6 +288,18 @@ struct ImageView
}
}
void pollExternal()
{
if(!observedVersion || requested.empty() || reading.valid()) return;
std::optional<ImageRevision> revision;
try {revision=imageRevision(requested);}
catch(const std::exception &) {return;}
if(revision==observedVersion) return;
if(draft && (GetForegroundWindow()!=window || !IsWindowEnabled(window) || !draft->dialogs.reloadChanged)) return;
observedVersion=revision;
if(!draft || draft->dialogs.reloadChanged(window)) request(requested,true);
}
double factor() const
{
if(!fit || !width || !height) return zoom;
@@ -242,9 +336,70 @@ struct ImageView
InvalidateRect(window,nullptr,FALSE);
}
void applyEdit(ImageGeometry next,bool undo)
{
if(next==draft->geometry) return;
auto raster=transformImage(draft->original,next);
if(!undo) draft->undo.push_back(draft->geometry);
try {show(raster);}
catch(...)
{
if(!undo) draft->undo.pop_back();
throw;
}
if(undo) draft->undo.pop_back();
draft->geometry=next;
fit=true;
zoom=1;
x=y=0;
updateButtons();
InvalidateRect(window,nullptr,FALSE);
}
void editAction(UINT id)
{
if(!draft || !bitmap) return;
try
{
if(id==rotateLeft || id==rotateRight)
{
auto next=draft->geometry;
next.turns=(next.turns+(id==rotateLeft?3:1))%4;
applyEdit(next,false);
}
else if(id==crop)
{
if(const auto area=draft->dialogs.crop(window,width,height))
applyEdit(cropImage(draft->geometry,*area),false);
}
else if(id==undoEdit && !draft->undo.empty())
applyEdit(draft->undo.back(),true);
else if(id==saveCopy)
{
const auto destination=draft->dialogs.copyPath(window,requested);
if(destination.empty()) return;
saveImage(transformImage(draft->original,draft->geometry),destination);
}
else if(id==replaceOriginal && draft->dirty() && draft->version &&
draft->dialogs.confirm(window,L"Replace the original image?\r\n\r\n"+requested.native(),L"Replace original"))
{
draft->version=saveImage(transformImage(draft->original,draft->geometry),requested,&*draft->version);
observedVersion=draft->version;
draft->saved=draft->geometry;
updateButtons();
}
}
catch(const std::exception &failure)
{
updateButtons();
draft->dialogs.report(window,wide(failure.what()).c_str());
}
}
void action(UINT id)
{
if(id==previous && position>0) request(images[--position]);
if(id>=rotateLeft && id<=replaceOriginal) editAction(id);
else if(id==previous && position>0) request(images[--position]);
else if(id==following && position+1<images.size()) request(images[++position]);
else if(id==zoomOut || id==zoomIn) changeZoom(id==zoomIn?1.25:0.8);
else if(id==fitImage || id==actualSize)
@@ -354,12 +509,19 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
case WM_CREATE:
{
constexpr const wchar_t *labels[]{L"Previous",L"Next",L"−",L"+",L"Fit",L"100%"};
for(unsigned id=view.embedded?zoomOut:previous;id<=actualSize;++id)
constexpr const wchar_t *labels[]{L"Previous",L"Next",L"−",L"+",L"Fit",L"100%",
L"Rotate left",L"Rotate right",L"Crop…",L"Undo",L"Save copy…",L"Replace…"};
const unsigned first=view.embedded || view.draft?zoomOut:previous;
const unsigned last=view.draft?replaceOriginal:actualSize;
for(unsigned id=first;id<=last;++id)
{
view.buttons[id-1]=CreateWindowW(L"BUTTON",labels[id-1],WS_CHILD|WS_VISIBLE|BS_OWNERDRAW,
0,0,0,0,window,reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),GetModuleHandleW(nullptr),nullptr);
if(!view.buttons[id-1]) return -1;
}
view.layout();
view.updateButtons();
if(!view.embedded && !view.load) SetTimer(window,externalImageTimer,500,nullptr);
return 0;
}
case WM_SIZE: view.layout(); return 0;
@@ -376,7 +538,10 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
case WM_ERASEBKGND: return 1;
case WM_PAINT: view.paint(); return 0;
case WM_DRAWITEM: view.paintButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp)); return TRUE;
case WM_TIMER: if(wp==imageTimer) view.poll(); return 0;
case WM_TIMER:
if(wp==imageTimer) view.poll();
if(wp==externalImageTimer) view.pollExternal();
return 0;
case WM_COMMAND:
if(HIWORD(wp)==BN_CLICKED) {view.action(LOWORD(wp)); SetFocus(window);}
return 0;
@@ -416,15 +581,26 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
return 0;
}
case WM_KEYDOWN:
if(wp==VK_ADD || wp==VK_OEM_PLUS) view.action(zoomIn);
if(view.draft && (GetKeyState(VK_CONTROL)&0x8000) && wp=='Z') view.action(undoEdit);
else if(view.draft && (GetKeyState(VK_CONTROL)&0x8000) && wp=='S')
view.action((GetKeyState(VK_SHIFT)&0x8000)?saveCopy:replaceOriginal);
else if(wp==VK_ADD || wp==VK_OEM_PLUS) view.action(zoomIn);
else if(wp==VK_SUBTRACT || wp==VK_OEM_MINUS) view.action(zoomOut);
else if(wp=='0') view.action(fitImage);
else if(wp=='1') view.action(actualSize);
else if(!view.embedded && (wp==VK_LEFT || wp==VK_PRIOR)) view.action(previous);
else if(!view.embedded && (wp==VK_RIGHT || wp==VK_NEXT)) view.action(following);
else if(!view.embedded && (wp==VK_ESCAPE || wp==VK_F10)) DestroyWindow(window);
else if(!view.embedded && (wp==VK_ESCAPE || wp==VK_F10)) SendMessageW(window,WM_CLOSE,0,0);
else break;
return 0;
case WM_CLOSE:
if(view.confirmingClose || (view.draft && view.draft->dialogs.dismissOwned(window))) return 0;
view.confirmingClose=true;
if(!view.draft || !view.draft->dirty() ||
view.draft->dialogs.confirm(window,L"Discard unsaved image edits?",L"Image editor"))
DestroyWindow(window);
view.confirmingClose=false;
return 0;
case WM_NCDESTROY:
imageViews.erase(found);
if(view.onClose) view.onClose(window);
@@ -435,7 +611,8 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
}
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose,ImageLoadRetry retry)
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose,ImageLoadRetry retry,
const ImageEditDialogs *editor)
{
const auto instance=GetModuleHandleW(nullptr);
static const bool registered=[instance]
@@ -450,6 +627,7 @@ HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<s
if(!registered) return nullptr;
auto state=std::make_shared<ImageView>();
state->embedded=embedded;
if(editor) state->draft.emplace(ImageView::Draft{*editor});
state->style=style;
state->images=std::move(images);
state->load=std::move(load);
@@ -471,4 +649,24 @@ void showImageViewFile(HWND window,const std::filesystem::path &path)
{
if(const auto found=imageViews.find(window);found!=imageViews.end()) found->second->request(path);
}
std::optional<ImageWindowSession> imageWindowSession(HWND window)
{
const auto found=imageViews.find(window);
if(found==imageViews.end()) return {};
const auto &view=*found->second;
if(view.embedded || view.load || !isLocalDocumentPath(view.requested)) return {};
return ImageWindowSession{view.requested,view.draft.has_value(),view.fit,view.zoom,view.x,view.y};
}
void restoreImageWindowSession(HWND window,const ImageWindowSession &state)
{
const auto found=imageViews.find(window);
if(found==imageViews.end()) return;
auto &view=*found->second;
view.fit=state.fit;
view.zoom=std::isfinite(state.zoom)?std::clamp(state.zoom,0.05,32.0):1.0;
view.x=std::isfinite(state.x)?state.x:0;
view.y=std::isfinite(state.y)?state.y:0;
}
}
+25 -2
View File
@@ -1,6 +1,7 @@
#pragma once
#include "files_image_decode.h"
#include "files_image_edit.h"
#include <optional>
#include <windows.h>
#include <functional>
#include <exception>
@@ -22,7 +23,29 @@ struct ImageViewStyle
COLORREF background{}, text{}, toolbar{}, toolbarText{}, selection{};
};
struct ImageEditDialogs
{
std::function<std::optional<ImageRegion>(HWND,unsigned,unsigned)> crop;
std::function<std::filesystem::path(HWND,const std::filesystem::path &)> copyPath;
std::function<bool(HWND,const std::wstring &,const wchar_t *)> confirm;
std::function<void(HWND,const wchar_t *)> report;
std::function<bool(HWND)> dismissOwned;
std::function<bool(HWND)> reloadChanged;
};
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={},ImageLoadRetry retry={});
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={},ImageLoadRetry retry={},
const ImageEditDialogs *editor=nullptr);
void showImageViewFile(HWND window,const std::filesystem::path &path);
struct ImageWindowSession
{
std::filesystem::path path;
bool editor{}, fit=true;
double zoom=1, x{}, y{};
RECT bounds{};
bool maximized{};
};
std::optional<ImageWindowSession> imageWindowSession(HWND window);
void restoreImageWindowSession(HWND window,const ImageWindowSession &state);
}
+397 -71
View File
@@ -41,7 +41,7 @@
#include "files_archive.h"
#include "files_git_changes.h"
#include "files_compare_text.h"
#include "files_image_decode.h"
#include "files_image_view.h"
#include "files_win32_directory.h"
#include "files_win32_replace.h"
#include "files_command_completion.h"
@@ -834,6 +834,11 @@ constexpr DWORD defaultStatusFields=15;
int sizeWidth=defaultSizeWidth;
bool alignExtensions=defaultAlignExtensions, showDetails=defaultShowDetails;
bool alignFolders=defaultAlignFolders;
bool rightClickMarks{}, showDriveButtons{}, compactLayout{}, restoreDocuments{};
constexpr wchar_t rightClickMarksKey[]=L"RightClickMarks", driveButtonsKey[]=L"ShowDriveButtons",
compactLayoutKey[]=L"CompactPanelLayout",restoreDocumentsKey[]=L"RestoreLocalDocuments";
constexpr int firstDriveButton=660, moreDriveButton=firstDriveButton+26;
std::array<HWND,27> driveButtons{};
DWORD statusFields=defaultStatusFields;
std::vector<fs::path> drivePaths;
bool lanDrivePicker{};
@@ -915,6 +920,7 @@ struct FilesNoticeOptions
FilesNoticeTone tone{FilesNoticeTone::dialog};
bool processes{};
bool saveChanges{}, chooseTransfer{};
const wchar_t *accept{}, *decline{};
};
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={});
void openMenu(HWND window, int index);
@@ -1594,6 +1600,8 @@ void swapPanels(HWND window)
}
notifyFilesPreferences(window);
layout(window);
showFileDetails(panels[active]);
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
}
bool hasSelectionSummary()
@@ -1631,7 +1639,12 @@ void layout(HWND window,bool activeOnly)
const bool gitMode=showingGitChanges();
const int terminalBottom=std::max(4,inputTop);
const int summaryHeight=!terminalVisible && hasSelectionSummary()?textHeight:0;
const int detailsHeight=terminalVisible?0:textHeight+12+summaryHeight;
const int detailsInset=compactLayout?2:4;
const int detailsHeight=terminalVisible?0:textHeight+(compactLayout?4:12)+summaryHeight;
const DWORD driveMask=showDriveButtons && !terminalVisible && !gitMode?GetLogicalDrives():0;
const int driveHeight=driveMask?textHeight+2:0;
const int panelMargin=compactLayout?4:5;
const int pathTop=driveHeight+(compactLayout?1:4);
const int terminalTop=terminalVisible?4:std::max(4,terminalBottom-
std::min(terminalRows,std::max(0,(terminalBottom-detailsHeight)/textHeight-4))*textHeight);
const int panelBottom=terminalTop-detailsHeight;
@@ -1645,21 +1658,41 @@ void layout(HWND window,bool activeOnly)
};
if(!activeOnly)
{
const int buttonWidth=std::max(4*cellWidth,32);
const int maxButtons=std::max(1,(width-8)/buttonWidth);
int drives=0;
for(int letter=0;letter<26;++letter) if(driveMask&(1UL<<letter)) ++drives;
const int visibleDrives=drives>maxButtons?maxButtons-1:drives;
int slot=0;
for(int letter=0;letter<26;++letter)
{
const auto button=driveButtons[letter];
if(!button) continue;
const bool visible=(driveMask&(1UL<<letter)) && slot<visibleDrives;
if(visible) place(button,4+slot++*buttonWidth,0,buttonWidth,textHeight);
ShowWindow(button,visible?SW_SHOWNA:SW_HIDE);
}
if(const auto more=driveButtons.back())
{
place(more,4+slot*buttonWidth,0,buttonWidth,textHeight);
ShowWindow(more,drives>maxButtons?SW_SHOWNA:SW_HIDE);
}
const int headingTop=pathTop+textHeight+(compactLayout?2:6);
for (int i = 0; i < 2; ++i)
{
int x = i ? middle + 2 : 0;
int end = i ? width : middle - 2;
place(panels[i].path, x + 5, 4, std::max(0, end - x - 10), textHeight);
place(panels[i].path, x+panelMargin,pathTop,std::max(0,end-x-2*panelMargin),textHeight);
int headingHeight=detailedPanel(panels[i])?textHeight:0;
const int listWidth=std::max(0,end-x-8-scrollBarWidth(panels[i].list));
const int listWidth=std::max(0,end-x-panelMargin-3-scrollBarWidth(panels[i].list));
const bool panelVisible=!gitMode && !terminalVisible && (!quickViewWindow || i==quickViewSource);
ShowWindow(panels[i].path,panelVisible?SW_SHOWNA:SW_HIDE);
ShowWindow(panels[i].list,panelVisible?SW_SHOWNA:SW_HIDE);
place(panels[i].heading,x+5,textHeight+10,listWidth,headingHeight);
place(panels[i].heading,x+panelMargin,headingTop,listWidth,headingHeight);
ShowWindow(panels[i].heading,panelVisible && detailedPanel(panels[i])?SW_SHOWNA:SW_HIDE);
place(panels[i].list, x + 5, textHeight+10+headingHeight,listWidth,
std::max(0, panelBottom-textHeight-10-headingHeight));
place(panels[i].selectionSummary,x+8,panelBottom+4,std::max(0,end-x-16),summaryHeight);
place(panels[i].list,x+panelMargin,headingTop+headingHeight,listWidth,
std::max(0,panelBottom-headingTop-headingHeight));
place(panels[i].selectionSummary,x+8,panelBottom+detailsInset,std::max(0,end-x-16),summaryHeight);
ShowWindow(panels[i].selectionSummary,panelVisible && summaryHeight?SW_SHOWNA:SW_HIDE);
}
place(menuBar,0,0,width,textHeight+4);
@@ -1669,7 +1702,7 @@ void layout(HWND window,bool activeOnly)
}
const int detailsLeft=active?middle+2:0;
const int detailsRight=active?width:middle-2;
place(status,detailsLeft+8,panelBottom+4+summaryHeight,std::max(0,detailsRight-detailsLeft-16),textHeight);
place(status,detailsLeft+8,panelBottom+detailsInset+summaryHeight,std::max(0,detailsRight-detailsLeft-16),textHeight);
const auto &current=panels[active];
const auto prompt=panelLocation(current)+(terminalVisible?L"> ":L">");
SetWindowTextW(terminalPrompt,prompt.c_str());
@@ -1686,7 +1719,13 @@ void layout(HWND window,bool activeOnly)
place(terminalInput,4+promptWidth,inputTop,std::max(0,width-8-promptWidth),textHeight);
if(activeOnly)
{
const RECT details{0,panelBottom+4+summaryHeight,width,panelBottom+4+summaryHeight+textHeight};
const RECT details{0,panelBottom+detailsInset+summaryHeight,width,
panelBottom+detailsInset+summaryHeight+textHeight};
if(driveHeight)
{
const RECT drives{0,0,width,driveHeight};
RedrawWindow(window,&drives,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
}
const RECT commandLine{0,inputTop,width,inputTop+textHeight};
if(!terminalVisible) RedrawWindow(window,&details,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
RedrawWindow(window,&commandLine,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
@@ -1723,8 +1762,9 @@ void layout(HWND window,bool activeOnly)
for(const auto preview:{quickViewWindow,quickImageWindow})
{
if(!preview) continue;
SetWindowPos(preview,nullptr,left+5,4,std::max(0,right-left-10),
std::max(0,panelBottom+summaryHeight+textHeight),SWP_NOZORDER|SWP_NOACTIVATE);
const int bottom=panelBottom+summaryHeight+textHeight+detailsInset;
SetWindowPos(preview,nullptr,left+panelMargin,pathTop,std::max(0,right-left-2*panelMargin),
std::max(0,bottom-pathTop),SWP_NOZORDER|SWP_NOACTIVATE);
const bool current=quickViewDisplaysImage==(preview==quickImageWindow);
ShowWindow(preview,!gitMode && !terminalVisible && current?SW_SHOWNA:SW_HIDE);
}
@@ -3721,6 +3761,7 @@ void collectFolderSizes(Panel &panel)
}
void openSelectedText(const Panel &panel, bool edit, bool external,bool hex=false);
ks::files::ImageEditDialogs imageEditDialogs();
ks::files::TextDialogs textWindowDialogs();
void findPanelFiles(HWND owner,Panel &panel);
void compareSelectedFiles(HWND owner);
@@ -3900,6 +3941,7 @@ void selectDrive()
else if(menuIndex==2 && row==15) showProcesses(owner);
else if(menuIndex==2 && row==16) openGitChanges(owner,panels[active]);
else if(menuIndex==2 && row==17) showEnvironmentPanel(owner);
else if(menuIndex==2 && row==18) swapPanels(owner);
else if(menuIndex==1 && row==4) createArchive(owner,panels[active]);
else if(menuIndex==1 && row==5) showPanelItemProperties(owner,panels[active]);
else if(menuIndex==1 && row==6) showPanelLockProcesses(owner,panels[active]);
@@ -4475,7 +4517,13 @@ ks::files::TextDialogs textWindowDialogs()
{
return showFilesNotice(owner,L"This file is already open. Switch to its window?",L"Files",
{.confirm=true})==IDYES;
},chooseTextSaveOptions};
},chooseTextSaveOptions,
[](HWND owner)
{
return showFilesNotice(owner,L"The file changed outside Files. Reload the disk version?",
L"File changed on disk",{.confirm=true,.tone=FilesNoticeTone::warning,
.accept=L"&Reload",.decline=L"&Keep buffer"})==IDYES;
}};
}
void refreshQuickView(const Panel &panel)
@@ -4605,6 +4653,11 @@ void openSelectedText(const Panel &panel, bool edit, bool external,bool hex)
openPanelFile(panel,path,edit?L"edit":L"open",
edit?L"No editor is registered for this file.":L"Cannot open the selected file.");
else if(!edit && !hex && ks::files::isImagePath(path)) openPanelImage(panel,path);
else if(edit && !hex && !panel.peer && !windowsNetworkPath(path) && ks::files::isEditableImagePath(path))
{
const auto dialogs=imageEditDialogs();
ks::files::openImageWindow(GetParent(panel.list),{path},path,textWindowDialogs(),nullptr,nullptr,&dialogs);
}
else ks::files::openTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),
panel.peer?&*panel.peer:nullptr,{},false,{.hex=hex});
}
@@ -4651,6 +4704,13 @@ struct CopyDestination
bool useSourcePeer{};
};
struct CopyOptions
{
std::wstring mask=L"*";
std::vector<fs::path> additional;
bool preserveTime=true, preservePermissions{};
};
struct CopyRequest
{
std::vector<fs::path> sources;
@@ -4665,6 +4725,7 @@ struct CopyRequest
std::wstring ftpDestination;
bool upload{};
bool ftpRename{}, externalSources{}, archiveSource{};
CopyOptions options;
};
bool directoryExists(const FilesPeer *peer,const fs::path &path)
@@ -5292,6 +5353,9 @@ CopyDestination validateCopyDestination(CopyRequest request,const std::wstring &
return {std::move(request.destination),std::move(request.newName),useSourcePeer};
}
#include "files_copy_options.inl"
#include "files_image_edit_options.inl"
INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
{
constexpr int summary=210, pathField=211, conflicts=212;
@@ -5347,7 +5411,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
SendDlgItemMessageW(dialog,pathField,EM_SETREADONLY,!single && !request.move,0);
if(request.move) SetDlgItemTextW(dialog,IDOK,request.externalSources?L"&Move":L"&Rename");
fitFarEditToLine(GetDlgItem(dialog,pathField));
layoutDialogButtons(dialog,214,{IDOK,IDCANCEL});
layoutDialogButtons(dialog,214,{IDOK,215,IDCANCEL});
installFarCheckbox(GetDlgItem(dialog,214),FarCheckboxSurface::gray);
CheckDlgButton(dialog,214,request.askReadOnly?BST_CHECKED:BST_UNCHECKED);
SendDlgItemMessageW(dialog,summary,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
@@ -5385,7 +5449,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
if(!request.validation.valid() ||
request.validation.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return TRUE;
KillTimer(dialog,validationTimer);
for(const auto control:{pathField,213,214,IDOK}) EnableWindow(GetDlgItem(dialog,control),TRUE);
for(const auto control:{pathField,213,214,215,IDOK}) EnableWindow(GetDlgItem(dialog,control),TRUE);
try
{
auto result=request.validation.get();
@@ -5403,6 +5467,14 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
InvalidateRect(GetDlgItem(dialog,213),nullptr,FALSE);
return FALSE;
}
if(LOWORD(wp)==215)
{
CopyOptionsPrompt options{request.options, request.ftpDestination.empty() && !request.archiveSource, request.move,
request.upload};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(129),dialog,copyOptionsDialog,
reinterpret_cast<LPARAM>(&options))==IDOK) request.options=std::move(options.value);
return TRUE;
}
if(LOWORD(wp)!=IDOK) return FALSE;
if(request.validation.valid()) return TRUE;
try
@@ -5446,7 +5518,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp)
std::thread(std::move(validation)).detach();
request.validation=std::move(ready);
SetFocus(GetDlgItem(dialog,IDCANCEL));
for(const auto control:{pathField,213,214,IDOK}) EnableWindow(GetDlgItem(dialog,control),FALSE);
for(const auto control:{pathField,213,214,215,IDOK}) EnableWindow(GetDlgItem(dialog,control),FALSE);
}
catch(const std::exception &e)
{
@@ -5526,14 +5598,17 @@ struct CopyProgress
std::atomic_bool canceled{};
bool closeOwner{};
bool move{}, fileSourcesOnly{};
bool writingArchive{};
bool writingArchive{}, deferRemoval{};
CopyOptions options;
int conflictChoice{};
ConflictMode conflictMode{};
bool askReadOnly=true;
uint64_t files{}, totalFiles{}, bytes{}, totalBytes{};
uint64_t skippedFiles{}, skippedBytes{};
const wchar_t *lastSkipReason=L"";
ULONGLONG lastPaint{};
ULONGLONG lastPaint{}, sampleStart{}, lastSample{};
uint64_t sampleBytes{}, lastBytes{};
unsigned samples{};
fs::path from,to,renamedTarget;
fs::path localLockSource,localLockTarget;
};
@@ -5599,8 +5674,30 @@ void updateCopyProgress(CopyProgress &progress,uint64_t current,uint64_t fileSiz
SetDlgItemTextW(progress.window,224,(L"Files: "+std::to_wstring(progress.files)+L" / "+
std::to_wstring(progress.totalFiles)+(progress.skippedFiles?
L" Skipped: "+std::to_wstring(progress.skippedFiles)+L" ("+progress.lastSkipReason+L")":L"")).c_str());
SetDlgItemTextW(progress.window,225,(L"Size: "+formatSize(bytes)+L" / "+
formatSize(progress.totalBytes)).c_str());
auto sizeText=L"Size: "+formatSize(bytes)+L" / "+formatSize(progress.totalBytes);
if(!progress.sampleStart || progress.lastPaint-progress.lastSample>1500 || bytes<progress.lastBytes)
{
progress.sampleStart=progress.lastSample=progress.lastPaint;
progress.sampleBytes=progress.lastBytes=bytes;
progress.samples=0;
}
else if(bytes>progress.lastBytes && progress.lastPaint-progress.lastSample>=200)
{
progress.lastSample=progress.lastPaint;
progress.lastBytes=bytes;
++progress.samples;
}
const auto elapsed=progress.lastSample-progress.sampleStart;
const auto accounted=std::min(progress.totalBytes,bytes+progress.skippedBytes);
if(progress.samples>=3 && elapsed>=1200 && bytes>progress.sampleBytes && accounted<progress.totalBytes)
{
const auto estimate=std::ceil((progress.totalBytes-accounted)*(elapsed/1000.0)/(bytes-progress.sampleBytes));
const auto seconds=static_cast<uint64_t>(std::min(estimate,360000000.0));
sizeText+=L" Remaining: "+std::to_wstring(seconds/3600)+L":"+
(seconds%3600/60<10?L"0":L"")+std::to_wstring(seconds%3600/60)+L":"+
(seconds%60<10?L"0":L"")+std::to_wstring(seconds%60);
}
SetDlgItemTextW(progress.window,225,sizeText.c_str());
}
void reportCopyProgress(CopyProgress &progress,uint64_t current,uint64_t fileSize,bool force=false)
@@ -5905,6 +6002,8 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
ShowWindow(GetDlgItem(window,IDYES),SW_SHOW);
ShowWindow(GetDlgItem(window,IDNO),SW_SHOW);
}
if(notice.options.accept) SetDlgItemTextW(window,IDYES,notice.options.accept);
if(notice.options.decline) SetDlgItemTextW(window,IDNO,notice.options.decline);
if(notice.options.saveChanges)
{
SetDlgItemTextW(window,IDYES,L"&Save");
@@ -6299,23 +6398,69 @@ ks::files::RemoteTextSource transferTextSource(const TransferProfile &profile)
return source;
}
bool countCopy(CopyHost &host,const fs::path &path,CopyProgress &progress)
struct CopyNode
{
if(progress.canceled) return false;
fs::path path;
FileInfo info;
std::vector<CopyNode> children;
bool whole=true;
};
std::optional<CopyNode> planCopy(CopyHost &host,const fs::path &path,CopyProgress &progress)
{
if(progress.canceled) throw std::system_error(ERROR_CANCELLED,std::system_category());
const auto info=host.stat(path,progress.canceled);
if(!info || (info->attributes&FILE_ATTRIBUTE_REPARSE_POINT))
throw std::system_error(info?ERROR_NOT_SUPPORTED:ERROR_FILE_NOT_FOUND,std::system_category());
if(progress.fileSourcesOnly && (info->attributes&FILE_ATTRIBUTE_DIRECTORY))
if(!info) throw std::system_error(ERROR_FILE_NOT_FOUND,std::system_category());
const bool directory=info->attributes&FILE_ATTRIBUTE_DIRECTORY;
if(!directory && !matchesFileMask(path.filename().native(),progress.options.mask)) return {};
if(info->attributes&FILE_ATTRIBUTE_REPARSE_POINT)
throw std::system_error(ERROR_NOT_SUPPORTED,std::system_category());
if(progress.fileSourcesOnly && directory)
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
if(!(info->attributes&FILE_ATTRIBUTE_DIRECTORY))
CopyNode node{path,*info,{}};
if(!directory)
{
++progress.totalFiles;
progress.totalBytes+=info->size;
return true;
}
for(const auto &[child,entry]:host.children(path,progress.canceled))
if(!countCopy(host,child,progress)) return false;
return true;
else
{
for(const auto &[child,entry]:host.children(path,progress.canceled))
{
auto item=planCopy(host,child,progress);
node.whole=node.whole && item && item->whole;
if(item) node.children.push_back(std::move(*item));
}
if(node.children.empty() && progress.options.mask!=L"*") return {};
}
return node;
}
void verifyCopyPlan(CopyHost &source,const CopyNode &node,const std::atomic_bool &canceled)
{
if(canceled) throw std::system_error(ERROR_CANCELLED,std::system_category());
const auto current=source.stat(node.path,canceled);
if(!current || current->size!=node.info.size || current->modified!=node.info.modified ||
((current->attributes^node.info.attributes)&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)))
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
for(const auto &child:node.children) verifyCopyPlan(source,child,canceled);
}
void removeCopiedPlan(CopyHost &source,const CopyNode &node,CopyProgress &progress,bool local)
{
if(progress.canceled) throw std::system_error(ERROR_CANCELLED,std::system_category());
const bool directory=node.info.attributes&FILE_ATTRIBUTE_DIRECTORY;
for(const auto &child:node.children) removeCopiedPlan(source,child,progress,local);
if(directory && !node.whole) return;
progress.localLockSource=local?node.path:fs::path{};
progress.localLockTarget.clear();
auto action=fileRequest(directory?"rmdir":"remove",node.path);
if(!directory)
{
action["size"]=node.info.size;
action["modified"]=node.info.modified;
}
checkFileReply(source.request(action));
}
enum class CopyResult { complete, skipped, failed };
@@ -6343,7 +6488,7 @@ void transferFile(const CopyEndpoints &hosts,const fs::path &from,const fs::path
}
if(hosts.target.ftp)
{
uploadTransferFile(*hosts.source.files,*hosts.target.ftp,from,to,info,replace,update);
uploadTransferFile(*hosts.source.files,*hosts.target.ftp,from,to,info,replace,update,nullptr,progress.options.preserveTime);
hosts.target.listedDirectory.clear();
return;
}
@@ -6362,9 +6507,27 @@ void transferFile(const CopyEndpoints &hosts,const fs::path &from,const fs::path
info.size,info.modified,replace,append,update);
}
CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::path &to,CopyProgress &progress,
void applyCopyMetadata(const CopyEndpoints &hosts,const fs::path &to,const FileInfo &info,
const CopyOptions &options,const Json &permissions,bool directory)
{
if(hosts.target.ftp)
{
if(directory && options.preserveTime) hosts.target.ftp->preserveModificationTime(to,info.modified);
return;
}
auto request=fileRequest("applyCopyMetadata",to);
if(directory && options.preserveTime && info.modified && hosts.target.supportsCopyMetadata())
request["modified"]=info.modified;
else if(!directory && !options.preserveTime)
request["modified"]=uint64_t{};
if(!permissions.is_null()) request["permissions"]=permissions;
if(request.size()>2) checkFileReply(hosts.target.request(request));
}
CopyResult copyItem(const CopyEndpoints &hosts,const CopyNode &node,const fs::path &to,CopyProgress &progress,
bool topLevel=false,bool singleItem=false)
{
const auto &from=node.path;
if(progress.canceled) return CopyResult::failed;
if((hosts.source.ftp || hosts.target.ftp) && !validFtpCopyName(to.filename().native(),hosts.target.ftp.has_value()))
throw std::system_error(ERROR_INVALID_NAME,std::system_category());
@@ -6373,12 +6536,21 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
const auto incoming=hosts.source.stat(from,progress.canceled);
if(!incoming || (incoming->attributes&FILE_ATTRIBUTE_REPARSE_POINT))
throw std::system_error(incoming?ERROR_NOT_SUPPORTED:ERROR_FILE_NOT_FOUND,std::system_category());
if(progress.fileSourcesOnly && (incoming->attributes&FILE_ATTRIBUTE_DIRECTORY))
if(((incoming->attributes^node.info.attributes)&FILE_ATTRIBUTE_DIRECTORY) ||
(!(incoming->attributes&FILE_ATTRIBUTE_DIRECTORY) &&
(incoming->size!=node.info.size || incoming->modified!=node.info.modified)))
throw std::system_error(ERROR_FILE_INVALID,std::system_category());
const auto readPermissions=[&] {
if(!progress.options.preservePermissions) return Json(nullptr);
const auto reply=hosts.source.request(fileRequest("copyPermissions",from));
checkFileReply(reply);
return Json(reply.at("permissions"));
};
const auto removeImmediately=progress.move && !progress.deferRemoval;
const auto moveOnHost=[&](const fs::path &target,bool replace)
{
if(!progress.move || !hosts.sameHost) return false;
if(!removeImmediately || !hosts.sameHost) return false;
auto request=fileRequest("move",from);
request["target"]=ks::utf8(target.native());
request["replace"]=replace;
@@ -6399,15 +6571,17 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
progress.bytes=progress.totalBytes;
return CopyResult::complete;
}
const auto permissions=existing?Json(nullptr):readPermissions();
if(!existing) hosts.target.makeDirectory(to);
auto result=CopyResult::complete;
for(const auto &[child,entry]:hosts.source.children(from,progress.canceled))
for(const auto &child:node.children)
{
const auto outcome=copyItem(hosts,child,to/child.filename(),progress);
const auto outcome=copyItem(hosts,child,to/child.path.filename(),progress);
if(outcome==CopyResult::failed) return outcome;
if(outcome==CopyResult::skipped) result=outcome;
}
if(progress.move && result==CopyResult::complete)
if(!existing) applyCopyMetadata(hosts,to,*incoming,progress.options,permissions,true);
if(removeImmediately && result==CopyResult::complete)
{
progress.localLockSource=hosts.sourceLocal?from:fs::path{};
progress.localLockTarget.clear();
@@ -6424,8 +6598,10 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa
if(hosts.targetLocal) progress.localLockTarget=target;
if(!moveOnHost(target,replace))
{
const auto permissions=readPermissions();
transferFile(hosts,from,target,*incoming,replace,append,progress);
if(progress.move)
applyCopyMetadata(hosts,target,*incoming,progress.options,permissions,false);
if(removeImmediately)
{
auto remove=fileRequest("remove",from);
remove["size"]=incoming->size;
@@ -6638,6 +6814,9 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
progress.fileSourcesOnly=fromSearch;
progress.conflictMode=request.conflictMode;
progress.askReadOnly=request.askReadOnly;
progress.options=std::move(request.options);
progress.deferRemoval=move && (progress.options.mask!=L"*" || !progress.options.additional.empty() ||
progress.options.preservePermissions || !progress.options.preserveTime);
FilesModalDialog progressDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(103),owner,
copyProgressDialog,reinterpret_cast<LPARAM>(&progress));
progress.window=progressDialog.window();
@@ -6652,8 +6831,11 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
for(const auto command:commands) EnableWindow(command,FALSE);
progressDialog.show();
bool failed=false, skipped=false;
size_t copied=0;
size_t copied=0, completedCopies=0, requestedCopies=0;
const bool multiple=!progress.options.additional.empty();
bool noMatchingFiles=false;
std::set<fs::path> results, removed;
fs::path failedDestination;
std::wstring failure;
std::vector<fs::path> lockPaths;
try
@@ -6706,43 +6888,103 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
const CopyEndpoints hosts{sourceHost,otherHost?*otherHost:sourceHost,sameHost,
request.sourcePeer?request.sourcePeer->id:"local",!request.sourcePeer && !sourceFtp,
!targetPeer && !destinationFtp};
for(const auto &path:sources)
if(!countCopy(sourceHost,path,progress)) { failed=true; break; }
reportCopyProgress(progress,0,0,true);
std::vector<std::pair<size_t,CopyNode>> plans;
for(size_t i=0;i<sources.size();++i)
if(auto plan=planCopy(sourceHost,sources[i],progress)) plans.emplace_back(i,std::move(*plan));
if(plans.empty()) { noMatchingFiles=true; return; }
const auto canonical=[&](const fs::path &name) {
const auto reply=hosts.target.request(fileRequest("canonical",name));
checkFileReply(reply);
return filePath(reply.at("path"));
};
const auto equalPath=[&](const fs::path &first,const fs::path &second) {
return destinationFtp?first==second:
CompareStringOrdinal(first.c_str(),-1,second.c_str(),-1,TRUE)==CSTR_EQUAL;
};
std::vector<fs::path> folders{targetDirectory};
std::vector<fs::path> locations{destinationFtp?targetDirectory:canonical(targetDirectory)};
for(const auto &folder:progress.options.additional)
{
if(failed) break;
const auto &path=sources[i];
const auto to=targetDirectory/(renamed?request.newName:path.filename());
if(sameHost)
const auto location=destinationFtp?folder:canonical(folder);
if(std::any_of(locations.begin(),locations.end(),[&](const auto &known) {return equalPath(known,location);}))
continue;
const auto info=folder==folder.root_path() && destinationFtp?std::optional<FileInfo>{
FileInfo{FILE_ATTRIBUTE_DIRECTORY,0,0}}:hosts.target.stat(folder,progress.canceled);
if(!info || !(info->attributes&FILE_ATTRIBUTE_DIRECTORY))
{
const auto canonical=[&](const fs::path &name)
failedDestination=folder;
throw std::system_error(ERROR_PATH_NOT_FOUND,std::system_category());
}
folders.push_back(folder);
locations.push_back(location);
}
requestedCopies=plans.size()*folders.size();
progress.totalFiles*=folders.size();
progress.totalBytes*=folders.size();
if(progress.options.preservePermissions &&
(!hosts.source.supportsCopyMetadata() || !hosts.target.supportsCopyMetadata()))
throw std::runtime_error("Update both KSwitcher computers to preserve Windows permissions.");
if(!progress.options.preserveTime && !destinationFtp && !hosts.target.supportsCopyMetadata())
throw std::runtime_error("Update KSwitcher on the destination to set a new modification time.");
if(sameHost)
{
for(const auto &[index,plan]:plans)
{
const auto canonicalSource=canonical(plan.path);
for(const auto &folder:folders)
{
const auto reply=sourceHost.request(fileRequest("canonical",name));
checkFileReply(reply);
return filePath(reply.at("path"));
};
const auto canonicalSource=canonical(path);
const auto canonicalTarget=canonical(to);
for(auto ancestor=canonicalTarget;;ancestor=ancestor.parent_path())
{
if(CompareStringOrdinal(ancestor.c_str(),-1,canonicalSource.c_str(),-1,TRUE)==CSTR_EQUAL)
const auto target=folder/(renamed?request.newName:plan.path.filename());
const auto canonicalTarget=canonical(target);
for(auto ancestor=canonicalTarget;;ancestor=ancestor.parent_path())
{
throw std::system_error(ERROR_INVALID_PARAMETER,std::system_category());
if(equalPath(ancestor,canonicalSource))
{
failedDestination=target;
throw std::system_error(ERROR_INVALID_PARAMETER,std::system_category());
}
if(!ancestor.has_relative_path()) break;
}
if(!ancestor.has_relative_path()) break;
}
}
if(failed) break;
progress.renamedTarget.clear();
const auto outcome=copyItem(hosts,path,to,progress,true,sources.size()==1);
if(outcome==CopyResult::failed) { failed=true; break; }
if(outcome==CopyResult::skipped) { skipped=true; continue; }
}
reportCopyProgress(progress,0,0,true);
for(const auto &[index,plan]:plans)
{
const auto &path=plan.path;
bool allDestinations=true;
fs::path primaryResult;
for(size_t destinationIndex=0;destinationIndex<folders.size();++destinationIndex)
{
if(progress.canceled) return;
const auto to=folders[destinationIndex]/(renamed?request.newName:path.filename());
failedDestination=to;
progress.renamedTarget.clear();
const auto outcome=copyItem(hosts,plan,to,progress,true,plans.size()==1 && folders.size()==1);
if(outcome==CopyResult::failed) { failed=true; return; }
if(outcome==CopyResult::skipped) { skipped=true; allDestinations=false; continue; }
++completedCopies;
if(destinationIndex==0)
{
primaryResult=progress.renamedTarget.empty()?to:progress.renamedTarget;
results.insert(primaryResult);
}
}
if(!allDestinations) continue;
failedDestination.clear();
if(progress.deferRemoval)
{
verifyCopyPlan(sourceHost,plan,progress.canceled);
removeCopiedPlan(sourceHost,plan,progress,hosts.sourceLocal);
if(!plan.whole) skipped=true;
}
if(!primaryResult.empty() && primaryResult.filename()!=path.filename())
progress.renamedTarget=primaryResult;
++copied;
if(move && fromSearch) removed.insert(path);
results.insert(progress.renamedTarget.empty()?to:progress.renamedTarget);
if(!request.externalSources) progress.ui.invoke([&] {
const auto row=std::find(source.rows.begin(),source.rows.end(),request.sources[i]);
if(move && plan.whole && (fromSearch || treePanelActive(source))) removed.insert(path);
if(!request.externalSources && plan.whole) progress.ui.invoke([&] {
const auto row=std::find(source.rows.begin(),source.rows.end(),request.sources[index]);
if(row!=source.rows.end()) markPanelRow(source,row-source.rows.begin(),false);
else if(treePanelActive(source)) source.tree.marks.erase(path);
InvalidateRect(source.list,nullptr,FALSE);
@@ -6764,7 +7006,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
catch(const std::exception &e)
{
failed=true;
failure=archive.empty()?L"File connection interrupted.":ks::wide(e.what());
failure=ks::wide(e.what());
}
const auto targetId=peerId(targetPeer);
const bool restoreFocus=GetForegroundWindow()==progress.window;
@@ -6824,9 +7066,24 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve
SetForegroundWindow(owner);
SetFocus(panels[active].list);
}
const auto outcomeText=[&] {
auto text=std::to_wstring(completedCopies)+L" of "+std::to_wstring(requestedCopies)+
L" item copies completed across the requested folders. "+std::to_wstring(progress.files)+L" files copied.";
if(move) text+=L" Sources were removed only after their requested copies completed.";
return text;
};
if(failed && !progress.canceled)
{
if(failure.empty()) failure=L"Could not complete the operation.";
if(!failedDestination.empty()) failure+=L"\r\n\r\nDestination: "+failedDestination.native();
if(multiple && requestedCopies) failure+=L"\r\n\r\n"+outcomeText();
showFileOperationError(owner,ftpRename?L"Rename failed":move?L"Move failed":L"Copy failed",
failure.empty()?L"Could not complete the operation.":failure,std::move(lockPaths));
failure,std::move(lockPaths));
}
else if(noMatchingFiles)
setStatus(L"No files match the copy mask.");
else if(multiple)
setStatus((progress.canceled?L"Canceled. ":skipped?L"Finished with skipped copies. ":L"")+outcomeText());
else if(ftpRename)
setStatus(copied?L"Rename complete.":L"Rename canceled.");
else if(move)
@@ -7675,6 +7932,27 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
if(message==WM_RBUTTONUP)
{
POINT screen{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
if(rightClickMarks && !(wp&MK_SHIFT) && commandLineAvailable(GetParent(window)))
{
auto &panel=panels[index];
const auto row=panelRowAt(window,screen,SendMessageW(window,LB_GETTOPINDEX,0,0),panel.rows.size());
if(row!=LB_ERR && panel.sizes[row]!=L"Up" && !transferProfileList(panel))
{
closePanelSearch();
SetFocus(window);
activatePanel(index);
panelClipboardContext=true;
clearTerminalSelection();
const auto previous=currentPanelRow(panel);
SendMessageW(window,LB_SETCURSEL,row,0);
markPanelRow(panel,row,!panel.marked[row]);
invalidatePanelRow(window,row);
if(previous!=row) invalidatePanelRow(window,previous);
updateSelectionSummary(panel);
showFileDetails(panel);
return 0;
}
}
ClientToScreen(window,&screen);
showPanelContextMenu(window,MAKELPARAM(screen.x,screen.y));
return 0;
@@ -7897,6 +8175,10 @@ bool loadFilesPreferences(HWND window)
alignExtensions=preference(L"AlignExtensions",defaultAlignExtensions)!=0;
showDetails=preference(L"ShowDetails",defaultShowDetails)!=0;
alignFolders=preference(L"AlignFolders",defaultAlignFolders)!=0;
rightClickMarks=preference(rightClickMarksKey,0)!=0;
showDriveButtons=preference(driveButtonsKey,0)!=0;
compactLayout=preference(compactLayoutKey,0)!=0;
restoreDocuments=preference(restoreDocumentsKey,0)!=0;
statusFields=preference(L"StatusFields",defaultStatusFields)&15;
loadCommandHistoryKeys();
loadComparisonShortcut();
@@ -7962,7 +8244,7 @@ void openMenu(HWND window, int index)
L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel(),
L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q",
L"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3",L"Viewer bookmarks…",L"Processes…",
L"Git Changes…",L"Environment Variables…"};
L"Git Changes…",L"Environment Variables…",L"Swap panels\tCtrl+U"};
}
const auto &panel=panels[active];
const bool remoteResults=remoteSearchResults(panel);
@@ -7988,6 +8270,7 @@ void openMenu(HWND window, int index)
else if(index==2)
{
commandActions={0,3,11,-1,1,13,14,2,4,5,8};
if(!terminalVisible) commandActions.insert(commandActions.begin()+1,18);
if(!terminalVisible) commandActions.push_back(15);
if(gitChangesAvailable(panel)) commandActions.push_back(16);
if(!terminalVisible) commandActions.push_back(17);
@@ -8366,6 +8649,13 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
for (int i = 0; i < static_cast<int>(std::size(commands)); ++i)
commands[i] = CreateWindowW(L"BUTTON", keyBar[i].label, WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
0, 0, 0, 0, window, reinterpret_cast<HMENU>(static_cast<INT_PTR>(keyBar[i].id)), instance, nullptr);
for(int i=0;i<static_cast<int>(driveButtons.size());++i)
{
const wchar_t letter[]{static_cast<wchar_t>(L'A'+i),L':',0};
driveButtons[i]=CreateWindowW(L"BUTTON",i==26?L"…":letter,WS_CHILD|BS_OWNERDRAW|WS_CLIPSIBLINGS,
0,0,0,0,window,reinterpret_cast<HMENU>(static_cast<INT_PTR>(firstDriveButton+i)),instance,nullptr);
if(!driveButtons[i]) return -1;
}
for (int i = 0; i < 2; ++i)
{
auto &panel = panels[i];
@@ -8409,6 +8699,13 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
return 0;
}
case WM_DEVICECHANGE:
if(showDriveButtons)
{
layout(window);
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
}
break;
case WM_SIZE:
hideCompletion();
hidePicker();
@@ -8489,7 +8786,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
GetWindowRect(status,&details);
MapWindowPoints(nullptr,window,reinterpret_cast<POINT*>(&details),2);
const RECT divider{box.left+1,box.bottom-2,box.right-1,box.bottom-1};
box.bottom=std::max(box.bottom,details.bottom+6);
box.bottom=std::max(box.bottom,details.bottom+(compactLayout?2:6));
FrameRect(dc,&box,border);
if(IsWindowVisible(panel.list)) paintScrollPosition(window,dc,panel.list,colors[PanelBlue]);
InflateRect(&box,-3,-3);
@@ -8661,6 +8958,21 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
GetWindowTextW(item.hwndItem,label,64);
text=label;
}
if(item.CtlID>=firstDriveButton && item.CtlID<=moreDriveButton)
{
const auto &panel=panels[active];
const auto drive=panel.directory.root_name().native();
const bool selected=item.CtlID!=moreDriveButton && !panel.peer && !panel.ftp && !panel.archive &&
drive.size()==2 && towupper(drive.front())==L'A'+item.CtlID-firstDriveButton;
auto bounds=item.rcItem;
FillRect(item.hDC,&bounds,selected?teal:blue);
SelectObject(item.hDC,mono);
SetBkMode(item.hDC,TRANSPARENT);
SetTextColor(item.hDC,colors[selected?Text:Frame]);
DrawTextW(item.hDC,text.c_str(),-1,&bounds,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX);
if(item.itemState&ODS_FOCUS) DrawFocusRect(item.hDC,&bounds);
return TRUE;
}
if(std::find(std::begin(commands),std::end(commands),item.hwndItem)!=std::end(commands))
{
if(item.CtlID==114 && remoteSearchResults(panels[active]) && panels[active].ftp)
@@ -8950,6 +9262,18 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
}
return 0;
}
if(HIWORD(wp)==BN_CLICKED && LOWORD(wp)>=firstDriveButton && LOWORD(wp)<=moreDriveButton)
{
const auto id=LOWORD(wp);
if(id==moreDriveButton) chooseDrive(active);
else
{
const wchar_t root[]{static_cast<wchar_t>(L'A'+id-firstDriveButton),L':',L'\\',0};
openOn(panels[active],root,false,{});
restoreCommandFocus();
}
return 0;
}
if(LOWORD(wp)==121 && HIWORD(wp)==LBN_DBLCLK) selectDrive();
if(LOWORD(wp)>=130 && LOWORD(wp)<=134 && HIWORD(wp)==BN_CLICKED)
{
@@ -8985,6 +9309,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
return 0;
}
savePlacement(window);
ks::files::saveLocalDocumentSession(schemeKey,restoreDocuments);
for(int i=0;i<2;++i)
{
saveFtpPanelLocation(panels[i],i);
@@ -9093,6 +9418,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
}
if(!restorePlacement(window)) ShowWindow(window, show);
SetFocus(terminalInput);
if(restoreDocuments) ks::files::restoreLocalDocumentSession(window,textWindowDialogs(),schemeKey,imageEditDialogs());
MSG message{};
for(;;)
{
+29 -2
View File
@@ -11,7 +11,8 @@ constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Pop
L"Menu selection",L"Command bar",L"File cursor"};
enum PanelSection { PanelLayout, WideColumns, StatusColumns };
constexpr const wchar_t *panelSectionNames[]{L"Panel layout",L"Wide panel columns",L"Status line columns"};
constexpr int panelLayoutControls[]{506,273,507,274};
constexpr int rightClickMarksControl=520, driveButtonsControl=521, compactLayoutControl=522;
constexpr int panelLayoutControls[]{506,273,507,274,rightClickMarksControl,driveButtonsControl,compactLayoutControl,523};
constexpr int wideColumnControls[]{275,276,201,202,204};
constexpr int statusColumnControls[]{277,203,205,206,207,208};
constexpr int colorOptionControls[]{279,280};
@@ -19,6 +20,7 @@ constexpr int appearanceControls[]{281,282};
enum AppearanceSection { Font, DialogFrame };
constexpr int outerFramePadding=303,innerFramePadding=305,rowTextPadding=307;
constexpr int dialogFrameControls[]{302,outerFramePadding,304,innerFramePadding,306,rowTextPadding};
constexpr int restoreDocumentsControl=524;
constexpr int textTabWidth=357,textLineEnding=359,
textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368;
constexpr int textControls[]{350,351,352,353,356,textTabWidth,
@@ -67,6 +69,9 @@ struct PanelProperty
};
constexpr PanelProperty panelProperties[]{
{PanelLayout,273,L"Left panel mode",defaultWide?1u:0u},{PanelLayout,274,L"Right panel mode",defaultWide?1u:0u},
{PanelLayout,rightClickMarksControl,L"Mark items with the right mouse button",0},
{PanelLayout,driveButtonsControl,L"Show drive buttons",0},
{PanelLayout,compactLayoutControl,L"Compact commander layout",0},
{WideColumns,201,L"Size column width",defaultSizeWidth},
{WideColumns,202,L"Align file extensions",defaultAlignExtensions},
{WideColumns,204,L"Align folder extensions",defaultAlignFolders},
@@ -107,6 +112,8 @@ struct OptionsBaseline
bool remoteUpdate=ks::lan::remoteUpdateAllowed();
DWORD width=static_cast<DWORD>(sizeWidth), fields=statusFields;
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
bool mouseMarks=rightClickMarks, drives=showDriveButtons, compact=compactLayout;
bool restoreLocal=restoreDocuments;
std::array<PanelMode,2> modes{panels[0].mode,panels[1].mode};
ks::files::TextSettings text=ks::files::loadTextPreferences();
ComparisonAppearance comparison=readComparisonAppearance();
@@ -181,6 +188,8 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
const bool dirty=!valid || draft.markdownError || width!=base.width ||
panelModeOption(dialog,0)!=base.modes[0] || panelModeOption(dialog,1)!=base.modes[1] ||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
checked(rightClickMarksControl)!=base.mouseMarks || checked(driveButtonsControl)!=base.drives ||
checked(compactLayoutControl)!=base.compact || checked(restoreDocumentsControl)!=base.restoreLocal ||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
@@ -501,6 +510,7 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
show(commandLineControls,page==CommandLine && section==0);
show(markdownControls,markdown);
show(textControls,textOptionsPage(page) && !markdown);
ShowWindow(GetDlgItem(dialog,restoreDocumentsControl),page==TextViewer && !markdown?SW_SHOW:SW_HIDE);
show(editingControls,page==TextEditor);
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]);
const bool fileTypes=page==PanelColors && section==fileStyleSection;
@@ -611,6 +621,7 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
const bool propertyMatches=matches(L"Tab width") ||
matches(L"Color scheme") || matches(L"Save scheme") || matches(L"Customize colors") ||
(page==TextEditor && matches(L"Line endings for new lines")) ||
(page==TextViewer && matches(L"Restore local Viewer and Editor windows after restart")) ||
std::any_of(std::begin(textChecks),std::end(textChecks),[&](const auto &check)
{return (page==TextEditor || check.id<354) && matches(check.name);}) ||
std::any_of(std::begin(ks::files::textColorNames),std::end(ks::files::textColorNames),matches);
@@ -679,6 +690,10 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments);
showPanelModeOptions(dialog);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
setOptionHistoryKeys(dialog,commandHistoryKeys);
@@ -875,6 +890,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=Font))
draft->framePadding=defaultDialogFramePadding;
if(draft->page==allOptions || (draft->page==TextViewer && draft->section!=markdownSection))
CheckDlgButton(dialog,restoreDocumentsControl,BST_UNCHECKED);
if(draft->page==allOptions || textOptionsPage(draft->page))
for(int page=TextViewer;page<=TextEditor;++page)
if(draft->page==allOptions || (draft->page==page && draft->section!=markdownSection))
@@ -898,7 +915,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
}
case 201:
case 202: case 203: case 204: case 205: case 206: case 207: case 208:
case 273: case 274: case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
case 273: case 274: case rightClickMarksControl: case driveButtonsControl: case compactLayoutControl:
case restoreDocumentsControl:
case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
updateOptionsApply(dialog,*draft);
return TRUE;
case 321: case 323: case comparisonShortcutControl:
@@ -1050,6 +1069,10 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
saveChanged(L"AlignExtensions",checked(202),base.extensions);
saveChanged(L"AlignFolders",checked(204),base.folders);
saveChanged(L"ShowDetails",checked(203),base.details);
saveChanged(rightClickMarksKey,checked(rightClickMarksControl),base.mouseMarks);
saveChanged(driveButtonsKey,checked(driveButtonsControl),base.drives);
saveChanged(compactLayoutKey,checked(compactLayoutControl),base.compact);
saveChanged(restoreDocumentsKey,checked(restoreDocumentsControl),base.restoreLocal);
DWORD fields=preference(L"StatusFields",defaultStatusFields)&15;
const auto initialFields=fields;
for(int i=0;i<4;++i)
@@ -1092,6 +1115,10 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
CheckDlgButton(dialog,202,alignExtensions);
CheckDlgButton(dialog,203,showDetails);
CheckDlgButton(dialog,204,alignFolders);
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments);
showPanelModeOptions(dialog);
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
setOptionHistoryKeys(dialog,commandHistoryKeys);
+18
View File
@@ -388,6 +388,24 @@ public:
if(libssh2_sftp_mkdir(sftp_.get(),name.c_str(),0755)) operationError("Could not create the SFTP folder");
}
void preserveModificationTime(const fs::path &path,uint64_t modified) const
{
constexpr uint64_t ticks=10000000, windowsEpoch=11644473600;
if(modified/ticks<windowsEpoch || modified/ticks-windowsEpoch>UINT32_MAX) return;
requireWriteAccess();
const auto name=encode(path);
LIBSSH2_SFTP_ATTRIBUTES attributes{};
if(libssh2_sftp_lstat(sftp_.get(),name.c_str(),&attributes))
operationError("Could not read the staged file timestamps");
const auto seconds=static_cast<unsigned long>(modified/ticks-windowsEpoch);
if(!(attributes.flags&LIBSSH2_SFTP_ATTR_ACMODTIME)) attributes.atime=seconds;
attributes.flags=LIBSSH2_SFTP_ATTR_ACMODTIME;
attributes.mtime=seconds;
if(libssh2_sftp_setstat(sftp_.get(),name.c_str(),&attributes) &&
libssh2_sftp_last_error(sftp_.get())!=LIBSSH2_FX_OP_UNSUPPORTED)
operationError("Could not preserve the SFTP modification time");
}
void remove(const fs::path &path,bool directory) const
{
requireWriteAccess();
+71 -25
View File
@@ -42,7 +42,7 @@ HANDLE openSource(const std::filesystem::path &path, bool editable)
HANDLE trackReplacement(const std::filesystem::path &path)
{
// A metadata-only handle survives the rename without blocking ReplaceFile.
const auto handle=CreateFileW(path.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
const auto handle=CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if(handle==INVALID_HANDLE_VALUE) fail("Track replacement file");
return handle;
@@ -90,15 +90,6 @@ bool sameFile(HANDLE a, HANDLE b)
return sameFileIdentity(first,second);
}
std::filesystem::path temporaryPath(const std::filesystem::path &directory)
{
GUID id{};
wchar_t name[40]{};
if (FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id, name, 40))
throw std::runtime_error("Cannot create a temporary file name.");
return directory / (std::wstring(L".kswitcher-") + name + L".tmp");
}
std::filesystem::path createTemporary(const std::filesystem::path &directory, File &file, DWORD flags)
{
auto path = temporaryPath(directory);
@@ -107,6 +98,11 @@ std::filesystem::path createTemporary(const std::filesystem::path &directory, Fi
return path;
}
void createEditorSnapshot(File &file)
{
createTemporary(std::filesystem::temp_directory_path(),file,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE);
}
bool isUtf16(TextEncoding encoding)
{
return encoding==TextEncoding::utf16le || encoding==TextEncoding::utf16be;
@@ -133,6 +129,18 @@ std::wstring decodeMultibyte(std::string_view bytes,UINT codePage,DWORD flags)
return units;
}
std::string encodeUtf8(std::wstring_view units)
{
if(units.empty()) return {};
const auto length=static_cast<int>(units.size());
const int required=WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,units.data(),length,nullptr,0,nullptr,nullptr);
if(!required) fail("Decode UTF-16");
std::string result(required,'\0');
if(!WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,units.data(),length,result.data(),required,nullptr,nullptr))
fail("Decode UTF-16");
return result;
}
std::string encode(std::string_view utf8,TextEncoding encoding)
{
if(encoding==TextEncoding::utf8 || utf8.empty()) return std::string(utf8);
@@ -179,8 +187,8 @@ std::string convertLineEndings(std::string_view text,TextLineEnding ending)
}
}
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding)
: path_(std::move(path)), editable_(editable)
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding,bool snapshotEdits)
: path_(std::move(path)), editable_(editable),snapshotEdits_(snapshotEdits && editable)
{
if(path_.empty())
{
@@ -210,7 +218,20 @@ TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding
encoding_=encoding;
if(prefix.starts_with(signature(encoding_))) bom_=signature(encoding_).size();
if(isUtf16(encoding_) && size_%2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
source_ = source.release();
if(snapshotEdits_)
{
version_=fileVersion(source.handle);
File snapshot;
createEditorSnapshot(snapshot);
for(uint64_t offset=0;offset<size_;)
{
const auto block=read(source.handle,offset,static_cast<size_t>(std::min(pageBytes,size_-offset)));
write(snapshot.handle,block);
offset+=block.size();
}
source_=snapshot.release();
}
else source_ = source.release();
}
TextDocument::~TextDocument()
@@ -289,13 +310,7 @@ std::string TextDocument::decode(std::string bytes) const
units[i] = static_cast<wchar_t>(encoding_ == TextEncoding::utf16le ? a | (b << 8) : (a << 8) | b);
}
}
const auto length = static_cast<int>(units.size());
const int required = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, nullptr, 0, nullptr, nullptr);
if (!required) fail("Decode UTF-16");
std::string result(required, '\0');
if (!WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, result.data(), required, nullptr, nullptr))
fail("Decode UTF-16");
return result;
return encodeUtf8(units);
}
std::string TextDocument::readPage(uint64_t page) const
@@ -377,6 +392,15 @@ std::string formatHexAddress(uint64_t offset)
return address;
}
std::string formatBinarySymbols(std::string_view bytes)
{
if(bytes.empty()) return {};
auto symbols=decodeMultibyte(bytes,437,0);
for(size_t i=0;i<bytes.size();++i)
if(const auto marker=binarySymbolMarker(static_cast<unsigned char>(bytes[i]))) symbols[i]=marker;
return encodeUtf8(symbols);
}
std::string formatHexPage(std::string_view bytes,uint64_t offset)
{
constexpr char digits[]="0123456789ABCDEF";
@@ -461,13 +485,26 @@ void TextDocument::stage(uint64_t page, std::string_view utf8)
bool TextDocument::save()
{
if (!modified()) return true;
const auto verify=[&](HANDLE current) {
if(version_ && *version_!=fileVersion(current))
throw std::runtime_error("The file changed outside Files. Your editor buffer was kept.");
if(!version_ && !sameFile(source_,current))
throw std::runtime_error("The file was replaced outside KSwitcher.");
};
if(version_)
{
File current{openSource(path_,true)};
verify(current.handle);
}
PendingSave pending;
File output;
File output,snapshot;
if(snapshotEdits_) createEditorSnapshot(snapshot);
pending.path = createTemporary(path_.parent_path(), output, FILE_ATTRIBUTE_NORMAL);
uint64_t written{};
const auto append = [&](std::string_view bytes) {
write(output.handle, bytes);
if(snapshotEdits_) write(snapshot.handle,bytes);
written += bytes.size();
};
const auto copyUntil = [&](uint64_t &offset, uint64_t end) {
@@ -491,7 +528,7 @@ bool TextDocument::save()
File replacement{trackReplacement(pending.path)};
File current{openSource(path_, true)};
if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher.");
verify(current.handle);
const auto backup = temporaryPath(path_.parent_path());
if (const auto error=replaceFileWithBackup(path_,pending.path,backup))
{
@@ -499,7 +536,9 @@ bool TextDocument::save()
fail("Replace original file");
}
pending.path.clear();
const auto newSource = ReOpenFile(replacement.handle, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, 0);
if(snapshotEdits_) version_=fileVersion(replacement.handle);
const auto newSource=snapshotEdits_?snapshot.release():
ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
DeleteFileW(backup.c_str());
CloseHandle(source_);
source_ = newSource;
@@ -517,10 +556,16 @@ bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
const auto bytes=encode(convertLineEndings(readPage(0),format.lineEnding),format.encoding);
const auto bom=format.bom?signature(format.encoding):std::string_view{};
PendingSave pending;
File output;
File output,snapshot;
pending.path=createTemporary(path.parent_path(),output,FILE_ATTRIBUTE_NORMAL);
write(output.handle,bom);
write(output.handle,bytes);
if(snapshotEdits_)
{
createEditorSnapshot(snapshot);
write(snapshot.handle,bom);
write(snapshot.handle,bytes);
}
if(!FlushFileBuffers(output.handle)) fail("Flush saved file");
CloseHandle(output.release());
File replacement{trackReplacement(pending.path)};
@@ -533,7 +578,8 @@ bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
changes_.clear();
if(spool_!=INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_,INVALID_HANDLE_VALUE));
spoolSize_=0;
source_=ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
if(snapshotEdits_) version_=fileVersion(replacement.handle);
source_=snapshotEdits_?snapshot.release():ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
return source_!=INVALID_HANDLE_VALUE;
}
}
+10 -3
View File
@@ -1,6 +1,6 @@
#pragma once
#include <windows.h>
#include "files_win32_replace.h"
#include <cstdint>
#include <filesystem>
#include <map>
@@ -17,6 +17,11 @@ enum class TextLineEnding { preserve, crlf, lf, cr };
inline constexpr uint64_t hexPageBytes=64*1024;
std::string formatHexAddress(uint64_t offset);
std::string formatHexPage(std::string_view bytes,uint64_t offset);
constexpr wchar_t binarySymbolMarker(unsigned char byte)
{
return byte<0x20 || byte==0x7f || byte==0xff || byte=='\\' ? static_cast<wchar_t>(0xe000+byte) : 0;
}
std::string formatBinarySymbols(std::string_view bytes);
struct TextSaveFormat
{
@@ -38,7 +43,7 @@ public:
static constexpr size_t editLimit = 8 * pageBytes;
explicit TextDocument(std::filesystem::path path, bool editable = true,
TextEncoding encoding=TextEncoding::automatic);
TextEncoding encoding=TextEncoding::automatic,bool snapshotEdits=false);
~TextDocument();
TextDocument(const TextDocument &) = delete;
TextDocument &operator=(const TextDocument &) = delete;
@@ -58,6 +63,7 @@ public:
bool saveNew(std::filesystem::path path, TextSaveFormat format);
const wchar_t *encodingName() const;
TextEncoding encoding() const { return encoding_; }
const std::optional<LocalFileVersion> &expectedVersion() const {return version_;}
private:
struct Change { uint64_t offset; size_t size; };
@@ -68,7 +74,8 @@ private:
uint64_t size_{}, spoolSize_{};
size_t bom_{};
TextEncoding encoding_ = TextEncoding::utf8;
bool editable_;
bool editable_, snapshotEdits_;
std::optional<LocalFileVersion> version_;
std::map<uint64_t, Change> changes_;
std::string decode(std::string bytes) const;
+352 -56
View File
@@ -776,7 +776,7 @@ public:
{
if (backend) remote=std::make_unique<RemoteTextFile>(*backend,original);
else if(!embedded) document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,
hex?TextEncoding::utf8:options.encoding);
hex?TextEncoding::utf8:options.encoding,isLocalDocumentPath(original));
if(options.encoding!=TextEncoding::automatic)
{
newFormat.encoding=options.encoding;
@@ -800,12 +800,14 @@ public:
if(smallIcon) DestroyIcon(smallIcon);
if(largeIcon) DestroyIcon(largeIcon);
}
HWND window{}, editor{};
HWND window{}, editor{}, quickModeButton{};
bool handleKey(const MSG &message);
void goToFragment(std::string_view fragment);
void previewFile(const std::filesystem::path &path);
void previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff);
bool openBookmark(const ViewerBookmark &bookmark);
nlohmann::json sessionState() const;
void restoreSession(const nlohmann::json &state);
std::filesystem::path original;
const std::string peerId;
@@ -860,13 +862,8 @@ private:
bool previewWanted{}, previewVisible{}, previewRetried{};
ULONGLONG previewDeadline{};
ULONGLONG nextFileCheck{};
struct FileStamp
{
uint64_t writeTime, fileIndex, size;
DWORD volume;
bool operator==(const FileStamp &) const = default;
};
std::optional<FileStamp> previewStamp;
std::optional<LocalFileVersion> previewStamp, observedVersion;
bool diskChanged{};
struct MarkdownTask
{
uint64_t revision;
@@ -875,6 +872,8 @@ private:
};
std::string previewText;
uint64_t previewRevision{};
int renderedScroll{};
std::optional<int> sessionScroll;
std::optional<MarkdownTask> pendingTask;
std::optional<size_t> taskOffset;
std::string previewFragment;
@@ -918,6 +917,7 @@ private:
static constexpr UINT_PTR quickViewTimer = 5;
static constexpr UINT_PTR bookmarkTimer = 6;
static constexpr UINT_PTR savedViewerTimer = 7;
static constexpr UINT_PTR externalChangeTimer = 8;
struct BookmarkLocation
{
std::filesystem::path path;
@@ -928,11 +928,14 @@ private:
};
std::future<BookmarkLocation> bookmarkTask;
std::stop_source bookmarkStop;
enum class QuickKind { text, html, binary };
struct QuickDocument
{
std::unique_ptr<TextDocument> document;
std::string firstPage;
std::optional<std::string> markdown;
std::optional<std::string> previewCode;
QuickKind kind{};
size_t binaryBytes{};
};
std::future<QuickDocument> quickLoading;
std::filesystem::path quickPath;
@@ -941,7 +944,13 @@ private:
uint64_t quickRequest{}, quickReading{};
ULONGLONG quickReadyAt{};
std::wstring quickError;
std::optional<std::string> quickMarkdown;
std::optional<std::string> quickPreviewCode;
QuickKind quickKind{};
bool quickHtmlRendered{}, binaryRepresentations{};
size_t quickBinaryBytes{};
static constexpr int quickModeControl=159;
void applySourceLayoutOptions();
void toggleQuickHtml();
void pollQuickView();
static constexpr UINT trimUndo = WM_APP + 1;
static constexpr UINT previewFailed = WM_APP + 2;
@@ -1003,7 +1012,7 @@ private:
void changeMode();
ViewerPosition currentPosition() const;
void restorePosition(const ViewerPosition &position);
void showTextMode(const ViewerPosition &position,std::string contents);
void showTextMode(const ViewerPosition &position,std::string contents,bool takeFocus=true);
void suspendEditor(std::unique_ptr<RemoteTextFile> saved={});
void restoreEditor();
void finishSavedViewer();
@@ -1015,7 +1024,9 @@ private:
void stopPreview(bool refresh=true,bool keepBrowser=false);
void renderPreview(bool keepPosition=false);
void applyMarkdownPreferences(const MarkdownPreferences &preferences);
std::optional<FileStamp> previewFileStamp() const;
std::optional<LocalFileVersion> previewFileStamp() const;
void rememberLocalVersion();
void pollExternalChanges();
void refreshPreview();
void startMarkdownTask();
void finishMarkdownTask();
@@ -1371,19 +1382,44 @@ void TextWindow::applyPreferences()
send(SCI_SETUSETABS, !prefs.tabsAsSpaces);
send(SCI_SETTABINDENTS, TRUE);
send(SCI_SETBACKSPACEUNINDENTS, TRUE);
send(SCI_SETWRAPMODE, !hex && prefs.wrap ? SC_WRAP_WORD : SC_WRAP_NONE);
send(SCI_SETVIEWWS, !hex && prefs.whitespace ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE);
send(SCI_SETVIEWEOL, !hex && prefs.whitespace);
applySourceLayoutOptions();
applyLineEnding();
updateLineNumberMargin();
layout();
invalidate();
}
void TextWindow::applySourceLayoutOptions()
{
const bool binary=embedded && quickKind==QuickKind::binary;
if(std::exchange(binaryRepresentations,binary)!=binary)
{
constexpr char digits[]="0123456789ABCDEF";
for(int byte=0;byte<256;++byte)
{
const auto marker=binarySymbolMarker(static_cast<unsigned char>(byte));
if(!marker) continue;
const auto key=utf8(std::wstring(1,marker));
const auto index=reinterpret_cast<WPARAM>(key.c_str());
if(binary)
{
const char value[]{'\\','x',digits[byte>>4],digits[byte&15],0};
send(SCI_SETREPRESENTATION,index,reinterpret_cast<LPARAM>(byte=='\\'?"\\\\":value));
send(SCI_SETREPRESENTATIONAPPEARANCE,index,SC_REPRESENTATION_PLAIN);
}
else send(SCI_CLEARREPRESENTATION,index);
}
}
send(SCI_SETWRAPMODE,binary?SC_WRAP_CHAR:!hex && prefs.wrap?SC_WRAP_WORD:SC_WRAP_NONE);
send(SCI_SETHSCROLLBAR,!binary);
send(SCI_SETVIEWWS,!binary && !hex && prefs.whitespace?SCWS_VISIBLEALWAYS:SCWS_INVISIBLE);
send(SCI_SETVIEWEOL,!binary && !hex && prefs.whitespace);
}
void TextWindow::updateLineNumberMargin()
{
LRESULT width{};
if (prefs.numbers && !hex)
if (prefs.numbers && !hex && (!embedded || quickKind!=QuickKind::binary))
{
const auto digits = std::to_string(send(SCI_GETLINECOUNT)).size();
const std::string sample(digits, '9');
@@ -1591,6 +1627,7 @@ void TextWindow::go(uint64_t index)
void TextWindow::initializeDocument(std::optional<std::string> firstPage)
{
rememberLocalVersion();
if(hex)
{
releaseMenu();
@@ -1601,8 +1638,9 @@ void TextWindow::initializeDocument(std::optional<std::string> firstPage)
return;
}
if(!firstPage) firstPage=document->readPage(0);
automatic=detectLanguage(original,*firstPage);
automatic=embedded && quickKind==QuickKind::binary?TextLanguage{}:detectLanguage(original,*firstPage);
language=automatic;
if(embedded) applySourceLayoutOptions();
if(canPreview()) ShowWindow(editor,SW_HIDE);
if(!embedded)
{
@@ -1633,7 +1671,10 @@ void TextWindow::previewFile(const std::filesystem::path &path)
quickReadyAt=GetTickCount64()+80;
stopPreview(false,true);
document.reset();
quickMarkdown.reset();
quickPreviewCode.reset();
quickKind=QuickKind::text;
quickHtmlRendered=false;
quickBinaryBytes=0;
quickError.clear();
layout();
SetTimer(window,quickViewTimer,30,nullptr);
@@ -1651,7 +1692,11 @@ void TextWindow::previewEmbeddedText(const std::wstring &title,std::string_view
quickError.clear();
stopPreview(false,true);
document.reset();
quickMarkdown.reset();
quickPreviewCode.reset();
quickKind=QuickKind::text;
quickHtmlRendered=false;
quickBinaryBytes=0;
applySourceLayoutOptions();
}
if(quickTextTitle.empty() || quickTextDiff!=diff)
{
@@ -1681,7 +1726,10 @@ void TextWindow::pollQuickView()
original=quickPath;
filename=original.filename().wstring();
document=std::move(loaded.document);
quickMarkdown=std::move(loaded.markdown);
quickPreviewCode=std::move(loaded.previewCode);
quickKind=loaded.kind;
quickHtmlRendered=quickKind==QuickKind::html && quickPreviewCode.has_value();
quickBinaryBytes=loaded.binaryBytes;
initializeDocument(std::move(loaded.firstPage));
}
}
@@ -1710,13 +1758,23 @@ void TextWindow::pollQuickView()
std::packaged_task<QuickDocument()> task([path=quickPath] {
auto source=std::make_unique<TextDocument>(path,false);
auto first=source->readPage(0);
if(first.find('\0')!=std::string::npos)
throw std::runtime_error("Binary preview is unavailable.");
std::optional<std::string> markdown;
if(source->size()<=TextDocument::editLimit && detectLanguage(path,first).lexer=="markdown")
markdown=readMarkdownDocument(*source);
const auto extension=lower(path.extension().wstring());
const auto html=extension==L".html" || extension==L".htm" || extension==L".xhtml";
const auto binary=std::any_of(first.begin(),first.end(),[](unsigned char c) {
return (c<32 && c!='\t' && c!='\r' && c!='\n' && c!='\f') || c==127;
});
if(binary && !html)
{
constexpr size_t limit=4096;
const auto bytes=source->readBytes(0,limit);
source->releaseReadHandle();
return QuickDocument{std::move(source),formatBinarySymbols(bytes),{},QuickKind::binary,bytes.size()};
}
std::optional<std::string> markup;
if(source->size()<=TextDocument::editLimit && (html || detectLanguage(path,first).lexer=="markdown"))
markup=readMarkdownDocument(*source);
source->releaseReadHandle();
return QuickDocument{std::move(source),std::move(first),std::move(markdown)};
return QuickDocument{std::move(source),std::move(first),std::move(markup),html?QuickKind::html:QuickKind::text};
});
quickLoading=task.get_future();
std::thread(std::move(task)).detach();
@@ -1850,6 +1908,7 @@ void TextWindow::finishSave()
navigationHistory.clear();
updateTitle();
}
rememberLocalVersion();
if (!reopened)
{
search.style.message(window, L"The file was saved. Reopen it to continue editing.");
@@ -1945,8 +2004,61 @@ void TextWindow::restorePosition(const ViewerPosition &position)
send(SCI_SETXOFFSET,position.horizontal);
}
void TextWindow::showTextMode(const ViewerPosition &position,std::string contents)
void writeDocumentPlacement(nlohmann::json &state,HWND window)
{
WINDOWPLACEMENT placement{sizeof(placement)};
if(GetWindowPlacement(window,&placement))
{
const auto &rect=placement.rcNormalPosition;
state["rect"]={rect.left,rect.top,rect.right,rect.bottom};
state["maximized"]=placement.showCmd==SW_SHOWMAXIMIZED ||
(placement.flags&WPF_RESTORETOMAXIMIZED)!=0;
}
}
RECT readDocumentBounds(const nlohmann::json &state)
{
if(!state.contains("rect")) return {};
const auto rect=state.at("rect").get<std::array<LONG,4>>();
return {rect[0],rect[1],rect[2],rect[3]};
}
int restoreDocumentPlacement(HWND window,HWND owner,const RECT &bounds,bool maximized)
{
if(bounds.left>=bounds.right || bounds.top>=bounds.bottom || !MonitorFromRect(&bounds,MONITOR_DEFAULTTONULL))
return IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW;
WINDOWPLACEMENT placement{sizeof(placement)};
placement.rcNormalPosition=bounds;
placement.showCmd=maximized?SW_SHOWMAXIMIZED:SW_SHOWNORMAL;
SetWindowPlacement(window,&placement);
return maximized?SW_MAXIMIZE:SW_SHOWNORMAL;
}
nlohmann::json TextWindow::sessionState() const
{
if(embedded || remote || draft || !document || !isLocalDocumentPath(original)) return nullptr;
const auto position=currentPosition();
nlohmann::json state{{"path",utf8(original.native())},{"editor",edit},{"hex",hex},
{"page",position.page},{"anchor",position.anchor},{"caret",position.caret},
{"firstLine",position.firstLine},{"horizontal",position.horizontal}};
if(previewVisible) state["renderedScroll"]=renderedScroll;
writeDocumentPlacement(state,window);
return state;
}
void TextWindow::restoreSession(const nlohmann::json &state)
{
ViewerPosition position{std::min(state.value("page",uint64_t{}),pageTotal?pageTotal-1:0),
state.value("anchor",LRESULT{}),state.value("caret",LRESULT{}),
std::max<LRESULT>(0,state.value("firstLine",LRESULT{})),std::max<LRESULT>(0,state.value("horizontal",LRESULT{}))};
if(position.page!=page) loadPage(position.page);
restorePosition(position);
if(state.contains("renderedScroll")) sessionScroll=std::max(0,state.at("renderedScroll").get<int>());
}
void TextWindow::showTextMode(const ViewerPosition &position,std::string contents,bool takeFocus)
{
rememberLocalVersion();
if(canPreview()) ShowWindow(editor,SW_HIDE);
prefs = loadTextPreferences().profiles[edit];
releaseMenu();
@@ -1959,7 +2071,7 @@ void TextWindow::showTextMode(const ViewerPosition &position,std::string content
updateTaskbarGroup();
updatePreview();
layout();
focusContent();
if(takeFocus) focusContent();
}
void TextWindow::changeMode()
@@ -1967,7 +2079,8 @@ void TextWindow::changeMode()
if(!edit && remote && !remote->revision.editable)
throw std::runtime_error("The remote file does not support editing.");
auto position=currentPosition();
auto replacement=std::make_unique<TextDocument>(remote?remote->cache:original,!edit,document->encoding());
auto replacement=std::make_unique<TextDocument>(remote?remote->cache:original,!edit,document->encoding(),
!remote && isLocalDocumentPath(original));
position.page=std::min(position.page,replacement->pages()-1);
auto contents=replacement->readPage(position.page);
document=std::move(replacement);
@@ -2064,8 +2177,17 @@ void TextWindow::updateTaskbarGroup(bool closing)
bool TextWindow::canPreview() const
{
return !edit && !hex && !showBookmarkSource && automatic.lexer=="markdown" && document &&
document->size()<=TextDocument::editLimit;
if(edit || hex || showBookmarkSource || !document || document->size()>TextDocument::editLimit) return false;
if(embedded && quickKind==QuickKind::html) return quickHtmlRendered;
return automatic.lexer=="markdown";
}
void TextWindow::toggleQuickHtml()
{
if(!embedded || quickKind!=QuickKind::html || !document || !quickPreviewCode) return;
quickHtmlRendered=!quickHtmlRendered;
if(quickHtmlRendered) updatePreview();
else stopPreview(true,true);
}
void TextWindow::updatePreview()
@@ -2096,6 +2218,11 @@ bool TextWindow::startPreviewBrowser()
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
if(embedded)
{
if(!ctrl && !alt && !(GetKeyState(VK_SHIFT)&0x8000) && key==VK_F6 && quickKind==QuickKind::html)
{
PostMessageW(window,WM_COMMAND,quickModeControl,0);
return true;
}
if(!ctrl || alt || key!='Q') return false;
PostMessageW(GetParent(window),quickViewToggleMessage,0,0);
return true;
@@ -2131,6 +2258,7 @@ void TextWindow::stopPreview(bool refresh,bool keepBrowser)
{
KillTimer(window,previewTimer);
previewWanted=previewVisible=false;
if(embedded && refresh && quickKind==QuickKind::html) quickHtmlRendered=false;
previewStamp.reset();
++previewRevision;
previewText.clear();
@@ -2167,33 +2295,70 @@ void TextWindow::goToFragment(std::string_view fragment)
else previewFragment=fragment;
}
std::optional<TextWindow::FileStamp> TextWindow::previewFileStamp() const
std::optional<LocalFileVersion> TextWindow::previewFileStamp() const
{
if(remote) return {};
if(remote || !isLocalDocumentPath(original)) 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);
std::optional<LocalFileVersion> stamp;
try {stamp=fileVersion(file);} catch(const std::system_error &) {}
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};
return stamp;
}
void TextWindow::rememberLocalVersion()
{
if(embedded || remote || !document) return;
observedVersion=edit?document->expectedVersion():previewFileStamp();
diskChanged=false;
}
void TextWindow::pollExternalChanges()
{
if(embedded || remote || draft || !document || busy() || previewWanted || navigation.valid() || !observedVersion)
return;
const auto stamp=previewFileStamp();
if(!stamp || stamp==observedVersion) return;
if(edit && (GetForegroundWindow()!=window || !IsWindowEnabled(window) || !search.style.reloadChanged)) return;
try
{
if(edit)
{
observedVersion=stamp;
diskChanged=true;
invalidate();
if(!search.style.reloadChanged(window)) return;
}
auto replacement=std::make_unique<TextDocument>(original,edit,hex?TextEncoding::utf8:TextEncoding::automatic,edit);
auto position=currentPosition();
const auto pages=hex?1+(replacement->size()?replacement->size()-1:0)/hexPageBytes:replacement->pages();
position.page=std::min(position.page,pages-1);
auto contents=hex?formatHexPage(replacement->readBytes(position.page*hexPageBytes,hexPageBytes),
position.page*hexPageBytes):replacement->readPage(position.page);
if(!hex) language=automatic=detectLanguage(original,contents);
document=std::move(replacement);
showTextMode(position,std::move(contents),edit);
}
catch(const std::exception &error)
{
if(edit) search.style.message(window,wide(error.what()).c_str());
}
}
void TextWindow::renderPreview(bool keepPosition)
{
applyMarkdownPreferences(loadTextPreferences().markdown);
previewDeadline=GetTickCount64()+30000;
previewText=quickMarkdown?*quickMarkdown:readMarkdownDocument(*document);
previewText=quickPreviewCode?*quickPreviewCode:readMarkdownDocument(*document);
if(!remote) document->releaseReadHandle();
nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision},
{"canSave",!embedded && !suspendedEditor && (!remote || remote->revision.editable)},{"compact",embedded},
{"html",embedded && quickKind==QuickKind::html},
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
{"keepPosition",keepPosition}};
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
if(sessionScroll) message["scroll"]=*std::exchange(sessionScroll,{});
restoreScroll=false;
preview.post(wide(message.dump(-1,' ',false,nlohmann::json::error_handler_t::replace)));
}
@@ -2358,6 +2523,7 @@ void TextWindow::previewMessage(const std::wstring &value)
}
const auto message=nlohmann::json::parse(utf8(value));
const auto action=message.at("action").get<std::string>();
if(embedded && quickKind==QuickKind::html && action!="rendered" && action!="failed") return;
if(action=="cycle")
{
PostMessageW(window,cycleWindow,message.value("reverse",false),0);
@@ -2366,6 +2532,11 @@ void TextWindow::previewMessage(const std::wstring &value)
if(embedded && action!="image" && action!="rendered" && action!="failed") return;
const auto revision=message.value("revision",previewRevision);
if(embedded && revision!=previewRevision) return;
if(action=="scroll")
{
if(!embedded && revision==previewRevision) renderedScroll=std::max(0,message.at("top").get<int>());
return;
}
if(action=="failed")
{
PostMessageW(window,previewFailed,static_cast<WPARAM>(revision),0);
@@ -2558,6 +2729,13 @@ void TextWindow::layout()
const int top=embedded?row:2*row;
const LONG bottom=std::max<LONG>(top,area.bottom-(embedded?0:row));
MoveWindow(editor,0,top,area.right,bottom-top,TRUE);
if(quickModeButton)
{
const int width=std::min(static_cast<int>(area.right),scale(108));
MoveWindow(quickModeButton,area.right-width,0,width,row,TRUE);
SetWindowTextW(quickModeButton,quickHtmlRendered?L"Show Source":L"Show Rendered");
ShowWindow(quickModeButton,quickKind==QuickKind::html && quickPreviewCode && document?SW_SHOWNA:SW_HIDE);
}
preview.layout({0,top,area.right,bottom},previewWanted && (!embedded || previewVisible));
ShowWindow(editor,(document || quickTextVisible) && !previewWanted?SW_SHOWNA:SW_HIDE);
invalidate();
@@ -2633,9 +2811,18 @@ void TextWindow::paint()
std::wstring label=L"Quick View";
if(!quickPath.empty()) label+=L" · "+quickPath.filename().native();
if(!quickError.empty()) label+=L" · "+quickError;
else if(quickPath.empty()) label+=L" · Select a local text file";
else if(quickPath.empty()) label+=L" · Select a local file";
else if(!document || (previewWanted && !previewVisible)) label+=L" · Loading…";
else if(!previewVisible && pageTotal>1) label+=L" · First page";
else if(quickKind==QuickKind::binary)
label=L"Binary · "+std::to_wstring(quickBinaryBytes)+L" / "+std::to_wstring(fileSize)+L" B · "+
quickPath.filename().native();
else
{
if(quickKind==QuickKind::html) label+=previewVisible?L" · Rendered":L" · Source";
if(!previewVisible && pageTotal>1) label+=L" · First page";
}
if(quickModeButton && IsWindowVisible(quickModeButton))
client.right=std::max(0L,client.right-scale(108));
if(!quickTextTitle.empty()) label=quickTextTitle;
drawEditorStatus(dc,{0,0,client.right,row},chromeFont,color(TextColor::chromebg),
color(TextColor::chrome),scale(6),label);
@@ -2691,6 +2878,7 @@ void TextWindow::paint()
if(pageTotal>1)
status+=L" │ Page "+std::to_wstring(page+1)+L"/"+std::to_wstring(pageTotal)+
L" @ "+std::to_wstring(pageOffset);
if(diskChanged && edit) status+=L" │ Disk changed";
status+=L" │ "+std::to_wstring(fileSize)+L" B";
if(bookmarkTask.valid()) status+=L" │ Locating line…";
drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status);
@@ -2872,7 +3060,13 @@ void TextWindow::notify(const SCNotification &notice)
bool TextWindow::handleKey(const MSG &message)
{
if(embedded) return false;
if(embedded)
{
if(quickKind!=QuickKind::html || message.message!=WM_KEYDOWN || message.wParam!=VK_F6 ||
((GetKeyState(VK_CONTROL)|GetKeyState(VK_SHIFT)|GetKeyState(VK_MENU))&0x8000)) return false;
if(!(message.lParam&(1LL<<30))) toggleQuickHtml();
return true;
}
const auto key = message.wParam;
if (message.hwnd != editor) return false;
if (message.message == WM_SYSKEYDOWN && (message.lParam & (1LL << 29)))
@@ -2953,6 +3147,12 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
self->editor = CreateWindowExW(0, L"Scintilla", L"", WS_CHILD | WS_TABSTOP |
WS_VSCROLL | WS_HSCROLL, 0, 0, 0, 0, window, nullptr, GetModuleHandleW(nullptr), nullptr);
if (!self->editor) throw std::runtime_error("Cannot create the text control.");
if(self->embedded)
{
self->quickModeButton=CreateWindowW(L"BUTTON",L"Show Source",WS_CHILD|WS_TABSTOP|BS_PUSHBUTTON,
0,0,0,0,window,reinterpret_cast<HMENU>(quickModeControl),GetModuleHandleW(nullptr),nullptr);
if(!self->quickModeButton) throw std::runtime_error("Cannot create the Quick View mode button.");
}
self->send(SCI_SETCODEPAGE, SC_CP_UTF8);
self->send(SCI_SETMARGINS, 1);
self->send(SCI_SETMODEVENTMASK, SC_MOD_INSERTCHECK | SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT);
@@ -2983,6 +3183,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
else self->initializeDocument();
if(!self->embedded)
{
if(!self->remote) SetTimer(window,externalChangeTimer,500,nullptr);
self->updateIcons(GetDpiForWindow(window));
self->updateTaskbarGroup();
}
@@ -3050,7 +3251,11 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
return 0;
}
case WM_COMMAND:
if(self->embedded) return 0;
if(self->embedded)
{
if(LOWORD(wparam)==quickModeControl) self->toggleQuickHtml();
return 0;
}
if (LOWORD(wparam) >= 600 && LOWORD(wparam) < 605) self->openMenu(LOWORD(wparam) - 600);
else self->command(LOWORD(wparam));
return 0;
@@ -3065,6 +3270,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 == externalChangeTimer) self->pollExternalChanges();
if (wparam == navigationTimer) self->finishNavigation();
if (wparam == quickViewTimer) self->pollQuickView();
if (wparam == bookmarkTimer) self->finishBookmark();
@@ -3323,7 +3529,8 @@ void previewImageQuickViewFile(HWND window,const std::filesystem::path &path)
}
void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const std::filesystem::path &path,
TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source)
TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source,const ImageEditDialogs *editor,
const ImageWindowSession *session)
{
try
{
@@ -3357,22 +3564,31 @@ void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const
[](HWND closed) {
std::erase(textWindowOrder,closed);
quitWhenFilesWindowsClose();
},std::move(retry));
if(!window) throw std::runtime_error("Could not open the image viewer.");
},std::move(retry),editor);
if(!window) throw std::runtime_error(editor?"Could not open the image editor.":"Could not open the image viewer.");
textWindowOrder.push_back(window);
const auto instance=GetModuleHandleW(nullptr);
const auto icon=LoadImageW(instance,MAKEINTRESOURCEW(IDI_FILES_VIEWER),IMAGE_ICON,0,0,LR_SHARED|LR_DEFAULTSIZE);
const int iconId=editor?IDI_FILES_EDITOR:IDI_FILES_VIEWER;
const auto icon=LoadImageW(instance,MAKEINTRESOURCEW(iconId),IMAGE_ICON,0,0,LR_SHARED|LR_DEFAULTSIZE);
if(icon) SendMessageW(window,WM_SETICON,ICON_BIG,reinterpret_cast<LPARAM>(icon));
setFileWindowTaskbar(window,IDI_FILES_VIEWER,L"HrynCo.KSwitcher.Files.Viewer");
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
setFileWindowTaskbar(window,iconId,editor?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer");
if(session) restoreImageWindowSession(window,*session);
ShowWindow(window,session?restoreDocumentPlacement(window,owner,session->bounds,session->maximized):
IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
SetFocus(window);
}
catch(const std::exception &error) {dialogs.message(owner,wide(error.what()).c_str());}
catch(const std::exception &error)
{
if(!session) dialogs.message(owner,wide(error.what()).c_str());
else log(L"Restore Files image: "+wide(error.what()));
}
}
static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options)
const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options,
const nlohmann::json *session=nullptr)
{
HWND created{};
if(!edit && !options.draft && !options.hex && !options.line && isImagePath(path))
{
openImageWindow(owner,{path},path,dialogs,nullptr,backend);
@@ -3408,10 +3624,90 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool
WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN,bounds.left,bounds.top,bounds.right-bounds.left,
bounds.bottom-bounds.top,nullptr,nullptr,instance,&state);
if(!window) return;
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
created=window;
int show=IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW;
if(session)
{
state->restoreSession(*session);
show=restoreDocumentPlacement(window,owner,readDocumentBounds(*session),session->value("maximized",false));
}
ShowWindow(window,show);
SendMessageW(window,WM_SETFOCUS,0,0);
}
catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());}
catch(const std::exception &error)
{
if(!session) dialogs.message(owner,wide(error.what()).c_str());
else
{
if(created) DestroyWindow(created);
log(L"Restore Files document: "+wide(error.what()));
}
}
}
constexpr wchar_t localSessionKey[]=L"LocalDocumentsV1";
void saveLocalDocumentSession(const wchar_t *registryKey,bool enabled)
{
if(!enabled)
{
RegDeleteKeyValueW(HKEY_CURRENT_USER,registryKey,localSessionKey);
return;
}
auto session=nlohmann::json::array();
for(const auto window:textWindowOrder)
{
if(session.size()>=128) break;
if(const auto found=textWindows.find(window);found!=textWindows.end())
{
auto state=found->second->sessionState();
if(!state.is_null()) session.push_back(std::move(state));
}
else if(const auto image=imageWindowSession(window))
{
nlohmann::json state{{"path",utf8(image->path.native())},{"editor",image->editor},{"image",true},
{"fit",image->fit},{"zoom",image->zoom},{"x",image->x},{"y",image->y}};
writeDocumentPlacement(state,window);
session.push_back(std::move(state));
}
}
const auto text=session.dump();
if(text.size()<=1024*1024)
RegSetKeyValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,REG_BINARY,text.data(),static_cast<DWORD>(text.size()));
}
void restoreLocalDocumentSession(HWND owner,TextDialogs dialogs,const wchar_t *registryKey,
const ImageEditDialogs &imageEditor)
{
DWORD bytes{};
if(RegGetValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
!bytes || bytes>1024*1024) return;
std::string text(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,RRF_RT_REG_BINARY,nullptr,text.data(),&bytes)!=ERROR_SUCCESS)
return;
const auto session=nlohmann::json::parse(text.begin(),text.begin()+bytes,nullptr,false);
if(!session.is_array()) return;
for(size_t i=0;i<std::min<size_t>(128,session.size());++i)
{
try
{
const auto &state=session[i];
const std::filesystem::path path=wide(state.at("path").get<std::string>());
if(!isLocalDocumentPath(path)) continue;
const auto attributes=GetFileAttributesW(path.c_str());
if(attributes==INVALID_FILE_ATTRIBUTES || (attributes&FILE_ATTRIBUTE_DIRECTORY)) continue;
const bool editor=state.value("editor",false);
if(state.value("image",false))
{
if(!isImagePath(path) || (editor && !isEditableImagePath(path))) continue;
ImageWindowSession image{path,editor,state.value("fit",true),state.value("zoom",1.0),
state.value("x",0.0),state.value("y",0.0),readDocumentBounds(state),state.value("maximized",false)};
openImageWindow(owner,{path},path,dialogs,nullptr,nullptr,editor?&imageEditor:nullptr,&image);
}
else openTextWindowImpl(owner,path,editor,dialogs,nullptr,{},true,{.hex=state.value("hex",false)},&state);
}
catch(const std::exception &error) {log(L"Restore Files document: "+wide(error.what()));}
}
}
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
+7 -1
View File
@@ -57,6 +57,7 @@ struct TextDialogs
bool (*dismissOwned)(HWND);
bool (*confirmExisting)(HWND);
bool (*saveOptions)(HWND,std::filesystem::path &,TextSaveFormat &);
bool (*reloadChanged)(HWND){};
};
struct TextOpenOptions
@@ -109,8 +110,11 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path);
void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff=false);
HWND createImageQuickView(HWND owner,TextDialogs dialogs);
void previewImageQuickViewFile(HWND window,const std::filesystem::path &path);
struct ImageEditDialogs;
struct ImageWindowSession;
void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const std::filesystem::path &path,
TextDialogs dialogs,const lan::FilesPeer *peer=nullptr,const RemoteTextSource *source=nullptr);
TextDialogs dialogs,const lan::FilesPeer *peer=nullptr,const RemoteTextSource *source=nullptr,
const ImageEditDialogs *editor=nullptr,const ImageWindowSession *session=nullptr);
void showAllViewerBookmarks(HWND owner,TextDialogs dialogs);
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
@@ -118,6 +122,8 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
TextOpenOptions options={});
void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false,TextOpenOptions options={});
void saveLocalDocumentSession(const wchar_t *registryKey,bool enabled);
void restoreLocalDocumentSession(HWND owner,TextDialogs dialogs,const wchar_t *registryKey,const ImageEditDialogs &imageEditor);
void textWindowOwnerClosed();
void standaloneFilesWindowOpened();
void standaloneFilesWindowClosed();
+5
View File
@@ -102,6 +102,11 @@ public:
FtpDeleteFileA(ftp_->handle(),name.c_str()));
}
void preserveModificationTime(const fs::path &path,uint64_t modified)
{
if(sftp_ && modified) sftp_->preserveModificationTime(path,modified);
}
void prepareReplacement(const fs::path &staged,const fs::path &existing)
{
if(sftp_) sftp_->prepareReplacement(staged,existing);
+46
View File
@@ -1,18 +1,64 @@
#pragma once
#include <windows.h>
#include <objbase.h>
#include <filesystem>
#include <stdexcept>
#include <string>
#include <string_view>
#include <system_error>
namespace ks::files
{
inline bool isLocalDocumentPath(const std::filesystem::path &path)
{
std::wstring_view name=path.native();
if(name.starts_with(L"\\\\?\\")) name.remove_prefix(4);
if(name.size()<3 || name[1]!=L':' || (name[2]!=L'\\' && name[2]!=L'/')) return false;
const auto type=GetDriveTypeW(std::wstring(name.substr(0,3)).c_str());
return type==DRIVE_FIXED || type==DRIVE_REMOVABLE || type==DRIVE_RAMDISK || type==DRIVE_CDROM;
}
inline std::filesystem::path temporaryPath(const std::filesystem::path &directory)
{
GUID id{};
wchar_t name[40]{};
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
throw std::runtime_error("Cannot create a temporary file name.");
return directory/(std::wstring(L".kswitcher-")+name+L".tmp");
}
inline bool sameFileIdentity(const BY_HANDLE_FILE_INFORMATION &left,const BY_HANDLE_FILE_INFORMATION &right)
{
return left.dwVolumeSerialNumber==right.dwVolumeSerialNumber && left.nFileIndexHigh==right.nFileIndexHigh &&
left.nFileIndexLow==right.nFileIndexLow;
}
struct LocalFileVersion
{
BY_HANDLE_FILE_INFORMATION info{};
LONGLONG changeTime{};
bool operator==(const LocalFileVersion &other) const
{
return sameFileIdentity(info,other.info) && changeTime==other.changeTime &&
info.nFileSizeHigh==other.info.nFileSizeHigh && info.nFileSizeLow==other.info.nFileSizeLow &&
CompareFileTime(&info.ftLastWriteTime,&other.info.ftLastWriteTime)==0;
}
};
inline LocalFileVersion fileVersion(HANDLE file)
{
LocalFileVersion version;
if(!GetFileInformationByHandle(file,&version.info))
throw std::system_error(static_cast<int>(GetLastError()),std::system_category(),"Read file revision");
FILE_BASIC_INFO basics{};
if(GetFileInformationByHandleEx(file,FileBasicInfo,&basics,sizeof(basics)))
version.changeTime=basics.ChangeTime.QuadPart;
return version;
}
inline DWORD replaceFileWithBackup(const std::filesystem::path &original,const std::filesystem::path &replacement,
const std::filesystem::path &backup)
{
+63 -1
View File
@@ -8,6 +8,7 @@
#include <bcrypt.h>
#include <wincrypt.h>
#include <sddl.h>
#include <aclapi.h>
#include <winsafer.h>
#include <cstring>
#include <mutex>
@@ -679,7 +680,7 @@ public:
}
return reply;
}
if(action=="fileCapabilities") return {{"error",0},{"revision",1}};
if(action=="fileCapabilities") return {{"error",0},{"revision",1},{"copyMetadata",true}};
if(action=="listNext") return listNext();
if(action=="read")
{
@@ -770,6 +771,67 @@ public:
const auto canonical=fs::weakly_canonical(name,error);
return error?failure(error.value()):Json{{"error",0},{"path",utf8(canonical.native())}};
}
if(action=="copyPermissions")
{
DWORD size{};
GetFileSecurityW(name.c_str(),DACL_SECURITY_INFORMATION,nullptr,0,&size);
if(!size || GetLastError()!=ERROR_INSUFFICIENT_BUFFER) return failure();
Bytes descriptor(size);
if(!GetFileSecurityW(name.c_str(),DACL_SECURITY_INFORMATION,descriptor.data(),size,&size)) return failure();
LPWSTR sddl{};
if(!ConvertSecurityDescriptorToStringSecurityDescriptorW(descriptor.data(),SDDL_REVISION_1,
DACL_SECURITY_INFORMATION,&sddl,nullptr)) return failure();
const auto value=utf8(sddl);
LocalFree(sddl);
return {{"error",0},{"permissions",value}};
}
if(action=="applyCopyMetadata")
{
if(request.contains("modified"))
{
FileHandle file{CreateFileW(name.c_str(),FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return failure();
BY_HANDLE_FILE_INFORMATION info{};
if(!GetFileInformationByHandle(file.value,&info)) return failure();
if(info.dwFileAttributes&FILE_ATTRIBUTE_REPARSE_POINT) return failure(ERROR_NOT_SUPPORTED);
auto stamp=request.at("modified").get<uint64_t>();
FILETIME time{static_cast<DWORD>(stamp),static_cast<DWORD>(stamp>>32)};
if(!stamp) GetSystemTimeAsFileTime(&time);
if(!SetFileTime(file.value,nullptr,nullptr,&time)) return failure();
}
if(request.contains("permissions"))
{
FileHandle file{CreateFileW(name.c_str(),FILE_READ_ATTRIBUTES|READ_CONTROL|WRITE_DAC,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,nullptr)};
if(file.value==INVALID_HANDLE_VALUE) return failure();
BY_HANDLE_FILE_INFORMATION info{};
if(!GetFileInformationByHandle(file.value,&info)) return failure();
if(info.dwFileAttributes&FILE_ATTRIBUTE_REPARSE_POINT) return failure(ERROR_NOT_SUPPORTED);
PSECURITY_DESCRIPTOR descriptor{};
const auto sddl=wide(request.at("permissions").get<std::string>());
if(!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(),SDDL_REVISION_1,
&descriptor,nullptr)) return failure();
SECURITY_DESCRIPTOR_CONTROL control{};
DWORD revision{};
BOOL present{}, defaulted{};
PACL acl{};
auto error=DWORD(ERROR_SUCCESS);
if(!GetSecurityDescriptorDacl(descriptor,&present,&acl,&defaulted) || !present ||
!GetSecurityDescriptorControl(descriptor,&control,&revision)) error=ERROR_INVALID_DATA;
else
{
auto security=DACL_SECURITY_INFORMATION|((control&SE_DACL_PROTECTED)?
PROTECTED_DACL_SECURITY_INFORMATION:UNPROTECTED_DACL_SECURITY_INFORMATION);
error=SetSecurityInfo(file.value,SE_FILE_OBJECT,security,nullptr,nullptr,acl,nullptr);
}
LocalFree(descriptor);
if(error) return failure(error);
}
return ok();
}
if(action=="mkdir") return CreateDirectoryW(name.c_str(),nullptr)?ok():failure();
if(action=="mkdir-link")
{
+56 -1
View File
@@ -1,4 +1,4 @@
#include "files_image_decode.h"
#include "files_image_edit.h"
#include <windows.h>
#include <wincodec.h>
#include <webp/encode.h>
@@ -84,6 +84,60 @@ void expectDecodeFailure(const fs::path &file,std::string_view text)
throw std::runtime_error("invalid image was decoded");
}
void verifyImageEdits(const fs::path &root)
{
ImageRaster original{4,3,{0xff110001,0xff110002,0xff110003,0xff110004,
0xff110005,0x80402010,0xff110007,0xff110008,0xff110009,0xff11000a,0xff11000b,0xff11000c}};
const ImageGeometry initial{{0,0,4,3},0};
const ImageGeometry clockwise{initial.region,1};
const auto rotated=transformImage(original,clockwise);
expect(rotated.width==3 && rotated.height==4 && rotated.pixels[0]==original.pixels[8] &&
rotated.pixels[11]==original.pixels[3],"clockwise rotation changed pixel order");
const auto reversed=transformImage(original,{initial.region,3});
expect(reversed.pixels.front()==original.pixels[3] && reversed.pixels.back()==original.pixels[8],
"counterclockwise rotation changed pixel order");
const auto cropped=transformImage(original,cropImage(clockwise,{1,1,2,2}));
expect(cropped.width==2 && cropped.height==2 && cropped.pixels==std::vector<uint32_t>{
original.pixels[5],original.pixels[1],original.pixels[6],original.pixels[2]},
"crop used coordinates before rotation");
bool outside=false;
try {cropImage(clockwise,{2,1,2,2});}
catch(const std::runtime_error &) {outside=true;}
expect(outside,"out-of-bounds crop was accepted");
const auto png=root/L"Редагування.png";
saveImage(cropped,png);
const auto saved=decodeImage(png,png);
expect(saved.width==2 && saved.height==2 && saved.pixels==cropped.pixels,"PNG copy lost alpha or pixels");
const auto before=imageRevision(png);
bool collision=false;
try {saveImage(rotated,png);}
catch(const std::system_error &) {collision=true;}
expect(collision && sameImageRevision(before,imageRevision(png)), "Save Copy overwrote an existing image");
const auto incoming=root/L"external.png";
saveImage(original,incoming);
fs::rename(png,root/L"first.png");
fs::rename(incoming,png);
bool stale=false;
try {saveImage(cropped,png,&before);}
catch(const std::runtime_error &) {stale=true;}
expect(stale && decodeImage(png,png).pixels==original.pixels,"Replace overwrote an external revision");
const auto current=imageRevision(png);
const auto written=saveImage(cropped,png,&current);
expect(sameImageRevision(written,imageRevision(png)), "returned revision did not track the installed image");
expect(decodeImage(png,png).pixels==cropped.pixels,"confirmed replacement lost image data");
const auto jpeg=root/L"copy.jpg";
const ImageRaster transparent{8,8,std::vector<uint32_t>(64,0)};
saveImage(transparent,jpeg);
const auto lossy=decodeImage(jpeg,jpeg);
expect(lossy.width==8 && lossy.height==8 && lossy.pixels.front()>=0xfffefefe,
"JPEG copy failed to composite transparency on white");
for(const auto &entry:fs::directory_iterator(root))
expect(entry.path().extension()!=L".tmp","image operation left a staging file");
}
std::vector<uint8_t> animatedWebp(const uint8_t *encoded,size_t size)
{
expect(size>12,"WebP fixture RIFF body");
@@ -109,6 +163,7 @@ int main()
{
expect(SUCCEEDED(apartment),"initialize COM");
Temp temp;
verifyImageEdits(temp.path);
for(const auto &[name,container]:std::array{
std::pair{L"знімок.PNG",&GUID_ContainerFormatPng},
std::pair{L"picture.jpeg",&GUID_ContainerFormatJpeg},
+17
View File
@@ -99,6 +99,23 @@ try {
: { key:'Enter', code:'Enter', windowsVirtualKeyCode:13 };
await command('Input.dispatchKeyEvent', { type:'keyDown', ...key });
await command('Input.dispatchKeyEvent', { type:'keyUp', ...key });
} else if (scenario === 'html-quick') {
await waitFor(() => evaluate(`document.documentElement.classList.contains('rendered') &&
document.querySelector('main h1')?.textContent === 'Offline HTML fixture'`), 'rendered HTML');
assert.equal(await evaluate(`document.querySelector('main td strong')?.textContent`), 'Formatted table');
assert.equal(await evaluate(`document.querySelector('main h1').style.color`), 'teal');
assert.equal(await evaluate(`document.querySelector('main h1').style.position`), '');
assert.equal(await evaluate(`document.querySelectorAll(
'main :is(script, style, link, meta, iframe, object, img, input, [href], [src], [onload], [onclick])'
).length`), 0);
assert.equal(await evaluate(`document.querySelector('main').textContent.includes('Image description')`), true);
assert.equal(await evaluate(`window.documentScriptRan`), undefined);
await evaluate(`document.querySelector('main a').click()`);
assert.equal(await evaluate('location.href'), 'https://kswitcher-markdown.invalid/markdown.html');
if (artifact) {
const screenshot = await command('Page.captureScreenshot', { format: 'png' });
await writeFile(artifact, Buffer.from(screenshot.data, 'base64'));
}
} else if (scenario === 'render') {
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
!!document.querySelector('figure svg') &&
+173 -32
View File
@@ -1,60 +1,133 @@
param(
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe"
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe",
[string]$ProfileSubkey = 'Software\KSwitcher\Files',
[string]$Node = (Get-Command node -ErrorAction SilentlyContinue).Source,
[string]$RenderedImage = '',
[string]$BinaryImage = ''
)
$ErrorActionPreference = 'Stop'
. "$PSScriptRoot/files_commands_ui.ps1"
$browserProbe = $Node -and ((& $Node -p "typeof WebSocket === 'function'") -eq 'true')
if($RenderedImage -and !$browserProbe){throw 'A Node runtime with WebSocket is required for a rendered screenshot'}
Add-Type @'
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class FilesQuickViewProbe {
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr parent, int id);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
public static bool Activate(IntPtr window) {
if (GetForegroundWindow() == window) return true;
keybd_event(0x12, 0, 0, UIntPtr.Zero);
keybd_event(0x12, 0, 2, UIntPtr.Zero);
SetForegroundWindow(window);
return GetForegroundWindow() == window;
}
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr window, IntPtr after, int x,
int y, int width, int height, uint flags);
[DllImport("user32.dll", EntryPoint="PostMessageW")]
public static extern bool Post(IntPtr window, uint msg, IntPtr wp, IntPtr lp);
[DllImport("user32.dll", EntryPoint="SendMessageW")]
public static extern IntPtr Send(IntPtr window, uint msg, IntPtr wp, IntPtr lp);
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
public static extern IntPtr FindRow(IntPtr window, uint msg, IntPtr wp, string name);
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
public static extern IntPtr Read(IntPtr window, uint msg, IntPtr wp, StringBuilder text);
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title);
}
'@
function Wait-Until([scriptblock]$Condition) {
for ($attempt = 0; $attempt -lt 100; $attempt++) {
if (& $Condition) { return }
function Wait-Until([string]$Label,[scriptblock]$Condition) {
for ($attempt = 0; $attempt -lt 150; $attempt++) {
$result = & $Condition
if ($result) { return $result }
Start-Sleep -Milliseconds 50
}
throw "Timed out waiting for: $Condition"
throw "Timed out waiting for $Label"
}
function Text([IntPtr]$Handle) {
$buffer = [Text.StringBuilder]::new(256)
[void][FilesQuickViewProbe]::Read($Handle, 13, [IntPtr]$buffer.Capacity, $buffer)
$buffer.ToString()
}
function Select-File([string]$Name) {
$row = [FilesQuickViewProbe]::FindRow($leftList, 0x1A2, [IntPtr](-1), $Name)
if ($row.ToInt64() -lt 0) { throw "Missing row $Name" }
[void][FilesQuickViewProbe]::Send($leftList, 0x186, $row, 0)
[void][FilesQuickViewProbe]::Post($window, 273, [IntPtr](0x10000+102), $leftList)
}
function Preview-Bytes([int]$Count) {
[byte[]]$bytes = @(
for($i=0; $i -lt $Count; ++$i) {
[byte]([FilesQuickViewProbe]::Send($editor, 2007, [IntPtr]$i, 0).ToInt32() -band 255)
}
)
[Text.Encoding]::UTF8.GetString($bytes)
}
function Browser {
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'html-quick' $RenderedImage 'preview.html'
if ($LASTEXITCODE) { throw 'WebView2 verification failed for rendered HTML' }
}
$exe = (Resolve-Path $Executable).Path
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$names = 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement'
$source = Split-Path $exe
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($ProfileSubkey)
$names = 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor',
'LeftPanelMode', 'RightPanelMode', 'WindowPlacement'
$saved = @{}
foreach ($name in $names) {
if ($name -in $key.GetValueNames()) { $saved[$name] = @($key.GetValue($name), $key.GetValueKind($name)) }
}
$flags = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
$profile = $env:WEBVIEW2_USER_DATA_FOLDER
$fixture = [IO.Directory]::CreateTempSubdirectory('ks-files-quick-view-')
$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
try {
$network = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$network.Start()
$probe = "http://127.0.0.1:$($network.LocalEndpoint.Port)/should-not-load"
$debug = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$debug.Start()
$port = $debug.LocalEndpoint.Port
$debug.Stop()
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = "--remote-debugging-port=$port --disable-background-networking"
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $fixture.FullName 'webview'
$app = $fixture.CreateSubdirectory('app')
Copy-Item -LiteralPath $exe,"$source\WebView2Loader.dll","$source\terminal" -Destination $app.FullName -Recurse
$left = $fixture.CreateSubdirectory('left')
$right = $fixture.CreateSubdirectory('right')
$document = Join-Path $left.FullName 'preview.txt'
[IO.File]::WriteAllText($document, 'Quick View fixture')
$key.SetValue('LeftWide', 1, 'DWord')
$key.SetValue('RightWide', 1, 'DWord')
[IO.File]::WriteAllText((Join-Path $left.FullName 'preview.html'), @"
<!doctype html>
<html><head><title>Document title</title>
<meta http-equiv="refresh" content="0;url=$probe">
<link rel="stylesheet" href="$probe">
<style>@import url('$probe');</style>
<script>window.documentScriptRan = true;</script></head>
<body onload="window.documentScriptRan = true;"><main>
<h1 style="color: teal; position: fixed" onclick="window.documentScriptRan = true;">Offline HTML fixture</h1>
<table><tr><td><strong>Formatted table</strong></td></tr></table>
<a href="$probe">External link</a>
<img src="$probe" alt="Image description"><iframe src="$probe"></iframe>
<form action="$probe"><input type="submit"></form>
</main></body></html>
"@)
$data = [byte[]]::new(5000)
[byte[]]$header = 0,1,9,10,13,27,31,32,65,127,128,255
$header.CopyTo($data,0)
for ($i=$header.Length; $i -lt $data.Length; ++$i) { $data[$i] = 66 }
[IO.File]::WriteAllBytes((Join-Path $left.FullName 'symbols.bin'), $data)
$expectedSymbols = -join ([char[]]@(0xe000,0xe001,0xe009,0xe00a,0xe00d,0xe01b,0xe01f,
0x20,0x41,0xe07f,0xC7,0xe0ff))
$key.SetValue('LeftPanelMode', 1, 'DWord')
$key.SetValue('RightPanelMode', 1, 'DWord')
$key.SetValue('LeftPath', $left.FullName, 'String')
$key.SetValue('RightPath', $right.FullName, 'String')
$key.SetValue('LeftCursor', $document, 'String')
$key.DeleteValue('RightCursor', $false)
$key.DeleteValue('WindowPlacement', $false)
$process = Start-Process -FilePath $exe -PassThru
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
$window = $process.MainWindowHandle
Wait-Until { [FilesQuickViewProbe]::Activate($window) }
$keyboard = New-Object -ComObject WScript.Shell
$process = Start-Process -FilePath (Join-Path $app.FullName (Split-Path -Leaf $exe)) -PassThru -WindowStyle Normal
$window = Wait-Until 'the Files window' {
$process.Refresh()
if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle }
}
[void][FilesQuickViewProbe]::SetWindowPos($window,0,40,50,1500,920,20)
$leftList = [FilesQuickViewProbe]::GetDlgItem($window, 102)
$rightList = [FilesQuickViewProbe]::GetDlgItem($window, 103)
$rightHeading = [FilesQuickViewProbe]::GetDlgItem($window, 141)
@@ -62,12 +135,16 @@ try {
if (!($leftList -and $rightList -and $rightHeading -and $rightPath)) {
throw 'Expected both file panels in the test window.'
}
Wait-Until { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) }
$keyboard.SendKeys('^q')
Wait-Until {
[void](Wait-Until 'both panels' { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) })
Invoke-FilesCommand $window 'Quick View*'
$preview = Wait-Until 'Quick View' {
$hostWindow = [FilesQuickViewProbe]::GetDlgItem($window, 158)
$hostWindow -ne [IntPtr]::Zero -and [FilesQuickViewProbe]::IsWindowVisible($hostWindow)
if ([FilesQuickViewProbe]::IsWindowVisible($hostWindow)) { $hostWindow }
}
$editor = [FilesQuickViewProbe]::FindWindowEx($preview,0,'Scintilla',[NullString]::Value)
[void](Wait-Until 'the text preview' { [FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -eq 18 })
$initialWrap = [FilesQuickViewProbe]::Send($editor,2269,0,0)
$initialScrollbar = [FilesQuickViewProbe]::Send($editor,2131,0,0)
foreach ($control in $rightList, $rightHeading, $rightPath) {
if ([FilesQuickViewProbe]::IsWindowVisible($control)) {
throw 'A file panel control can draw over the Quick View content.'
@@ -75,19 +152,75 @@ try {
}
if (![FilesQuickViewProbe]::IsWindowVisible($leftList)) { throw 'Quick View hid the source panel.' }
$keyboard.SendKeys('^q')
Wait-Until { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero }
Select-File 'preview.html'
$mode = [FilesQuickViewProbe]::GetDlgItem($preview,159)
[void](Wait-Until 'the HTML mode switch' { [FilesQuickViewProbe]::IsWindowVisible($mode) -and (Text $mode) -eq 'Show Source' })
if ($browserProbe) { Browser }
[void][FilesQuickViewProbe]::Post($preview,273,159,$mode)
[void](Wait-Until 'the HTML source' {
[FilesQuickViewProbe]::IsWindowVisible($editor) -and (Text $mode) -eq 'Show Rendered' -and
(Preview-Bytes 15) -eq '<!doctype html>'
})
[void][FilesQuickViewProbe]::Post($editor,0x100,117,0)
[void](Wait-Until 'keyboard switch back to Rendered' { (Text $mode) -eq 'Show Source' })
if ($browserProbe) { Browser }
if ($network.Pending()) { throw 'Rendering HTML attempted an outbound resource request' }
Select-File 'symbols.bin'
[void](Wait-Until 'binary glyphs in the embedded view' {
[FilesQuickViewProbe]::IsWindowVisible($editor) -and [FilesQuickViewProbe]::Send($editor,2269,0,0).ToInt32() -eq 2
})
if ((Preview-Bytes ([Text.Encoding]::UTF8.GetByteCount($expectedSymbols))) -cne $expectedSymbols) {
throw 'Binary control bytes were lost or decoded as text'
}
$expectedLength = [Text.Encoding]::UTF8.GetByteCount($expectedSymbols) + 4096 - $header.Length
if ([FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -ne $expectedLength -or
[FilesQuickViewProbe]::Send($editor,2131,0,0).ToInt32() -ne 0) {
throw 'Binary preview exceeded its byte limit or enabled horizontal scrolling'
}
$escapeWidth = [FilesQuickViewProbe]::Send($editor,2164,0,3).ToInt32() -
[FilesQuickViewProbe]::Send($editor,2164,0,0).ToInt32()
if($escapeWidth -le [FilesQuickViewProbe]::Send($editor,2279,0,0).ToInt32()){
throw 'The control byte did not render as a full visible escape'
}
if($BinaryImage){
Add-Type -AssemblyName System.Drawing
$bounds = [FilesCommandsUi+Rect]::new()
[void][FilesCommandsUi]::GetClientRect($preview,[ref]$bounds)
$bitmap = [Drawing.Bitmap]::new($bounds.Right,$bounds.Bottom)
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try {
$dc = $graphics.GetHdc()
try { if(![FilesCommandsUi]::PrintWindow($preview,$dc,3)){throw 'Could not render binary preview'} }
finally { $graphics.ReleaseHdc($dc) }
$bitmap.Save($BinaryImage,[Drawing.Imaging.ImageFormat]::Png)
} finally { $graphics.Dispose(); $bitmap.Dispose() }
}
$wideRows = [FilesQuickViewProbe]::Send($editor,2235,0,0).ToInt32()
[void][FilesQuickViewProbe]::SetWindowPos($window,0,40,50,840,920,20)
[void](Wait-Until 'binary rows wrap in a narrower pane' { [FilesQuickViewProbe]::Send($editor,2235,0,0).ToInt32() -gt $wideRows })
Select-File 'preview.txt'
[void](Wait-Until 'ordinary text preview restored' { [FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -eq 18 })
if ([FilesQuickViewProbe]::IsWindowVisible($mode) -or [FilesQuickViewProbe]::Send($editor,2269,0,0) -ne $initialWrap -or
[FilesQuickViewProbe]::Send($editor,2131,0,0) -ne $initialScrollbar) { throw 'Preview mode leaked into a text file' }
[void][FilesQuickViewProbe]::Post($window,0x801F,0,0)
[void](Wait-Until 'Quick View closed' { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero })
foreach ($control in $rightList, $rightHeading, $rightPath) {
if (![FilesQuickViewProbe]::IsWindowVisible($control)) {
throw 'A file panel control remained hidden after closing Quick View.'
}
}
'Quick View hides the covered list and chrome, then restores the same controls.'
'Quick View verified with offline HTML, source switching, bounded binary glyphs and restored file panels.'
} finally {
if ($process -and !$process.HasExited) {
[void]$process.CloseMainWindow()
if (!$process.WaitForExit(3000)) { $process.Kill(); $process.WaitForExit() }
}
if ($network) { $network.Stop() }
if ($dpi) { [void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi) }
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = $flags
$env:WEBVIEW2_USER_DATA_FOLDER = $profile
foreach ($name in $names) {
if ($saved.ContainsKey($name)) { $key.SetValue($name, $saved[$name][0], $saved[$name][1]) }
else { $key.DeleteValue($name, $false) }
@@ -96,6 +229,14 @@ try {
$path = [IO.Path]::GetFullPath($fixture.FullName)
if ([IO.Path]::GetDirectoryName($path) -eq [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath()) -and
[IO.Path]::GetFileName($path).StartsWith('ks-files-quick-view-')) {
[IO.Directory]::Delete($path, $true)
for($attempt=0; $attempt -lt 50; ++$attempt){
try {
[IO.Directory]::Delete($path, $true)
break
} catch [System.IO.IOException] {
if($attempt -eq 49){throw}
Start-Sleep -Milliseconds 100
}
}
}
}
+30
View File
@@ -160,11 +160,40 @@ void hexBytes(const fs::path &file)
const auto text=ks::files::formatHexPage(bytes,0);
check(text.starts_with("0000000000000000 EF BB BF 00 41 FF 7F 0D 0A") &&
text.ends_with("|....A.... |"),"Hex and ASCII columns retain unprintable bytes and alignment");
const std::string controls("\x00\x01\x09\x0A\x0D\x1B\x1F A\x7F\x80\xFF",12);
const std::string symbols(reinterpret_cast<const char *>(u8"\ue000\ue001\ue009\ue00a\ue00d\ue01b\ue01f A\ue07f\u00c7\ue0ff"));
check(ks::files::formatBinarySymbols(controls)==symbols,"Quick View displays all control and high bytes as glyphs");
const std::string slash(reinterpret_cast<const char *>(u8"\ue05c"));
check(ks::files::formatBinarySymbols("\\x00")==slash+"x00","Binary preview distinguishes literal escapes");
check(ks::files::formatBinarySymbols({}).empty(),"An empty symbol preview stays empty");
const std::string twoRows(17,'a');
check(ks::files::formatHexPage(twoRows,0).find("\r\n0000000000000010 61")!=std::string::npos,
"Hex offsets advance by the row width");
}
void watchedEditor(const fs::path &file)
{
writeFile(file,"original bytes");
TextDocument editor(file,true,TextEncoding::automatic,true);
check(editor.expectedVersion().has_value(),"local editor captured the original version");
writeFile(file,"external bytes");
check(editor.readPage(0)=="original bytes","external edit replaced the editor snapshot");
editor.stage(0,"editor buffer");
bool rejected=false;
try {editor.save();}
catch(const std::runtime_error &error)
{
rejected=std::string_view(error.what()).find("changed outside Files")!=std::string_view::npos;
}
check(rejected && editor.readPage(0)=="editor buffer","external edit was overwritten or the draft was cleared");
TextDocument reloaded(file,true,TextEncoding::automatic,true);
check(reloaded.readPage(0)=="external bytes","reload did not take the external version");
reloaded.stage(0,"confirmed write");
check(reloaded.save() && reloaded.readPage(0)=="confirmed write","local save lost the new snapshot");
writeFile(file,"next change");
check(reloaded.readPage(0)=="confirmed write","the post-save editor lost snapshot isolation");
}
void bookmarkedLines(const fs::path &file)
{
const auto longLine=std::string(TextDocument::pageBytes+32,'x');
@@ -256,6 +285,7 @@ int main()
rejectExternalReplacement(fixture.directory / L"external.txt");
saveDraft(fixture.directory / L"created.txt");
hexBytes(fixture.directory / L"raw.bin");
watchedEditor(fixture.directory / L"watched.txt");
bookmarkedLines(fixture.directory / L"bookmarks.txt");
comparisonEdits();
sparseFile(fixture.directory / L"5gib.log");
+31
View File
@@ -200,6 +200,37 @@ int main()
catch(const std::system_error &){}
verifyConnectionCancellation(client,key);
FilesConnection host(one,client,key);
{
const auto source=root/L"acl-source.txt", copied=root/L"acl-target.txt";
save(source,"source");
save(copied,"target");
auto get=fileRequest("copyPermissions",source);
const auto inherited=host.call(get);
checkFileReply(inherited);
auto acl=inherited.at("permissions").get<std::string>();
if(!acl.starts_with("D:P")) acl.insert(2,"P");
auto protect=fileRequest("applyCopyMetadata",source);
protect["permissions"]=acl;
const auto protectedSource=host.call(protect);
require(protectedSource.at("error")==ERROR_SUCCESS, "could not set a protected source DACL");
const auto permissions=host.call(get);
checkFileReply(permissions);
require(permissions.at("permissions").get<std::string>().starts_with("D:P"),
"copy permission action did not protect the Windows DACL");
auto apply=fileRequest("applyCopyMetadata",copied);
constexpr uint64_t modified=132537600000000000ULL;
apply["permissions"]=permissions.at("permissions");
apply["modified"]=modified;
const auto applied=host.call(apply);
require(applied.at("error")==ERROR_SUCCESS, "could not copy Windows metadata to the target");
auto result=host.call(fileRequest("copyPermissions",copied));
checkFileReply(result);
require(result.at("permissions")==permissions.at("permissions"),
"Windows permissions did not survive LAN metadata copy");
result=host.call(fileRequest("stat",copied));
checkFileReply(result);
require(result.at("modified")==modified,"LAN copy metadata lost the file modification time");
}
{
const Json hibernate={{"action","hibernate"}};
FilesConnection target(two,client,key);