Compare commits

..
Author SHA1 Message Date
agrynco 6467481d2f Merge pull request 'KSwitcher.Files: Restore FTP panels and recover LAN folders' (#160) from codex/issue-107-remote-panel-restore into prerelease
Refs #107
2026-11-25 17:22:57 +02:00
agrynco 7033c1e336 Restore FTP panels and recover interrupted LAN scans
Refs #107
2026-11-25 17:22:44 +02:00
agrynco 03145ae75a Merge pull request 'KSwitcher.Files: Unified diff and context folding' (#159) from codex/issue-106-unified-diff into prerelease
Refs #106
2026-11-25 17:04:17 +02:00
agrynco 9d57568351 Add unified comparison and context folding
Refs #106
2026-11-25 17:04:05 +02:00
agrynco f74b8b2ac0 Merge pull request 'KSwitcher.Files: Apply selected blocks in file comparison' (#158) from codex/issue-105-compare-apply into prerelease
Refs #105
2026-11-25 16:54:38 +02:00
agrynco 5bf2d7ab45 Apply selected blocks in file comparison
Refs #105
2026-11-25 16:54:25 +02:00
agrynco 4ab1f3c950 Merge pull request 'KSwitcher.Files: Збереження чернетки при перемиканні F6' (#157) from codex/issue-104-editor-draft into prerelease
Refs #104
2026-11-25 16:40:35 +02:00
agrynco 872c03823f Keep editor drafts when switching to the saved Viewer
Refs #104
2026-11-25 16:40:26 +02:00
agrynco 0c09fbdb88 Merge pull request 'KSwitcher.Files: Постійні закладки на рядки у Viewer' (#156) from codex/issue-103-viewer-bookmarks into prerelease
Refs #103
2026-11-25 16:32:33 +02:00
agrynco 50010c99ba Persist Viewer bookmarks and reopen files at saved lines
Refs #103
2026-11-25 16:32:23 +02:00
agrynco e92984d124 Merge pull request 'KSwitcher.Files: Hex Viewer для двійкових файлів' (#155) from codex/issue-102-hex-viewer into prerelease
Refs #102
2026-11-25 16:21:03 +02:00
agrynco 6f2f1f38e2 Show original file bytes in Hex Viewer
Refs #102
2026-11-25 16:20:52 +02:00
agrynco dc4e503c84 Merge pull request 'KSwitcher.Files: Перегляд зображень у Viewer та Quick View' (#154) from codex/issue-101-image-viewer into prerelease
Refs #101
2026-11-25 16:12:28 +02:00
17 changed files with 2027 additions and 332 deletions

No files matched your search

+53 -10
View File
@@ -42,6 +42,13 @@ Warning і початковий фокус на No.
Назви файлів і папок передаються в UTF-8. Для старого сервера, який
використовує системну кодову сторінку Windows, увімкни в профілі
**Use Windows encoding for file names** і підключися знову.
Після закриття Files окремо для кожної FTP-панелі зберігаються профіль,
каталог і рядок курсора. При наступному запуску Files відкриває цей каталог
і вибирає попередній рядок, якщо він ще існує. Коли каталог недоступний,
панель показує попередню локальну папку й причину помилки. **Ctrl+R**
повторює підключення. Натискання рядка стану відкриває повну причину
помилки й підтвердження повторної спроби. Вибір іншого джерела скасовує
відновлення.
- F5 копіює поточний або позначені файли й папки між локальною та
підключеною FTP-панелями в обидва боки. Призначенням є каталог іншої
панелі. Для одного елемента можна вказати ім’я копії в цьому каталозі.
@@ -61,16 +68,21 @@ Warning і початковий фокус на No.
активної панелі або по одному файлу з кожної панелі. Якщо в панелі немає
позначок, береться файл під курсором. Підтримуються локальні, LAN- та
FTP-файли. Файли показуються поруч із синхронною прокруткою, номерами
рядків і підсвічуванням вставок, видалень і замін. У замінених рядках
виділяється змінений фрагмент. **Previous** (F7) і **Next** (F8)
переходять між блоками змін. Подвійний клік відкриває повний текст пари рядків.
рядків і підсвічуванням вставок, видалень і замін. **Unified** перемикає
на єдину колонку з номерами рядків обох файлів, видаленнями зі знаком −
і вставками зі знаком +. Перемикання зберігає поточний блок.
**Fold unchanged** згортає довгі незмінені ділянки до рядка з лічильником
і залишає до трьох рядків контексту перед і після кожного блока.
У замінених рядках виділяється змінений фрагмент. **Previous** (F7) і
**Next** (F8) переходять між блоками змін в обох поданнях.
Подвійний клік відкриває повний текст пари рядків.
Лічильник, навігація й перемикач пробілів розміщені в одному компактному
рядку над заголовками файлів. Вікно закривається системним хрестиком або Esc.
Вікно має системну рамку зі зміною розміру й нативний тулбар Windows
зі стрілками переходу, розділювачами та кнопкою-перемикачем пробілів.
Текст файлів і порожня область під ним мають білий фон, рядки
зі змінами виділяються кольором. Область порівняння займає всю ширину вікна.
Центральний розділювач можна перетягнути мишею. Під час зміни розміру
У поданні поруч центральний розділювач можна перетягнути мишею. Під час зміни розміру
вікна пропорція колонок зберігається.
Ctrl+колесо змінює масштаб тексту в поточному вікні.
Порівняння відкривається в окремому вікні із власною іконкою та кнопкою
@@ -79,13 +91,20 @@ Warning і початковий фокус на No.
Shift+F11 відкриває порівняння. Комбінацію можна змінити в тому ж розділі,
і меню Commands показує поточне призначення.
Рядки зіставляються за вмістом. Зміни лише у відступах і кінцевих пробілах
типово пропускаються. Перемикач **Show whitespace changes** показує їх.
типово пропускаються. Перемикач **Show whitespace changes** показує їх
в обох поданнях і враховує під час згортання.
Вставлені й видалені порожні рядки враховуються завжди.
**Apply to left/right** копіює виділений блок у відповідну сторону.
Порівняння перераховується, а змінену сторону позначає зірочка.
**Undo** або **Ctrl+Z** повертає останню незаписану дію.
**Save left/right** зберігає відповідну сторону, **Ctrl+S** зберігає обидві.
Зовнішня зміна цільового файла зупиняє запис і залишає правки для перегляду.
Закриття зі змінами пропонує Save, Discard або Cancel.
Кнопка розгортання в системному заголовку збільшує вікно порівняння
до робочої області екрана. Повторне натискання відновлює попередній розмір.
Вікно працює в режимі перегляду. Підтримуються UTF-8 і UTF-16 з BOM,
до 2 МіБ і 100 000 рядків на файл. Стилі переносу рядків порівнюються
як рівнозначні.
Підтримуються UTF-8 і UTF-16 з BOM, до 2 МіБ і 100 000 рядків на файл.
Стилі переносу рядків порівнюються як рівнозначні. Під час запису
зберігаються кодування, BOM і наявні кінці рядків цільового файла.
- У меню Files і його списках, що випадають, стрілки вгору й вниз
переходять між першим і останнім пунктами циклічно та оминають розділювачі.
@@ -311,8 +330,18 @@ Warning і початковий фокус на No.
При повторному відкритті Files пропонує перейти до вже
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
Помилка збереження залишає відкритим редактор зі змінами.
Viewer показує збережену версію, а чернетка зберігається в поточному
вікні з позначкою Draft retained. Повторне F6 повертає правки, сторінку,
виділення й прокрутку.
Для нового файла Viewer показує порожній документ. Закриття вікна
з чернеткою в обох режимах пропонує Save, Discard або Cancel.
- **Shift+F3** або **Commands → View as hex** відкриває файл у Hex Viewer.
**F4** у Viewer перемикає текстовий або форматований перегляд і Hex.
Hex показує 64-бітну адресу, 16 вихідних байтів у рядку й ASCII.
Нульові й недруковані байти видно в hex, а в ASCII їх позначає крапка.
Блоки по 64 КіБ перемикаються через Ctrl+Page Up, Ctrl+Page Down або F5.
Esc повертає до попереднього режиму Viewer або, якщо файл відкрито
напряму в Hex, до файлової панелі.
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному
порядку. Коли відкрито лише Files, активна панель не змінюється.
@@ -390,6 +419,15 @@ Warning і початковий фокус на No.
Ctrl+Shift+Home/End відкривають першу й останню. Ctrl+F шукає в поточній
сторінці, F3 повторює пошук. Ctrl+A виділяє поточну сторінку.
Історія Undo/Redo діє в межах відкритої сторінки.
- **Ctrl+D** або **Navigate → Add bookmark** у Viewer додає закладку
на рядок локального файла. Номер рахується від початку файла, а назва
необов’язкова. У Markdown номер можна вказати за вихідним текстом.
**Navigate → Bookmarks in this file** і **All bookmarks** відкривають
відповідні списки. **Commands → Viewer bookmarks** у панелях працює,
навіть коли Viewer закрито. Списки зберігаються після перезапуску.
Open переходить до рядка, для Markdown у вихідному тексті. Rename
змінює назву, Remove видаляє закладку. Якщо файл або рядок недоступний,
Files показує повідомлення.
- Початкова сторінка займає близько 1 МіБ файла. Для вставок і редагування
сторінка може вирости до 8 МіБ у UTF-8. Зміни інших сторінок тимчасово
зберігаються на диску. F2 або Ctrl+S потоково записують нову копію в
@@ -522,6 +560,11 @@ Warning і початковий фокус на No.
- Меню Change drive показує літеру, тип, загальний обсяг і вільне місце. Відкриття меню запускає нове LAN-виявлення. Секція KSwitcher LAN показує збережені пари, зокрема офлайн. Після кожного відкриття меню асинхронно запитує диски й показує їх під назвою відповідного ПК. Поки триває запит, видно стан завантаження. Якщо запит не вдався, видно помилку. Повторне відкриття запускає новий запит. Кожна панель має власний диск і шлях, а в заголовку віддаленої панелі перед шляхом показано назву ПК.
- Список дисків і файлові операції використовують права облікового запису Windows, під яким працює віддалений KSwitcher. Достатньо спарювання й доступного TCP 45885, спільні папки налаштовувати не потрібно.
- Якщо читання LAN-папки переривається через мережеву помилку, Files
зберігає поточний список і до трьох разів повторює читання того самого
ПК, диска й каталогу. Після відновлення курсор залишається на наявному
рядку. Рядок стану показує причину збою й дію **Ctrl+R** для повторної
спроби. Перехід в інший каталог або джерело скасовує попередню спробу.
- F5, F6, F8 і Shift+Delete у віддалених панелях використовують спільні підтвердження, попередження й прогрес. F5/F6 працюють із файлами та деревами папок між локальними й віддаленими панелями, зокрема між двома різними ПК. Між шляхами одного віддаленого ПК вміст копіюється на ньому. F8 використовує кошик того ПК, на якому лежить файл.
- Після розриву з’єднання повтори F5 або F6 до того самого призначення. Віддалене копіювання відновлюється з підтвердженої позиції, якщо збережені байти відповідають початку вихідного файла. Підтверджене скасування видаляє частковий запис поточного файла. Завершені файли лишаються на місці. Наявний файл призначення замінюється після повного запису, а при переміщенні джерело видаляється після підтвердження запису призначення.
+29 -4
View File
@@ -100,6 +100,30 @@ BEGIN
CONTROL "&Processes…", 103, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 14, 38, 75, 15
END
613 DIALOGEX 0, 0, 255, 100
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "&Line:", 534, 14, 17, 60, 12
FAR_EDIT(536, ES_NUMBER | WS_BORDER, 75, 16, 166, 14)
LTEXT "&Name (optional):", 537, 14, 37, 227, 12
FAR_EDIT(535, WS_BORDER, 14, 50, 227, 14)
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 76, 60, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 132, 76, 60, 16
END
614 DIALOGEX 0, 0, 418, 166
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "", 541, 14, 16, 390, 12, SS_PATHELLIPSIS | SS_NOPREFIX
LISTBOX 538, 14, 33, 390, 100, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP
CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 83, 140, 58, 16
CONTROL "Re&name", 539, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 140, 58, 16
CONTROL "&Remove", 540, "Button", BS_OWNERDRAW | WS_TABSTOP, 211, 140, 58, 16
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 275, 140, 58, 16
END
609 DIALOGEX 0, 0, 350, 135
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
@@ -394,11 +418,12 @@ EXSTYLE WS_EX_APPWINDOW
CAPTION "Compare files"
FONT 9, "Segoe UI"
BEGIN
LTEXT "", 400, 4, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 401, 259, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 45, 510, 207
LTEXT "", 400, 4, 50, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
LTEXT "", 401, 259, 50, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX
CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 65, 510, 187
CONTROL "", 407, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 8, 200, 19
LTEXT "", 403, 216, 12, 98, 14
CONTROL "", 408, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 28, 490, 19
END
115 DIALOGEX 0, 0, 290, 58
@@ -406,7 +431,7 @@ STYLE DS_SETFONT | DS_CENTER | WS_POPUP
CAPTION "Compare files"
FONT 10, "Consolas"
BEGIN
LTEXT "Reading and comparing files...", -1, 14, 15, 262, 13
LTEXT "Reading and comparing files...", 548, 14, 15, 262, 13
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 101, 31, 88, 17
END
+574 -137
View File
@@ -67,6 +67,11 @@ struct CompareFile
std::wstring label;
std::optional<FilesPeer> peer;
std::optional<FtpProfile> ftp;
std::optional<ks::files::RemoteTextSource> remote;
ks::files::RemoteTextRevision revision;
std::string originalBytes;
std::wstring originalText;
bool dirty{};
};
struct CompareRow
@@ -79,14 +84,31 @@ struct CompareRow
bool hasChange(bool showWhitespace) const {return changed && (showWhitespace || !whitespaceOnly);}
};
struct ComparisonDisplayRow
{
int first=-1,past{};
int side=-1;
bool folded() const {return past>first+1;}
};
struct FileComparison
{
static constexpr std::array controls{400,401,402,403,407};
static constexpr std::array controls{400,401,402,403,407,408};
CompareFile files[2];
std::vector<std::wstring> lines[2];
ks::files::ComparisonText text[2];
std::vector<CompareRow> rows;
std::vector<int> changes,allChanges;
bool showWhitespace{};
std::vector<ComparisonDisplayRow> displayRows;
std::vector<std::array<int,2>> displayPositions;
std::vector<int> displayBlockStarts;
struct Undo
{
int side{};
ks::files::ComparisonReplace edit;
};
std::vector<Undo> undo;
bool working{};
bool showWhitespace{},unified{},foldContext{};
RECT initialClient{};
std::array<RECT,controls.size()> initialControls{};
SIZE minimumWindow{};
@@ -118,7 +140,8 @@ void layoutComparisonHeaders(HWND dialog,const FileComparison &comparison)
RECT bounds{};
GetClientRect(list,&bounds);
MapWindowPoints(list,dialog,reinterpret_cast<POINT*>(&bounds),2);
const auto middle=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
const auto width=bounds.right-bounds.left;
const auto middle=bounds.left+(comparison.unified?width/2:comparisonSplitX(comparison,width));
const auto inset=comparison.initialControls[0].left;
for(int side=0;side<2;++side)
{
@@ -206,63 +229,132 @@ bool handleComparisonMessage(MSG &message)
}
return true;
}
std::vector<std::wstring> readComparisonLines(const CompareFile &input,const std::atomic_bool &canceled)
struct CompareCache
{
struct TemporaryDirectory
fs::path directory;
fs::path create()
{
fs::path path;
~TemporaryDirectory()
{
if(path.empty()) return;
std::error_code ignored;
fs::remove_all(path,ignored);
}
} temporary;
auto path=input.path;
if(input.ftp || input.peer)
{
const auto directory=fs::temp_directory_path()/(L"ks-files-compare-"+ks::wide(ks::lan::randomHex(16)));
requireFileOperation(fs::create_directory(directory),ERROR_ALREADY_EXISTS);
temporary.path=directory;
path=directory/L"file";
CopyHost source(input.peer?&*input.peer:nullptr,input.ftp);
const auto info=source.stat(input.path,canceled);
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),
ERROR_NOT_SUPPORTED);
requireFileOperation(info->size<=compareFileLimit,ERROR_FILE_TOO_LARGE);
FilesConnection local;
const auto progress=[&](uint64_t,uint64_t){return !canceled;};
if(source.ftp) downloadFtpFile(*source.ftp,local,input.path,path,*info,false,progress);
else ks::lan::streamFile(*source.files,local,input.peer->id,input.path,path,info->size,
info->modified,false,false,progress);
auto path=fs::temp_directory_path()/(L"ks-files-compare-"+ks::wide(ks::lan::randomHex(16)));
requireFileOperation(fs::create_directory(path),ERROR_ALREADY_EXISTS);
directory=std::move(path);
return directory/L"file";
}
ks::files::TextDocument document(path,false);
~CompareCache()
{
if(directory.empty()) return;
std::error_code ignored;
fs::remove_all(directory,ignored);
}
};
ks::files::RemoteTextRevision comparisonLocalRevision(const fs::path &path)
{
WIN32_FILE_ATTRIBUTE_DATA info{};
checkFileOperation(GetFileAttributesExW(path.c_str(),GetFileExInfoStandard,&info)!=FALSE);
requireFileOperation(!(info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY),ERROR_NOT_SUPPORTED);
const auto size=(uint64_t(info.nFileSizeHigh)<<32)|info.nFileSizeLow;
const auto stamp=(uint64_t(info.ftLastWriteTime.dwHighDateTime)<<32)|info.ftLastWriteTime.dwLowDateTime;
return {size,stamp,(info.dwFileAttributes&(FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_REPARSE_POINT))==0};
}
std::string comparisonRawBytes(const ks::files::TextDocument &document,const std::atomic_bool &canceled)
{
requireFileOperation(document.size()<=compareFileLimit,ERROR_FILE_TOO_LARGE);
std::string raw;
raw.reserve(static_cast<size_t>(document.size()));
while(raw.size()<document.size())
{
requireFileOperation(!canceled,ERROR_CANCELLED);
raw+=document.readBytes(raw.size(),ks::files::hexPageBytes);
}
return raw;
}
ks::files::ComparisonText readComparisonLines(CompareFile &input,const std::atomic_bool &canceled)
{
CompareCache temp;
auto path=input.path;
if(input.ftp) input.remote=ftpTextSource(*input.ftp);
else if(input.peer)
{
FilesConnection source(&*input.peer);
const auto info=statFile(source,input.path);
requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND);
requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),ERROR_NOT_SUPPORTED);
input.remote=ks::files::createLanTextSource(*input.peer);
}
if(input.remote)
{
path=temp.create();
input.revision=input.remote->download(input.path,path,false,[&](uint64_t,uint64_t){return !canceled;},
compareFileLimit);
}
else input.revision=comparisonLocalRevision(path);
ks::files::TextDocument document(path,false);
input.originalBytes=comparisonRawBytes(document,canceled);
std::string text;
for(uint64_t page=0;page<document.pages() && !canceled;++page) text+=document.readPage(page);
requireFileOperation(!canceled,ERROR_CANCELLED);
if(std::any_of(text.begin(),text.end(),[](unsigned char ch){
return ch<32 && ch!='\t' && ch!='\r' && ch!='\n' && ch!='\f';
})) throw std::runtime_error("Select two text files.");
if(!input.remote && (comparisonLocalRevision(path).modified!=input.revision.modified ||
comparisonRawBytes(document,canceled)!=input.originalBytes))
throw std::runtime_error("The file changed while it was read for comparison.");
if(text.empty()) return {};
const auto bytes=static_cast<int>(text.size());
const auto count=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,nullptr,0);
if(!count) throw std::runtime_error("Compare files supports UTF-8 and UTF-16 text.");
std::wstring decoded(count,L'\0');
checkFileOperation(MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,decoded.data(),count)!=0);
std::vector<std::wstring> lines;
size_t start=0;
while(true)
auto result=ks::files::splitComparisonText(decoded);
if(result.lines.size()>100'000) throw std::runtime_error("Each file can contain up to 100,000 lines.");
input.originalText=std::move(decoded);
return result;
}
void saveComparisonFile(CompareFile &file,const ks::files::ComparisonText &text,const std::atomic_bool &canceled)
{
requireFileOperation(file.revision.editable,ERROR_ACCESS_DENIED);
CompareCache temporary;
auto target=file.path;
if(file.remote)
{
requireFileOperation(!canceled,ERROR_CANCELLED);
if(lines.size()==100'000) throw std::runtime_error("Each file can contain up to 100,000 lines.");
const auto end=decoded.find_first_of(L"\r\n",start);
lines.push_back(decoded.substr(start,end==decoded.npos?end:end-start));
if(end==decoded.npos) break;
start=end+((decoded[end]==L'\r' && end+1<decoded.size() && decoded[end+1]==L'\n')?2:1);
target=temporary.create();
const auto revision=file.remote->download(file.path,target,true,[&](uint64_t,uint64_t){return !canceled;},
compareFileLimit);
if(revision.modified!=file.revision.modified || revision.size!=file.revision.size)
throw std::runtime_error("The file changed since it was compared. Open a new comparison before saving.");
}
return lines;
else
{
const auto revision=comparisonLocalRevision(target);
requireFileOperation(revision.editable,ERROR_ACCESS_DENIED);
if(revision.modified!=file.revision.modified || revision.size!=file.revision.size)
throw std::runtime_error("The file changed since it was compared. Open a new comparison before saving.");
}
ks::files::TextDocument document(target,true);
if(comparisonRawBytes(document,canceled)!=file.originalBytes)
throw std::runtime_error("The file changed since it was compared. Open a new comparison before saving.");
auto joined=text.joined();
const auto contents=ks::utf8(joined);
const auto bytes=document.encoding()==ks::files::TextEncoding::utf8?contents.size():
joined.size()*sizeof(wchar_t);
requireFileOperation(bytes+document.boundary(0)<=compareFileLimit,ERROR_FILE_TOO_LARGE);
for(uint64_t page=1;page<document.pages();++page) document.stage(page,{});
document.stage(0,contents);
requireFileOperation(!canceled,ERROR_CANCELLED);
if(!document.save()) throw std::runtime_error("The file was saved but could not be reopened.");
if(file.remote)
file.revision=file.remote->upload(file.path,target,file.revision);
else file.revision=comparisonLocalRevision(target);
const std::atomic_bool committed{};
file.originalBytes=comparisonRawBytes(document,committed);
file.originalText=std::move(joined);
file.dirty=false;
}
std::wstring_view comparisonContent(std::wstring_view line)
@@ -274,7 +366,7 @@ std::wstring_view comparisonContent(std::wstring_view line)
void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
{
const auto &left=result.lines[0],&right=result.lines[1];
const auto &left=result.text[0].lines,&right=result.text[1].lines;
std::map<std::wstring_view,unsigned> ids;
std::map<unsigned,unsigned> blankIds;
unsigned nextId=1;
@@ -313,8 +405,6 @@ void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
const auto append=[&](int x,int y)
{
CompareRow row{x,y,x<0 || y<0 || left[x]!=right[y]};
if(row.changed && (result.rows.empty() || !result.rows.back().changed))
result.allChanges.push_back(static_cast<int>(result.rows.size()));
if(row.changed && x>=0 && y>=0)
{
const auto &l=left[x],&r=right[y];
@@ -328,8 +418,6 @@ void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
if(row.commonEnd && l[l.size()-row.commonEnd]>=0xdc00 && l[l.size()-row.commonEnd]<=0xdfff)
--row.commonEnd;
}
if(row.hasChange(false) && (result.rows.empty() || !result.rows.back().hasChange(false)))
result.changes.push_back(static_cast<int>(result.rows.size()));
result.rows.push_back(row);
};
const auto change=[&](size_t x,size_t y,size_t countLeft,size_t countRight)
@@ -436,6 +524,233 @@ void alignComparison(FileComparison &result,const std::atomic_bool &canceled)
append(static_cast<int>(a.size()-suffix+i),static_cast<int>(b.size()-suffix+i));
}
enum ComparisonCommand { applyLeft=409,applyRight,undoCompare,saveLeft,saveRight,saveComparison,
unifiedCompare,foldCompareContext };
struct ComparisonProgress
{
const wchar_t *status;
bool cancelable=true;
std::atomic_bool canceled{};
};
INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp);
template<class Work>
bool runComparisonWork(HWND owner,const wchar_t *status,bool cancelable,const Work &work)
{
ComparisonProgress state{status,cancelable};
FileOperationUi worker;
FilesModalDialog progress(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(115),owner,
comparisonProgressDialog,reinterpret_cast<LPARAM>(&state),false);
if(!progress.window()) throw std::runtime_error("Could not open the comparison progress dialog.");
progress.show();
try {worker.run(progress.window(),state.canceled,[&]{work(state.canceled);});}
catch(const std::system_error &error)
{
if(error.code().value()==ERROR_CANCELLED) return false;
throw;
}
return !state.canceled;
}
std::optional<ks::files::ComparisonReplace> comparisonBlock(const FileComparison &comparison,int side,LRESULT selected)
{
if(selected<0 || static_cast<size_t>(selected)>=comparison.rows.size() ||
!comparison.rows[selected].hasChange(comparison.showWhitespace)) return {};
auto first=static_cast<size_t>(selected),end=first+1;
while(first>0 && comparison.rows[first-1].hasChange(comparison.showWhitespace)) --first;
while(end<comparison.rows.size() && comparison.rows[end].hasChange(comparison.showWhitespace)) ++end;
const auto line=[](const CompareRow &row,int file){return file==0?row.left:row.right;};
const auto &target=comparison.text[side];
const auto &source=comparison.text[1-side];
ks::files::ComparisonReplace edit{target.lines.size()};
for(size_t row=first;row<end;++row)
{
const auto old=line(comparison.rows[row],side);
const auto incoming=line(comparison.rows[row],1-side);
if(old>=0)
{
edit.start=std::min(edit.start,static_cast<size_t>(old));
++edit.count;
}
if(incoming>=0)
{
edit.lines.push_back(source.lines[incoming]);
edit.endings.push_back(old>=0?target.endings[old]:target.preferred);
}
}
if(!edit.count)
for(size_t row=end;row<comparison.rows.size();++row)
if(const auto next=line(comparison.rows[row],side);next>=0)
{
edit.start=static_cast<size_t>(next);
break;
}
return edit;
}
void updateComparisonSummary(HWND dialog,const FileComparison &comparison);
ComparisonDisplayRow comparisonDisplayAnchor(const FileComparison &comparison,LRESULT position)
{
if(position<0 || static_cast<size_t>(position)>=comparison.displayRows.size()) return {};
return comparison.displayRows[position];
}
int comparisonDisplayPosition(const FileComparison &comparison,ComparisonDisplayRow anchor)
{
if(anchor.first<0 || comparison.displayPositions.empty()) return -1;
const auto last=static_cast<int>(comparison.displayPositions.size())-1;
const auto &positions=comparison.displayPositions[std::min(anchor.first,last)];
if(anchor.side>=0 && positions[anchor.side]>=0) return positions[anchor.side];
if(positions[0]<0) return positions[1];
if(positions[1]<0) return positions[0];
return std::min(positions[0],positions[1]);
}
void comparisonUpdateRows(HWND dialog,FileComparison &comparison,ComparisonDisplayRow selected,
ComparisonDisplayRow top={})
{
const auto list=GetDlgItem(dialog,402);
comparison.displayRows.clear();
const auto size=static_cast<int>(comparison.rows.size());
comparison.displayPositions.assign(size,{-1,-1});
comparison.displayBlockStarts.clear();
const auto append=[&](int first,int past,int side=-1)
{
const auto position=static_cast<int>(comparison.displayRows.size());
comparison.displayRows.push_back({first,past,side});
for(int row=first;row<past;++row)
{
auto &positions=comparison.displayPositions[row];
if(side<0) positions={position,position};
else positions[side]=position;
}
};
const auto changed=[&](int row){return comparison.rows[row].hasChange(comparison.showWhitespace);};
for(int first=0;first<size;)
{
const auto isChange=changed(first);
int past=first+1;
while(past<size && changed(past)==isChange) ++past;
if(isChange) comparison.displayBlockStarts.push_back(static_cast<int>(comparison.displayRows.size()));
if(isChange && comparison.unified)
{
for(int row=first;row<past;++row)
if(comparison.rows[row].left>=0) append(row,row+1,0);
for(int row=first;row<past;++row)
if(comparison.rows[row].right>=0) append(row,row+1,1);
}
else
{
constexpr int context=3;
const int hiddenFirst=comparison.foldContext && !isChange?first+(first>0?context:0):past;
const int hiddenPast=past-(past<size?context:0);
if(hiddenPast-hiddenFirst>=2)
{
for(int row=first;row<hiddenFirst;++row) append(row,row+1);
append(hiddenFirst,hiddenPast);
for(int row=hiddenPast;row<past;++row) append(row,row+1);
}
else for(int row=first;row<past;++row) append(row,row+1);
}
first=past;
}
SendMessageW(list,LB_SETCOUNT,comparison.displayRows.size(),0);
const auto position=comparisonDisplayPosition(comparison,selected);
if(const auto firstVisible=comparisonDisplayPosition(comparison,top);firstVisible>=0)
SendMessageW(list,LB_SETTOPINDEX,firstVisible,0);
SendMessageW(list,LB_SETCURSEL,position,0);
updateComparisonSummary(dialog,comparison);
InvalidateRect(list,nullptr,TRUE);
}
bool applyComparisonEdit(HWND dialog,FileComparison &comparison,int side,const ks::files::ComparisonReplace &edit,
bool remember)
{
const auto list=GetDlgItem(dialog,402);
const auto selected=comparisonDisplayAnchor(comparison,SendMessageW(list,LB_GETCURSEL,0,0));
const auto top=comparisonDisplayAnchor(comparison,SendMessageW(list,LB_GETTOPINDEX,0,0));
FileComparison candidate;
ks::files::ComparisonReplace reverse;
comparison.working=true;
try
{
const bool success=runComparisonWork(dialog,L"Updating comparison…",true,[&](const auto &stop) {
candidate.text[0]=comparison.text[0];
candidate.text[1]=comparison.text[1];
reverse=ks::files::replaceComparisonText(candidate.text[side],edit);
if(candidate.text[side].lines.size()>100'000)
throw std::runtime_error("Each file can contain up to 100,000 lines.");
alignComparison(candidate,stop);
});
comparison.working=false;
if(!success) return false;
if(remember) comparison.undo.push_back({side,std::move(reverse)});
else comparison.undo.pop_back();
comparison.text[side]=std::move(candidate.text[side]);
comparison.rows=std::move(candidate.rows);
comparison.files[side].dirty=comparison.text[side].joined()!=comparison.files[side].originalText;
comparisonUpdateRows(dialog,comparison,selected,top);
return true;
}
catch(const std::exception &error)
{
comparison.working=false;
showFileOperationError(dialog,L"Could not apply the block",ks::wide(error.what()));
return false;
}
}
bool commitComparison(HWND dialog,FileComparison &comparison,int requested=-1)
{
std::array committed{comparison.files[0],comparison.files[1]};
comparison.working=true;
bool success=true;
try
{
runComparisonWork(dialog,L"Saving comparison changes…",false,[&](const auto &stop) {
for(int side=0;side<2;++side)
if((requested<0 || requested==side) && comparison.files[side].dirty)
saveComparisonFile(committed[side],comparison.text[side],stop);
});
}
catch(const std::system_error &error)
{
const auto detail=error.code().value()==ERROR_FILE_TOO_LARGE?L"Each text file can be up to 2 MiB.":fileError(error);
showFileOperationError(dialog,L"Comparison save failed",detail);
success=false;
}
catch(const std::exception &error)
{
showFileOperationError(dialog,L"Comparison save failed",ks::wide(error.what()));
success=false;
}
comparison.working=false;
for(int side=0;side<2;++side)
if(!committed[side].dirty) comparison.files[side]=std::move(committed[side]);
std::erase_if(comparison.undo,[&](const auto &previous){return !comparison.files[previous.side].dirty;});
updateComparisonSummary(dialog,comparison);
return success;
}
void closeComparison(HWND dialog,FileComparison &comparison)
{
if(comparison.working || FilesModalDialog::dismissOwned(dialog)) return;
if(comparison.files[0].dirty || comparison.files[1].dirty)
{
const auto choice=showFilesNotice(dialog,L"Save changes from the comparison?",L"Compare files",
{.saveChanges=true});
if(choice==IDYES)
{
if(!commitComparison(dialog,comparison)) return;
}
else if(choice!=IDNO) return;
}
DestroyWindow(dialog);
}
void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &item)
{
const auto dc=item.hDC;
@@ -448,47 +763,23 @@ void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &it
const auto &palette=comparison.appearance.palette;
const auto cell=comparison.characterWidth;
fill(bounds,palette[CompareBackground]);
if(item.itemID>=comparison.rows.size()) return;
const auto &row=comparison.rows[item.itemID];
if(item.itemID>=comparison.displayRows.size()) return;
const auto &display=comparison.displayRows[item.itemID];
const auto &row=comparison.rows[display.first];
const bool changed=row.hasChange(comparison.showWhitespace);
const LONG center=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
const LONG gutter=std::max(4,cell);
const RECT link{center-gutter,bounds.top,center+gutter,bounds.bottom};
const auto highlight=palette[row.left<0?CompareInsert:row.right<0?CompareDelete:CompareReplace];
if(changed) fill(link,highlight);
else
{
const RECT divider{center,bounds.top,center+1,bounds.bottom};
fill(divider,palette[CompareDivider]);
}
if(changed)
{
const LONG middle=(bounds.top+bounds.bottom)/2;
const LONG start=row.left<0?bounds.top:middle,end=row.right<0?bounds.top:middle;
SetDCPenColor(dc,palette[CompareChangedText]);
const auto pen=SelectObject(dc,GetStockObject(DC_PEN));
MoveToEx(dc,link.left,start,nullptr);
LineTo(dc,link.right,end);
SelectObject(dc,pen);
}
const auto ink=palette[changed?CompareChangedText:CompareText];
SelectObject(dc,comparison.font?comparison.font:mono);
SetBkMode(dc,TRANSPARENT);
const auto ink=palette[changed?CompareChangedText:CompareText];
SetTextColor(dc,ink);
const auto drawSide=[&](int side,int number,RECT area)
const auto drawNumber=[&](int number,RECT area)
{
if(number<0)
{
fill(area,palette[ComparePadding]);
return;
}
if(changed) fill(area,highlight);
const auto numberText=std::to_wstring(number+1);
RECT numberArea=area;
numberArea.right=std::min(area.right,area.left+7*cell);
DrawTextW(dc,numberText.c_str(),-1,&numberArea,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX);
area.left=std::min(area.right,numberArea.right+cell);
const auto &line=comparison.lines[side][number];
if(number<0) return;
const auto text=std::to_wstring(number+1);
DrawTextW(dc,text.c_str(),-1,&area,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX);
};
const auto drawContent=[&](int side,int number,RECT area)
{
const auto &line=comparison.text[side].lines[number];
const auto paneWidth=area.right-area.left;
if(paneWidth<=0) return;
const auto limit=static_cast<size_t>(paneWidth/cell+2)*4;
@@ -519,8 +810,62 @@ void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &it
}
else if(!visible.empty()) DrawTextW(dc,visible.data(),static_cast<int>(visible.size()),&area,flags);
};
drawSide(0,row.left,{bounds.left,bounds.top,link.left,bounds.bottom});
drawSide(1,row.right,{link.right,bounds.top,bounds.right,bounds.bottom});
if(display.folded())
{
fill(bounds,palette[ComparePadding]);
auto line=bounds;
line.left+=2*cell;
const auto label=L"… "+std::to_wstring(display.past-display.first)+L" unchanged lines …";
DrawTextW(dc,label.c_str(),-1,&line,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX);
}
else if(comparison.unified)
{
if(changed) fill(bounds,palette[display.side==0?CompareDelete:CompareInsert]);
RECT number=bounds;
number.right=std::min(bounds.right,bounds.left+7*cell);
if(display.side!=1) drawNumber(row.left,number);
number.left=number.right;
number.right=std::min(bounds.right,number.left+7*cell);
if(display.side!=0) drawNumber(row.right,number);
auto content=bounds;
content.left=std::min(bounds.right,number.right+3*cell);
if(changed)
{
RECT marker{std::min(bounds.right,number.right+cell),bounds.top,content.left,bounds.bottom};
DrawTextW(dc,display.side==0?L"−":L"+",1,&marker,DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX);
}
const auto side=display.side<0?1:display.side;
drawContent(side,side==0?row.left:row.right,content);
}
else
{
const LONG center=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left);
const LONG gutter=std::max(4,cell);
const RECT link{center-gutter,bounds.top,center+gutter,bounds.bottom};
const auto highlight=palette[row.left<0?CompareInsert:row.right<0?CompareDelete:CompareReplace];
if(changed)
{
fill(link,highlight);
const LONG middle=(bounds.top+bounds.bottom)/2;
SetDCPenColor(dc,ink);
const auto pen=SelectObject(dc,GetStockObject(DC_PEN));
MoveToEx(dc,link.left,row.left<0?bounds.top:middle,nullptr);
LineTo(dc,link.right,row.right<0?bounds.top:middle);
SelectObject(dc,pen);
}
else fill({center,bounds.top,center+1,bounds.bottom},palette[CompareDivider]);
const auto drawSide=[&](int side,int number,RECT area)
{
if(number<0) {fill(area,palette[ComparePadding]);return;}
if(changed) fill(area,highlight);
const auto end=std::min(area.right,area.left+7*cell);
drawNumber(number,{area.left,area.top,end,area.bottom});
area.left=std::min(area.right,end+cell);
drawContent(side,number,area);
};
drawSide(0,row.left,{bounds.left,bounds.top,link.left,bounds.bottom});
drawSide(1,row.right,{link.right,bounds.top,bounds.right,bounds.bottom});
}
if(item.itemState&ODS_SELECTED)
{
SetDCBrushColor(dc,ink);
@@ -530,6 +875,11 @@ void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &it
LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
{
if(message==WM_KEYDOWN && (GetKeyState(VK_CONTROL)&0x8000) && (wp=='Z' || wp=='S'))
{
SendMessageW(GetParent(control),WM_COMMAND,wp=='Z'?undoCompare:saveComparison,0);
return 0;
}
if(message==WM_KEYDOWN && (wp==VK_F7 || wp==VK_F8))
{
SendMessageW(GetParent(control),WM_COMMAND,wp==VK_F7?404:405,0);
@@ -540,7 +890,7 @@ LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UI
auto *comparison=reinterpret_cast<FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!comparison) return DefSubclassProc(control,message,wp,lp);
if(message==WM_MOUSEWHEEL && zoomComparison(dialog,*comparison,wp)) return 0;
if(message==WM_SETCURSOR || message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK)
if(!comparison->unified && (message==WM_SETCURSOR || message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK))
{
RECT client{};
GetClientRect(control,&client);
@@ -604,9 +954,12 @@ LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UI
// The list box repaints its rows but can leave earlier divider marks below them.
FillRect(dc,&blank,comparison->background?comparison->background:
static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
const RECT divider{middle,blank.top,middle+1,blank.bottom};
SetDCBrushColor(dc,comparison->appearance.palette[CompareDivider]);
FillRect(dc,&divider,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
if(!comparison->unified)
{
const RECT divider{middle,blank.top,middle+1,blank.bottom};
SetDCBrushColor(dc,comparison->appearance.palette[CompareDivider]);
FillRect(dc,&divider,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
}
ReleaseDC(control,dc);
}
}
@@ -626,6 +979,7 @@ void layoutComparison(HWND dialog)
if(id==400 || id==401) continue;
auto bounds=comparison->initialControls[i];
if(id==402) bounds={0,bounds.top,client.right,client.bottom};
if(id==408) bounds.right=client.right-bounds.left;
SetWindowPos(GetDlgItem(dialog,id),nullptr,bounds.left,bounds.top,
bounds.right-bounds.left,std::max(0L,bounds.bottom-bounds.top),
SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS);
@@ -636,12 +990,24 @@ void layoutComparison(HWND dialog)
void updateComparisonSummary(HWND dialog,const FileComparison &comparison)
{
const auto blocks=(comparison.showWhitespace?comparison.allChanges:comparison.changes).size();
const auto blocks=comparison.displayBlockStarts.size();
const auto summary=blocks==0?L"Text is identical":blocks==1?L"1 change block":
std::to_wstring(blocks)+L" change blocks";
SetDlgItemTextW(dialog,403,summary.c_str());
const auto toolbar=GetDlgItem(dialog,407);
for(const auto id:{404,405}) SendMessageW(toolbar,TB_ENABLEBUTTON,id,MAKELONG(blocks!=0,0));
const auto actions=GetDlgItem(dialog,408);
const auto row=comparisonDisplayAnchor(comparison,SendDlgItemMessageW(dialog,402,LB_GETCURSEL,0,0));
const bool selected=row.first>=0 && !row.folded() && comparison.rows[row.first].hasChange(comparison.showWhitespace);
for(int side=0;side<2;++side)
{
const auto &file=comparison.files[side];
const auto header=(file.dirty?L"* ":L"")+file.label+(file.revision.editable?L"":L" (read-only)");
SetDlgItemTextW(dialog,400+side,header.c_str());
SendMessageW(actions,TB_ENABLEBUTTON,applyLeft+side,MAKELONG(selected && file.revision.editable,0));
SendMessageW(actions,TB_ENABLEBUTTON,saveLeft+side,MAKELONG(file.dirty,0));
}
SendMessageW(actions,TB_ENABLEBUTTON,undoCompare,MAKELONG(!comparison.undo.empty(),0));
}
void initializeComparisonToolbar(HWND toolbar)
@@ -662,6 +1028,27 @@ void initializeComparisonToolbar(HWND toolbar)
SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast<LPARAM>(buttons));
}
void initializeComparisonActions(HWND toolbar)
{
SendMessageW(toolbar,TB_BUTTONSTRUCTSIZE,sizeof(TBBUTTON),0);
SendMessageW(toolbar,TB_SETEXTENDEDSTYLE,0,TBSTYLE_EX_MIXEDBUTTONS);
SendMessageW(toolbar,TB_SETMAXTEXTROWS,1,0);
constexpr BYTE text=BTNS_AUTOSIZE|BTNS_SHOWTEXT;
const auto separator=MulDiv(8,GetDpiForWindow(toolbar),96);
const TBBUTTON buttons[]{
{I_IMAGENONE,applyLeft,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Apply to left")},
{I_IMAGENONE,applyRight,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Apply to right")},
{I_IMAGENONE,undoCompare,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Undo")},
{separator,0,0,BTNS_SEP,{},0,0},
{I_IMAGENONE,saveLeft,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Save left")},
{I_IMAGENONE,saveRight,TBSTATE_ENABLED,text,{},0,reinterpret_cast<INT_PTR>(L"Save right")},
{separator,0,0,BTNS_SEP,{},0,0},
{I_IMAGENONE,unifiedCompare,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast<INT_PTR>(L"Unified")},
{I_IMAGENONE,foldCompareContext,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast<INT_PTR>(L"Fold unchanged")}
};
SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast<LPARAM>(buttons));
}
INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
auto *comparison=reinterpret_cast<FileComparison*>(GetWindowLongPtrW(dialog,DWLP_USER));
@@ -685,15 +1072,19 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
SendMessageW(dialog,WM_SETICON,ICON_SMALL,reinterpret_cast<LPARAM>(small));
SendMessageW(dialog,WM_SETICON,ICON_BIG,reinterpret_cast<LPARAM>(large));
ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,L"HrynCo.KSwitcher.Files.Compare");
for(int side=0;side<2;++side) SetDlgItemTextW(dialog,400+side,comparison->files[side].label.c_str());
initializeComparisonToolbar(toolbar);
updateComparisonSummary(dialog,*comparison);
const auto actions=GetDlgItem(dialog,408);
initializeComparisonActions(actions);
SetWindowSubclass(list,comparisonKeys,1,0);
SetWindowSubclass(toolbar,comparisonKeys,1,0);
SetWindowSubclass(actions,comparisonKeys,1,0);
applyComparisonAppearance(dialog,*comparison);
SendMessageW(list,LB_SETCOUNT,comparison->rows.size(),0);
layoutComparisonHeaders(dialog,*comparison);
if(!comparison->changes.empty()) SendMessageW(list,LB_SETCURSEL,comparison->changes.front(),0);
const auto first=std::find_if(comparison->rows.begin(),comparison->rows.end(),
[](const auto &row){return row.hasChange(false);});
ComparisonDisplayRow selected;
if(first!=comparison->rows.end()) selected.first=static_cast<int>(first-comparison->rows.begin());
comparisonUpdateRows(dialog,*comparison,selected);
return TRUE;
}
if(message==filesPreferencesChanged && comparison)
@@ -702,16 +1093,16 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
layoutComparisonHeaders(dialog,*comparison);
return TRUE;
}
if(message==WM_CLOSE)
if(message==WM_CLOSE && comparison)
{
DestroyWindow(dialog);
closeComparison(dialog,*comparison);
return TRUE;
}
if(message==WM_MOUSEWHEEL && comparison && zoomComparison(dialog,*comparison,wp)) return TRUE;
if(message==WM_NCDESTROY)
{
ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,nullptr);
comparisonWindows.erase(dialog);
if(comparisonWindows.erase(dialog)) ks::files::standaloneFilesWindowClosed();
return FALSE;
}
if(message==WM_GETMINMAXINFO && comparison && comparison->minimumWindow.cx)
@@ -737,45 +1128,92 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
if(message==WM_COMMAND && comparison)
{
const auto id=LOWORD(wp);
if(id==IDCANCEL) {DestroyWindow(dialog);return TRUE;}
if(id==406 && HIWORD(wp)==BN_CLICKED)
if(comparison->working) return TRUE;
if(id==IDCANCEL) {closeComparison(dialog,*comparison);return TRUE;}
if(id==applyLeft || id==applyRight)
{
comparison->showWhitespace=SendMessageW(toolbar,TB_ISBUTTONCHECKED,id,0)!=0;
updateComparisonSummary(dialog,*comparison);
InvalidateRect(list,nullptr,FALSE);
const auto side=id-applyLeft;
const auto selected=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETCURSEL,0,0));
if(!selected.folded() && comparison->files[side].revision.editable)
if(const auto edit=comparisonBlock(*comparison,side,selected.first))
applyComparisonEdit(dialog,*comparison,side,*edit,true);
SetFocus(list);
return TRUE;
}
const auto &changes=comparison->showWhitespace?comparison->allChanges:comparison->changes;
if(id==undoCompare)
{
if(!comparison->undo.empty())
{
const auto &previous=comparison->undo.back();
applyComparisonEdit(dialog,*comparison,previous.side,previous.edit,false);
}
SetFocus(list);
return TRUE;
}
if(id==saveLeft || id==saveRight || id==saveComparison)
{
if(comparison->files[0].dirty || comparison->files[1].dirty)
commitComparison(dialog,*comparison,id==saveComparison?-1:id-saveLeft);
SetFocus(list);
return TRUE;
}
if((id==406 || id==unifiedCompare || id==foldCompareContext) && HIWORD(wp)==BN_CLICKED)
{
const auto selected=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETCURSEL,0,0));
const auto top=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETTOPINDEX,0,0));
const auto source=id==406?toolbar:GetDlgItem(dialog,408);
const bool enabled=SendMessageW(source,TB_ISBUTTONCHECKED,id,0)!=0;
if(id==406) comparison->showWhitespace=enabled;
if(id==unifiedCompare)
{
if(comparison->splitDragOffset) ReleaseCapture();
comparison->unified=enabled;
layoutComparisonHeaders(dialog,*comparison);
}
if(id==foldCompareContext) comparison->foldContext=enabled;
comparisonUpdateRows(dialog,*comparison,selected,top);
SetFocus(list);
return TRUE;
}
const auto &changes=comparison->displayBlockStarts;
if((id==404 || id==405) && !changes.empty())
{
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
if(id==404)
const auto next=std::upper_bound(changes.begin(),changes.end(),current);
if(id==404 && next!=changes.begin())
{
const auto previous=std::lower_bound(changes.begin(),changes.end(),current);
if(previous!=changes.begin()) SendMessageW(list,LB_SETCURSEL,*std::prev(previous),0);
}
else
{
const auto next=std::upper_bound(changes.begin(),changes.end(),current);
if(next!=changes.end()) SendMessageW(list,LB_SETCURSEL,*next,0);
const auto here=comparisonDisplayAnchor(*comparison,current);
const bool inBlock=here.first>=0 && !here.folded() &&
comparison->rows[here.first].hasChange(comparison->showWhitespace);
const auto previous=std::prev(next);
if(!inBlock) SendMessageW(list,LB_SETCURSEL,*previous,0);
if(inBlock && previous!=changes.begin())
SendMessageW(list,LB_SETCURSEL,*std::prev(previous),0);
}
if(id==405 && next!=changes.end()) SendMessageW(list,LB_SETCURSEL,*next,0);
updateComparisonSummary(dialog,*comparison);
return TRUE;
}
if(id==402 && HIWORD(wp)==LBN_DBLCLK)
{
const auto current=SendMessageW(list,LB_GETCURSEL,0,0);
if(current>=0 && static_cast<size_t>(current)<comparison->rows.size())
const auto current=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETCURSEL,0,0));
if(current.first>=0 && !current.folded())
{
const auto &row=comparison->rows[current];
const auto &row=comparison->rows[current.first];
const auto side=[&](int file,int line)
{
return line<0?std::wstring(L"—"):comparison->lines[file][line];
return line<0?std::wstring(L"—"):comparison->text[file].lines[line];
};
const auto detail=L"Left\n"+side(0,row.left)+L"\n\nRight\n"+side(1,row.right);
showFilesNotice(dialog,detail.c_str(),L"Line details");
}
return TRUE;
}
if(id==402 && HIWORD(wp)==LBN_SELCHANGE)
{
updateComparisonSummary(dialog,*comparison);
return TRUE;
}
}
return FALSE;
}
@@ -785,13 +1223,20 @@ INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPA
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
const auto &state=*reinterpret_cast<ComparisonProgress *>(lp);
prepareTextDialog(dialog);
SetDlgItemTextW(dialog,548,state.status);
EnableWindow(GetDlgItem(dialog,IDCANCEL),state.cancelable);
return TRUE;
}
if(message==WM_COMMAND && LOWORD(wp)==IDCANCEL)
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
{
*reinterpret_cast<std::atomic_bool*>(GetWindowLongPtrW(dialog,DWLP_USER))=true;
EnableWindow(GetDlgItem(dialog,IDCANCEL),FALSE);
auto &state=*reinterpret_cast<ComparisonProgress *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(state.cancelable)
{
state.canceled=true;
EnableWindow(GetDlgItem(dialog,IDCANCEL),FALSE);
}
return TRUE;
}
return paintTextDialog(dialog,message,wp,lp,L" Compare files ");
@@ -828,41 +1273,33 @@ void compareSelectedFiles(HWND owner)
L"Compare files");
return;
}
std::atomic_bool canceled{};
try
{
{
FileOperationUi worker;
FilesModalDialog progress(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(115),owner,
comparisonProgressDialog,reinterpret_cast<LPARAM>(&canceled),false);
if(!progress.window()) throw std::runtime_error("Could not open the progress dialog.");
progress.show();
worker.run(progress.window(),canceled,[&]
{
for(int side=0;side<2;++side)
comparison.lines[side]=readComparisonLines(comparison.files[side],canceled);
alignComparison(comparison,canceled);
});
}
if(!canceled)
const bool read=runComparisonWork(owner,L"Reading and comparing files…",true,[&](const auto &stop) {
for(int side=0;side<2;++side)
comparison.text[side]=readComparisonLines(comparison.files[side],stop);
alignComparison(comparison,stop);
});
if(read)
{
const auto window=CreateDialogParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(114),nullptr,
comparisonDialog,reinterpret_cast<LPARAM>(&comparison));
if(!window) throw std::runtime_error("Could not open the comparison window.");
comparisonWindows.emplace(window,std::move(state));
ks::files::standaloneFilesWindowOpened();
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
SetFocus(GetDlgItem(window,402));
}
}
catch(const std::system_error &error)
{
if(canceled || error.code().value()==ERROR_CANCELLED) return;
if(error.code().value()==ERROR_CANCELLED) return;
const auto detail=error.code().value()==ERROR_FILE_TOO_LARGE?L"Each text file can be up to 2 MiB.":
fileError(error);
showFileOperationError(owner,L"Comparison failed",detail);
}
catch(const std::exception &error)
{
if(!canceled) showFileOperationError(owner,L"Comparison failed",ks::wide(error.what()));
showFileOperationError(owner,L"Comparison failed",ks::wide(error.what()));
}
}
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include <algorithm>
#include <string>
#include <string_view>
#include <vector>
namespace ks::files
{
enum class ComparisonEnding { absent, crlf, lf, cr };
inline std::wstring_view comparisonEndingText(ComparisonEnding ending)
{
switch(ending)
{
case ComparisonEnding::crlf: return L"\r\n";
case ComparisonEnding::lf: return L"\n";
case ComparisonEnding::cr: return L"\r";
default: return {};
}
}
struct ComparisonText
{
std::vector<std::wstring> lines;
std::vector<ComparisonEnding> endings;
ComparisonEnding preferred=ComparisonEnding::crlf;
std::wstring joined() const
{
std::wstring result;
for(size_t i=0;i<lines.size();++i)
{
result+=lines[i];
if(i+1<lines.size())
result+=comparisonEndingText(endings[i]==ComparisonEnding::absent?preferred:endings[i]);
}
return result;
}
};
inline ComparisonText splitComparisonText(std::wstring_view contents)
{
ComparisonText result;
if(contents.empty()) return result;
size_t start=0;
while(true)
{
const auto end=contents.find_first_of(L"\r\n",start);
result.lines.emplace_back(contents.substr(start,end==contents.npos?end:end-start));
auto ending=ComparisonEnding::absent;
if(end!=contents.npos)
ending=contents[end]==L'\n'?ComparisonEnding::lf:
end+1<contents.size() && contents[end+1]==L'\n'?ComparisonEnding::crlf:ComparisonEnding::cr;
result.endings.push_back(ending);
if(ending==ComparisonEnding::absent) break;
if(result.endings.size()==1) result.preferred=ending;
start=end+(ending==ComparisonEnding::crlf?2:1);
}
return result;
}
struct ComparisonReplace
{
size_t start{}, count{};
std::vector<std::wstring> lines;
std::vector<ComparisonEnding> endings;
};
inline ComparisonReplace replaceComparisonText(ComparisonText &document,const ComparisonReplace &change)
{
const auto first=document.lines.begin()+change.start, last=first+change.count;
const auto firstEnding=document.endings.begin()+change.start, lastEnding=firstEnding+change.count;
ComparisonReplace reverse{change.start,change.lines.size(),{first,last},{firstEnding,lastEnding}};
document.lines.erase(first,last);
document.lines.insert(document.lines.begin()+change.start,change.lines.begin(),change.lines.end());
document.endings.erase(firstEnding,lastEnding);
document.endings.insert(document.endings.begin()+change.start,change.endings.begin(),change.endings.end());
return reverse;
}
}
+1
View File
@@ -75,6 +75,7 @@ void startFileSearch(Panel &panel,Panel::FindOptions options)
{
if(panel.scanRequest) return;
cancelFolderSizes(panel);
panel.remoteRetry.reset();
panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)};
startDirectoryScan(panel);
}
+39 -2
View File
@@ -4,6 +4,7 @@ struct FtpProfile
INTERNET_PORT port=INTERNET_DEFAULT_FTP_PORT;
ks::Bytes secret;
bool legacyNames{};
std::string id;
};
std::vector<FtpProfile> ftpProfiles;
@@ -25,7 +26,7 @@ bool saveFtpProfiles(const std::vector<FtpProfile> &profiles)
for(const auto &profile:profiles)
rows.push_back({{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)},
{"port",profile.port},{"user",ks::utf8(profile.user)},{"secret",profile.secret},
{"legacyNames",profile.legacyNames}});
{"legacyNames",profile.legacyNames},{"id",profile.id}});
const auto data=rows.dump();
return data.size()<=ftpProfilesMaxBytes &&
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,REG_BINARY,data.data(),
@@ -58,7 +59,8 @@ bool loadFtpProfiles()
if(!port || port>65535) return false;
FtpProfile profile{ks::wide(row.at("name")),ks::wide(row.at("host")),
ks::wide(row.at("user")),static_cast<INTERNET_PORT>(port),row.at("secret").get<ks::Bytes>(),
row.value("legacyNames",false)};
row.value("legacyNames",false),row.value("id",std::string{})};
if(profile.id.empty()) profile.id="legacy:"+ks::utf8(profile.name);
if(profile.name.empty() || profile.host.empty()) return false;
profiles.push_back(std::move(profile));
}
@@ -99,6 +101,41 @@ void checkFileOperation(bool success)
if(!success) requireFileOperation(false,GetLastError());
}
std::wstring ftpFolderError(const std::system_error &error)
{
switch(error.code().value())
{
case ERROR_INTERNET_CANNOT_CONNECT: return L"Cannot reach FTP server.";
case ERROR_INTERNET_NAME_NOT_RESOLVED: return L"FTP host name could not be resolved.";
case ERROR_INTERNET_LOGIN_FAILURE: return L"FTP sign-in failed.";
case ERROR_INTERNET_TIMEOUT: return L"FTP connection timed out.";
default: break;
}
if(error.code().value()==ERROR_INTERNET_EXTENDED_ERROR)
{
DWORD response{},length{};
InternetGetLastResponseInfoW(&response,nullptr,&length);
if(length && length<=2048)
{
std::wstring text(length,L'\0');
if(InternetGetLastResponseInfoW(&response,text.data(),&length))
{
text.resize(length);
text.resize(std::min(text.size(),text.find_first_of(L"\r\n")));
if(!text.empty()) return text;
}
}
return L"The FTP server rejected the request.";
}
wchar_t message[256]{};
const DWORD length=FormatMessageW(FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_IGNORE_INSERTS,
GetModuleHandleW(L"wininet.dll"),error.code().value(),0,message,static_cast<DWORD>(std::size(message)),nullptr);
if(!length) return fileError(error);
std::wstring text(message,length);
while(!text.empty() && (text.back()==L'\r' || text.back()==L'\n')) text.pop_back();
return text;
}
class FtpSession
{
FtpHandle internet_{InternetOpenW(L"KSwitcher Files",INTERNET_OPEN_TYPE_DIRECT,nullptr,nullptr,0)};
+1
View File
@@ -91,6 +91,7 @@ INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
profile.secret=ks::protect(bytes);
SecureZeroMemory(bytes.data(),bytes.size());
}
profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16);
auto updated=ftpProfiles;
if(edit.index) updated[*edit.index]=std::move(profile);
else updated.push_back(std::move(profile));
+144 -55
View File
@@ -28,6 +28,7 @@
#include <wininet.h>
#include "files_terminal.h"
#include "files_archive.h"
#include "files_compare_text.h"
#include "files_image_decode.h"
#include "files_win32_directory.h"
#include "files_command_completion.h"
@@ -492,6 +493,13 @@ struct ArchiveLocation
std::shared_ptr<const ks::files::ArchiveEntries> entries;
};
struct RemotePanelLocation
{
fs::path directory,cursor;
std::string ftpProfile;
std::optional<FilesPeer> peer;
};
struct Panel
{
HWND path{}, list{}, heading{};
@@ -551,7 +559,17 @@ struct Panel
std::optional<FindOptions> find;
std::optional<size_t> navigationPosition;
std::optional<ArchiveLocation> archive;
unsigned reconnectAttempt{};
fs::path fallbackSelection;
};
struct RemoteRetry
{
RemotePanelLocation location;
std::wstring failure;
ULONGLONG retryAt{};
unsigned reconnectAttempt{};
};
std::optional<RemoteRetry> remoteRetry;
struct ScanResult
{
DirectoryWatch watch;
@@ -716,8 +734,14 @@ DWORD statusFields=defaultStatusFields;
std::vector<fs::path> drivePaths;
int driveHover=-1;
std::array<LONG,3> driveColumnStarts{};
HWND drivePeerService{};
bool drivePeerReplyReceived{};
struct FilesPeerLookup
{
HWND service{};
bool received{};
std::wstring error;
std::vector<FilesPeer> peers;
};
FilesPeerLookup *peerLookupRequest{};
std::wstring drivePeerLookupError;
std::vector<FilesPeer> drivePeers;
std::future<std::wstring> pendingPeerAction;
@@ -830,7 +854,7 @@ FileRowStyle panelRowStyle(const Panel &panel,size_t row,bool cursor,bool active
return resolveFileStyle(panel.rows[row].extension().native(),panel.sizes[row]!=L"Folder",panel.dimmed[row],
focused || marked || transferred,foreground,background,fileStyles,state,transferred);
}
void setStatus(const std::wstring &message);
void setStatus(const std::wstring &message,bool retryAction=false);
void refreshCommandHistory();
#include "files_command_history.inl"
@@ -1593,9 +1617,13 @@ void layout(HWND window,bool activeOnly)
}
uint64_t statusRevision{};
void setStatus(const std::wstring &message)
void setStatus(const std::wstring &message,bool retryAction)
{
++statusRevision;
const auto style=GetWindowLongPtrW(status,GWL_STYLE);
const auto actionStyle=(style&~(SS_ENDELLIPSIS|SS_PATHELLIPSIS|SS_WORDELLIPSIS|SS_NOTIFY)) |
(retryAction?(SS_ENDELLIPSIS|SS_NOTIFY):SS_PATHELLIPSIS);
if(style!=actionStyle) SetWindowLongPtrW(status,GWL_STYLE,actionStyle);
SetWindowTextW(status, message.c_str());
}
@@ -2058,12 +2086,15 @@ void copyCommandLineOrPanelNames(HWND owner)
void startFileSearch(Panel &panel,Panel::FindOptions options);
void refreshArchive(Panel &panel);
bool retryRemotePanel(Panel &panel,bool automatic=false,const fs::path &fallback={});
void refreshPanel(Panel &panel)
{
cancelFolderSizes(panel);
if(!panel.view.automaticSizes) panel.folderSizes.clear();
updateSelectionSummary(panel);
if(retryRemotePanel(panel)) return;
if(panel.scanRequest && (panel.scanRequest->peer || panel.scanRequest->ftp)) return;
if(panel.archive) refreshArchive(panel);
else if(panel.findOrigin) startFileSearch(panel,panel.findOrigin->options);
else open(panel,panel.directory,false);
@@ -2506,6 +2537,11 @@ void showFileDetails(const Panel &panel)
{
refreshQuickView(panel);
if(&panel==&panels[active] && showDirectoryScanProgress(panels[active])) return;
if(panel.remoteRetry)
{
setStatus(L"Ctrl+R to retry · "+panel.remoteRetry->failure,true);
return;
}
if(panel.findOrigin)
{
const auto error=panel.findOrigin->error;
@@ -2628,13 +2664,14 @@ std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &reque
(info.attributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path);
entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed);
return !stop.stop_requested();
});
},stop);
if(stop.stop_requested()) error=ERROR_CANCELLED;
if(error!=ERROR_NO_MORE_FILES && error!=ERROR_CANCELLED) requireFileOperation(false,error);
}
catch(const std::system_error &e)
{
failure=L"Cannot read FTP folder on "+request.ftp->name+L": "+fileError(e);
error=static_cast<DWORD>(e.code().value());
failure=ftpFolderError(e)+L" ("+request.ftp->name+L")";
}
catch(const std::exception &e)
{
@@ -2682,7 +2719,11 @@ std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &reque
opened=true;
if(!complete) error=ERROR_CANCELLED;
}
catch(const std::system_error &e){result->failure=peer->name+L" — "+fileError(e);}
catch(const std::system_error &e)
{
error=static_cast<DWORD>(e.code().value());
failure=peer->name+L" — "+fileError(e);
}
catch(const std::exception &){result->failure=L"Cannot open folder on "+peer->name;}
if(!opened && stop.stop_requested())
{
@@ -2727,7 +2768,7 @@ void appendTreeRows(Panel &panel,PanelRowsUpdate &rows);
bool samePanelSource(const Panel &panel,const std::optional<FilesPeer> &peer,const std::optional<FtpProfile> &ftp)
{
return (panel.peer?panel.peer->id:std::string{})==(peer?peer->id:std::string{}) &&
panel.ftp.has_value()==ftp.has_value() && (!panel.ftp || panel.ftp->name==ftp->name);
panel.ftp.has_value()==ftp.has_value() && (!panel.ftp || panel.ftp->id==ftp->id);
}
bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResult &scan)
@@ -2740,7 +2781,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul
const bool partial=error==ERROR_CANCELLED;
if(!failure.empty())
{
setStatus(failure);
if((!peer && !request.ftp) || &panel==&panels[active]) setStatus(failure);
return false;
}
if(partial && !opened)
@@ -2977,15 +3018,18 @@ void startDirectoryScan(Panel &panel)
void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::optional<FilesPeer> peer,
fs::path selection={},fs::path fallback={},std::optional<FtpProfile> ftp={},
std::optional<size_t> navigationPosition={},std::optional<ArchiveLocation> archive={})
std::optional<size_t> navigationPosition={},std::optional<ArchiveLocation> archive={},
unsigned reconnectAttempt=0,fs::path fallbackSelection={})
{
if(directory.empty() && !ftp) return;
panel.remoteRetry.reset();
if(!panel.view.revealedFile.empty() &&
(peer || ftp || panel.view.revealedFile.parent_path()!=directory)) panel.view.revealedFile.clear();
if(directory!=panel.directory || !samePanelSource(panel,peer,ftp))
cancelFolderSizes(panel);
panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback),
std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition,std::move(archive)};
std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition,
std::move(archive),reconnectAttempt,std::move(fallbackSelection)};
if(panel.scan.valid())
{
panel.scanSuperseded=true;
@@ -2995,6 +3039,8 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti
else startDirectoryScan(panel);
}
#include "files_panel_recovery.inl"
void collectDirectoryScans()
{
for(auto &panel:panels)
@@ -3011,21 +3057,37 @@ void collectDirectoryScans()
panel.scanRequest.reset();
panel.scanEntriesRead.reset();
bool applied=false;
auto retry=panel.remoteRetry;
const auto fallback=request.fallback;
const auto fallbackSelection=request.fallbackSelection;
const bool usesFtp=request.ftp && !request.ftp->id.empty();
try
{
auto result=panel.scan.get();
if(!result->failure.empty() && (request.peer || usesFtp) && !panel.scanStop.stop_requested())
{
retry=Panel::RemoteRetry{{request.directory,request.selection,usesFtp?request.ftp->id:std::string{},
request.peer},result->failure,0,request.reconnectAttempt};
if(request.peer && transientLanError(result->error) && retry->reconnectAttempt<lanRetryDelays.size())
retry->retryAt=GetTickCount64()+lanRetryDelays[retry->reconnectAttempt];
}
applied=applyDirectoryScan(panel,std::move(request),*result);
if(result->error==ERROR_CANCELLED) continue;
if(result->error==ERROR_CANCELLED && fallback.empty()) continue;
}
catch(const std::exception &) {setStatus(L"Could not read the folder.");}
if(!applied && !fallback.empty()) openOn(panel,fallback,false,{});
else if(applied && !panel.scan.valid() && !panel.peer && panel.watch.handle!=INVALID_HANDLE_VALUE &&
WaitForSingleObject(panel.watch.handle,0)==WAIT_OBJECT_0)
if(!applied && !fallback.empty())
{
const auto root=usesFtp?systemPanelRoot():fs::path{};
openOn(panel,fallback,false,{},fallbackSelection,fallback==root?fs::path{}:root);
}
else if(applied && !panel.scan.valid() && !panel.peer && !panel.ftp &&
panel.watch.handle!=INVALID_HANDLE_VALUE && WaitForSingleObject(panel.watch.handle,0)==WAIT_OBJECT_0)
{
if(!FindNextChangeNotification(panel.watch.handle)) panel.watch.reset();
openOn(panel,panel.directory,false,{});
}
panel.remoteRetry=std::move(retry);
if(panel.remoteRetry && !panel.scan.valid() && &panel==&panels[active]) showFileDetails(panel);
}
}
@@ -3201,7 +3263,9 @@ void refreshChangedPanels()
// Pass a copy because opening the folder rebuilds the panel.
const auto directory=panel.directory;
if(panel.view.automaticSizes) cancelFolderSizes(panel);
auto retry=std::move(panel.remoteRetry);
open(panel,directory);
panel.remoteRetry=std::move(retry);
}
}
@@ -3381,7 +3445,8 @@ void collectFolderSizes(Panel &panel)
if((finished || !completed.empty()) && &panel==&panels[active]) showFileDetails(panel);
}
void openSelectedText(const Panel &panel, bool edit, bool external);
void openSelectedText(const Panel &panel, bool edit, bool external,bool hex=false);
ks::files::TextDialogs textWindowDialogs();
void findLocalFiles(HWND owner,Panel &panel);
void compareSelectedFiles(HWND owner);
void createArchive(HWND owner,Panel &panel);
@@ -3537,6 +3602,8 @@ void selectDrive()
else if(menuIndex==2 && row==10) toggleQuickView(owner);
else if(menuIndex==2 && row==11) copyFullPanelPath(owner,panels[active]);
else if(menuIndex==2 && row==12) openSpaceAnalyzer(owner,panels[active]);
else if(menuIndex==2 && row==13) openSelectedText(panels[active],false,false,true);
else if(menuIndex==2 && row==14) ks::files::showAllViewerBookmarks(owner,textWindowDialogs());
else if(menuIndex==1 && row==4) createArchive(owner,panels[active]);
else
{
@@ -3709,44 +3776,51 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT
return DefSubclassProc(window,msg,wp,lp);
}
void queryDrivePeers()
FilesPeerLookup lookupFilesPeers(HWND owner)
{
drivePeers.clear();
drivePeerLookupError.clear();
drivePeerReplyReceived=false;
drivePeerService=FindWindowW(L"KSwitcher.Main",L"KSwitcher");
if(drivePeerService)
FilesPeerLookup lookup;
lookup.service=FindWindowW(L"KSwitcher.Main",L"KSwitcher");
if(lookup.service)
{
COPYDATASTRUCT request{FilesLanPeers,0,nullptr};
DWORD_PTR result{};
auto *previous=std::exchange(peerLookupRequest,&lookup);
SetLastError(ERROR_SUCCESS);
const auto delivered=SendMessageTimeoutW(drivePeerService,WM_COPYDATA,
reinterpret_cast<WPARAM>(GetParent(picker)),reinterpret_cast<LPARAM>(&request),
const auto delivered=SendMessageTimeoutW(lookup.service,WM_COPYDATA,
reinterpret_cast<WPARAM>(owner),reinterpret_cast<LPARAM>(&request),
SMTO_ABORTIFHUNG|SMTO_ERRORONEXIT,350,&result);
const auto error=GetLastError();
if(!delivered || result!=1 || !drivePeerReplyReceived)
peerLookupRequest=previous;
if(!delivered || result!=1 || !lookup.received)
{
drivePeers.clear();
lookup.peers.clear();
if(delivered && result!=1)
drivePeerLookupError=L"KSwitcher rejected the peer request";
lookup.error=L"KSwitcher rejected the peer request";
else if(delivered)
drivePeerLookupError=L"Invalid peer list from KSwitcher";
lookup.error=L"Invalid peer list from KSwitcher";
else if(error==ERROR_ACCESS_DENIED)
drivePeerLookupError=L"Access denied by Windows";
lookup.error=L"Access denied by Windows";
else if(error==ERROR_TIMEOUT)
drivePeerLookupError=L"KSwitcher did not respond in time";
lookup.error=L"KSwitcher did not respond in time";
else
drivePeerLookupError=L"Peer request failed (Windows code "+std::to_wstring(error)+L")";
lookup.error=L"Peer request failed (Windows code "+std::to_wstring(error)+L")";
ks::log(L"LAN Files peer lookup failed: delivered="+std::to_wstring(delivered!=0)+
L", reply="+std::to_wstring(result)+L", Windows error="+std::to_wstring(error));
}
}
else
{
drivePeerLookupError=L"KSwitcher is not running";
lookup.error=L"KSwitcher is not running";
ks::log(L"LAN Files peer lookup failed: local KSwitcher window not found");
}
drivePeerService=nullptr;
return lookup;
}
void queryDrivePeers()
{
auto lookup=lookupFilesPeers(GetParent(picker));
drivePeers=std::move(lookup.peers);
drivePeerLookupError=std::move(lookup.error);
}
void startDriveQuery(DriveQuery &query)
@@ -4161,7 +4235,7 @@ void openPanelImage(const Panel &panel,const fs::path &path,const ks::files::Rem
panel.peer?&*panel.peer:nullptr,source);
}
void openArchiveText(const Panel &panel,const fs::path &path)
void openArchiveText(const Panel &panel,const fs::path &path,bool hex=false)
{
const auto file=panel.archive->file;
const auto member=path.lexically_relative(file);
@@ -4180,11 +4254,12 @@ void openArchiveText(const Panel &panel,const fs::path &path)
const auto entry=ks::files::readArchiveMember(file,relative,cache,limit,progress);
return ks::files::RemoteTextRevision{entry.size,entry.modified,false};
},{}};
if(ks::files::isImagePath(path)) openPanelImage(panel,path,&archive);
else ks::files::openRemoteTextWindow(GetParent(panel.list),path,false,textWindowDialogs(),archive);
if(!hex && ks::files::isImagePath(path)) openPanelImage(panel,path,&archive);
else ks::files::openRemoteTextWindow(GetParent(panel.list),path,false,textWindowDialogs(),archive,{},
false,{.hex=hex});
}
void openSelectedText(const Panel &panel, bool edit, bool external)
void openSelectedText(const Panel &panel, bool edit, bool external,bool hex)
{
if(ftpProfileList(panel)) return;
const auto row=currentPanelRow(panel);
@@ -4192,7 +4267,7 @@ void openSelectedText(const Panel &panel, bool edit, bool external)
if(panel.archive)
{
if(edit || external) setStatus(L"Archive entries are read-only. Use F5 to extract them.");
else openArchiveText(panel,panel.rows[row]);
else openArchiveText(panel,panel.rows[row],hex);
return;
}
if((panel.peer || panel.ftp) && external)
@@ -4204,16 +4279,16 @@ void openSelectedText(const Panel &panel, bool edit, bool external)
if(panel.ftp)
{
const auto ftp=ftpTextSource(*panel.ftp);
if(!edit && ks::files::isImagePath(path)) openPanelImage(panel,path,&ftp);
else ks::files::openRemoteTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),ftp);
if(!edit && !hex && ks::files::isImagePath(path)) openPanelImage(panel,path,&ftp);
else ks::files::openRemoteTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),ftp,{},false,{.hex=hex});
return;
}
if(external)
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 && ks::files::isImagePath(path)) openPanelImage(panel,path);
else if(!edit && !hex && ks::files::isImagePath(path)) openPanelImage(panel,path);
else ks::files::openTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),
panel.peer?&*panel.peer:nullptr);
panel.peer?&*panel.peer:nullptr,{},false,{.hex=hex});
}
void enter(Panel &panel)
@@ -5856,7 +5931,7 @@ ks::files::RemoteTextSource ftpTextSource(const FtpProfile &profile)
ERROR_NOT_SUPPORTED);
const bool editable=!(info->attributes&FILE_ATTRIBUTE_READONLY);
if(edit && !editable) throw std::runtime_error("The FTP file is read-only.");
if(info->size>limit) throw std::runtime_error("The image is too large to preview.");
if(info->size>limit) throw std::system_error(ERROR_FILE_TOO_LARGE,std::system_category());
FilesConnection local;
downloadFtpFile(ftp,local,path,cache,*info,false,progress);
return ks::files::RemoteTextRevision{info->size,info->modified,editable};
@@ -7510,12 +7585,12 @@ void openMenu(HWND window, int index)
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4",
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"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3",L"Viewer bookmarks…"};
}
commandActions.clear();
if(index==2)
{
commandActions={0,3,11,-1,1,2,4,5,8};
commandActions={0,3,11,-1,1,13,14,2,4,5,8};
if(!panels[active].peer && !panels[active].ftp)
{
commandActions.insert(commandActions.begin()+1,9);
@@ -7761,7 +7836,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
case WM_COPYDATA:
{
const auto *reply=reinterpret_cast<const COPYDATASTRUCT*>(lp);
if(!drivePeerService || reinterpret_cast<HWND>(wp)!=drivePeerService || !reply ||
auto *lookup=peerLookupRequest;
if(!lookup || reinterpret_cast<HWND>(wp)!=lookup->service || !reply ||
reply->dwData!=FilesLanPeersReply || reply->cbData>FilesLanPeersLimit ||
(!reply->cbData || !reply->lpData)) return FALSE;
try
@@ -7770,11 +7846,11 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
const auto rows=Json::parse(begin,begin+reply->cbData);
if(!rows.is_array()) return FALSE;
for(const auto &row:rows)
drivePeers.push_back({row.at("id"),row.at("address"),ks::wide(row.at("name")),ks::lan::FilesPort,
lookup->peers.push_back({row.at("id"),row.at("address"),ks::wide(row.at("name")),ks::lan::FilesPort,
row.value("filesBrowse",false)});
}
catch(const std::exception &){drivePeers.clear();return FALSE;}
drivePeerReplyReceived=true;
catch(const std::exception &){lookup->peers.clear();return FALSE;}
lookup->received=true;
return TRUE;
}
case ks::files::quickViewToggleMessage:
@@ -7807,6 +7883,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
{
collectDirectoryScans();
collectTreeBranches();
pollRemotePanels();
refreshChangedPanels();
showDirectoryScanProgress(panels[active]);
}
@@ -7893,12 +7970,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
for (auto child : {panel.path, panel.list, panel.selectionSummary})
SendMessageW(child, WM_SETFONT, reinterpret_cast<WPARAM>(mono), FALSE);
SendMessageW(panel.list,LB_SETITEMHEIGHT,0,textHeight);
wchar_t system[MAX_PATH]{};
GetWindowsDirectoryW(system, MAX_PATH);
const auto saved=savedPanelPath(panelPathKeys[i]);
const auto root=fs::path(system).root_path();
openOn(panel,saved.is_absolute()?saved:root,false,{},savedPanelPath(panelCursorKeys[i]),
saved.is_absolute() && saved!=root?root:fs::path{});
restorePanelLocation(panel,i);
SetWindowSubclass(panel.list, panelKeys, 1, 0);
if(auto target=new(std::nothrow) PanelDropTarget(panel.list))
{
@@ -8446,6 +8518,17 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
resetCompletion();
}
if(copyInProgress || commandHistoryWindow || FilesModalDialog::activeFor(window)) return 0;
if(reinterpret_cast<HWND>(lp)==status && HIWORD(wp)==STN_CLICKED)
{
auto &panel=panels[active];
if(panel.remoteRetry && !panel.scan.valid())
{
const auto message=panel.remoteRetry->failure+L"\r\n\r\nRetry opening this folder?";
if(showFilesNotice(window,message.c_str(),L"Remote folder",{.confirm=true})==IDYES)
refreshPanel(panel);
}
return 0;
}
if(LOWORD(wp)==121 && HIWORD(wp)==LBN_DBLCLK) selectDrive();
if(LOWORD(wp)>=130 && LOWORD(wp)<=134 && HIWORD(wp)==BN_CLICKED)
{
@@ -8481,6 +8564,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
savePlacement(window);
for(int i=0;i<2;++i)
{
saveFtpPanelLocation(panels[i],i);
const auto path=(panels[i].archive?panels[i].archive->file.parent_path():panels[i].directory).native();
if(!panels[i].peer && !panels[i].ftp && !path.empty())
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,panelPathKeys[i],REG_SZ,path.c_str(),
@@ -8795,6 +8879,11 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
}
continue;
}
if(shift && !ctrl && message.wParam==VK_F3 && !terminalVisible && commandLineAvailable(window))
{
if(!(message.lParam&(1LL<<30))) openSelectedText(panels[active],false,false,true);
continue;
}
if(ctrl && !shift &&
(message.wParam=='F' || message.wParam=='C' || message.wParam=='R' ||
(message.wParam=='U' && !terminalVisible) ||
+148
View File
@@ -0,0 +1,148 @@
constexpr std::array<ULONGLONG,3> lanRetryDelays{1200,2500,5000};
constexpr const wchar_t *ftpPanelLocationKeys[]{L"LeftFtpLocation",L"RightFtpLocation"};
constexpr DWORD maxFtpLocationBytes=256*1024;
FilesPeerLookup lookupFilesPeers(HWND owner);
bool transientLanError(DWORD code)
{
switch(code)
{
case WSAENETDOWN:
case WSAENETUNREACH:
case WSAENETRESET:
case WSAECONNABORTED:
case WSAECONNRESET:
case WSAECONNREFUSED:
case WSAETIMEDOUT:
case WSAEHOSTDOWN:
case WSAEHOSTUNREACH:
case ERROR_CONNECTION_ABORTED:
case ERROR_NETNAME_DELETED:
case ERROR_NETWORK_UNREACHABLE:
case ERROR_SEM_TIMEOUT:
return true;
default:
return false;
}
}
bool retryRemotePanel(Panel &panel,bool automatic,const fs::path &fallback)
{
if(!panel.remoteRetry) return false;
auto &retry=*panel.remoteRetry;
auto location=retry.location;
const auto attempt=automatic?retry.reconnectAttempt+1:0;
if(location.peer)
{
const auto lookup=lookupFilesPeers(GetParent(panel.list));
const auto peer=std::find_if(lookup.peers.begin(),lookup.peers.end(),[&](const auto &entry) {
return entry.id==location.peer->id && !entry.address.empty();
});
if(peer!=lookup.peers.end()) location.peer=*peer;
openOn(panel,location.directory,false,std::move(location.peer),location.cursor,
{},{},{},{},attempt);
return true;
}
const bool loaded=loadFtpProfiles();
const auto profile=std::find_if(ftpProfiles.begin(),ftpProfiles.end(),[&](const auto &entry) {
return entry.id==location.ftpProfile;
});
if(!loaded || profile==ftpProfiles.end())
{
retry.failure=loaded?L"The saved FTP connection is missing. Select a profile in Change drive → FTP.":
L"Could not load the saved FTP connections.";
if(&panel==&panels[active] && !panel.scan.valid()) showFileDetails(panel);
return true;
}
openOn(panel,location.directory,false,{},location.cursor,fallback,*profile,{},{},0,
fallback.empty()?fs::path{}:savedPanelPath(panelCursorKeys[&panel-panels]));
return true;
}
void pollRemotePanels()
{
const auto now=GetTickCount64();
for(auto &panel:panels)
if(!panel.scan.valid() && panel.remoteRetry && panel.remoteRetry->retryAt &&
now>=panel.remoteRetry->retryAt)
retryRemotePanel(panel,true);
}
bool ftpPanelPath(const fs::path &path)
{
return path.has_root_directory() && !path.has_root_name();
}
std::optional<RemotePanelLocation> savedFtpPanelLocation(int index)
{
DWORD size{};
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpPanelLocationKeys[index],RRF_RT_REG_BINARY,nullptr,
nullptr,&size)!=ERROR_SUCCESS || !size || size>maxFtpLocationBytes) return {};
std::string data(size,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpPanelLocationKeys[index],RRF_RT_REG_BINARY,nullptr,
data.data(),&size)!=ERROR_SUCCESS) return {};
try
{
const auto saved=Json::parse(data.begin(),data.begin()+size);
RemotePanelLocation location{fs::path(ks::wide(saved.at("directory"))),fs::path(ks::wide(saved.at("cursor"))),
saved.at("profile").get<std::string>()};
if(!ftpPanelPath(location.directory) || location.ftpProfile.empty()) return {};
if(!location.cursor.empty() && !ftpPanelPath(location.cursor)) location.cursor.clear();
return location;
}
catch(const std::exception &) {return {};}
}
void saveFtpPanelLocation(const Panel &panel,int index)
{
RemotePanelLocation location;
if(panel.ftp && !panel.ftp->id.empty())
{
const auto row=currentPanelRow(panel);
location={panel.directory,row<0?fs::path{}:panel.rows[row],panel.ftp->id};
}
else if(panel.remoteRetry && !panel.remoteRetry->location.ftpProfile.empty())
location=panel.remoteRetry->location;
else if(panel.scanRequest && panel.scanRequest->ftp)
location={panel.scanRequest->directory,panel.scanRequest->selection,panel.scanRequest->ftp->id};
const auto key=ftpPanelLocationKeys[index];
if(location.ftpProfile.empty() || !ftpPanelPath(location.directory))
{
RegDeleteKeyValueW(HKEY_CURRENT_USER,schemeKey,key);
return;
}
try
{
const auto data=Json{{"profile",location.ftpProfile},{"directory",ks::utf8(location.directory.native())},
{"cursor",ks::utf8(location.cursor.native())}}.dump();
if(data.size()<=maxFtpLocationBytes)
RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,key,REG_BINARY,data.data(),static_cast<DWORD>(data.size()));
}
catch(const std::exception &) {}
}
fs::path systemPanelRoot()
{
wchar_t system[MAX_PATH]{};
GetWindowsDirectoryW(system,MAX_PATH);
return fs::path(system).root_path();
}
void restorePanelLocation(Panel &panel,int index)
{
const auto root=systemPanelRoot();
const auto saved=savedPanelPath(panelPathKeys[index]);
const auto local=saved.is_absolute()?saved:root;
auto remote=savedFtpPanelLocation(index);
if(remote)
{
panel.remoteRetry=Panel::RemoteRetry{std::move(*remote),L"Could not restore the saved FTP folder."};
retryRemotePanel(panel,false,local);
if(panel.scan.valid()) return;
}
auto retry=std::move(panel.remoteRetry);
openOn(panel,local,false,{},savedPanelPath(panelCursorKeys[index]),local!=root?root:fs::path{});
panel.remoteRetry=std::move(retry);
}
+108
View File
@@ -306,6 +306,114 @@ std::string TextDocument::readPage(uint64_t page) const
return readOriginal(page);
}
std::string TextDocument::readBytes(uint64_t offset,size_t count) const
{
if(path_.empty() || offset>=size_ || !count) return {};
const auto length=static_cast<size_t>(std::min<uint64_t>({count,hexPageBytes,size_-offset}));
File temporary{source_==INVALID_HANDLE_VALUE?openSource(path_,false):INVALID_HANDLE_VALUE};
return read(source_==INVALID_HANDLE_VALUE?temporary.handle:source_,offset,length);
}
namespace
{
struct TextLineCounter
{
uint64_t line=1;
bool afterCr{};
void consume(char value)
{
if(value=='\r' || (value=='\n' && !afterCr)) ++line;
afterCr=value=='\r';
}
};
void checkLineScan(std::stop_token stop)
{
if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category());
}
}
uint64_t TextDocument::lineAt(uint64_t page,size_t offset,std::stop_token stop) const
{
TextLineCounter counter;
page=std::min(page,pages()-1);
for(uint64_t index=0;index<=page;++index)
{
checkLineScan(stop);
const auto contents=readPage(index);
const auto prefix=index==page?std::string_view(contents).substr(0,offset):std::string_view(contents);
for(const char value:prefix) counter.consume(value);
}
return counter.line;
}
std::optional<TextLineLocation> TextDocument::locateLine(uint64_t line,std::stop_token stop) const
{
if(!line) return {};
TextLineCounter counter;
const auto count=pages();
size_t end=0;
for(uint64_t index=0;index<count;++index)
{
checkLineScan(stop);
const auto contents=readPage(index);
end=contents.size();
for(size_t offset=0;offset<end;++offset)
{
const auto value=contents[offset];
if(counter.line==line && !(counter.afterCr && value=='\n'))
return TextLineLocation{index,offset};
counter.consume(value);
}
}
return counter.line==line?std::optional(TextLineLocation{count-1,end}):std::nullopt;
}
std::string formatHexAddress(uint64_t offset)
{
constexpr char digits[]="0123456789ABCDEF";
std::string address(16,'0');
for(size_t i=address.size();i;offset>>=4) address[--i]=digits[offset&15];
return address;
}
std::string formatHexPage(std::string_view bytes,uint64_t offset)
{
constexpr char digits[]="0123456789ABCDEF";
constexpr size_t rowBytes=16;
std::string formatted;
formatted.reserve(((bytes.size()+rowBytes-1)/rowBytes)*88);
for(size_t row=0;row<bytes.size();row+=rowBytes)
{
const auto length=std::min(rowBytes,bytes.size()-row);
formatted+=formatHexAddress(offset+row);
formatted+=" ";
for(size_t column=0;column<rowBytes;++column)
{
if(column==8) formatted+=' ';
if(column<length)
{
const auto value=static_cast<unsigned char>(bytes[row+column]);
formatted+=digits[value>>4];
formatted+=digits[value&15];
}
else formatted+=" ";
formatted+=' ';
}
formatted+=" |";
for(size_t column=0;column<length;++column)
{
const auto value=static_cast<unsigned char>(bytes[row+column]);
formatted+=value>=0x20 && value<=0x7e?static_cast<char>(value):'.';
}
formatted.append(rowBytes-length,' ');
formatted+="|\r\n";
}
if(!formatted.empty()) formatted.resize(formatted.size()-2);
return formatted;
}
std::string TextDocument::readOriginal(uint64_t page) const
{
if(path_.empty()) return {};
+15
View File
@@ -4,6 +4,8 @@
#include <cstdint>
#include <filesystem>
#include <map>
#include <optional>
#include <stop_token>
#include <string>
#include <string_view>
@@ -12,6 +14,10 @@ namespace ks::files
enum class TextEncoding { automatic, utf8, utf16le, utf16be, windows1252 };
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);
struct TextSaveFormat
{
TextEncoding encoding=TextEncoding::utf8;
@@ -19,6 +25,12 @@ struct TextSaveFormat
TextLineEnding lineEnding=TextLineEnding::preserve;
};
struct TextLineLocation
{
uint64_t page{};
size_t offset{};
};
class TextDocument
{
public:
@@ -35,6 +47,9 @@ public:
uint64_t size() const { return size_; }
uint64_t boundary(uint64_t page) const;
std::string readPage(uint64_t page) const;
std::string readBytes(uint64_t offset,size_t count) const;
uint64_t lineAt(uint64_t page,size_t offset,std::stop_token stop={}) const;
std::optional<TextLineLocation> locateLine(uint64_t line,std::stop_token stop={}) const;
void releaseReadHandle();
void stage(uint64_t page, std::string_view utf8);
bool modified() const { return !changes_.empty(); }
+455 -110
View File
@@ -25,6 +25,7 @@
#include "../vendor/json.hpp"
#include <algorithm>
#include <array>
#include <cerrno>
#include <chrono>
#include <cstring>
#include <cwchar>
@@ -200,7 +201,7 @@ enum Command : UINT
{
save = 1, close, findText, findNext, previousPage, nextPage, firstPage, lastPage, goToPage,
undo, redo, cut, copy, paste, selectAll, lexerAuto, lexerPlain, options, switchMode,
historyBack, historyForward, findPrevious, previewEscape,
historyBack, historyForward, findPrevious, previewEscape, switchHex, addBookmark, currentBookmarks, allBookmarks,
lexerStart = 1000,
};
@@ -218,6 +219,8 @@ void initializePrompt(TextDialogs style, HWND dialog)
SendDlgItemMessageW(dialog, 100, EM_SETSEL, 0, -1);
}
#include "files_viewer_bookmarks.inl"
INT_PTR CALLBACK pageDialog(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam)
{
if (message == WM_INITDIALOG)
@@ -597,7 +600,7 @@ RemoteTextSource lanTextSource(const lan::FilesPeer &peer)
throw std::runtime_error("Update KSwitcher on the remote computer to edit this file.");
if(edit && readOnly) throw std::runtime_error("The remote file is read-only.");
const RemoteTextRevision revision{info.at("size"),info.at("modified"),canCommit && !readOnly};
if(revision.size>sizeLimit) throw std::runtime_error("The image is too large to preview.");
if(revision.size>sizeLimit) throw std::system_error(ERROR_FILE_TOO_LARGE,std::system_category());
try
{
lan::streamFile(source,target,peer.id,original,cache,revision.size,revision.modified,false,false,progress);
@@ -663,11 +666,30 @@ struct RemoteTextFile
}
};
std::future<std::unique_ptr<RemoteTextFile>> fetchRemoteText(const RemoteTextSource &source,
const std::filesystem::path &path,const std::shared_ptr<std::atomic<bool>> &canceled)
{
std::packaged_task<std::unique_ptr<RemoteTextFile>()> task([source,path,canceled] {
auto file=std::make_unique<RemoteTextFile>(source,path);
file->download(false,[canceled](uint64_t,uint64_t){return !*canceled;});
return file;
});
auto result=task.get_future();
std::thread(std::move(task)).detach();
return result;
}
class TextWindow;
std::map<HWND,std::shared_ptr<TextWindow>> textWindows;
std::vector<HWND> textWindowOrder;
HWND filesOwner{};
bool textOwnerClosed=false;
unsigned standaloneFilesWindows{};
void quitWhenFilesWindowsClose()
{
if(textOwnerClosed && textWindows.empty() && textWindowOrder.empty() && !standaloneFilesWindows)
PostQuitMessage(0);
}
constexpr ULONG_PTR openDocumentQuery=0x4B534644;
std::wstring documentIdentity(const std::filesystem::path &path,std::string_view peer)
@@ -743,11 +765,14 @@ public:
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const RemoteTextSource *backend,
std::string_view fragment,TextOpenOptions options,bool quickView=false)
: original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()),
edit(editable), draft(options.draft), embedded(quickView), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
edit(editable), draft(options.draft), embedded(quickView), hex(options.hex && !editable),
initialBookmark(options.line),
prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
search{dialogs}, previewFragment(fragment)
{
if (backend) remote=std::make_unique<RemoteTextFile>(*backend,original);
else if(!embedded) document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
else if(!embedded) document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,
hex?TextEncoding::utf8:options.encoding);
if(options.encoding!=TextEncoding::automatic)
{
newFormat.encoding=options.encoding;
@@ -767,6 +792,7 @@ public:
static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM wparam, LPARAM lparam);
~TextWindow()
{
if(savedViewerFile) document.reset();
if(smallIcon) DestroyIcon(smallIcon);
if(largeIcon) DestroyIcon(largeIcon);
}
@@ -774,6 +800,7 @@ public:
bool handleKey(const MSG &message);
void goToFragment(std::string_view fragment);
void previewFile(const std::filesystem::path &path);
bool openBookmark(const ViewerBookmark &bookmark);
std::filesystem::path original;
const std::string peerId;
@@ -783,6 +810,25 @@ private:
std::wstring filename;
bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{};
bool draft{}, embedded{};
bool hex{};
uint64_t initialBookmark{};
bool showBookmarkSource{};
struct ViewerPosition
{
uint64_t page{};
LRESULT anchor{}, caret{}, firstLine{}, horizontal{};
};
std::optional<ViewerPosition> beforeHex;
struct SuspendedEditor
{
std::unique_ptr<TextDocument> document;
ViewerPosition position;
bool uploadPending{};
};
std::optional<SuspendedEditor> suspendedEditor;
std::unique_ptr<RemoteTextFile> savedViewerFile;
std::future<std::unique_ptr<RemoteTextFile>> savedViewerLoad;
std::shared_ptr<std::atomic<bool>> cancelSavedViewer;
TextSaveFormat newFormat;
std::filesystem::path pendingSavePath;
HICON smallIcon{},largeIcon{};
@@ -805,7 +851,6 @@ private:
int pageEol = SC_EOL_CRLF;
size_t undoBytes{};
bool uploadPending{};
bool switchAfterSave{};
FilesTerminalView preview;
bool previewWanted{}, previewVisible{}, previewRetried{};
ULONGLONG previewDeadline{};
@@ -865,6 +910,18 @@ private:
static constexpr UINT_PTR previewTimer = 3;
static constexpr UINT_PTR navigationTimer = 4;
static constexpr UINT_PTR quickViewTimer = 5;
static constexpr UINT_PTR bookmarkTimer = 6;
static constexpr UINT_PTR savedViewerTimer = 7;
struct BookmarkLocation
{
std::filesystem::path path;
uint64_t line{};
bool adding{};
std::optional<TextLineLocation> position;
std::unique_ptr<TextDocument> source;
};
std::future<BookmarkLocation> bookmarkTask;
std::stop_source bookmarkStop;
struct QuickDocument
{
std::unique_ptr<TextDocument> document;
@@ -923,6 +980,10 @@ private:
void applyLineEnding();
void installLexer();
void loadPage(uint64_t index,std::optional<std::string> cached={});
void toggleHex();
void locateBookmark(uint64_t line);
void finishBookmark();
void pickBookmark(bool currentFile);
void stagePage();
void go(uint64_t index);
void saveFile(bool closeWhenDone);
@@ -930,6 +991,13 @@ private:
void requestClose();
void toggleMode();
void changeMode();
ViewerPosition currentPosition() const;
void restorePosition(const ViewerPosition &position);
void showTextMode(const ViewerPosition &position,std::string contents);
void suspendEditor(std::unique_ptr<RemoteTextFile> saved={});
void restoreEditor();
void finishSavedViewer();
void cancelSavedViewerLoad();
bool needsSave() const;
bool canPreview() const;
void updatePreview();
@@ -978,7 +1046,8 @@ void TextWindow::createMenu()
const auto menu = CreateMenu();
const auto file = addGroup(menu, L"&File");
if (edit) addItem(file, save, L"&Save\tF2");
addItem(file, switchMode, edit ? L"&View\tF6" : L"&Edit\tF6");
if(!hex) addItem(file, switchMode, edit ? L"&View\tF6" : L"&Edit\tF6");
if(!edit) addItem(file,switchHex,hex?L"&Text view\tF4":L"View as &hex\tF4");
addItem(file, close, L"&Close\tF10");
const auto actions = addGroup(menu, edit ? L"&Edit" : L"&Selection");
if (edit)
@@ -992,52 +1061,65 @@ void TextWindow::createMenu()
addItem(actions, copy, L"&Copy\tCtrl+C");
addItem(actions, selectAll, L"Select &page\tCtrl+A");
const auto navigation = addGroup(menu, L"&Navigate");
if (!edit)
if (!edit && !hex)
{
addItem(navigation, historyBack, L"&Back\tAlt+Left");
addItem(navigation, historyForward, L"F&orward\tAlt+Right");
AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr);
}
addItem(navigation, findText, L"&Find on page…\tCtrl+F");
addItem(navigation, findNext, L"Find &next\tF3");
AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr);
if(!hex)
{
addItem(navigation, findText, L"&Find on page…\tCtrl+F");
addItem(navigation, findNext, L"Find &next\tF3");
AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr);
}
if(!edit && !hex)
{
addItem(navigation,addBookmark,L"Add &bookmark…\tCtrl+D");
addItem(navigation,currentBookmarks,L"Bookmarks in &this file…");
addItem(navigation,allBookmarks,L"&All bookmarks…");
AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr);
}
addItem(navigation, previousPage, L"&Previous page\tCtrl+PgUp");
addItem(navigation, nextPage, L"N&ext page\tCtrl+PgDn");
addItem(navigation, firstPage, L"F&irst page\tCtrl+Shift+Home");
addItem(navigation, lastPage, L"&Last page\tCtrl+Shift+End");
addItem(navigation, goToPage, L"&Go to page…\tF5");
const auto syntax = addGroup(menu, L"S&yntax");
addItem(syntax, lexerAuto, L"&Automatic");
addItem(syntax, lexerPlain, L"&Plain text");
constexpr std::wstring_view groups[] = {L"A–&F", L"G–&L", L"M–&R", L"S–&Z"};
const wchar_t lastLetters[] = {L'f', L'l', L'r', L'z'};
HMENU group{};
size_t groupIndex{};
std::wstring assignedKeys;
for (size_t i = 0; i < lexers.size(); ++i)
const auto syntax = hex?nullptr:addGroup(menu, L"S&yntax");
if(syntax)
{
auto name = wide(lexers[i]);
const auto letter = std::towlower(name.front());
while (groupIndex + 1 < std::size(groups) && letter > lastLetters[groupIndex])
addItem(syntax, lexerAuto, L"&Automatic");
addItem(syntax, lexerPlain, L"&Plain text");
constexpr std::wstring_view groups[] = {L"A–&F", L"G–&L", L"M–&R", L"S–&Z"};
const wchar_t lastLetters[] = {L'f', L'l', L'r', L'z'};
HMENU group{};
size_t groupIndex{};
std::wstring assignedKeys;
for (size_t i = 0; i < lexers.size(); ++i)
{
++groupIndex;
group = nullptr;
assignedKeys.clear();
}
if (!group) group = addGroup(syntax, groups[groupIndex].data());
for (size_t position = 0; position < name.size(); ++position)
{
const auto key = static_cast<wchar_t>(std::towlower(name[position]));
if (((key >= L'a' && key <= L'z') || (key >= L'0' && key <= L'9')) &&
assignedKeys.find(key) == assignedKeys.npos)
auto name = wide(lexers[i]);
const auto letter = std::towlower(name.front());
while (groupIndex + 1 < std::size(groups) && letter > lastLetters[groupIndex])
{
assignedKeys += key;
name.insert(position, 1, L'&');
break;
++groupIndex;
group = nullptr;
assignedKeys.clear();
}
if (!group) group = addGroup(syntax, groups[groupIndex].data());
for (size_t position = 0; position < name.size(); ++position)
{
const auto key = static_cast<wchar_t>(std::towlower(name[position]));
if (((key >= L'a' && key <= L'z') || (key >= L'0' && key <= L'9')) &&
assignedKeys.find(key) == assignedKeys.npos)
{
assignedKeys += key;
name.insert(position, 1, L'&');
break;
}
}
addItem(group, static_cast<UINT>(lexerStart + i), name.c_str());
}
addItem(group, static_cast<UINT>(lexerStart + i), name.c_str());
}
addItem(menu, options, L"&Options…");
menuRoot = menu;
@@ -1191,7 +1273,7 @@ void TextWindow::updateMenus()
void TextWindow::installLexer()
{
lexer = createTextLexer(language);
lexer = hex?nullptr:createTextLexer(language);
send(SCI_SETILEXER, 0, reinterpret_cast<LPARAM>(lexer));
applyPreferences();
send(SCI_COLOURISE, 0, -1);
@@ -1279,9 +1361,9 @@ void TextWindow::applyPreferences()
send(SCI_SETUSETABS, !prefs.tabsAsSpaces);
send(SCI_SETTABINDENTS, TRUE);
send(SCI_SETBACKSPACEUNINDENTS, TRUE);
send(SCI_SETWRAPMODE, prefs.wrap ? SC_WRAP_WORD : SC_WRAP_NONE);
send(SCI_SETVIEWWS, prefs.whitespace ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE);
send(SCI_SETVIEWEOL, prefs.whitespace);
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);
applyLineEnding();
updateLineNumberMargin();
layout();
@@ -1291,7 +1373,7 @@ void TextWindow::applyPreferences()
void TextWindow::updateLineNumberMargin()
{
LRESULT width{};
if (prefs.numbers)
if (prefs.numbers && !hex)
{
const auto digits = std::to_string(send(SCI_GETLINECOUNT)).size();
const std::string sample(digits, '9');
@@ -1312,12 +1394,13 @@ void TextWindow::applyLineEnding()
void TextWindow::loadPage(uint64_t index,std::optional<std::string> cached)
{
auto data=cached?std::move(*cached):document->readPage(index);
const auto offset = document->boundary(index);
const auto offset=hex?index*hexPageBytes:document->boundary(index);
auto data=cached?std::move(*cached):hex?formatHexPage(document->readBytes(offset,hexPageBytes),offset):
document->readPage(index);
page = index;
pageOffset = offset;
pageTotal = document->pages();
fileSize = document->size();
pageTotal = hex?1+(fileSize?fileSize-1:0)/hexPageBytes:document->pages();
stagedDirty = document->modified();
const auto eol = data.find_first_of("\r\n");
pageEol = eol == data.npos ? SC_EOL_CRLF : data[eol] == '\n' ? SC_EOL_LF :
@@ -1343,6 +1426,137 @@ void TextWindow::loadPage(uint64_t index,std::optional<std::string> cached)
invalidate();
}
void TextWindow::toggleHex()
{
if(edit || embedded || !document) return;
if(hex)
{
const auto restored=beforeHex.value_or(ViewerPosition{});
const auto index=std::min(restored.page,document->pages()-1);
auto normal=beforeHex?nullptr:std::make_unique<TextDocument>(remote?remote->cache:original,false);
auto text=(normal?normal.get():document.get())->readPage(index);
if(normal)
{
document=std::move(normal);
language=automatic=detectLanguage(original,text);
if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment});
}
hex=false;
beforeHex.reset();
installLexer();
loadPage(index,std::move(text));
restorePosition(restored);
updatePreview();
}
else
{
const auto index=pageOffset/hexPageBytes;
const auto offset=index*hexPageBytes;
auto bytes=formatHexPage(document->readBytes(offset,hexPageBytes),offset);
beforeHex=currentPosition();
hex=true;
stopPreview(false,true);
installLexer();
loadPage(index,std::move(bytes));
focusContent();
}
releaseMenu();
createMenu();
updateTitle();
invalidate();
}
bool TextWindow::openBookmark(const ViewerBookmark &bookmark)
{
if(edit || hex || embedded || remote || !document || compareBookmarkPaths(original,bookmark.path)!=0) return false;
if(IsIconic(window)) ShowWindow(window,SW_RESTORE);
SetForegroundWindow(window);
locateBookmark(bookmark.line);
return true;
}
void TextWindow::locateBookmark(uint64_t line)
{
if(!document || edit || hex || embedded || remote)
{
search.style.message(window,L"Line bookmarks are available for local files in the text Viewer.");
return;
}
if(bookmarkTask.valid()) bookmarkStop.request_stop();
bookmarkStop=std::stop_source{};
const auto token=bookmarkStop.get_token();
const auto currentPage=page;
const auto caret=static_cast<size_t>(std::max<LRESULT>(0,send(SCI_GETCURRENTPOS)));
const auto encoding=document->encoding();
std::packaged_task<BookmarkLocation()> task([path=original,currentPage,caret,encoding,line,token] {
auto source=std::make_unique<TextDocument>(path,false,encoding);
if(!line) return BookmarkLocation{path,source->lineAt(currentPage,caret,token),true,{},{}};
const auto position=source->locateLine(line,token);
return BookmarkLocation{path,line,false,position,std::move(source)};
});
if(!SetTimer(window,bookmarkTimer,40,nullptr)) throw std::runtime_error("Cannot start locating the bookmarked line.");
bookmarkTask=task.get_future();
try {std::thread(std::move(task)).detach();}
catch(...)
{
bookmarkTask={};
KillTimer(window,bookmarkTimer);
throw;
}
invalidateStatus();
}
void TextWindow::finishBookmark()
{
if(!bookmarkTask.valid() || bookmarkTask.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
KillTimer(window,bookmarkTimer);
auto result=bookmarkTask.get();
invalidateStatus();
if(edit || hex || !document || compareBookmarkPaths(result.path,original)!=0) return;
if(result.adding)
{
BookmarkPrompt prompt{search.style,{result.path,result.line,{}}};
const auto bookmarks=readViewerBookmarks(viewerBookmarksFile());
const auto same=std::find_if(bookmarks.begin(),bookmarks.end(),[&](const auto &entry){
return sameViewerBookmark(entry,prompt.bookmark);
});
if(same!=bookmarks.end()) prompt.bookmark.name=same->name;
if(search.style.run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(613),window,bookmarkNameDialog,
reinterpret_cast<LPARAM>(&prompt))==IDOK) focusContent();
return;
}
if(!result.position)
{
search.style.message(window,L"The bookmarked line is no longer in the file.");
return;
}
showBookmarkSource=true;
if(previewWanted || previewVisible) stopPreview(true,true);
document=std::move(result.source);
loadPage(result.position->page);
send(SCI_GOTOPOS,result.position->offset);
send(SCI_SCROLLCARET);
focusContent();
}
void openChosenBookmark(HWND owner,TextDialogs style,const ViewerBookmark &bookmark)
{
for(const auto &entry:textWindows)
if(entry.second->openBookmark(bookmark)) return;
openTextWindow(owner,bookmark.path,false,style,nullptr,{},true,{.line=bookmark.line});
}
void TextWindow::pickBookmark(bool currentFile)
{
if(currentFile && remote)
{
search.style.message(window,L"Line bookmarks are available for local files in the text Viewer.");
return;
}
const auto selected=selectViewerBookmark(window,search.style,currentFile?original:std::filesystem::path{});
if(selected) openChosenBookmark(window,search.style,*selected);
}
void TextWindow::stagePage()
{
if (!currentChanged()) return;
@@ -1362,6 +1576,15 @@ void TextWindow::go(uint64_t index)
void TextWindow::initializeDocument(std::optional<std::string> firstPage)
{
if(hex)
{
releaseMenu();
createMenu();
installLexer();
loadPage(0);
updateTitle();
return;
}
if(!firstPage) firstPage=document->readPage(0);
automatic=detectLanguage(original,*firstPage);
language=automatic;
@@ -1375,6 +1598,7 @@ void TextWindow::initializeDocument(std::optional<std::string> firstPage)
installLexer();
loadPage(0,std::move(firstPage));
updatePreview();
if(initialBookmark) locateBookmark(std::exchange(initialBookmark,0));
}
std::string readMarkdownDocument(TextDocument &document)
@@ -1461,7 +1685,7 @@ void TextWindow::finishOpen()
{
opening.get();
if(cancelOpen) { DestroyWindow(window); return; }
document=std::make_unique<TextDocument>(remote->cache,edit);
document=std::make_unique<TextDocument>(remote->cache,edit,hex?TextEncoding::utf8:TextEncoding::automatic);
initializeDocument();
invalidate();
}
@@ -1474,14 +1698,13 @@ void TextWindow::finishOpen()
void TextWindow::saveFile(bool closeWhenDone)
{
if (busy() || !edit) return;
if (busy() || savedViewerLoad.valid() || !edit) return;
auto destination=original;
if(draft && !search.style.saveOptions(window,destination,newFormat)) return;
stagePage();
if (!draft && !stagedDirty && !uploadPending)
{
if (closeWhenDone) DestroyWindow(window);
else if (std::exchange(switchAfterSave, false)) changeMode();
return;
}
pendingCaret = send(SCI_GETCURRENTPOS);
@@ -1522,7 +1745,6 @@ void TextWindow::finishSave()
return;
}
send(SCI_SETREADONLY, !edit);
const auto change = std::exchange(switchAfterSave, false);
const auto reopened = saving.get();
stagedDirty = false;
const bool created=std::exchange(draft,false);
@@ -1540,7 +1762,6 @@ void TextWindow::finishSave()
return;
}
if (closeAfterSave) { DestroyWindow(window); return; }
if (change) { changeMode(); return; }
if(created)
{
initializeDocument();
@@ -1561,11 +1782,17 @@ void TextWindow::requestClose()
{
if (opening.valid()) { cancelOpen=true; return; }
if (busy()) return;
cancelSavedViewerLoad();
if (needsSave())
{
const auto answer = search.style.confirmSave(window,draft);
if (answer == IDCANCEL) return;
if (answer == IDYES) { saveFile(true); return; }
if (answer == IDYES)
{
if(suspendedEditor) restoreEditor();
saveFile(true);
return;
}
if (answer != IDNO) return;
}
DestroyWindow(window);
@@ -1573,54 +1800,61 @@ void TextWindow::requestClose()
bool TextWindow::needsSave() const
{
if(suspendedEditor) return suspendedEditor->uploadPending || suspendedEditor->document->modified();
return uploadPending || (currentChanged() ? document->modifiedWith(page, pageText()) : stagedDirty);
}
void TextWindow::toggleMode()
{
if (busy() || navigation.valid()) return;
if(draft) return;
if (edit && needsSave())
if (busy() || navigation.valid() || savedViewerLoad.valid()) return;
if(suspendedEditor)
{
const auto answer = search.style.confirmSave(window,false);
if (answer == IDYES)
restoreEditor();
return;
}
if(edit && (draft || needsSave()))
{
if(!uploadPending) suspendEditor();
else
{
switchAfterSave = true;
try { saveFile(false); }
catch (...) { switchAfterSave = false; throw; }
return;
}
if (answer != IDNO) return;
// The local LAN cache may already contain changes from a failed upload.
if (uploadPending)
{
auto refreshed = std::make_unique<RemoteTextFile>(remote->source,original);
refreshed->download(false,{});
auto replacement = std::make_unique<TextDocument>(refreshed->cache,false);
document.reset();
remote = std::move(refreshed);
document = std::move(replacement);
uploadPending = false;
auto cancel=std::make_shared<std::atomic<bool>>(false);
if(!SetTimer(window,savedViewerTimer,75,nullptr))
throw std::runtime_error("Cannot start loading the saved version.");
try
{
savedViewerLoad=fetchRemoteText(remote->source,original,cancel);
cancelSavedViewer=std::move(cancel);
}
catch(...) {KillTimer(window,savedViewerTimer); throw;}
invalidate();
}
return;
}
changeMode();
}
void TextWindow::changeMode()
TextWindow::ViewerPosition TextWindow::currentPosition() const
{
return {page,send(SCI_GETANCHOR),send(SCI_GETCURRENTPOS),send(SCI_GETFIRSTVISIBLELINE),send(SCI_GETXOFFSET)};
}
void TextWindow::restorePosition(const ViewerPosition &position)
{
const auto length=send(SCI_GETLENGTH);
send(SCI_SETSEL,std::clamp<LRESULT>(position.anchor,0,length),std::clamp<LRESULT>(position.caret,0,length));
send(SCI_SETFIRSTVISIBLELINE,position.firstLine);
send(SCI_SETXOFFSET,position.horizontal);
}
void TextWindow::showTextMode(const ViewerPosition &position,std::string contents)
{
if (!edit && remote && !remote->revision.editable)
throw std::runtime_error("The remote file does not support editing.");
auto replacement = std::make_unique<TextDocument>(remote ? remote->cache : original, !edit);
const auto caret = send(SCI_GETCURRENTPOS);
document = std::move(replacement);
edit = !edit;
if(canPreview()) ShowWindow(editor,SW_HIDE);
prefs = loadTextPreferences().profiles[edit];
releaseMenu();
createMenu();
installLexer();
loadPage(std::min(page, document->pages() - 1));
send(SCI_GOTOPOS, std::min(caret, send(SCI_GETLENGTH)));
loadPage(position.page,std::move(contents));
restorePosition(position);
updateTitle();
updateIcons(GetDpiForWindow(window));
updateTaskbarGroup();
@@ -1629,9 +1863,71 @@ void TextWindow::changeMode()
focusContent();
}
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());
position.page=std::min(position.page,replacement->pages()-1);
auto contents=replacement->readPage(position.page);
document=std::move(replacement);
edit=!edit;
showTextMode(position,std::move(contents));
}
void TextWindow::suspendEditor(std::unique_ptr<RemoteTextFile> saved)
{
const auto position=currentPosition();
const auto path=draft?std::filesystem::path{}:saved?saved->cache:remote?remote->cache:original;
auto replacement=std::make_unique<TextDocument>(path,false,document->encoding());
auto viewing=position;
viewing.page=std::min(viewing.page,replacement->pages()-1);
auto contents=replacement->readPage(viewing.page);
stagePage();
suspendedEditor=SuspendedEditor{std::move(document),position,std::exchange(uploadPending,false)};
document=std::move(replacement);
savedViewerFile=std::move(saved);
edit=false;
showTextMode(viewing,std::move(contents));
}
void TextWindow::restoreEditor()
{
const auto position=suspendedEditor->position;
auto contents=suspendedEditor->document->readPage(position.page);
document=std::move(suspendedEditor->document);
uploadPending=suspendedEditor->uploadPending;
suspendedEditor.reset();
savedViewerFile.reset();
edit=true;
hex=false;
beforeHex.reset();
showTextMode(position,std::move(contents));
}
void TextWindow::finishSavedViewer()
{
if(!savedViewerLoad.valid() || savedViewerLoad.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
KillTimer(window,savedViewerTimer);
cancelSavedViewer.reset();
invalidate();
suspendEditor(savedViewerLoad.get());
}
void TextWindow::cancelSavedViewerLoad()
{
if(!savedViewerLoad.valid()) return;
*cancelSavedViewer=true;
cancelSavedViewer.reset();
savedViewerLoad={};
KillTimer(window,savedViewerTimer);
invalidate();
}
void TextWindow::updateTitle()
{
const auto title = std::wstring(edit ? L"Editor — " : L"Viewer — ") +
const auto title = std::wstring(edit ? L"Editor — " : hex ? L"Hex Viewer — " : L"Viewer — ") +
(remote ? remote->source.name + L" · " : std::wstring{}) + original.wstring();
SetWindowTextW(window,title.c_str());
}
@@ -1669,7 +1965,8 @@ void TextWindow::updateTaskbarGroup(bool closing)
bool TextWindow::canPreview() const
{
return !edit && automatic.lexer=="markdown" && document && document->size()<=TextDocument::editLimit;
return !edit && !hex && !showBookmarkSource && automatic.lexer=="markdown" && document &&
document->size()<=TextDocument::editLimit;
}
void TextWindow::updatePreview()
@@ -1710,6 +2007,11 @@ bool TextWindow::startPreviewBrowser()
PostMessageW(window,WM_COMMAND,key=='F'?findText:shift?findPrevious:findNext,0);
return true;
}
if(ctrl && !alt && key=='D')
{
PostMessageW(window,WM_COMMAND,addBookmark,0);
return true;
}
if(ctrl && !alt && key==VK_TAB)
{
PostMessageW(window,cycleWindow,(GetKeyState(VK_SHIFT)&0x8000)!=0,0);
@@ -1720,8 +2022,8 @@ bool TextWindow::startPreviewBrowser()
PostMessageW(window,WM_COMMAND,key==VK_LEFT || key==VK_BROWSER_BACK?historyBack:historyForward,0);
return true;
}
if(key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false;
PostMessageW(window,WM_COMMAND,key==VK_F6?switchMode:key==VK_ESCAPE?previewEscape:close,0);
if(key!=VK_F4 && key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false;
PostMessageW(window,WM_COMMAND,key==VK_F4?switchHex:key==VK_F6?switchMode:key==VK_ESCAPE?previewEscape:close,0);
return true;
});
}
@@ -1789,7 +2091,7 @@ void TextWindow::renderPreview(bool keepPosition)
previewText=quickMarkdown?*quickMarkdown:readMarkdownDocument(*document);
if(!remote) document->releaseReadHandle();
nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision},
{"canSave",!embedded && (!remote || remote->revision.editable)},{"compact",embedded},
{"canSave",!embedded && !suspendedEditor && (!remote || remote->revision.editable)},{"compact",embedded},
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
{"keepPosition",keepPosition}};
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
@@ -1839,7 +2141,7 @@ void TextWindow::startMarkdownTask()
{
const auto task=std::exchange(pendingTask,{});
if(!task) return;
if(!previewVisible || edit || busy() || navigation.valid() || task->revision!=previewRevision ||
if(!previewVisible || edit || suspendedEditor || busy() || navigation.valid() || task->revision!=previewRevision ||
(remote && !remote->revision.editable))
{
reportMarkdownTask(task->revision,false);
@@ -2029,13 +2331,18 @@ void TextWindow::previewMessage(const std::wstring &value)
void TextWindow::syncNavigation()
{
preview.post(wide(nlohmann::json{{"action","history"},{"back",navigationIndex>0},
{"forward",navigationIndex+1<navigationHistory.size()}}.dump()));
preview.post(wide(nlohmann::json{{"action","history"},{"back",!suspendedEditor && navigationIndex>0},
{"forward",!suspendedEditor && navigationIndex+1<navigationHistory.size()}}.dump()));
}
void TextWindow::navigatePreview(PreviewLink request)
{
if(edit || busy() || pendingTask || navigation.valid() || navigationHistory.empty()) return;
if(suspendedEditor)
{
if(request.direction) return;
if(request.target.path!=original) request.newWindow=true;
}
if(request.newWindow)
{
if(remote)
@@ -2056,19 +2363,11 @@ void TextWindow::navigatePreview(PreviewLink request)
else destination=std::move(request.target);
if(destination.path==original || !remote) { showLocation(nullptr); return; }
auto cancel=std::make_shared<std::atomic<bool>>(false);
std::packaged_task<std::unique_ptr<RemoteTextFile>()> task(
[backend=remote->source,path=destination.path,cancel] {
auto file=std::make_unique<RemoteTextFile>(backend,path);
file->download(false,[cancel](uint64_t,uint64_t){return !*cancel;});
return file;
});
if(!SetTimer(window,navigationTimer,75,nullptr))
throw std::runtime_error("Cannot start the remote navigation timer.");
try
{
auto result=task.get_future();
std::thread(std::move(task)).detach();
navigation=std::move(result);
navigation=fetchRemoteText(remote->source,destination.path,cancel);
cancelNavigation=std::move(cancel);
}
catch(...) { KillTimer(window,navigationTimer); throw; }
@@ -2284,20 +2583,25 @@ void TextWindow::paint()
const auto position=send(SCI_GETCURRENTPOS);
const auto line=send(SCI_LINEFROMPOSITION,position)+1;
const auto column=send(SCI_GETCOLUMN,position)+1;
auto status=filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+
const auto retained=suspendedEditor?L" │ Draft retained":L"";
auto status=hex?filename+L" (Hex)"+retained+L" │ 0x"+wide(formatHexAddress(pageOffset+(line-1)*16)):
filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+retained+
L" │ "+(document?document->encodingName():L"Loading…")+L" │ "+textLanguageLabel(language)+
L" │ Ln "+std::to_wstring(line)+L":"+std::to_wstring(column);
if(pageTotal>1)
status+=L" │ Page "+std::to_wstring(page+1)+L"/"+std::to_wstring(pageTotal)+
L" @ "+std::to_wstring(pageOffset);
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);
}
const auto hints = busy() ? L"Saving…" : insertRejected ? L"Page edit limit: 8 MiB" :
const auto hints = busy() ? L"Saving…" : savedViewerLoad.valid()?L"Loading saved version…" :
hex?L"F4 Text F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close":
insertRejected ? L"Page edit limit: 8 MiB" :
edit ? L"F2 Save F3 Find next F5 Go to page F6 View Ctrl+PgUp/PgDn Pages F10 Close" :
previewVisible ? L"F6 Edit Ctrl+W Close" :
previewVisible ? L"F4 Hex F6 Edit Ctrl+W Close" :
previewWanted ? L"Rendering Markdown… Ctrl+W Close" :
L"F3 Find next F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close";
L"F3 Find next F4 Hex F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close";
constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX;
DrawTextW(dc, hints, -1, &bottom, format);
SelectObject(dc, previous);
@@ -2348,11 +2652,17 @@ void TextWindow::command(UINT id)
{
if(!document && id!=close) return;
if (busy()) return;
if(hex && (id==switchMode || id==historyBack || id==historyForward || id==findText || id==findNext ||
id==findPrevious || id==lexerAuto || id==lexerPlain || id>=lexerStart)) return;
switch (id)
{
case save: saveFile(false); return;
case close: requestClose(); return;
case switchMode: toggleMode(); return;
case switchHex: toggleHex(); return;
case addBookmark: if(!edit && !hex) locateBookmark(0); return;
case currentBookmarks: if(!edit && !hex) pickBookmark(true); return;
case allBookmarks: if(!edit && !hex) pickBookmark(false); return;
case historyBack:
case historyForward:
if(previewVisible)
@@ -2487,13 +2797,16 @@ bool TextWindow::handleKey(const MSG &message)
UINT id{};
if (key == VK_F2 || (ctrl && key == 'S')) id = save;
if (key == VK_F3) id = findNext;
if (key == VK_F4 && !ctrl && !shift && !edit) id = switchHex;
if (key == VK_F5 || (ctrl && key == 'G')) id = goToPage;
if (key == VK_F6) id = switchMode;
if (key == VK_F9) id = 600;
if (key == VK_ESCAPE || key == VK_F10 || (!edit && ctrl && key=='W')) id = close;
if (key == VK_ESCAPE) id = hex && beforeHex?switchHex:close;
if (key == VK_F10 || (!edit && ctrl && key=='W')) id = close;
if (!edit && key==VK_BROWSER_BACK) id=historyBack;
if (!edit && key==VK_BROWSER_FORWARD) id=historyForward;
if (ctrl && key == 'F') id = findText;
if (ctrl && key == 'D' && !edit && !hex) id = addBookmark;
if (ctrl && key == VK_PRIOR) id = previousPage;
if (ctrl && key == VK_NEXT) id = nextPage;
if (ctrl && shift && key == VK_HOME) id = firstPage;
@@ -2598,6 +2911,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
case WM_KEYDOWN:
if(!self->embedded && self->previewWanted && !self->previewVisible)
{
if(wparam==VK_F4) self->command(switchHex);
if(wparam==VK_F6) self->toggleMode();
if(wparam==VK_ESCAPE || wparam==VK_F10 ||
(wparam=='W' && (GetKeyState(VK_CONTROL)&0x8000))) self->requestClose();
@@ -2658,6 +2972,8 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
if (wparam == previewTimer) self->pollImages();
if (wparam == navigationTimer) self->finishNavigation();
if (wparam == quickViewTimer) self->pollQuickView();
if (wparam == bookmarkTimer) self->finishBookmark();
if (wparam == savedViewerTimer) self->finishSavedViewer();
return 0;
case trimUndo:
if (self->undoBytes >= 32 * TextDocument::pageBytes)
@@ -2669,6 +2985,8 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
}
return 0;
case WM_DESTROY:
self->cancelSavedViewerLoad();
self->bookmarkStop.request_stop();
if(self->cancelNavigation) *self->cancelNavigation=true;
if(!self->embedded) self->updateTaskbarGroup(true);
self->stopPreview(false);
@@ -2678,7 +2996,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
self->window=nullptr;
textWindows.erase(window);
std::erase(textWindowOrder,window);
if(textOwnerClosed && textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0);
quitWhenFilesWindowsClose();
break;
}
}
@@ -2796,7 +3114,18 @@ void textWindowOwnerClosed()
{
filesOwner=nullptr;
textOwnerClosed=true;
if(textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0);
quitWhenFilesWindowsClose();
}
void standaloneFilesWindowOpened()
{
++standaloneFilesWindows;
}
void standaloneFilesWindowClosed()
{
if(standaloneFilesWindows) --standaloneFilesWindows;
quitWhenFilesWindowsClose();
}
bool cycleTextWindows(HWND current,bool reverse)
@@ -2909,7 +3238,7 @@ void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const
const auto window=createImageView(owner,false,imageViewStyle(dialogs),std::move(images),path,std::move(load),
[](HWND closed) {
std::erase(textWindowOrder,closed);
if(textOwnerClosed && textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0);
quitWhenFilesWindowsClose();
});
if(!window) throw std::runtime_error("Could not open the image viewer.");
textWindowOrder.push_back(window);
@@ -2926,7 +3255,7 @@ void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const
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)
{
if(!edit && !options.draft && isImagePath(path))
if(!edit && !options.draft && !options.hex && !options.line && isImagePath(path))
{
openImageWindow(owner,{path},path,dialogs,nullptr,backend);
return;
@@ -2937,7 +3266,8 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool
std::error_code error;
const auto identity=backend?path.lexically_normal():std::filesystem::weakly_canonical(path,error);
const auto &original=error?path:identity;
if(const auto existing=newWindow?nullptr:findOpenDocument(original,backend?backend->id:""))
if(const auto existing=newWindow || options.hex || options.line?nullptr:
findOpenDocument(original,backend?backend->id:""))
{
if(dialogs.confirmExisting(owner) && IsWindow(existing))
{
@@ -2952,7 +3282,7 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool
const auto instance=GetModuleHandleW(nullptr);
if(!registerTextWindowClass(instance)) throw std::runtime_error("Cannot register the text window.");
auto state=std::make_shared<TextWindow>(original,edit,dialogs,backend,fragment,options);
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
const auto title=std::wstring(edit?L"Editor — ":options.hex?L"Hex Viewer — ":L"Viewer — ")+
(backend?backend->name+L" · ":std::wstring{})+path.wstring();
RECT bounds{};
GetWindowRect(owner,&bounds);
@@ -2974,8 +3304,23 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
}
void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const RemoteTextSource &source,std::string_view fragment,bool newWindow)
const RemoteTextSource &source,std::string_view fragment,bool newWindow,TextOpenOptions options)
{
openTextWindowImpl(owner,path,edit,dialogs,&source,fragment,newWindow,{});
openTextWindowImpl(owner,path,edit,dialogs,&source,fragment,newWindow,options);
}
RemoteTextSource createLanTextSource(const lan::FilesPeer &peer)
{
return lanTextSource(peer);
}
void showAllViewerBookmarks(HWND owner,TextDialogs dialogs)
{
try
{
const auto selected=selectViewerBookmark(owner,dialogs);
if(selected) openChosenBookmark(owner,dialogs,*selected);
}
catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());}
}
}
+7 -1
View File
@@ -61,6 +61,8 @@ struct TextOpenOptions
{
TextEncoding encoding=TextEncoding::automatic;
bool draft{};
bool hex{};
uint64_t line{};
};
struct RemoteTextRevision
@@ -79,6 +81,7 @@ struct RemoteTextSource
std::function<RemoteTextRevision(const std::filesystem::path &,const std::filesystem::path &,
const RemoteTextRevision &)> upload;
};
RemoteTextSource createLanTextSource(const lan::FilesPeer &peer);
inline constexpr UINT quickViewToggleMessage=WM_APP+31;
HWND createQuickView(HWND owner,TextDialogs dialogs);
@@ -87,12 +90,15 @@ HWND createImageQuickView(HWND owner,TextDialogs dialogs);
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=nullptr,const RemoteTextSource *source=nullptr);
void showAllViewerBookmarks(HWND owner,TextDialogs dialogs);
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false,
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);
const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false,TextOpenOptions options={});
void textWindowOwnerClosed();
void standaloneFilesWindowOpened();
void standaloneFilesWindowClosed();
bool cycleTextWindows(HWND current,bool reverse);
}
+251
View File
@@ -0,0 +1,251 @@
struct ViewerBookmark
{
std::filesystem::path path;
uint64_t line{};
std::wstring name;
};
int compareBookmarkPaths(const std::filesystem::path &left,const std::filesystem::path &right)
{
return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE)-CSTR_EQUAL;
}
bool sameViewerBookmark(const ViewerBookmark &left,const ViewerBookmark &right)
{
return left.line==right.line && compareBookmarkPaths(left.path,right.path)==0;
}
std::vector<ViewerBookmark> readViewerBookmarks(const std::filesystem::path &file)
{
if(!std::filesystem::exists(file)) return {};
const auto saved=nlohmann::json::parse(readFile(file,2*1024*1024));
if(!saved.is_array()) throw std::runtime_error("Could not read the Viewer bookmarks.");
std::vector<ViewerBookmark> bookmarks;
for(const auto &item:saved)
{
if(!item.is_object() || !item.contains("path") || !item["path"].is_string() ||
!item.contains("line") || !item["line"].is_number_unsigned()) continue;
std::filesystem::path path=wide(item["path"].get<std::string>());
const auto line=item["line"].get<uint64_t>();
if(!path.is_absolute() || !line || path.native().find(L'\0')!=std::wstring::npos) continue;
std::wstring name;
if(item.contains("name") && item["name"].is_string()) name=wide(item["name"].get<std::string>());
if(name.find(L'\0')!=std::wstring::npos) name.clear();
bookmarks.push_back({std::move(path),line,std::move(name)});
}
std::sort(bookmarks.begin(),bookmarks.end(),[](const auto &left,const auto &right) {
const auto pathOrder=compareBookmarkPaths(left.path,right.path);
return pathOrder?pathOrder<0:left.line<right.line;
});
bookmarks.erase(std::unique(bookmarks.begin(),bookmarks.end(),sameViewerBookmark),bookmarks.end());
return bookmarks;
}
std::filesystem::path viewerBookmarksFile()
{
return dataDirectory()/L"files-viewer-bookmarks.json";
}
enum class BookmarkChange { upsert, rename, remove };
void changeViewerBookmark(const ViewerBookmark &bookmark,BookmarkChange change)
{
struct Lock
{
HANDLE handle=CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.ViewerBookmarks");
bool owned{};
~Lock()
{
if(owned) ReleaseMutex(handle);
if(handle) CloseHandle(handle);
}
} lock;
if(!lock.handle) throw std::runtime_error("Could not open Viewer bookmark storage.");
const auto wait=WaitForSingleObject(lock.handle,100);
lock.owned=wait==WAIT_OBJECT_0 || wait==WAIT_ABANDONED;
if(!lock.owned) throw std::runtime_error("Viewer bookmark storage is busy.");
const auto file=viewerBookmarksFile();
auto bookmarks=readViewerBookmarks(file);
const auto existing=std::find_if(bookmarks.begin(),bookmarks.end(),[&](const auto &item) {
return sameViewerBookmark(item,bookmark);
});
if(existing==bookmarks.end())
{
if(change!=BookmarkChange::upsert) throw std::runtime_error("This bookmark has already been removed.");
bookmarks.push_back(bookmark);
}
else if(change==BookmarkChange::remove) bookmarks.erase(existing);
else existing->name=bookmark.name;
auto saved=nlohmann::json::array();
for(const auto &entry:bookmarks)
saved.push_back({{"path",utf8(entry.path.native())},{"line",entry.line},{"name",utf8(entry.name)}});
const auto contents=saved.dump();
if(contents.size()>2*1024*1024) throw std::runtime_error("Viewer bookmark storage is full.");
atomicWrite(file,Bytes(contents.begin(),contents.end()));
}
struct BookmarkPrompt
{
TextDialogs style;
ViewerBookmark bookmark;
bool rename{};
};
constexpr int bookmarkName=535, bookmarkLine=536, bookmarkList=538, bookmarkRename=539, bookmarkRemove=540;
INT_PTR CALLBACK bookmarkNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
auto &prompt=*reinterpret_cast<BookmarkPrompt *>(lp);
prompt.style.prepare(dialog);
SetDlgItemTextW(dialog,bookmarkName,prompt.bookmark.name.c_str());
SetDlgItemTextW(dialog,bookmarkLine,std::to_wstring(prompt.bookmark.line).c_str());
SendDlgItemMessageW(dialog,bookmarkName,EM_SETLIMITTEXT,160,0);
SendDlgItemMessageW(dialog,bookmarkLine,EM_SETLIMITTEXT,20,0);
SendDlgItemMessageW(dialog,bookmarkLine,EM_SETREADONLY,prompt.rename,0);
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(GetDlgItem(dialog,bookmarkName));
SendDlgItemMessageW(dialog,bookmarkName,EM_SETSEL,0,-1);
return FALSE;
}
const auto prompt=reinterpret_cast<BookmarkPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!prompt) return FALSE;
if(const auto painted=prompt->style.paint(dialog,message,wp,lp,prompt->rename?L" Rename bookmark ":L" Add bookmark "))
return painted;
if(message!=WM_COMMAND) return FALSE;
if(LOWORD(wp)==IDCANCEL) {prompt->style.finish(dialog,IDCANCEL);return TRUE;}
if(LOWORD(wp)!=IDOK) return FALSE;
wchar_t line[24]{};
GetDlgItemTextW(dialog,bookmarkLine,line,static_cast<int>(std::size(line)));
wchar_t *end=nullptr;
errno=0;
const auto number=std::wcstoull(line,&end,10);
if(!number || errno==ERANGE || *end || line[0]<L'0' || line[0]>L'9')
{
prompt->style.message(dialog,L"Enter a positive line number.");
SetFocus(GetDlgItem(dialog,bookmarkLine));
return TRUE;
}
wchar_t name[161]{};
GetDlgItemTextW(dialog,bookmarkName,name,static_cast<int>(std::size(name)));
prompt->bookmark.line=number;
prompt->bookmark.name=name;
try {changeViewerBookmark(prompt->bookmark,prompt->rename?BookmarkChange::rename:BookmarkChange::upsert);}
catch(const std::exception &error)
{
prompt->style.message(dialog,wide(error.what()).c_str());
return TRUE;
}
prompt->style.finish(dialog,IDOK);
return TRUE;
}
struct ViewerBookmarkList
{
TextDialogs style;
std::filesystem::path filter;
std::vector<ViewerBookmark> bookmarks;
std::optional<ViewerBookmark> opening;
};
void showBookmarkPath(HWND dialog,const ViewerBookmarkList &state)
{
const auto row=SendDlgItemMessageW(dialog,bookmarkList,LB_GETCURSEL,0,0);
SetDlgItemTextW(dialog,541,row>=0 && static_cast<size_t>(row)<state.bookmarks.size()?
state.bookmarks[row].path.c_str():L"No bookmarks");
}
void renderBookmarkList(HWND dialog,ViewerBookmarkList &state,LRESULT oldSelection)
{
state.bookmarks=readViewerBookmarks(viewerBookmarksFile());
if(!state.filter.empty()) std::erase_if(state.bookmarks,[&](const auto &item) {
return compareBookmarkPaths(state.filter,item.path)!=0;
});
const auto list=GetDlgItem(dialog,bookmarkList);
SendMessageW(list,LB_RESETCONTENT,0,0);
const auto dc=GetDC(list);
HGDIOBJ oldFont{};
if(dc)
if(const auto font=SendMessageW(list,WM_GETFONT,0,0))
oldFont=SelectObject(dc,reinterpret_cast<HFONT>(font));
LONG width=0;
for(const auto &item:state.bookmarks)
{
auto label=L"Line "+std::to_wstring(item.line);
if(state.filter.empty()) label+=L" "+item.path.filename().native();
if(!item.name.empty()) label+=L" "+item.name;
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
SIZE dimensions{};
if(dc && GetTextExtentPoint32W(dc,label.c_str(),static_cast<int>(label.size()),&dimensions))
width=std::max(width,dimensions.cx);
}
if(oldFont) SelectObject(dc,oldFont);
if(dc) ReleaseDC(list,dc);
SendMessageW(list,LB_SETHORIZONTALEXTENT,width,0);
const bool rows=!state.bookmarks.empty();
if(rows) SendMessageW(list,LB_SETCURSEL,std::clamp<LRESULT>(oldSelection,0,state.bookmarks.size()-1),0);
showBookmarkPath(dialog,state);
for(const auto button:{IDOK,bookmarkRename,bookmarkRemove}) EnableWindow(GetDlgItem(dialog,button),rows);
}
INT_PTR CALLBACK viewerBookmarkDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
auto &state=*reinterpret_cast<ViewerBookmarkList *>(lp);
state.style.prepare(dialog);
try {renderBookmarkList(dialog,state,0);}
catch(const std::exception &error) {state.style.message(dialog,wide(error.what()).c_str());}
SetFocus(GetDlgItem(dialog,state.bookmarks.empty()?IDCANCEL:bookmarkList));
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
return FALSE;
}
auto *state=reinterpret_cast<ViewerBookmarkList *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!state) return FALSE;
if(const auto painted=state->style.paint(dialog,message,wp,lp,
state->filter.empty()?L" All Viewer bookmarks ":L" Bookmarks in this file ")) return painted;
if(message!=WM_COMMAND) return FALSE;
const auto id=LOWORD(wp);
if(id==IDCANCEL) {state->style.finish(dialog,IDCANCEL);return TRUE;}
if(id==bookmarkList && HIWORD(wp)==LBN_SELCHANGE) {showBookmarkPath(dialog,*state); return TRUE;}
const bool open=id==IDOK || (id==bookmarkList && HIWORD(wp)==LBN_DBLCLK);
if(!open && id!=bookmarkRename && id!=bookmarkRemove) return FALSE;
const auto selected=SendDlgItemMessageW(dialog,bookmarkList,LB_GETCURSEL,0,0);
if(selected<0 || static_cast<size_t>(selected)>=state->bookmarks.size()) return TRUE;
const auto entry=state->bookmarks[selected];
try
{
if(open)
{
const auto attr=GetFileAttributesW(entry.path.c_str());
if(attr==INVALID_FILE_ATTRIBUTES || attr&FILE_ATTRIBUTE_DIRECTORY)
throw std::runtime_error("The bookmarked file is unavailable.");
state->opening=entry;
state->style.finish(dialog,IDOK);
}
else if(id==bookmarkRename)
{
BookmarkPrompt prompt{state->style,entry,true};
if(state->style.run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(613),dialog,bookmarkNameDialog,
reinterpret_cast<LPARAM>(&prompt))==IDOK) renderBookmarkList(dialog,*state,selected);
}
else
{
changeViewerBookmark(entry,BookmarkChange::remove);
renderBookmarkList(dialog,*state,selected);
}
}
catch(const std::exception &error) {state->style.message(dialog,wide(error.what()).c_str());}
return TRUE;
}
std::optional<ViewerBookmark> selectViewerBookmark(HWND owner,TextDialogs style,std::filesystem::path filter={})
{
ViewerBookmarkList state{style,std::move(filter)};
if(style.run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(614),owner,viewerBookmarkDialog,
reinterpret_cast<LPARAM>(&state))==IDOK) return std::move(state.opening);
return {};
}
+1
View File
@@ -24,6 +24,7 @@ public static class FilesCommandsUi {
[DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr window, ref Point point);
[DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags);
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr window, IntPtr target, uint flags);
[DllImport("user32.dll", EntryPoint="PostMessageW")] public static extern bool Post(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l);
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
+53 -13
View File
@@ -5,7 +5,8 @@ Add-Type -AssemblyName System.Drawing
. "$PSScriptRoot/files_commands_ui.ps1"
$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$names = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance'
$names = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance',
'LeftFtpLocation', 'RightFtpLocation'
$saved = @{}
foreach ($name in $names) {
if ($name -in $preferences.GetValueNames()) {
@@ -16,6 +17,24 @@ $temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\')
$root = Join-Path $temp ('ks-files-splitter-' + [Guid]::NewGuid().ToString('N'))
$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
$process = $null
function Render-ComparisonList([IntPtr]$List, [FilesCommandsUi+Rect]$Bounds) {
$bitmap = [Drawing.Bitmap]::new($Bounds.Right, $Bounds.Bottom)
try {
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try {
$dc = $graphics.GetHdc()
try {
if (![FilesCommandsUi]::PrintWindow($List, $dc, 3)) { throw 'Could not render the comparison list.' }
} finally { $graphics.ReleaseHdc($dc) }
} finally { $graphics.Dispose() }
} catch {
$bitmap.Dispose()
throw
}
$bitmap
}
try {
$left = Join-Path $root 'left'
$right = Join-Path $root 'right'
@@ -25,7 +44,8 @@ try {
[IO.File]::WriteAllText((Join-Path $right 'sample.txt'), "one`nthree")
$preferences.SetValue('LeftPath', $left)
$preferences.SetValue('RightPath', $right)
foreach ($name in 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance') {
foreach ($name in 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance',
'LeftFtpLocation', 'RightFtpLocation') {
$preferences.DeleteValue($name, $false)
}
@@ -42,19 +62,20 @@ try {
[void][FilesCommandsUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero)
}
Invoke-FilesCommand $main 'Compare files*'
$list = Wait-For 'the foreground comparison list' {
$comparison = Wait-For 'the rendered comparison window' {
$dialog = [IntPtr]::Zero
while (($dialog = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) {
[uint32]$ownerPid = 0
[void][FilesCommandsUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid)
if ($ownerPid -ne $process.Id) { continue }
$control = [FilesCommandsUi]::GetDlgItem($dialog, 402)
if ([FilesCommandsUi]::IsWindowVisible($control) -and [FilesCommandsUi]::Activate($dialog)) {
return $control
if ([FilesCommandsUi]::IsWindowVisible($control)) {
return $dialog
}
}
}
$list = [FilesCommandsUi]::GetDlgItem($comparison, 402)
$bounds = [FilesCommandsUi+Rect]::new()
[void][FilesCommandsUi]::GetClientRect($list, [ref]$bounds)
$middle = [int]($bounds.Right / 2)
@@ -67,15 +88,10 @@ try {
}
[void][FilesCommandsUi]::Send($list, 514, [IntPtr]::Zero, [IntPtr]($mouseY -bor $destination))
[void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
$origin = [FilesCommandsUi+Point]::new()
[void][FilesCommandsUi]::ClientToScreen($list, [ref]$origin)
$bitmap = [Drawing.Bitmap]::new($bounds.Right, 1)
$bitmap = Render-ComparisonList $list $bounds
try {
$graphics = [Drawing.Graphics]::FromImage($bitmap)
try { $graphics.CopyFromScreen($origin.X, ($origin.Y + $bounds.Bottom - 10), 0, 0, $bitmap.Size) }
finally { $graphics.Dispose() }
$ink = @(for ($x = $middle - 4; $x -le $destination + 4; ++$x) {
if ($bitmap.GetPixel($x, 0).ToArgb() -ne [Drawing.Color]::White.ToArgb()) { $x }
if ($bitmap.GetPixel($x, $bounds.Bottom - 10).ToArgb() -ne [Drawing.Color]::White.ToArgb()) { $x }
})
# Desktop scaling can spread the single-pixel divider across two adjacent screen pixels.
if (!$ink.Count -or $ink.Count -gt 2 -or [Math]::Abs($ink[0] - $destination) -gt 1 -or
@@ -83,7 +99,31 @@ try {
throw "Expected one divider under the last row at $destination. Found $($ink.Count) marked pixels, starting at $($ink | Select-Object -First 8)."
}
} finally { $bitmap.Dispose() }
'Verified that dragging leaves exactly one divider below the file contents.'
$toolbar = [FilesCommandsUi]::GetDlgItem($comparison, 408)
if ([FilesCommandsUi]::Send($toolbar, 0x402, [IntPtr]415, [IntPtr]1) -eq [IntPtr]::Zero) {
throw 'The Unified toolbar button is missing.'
}
[void][FilesCommandsUi]::Send($comparison, 0x111, [IntPtr]415, $toolbar)
[void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101)
$height = [FilesCommandsUi]::Send($list, 0x1A1, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32()
# This part of the first unchanged row contains the right line number in the default font.
$numbers = Render-ComparisonList $list $bounds
try {
$left = [int]($height * 3.6)
$right = [int]($height * 5.05)
$hasNumber = $false
for ($y = [int]($height / 4); $y -lt [int]($height * 3 / 4) -and !$hasNumber; ++$y) {
for ($x = $left; $x -lt $right; ++$x) {
$pixel = $numbers.GetPixel($x, $y)
if ($pixel.R -lt 90 -and $pixel.G -lt 90 -and $pixel.B -lt 90) {
$hasNumber = $true
break
}
}
}
if (!$hasNumber) { throw 'The right line number did not render in the Unified view.' }
} finally { $numbers.Dispose() }
'Verified the dragged divider and the right line number in the Unified view.'
} finally {
if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() }
foreach ($name in $names) {
+67
View File
@@ -1,4 +1,5 @@
#include "files_text_document.h"
#include "files_compare_text.h"
#include <objbase.h>
#include <winioctl.h>
@@ -140,8 +141,71 @@ void sparseFile(const fs::path &file)
const auto index = document.pages() - 1;
check(document.size() == offset + 4 && document.boundary(index) == offset, "Use 64-bit offsets");
check(document.readPage(index) == "last", "Read past 4 GiB");
const auto raw=document.readBytes(offset-2,8);
check(raw==std::string("\0\0last",6),"Read original bytes across a sparse section beyond 4 GiB");
check(ks::files::formatHexPage(raw,offset-2).starts_with("000000013FFFFFFE 00 00 6C 61 73 74"),
"Format a 64-bit hex offset and embedded NULs");
document.stage(index, "edited");
check(document.readPage(index) == "edited", "Stage an edit past 4 GiB");
check(document.readBytes(offset,4)=="last","Hex reads original bytes instead of staged edits");
}
void hexBytes(const fs::path &file)
{
const std::string bytes("\xef\xbb\xbf\0A\xff\x7f\r\n",9);
writeFile(file,bytes);
TextDocument document(file,false);
check(document.boundary(0)==3 && document.readBytes(0,64)==bytes,"Hex includes the original BOM");
check(document.readBytes(9,40).empty(),"Reading at EOF returns an empty block");
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 twoRows(17,'a');
check(ks::files::formatHexPage(twoRows,0).find("\r\n0000000000000010 61")!=std::string::npos,
"Hex offsets advance by the row width");
}
void bookmarkedLines(const fs::path &file)
{
const auto longLine=std::string(TextDocument::pageBytes+32,'x');
writeFile(file,"first\r\n"+longLine+"\r\nending\rtail\n");
TextDocument document(file,false);
check(document.pages()==2 && document.lineAt(1,0)==3,"Absolute line numbering at a paged boundary");
const auto second=document.locateLine(2);
check(second && second->page==0 && second->offset==7,"Locate an original CRLF line");
const auto third=document.locateLine(3);
check(third && document.readPage(third->page).substr(third->offset).starts_with("ending"),
"Find a line after a long line and a page boundary");
const auto fourth=document.locateLine(4);
check(fourth && document.readPage(fourth->page).substr(fourth->offset).starts_with("tail"),
"Locate a line after CR");
const auto empty=document.locateLine(5);
check(empty && document.readPage(empty->page).size()==empty->offset && !document.locateLine(6),
"Locate the trailing empty line and reject out-of-range bookmarks");
std::stop_source canceled;
canceled.request_stop();
bool rejected=false;
try {document.locateLine(3,canceled.get_token());}
catch(const std::system_error &error) {rejected=error.code().value()==ERROR_CANCELLED;}
check(rejected,"Cancel a bookmark scan");
}
void comparisonEdits()
{
using namespace ks::files;
auto mixed=splitComparisonText(L"alpha\r\nbeta\nlast\r");
check(mixed.joined()==L"alpha\r\nbeta\nlast\r","Round-trip mixed line endings");
const auto replace=replaceComparisonText(mixed,{1,1,{L"new",L"extra"},{ComparisonEnding::lf,ComparisonEnding::crlf}});
check(mixed.joined()==L"alpha\r\nnew\nextra\r\nlast\r","Replace a block and retain the other line endings");
replaceComparisonText(mixed,replace);
check(mixed.joined()==L"alpha\r\nbeta\nlast\r","Undo a block replacement");
const auto shorten=replaceComparisonText(mixed,{3,1,{},{}});
check(mixed.joined()==L"alpha\r\nbeta\nlast","Remove the terminating empty line");
replaceComparisonText(mixed,shorten);
check(mixed.joined()==L"alpha\r\nbeta\nlast\r","Undo preserves the original trailing separator");
auto single=splitComparisonText(L"first");
replaceComparisonText(single,{1,0,{L"second"},{ComparisonEnding::absent}});
check(single.joined()==L"first\r\nsecond","Use the target convention when inserting past EOF");
}
void saveDraft(const fs::path &file)
@@ -191,6 +255,9 @@ int main()
unicodeBoundaries(fixture.directory / L"unicode.txt");
rejectExternalReplacement(fixture.directory / L"external.txt");
saveDraft(fixture.directory / L"created.txt");
hexBytes(fixture.directory / L"raw.bin");
bookmarkedLines(fixture.directory / L"bookmarks.txt");
comparisonEdits();
sparseFile(fixture.directory / L"5gib.log");
std::cout << "Files text document regressions passed.\n";
}