Compare commits

..
Author SHA1 Message Date
agrynco a0aeb62270 Release KSwitcher v0.6.115 (#61)
Add Shift+F4, prevent editor flicker, and record file launches as short start commands.
2026-11-17 17:30:07 +02:00
agrynco 4be9b24c4b Record the v0.6.115 package manifest and checksum 2026-11-17 17:29:31 +02:00
agrynco 9c30dd91b4 Prepare KSwitcher v0.6.115 with new files and concise open history 2026-11-17 17:27:08 +02:00
agrynco 5ba51ebb00 Release KSwitcher v0.6.114 (#60)
Move the active pane highlight directly to the clicked row.
2026-11-17 16:35:49 +02:00
agrynco 2bc6eb60c9 Record the v0.6.114 package manifest and checksum 2026-11-17 16:35:40 +02:00
agrynco 9c1badcb45 Prepare KSwitcher v0.6.114 with direct panel cursor highlighting 2026-11-17 16:30:18 +02:00
agrynco 9dcc20673a Release KSwitcher v0.6.113 (#59)
Prevent the terminal startup flash and stabilize the clipboard regression test.
2026-11-17 16:14:27 +02:00
agrynco ec4079b346 Record the v0.6.113 package manifest and checksum 2026-11-17 16:13:36 +02:00
agrynco 41cef4d4f3 Prepare KSwitcher v0.6.113 with a dark terminal from startup 2026-11-17 16:11:41 +02:00
20 changed files with 962 additions and 186 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.24)
project(KSwitcher VERSION 0.6.112 LANGUAGES CXX RC)
project(KSwitcher VERSION 0.6.115 LANGUAGES CXX RC)
if(NOT WIN32)
message(FATAL_ERROR "KSwitcher uses native Windows APIs")
endif()
+12
View File
@@ -37,6 +37,8 @@ Warning і початковий фокус на No.
окремим процесом. BAT і CMD виконуються в поточній сесії вбудованого
термінала, а їхній вивід з’являється під панелями. Щоб відкрити файл із
панелі LAN, спочатку скопіюй його до локальної папки.
Після успішного відкриття локального файла через Windows дія
`start 'шлях до файла'` з’являється у виводі термінала й історії команд.
- Коли командний рядок порожній, Shift+Enter відкриває поточний локальний
елемент через Windows.
Папка відкривається у Провіднику, файл виконує свою стандартну дію Windows.
@@ -50,6 +52,9 @@ Warning і початковий фокус на No.
Стрілки вліво й вправо переходять до першого й останнього рядків, коли
командний рядок порожній.
Клік оновлює підсвічування рядків курсора без перемальовування всієї панелі.
При кліку в іншу панель курсор відразу з’являється на вибраному рядку.
Попередній рядок цієї панелі оновлюється лише тоді, коли для неактивного
курсора він мав інше оформлення.
Меню й діалоги тимчасово приймають фокус. Ctrl+V і Shift+Insert вставляють
текст із буфера обміну в позицію курсора або замінюють виділення.
Enter виконує введену команду, якщо підказку не вибрано. Shift+Enter
@@ -58,6 +63,8 @@ Warning і початковий фокус на No.
Enter передає порожній рядок у термінал.
Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до
командного рядка й виконують відповідну дію за тими самими правилами.
Під час запуску термінала область виводу має темне тло, поки WebView2
готує сторінку.
Промпт і текст команди вирівняні по спільній базовій лінії.
- Під час набору локальної команди над полем з’являються підказки PowerShell.
Автодоповнення працює з відкритими й прихованими панелями (Ctrl+O).
@@ -217,6 +224,11 @@ Warning і початковий фокус на No.
- Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами
у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному
порядку. Коли відкрито лише Files, активна панель не змінюється.
- Shift+F4 у локальній панелі відкриває Editor для наявного або нового файла.
Порожнє ім’я підставляє `New_File_<дата>_<час>.txt`. Новий файл з’являється
на диску після збереження. Esc після змін пропонує Save, Discard або Cancel.
Save для нового файла відкриває параметри імені, кодування, BOM та кінців
рядків. Скасування параметрів залишає текст у редакторі.
- F3 відкриває Markdown як форматований документ із таблицями, блоками коду,
інтерактивними чекбоксами списків і діаграмами Mermaid. Відмітки в перегляді
діють до повторного рендерингу або виходу з цього режиму. F4 відкриває текст
+30
View File
@@ -1,5 +1,35 @@
# Latest Windows release
## v0.6.115 — 2026-11-17
- **Shift+F4** opens or creates a file in the active local panel. Leave the name blank for a generated `New_File_…txt` name. After editing a draft, **Esc → Save** opens options for the file name, encoding, BOM, and line endings.
- Typing updates the editor status line without repainting the menu or flashing the editor window.
- When **Enter** opens a local file through Windows, Files displays `start 'path'` in the terminal and saves it in command history.
**Українською.**
- **Shift+F4** відкриває або створює файл в активній локальній панелі. Якщо залишити ім’я порожнім, Files підставить `New_File_…txt`. Після редагування чернетки **Esc → Save** відкриває параметри імені, кодування, BOM і кінців рядків.
- Під час набору редактор оновлює рядок стану без перемальовування меню й миготіння вікна.
- Коли **Enter** відкриває локальний файл через Windows, Files показує `start 'шлях'` у терміналі й додає команду до історії.
## v0.6.114 — 2026-11-17
In KSwitcher Files, clicking a row in the inactive pane highlights that row immediately. The previous cursor row in that pane no longer flashes with the active highlight. If it had a custom unfocused cursor color, it returns directly to its normal style.
**Українською.**
У KSwitcher Files клік по рядку неактивної панелі одразу підсвічує вибраний рядок. Попередній рядок курсора цієї панелі більше не блимає активним підсвічуванням. Якщо він мав окремий колір неактивного курсора, рядок одразу повертається до звичайного оформлення.
## v0.6.113 — 2026-11-17
- KSwitcher Files keeps the terminal output area dark while WebView2 initializes. This fixes the white flash during startup.
- The terminal copy regression test checks for a new clipboard write and verifies its contents without first taking clipboard ownership.
**Українською.**
- Під час запуску термінала область виводу KSwitcher Files залишається темною, поки WebView2 готує сторінку. Це усуває білий спалах під час відкриття термінала.
- Тест копіювання з термінала перевіряє новий запис і його вміст без попереднього захоплення буфера обміну.
## v0.6.112 — 2026-11-17
In KSwitcher Files, **Ctrl+Shift+Tab** cycles backward through Files, Editor, and Viewer windows. **Ctrl+Tab** cycles forward. Both shortcuts wrap at the ends of the window list, including in the Markdown preview.
+1 -1
View File
@@ -1 +1 @@
8ac71477b90b4a8893c43e000d77d53df57db63c07f0d4784820c5563b106218 KSwitcher-win-x64.zip
debcdf6dbb7d7dc959e094d4e39d6c7655efff453f90d13b69b0d7f1c406072c KSwitcher-win-x64.zip
+7 -7
View File
@@ -1,26 +1,26 @@
{
"version": "0.6.112",
"schema": 1,
"version": "0.6.115",
"files": [
{
"sha256": "53c3f9aeca02136acbd2ec3c187ee858cb5f60a2f1bf5641ee264e062f73653f",
"sha256": "e50dfca08dfc1e4149c43303cf303d1860410b263901dd39ba621d5d175142cd",
"path": "KSwitcher.exe",
"size": 2479104
},
{
"sha256": "c4dbd247e48fd1d37744d280c2fd948c3355eb3507324ae79adc0dcd24ef5469",
"sha256": "2ec390faaddad72ee59f819cf54f3f0aafa463b637180e7f877034b7352d474a",
"path": "KSwitcher.Config.exe",
"size": 2458112
},
{
"sha256": "30e8dbe575b3705ae379fda30174e0a486ef5605ec582dd81e01b121180c127b",
"sha256": "149ef86ea46f8c2b01b1d806a4770d7226cffc1b55059fa3ef63233d90b17e96",
"path": "KSwitcher.Screenshot.exe",
"size": 3060224
},
{
"sha256": "b45ff37c0f279dcf142606c282b73cf3403cb026c4800beea216fd532bc5993f",
"sha256": "85b7aa5e99a4e60d49193de077c6067afb53fbadcc724504167855732d787543",
"path": "KSwitcher.Files.exe",
"size": 4214272
"size": 4229120
},
{
"sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6",
@@ -153,7 +153,7 @@
"size": 993
},
{
"sha256": "f1cd3477fc3e64ed26986b86d85472ca0780963b225231ab575489d4fa82e01b",
"sha256": "9aa1710226ee70d49b6a02fed41411f5f70c16422a76ee079e67d2eb3a53c5d2",
"path": "tools/StayHere.exe",
"size": 133120
},
+3 -3
View File
@@ -9,8 +9,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur"
1 RT_MANIFEST "app.manifest"
201 RCDATA "update.ps1"
1 VERSIONINFO
FILEVERSION 0,6,112,0
PRODUCTVERSION 0,6,112,0
FILEVERSION 0,6,115,0
PRODUCTVERSION 0,6,115,0
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_APP
BEGIN
@@ -20,7 +20,7 @@ BEGIN
BEGIN
VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility"
VALUE "ProductName", "KSwitcher"
VALUE "FileVersion", "0.6.112"
VALUE "FileVersion", "0.6.115"
END
END
BLOCK "VarFileInfo"
+36
View File
@@ -50,6 +50,41 @@ BEGIN
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 153, 42, 60, 17
END
611 DIALOGEX 0, 0, 332, 96
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "&Open/create file:", 460, 14, 16, 304, 12
FAR_EDIT(461, 0, 14, 29, 304, 14)
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
LTEXT "&Code page:", 462, 14, 53, 94, 12
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
CONTROL "", 467, "Static", NOT WS_VISIBLE, 14, 72, 1, 1
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 76, 60, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 76, 60, 16
END
612 DIALOGEX 0, 0, 332, 184
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
BEGIN
LTEXT "Save file &as:", 460, 14, 16, 304, 12
FAR_EDIT(461, 0, 14, 29, 304, 14)
CONTROL "", 466, "Static", NOT WS_VISIBLE, 14, 50, 1, 1
LTEXT "&Code page:", 462, 14, 53, 94, 12
COMBOBOX 463, 112, 51, 206, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
AUTOCHECKBOX "Add signature (&BOM)", 464, 14, 66, 304, 12
CONTROL "", 468, "Static", NOT WS_VISIBLE, 14, 86, 1, 1
LTEXT "Change line breaks to:", 469, 14, 87, 304, 12
AUTORADIOBUTTON "Do &not change", 470, 14, 100, 304, 12, WS_GROUP | WS_TABSTOP
AUTORADIOBUTTON "&Windows (CR LF)", 471, 14, 112, 304, 12
AUTORADIOBUTTON "&Unix (LF)", 472, 14, 124, 304, 12
AUTORADIOBUTTON "&Mac (CR)", 473, 14, 136, 304, 12
CONTROL "", 467, "Static", NOT WS_VISIBLE | WS_GROUP, 14, 155, 1, 1
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 157, 60, 16
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 170, 157, 60, 16
END
607 DIALOGEX 0, 0, 185, 57
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
FONT 10, "Consolas"
@@ -60,6 +95,7 @@ BEGIN
CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 67, 38, 51, 15
CONTROL "&Yes", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 36, 38, 51, 15
CONTROL "&No", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 98, 38, 51, 15
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 129, 38, 51, 15
CONTROL "&Processes…", 103, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 14, 38, 75, 15
END
+306 -64
View File
@@ -376,8 +376,8 @@ struct Panel
};
Panel panels[2];
FilesTerminal terminal;
std::mutex remoteOutputMutex;
std::string remoteOutput;
std::mutex pendingTerminalOutputMutex;
std::string pendingTerminalOutput;
std::atomic<bool> remoteCommandRunning{};
std::jthread remoteCommandThread;
std::ofstream terminalTrace;
@@ -499,6 +499,7 @@ struct FilesNoticeOptions
bool *remember{};
FilesNoticeTone tone{FilesNoticeTone::dialog};
bool processes{};
bool saveChanges{};
};
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={});
void openMenu(HWND window, int index);
@@ -528,6 +529,19 @@ void savePreference(const wchar_t *name, DWORD value)
}
#include "files_styles.inl"
FileRowStyle panelRowStyle(const Panel &panel,size_t row,bool cursor,bool activePanel)
{
const bool focused=cursor && activePanel;
const auto foreground=colors[Text],background=colors[focused?PanelCursor:PanelBlue];
if(row>=panel.rows.size() || panel.sizes[row]==L"Up") return {foreground,background};
const bool marked=panel.marked[row];
const bool transferred=transferHighlightPhase%2==0 && panel.transferResults.contains(panel.rows[row]);
const auto state=marked?FileRowState::Marked:!cursor?FileRowState::Normal:
focused?FileRowState::Focused:FileRowState::Unfocused;
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 refreshCommandHistory();
#include "files_command_history.inl"
@@ -1610,23 +1624,23 @@ void updateTerminalOutput()
if(!bytes.empty()) terminalView.send(bytes);
std::string incoming;
{
const std::lock_guard lock(remoteOutputMutex);
incoming.swap(remoteOutput);
const std::lock_guard lock(pendingTerminalOutputMutex);
incoming.swap(pendingTerminalOutput);
}
if(!incoming.empty()) terminalView.send(incoming);
}
void appendRemoteOutput(std::string_view output)
void appendTerminalOutput(std::string_view output)
{
const std::lock_guard lock(remoteOutputMutex);
const std::lock_guard lock(pendingTerminalOutputMutex);
for(const auto character:output)
{
const auto byte=static_cast<unsigned char>(character);
if(byte>=32 || character=='\r' || character=='\n' || character=='\t')
remoteOutput+=character;
pendingTerminalOutput+=character;
}
constexpr size_t limit=1024*1024;
if(remoteOutput.size()>limit) remoteOutput.erase(0,remoteOutput.size()-limit);
if(pendingTerminalOutput.size()>limit) pendingTerminalOutput.erase(0,pendingTerminalOutput.size()-limit);
}
bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
@@ -1636,7 +1650,7 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
{
constexpr auto busy=L"A remote command is running. Clear the command line and press Escape to cancel it.";
setStatus(busy);
if(terminalVisible) appendRemoteOutput(ks::utf8(std::wstring(L"\r\n")+busy+L"\r\n"));
if(terminalVisible) appendTerminalOutput(ks::utf8(std::wstring(L"\r\n")+busy+L"\r\n"));
return false;
}
if(panel.peer)
@@ -1647,7 +1661,7 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
layout(owner);
const auto peer=*panel.peer;
const auto directory=panel.directory;
appendRemoteOutput(ks::utf8(L"\r\n["+peer.name+L" · "+directory.wstring()+L"]> "+value+L"\r\n"));
appendTerminalOutput(ks::utf8(L"\r\n["+peer.name+L" · "+directory.wstring()+L"]> "+value+L"\r\n"));
remoteCommandRunning=true;
try
{
@@ -1656,11 +1670,11 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
try
{
FilesConnection host(&peer);
const auto code=ks::lan::runRemoteCommand(host,directory,value,appendRemoteOutput,stop);
const auto code=ks::lan::runRemoteCommand(host,directory,value,appendTerminalOutput,stop);
if(code==STATUS_DLL_INIT_FAILED)
appendRemoteOutput("\r\nRemote PowerShell could not start: DLL initialization failed (0xC0000142).\r\n");
appendTerminalOutput("\r\nRemote PowerShell could not start: DLL initialization failed (0xC0000142).\r\n");
else
appendRemoteOutput("\r\n[Remote exit code "+std::to_string(code)+"]\r\n");
appendTerminalOutput("\r\n[Remote exit code "+std::to_string(code)+"]\r\n");
}
catch(const std::system_error &error)
{
@@ -1669,11 +1683,11 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value)
? L"The remote PC denied this command. Check its Files command-line settings."
: code==ERROR_INVALID_FUNCTION?L"Update KSwitcher on the remote PC."
: code==ERROR_CANCELLED?L"Remote command canceled.":fileError(error);
appendRemoteOutput(ks::utf8(L"\r\n"+std::wstring(reason)+L"\r\n"));
appendTerminalOutput(ks::utf8(L"\r\n"+std::wstring(reason)+L"\r\n"));
}
catch(const std::exception &)
{
appendRemoteOutput("\r\nThe remote command connection ended.\r\n");
appendTerminalOutput("\r\nThe remote command connection ended.\r\n");
}
remoteCommandRunning=false;
});
@@ -2182,7 +2196,8 @@ void collectFolderSizes()
}
void openSelectedText(const Panel &panel, bool edit, bool external);
INT_PTR confirmTextSave(HWND owner);
INT_PTR confirmTextSave(HWND owner,bool draft);
bool chooseTextSaveOptions(HWND owner,fs::path &destination,ks::files::TextSaveFormat &format);
INT_PTR paintTextDialog(HWND window, UINT message, WPARAM wp, LPARAM lp, const wchar_t *caption);
INT_PTR paintSearchDialog(HWND window,UINT message,WPARAM wp,LPARAM lp);
ks::files::FarDropDownPalette farDropDownPalette();
@@ -2718,12 +2733,13 @@ void chooseDrive(int index,bool fromMenu)
RedrawWindow(owner,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN|RDW_UPDATENOW);
}
void openPanelPathWithSystem(const Panel &panel,const fs::path &path,const wchar_t *verb,
bool openPanelPathWithSystem(const Panel &panel,const fs::path &path,const wchar_t *verb,
const wchar_t *failureMessage)
{
if (reinterpret_cast<INT_PTR>(ShellExecuteW(GetParent(panel.list), verb, path.c_str(), nullptr,
panel.directory.c_str(), SW_SHOWNORMAL)) <= 32)
setStatus(failureMessage);
panel.directory.c_str(), SW_SHOWNORMAL)) > 32) return true;
setStatus(failureMessage);
return false;
}
void openPanelFile(const Panel &panel, const fs::path &file, const wchar_t *verb, const wchar_t *failureMessage)
@@ -2754,8 +2770,21 @@ void openPanelFile(const Panel &panel, const fs::path &file, const wchar_t *verb
}
return;
}
const bool recordOpen=!verb;
if(!verb && isExtension(L".exe")) verb=L"open";
openPanelPathWithSystem(panel,file,verb,failureMessage);
if(!openPanelPathWithSystem(panel,file,verb,failureMessage) || !recordOpen) return;
const auto command=L"start "+powerShellPath(file);
rememberCommand(command);
terminalHistoryIndex=terminalHistory.size();
const auto owner=GetParent(panel.list);
if(!ensureTerminalView(owner)) return;
appendTerminalOutput(ks::utf8(L"\r\n"+command+L"\r\n"));
if(!terminalVisible && terminalRows==0)
{
terminalRows=5;
layout(owner);
}
terminalView.post(L"scroll-bottom");
}
void openSelectedWithSystem(const Panel &panel)
@@ -2774,6 +2803,17 @@ void openSelectedWithSystem(const Panel &panel)
#include "files_dialog_input.inl"
ks::files::TextDialogs textWindowDialogs()
{
return {confirmTextSave,paintTextDialog,paintSearchDialog,prepareTextDialog,editTextOptions,showTextMessage,readFilesFont,
farDropDownPalette,FilesModalDialog::run,FilesModalDialog::finish,FilesModalDialog::dismissOwned,
[](HWND owner)
{
return showFilesNotice(owner,L"This file is already open. Switch to its window?",L"Files",
{.confirm=true})==IDYES;
},chooseTextSaveOptions};
}
void openSelectedText(const Panel &panel, bool edit, bool external)
{
const auto row=currentPanelRow(panel);
@@ -2787,14 +2827,8 @@ void openSelectedText(const Panel &panel, bool edit, bool external)
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 ks::files::openTextWindow(GetParent(panel.list),path,edit,
{confirmTextSave,paintTextDialog,paintSearchDialog,prepareTextDialog,editTextOptions,showTextMessage,readFilesFont,
farDropDownPalette,FilesModalDialog::run,FilesModalDialog::finish,FilesModalDialog::dismissOwned,
[](HWND owner)
{
return showFilesNotice(owner,L"This file is already open. Switch to its window?",L"Files",
{.confirm=true})==IDYES;
}},panel.peer?&*panel.peer:nullptr);
else ks::files::openTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),
panel.peer?&*panel.peer:nullptr);
}
void enter(Panel &panel)
@@ -3329,7 +3363,9 @@ LRESULT CALLBACK paintFarCheckbox(HWND field,UINT message,WPARAM wp,LPARAM lp,UI
SetTextColor(dc,IsWindowEnabled(field)?ink:RGB(128,128,128));
wchar_t label[80]{};
GetWindowTextW(field,label,static_cast<int>(std::size(label)));
const auto text=(SendMessageW(field,BM_GETCHECK,0,0)==BST_CHECKED?L"[x] ":L"[ ] ")+std::wstring(label);
const bool radio=(GetWindowLongPtrW(field,GWL_STYLE)&BS_TYPEMASK)==BS_AUTORADIOBUTTON;
const bool checked=SendMessageW(field,BM_GETCHECK,0,0)==BST_CHECKED;
const auto text=(radio?(checked?L"(•) ":L"( ) "):(checked?L"[x] ":L"[ ] "))+std::wstring(label);
if(IsWindowEnabled(field)) drawFarDialogLabel(dc,bounds,text,false);
else DrawTextW(dc,text.c_str(),-1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS);
EndPaint(field,&paint);
@@ -3894,8 +3930,6 @@ void prepareTextDialog(HWND dialog)
INT_PTR CALLBACK textSaveDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(const auto painted=paintTextDialog(window,message,wp,lp,L" Editor "))
return painted;
if(message==WM_INITDIALOG)
{
prepareTextDialog(window);
@@ -3904,6 +3938,7 @@ INT_PTR CALLBACK textSaveDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
SetFocus(GetDlgItem(window,IDCANCEL));
return FALSE;
}
if(const auto painted=paintTextDialog(window,message,wp,lp,L" Editor ")) return painted;
if(message==WM_COMMAND && (LOWORD(wp)==IDYES || LOWORD(wp)==IDNO || LOWORD(wp)==IDCANCEL))
{
FilesModalDialog::finish(window,LOWORD(wp));
@@ -3912,8 +3947,11 @@ INT_PTR CALLBACK textSaveDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
return FALSE;
}
INT_PTR confirmTextSave(HWND owner)
INT_PTR confirmTextSave(HWND owner,bool draft)
{
if(draft)
return showFilesNotice(owner,L"Save changes to this file?",L"Editor",
{.tone=FilesNoticeTone::warning,.saveChanges=true});
return FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(603),owner,textSaveDialog,0);
}
@@ -3968,7 +4006,8 @@ void layoutFilesNotice(HWND dialog)
bottom+=textHeight;
}
place(102,bottom+dialogRowGap()+4,1);
if(notice.options.confirm) layoutDialogButtons(dialog,102,{IDYES,IDNO});
if(notice.options.saveChanges) layoutDialogButtons(dialog,102,{IDYES,IDNO,IDCANCEL});
else if(notice.options.confirm) layoutDialogButtons(dialog,102,{IDYES,IDNO});
else if(notice.options.processes) layoutDialogButtons(dialog,102,{showProcessesButton,IDOK});
else layoutDialogButtons(dialog,102,{IDOK});
}
@@ -3991,12 +4030,18 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
notice.options.tone==FilesNoticeTone::neutral?FarCheckboxSurface::gray:FarCheckboxSurface::dialog);
ShowWindow(checkbox,SW_SHOW);
}
if(notice.options.confirm)
if(notice.options.confirm || notice.options.saveChanges)
{
ShowWindow(GetDlgItem(window,IDOK),SW_HIDE);
ShowWindow(GetDlgItem(window,IDYES),SW_SHOW);
ShowWindow(GetDlgItem(window,IDNO),SW_SHOW);
}
if(notice.options.saveChanges)
{
SetDlgItemTextW(window,IDYES,L"&Save");
SetDlgItemTextW(window,IDNO,L"&Discard");
ShowWindow(GetDlgItem(window,IDCANCEL),SW_SHOW);
}
if(notice.options.processes) ShowWindow(GetDlgItem(window,showProcessesButton),SW_SHOW);
RECT caption{},text{};
if(const auto dc=GetDC(window))
@@ -4009,12 +4054,12 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
}
const auto inset=dialogFrameMetrics(GetDpiForWindow(window)).content();
const auto minimum=std::max({24L*cellWidth,caption.right+6*cellWidth,
notice.options.remember || notice.options.processes?34L*cellWidth:0L})+2*inset;
notice.options.remember || notice.options.processes || notice.options.saveChanges?34L*cellWidth:0L})+2*inset;
const auto width=std::clamp(text.right+cellWidth+2*inset,minimum,std::max(minimum,60L*cellWidth+2*inset));
SetWindowPos(window,nullptr,0,0,width,1,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
layoutFilesNotice(window);
FilesModalDialog::fitWidthToOwner(window,minimum,layoutFilesNotice);
const auto defaultButton=notice.options.confirm?IDNO:IDOK;
const auto defaultButton=notice.options.saveChanges?IDCANCEL:notice.options.confirm?IDNO:IDOK;
SendMessageW(window,DM_SETDEFID,defaultButton,0);
SetFocus(GetDlgItem(window,defaultButton));
return FALSE;
@@ -5230,6 +5275,196 @@ void makeFolder(HWND owner,Panel &panel)
selectPanelPath(panel,request.created);
}
struct TextFilePrompt
{
fs::path directory,path;
ks::files::TextSaveFormat format;
bool saving{};
};
constexpr const wchar_t *textCodePages[]{L"Default",L"65001 | UTF-8",L"1200 | UTF-16 LE",
L"1201 | UTF-16 BE",L"1252 | Windows-1252"};
constexpr int textPathField=461,textCodePage=463,textBom=464,textFooter=467,textFirstLineEnding=470;
void layoutTextFilePrompt(HWND dialog)
{
RECT client{};
GetClientRect(dialog,&client);
const auto frame=dialogFrameMetrics(GetDpiForWindow(dialog));
const auto inset=frame.content(),gap=dialogRowGap();
const auto width=client.right-2*inset;
const auto place=[&](int id,int x,int y,int w,int h)
{
SetWindowPos(GetDlgItem(dialog,id),nullptr,x,y,w,h,SWP_NOZORDER|SWP_NOACTIVATE);
};
auto y=dialogListInset(frame,textHeight);
const auto row=[&](int id)
{
place(id,inset,y,width,textHeight);
y+=textHeight;
};
const auto divider=[&](int id)
{
y+=gap;
place(id,inset,y+4,1,1);
y+=gap+1;
};
row(460);
row(textPathField);
fitFarEditToLine(GetDlgItem(dialog,textPathField));
divider(466);
const auto labelWidth=12*cellWidth;
place(462,inset,y,labelWidth,textHeight);
place(textCodePage,inset+labelWidth,y,width-labelWidth,textHeight);
y+=textHeight;
if(GetDlgItem(dialog,textBom))
{
row(textBom);
divider(468);
row(469);
for(int i=0;i<4;++i) row(textFirstLineEnding+i);
}
divider(textFooter);
layoutDialogButtons(dialog,textFooter,{IDOK,IDCANCEL});
}
fs::path unnamedTextFile(const fs::path &directory)
{
SYSTEMTIME time{};
GetLocalTime(&time);
wchar_t stem[64]{};
swprintf_s(stem,L"New_File_%04u-%02u-%02u_%02u.%02u.%02u.%03u",
unsigned(time.wYear),unsigned(time.wMonth),unsigned(time.wDay),unsigned(time.wHour),
unsigned(time.wMinute),unsigned(time.wSecond),unsigned(time.wMilliseconds));
auto path=directory/(std::wstring(stem)+L".txt");
for(unsigned suffix=1;GetFileAttributesW(path.c_str())!=INVALID_FILE_ATTRIBUTES;++suffix)
path=directory/(std::wstring(stem)+L"_"+std::to_wstring(suffix)+L".txt");
return path;
}
INT_PTR CALLBACK textFilePrompt(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
{
using namespace ks::files;
const auto field=GetDlgItem(dialog,textPathField);
const auto combo=GetDlgItem(dialog,textCodePage);
if(message==WM_INITDIALOG)
{
SetWindowLongPtrW(dialog,DWLP_USER,lp);
const auto &prompt=*reinterpret_cast<const TextFilePrompt *>(lp);
prepareTextDialog(dialog);
const auto inset=dialogFrameMetrics(GetDpiForWindow(dialog)).content();
SetWindowPos(dialog,nullptr,0,0,48*cellWidth+2*inset,1,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
layoutTextFilePrompt(dialog);
if(prompt.saving)
{
SetWindowTextW(field,prompt.path.filename().c_str());
installFarCheckbox(GetDlgItem(dialog,textBom),FarCheckboxSurface::gray);
for(int i=0;i<4;++i)
installFarCheckbox(GetDlgItem(dialog,textFirstLineEnding+i),FarCheckboxSurface::gray);
CheckDlgButton(dialog,textBom,prompt.format.bom?BST_CHECKED:BST_UNCHECKED);
CheckRadioButton(dialog,textFirstLineEnding,textFirstLineEnding+3,
textFirstLineEnding+static_cast<int>(prompt.format.lineEnding));
}
const int first=prompt.saving?1:0;
for(int i=first;i<static_cast<int>(std::size(textCodePages));++i)
SendMessageW(combo,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(textCodePages[i]));
installFarCombo(combo,field);
SendMessageW(combo,CB_SETCURSEL,static_cast<int>(prompt.format.encoding)-first,0);
if(prompt.saving) EnableWindow(GetDlgItem(dialog,textBom),prompt.format.encoding!=TextEncoding::windows1252);
FilesModalDialog::fitWidthToOwner(dialog,36*cellWidth+2*inset,layoutTextFilePrompt);
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
SetFocus(field);
SendMessageW(field,EM_SETSEL,0,-1);
return FALSE;
}
auto *prompt=reinterpret_cast<TextFilePrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
if(!prompt) return FALSE;
if(message==WM_DRAWITEM && wp==textCodePage)
{
drawFarComboRow(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
return TRUE;
}
if(message==WM_CTLCOLORLISTBOX)
{
const auto dc=reinterpret_cast<HDC>(wp);
SetTextColor(dc,colors[Text]);
SetBkColor(dc,colors[Dialog]);
return reinterpret_cast<INT_PTR>(teal);
}
const auto painted=prompt->saving?paintCopyDialog(dialog,message,wp,lp,L" Editor ",false,{466,468,textFooter}):
paintCopyDialog(dialog,message,wp,lp,L" Editor ",false,{466,textFooter});
if(painted) return painted;
if(message!=WM_COMMAND) return FALSE;
const auto command=LOWORD(wp);
if(command==IDCANCEL) {FilesModalDialog::finish(dialog,IDCANCEL); return TRUE;}
const auto selected=SendMessageW(combo,CB_GETCURSEL,0,0);
const auto encoding=static_cast<TextEncoding>(std::max<LRESULT>(0,selected)+prompt->saving);
if(command==textCodePage && HIWORD(wp)==CBN_SELCHANGE && prompt->saving)
{
EnableWindow(GetDlgItem(dialog,textBom),encoding!=TextEncoding::windows1252);
return TRUE;
}
if(command!=IDOK) return FALSE;
const auto entered=dialogFieldText(field);
const fs::path name=entered;
const auto path=(name.empty()?unnamedTextFile(prompt->directory):prompt->directory/name).lexically_normal();
const auto parent=GetFileAttributesW(path.parent_path().c_str());
const auto attributes=GetFileAttributesW(path.c_str());
if((name.has_root_name() && !name.is_absolute()) || !validFileName(path.filename().native()) ||
parent==INVALID_FILE_ATTRIBUTES || !(parent&FILE_ATTRIBUTE_DIRECTORY) ||
(attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY)))
{
showFilesNotice(dialog,L"Enter a valid file name in an existing folder.",L"Editor");
SetFocus(field);
return TRUE;
}
if(prompt->saving && attributes!=INVALID_FILE_ATTRIBUTES)
{
showFilesNotice(dialog,L"A file with this name already exists. Choose another name.",L"Editor");
SetFocus(field);
return TRUE;
}
prompt->path=path;
prompt->format.encoding=encoding;
if(prompt->saving)
{
prompt->format.bom=encoding!=TextEncoding::windows1252 &&
IsDlgButtonChecked(dialog,textBom)==BST_CHECKED;
for(int i=0;i<4;++i)
if(IsDlgButtonChecked(dialog,textFirstLineEnding+i)==BST_CHECKED)
prompt->format.lineEnding=static_cast<TextLineEnding>(i);
}
FilesModalDialog::finish(dialog,IDOK);
return TRUE;
}
bool chooseTextSaveOptions(HWND owner,fs::path &destination,ks::files::TextSaveFormat &format)
{
TextFilePrompt prompt{destination.parent_path(),destination,format,true};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(612),owner,textFilePrompt,
reinterpret_cast<LPARAM>(&prompt))!=IDOK) return false;
destination=std::move(prompt.path);
format=prompt.format;
return true;
}
void openOrCreateText(HWND owner,const Panel &panel)
{
if(panel.peer)
{
setStatus(L"Open/create file is available in local panels.");
return;
}
if(panel.directory.empty()) return;
TextFilePrompt prompt{panel.directory,{}, {.encoding=ks::files::TextEncoding::automatic}};
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(611),owner,textFilePrompt,
reinterpret_cast<LPARAM>(&prompt))!=IDOK) return;
const auto attributes=GetFileAttributesW(prompt.path.c_str());
const bool draft=attributes==INVALID_FILE_ATTRIBUTES && GetLastError()==ERROR_FILE_NOT_FOUND;
ks::files::openTextWindow(owner,prompt.path,true,textWindowDialogs(),nullptr,{},false,
{prompt.format.encoding,draft});
}
LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
{
const auto index=GetDlgCtrlID(window)-102;
@@ -5238,9 +5473,12 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
{
if(message==WM_LBUTTONDOWN) clearTerminalSelection();
auto &panel=panels[index];
activatePanel(static_cast<int>(index));
const auto count=SendMessageW(window,LB_GETCOUNT,0,0);
if(!count || count==LB_ERR) return 0;
if(count<=0)
{
activatePanel(index);
return 0;
}
const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp);
const auto row=static_cast<LRESULT>(LOWORD(hit));
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
@@ -5250,13 +5488,26 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
PtInRect(&bounds,point);
const auto previous=SendMessageW(window,LB_GETCURSEL,0,0);
const auto target=rowHit?row:point.y>=0 && message==WM_LBUTTONDOWN?count-1:previous;
if(target!=previous)
if(target!=previous && index!=active)
{
const auto top=SendMessageW(window,LB_GETTOPINDEX,0,0);
// The native list can repaint during selection. Activate it only after moving the cursor.
const bool visible=IsWindowVisible(window);
if(visible) SendMessageW(window,WM_SETREDRAW,FALSE,0);
SendMessageW(window,LB_SETCURSEL,target,0);
if(visible) SendMessageW(window,WM_SETREDRAW,TRUE,0);
if(top!=SendMessageW(window,LB_GETTOPINDEX,0,0))
InvalidateRect(window,nullptr,FALSE);
else if(panelRowStyle(panel,previous,true,false)!=panelRowStyle(panel,previous,false,false))
invalidatePanelRow(window,previous);
}
else if(target!=previous)
{
// The list box can draw synchronously before committing its new selection.
SendMessageW(window,LB_SETCURSEL,target,0);
invalidatePanelCursorChange(window,previous);
}
showFileDetails(panel);
activatePanel(index);
if(message==WM_LBUTTONDOWN) SetCapture(window);
if(message==WM_LBUTTONDBLCLK && rowHit) enter(panel);
return 0;
@@ -5748,7 +5999,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
if(!completionList || !completionFrame) return -1;
SetWindowSubclass(completionList,completionClick,1,0);
installScrollBar(completionList,completionFrame);
terminalBackground=CreateSolidBrush(RGB(24,24,24));
terminalBackground=CreateSolidBrush(terminalSurface);
if(!terminalInput || !terminalOutput || !terminalPrompt || !terminalBackground) return -1;
for(const auto control:{terminalInput,terminalOutput,terminalPrompt})
SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
@@ -5899,7 +6150,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
reinterpret_cast<HWND>(lp)==terminalPrompt)
{
SetTextColor(dc,RGB(232,232,232));
SetBkColor(dc,RGB(24,24,24));
SetBkColor(dc,terminalSurface);
return reinterpret_cast<LRESULT>(terminalBackground);
}
SetTextColor(dc,colors[Frame]);
@@ -6069,34 +6320,19 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
background=Selection;
const bool panelRow=item.CtlID==102 || item.CtlID==103;
const bool activePanelRow=panelRow && item.hwndItem==panels[active].list;
if(panelRow)
{
const auto cursor=SendMessageW(item.hwndItem,LB_GETCURSEL,0,0);
if(activePanelRow && cursor!=LB_ERR &&
static_cast<UINT>(cursor)==item.itemID) background=PanelCursor;
traceTerminal("panel-draw",item.CtlID-102,item.itemID,background==PanelCursor);
}
else if(item.itemState&(ODS_SELECTED|ODS_FOCUS))
if(!panelRow && (item.itemState&(ODS_SELECTED|ODS_FOCUS)))
background=Selection;
COLORREF rowBackground=colors[background];
HFONT rowFont{};
if(panelRow)
{
const auto &panel=panels[item.CtlID-102];
if(item.itemID<panel.rows.size() && panel.sizes[item.itemID]!=L"Up")
{
const bool marked=panel.marked[item.itemID];
const bool transferred=transferHighlightPhase%2==0 && panel.transferResults.contains(panel.rows[item.itemID]);
const bool cursor=SendMessageW(panel.list,LB_GETCURSEL,0,0)==item.itemID;
const auto state=marked?FileRowState::Marked:!cursor?FileRowState::Normal:
activePanelRow?FileRowState::Focused:FileRowState::Unfocused;
const auto resolved=resolveFileStyle(panel.rows[item.itemID].extension().native(),
panel.sizes[item.itemID]!=L"Folder",panel.dimmed[item.itemID],
background==PanelCursor || marked || transferred,foreground,rowBackground,fileStyles,state,transferred);
foreground=resolved.foreground;
rowBackground=resolved.background;
rowFont=fileStyleFonts[resolved.decorations];
}
const bool cursor=item.itemID!=UINT(-1) && SendMessageW(panel.list,LB_GETCURSEL,0,0)==item.itemID;
traceTerminal("panel-draw",item.CtlID-102,item.itemID,activePanelRow && cursor);
const auto resolved=panelRowStyle(panel,item.itemID,cursor,activePanelRow);
foreground=resolved.foreground;
rowBackground=resolved.background;
rowFont=fileStyleFonts[resolved.decorations];
}
auto shortcut=text.find(L'\t');
if(item.hwndItem==picker && commandPicker && item.itemID<commandAccessPositions.size())
@@ -6477,6 +6713,12 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
{
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0;
if(shift && !ctrl && message.wParam==VK_F4 && !terminalVisible)
{
if(!(message.lParam & (1LL<<30)) && commandLineAvailable(window))
openOrCreateText(window,panels[active]);
continue;
}
if(ctrl && !shift &&
(message.wParam=='F' || message.wParam=='C' || message.wParam=='R' ||
(message.wParam=='U' && !terminalVisible) ||
+1
View File
@@ -128,6 +128,7 @@ struct FileRowStyle
{
COLORREF foreground,background;
unsigned decorations{};
bool operator==(const FileRowStyle &) const = default;
};
FileRowStyle resolveFileStyle(std::wstring_view extension,bool file,bool dimmed,bool protectedRow,
COLORREF foreground,COLORREF background,const std::vector<FileStyle> &styles=fileStyles,
+35 -3
View File
@@ -3,6 +3,9 @@
#ifdef __MINGW32__
__CRT_UUID_DECL(ICoreWebView2_3, 0xA0D6DF20, 0x3B92, 0x416D, 0xAA, 0x0C, 0x43, 0x7A, 0x9C, 0x72, 0x78, 0x57)
__CRT_UUID_DECL(ICoreWebView2Controller2, 0xc979903e, 0xd4ca, 0x4228, 0x92, 0xeb, 0x47, 0xee, 0x3f, 0xa9, 0x6e, 0xab)
__CRT_UUID_DECL(ICoreWebView2ControllerOptions3, 0xb32b191a, 0x8998, 0x57ca, 0xb7, 0xcb, 0xe0, 0x46, 0x17, 0xe4, 0xce, 0x4a)
__CRT_UUID_DECL(ICoreWebView2Environment10, 0xee0eb9df, 0x6f12, 0x46ce, 0xb5, 0x3f, 0x3f, 0x47, 0xb9, 0xc9, 0x28, 0xe0)
__CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler, 0x4e8a3389, 0xc9d8, 0x4bd2, 0xb6, 0xb5, 0x12, 0x4f, 0xee, 0x6c, 0xc1, 0x4d)
__CRT_UUID_DECL(ICoreWebView2CreateCoreWebView2ControllerCompletedHandler, 0x6c4819f3, 0xc9b7, 0x4260, 0x81, 0x27, 0xc9, 0xf5, 0xbd, 0xe7, 0xf6, 0x8c)
__CRT_UUID_DECL(ICoreWebView2WebMessageReceivedEventHandler, 0x57213f19, 0x00e6, 0x49fa, 0x8e, 0x07, 0x89, 0x8e, 0xa0, 0x1e, 0xcb, 0xd2)
@@ -16,6 +19,8 @@ __CRT_UUID_DECL(ICoreWebView2AcceleratorKeyPressedEventHandler, 0xb29c7e28, 0xfa
#include <memory>
#include <utility>
inline constexpr COLORREF terminalSurface=RGB(24,24,24);
template<class Interface, class... Args>
class TerminalCallback final : public Interface
{
@@ -56,6 +61,7 @@ class FilesTerminalView
RECT bounds{};
bool ready{};
bool visible{};
bool waitForReady{};
public:
~FilesTerminalView() { close(); }
void focus()
@@ -94,9 +100,10 @@ public:
RECT current{};
if(FAILED(controller->get_Bounds(&current)) || !EqualRect(&current,&bounds))
controller->put_Bounds(bounds);
const bool showController=show && (!waitForReady || ready);
BOOL currentVisibility{};
if(FAILED(controller->get_IsVisible(&currentVisibility)) || !!currentVisibility!=show)
controller->put_IsVisible(show);
if(FAILED(controller->get_IsVisible(&currentVisibility)) || !!currentVisibility!=showController)
controller->put_IsVisible(showController);
}
void close()
{
@@ -140,6 +147,9 @@ public:
const auto uri=std::wstring(L"https://")+origin+(markdown?L"/markdown.html":L"/index.html");
const auto assets=folder/L"terminal";
if(markdown && !std::filesystem::exists(assets/L"markdown.html")) return false;
waitForReady=!markdown;
constexpr COREWEBVIEW2_COLOR background{
255,GetRValue(terminalSurface),GetGValue(terminalSurface),GetBValue(terminalSurface)};
lifetime=std::make_shared<int>(0);
const std::weak_ptr<int> alive=lifetime;
auto environment=terminalCallback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler,
@@ -153,6 +163,12 @@ public:
if(alive.expired()) return S_OK;
if(FAILED(result) || !view) { failed(); return S_OK; }
controller=view;
if(!markdown)
{
view->put_IsVisible(FALSE);
Microsoft::WRL::ComPtr<ICoreWebView2Controller2> colors;
if(SUCCEEDED(controller.As(&colors))) colors->put_DefaultBackgroundColor(background);
}
view->get_CoreWebView2(&web);
Microsoft::WRL::ComPtr<ICoreWebView2_3> mapped;
if(!web || FAILED(web.As(&mapped)) || FAILED(mapped->SetVirtualHostNameToFolderMapping(
@@ -207,7 +223,11 @@ public:
uri==source &&
SUCCEEDED(args->TryGetWebMessageAsString(&value)))
{
if(wcscmp(value,L"ready")==0) ready=true;
if(!ready && wcscmp(value,L"ready")==0)
{
ready=true;
if(waitForReady) layout(bounds,visible);
}
if(ready) receive(value);
}
CoTaskMemFree(value);
@@ -222,6 +242,18 @@ public:
layout(bounds,visible);
return S_OK;
});
if(!markdown)
{
Microsoft::WRL::ComPtr<ICoreWebView2Environment10> configurable;
Microsoft::WRL::ComPtr<ICoreWebView2ControllerOptions> options;
Microsoft::WRL::ComPtr<ICoreWebView2ControllerOptions3> colors;
if(SUCCEEDED(env->QueryInterface(IID_PPV_ARGS(&configurable))) &&
SUCCEEDED(configurable->CreateCoreWebView2ControllerOptions(&options)) &&
SUCCEEDED(options.As(&colors)) &&
SUCCEEDED(colors->put_DefaultBackgroundColor(background)) &&
SUCCEEDED(configurable->CreateCoreWebView2ControllerWithOptions(host,options.Get(),completed.Get())))
return S_OK;
}
if(FAILED(env->CreateCoreWebView2Controller(host,completed.Get()))) failed();
return S_OK;
});
+142 -42
View File
@@ -38,6 +38,15 @@ HANDLE openSource(const std::filesystem::path &path, bool editable)
return result;
}
HANDLE trackReplacement(const std::filesystem::path &path)
{
// A metadata-only handle survives the rename without blocking ReplaceFile.
const auto handle=CreateFileW(path.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if(handle==INVALID_HANDLE_VALUE) fail("Track replacement file");
return handle;
}
uint64_t fileSize(HANDLE file)
{
LARGE_INTEGER size{};
@@ -97,10 +106,87 @@ std::filesystem::path createTemporary(const std::filesystem::path &directory, Fi
if (file.handle == INVALID_HANDLE_VALUE) fail("Create temporary file");
return path;
}
bool isUtf16(TextEncoding encoding)
{
return encoding==TextEncoding::utf16le || encoding==TextEncoding::utf16be;
}
TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(std::move(path)), editable_(editable)
std::string_view signature(TextEncoding encoding)
{
switch(encoding)
{
case TextEncoding::utf16le: return "\xff\xfe";
case TextEncoding::utf16be: return "\xfe\xff";
case TextEncoding::utf8: return "\xef\xbb\xbf";
default: return {};
}
}
std::wstring decodeMultibyte(std::string_view bytes,UINT codePage,DWORD flags)
{
const int length=static_cast<int>(bytes.size());
const auto required=MultiByteToWideChar(codePage,flags,bytes.data(),length,nullptr,0);
if(!required) fail("Decode text");
std::wstring units(required,L'\0');
if(!MultiByteToWideChar(codePage,flags,bytes.data(),length,units.data(),required)) fail("Decode text");
return units;
}
std::string encode(std::string_view utf8,TextEncoding encoding)
{
if(encoding==TextEncoding::utf8 || utf8.empty()) return std::string(utf8);
const auto units=decodeMultibyte(utf8,CP_UTF8,MB_ERR_INVALID_CHARS);
if(encoding==TextEncoding::windows1252)
{
BOOL substituted{};
const int length=static_cast<int>(units.size());
const auto required=WideCharToMultiByte(1252,WC_NO_BEST_FIT_CHARS,units.data(),length,
nullptr,0,nullptr,&substituted);
if(!required) fail("Encode Windows-1252");
if(substituted) throw std::runtime_error("Some characters cannot be saved as Windows-1252. Choose a Unicode encoding.");
std::string bytes(required,'\0');
if(!WideCharToMultiByte(1252,WC_NO_BEST_FIT_CHARS,units.data(),length,bytes.data(),required,nullptr,&substituted))
fail("Encode Windows-1252");
return bytes;
}
std::string bytes(units.size()*2,'\0');
const size_t low=encoding==TextEncoding::utf16le?0:1;
for(size_t i=0;i<units.size();++i)
{
bytes[2*i+low]=static_cast<char>(units[i]&0xff);
bytes[2*i+1-low]=static_cast<char>(units[i]>>8);
}
return bytes;
}
std::string convertLineEndings(std::string_view text,TextLineEnding ending)
{
if(ending==TextLineEnding::preserve) return std::string(text);
const std::string_view replacement=ending==TextLineEnding::crlf?"\r\n":ending==TextLineEnding::lf?"\n":"\r";
std::string result;
result.reserve(text.size());
for(size_t start=0;start<text.size();)
{
const auto next=text.find_first_of("\r\n",start);
result.append(text.substr(start,next==text.npos?text.npos:next-start));
if(next==text.npos) break;
result.append(replacement);
start=next+1;
if(text[next]=='\r' && start<text.size() && text[start]=='\n') ++start;
}
return result;
}
}
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding)
: path_(std::move(path)), editable_(editable)
{
if(path_.empty())
{
if(encoding!=TextEncoding::automatic) encoding_=encoding;
return;
}
File source{openSource(path_, editable)};
if (editable)
{
@@ -115,13 +201,15 @@ TextDocument::TextDocument(std::filesystem::path path, bool editable) : path_(st
}
size_ = fileSize(source.handle);
const auto prefix = read(source.handle, 0, static_cast<size_t>(std::min<uint64_t>(3, size_)));
if (prefix.starts_with("\xef\xbb\xbf")) bom_ = 3;
else if (prefix.starts_with("\xff\xfe") || prefix.starts_with("\xfe\xff"))
if(encoding==TextEncoding::automatic)
{
encoding_ = prefix.starts_with("\xff") ? Encoding::utf16le : Encoding::utf16be;
bom_ = 2;
if (size_ % 2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
encoding=TextEncoding::utf8;
for(const auto candidate:{TextEncoding::utf16le,TextEncoding::utf16be})
if(prefix.starts_with(signature(candidate))) encoding=candidate;
}
encoding_=encoding;
if(prefix.starts_with(signature(encoding_))) bom_=signature(encoding_).size();
if(isUtf16(encoding_) && size_%2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
source_ = source.release();
}
@@ -135,8 +223,9 @@ const wchar_t *TextDocument::encodingName() const
{
switch (encoding_)
{
case Encoding::utf16le: return L"UTF-16 LE";
case Encoding::utf16be: return L"UTF-16 BE";
case TextEncoding::utf16le: return L"UTF-16 LE";
case TextEncoding::utf16be: return L"UTF-16 BE";
case TextEncoding::windows1252: return L"Windows-1252";
default: return bom_ ? L"UTF-8 BOM" : L"UTF-8";
}
}
@@ -160,40 +249,45 @@ uint64_t TextDocument::boundary(uint64_t page,HANDLE source) const
if (page >= pages()) return size_;
const auto offset = bom_ + page * pageBytes;
const auto unit = encoding_ == Encoding::utf8 ? 1u : 2u;
const auto unit = isUtf16(encoding_) ? 2u : 1u;
const auto sample = read(source, offset - unit,
static_cast<size_t>(std::min<uint64_t>(4096 + unit, size_ - offset + unit)));
const auto getUnit = [&](size_t i) -> unsigned {
const auto first = static_cast<unsigned char>(sample[i]);
if (unit == 1) return first;
const auto second = static_cast<unsigned char>(sample[i + 1]);
return encoding_ == Encoding::utf16le ? first | (second << 8) : (first << 8) | second;
return encoding_ == TextEncoding::utf16le ? first | (second << 8) : (first << 8) | second;
};
if (getUnit(0) == '\n') return offset;
for (size_t i = unit; i + unit < sample.size(); i += unit)
if (getUnit(i) == '\n') return offset + i;
size_t i = unit;
if (unit == 1)
if (encoding_ == TextEncoding::utf8)
{
// Advance past at most one UTF-8 code point, even on malformed input.
while (i < sample.size() && i <= 3 && (getUnit(i) & 0xc0) == 0x80) ++i;
}
else if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
else if (isUtf16(encoding_))
if (const auto value = getUnit(i); value >= 0xdc00 && value <= 0xdfff) i += unit;
if (i == unit && getUnit(0) == '\r' && getUnit(i) == '\n') i += unit;
return offset + i - unit;
}
std::string TextDocument::decode(std::string bytes) const
{
if (encoding_ == Encoding::utf8 || bytes.empty()) return bytes;
if (encoding_ == TextEncoding::utf8 || bytes.empty()) return bytes;
std::wstring units;
units.resize(bytes.size() / 2);
for (size_t i = 0; i < units.size(); ++i)
if(encoding_==TextEncoding::windows1252) units=decodeMultibyte(bytes,1252,0);
else
{
const auto a = static_cast<unsigned char>(bytes[2 * i]);
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
units[i] = static_cast<wchar_t>(encoding_ == Encoding::utf16le ? a | (b << 8) : (a << 8) | b);
units.resize(bytes.size() / 2);
for (size_t i = 0; i < units.size(); ++i)
{
const auto a = static_cast<unsigned char>(bytes[2 * i]);
const auto b = static_cast<unsigned char>(bytes[2 * i + 1]);
units[i] = static_cast<wchar_t>(encoding_ == TextEncoding::utf16le ? a | (b << 8) : (a << 8) | b);
}
}
const auto length = static_cast<int>(units.size());
const int required = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, nullptr, 0, nullptr, nullptr);
@@ -204,25 +298,6 @@ std::string TextDocument::decode(std::string bytes) const
return result;
}
std::string TextDocument::encode(std::string_view utf8) const
{
if (encoding_ == Encoding::utf8 || utf8.empty()) return std::string(utf8);
const auto length = static_cast<int>(utf8.size());
const int required = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, nullptr, 0);
if (!required) fail("Encode UTF-16");
std::wstring units(required, L'\0');
if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), length, units.data(), required))
fail("Encode UTF-16");
std::string bytes(units.size() * 2, '\0');
const int low = encoding_ == Encoding::utf16le ? 0 : 1;
for (size_t i = 0; i < units.size(); ++i)
{
bytes[2 * i + low] = static_cast<char>(units[i] & 0xff);
bytes[2 * i + 1 - low] = static_cast<char>(units[i] >> 8);
}
return bytes;
}
std::string TextDocument::readPage(uint64_t page) const
{
if (const auto it = changes_.find(page); it != changes_.end())
@@ -232,6 +307,7 @@ std::string TextDocument::readPage(uint64_t page) const
std::string TextDocument::readOriginal(uint64_t page) const
{
if(path_.empty()) return {};
File temporary{source_ == INVALID_HANDLE_VALUE ? openSource(path_, false) : INVALID_HANDLE_VALUE};
const auto source=source_ == INVALID_HANDLE_VALUE ? temporary.handle : source_;
const auto start = boundary(page,source);
@@ -298,17 +374,14 @@ bool TextDocument::save()
for (const auto &[page, change] : changes_)
{
copyUntil(offset, boundary(page));
append(encode(read(spool_, change.offset, change.size)));
append(encode(read(spool_, change.offset, change.size),encoding_));
offset = boundary(page + 1);
}
copyUntil(offset, size_);
if (!FlushFileBuffers(output.handle)) fail("Flush saved file");
CloseHandle(output.release());
// A metadata-only handle survives the rename without blocking ReplaceFile's exclusive open.
File replacement{CreateFileW(pending.path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)};
if (replacement.handle == INVALID_HANDLE_VALUE) fail("Track replacement file");
File replacement{trackReplacement(pending.path)};
File current{openSource(path_, true)};
if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher.");
const auto backup = temporaryPath(path_.parent_path());
@@ -336,4 +409,31 @@ bool TextDocument::save()
spoolSize_ = 0;
return source_ != INVALID_HANDLE_VALUE;
}
bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
{
if(!path_.empty() || !editable_) throw std::logic_error("The document is not a new editable file.");
if(format.encoding==TextEncoding::automatic) format.encoding=TextEncoding::utf8;
const auto bytes=encode(convertLineEndings(readPage(0),format.lineEnding),format.encoding);
const auto bom=format.bom?signature(format.encoding):std::string_view{};
PendingSave pending;
File output;
pending.path=createTemporary(path.parent_path(),output,FILE_ATTRIBUTE_NORMAL);
write(output.handle,bom);
write(output.handle,bytes);
if(!FlushFileBuffers(output.handle)) fail("Flush saved file");
CloseHandle(output.release());
File replacement{trackReplacement(pending.path)};
if(!MoveFileExW(pending.path.c_str(),path.c_str(),MOVEFILE_WRITE_THROUGH)) fail("Create new file");
pending.path.clear();
path_=std::move(path);
encoding_=format.encoding;
bom_=bom.size();
size_=bom_+bytes.size();
changes_.clear();
if(spool_!=INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_,INVALID_HANDLE_VALUE));
spoolSize_=0;
source_=ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
return source_!=INVALID_HANDLE_VALUE;
}
}
+14 -4
View File
@@ -9,13 +9,24 @@
namespace ks::files
{
enum class TextEncoding { automatic, utf8, utf16le, utf16be, windows1252 };
enum class TextLineEnding { preserve, crlf, lf, cr };
struct TextSaveFormat
{
TextEncoding encoding=TextEncoding::utf8;
bool bom{};
TextLineEnding lineEnding=TextLineEnding::preserve;
};
class TextDocument
{
public:
static constexpr uint64_t pageBytes = 1024 * 1024;
static constexpr size_t editLimit = 8 * pageBytes;
explicit TextDocument(std::filesystem::path path, bool editable = true);
explicit TextDocument(std::filesystem::path path, bool editable = true,
TextEncoding encoding=TextEncoding::automatic);
~TextDocument();
TextDocument(const TextDocument &) = delete;
TextDocument &operator=(const TextDocument &) = delete;
@@ -29,10 +40,10 @@ public:
bool modified() const { return !changes_.empty(); }
bool modifiedWith(uint64_t page, std::string_view current) const;
bool save();
bool saveNew(std::filesystem::path path, TextSaveFormat format);
const wchar_t *encodingName() const;
private:
enum class Encoding { utf8, utf16le, utf16be };
struct Change { uint64_t offset; size_t size; };
std::filesystem::path path_;
@@ -40,13 +51,12 @@ private:
HANDLE spool_ = INVALID_HANDLE_VALUE;
uint64_t size_{}, spoolSize_{};
size_t bom_{};
Encoding encoding_ = Encoding::utf8;
TextEncoding encoding_ = TextEncoding::utf8;
bool editable_;
std::map<uint64_t, Change> changes_;
std::string decode(std::string bytes) const;
uint64_t boundary(uint64_t page,HANDLE source) const;
std::string readOriginal(uint64_t page) const;
std::string encode(std::string_view utf8) const;
};
}
+113 -30
View File
@@ -729,13 +729,18 @@ class TextWindow
{
public:
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const lan::FilesPeer *peer,
std::string_view fragment)
std::string_view fragment,TextOpenOptions options)
: original(std::move(path)), peerId(peer?peer->id:""), filename(original.filename().wstring()),
edit(editable), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
edit(editable), draft(options.draft), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()),
search{dialogs}, previewFragment(fragment)
{
if (peer) remote=std::make_unique<RemoteTextFile>(RemoteTextFile{*peer,original});
else document=std::make_unique<TextDocument>(original,edit);
else document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
if(options.encoding!=TextEncoding::automatic)
{
newFormat.encoding=options.encoding;
newFormat.bom=options.encoding==TextEncoding::utf16le || options.encoding==TextEncoding::utf16be;
}
for (int index = 0; index < GetLexerCount(); ++index)
{
char name[128]{};
@@ -764,6 +769,9 @@ private:
std::unique_ptr<TextDocument> document;
std::wstring filename;
bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{};
bool draft{};
TextSaveFormat newFormat;
std::filesystem::path pendingSavePath;
HICON smallIcon{},largeIcon{};
TextPreferences prefs;
TextWindowFont filesFont;
@@ -856,6 +864,9 @@ private:
bool dirty() const { return stagedDirty || (!busy() && uploadPending) || currentChanged(); }
bool busy() const { return saving.valid(); }
void invalidate() const { InvalidateRect(window, nullptr, FALSE); }
RECT statusBounds() const;
void invalidateStatus() const;
void invalidateHints() const;
void initializeDocument();
void finishOpen();
@@ -1342,22 +1353,25 @@ void TextWindow::finishOpen()
void TextWindow::saveFile(bool closeWhenDone)
{
if (busy() || !edit) return;
auto destination=original;
if(draft && !search.style.saveOptions(window,destination,newFormat)) return;
stagePage();
if (!stagedDirty && !uploadPending)
if (!draft && !stagedDirty && !uploadPending)
{
if (closeWhenDone) DestroyWindow(window);
else if (std::exchange(switchAfterSave, false)) changeMode();
return;
}
pendingCaret = send(SCI_GETCURRENTPOS);
if(draft) pendingSavePath=destination;
closeAfterSave = closeWhenDone;
if (!SetTimer(window, saveTimer, 75, nullptr)) throw std::runtime_error("Cannot start the save timer.");
send(SCI_SETREADONLY, TRUE);
try
{
saving=std::async(std::launch::async,[this]
saving=std::async(std::launch::async,[this,destination=std::move(destination)]
{
const auto reopened=document->save();
const auto reopened=draft?document->saveNew(destination,newFormat):document->save();
if(remote)
{
uploadPending=true;
@@ -1384,6 +1398,14 @@ void TextWindow::finishSave()
const auto change = std::exchange(switchAfterSave, false);
const auto reopened = saving.get();
stagedDirty = false;
const bool created=std::exchange(draft,false);
if(created)
{
original=std::move(pendingSavePath);
filename=original.filename().wstring();
navigationHistory.clear();
updateTitle();
}
if (!reopened)
{
search.style.message(window, L"The file was saved. Reopen it to continue editing.");
@@ -1392,6 +1414,12 @@ void TextWindow::finishSave()
}
if (closeAfterSave) { DestroyWindow(window); return; }
if (change) { changeMode(); return; }
if(created)
{
initializeDocument();
send(SCI_GOTOPOS,std::min<LRESULT>(pendingCaret,send(SCI_GETLENGTH)));
return;
}
if (pageTotal == 1 && document->pages() == 1)
{
fileSize = document->size();
@@ -1408,7 +1436,7 @@ void TextWindow::requestClose()
if (busy()) return;
if (needsSave())
{
const auto answer = search.style.confirmSave(window);
const auto answer = search.style.confirmSave(window,draft);
if (answer == IDCANCEL) return;
if (answer == IDYES) { saveFile(true); return; }
if (answer != IDNO) return;
@@ -1424,9 +1452,10 @@ bool TextWindow::needsSave() const
void TextWindow::toggleMode()
{
if (busy() || navigation.valid()) return;
if(draft) return;
if (edit && needsSave())
{
const auto answer = search.style.confirmSave(window);
const auto answer = search.style.confirmSave(window,false);
if (answer == IDYES)
{
switchAfterSave = true;
@@ -1861,6 +1890,58 @@ void TextWindow::layout()
invalidate();
}
RECT TextWindow::statusBounds() const
{
RECT bounds{};
GetClientRect(window,&bounds);
bounds.top=chromeHeight();
bounds.bottom=2*bounds.top;
return bounds;
}
void TextWindow::invalidateStatus() const
{
const auto bounds=statusBounds();
InvalidateRect(window,&bounds,FALSE);
}
void TextWindow::invalidateHints() const
{
RECT bounds{};
GetClientRect(window,&bounds);
bounds.top=std::max(0L,bounds.bottom-chromeHeight());
InvalidateRect(window,&bounds,FALSE);
}
void drawEditorStatus(HDC dc,RECT bounds,HFONT font,COLORREF background,COLORREF foreground,
int inset,const std::wstring &status)
{
const auto width=bounds.right-bounds.left,height=bounds.bottom-bounds.top;
if(width<=0 || height<=0) return;
const auto memory=CreateCompatibleDC(dc);
const auto bitmap=memory?CreateCompatibleBitmap(dc,width,height):nullptr;
const auto target=bitmap?memory:dc;
const auto oldBitmap=bitmap?SelectObject(memory,bitmap):nullptr;
const auto oldFont=SelectObject(target,font);
auto row=bitmap?RECT{0,0,width,height}:bounds;
SetDCBrushColor(target,background);
FillRect(target,&row,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
SetBkMode(target,TRANSPARENT);
SetTextColor(target,foreground);
row.left+=inset;
row.right-=inset;
if(row.left<row.right)
DrawTextW(target,status.c_str(),-1,&row,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX);
SelectObject(target,oldFont);
if(bitmap)
{
BitBlt(dc,bounds.left,bounds.top,width,height,memory,0,0,SRCCOPY);
SelectObject(memory,oldBitmap);
DeleteObject(bitmap);
}
if(memory) DeleteDC(memory);
}
void TextWindow::paint()
{
PAINTSTRUCT paint{};
@@ -1870,12 +1951,12 @@ void TextWindow::paint()
const auto row = chromeHeight();
const auto brush = static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
SetDCBrushColor(dc, color(TextColor::background));
FillRect(dc, &client, brush);
const RECT body{0,2*row,client.right,std::max<LONG>(2*row,client.bottom-row)};
FillRect(dc, &body, brush);
SetDCBrushColor(dc, color(TextColor::chromebg));
RECT menuBar{0, 0, client.right, row};
RECT top{0, row, client.right, 2 * row};
const RECT top=statusBounds();
RECT bottom{0, client.bottom - row, client.right, client.bottom};
FillRect(dc, &top, brush);
FillRect(dc, &bottom, brush);
FillRect(dc, &menuBar, brush);
const auto chromeFont = createChromeFont();
@@ -1904,27 +1985,27 @@ void TextWindow::paint()
}
SetTextColor(dc, color(TextColor::chrome));
bottom.left += scale(7);
const auto position = send(SCI_GETCURRENTPOS);
const auto line = send(SCI_LINEFROMPOSITION, position) + 1;
const auto column = send(SCI_GETCOLUMN, position) + 1;
const auto displayLanguage = textLanguageLabel(language);
auto status = filename + (edit ? L" (Edit)" : L" (View)") + (dirty() ? L" *" : L"") +
L" │ " + (document?document->encodingName():L"Loading…") + L" │ " + displayLanguage +
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";
RECT statusPaint{};
if(IntersectRect(&statusPaint,&top,&paint.rcPaint))
{
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"")+
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";
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" :
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" :
previewWanted ? L"Rendering Markdown… Ctrl+W Close" :
L"F3 Find next F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close";
constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX;
top.left += scale(12);
top.right -= scale(12);
if (top.left < top.right)
DrawTextW(dc, status.c_str(), -1, &top, format | DT_RIGHT);
DrawTextW(dc, hints, -1, &bottom, format);
SelectObject(dc, previous);
DeleteObject(chromeFont);
@@ -2044,6 +2125,7 @@ void TextWindow::notify(const SCNotification &notice)
case SCN_MODIFIED:
if (notice.modificationType & SC_MOD_INSERTCHECK)
{
const auto hadWarning=insertRejected;
if (send(SCI_GETLENGTH) + notice.length > static_cast<LRESULT>(TextDocument::editLimit))
{
send(SCI_CHANGEINSERTION, 0, reinterpret_cast<LPARAM>(""));
@@ -2051,6 +2133,7 @@ void TextWindow::notify(const SCNotification &notice)
MessageBeep(MB_ICONWARNING);
}
else insertRejected = false;
if(hadWarning!=insertRejected) invalidateHints();
}
if (notice.modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
{
@@ -2058,8 +2141,8 @@ void TextWindow::notify(const SCNotification &notice)
undoBytes += static_cast<size_t>(notice.length) + 64;
if (undoBytes >= 32 * TextDocument::pageBytes)
PostMessageW(window, trimUndo, 0, 0);
invalidateStatus();
}
invalidate();
break;
case SCN_CHARADDED:
if (edit && prefs.autoIndent && (notice.ch == '\n' || (notice.ch == '\r' && send(SCI_GETEOLMODE) == SC_EOL_CR)))
@@ -2079,7 +2162,7 @@ void TextWindow::notify(const SCNotification &notice)
case SCN_UPDATEUI:
case SCN_SAVEPOINTREACHED:
case SCN_SAVEPOINTLEFT:
invalidate();
invalidateStatus();
break;
}
}
@@ -2458,7 +2541,7 @@ HWND findOpenDocument(const std::filesystem::path &path,const lan::FilesPeer *pe
}
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow)
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow,TextOpenOptions options)
{
try
{
@@ -2490,7 +2573,7 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
return Scintilla_RegisterClasses(instance) && RegisterClassW(&type);
}();
if(!registered) throw std::runtime_error("Cannot register the text window.");
auto state=std::make_shared<TextWindow>(original,edit,dialogs,peer,fragment);
auto state=std::make_shared<TextWindow>(original,edit,dialogs,peer,fragment,options);
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
(peer?peer->name+L" · ":std::wstring{})+path.wstring();
RECT bounds{};
+11 -2
View File
@@ -4,6 +4,7 @@
#include <filesystem>
#include <string_view>
#include <vector>
#include "files_text_document.h"
namespace ks::lan { struct FilesPeer; }
@@ -37,7 +38,7 @@ void installFarHistoryKey(HWND field,int arrowId);
struct TextDialogs
{
INT_PTR (*confirmSave)(HWND);
INT_PTR (*confirmSave)(HWND,bool draft);
INT_PTR (*paint)(HWND, UINT, WPARAM, LPARAM, const wchar_t *);
INT_PTR (*paintSearch)(HWND, UINT, WPARAM, LPARAM);
void (*prepare)(HWND);
@@ -49,10 +50,18 @@ struct TextDialogs
void (*finish)(HWND,INT_PTR);
bool (*dismissOwned)(HWND);
bool (*confirmExisting)(HWND);
bool (*saveOptions)(HWND,std::filesystem::path &,TextSaveFormat &);
};
struct TextOpenOptions
{
TextEncoding encoding=TextEncoding::automatic;
bool draft{};
};
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);
const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false,
TextOpenOptions options={});
void textWindowOwnerClosed();
bool cycleTextWindows(HWND current,bool reverse);
}
+1 -1
View File
@@ -2,7 +2,7 @@
#include "platform.h"
namespace ks
{
inline constexpr wchar_t AppVersion[] = L"0.6.112";
inline constexpr wchar_t AppVersion[] = L"0.6.115";
inline constexpr UINT UpdateMessage = WM_APP + 7;
inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000;
inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000;
+93 -15
View File
@@ -27,6 +27,22 @@ public static class FilesActivationUi {
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr window);
[DllImport("user32.dll")] static extern int ReleaseDC(IntPtr window, IntPtr dc);
[DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y);
[DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr window, out Rect rect);
[DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
public static uint ReadScreenCenter(IntPtr window) {
var previous = SetThreadDpiAwarenessContext(new IntPtr(-4));
try {
Rect bounds;
if (!GetWindowRect(window, out bounds)) throw new InvalidOperationException("Missing terminal output.");
var dc = GetDC(IntPtr.Zero);
if (dc == IntPtr.Zero) throw new InvalidOperationException("Could not read the screen.");
try { return GetPixel(dc, (bounds.Left + bounds.Right) / 2, (bounds.Top + bounds.Bottom) / 2); }
finally { ReleaseDC(IntPtr.Zero, dc); }
} finally {
if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous);
}
}
public static bool HasWarningBackground(IntPtr window) {
var dc = GetDC(window);
@@ -35,6 +51,7 @@ public static class FilesActivationUi {
finally { ReleaseDC(window, dc); }
}
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] public static extern uint GetClipboardSequenceNumber();
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window);
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr window, uint msg, IntPtr w, IntPtr l);
@@ -86,6 +103,19 @@ function Wait-Until([string]$Description, [scriptblock]$Condition) {
throw "Timed out waiting for $Description"
}
function Invoke-ClipboardOperation([scriptblock]$Operation) {
for ($attempt = 1; $attempt -le 3; $attempt++) {
try { return (& $Operation) }
catch {
# CLIPBRD_E_CANT_OPEN means another process is using the shared clipboard.
if ($_.Exception.GetBaseException().HResult -ne 0x800401D0 -or
$attempt -eq 3) { throw }
[Windows.Forms.Application]::DoEvents()
Start-Sleep -Milliseconds 25
}
}
}
function Find-OperationDialog($Owner, [int]$Control) {
$candidate = [IntPtr]::Zero
while ($true) {
@@ -214,6 +244,18 @@ try {
$profile.SetValue('StatusFields', 3)
if($TerminalOnly){
$terminalPage = Join-Path $app 'terminal/index.html'
$page = Get-Content -Raw -LiteralPath $terminalPage
$page = $page.Replace('<style>','<style media="not all">').Replace('src="terminal.js"','src="startup-fixture.js"')
[IO.File]::WriteAllText($terminalPage,$page)
[IO.File]::WriteAllText((Join-Path $app 'terminal/startup-fixture.js'), @'
function startTerminalFixture() {
document.querySelector('style').media = 'all';
const script = document.createElement('script');
script.src = 'terminal.js';
document.body.append(script);
}
'@)
$listener=[Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
$listener.Start()
$port=$listener.LocalEndpoint.Port
@@ -271,11 +313,41 @@ try {
Wait-Until 'plain Enter invoking the default Windows file association' {
(Test-Path -LiteralPath "$document.opened") -and [IO.File]::ReadAllText("$document.opened") -eq 'opened'
}
$command="start '$($document.Replace("'","''"))'"
Wait-Until 'the system open action in terminal output and command history' {
$history=$profile.GetValue('CommandHistory')
[FilesActivationUi]::IsWindowVisible($output) -and $history -and
([Text.Encoding]::Unicode.GetString($history).Split([char]0) -ccontains $command) -and
(Select-String -LiteralPath $trace -SimpleMatch "start '$($document.Substring(0,12))" -Quiet)
}
Write-Output 'Verified Shift+Enter opens folders in Explorer. Both Enter and Shift+Enter invoke the default file action.'
Remove-Item -LiteralPath "$document.opened"
}
if($SystemOpenOnly -or $TerminalOnly){
$keys = New-Object -ComObject WScript.Shell
if ($TerminalOnly) {
Wait-Until 'Files active for the terminal startup check' {
[FilesActivationUi]::Activate($window) -and [FilesActivationUi]::Focus($window) -eq $inputBox
}
$keys.SendKeys('^o')
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-startup-pause'
if ($LASTEXITCODE) { throw 'Could not pause terminal page initialization.' }
foreach ($frame in 1..10) {
if ([FilesActivationUi]::GetForegroundWindow() -ne $window -or
![FilesActivationUi]::IsWindowVisible($output)) { throw 'The terminal must be visible for the startup check.' }
$pixel = [FilesActivationUi]::ReadScreenCenter($output)
if ($pixel -ne 0x181818) { throw ('Unexpected terminal startup background 0x{0:X6}.' -f $pixel) }
Start-Sleep -Milliseconds 30
}
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-startup-resume'
if ($LASTEXITCODE) { throw 'Could not resume terminal page initialization.' }
Wait-Until 'the terminal rendering after startup' {
Select-String -LiteralPath $trace -SimpleMatch ' web-anchor ' -Quiet -ErrorAction SilentlyContinue
}
$keys.SendKeys('^o')
Wait-Until 'file panes restored after the startup check' { [FilesActivationUi]::IsWindowVisible($left) }
Write-Output 'Verified the dark terminal background before WebView initialization completes.'
}
foreach($case in @(
@{Name='enter-panes'; Keys='{ENTER}'},
@{Name='shift-enter-panes'; Keys='+{ENTER}'},
@@ -334,21 +406,21 @@ try {
Send-InteractiveTerminal "Write-Output '$outputSelection'"
Wait-Until 'output selection fixture command submitted' { !(Read-Text $inputBox) }
Add-Type -AssemblyName System.Windows.Forms
$savedClipboard = [Windows.Forms.Clipboard]::GetDataObject()
$savedClipboard = Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetDataObject() }
try {
$nativeDraft = "Get-Item -LiteralPath '$leftDir'"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$nativeDraft)
[void][FilesActivationUi]::Send($inputBox,0xB1,[IntPtr]0,[IntPtr]4)
$keys.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the full command line with a partial selection' {
[Windows.Forms.Clipboard]::GetText() -ceq $nativeDraft
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $nativeDraft
}
$webviewDraft = "Get-Item -LiteralPath '$rightDir'"
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,$webviewDraft)
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-copy'
if($LASTEXITCODE){throw 'Could not send Ctrl+Insert through the terminal WebView.'}
Wait-Until 'Ctrl+Insert copying the command line with focus in the terminal WebView' {
[Windows.Forms.Clipboard]::GetText() -ceq $webviewDraft
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $webviewDraft
}
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'terminal-select-output'
if($LASTEXITCODE){throw 'Could not select the terminal output fixture.'}
@@ -356,22 +428,26 @@ try {
[FilesActivationUi]::Focus($window) -eq $inputBox
}
foreach($key in '^c','^{INSERT}') {
[Windows.Forms.Clipboard]::SetText($webviewDraft)
# Require a new clipboard write without making the test process the clipboard owner.
$beforeCopy = [FilesActivationUi]::GetClipboardSequenceNumber()
$keys.SendKeys($key)
Wait-Until "$key copying only the selected terminal output with a command present" {
[Windows.Forms.Clipboard]::GetText() -ceq $outputSelection
[FilesActivationUi]::GetClipboardSequenceNumber() -ne $beforeCopy -and
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $outputSelection
}
if ((Read-Text $inputBox) -cne $webviewDraft) { throw 'Copying output changed the command line.' }
}
[void][FilesActivationUi]::Write($inputBox,0x0C,[IntPtr]::Zero,'')
$keys.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the selected folder name when the command line is empty' {
[Windows.Forms.Clipboard]::GetText() -ceq 'Test folder'
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq 'Test folder'
}
} finally {
if ([Windows.Forms.Clipboard]::GetText() -cin @($nativeDraft,$webviewDraft,$outputSelection,'Test folder')) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
Invoke-ClipboardOperation {
if ([Windows.Forms.Clipboard]::GetText() -cin @($nativeDraft,$webviewDraft,$outputSelection,'Test folder')) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
}
}
}
Write-Output 'Verified Ctrl+C and Ctrl+Insert copy the selected output, then fall back to the command line or panel.'
@@ -477,7 +553,7 @@ try {
Write-Output 'Both panels refreshed external creation, modification and deletion while preserving focus.'
Add-Type -AssemblyName System.Windows.Forms
$savedClipboard=[Windows.Forms.Clipboard]::GetDataObject()
$savedClipboard=Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetDataObject() }
$programName=[IO.Path]::GetFileName($program)
$expectedNames="Test folder`r`n$programName"
try {
@@ -490,18 +566,20 @@ try {
}
$shell.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying marked names in panel order' {
[Windows.Forms.Clipboard]::GetText() -ceq $expectedNames
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $expectedNames
}
Select-Row $right $fileName
$shell.SendKeys('^{INSERT}')
Wait-Until 'Ctrl+Insert copying the current item in the other pane' {
[Windows.Forms.Clipboard]::GetText() -ceq $fileName
(Invoke-ClipboardOperation { [Windows.Forms.Clipboard]::GetText() }) -ceq $fileName
}
Write-Output 'Ctrl+Insert copied marked names in order and used the cursor in the other pane.'
} finally {
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
Invoke-ClipboardOperation {
if ([Windows.Forms.Clipboard]::GetText() -cin @($expectedNames,$fileName)) {
if ($savedClipboard) { [Windows.Forms.Clipboard]::SetDataObject($savedClipboard,$true) }
else { [Windows.Forms.Clipboard]::Clear() }
}
}
}
+5 -2
View File
@@ -3,7 +3,7 @@ import { writeFile } from 'node:fs/promises';
import { setTimeout as delay } from 'node:timers/promises';
const [port, scenario, artifact, title] = process.argv.slice(2);
const terminalScenario = ['terminal-enter', 'terminal-copy', 'terminal-select-output'].includes(scenario);
const terminalScenario = scenario.startsWith('terminal-');
let socket;
const pending = new Map();
let sequence = 0;
@@ -69,7 +69,10 @@ await new Promise((resolve, reject) => {
});
try {
if (scenario === 'terminal-select-output') {
if (scenario === 'terminal-startup-pause' || scenario === 'terminal-startup-resume') {
await waitFor(() => evaluate('typeof startTerminalFixture === "function"'), 'the delayed terminal page');
if (scenario === 'terminal-startup-resume') await evaluate('startTerminalFixture()');
} else if (scenario === 'terminal-select-output') {
const selection = await waitFor(() => evaluate(`(() => {
const marker = 'terminal-output-copy-fixture';
const buffer = terminal.buffer.active;
+1 -1
View File
@@ -57,7 +57,7 @@ int WINAPI wWinMain(HINSTANCE instance,HINSTANCE,PWSTR,int)
return font;
};
dialogs.confirmExisting=[](HWND){return true;};
dialogs.confirmSave=[](HWND)->INT_PTR {return IDYES;};
dialogs.confirmSave=[](HWND,bool)->INT_PTR {return IDYES;};
dialogs.message=[](HWND,const wchar_t *message){log(message);};
dialogs.dismissOwned=[](HWND){return false;};
files::openTextWindow(owner,document,false,dialogs,&peer);
+110 -10
View File
@@ -1,4 +1,4 @@
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly)
param([Parameter(Mandatory)][string]$Executable,[switch]$KeyboardCursorOnly,[switch]$CreateFileOnly)
$ErrorActionPreference='Stop'
Add-Type -AssemblyName System.Drawing
Add-Type @"
@@ -19,6 +19,21 @@ public static class SearchArrowTest {
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hwnd, IntPtr after, int x, int y, int w, int h, uint flags);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hwnd, IntPtr dc, uint flags);
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")] static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);
[DllImport("user32.dll")] public static extern bool InvalidateRect(IntPtr hwnd, IntPtr rect, bool erase);
[DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y);
[DllImport("gdi32.dll")] static extern bool SetPixelV(IntPtr dc, int x, int y, uint color);
public static bool EditorMenuProbe(IntPtr window, bool write) {
const uint color = 0x00ff00ff;
var dc = GetDC(window);
if (dc == IntPtr.Zero) throw new InvalidOperationException("Cannot sample the editor.");
try {
if (write && !SetPixelV(dc, 4, 4, color))
throw new InvalidOperationException("Cannot mark the editor menu.");
return GetPixel(dc, 4, 4) == color;
} finally { ReleaseDC(window, dc); }
}
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hwnd, out Rect rect);
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hwnd);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hwnd);
@@ -242,7 +257,7 @@ foreach($name in 'A.txt','B.txt','C.txt','D.txt'){
$copy=Join-Path $scratch 'KSwitcher.Files.search-arrow-test.exe'
Copy-Item -LiteralPath $Executable -Destination $copy
$profile=[Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
$keysToRestore='LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement'
$keysToRestore='LeftPath','RightPath','LeftCursor','RightCursor','WindowPlacement','FileStyles'
$saved=@{}
foreach($name in $keysToRestore){
if($name -in $profile.GetValueNames()){
@@ -256,6 +271,8 @@ try {
$profile.SetValue('RightPath',$rightFixture)
$profile.DeleteValue('LeftCursor',$false)
$profile.DeleteValue('RightCursor',$false)
$styles='[{"extension":".txt","background":3158064,"states":[{},{},{"background":3166352}]}]'
$profile.SetValue('FileStyles',[Text.Encoding]::UTF8.GetBytes($styles),'Binary')
$process=Start-Process -FilePath $copy -ArgumentList '--terminal-trace' -PassThru -WindowStyle Normal
$paintTrace=Join-Path ([IO.Path]::GetTempPath()) "KSwitcher.Files.terminal-trace-$($process.Id).log"
$previousDpi=[SearchArrowTest]::SetThreadDpiAwarenessContext([IntPtr](-4))
@@ -267,6 +284,73 @@ try {
[SearchArrowTest]::SendText($leftPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0 -and
[SearchArrowTest]::SendText($rightPanel,0x1A2,-1,'A.txt').ToInt64() -ge 0
})
if ($CreateFileOnly) {
function Assert-DialogSurface($Dialog, [int]$Red, [int]$Green) {
$bounds=Read-Bounds $Dialog
$bitmap=[Drawing.Bitmap]::new(1,1)
try {
$graphics=[Drawing.Graphics]::FromImage($bitmap)
try {
[void](Wait-Until {
$graphics.CopyFromScreen(($bounds.Left+4),($bounds.Top+4),0,0,$bitmap.Size)
$pixel=$bitmap.GetPixel(0,0)
$pixel.R -eq $Red -and $pixel.G -eq $Green -and $pixel.B -eq $Green
})
} finally { $graphics.Dispose() }
} finally { $bitmap.Dispose() }
}
$keyboard=New-Object -ComObject WScript.Shell
[void](Wait-Until { $keyboard.AppActivate($process.Id) })
$keyboard.SendKeys('+{F4}')
$open=Wait-Until { Find-Window '#32770' $process.Id 461 }
Assert-DialogSurface $open 192 192
Post $open 0x111 1
$editor=Wait-Until { Find-Window 'KSwitcher.Files.Text' $process.Id }
$title=[Text.StringBuilder]::new(1024)
[void][SearchArrowTest]::GetText($editor,0xD,$title.Capacity,$title)
if ($title.ToString() -notmatch '(New_File_[0-9-]+_[0-9.]+\.txt)$') { throw "Missing generated name in $title." }
$generated=$Matches[1]
if (Test-Path -LiteralPath (Join-Path $scratch $generated)) { throw 'Opening a draft created a file.' }
$control=Wait-Until { [SearchArrowTest]::FindWindowEx($editor,0,'Scintilla',[NullString]::Value) }
Start-Sleep -Milliseconds 150
if (![SearchArrowTest]::EditorMenuProbe($editor,$true)) { throw 'Cannot mark the editor menu for the repaint check.' }
foreach($ch in 'First'.ToCharArray()){Post $control 0x102 ([int]$ch)}
Post $control 0x100 13
foreach($ch in 'Second'.ToCharArray()){Post $control 0x102 ([int]$ch)}
[void](Wait-Until { [SearchArrowTest]::Send($control,2159,0,0).ToInt64() })
Start-Sleep -Milliseconds 150
$menuWasPreserved=[SearchArrowTest]::EditorMenuProbe($editor,$false)
[void][SearchArrowTest]::InvalidateRect($editor,0,$false)
if (!$menuWasPreserved) { throw 'Typing in a draft repainted the unchanged editor menu.' }
foreach($cancel in $true,$false) {
Post $control 0x100 27
$confirm=Wait-Until { Find-Window '#32770' $process.Id 6 }
Assert-DialogSurface $confirm 128 0
Post $confirm 0x111 6
$save=Wait-Until { Find-Window '#32770' $process.Id 464 }
Assert-DialogSurface $save 192 192
$name=[SearchArrowTest]::GetDlgItem($save,461)
$current=[Text.StringBuilder]::new(1024)
[void][SearchArrowTest]::GetText($name,0xD,$current.Capacity,$current)
if ($current.ToString() -ne $generated) { throw 'Save options did not carry the generated name.' }
if ($cancel) {
Post $save 0x111 2
[void](Wait-Until { ![SearchArrowTest]::IsWindow($save) -and [SearchArrowTest]::IsWindow($editor) })
continue
}
[void][SearchArrowTest]::SendText($name,0x0C,0,'created.txt')
[void][SearchArrowTest]::Send([SearchArrowTest]::GetDlgItem($save,464),0xF1,1,0)
[void][SearchArrowTest]::Send([SearchArrowTest]::GetDlgItem($save,472),0xF5,0,0)
Post $save 0x111 1
}
$result=Join-Path $scratch 'created.txt'
[void](Wait-Until { (Test-Path -LiteralPath $result) -and ![SearchArrowTest]::IsWindow($editor) })
if ([Convert]::ToHexString([IO.File]::ReadAllBytes($result)) -ne 'EFBBBF46697273740A5365636F6E64') {
throw 'The saved bytes must contain a UTF-8 BOM and LF line endings.'
}
Write-Output 'Verified Shift+F4, the generated name, Escape confirmation, cancellation, and Save options.'
return
}
if (!$KeyboardCursorOnly) {
$leftPath = [SearchArrowTest]::GetDlgItem($main,142)
foreach ($step in @(@{ Row='[Right fixture]'; Path=$rightFixture }, @{ Row='..'; Path=$scratch })) {
@@ -290,12 +374,27 @@ try {
Write-Output 'Verified folder navigation repaints only the panel that changes directories.'
}
$clicks=if(!$KeyboardCursorOnly){
@(@{Panel=$leftPanel; Index=0},@{Panel=$rightPanel; Index=1},@{Panel=$rightPanel; Index=1})
@(@{Panel=$leftPanel; Index=0},
@{Panel=$rightPanel; Index=1; Label='A.txt'},
@{Panel=$leftPanel; Index=0; Label='A.txt'},
@{Panel=$rightPanel; Index=1; Label='..'; UnfocusedStyle=$true},
@{Panel=$rightPanel; Index=1; Label='A.txt'})
}
$activeIndex=0
foreach($check in $clicks) {
$before=[SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32()
$top=[SearchArrowTest]::Send($check.Panel,0x18E,0,0).ToInt32()
$row=if($before -eq $top){$top+1}else{$top}
$row=if($check.Label){[SearchArrowTest]::SendText($check.Panel,0x1A2,-1,$check.Label).ToInt32()}
elseif($before -eq $top){$top+1}else{$top}
if($row -lt 0 -or $row -eq $before){throw 'The click fixture must move the cursor.'}
$previousKey="$($check.Index)/$before"
$expected=@{"$($check.Index)/$row"='1'}
if($check.Index -ne $activeIndex){
$source=if($activeIndex -eq 0){$leftPanel}else{$rightPanel}
$sourceRow=[SearchArrowTest]::Send($source,0x188,0,0).ToInt32()
$expected["$activeIndex/$sourceRow"]='0'
}
if($check.Index -eq $activeIndex -or $check.UnfocusedStyle){$expected[$previousKey]='0'}
[void](Wait-Until { Test-Path -LiteralPath $paintTrace })
Start-Sleep -Milliseconds 150
$lineCount=@(Get-Content -LiteralPath $paintTrace).Count
@@ -303,14 +402,15 @@ try {
[void](Wait-Until { [SearchArrowTest]::Send($check.Panel,0x188,0,0).ToInt32() -eq $row })
Start-Sleep -Milliseconds 150
$highlight=Read-PanelHighlights $paintTrace $lineCount
$draws=@($highlight.Keys)
if("$($check.Index)/$row" -notin $draws -or $draws.Count -gt 3){
throw "Clicking a row repainted unrelated file rows. Drawn rows: $draws"
if($highlight.Count -ne $expected.Count -or
@($expected.Keys | Where-Object {$highlight[$_] -ne $expected[$_]}).Count){
throw "Unexpected cursor redraw. Expected rows: $($expected.Keys -join ', '). Drawn rows: $($highlight.Keys -join ', ')."
}
if($highlight["$($check.Index)/$row"] -ne '1' -or
($before -ge $top -and $highlight["$($check.Index)/$before"] -ne '0')){
throw 'The new row must be painted active and the previous visible row must lose its highlight.'
if($check.Index -ne $activeIndex -and (Get-Content -LiteralPath $paintTrace | Select-Object -Skip $lineCount |
Where-Object {$_ -match "^\d+ panel-draw $($check.Index) $before 1 "})){
throw 'The old row in the destination panel flashed as the active cursor.'
}
$activeIndex=$check.Index
}
if($clicks){Write-Output 'Verified file clicks repaint only cursor rows in the active pane and when changing panes.'}
Post $main 0x111 132
+40
View File
@@ -8,6 +8,8 @@
namespace fs = std::filesystem;
using ks::files::TextDocument;
using ks::files::TextEncoding;
using ks::files::TextLineEnding;
namespace
{
@@ -141,6 +143,43 @@ void sparseFile(const fs::path &file)
document.stage(index, "edited");
check(document.readPage(index) == "edited", "Stage an edit past 4 GiB");
}
void saveDraft(const fs::path &file)
{
TextDocument draft({});
check(draft.readPage(0).empty() && draft.pages()==1, "Start with an empty draft");
draft.stage(0,"one\r\ntwo\rthree\n");
writeFile(file,"existing");
bool rejected{};
try {draft.saveNew(file,{});}
catch(const std::exception &) {rejected=true;}
check(rejected && draft.modified() && readFile(file)=="existing", "Preserve a conflicting file and the draft");
fs::remove(file);
check(draft.saveNew(file,{TextEncoding::utf8,true,TextLineEnding::lf}), "Save a draft as a new file");
check(readFile(file)=="\xef\xbb\xbfone\ntwo\nthree\n" && draft.readPage(0)=="one\ntwo\nthree\n",
"Save a UTF-8 signature and normalize mixed line endings");
draft.stage(0,"after");
check(draft.save() && readFile(file)=="\xef\xbb\xbf" "after", "Edit normally after the first save");
const auto ansiFile=file.parent_path()/L"windows1252.txt";
TextDocument ansiDraft({});
ansiDraft.stage(0,"caf\xc3\xa9\n");
check(ansiDraft.saveNew(ansiFile,{TextEncoding::windows1252,false,TextLineEnding::crlf}),
"Save a draft in Windows-1252");
check(readFile(ansiFile)=="caf\xe9\r\n" && ansiDraft.readPage(0)=="caf\xc3\xa9\r\n",
"Round-trip Windows-1252 text and CRLF");
TextDocument ansiReader(ansiFile,false,TextEncoding::windows1252);
check(ansiReader.readPage(0)=="caf\xc3\xa9\r\n", "Open an existing file with an explicit code page");
const auto unicodeFile=file.parent_path()/L"utf16be.txt";
TextDocument unicodeDraft({});
unicodeDraft.stage(0,"a\n");
check(unicodeDraft.saveNew(unicodeFile,{TextEncoding::utf16be,true,TextLineEnding::cr}),
"Save a UTF-16 draft with a signature");
TextDocument unicodeReader(unicodeFile,false);
check(readFile(unicodeFile)==std::string("\xfe\xff\0a\0\r",6) && unicodeReader.readPage(0)=="a\r",
"Detect the UTF-16 signature and read CR line endings");
}
}
int main()
@@ -151,6 +190,7 @@ int main()
editsAcrossPages(fixture.directory / L"pages.txt");
unicodeBoundaries(fixture.directory / L"unicode.txt");
rejectExternalReplacement(fixture.directory / L"external.txt");
saveDraft(fixture.directory / L"created.txt");
sparseFile(fixture.directory / L"5gib.log");
std::cout << "Files text document regressions passed.\n";
}