Files
hrynco-kswitcher/src/files_text_window.cpp
T
2026-11-25 23:29:30 +02:00

3809 lines
146 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "files_text_window.h"
#include "files_help.h"
#include "files_image_view.h"
#include "files_text_preferences.h"
#include "files_menu_paint.h"
#include "files_menu_navigation.h"
#include "files_scrollbar.h"
#include "files_history_date.h"
#include "files_text_document.h"
#include "files_text_language.h"
#include "files_terminal_view.h"
#include "platform.h"
#include "lan_files.h"
#include "../resources/resource.h"
#include <commctrl.h>
#include <shellapi.h>
#include <shlobj.h>
#include <atomic>
#include <windowsx.h>
#include <commdlg.h>
#include <wincrypt.h>
#include <Scintilla.h>
#include <ILexer.h>
#include <Lexilla.h>
#include "../vendor/json.hpp"
#include <algorithm>
#include <array>
#include <cerrno>
#include <chrono>
#include <cstring>
#include <cwchar>
#include <cwctype>
#include <deque>
#include <future>
#include <fstream>
#include <thread>
#include <map>
#include <stdexcept>
#include <string_view>
#include <utility>
#include <vector>
namespace ks::files
{
namespace
{
constexpr const char *profileNames[]{"viewer", "editor"};
void readTextProfile(TextPreferences &prefs, const nlohmann::json &data)
{
prefs.wrap = data.value("wrap", prefs.wrap);
prefs.numbers = data.value("lineNumbers", prefs.numbers);
prefs.whitespace = data.value("whitespace", prefs.whitespace);
prefs.tabsAsSpaces = data.value("tabsAsSpaces", prefs.tabsAsSpaces);
prefs.autoIndent = data.value("autoIndent", prefs.autoIndent);
prefs.caretLine = data.value("caretLine", prefs.caretLine);
prefs.tabWidth = std::clamp(data.value("tabWidth", prefs.tabWidth), 1, 16);
prefs.lineEnding = std::clamp(data.value("lineEnding", prefs.lineEnding), 0, 3);
const auto theme = std::clamp(data.value("theme", 0), 0, static_cast<int>(std::size(textPalettes)) - 1);
prefs.scheme = wide(data.value("scheme", utf8(textPaletteNames[theme]))).substr(0, maxTextPaletteName);
prefs.colors = textPalettes[theme];
if (data.contains("colors"))
{
const auto documentColors = data.at("colors").get<std::array<COLORREF, documentColorCount>>();
std::copy(documentColors.begin(), documentColors.end(), prefs.colors.begin());
}
if (data.contains("menuColors"))
{
const auto menuColors = data.at("menuColors").get<std::array<COLORREF, TextPalette{}.size() - documentColorCount>>();
std::copy(menuColors.begin(), menuColors.end(), prefs.colors.begin() + documentColorCount);
}
for (auto &color : prefs.colors) color &= 0xffffff;
}
}
std::optional<TextPalette> namedTextPalette(const TextSettings &settings,std::wstring_view name)
{
const auto matches=[&](const wchar_t *other)
{
return !name.empty() && CompareStringOrdinal(name.data(),static_cast<int>(name.size()),other,-1,TRUE)==CSTR_EQUAL;
};
for(size_t i=0;i<std::size(textPalettes);++i)
if(matches(textPaletteNames[i])) return textPalettes[i];
for(const auto &scheme:settings.schemes)
if(matches(scheme.name.c_str())) return scheme.colors;
return {};
}
TextPreferences resolvedTextProfile(const TextSettings &settings,bool editor)
{
auto profile=settings.profiles[editor];
if(profile.scheme==systemTextScheme)
{
const bool dark=windowsUsesDarkApps();
profile.colors=namedTextPalette(settings,settings.systemThemes[dark]).value_or(textPalettes[dark?1:2]);
}
return profile;
}
TextSettings loadTextPreferences()
{
TextSettings settings{};
auto &profiles = settings.profiles;
try
{
const auto folder = dataDirectory();
const auto combined = folder / L"files-text.json";
if (std::filesystem::exists(combined))
{
const auto data = nlohmann::json::parse(readFile(combined, 64 * 1024));
for (size_t i = 0; i < profiles.size(); ++i)
if (data.contains(profileNames[i])) readTextProfile(profiles[i], data.at(profileNames[i]));
if (const auto markdown=data.find("markdown");markdown!=data.end() && markdown->is_object())
{
if (const auto width=markdown->find("width");width!=markdown->end() && width->is_number_unsigned() && *width<=999999)
settings.markdown.width=width->get<unsigned>();
if (const auto size=markdown->find("fontSize");size!=markdown->end() && size->is_number_unsigned() && *size>=8 && *size<=72)
settings.markdown.fontSize=size->get<unsigned>();
if (const auto family=markdown->find("font");family!=markdown->end() && family->is_string())
settings.markdown.font=wide(family->get<std::string>()).substr(0,LF_FACESIZE-1);
}
if (data.contains("schemes") && data.at("schemes").is_array())
for (const auto &entry : data.at("schemes"))
{
if (settings.schemes.size() >= maxTextPalettes) break;
try
{
auto name = wide(entry.at("name").get<std::string>());
if (name.empty() || name.size() > maxTextPaletteName) continue;
auto colors = entry.at("colors").get<TextPalette>();
for (auto &color : colors) color &= 0xffffff;
settings.schemes.push_back({std::move(name), colors});
}
catch (const std::exception &) {}
}
if(const auto system=data.find("systemThemes");system!=data.end() && system->is_object())
{
constexpr const char *roles[]{"light","dark"};
for(size_t i=0;i<settings.systemThemes.size();++i)
if(const auto name=system->find(roles[i]);name!=system->end() && name->is_string())
{
auto value=wide(name->get<std::string>());
if(value.size()<=maxTextPaletteName && namedTextPalette(settings,value))
settings.systemThemes[i]=std::move(value);
}
}
return settings;
}
const wchar_t *legacy[]{L"files-viewer.json", L"files-editor.json"};
for (size_t i = 0; i < profiles.size(); ++i)
{
try { readTextProfile(profiles[i], nlohmann::json::parse(readFile(folder / legacy[i], 16 * 1024))); }
catch (const std::exception &) {}
}
}
catch (const std::exception &) {}
return settings;
}
void saveTextPreferences(const TextSettings &settings)
{
nlohmann::json data;
for (size_t i = 0; i < settings.profiles.size(); ++i)
{
const auto &p = settings.profiles[i];
data[profileNames[i]] = {{"wrap", p.wrap}, {"lineNumbers", p.numbers}, {"whitespace", p.whitespace},
{"tabsAsSpaces", p.tabsAsSpaces}, {"autoIndent", p.autoIndent}, {"caretLine", p.caretLine},
{"tabWidth", p.tabWidth}, {"lineEnding", p.lineEnding}, {"scheme", utf8(p.scheme)},
{"theme", p.scheme == textPaletteNames[1] ? 1 : p.scheme == textPaletteNames[2] ? 2 : 0},
{"colors", std::vector<COLORREF>(p.colors.begin(), p.colors.begin() + documentColorCount)},
{"menuColors", std::vector<COLORREF>(p.colors.begin() + documentColorCount, p.colors.end())}};
}
auto &schemes = data["schemes"] = nlohmann::json::array();
for (const auto &scheme : settings.schemes)
schemes.push_back({{"name", utf8(scheme.name)}, {"colors", scheme.colors}});
data["markdown"]={{"width",settings.markdown.width},{"fontSize",settings.markdown.fontSize},
{"font",utf8(settings.markdown.font)}};
data["systemThemes"]={{"light",utf8(settings.systemThemes[0])},{"dark",utf8(settings.systemThemes[1])}};
const auto json = data.dump(2);
atomicWrite(dataDirectory() / L"files-text.json", Bytes(json.begin(), json.end()));
}
namespace
{
constexpr wchar_t windowClass[] = L"KSwitcher.Files.Text";
const UINT preferencesChanged = RegisterWindowMessageW(L"KSwitcher.Files.PreferencesChanged");
static_assert(std::size(textColorNames) == static_cast<size_t>(TextColor::count));
static_assert(TextPalette{}.size() == std::size(textColorNames));
struct MenuLabel
{
std::wstring title, shortcut;
size_t access = std::wstring::npos;
explicit MenuLabel(std::wstring_view source)
{
const auto tab = source.find(L'\t');
if (tab != source.npos) shortcut = source.substr(tab + 1);
source = source.substr(0, tab);
for (size_t i = 0; i < source.size(); ++i)
{
if (source[i] == L'&' && i + 1 < source.size())
{
if (source[i + 1] == L'&') ++i;
else { access = title.size(); continue; }
}
title += source[i];
}
}
bool matches(wchar_t key) const
{
return access < title.size() && std::towupper(title[access]) == std::towupper(key);
}
};
COLORREF tintText(COLORREF ink, COLORREF background, int opacity)
{
const auto blend = [opacity](int foreground, int behind) {
return (foreground * opacity + behind * (100 - opacity)) / 100;
};
return RGB(blend(GetRValue(ink), GetRValue(background)),
blend(GetGValue(ink), GetGValue(background)), blend(GetBValue(ink), GetBValue(background)));
}
void drawMenuTitle(HDC dc, RECT bounds, const MenuLabel &label, COLORREF accessInk, bool enabled)
{
DrawTextW(dc, label.title.c_str(), -1, &bounds, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX);
if (!enabled || label.access >= label.title.size()) return;
TEXTMETRICW metrics{};
GetTextMetricsW(dc, &metrics);
const POINT origin{bounds.left, bounds.top + (bounds.bottom - bounds.top - metrics.tmHeight) / 2};
paintMenuAccessKey(dc, bounds, origin, label.title, label.access, accessInk);
}
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, switchHex, addBookmark, currentBookmarks, allBookmarks,
lexerStart = 1000,
};
struct PagePrompt
{
TextDialogs style;
uint64_t page{}, pages{};
};
void initializePrompt(TextDialogs style, HWND dialog)
{
style.prepare(dialog);
SendMessageW(dialog, DM_SETDEFID, IDOK, 0);
SetFocus(GetDlgItem(dialog, 100));
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)
{
auto *prompt = reinterpret_cast<PagePrompt *>(lparam);
SetWindowLongPtrW(dialog, DWLP_USER, lparam);
const auto title = L"&Page number (1–" + std::to_wstring(prompt->pages) + L")";
SetDlgItemTextW(dialog, 101, title.c_str());
SetDlgItemTextW(dialog, 100, std::to_wstring(prompt->page + 1).c_str());
initializePrompt(prompt->style, dialog);
return FALSE;
}
auto *prompt = reinterpret_cast<PagePrompt *>(GetWindowLongPtrW(dialog, DWLP_USER));
if (!prompt) return FALSE;
if (const auto painted = prompt->style.paint(dialog, message, wparam, lparam, L" Go to page "))
return painted;
if (message != WM_COMMAND) return FALSE;
if (LOWORD(wparam) == IDCANCEL) { prompt->style.finish(dialog, IDCANCEL); return TRUE; }
if (LOWORD(wparam) != IDOK) return FALSE;
wchar_t buffer[32]{};
const int length = GetDlgItemTextW(dialog, 100, buffer, static_cast<int>(std::size(buffer)));
wchar_t *end{};
const auto page = std::wcstoull(buffer, &end, 10);
if (!length || *end || !page || page > prompt->pages)
{
MessageBeep(MB_ICONWARNING);
return TRUE;
}
prompt->page = page - 1;
prompt->style.finish(dialog, IDOK);
return TRUE;
}
constexpr size_t searchHistoryLimit = 100;
constexpr int searchQueryLimit = 511;
std::vector<FarHistoryEntry> readFarHistory(FarHistoryKind kind)
{
std::vector<FarHistoryEntry> entries;
try
{
const auto json = nlohmann::json::parse(readFile(dataDirectory() / (kind==FarHistoryKind::search?L"files-search-history.json":L"files-folder-history.json"), 512 * 1024));
if (!json.is_array()) return entries;
for (const auto &item : json)
{
if (entries.size() == searchHistoryLimit) break;
if (!item.is_object() || !item.contains("date") || !item["date"].is_string() ||
!item.contains("text") || !item["text"].is_string()) continue;
auto date = wide(item["date"].get<std::string>());
auto text = wide(item["text"].get<std::string>());
if (date.size() == 10 && !text.empty() && text.size() <= searchQueryLimit)
entries.push_back({std::move(date), std::move(text)});
}
}
catch (const std::exception &) {}
return entries;
}
void writeFarHistory(FarHistoryKind kind,std::wstring_view text)
{
const auto mutex = CreateMutexW(nullptr, FALSE, kind==FarHistoryKind::search?L"Local\\KSwitcher.Files.SearchHistoryWrite":L"Local\\KSwitcher.Files.FolderHistoryWrite");
if (!mutex) return;
const auto lock = WaitForSingleObject(mutex, 100);
if (lock == WAIT_OBJECT_0 || lock == WAIT_ABANDONED)
{
try
{
auto entries = readFarHistory(kind);
std::erase_if(entries, [text](const auto &entry) { return entry.text == text; });
auto json = nlohmann::json::array();
json.push_back({{"date", utf8(historyDate())}, {"text", utf8(std::wstring(text))}});
for (size_t index = 0; index < entries.size() && index + 1 < searchHistoryLimit; ++index)
json.push_back({{"date", utf8(entries[index].date)}, {"text", utf8(entries[index].text)}});
const auto contents = json.dump();
atomicWrite(dataDirectory() / (kind==FarHistoryKind::search?L"files-search-history.json":L"files-folder-history.json"), Bytes(contents.begin(), contents.end()));
}
catch (const std::exception &) {}
ReleaseMutex(mutex);
}
CloseHandle(mutex);
}
struct FindPrompt
{
TextDialogs style;
std::wstring text;
std::wstring word, selection;
DWORD flags = FR_DOWN;
std::vector<FarHistoryEntry> history;
FarDropDownPalette historyPalette{};
};
struct FarPopup
{
struct Row { std::wstring_view text; int index; };
std::vector<Row> rows;
FarDropDownPalette palette;
HFONT font{};
int rowHeight{},inset{},visible{},top{},current{},result=-1;
int dragOffset=-1;
bool done{};
int rowTop() const { return inset+1+rowHeight/2; }
int bottomMargin() const { return inset+1+rowHeight/4; }
ScrollPosition scrollPosition() const {return {static_cast<int>(rows.size()),visible,top};}
RECT scrollTrack(HWND window,RECT bounds) const
{
const LONG right=bounds.right-inset-1;
return {std::max(bounds.left,right-scrollBarWidth(window)),rowTop(),right,rowTop()+visible*rowHeight};
}
void select(int row)
{
if(row<0 || row>=static_cast<int>(rows.size()) || rows[row].index<0) return;
current=row;
top=std::clamp(top,current-visible+1,current);
}
void step(int direction,int count=1)
{
auto row=current;
while(count>0)
{
row+=direction;
if(row<0 || row>=static_cast<int>(rows.size())) break;
if(rows[row].index<0) continue;
select(row);
--count;
}
}
void stepMenu(int direction)
{
select(adjacentMenuRow(current,static_cast<int>(rows.size()),direction,
[this](int candidate){return rows[candidate].index>=0;}));
}
void accept()
{
result=rows[current].index;
done=true;
}
void paint(HWND window,HDC dc) const
{
RECT bounds{};
GetClientRect(window,&bounds);
const auto brush=static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
SetDCBrushColor(dc,palette.surface);
FillRect(dc,&bounds,brush);
RECT frame=bounds;
InflateRect(&frame,-inset,-inset);
frame.bottom-=rowHeight/4;
SetDCBrushColor(dc,palette.text);
FrameRect(dc,&frame,brush);
SetBkMode(dc,TRANSPARENT);
SetTextColor(dc,palette.text);
SelectObject(dc,font);
const LONG rowLeft=frame.left+inset;
const auto position=scrollPosition();
const auto track=scrollTrack(window,bounds);
const LONG rowRight=position.last()?track.left:frame.right-1;
LONG y=rowTop();
for(int offset=0;offset<visible;++offset,y+=rowHeight)
{
const auto row=top+offset;
const auto &entry=rows[row];
RECT box{rowLeft,y,rowRight,y+rowHeight};
if(row==current)
{
SetDCBrushColor(dc,palette.selection);
FillRect(dc,&box,brush);
}
if(entry.index<0)
{
SIZE text{};
GetTextExtentPoint32W(dc,entry.text.data(),static_cast<int>(entry.text.size()),&text);
const auto mid=(box.left+box.right)/2;
const auto center=y+rowHeight/2;
const auto gap=text.cx/2+inset*2;
RECT left{frame.left+1,center,mid-gap,center+1};
RECT right{mid+gap,center,rowRight,center+1};
SetDCBrushColor(dc,palette.text);
if(left.right>left.left) FillRect(dc,&left,brush);
if(right.right>right.left) FillRect(dc,&right,brush);
}
else box.left+=rowHeight;
DrawTextW(dc,entry.text.data(),static_cast<int>(entry.text.size()),&box,
DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_END_ELLIPSIS|(entry.index<0?DT_CENTER:DT_LEFT));
}
if(position.last()) paintScrollBar(dc,track,position,palette.surface);
}
};
LRESULT CALLBACK farPopupWindow(HWND window,UINT message,WPARAM wp,LPARAM lp)
{
if(message==WM_NCCREATE)
SetWindowLongPtrW(window,GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(reinterpret_cast<CREATESTRUCTW *>(lp)->lpCreateParams));
auto *state=reinterpret_cast<FarPopup *>(GetWindowLongPtrW(window,GWLP_USERDATA));
if(!state) return DefWindowProcW(window,message,wp,lp);
switch(message)
{
case WM_ERASEBKGND: return 1;
case WM_PAINT:
{
PAINTSTRUCT paint{};
const auto dc=BeginPaint(window,&paint);
const auto saved=SaveDC(dc);
state->paint(window,dc);
RestoreDC(dc,saved);
EndPaint(window,&paint);
return 0;
}
case WM_PRINT:
case WM_PRINTCLIENT:
{
const auto dc=reinterpret_cast<HDC>(wp);
const auto saved=SaveDC(dc);
state->paint(window,dc);
RestoreDC(dc,saved);
return 0;
}
case WM_CLOSE: state->done=true; return 0;
case WM_CAPTURECHANGED: state->done=true; return 0;
case WM_NCDESTROY:
state->done=true;
SetWindowLongPtrW(window,GWLP_USERDATA,0);
break;
case WM_KEYDOWN:
switch(wp)
{
case VK_ESCAPE: state->done=true; break;
case VK_RETURN: state->accept(); break;
case VK_UP: state->stepMenu(-1); break;
case VK_DOWN: state->stepMenu(1); break;
case VK_PRIOR: state->step(-1,state->visible); break;
case VK_NEXT: state->step(1,state->visible); break;
case VK_HOME: state->step(-1,static_cast<int>(state->rows.size())); break;
case VK_END: state->step(1,static_cast<int>(state->rows.size())); break;
}
InvalidateRect(window,nullptr,FALSE);
return 0;
case WM_MOUSEWHEEL:
{
const int direction=GET_WHEEL_DELTA_WPARAM(wp)>0?-1:1;
state->top=std::clamp(state->top+3*direction,0,static_cast<int>(state->rows.size())-state->visible);
InvalidateRect(window,nullptr,FALSE);
return 0;
}
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_MOUSEMOVE:
{
RECT bounds{};
GetClientRect(window,&bounds);
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
const auto position=state->scrollPosition();
const auto track=state->scrollTrack(window,bounds);
if(state->dragOffset>=0)
{
if(message==WM_MOUSEMOVE) state->top=position.drag(track,point.y,state->dragOffset);
if(message==WM_LBUTTONUP) state->dragOffset=-1;
InvalidateRect(window,nullptr,FALSE);
return 0;
}
if(!PtInRect(&bounds,point))
{
if(message==WM_LBUTTONDOWN) state->done=true;
return 0;
}
const auto offset=(point.y-state->rowTop())/state->rowHeight;
const bool scroll=position.last() && PtInRect(&track,point);
if(scroll && message==WM_LBUTTONDOWN)
{
const auto thumb=position.thumb(track);
if(PtInRect(&thumb,point)) state->dragOffset=point.y-thumb.top;
else state->top=position.click(track,point.y);
}
if(!scroll && point.y>=state->rowTop() && offset<state->visible)
{
const auto row=state->top+offset;
if(state->rows[row].index>=0)
{
state->select(row);
if(message==WM_LBUTTONUP) state->accept();
}
}
InvalidateRect(window,nullptr,FALSE);
return 0;
}
}
return DefWindowProcW(window,message,wp,lp);
}
void showHistoryPopup(HWND dialog,int fieldId,const std::vector<FarHistoryEntry> &history,
FarDropDownPalette palette)
{
const auto field=GetDlgItem(dialog,fieldId);
const auto selected=chooseFarDropDown(field,history,0,palette);
if(selected>=0)
{
SetWindowTextW(field,history[selected].text.c_str());
SendMessageW(field,EM_SETSEL,0,-1);
}
}
LRESULT CALLBACK searchFieldKeys(HWND field,UINT message,WPARAM key,LPARAM flags,UINT_PTR,DWORD_PTR arrow)
{
if(message==WM_SYSKEYDOWN && key==VK_DOWN && (flags&(1LL<<29)))
{
PostMessageW(GetParent(field),WM_COMMAND,arrow,0);
return 0;
}
return DefSubclassProc(field,message,key,flags);
}
INT_PTR CALLBACK searchDialog(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam)
{
if (message == WM_INITDIALOG)
{
auto *prompt = reinterpret_cast<FindPrompt *>(lparam);
SetWindowLongPtrW(dialog, DWLP_USER, lparam);
SetDlgItemTextW(dialog, 100, prompt->text.c_str());
SendDlgItemMessageW(dialog, 100, EM_SETLIMITTEXT, searchQueryLimit, 0);
installFarHistoryKey(GetDlgItem(dialog,100),searchHistoryButton);
EnableWindow(GetDlgItem(dialog, searchHistoryButton), !prompt->history.empty());
CheckDlgButton(dialog, 101, prompt->flags & FR_MATCHCASE ? BST_CHECKED : BST_UNCHECKED);
CheckDlgButton(dialog, 102, prompt->flags & FR_WHOLEWORD ? BST_CHECKED : BST_UNCHECKED);
EnableWindow(GetDlgItem(dialog, 106), !prompt->word.empty());
EnableWindow(GetDlgItem(dialog, 107), !prompt->selection.empty());
initializePrompt(prompt->style, dialog);
return FALSE;
}
auto *prompt = reinterpret_cast<FindPrompt *>(GetWindowLongPtrW(dialog, DWLP_USER));
if (!prompt) return FALSE;
if (const auto painted = prompt->style.paintSearch(dialog, message, wparam, lparam))
return painted;
if (message != WM_COMMAND) return FALSE;
const auto command = LOWORD(wparam);
if (command == searchHistoryButton) { showHistoryPopup(dialog,100,prompt->history,prompt->historyPalette); return TRUE; }
if (command == IDCANCEL) { prompt->style.finish(dialog, IDCANCEL); return TRUE; }
if (command == 106 || command == 107)
{
const auto &value = command == 106 ? prompt->word : prompt->selection;
if (value.empty()) return TRUE;
SetDlgItemTextW(dialog, 100, value.c_str());
SetFocus(GetDlgItem(dialog, 100));
SendDlgItemMessageW(dialog, 100, EM_SETSEL, 0, -1);
return TRUE;
}
if (command != IDOK && command != 103) return FALSE;
wchar_t buffer[searchQueryLimit + 1]{};
if (!GetDlgItemTextW(dialog, 100, buffer, static_cast<int>(std::size(buffer)))) return TRUE;
prompt->text = buffer;
writeFarHistory(FarHistoryKind::search,prompt->text);
prompt->flags = (IsDlgButtonChecked(dialog, 101) == BST_CHECKED ? FR_MATCHCASE : 0) |
(IsDlgButtonChecked(dialog, 102) == BST_CHECKED ? FR_WHOLEWORD : 0) |
(command == IDOK ? FR_DOWN : 0);
prompt->style.finish(dialog, IDOK);
return TRUE;
}
RemoteTextSource lanTextSource(const lan::FilesPeer &peer)
{
return {peer.id,peer.name,
[peer](const std::filesystem::path &original,const std::filesystem::path &cache,
bool edit,const RemoteTextSource::Progress &progress,uint64_t sizeLimit)
{
lan::FilesConnection source(&peer),target;
const auto info=source.call(lan::fileRequest("stat",original));
lan::checkFileReply(info);
const bool canCommit=info.value("editCommit",false);
const bool readOnly=info.at("attributes").get<DWORD>()&FILE_ATTRIBUTE_READONLY;
if(edit && !canCommit)
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::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);
}
catch(...)
{
target.call({{"action","abort"}});
throw;
}
return revision;
},
[peer](const std::filesystem::path &original,const std::filesystem::path &cache,
const RemoteTextRevision &revision)
{
lan::FilesConnection source,target(&peer);
const auto info=source.call(lan::fileRequest("stat",cache));
lan::checkFileReply(info);
const RemoteTextRevision local{info.at("size"),info.at("modified"),revision.editable};
const lan::FileRevision expected{revision.size,revision.modified};
try { lan::streamFile(source,target,"Files editor",cache,original,local.size,local.modified,true,false,{},&expected); }
catch(const std::system_error &error)
{
if(error.code().value()==ERROR_FILE_INVALID)
throw std::runtime_error("The remote file changed since it was opened. Your edits are still in the editor.");
throw;
}
return local;
}};
}
struct RemoteTextFile
{
RemoteTextSource source;
std::filesystem::path original,cache;
RemoteTextRevision revision{};
RemoteTextFile(const RemoteTextSource &backend,const std::filesystem::path &path):source(backend),original(path) {}
~RemoteTextFile()
{
if(cache.empty()) return;
std::error_code ignored;
std::filesystem::remove(cache,ignored);
std::filesystem::remove(cache.parent_path(),ignored);
}
void download(bool edit,const RemoteTextSource::Progress &progress,uint64_t sizeLimit=UINT64_MAX,bool elevated=false)
{
if(cache.empty())
{
GUID id{};
wchar_t name[40]{};
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40))
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
const auto directory=std::filesystem::temp_directory_path()/(L"ks-files-edit-"+std::wstring(name));
if(!std::filesystem::create_directory(directory))
throw std::runtime_error("Cannot create a temporary directory for the remote file.");
cache=directory/L"content";
}
const auto &read=elevated?source.elevation->download:source.download;
revision=read(original,cache,edit,progress,sizeLimit);
}
void upload(const RemoteTextSource::Progress &cancel)
{
revision=cancel?source.elevation->upload(original,cache,revision,cancel):source.upload(original,cache,revision);
}
};
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;
}
unsigned textAreaScale(TextDialogs dialogs,AppearanceArea area)
{
return dialogs.readScale?dialogs.readScale(area):100;
}
TextWindowFont scaledDocumentFont(TextDialogs dialogs,bool editor)
{
auto font=dialogs.readFont();
font.tenthsOfPoint=scaledAppearanceSize(font.tenthsOfPoint,
textAreaScale(dialogs,editor?AppearanceArea::editor:AppearanceArea::viewer));
return font;
}
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)
{
return wide(std::string(peer))+L"\n"+path.native();
}
std::filesystem::path markdownTarget(const std::filesystem::path &document,std::string_view url)
{
url=url.substr(0,url.find_first_of("?#"));
std::string decoded;
const auto hex=[](char c) {
if(c>='0' && c<='9') return c-'0';
if(c>='a' && c<='f') return c-'a'+10;
if(c>='A' && c<='F') return c-'A'+10;
return -1;
};
for(size_t i=0;i<url.size();++i)
{
if(url[i]!='%') { decoded+=url[i]; continue; }
if(i+2>=url.size()) return {};
const auto high=hex(url[i+1]), low=hex(url[i+2]);
if(high<0 || low<0) return {};
decoded+=static_cast<char>(16*high+low);
i+=2;
}
if(decoded.empty() || decoded.find_first_of(":\0",0,2)!=decoded.npos) return {};
const std::filesystem::path relative(wide(decoded));
if(relative.has_root_path()) return {};
return (document.parent_path()/relative).lexically_normal();
}
std::string markdownImage(const std::filesystem::path &path,const RemoteTextSource *backend,
const std::shared_ptr<std::atomic<bool>> &cancel)
{
auto extension=path.extension().wstring();
std::transform(extension.begin(),extension.end(),extension.begin(),::towlower);
const std::map<std::wstring,std::string> types{
{L".png","png"},{L".jpg","jpeg"},{L".jpeg","jpeg"},{L".gif","gif"},
{L".webp","webp"},{L".bmp","bmp"},{L".svg","svg+xml"},{L".avif","avif"}
};
const auto type=types.find(extension);
if(type==types.end()) return {};
constexpr uint64_t limit=16*1024*1024;
auto source=path;
std::optional<RemoteTextFile> fetched;
if(backend)
{
if(*cancel) return {};
fetched.emplace(*backend,path);
fetched->download(false,[&](uint64_t,uint64_t){return !*cancel;},limit);
source=fetched->cache;
}
if(*cancel) return {};
std::ifstream input(source,std::ios::binary|std::ios::ate);
const auto size=input.tellg();
if(size<=0 || static_cast<uint64_t>(size)>limit) return {};
std::string bytes(static_cast<size_t>(size),'\0');
if(!input.seekg(0).read(bytes.data(),bytes.size())) return {};
constexpr auto flags=CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF;
DWORD length{};
const auto data=reinterpret_cast<const BYTE *>(bytes.data());
if(!CryptBinaryToStringA(data,static_cast<DWORD>(bytes.size()),flags,nullptr,&length)) return {};
std::string encoded(length,'\0');
if(!CryptBinaryToStringA(data,static_cast<DWORD>(bytes.size()),flags,encoded.data(),&length)) return {};
encoded.resize(length);
return "data:image/"+type->second+";base64,"+encoded;
}
class TextWindow
{
public:
TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const 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), hex(options.hex && !editable),
initialBookmark(options.line),
prefs(resolvedTextProfile(loadTextPreferences(),editable)), filesFont(scaledDocumentFont(dialogs,editable)),
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,
hex?TextEncoding::utf8:options.encoding,isLocalDocumentPath(original));
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]{};
GetLexerName(index, name, sizeof(name));
if (*name && std::string_view(name) != "null") lexers.emplace_back(name);
}
std::sort(lexers.begin(), lexers.end(), [](const auto &a, const auto &b) {
return _stricmp(a.c_str(), b.c_str()) < 0;
});
}
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);
}
HWND window{}, editor{}, quickModeButton{};
bool handleKey(const MSG &message);
void goToFragment(std::string_view fragment);
void previewFile(const std::filesystem::path &path);
void previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff);
bool openBookmark(const ViewerBookmark &bookmark);
nlohmann::json sessionState() const;
void restoreSession(const nlohmann::json &state);
AppearanceArea appearanceArea() const
{
return previewWanted?AppearanceArea::markdown:edit?AppearanceArea::editor:AppearanceArea::viewer;
}
std::filesystem::path original;
const std::string peerId;
private:
std::unique_ptr<RemoteTextFile> remote;
std::unique_ptr<TextDocument> document;
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{};
TextPreferences prefs;
TextWindowFont filesFont;
TextLanguage automatic, language;
std::vector<std::string> lexers;
FindPrompt search;
std::string cleanPage;
std::deque<MenuLabel> menuLabels;
std::vector<MenuLabel> menuBarLabels;
HBRUSH menuSurface{};
HMENU menuRoot{};
std::array<RECT, 5> menuBounds{};
int menuSelection = -1;
bool pendingPreferences{};
Scintilla::ILexer5 *lexer{}; // Scintilla owns the installed lexer.
uint64_t page{}, pageOffset{}, pageTotal{}, fileSize{};
intptr_t pendingCaret{};
int pageEol = SC_EOL_CRLF;
size_t undoBytes{};
bool uploadPending{};
FilesTerminalView preview;
bool previewWanted{}, previewVisible{}, previewRetried{};
ULONGLONG previewDeadline{};
ULONGLONG nextFileCheck{};
std::optional<LocalFileVersion> previewStamp, observedVersion;
bool diskChanged{};
struct MarkdownTask
{
uint64_t revision;
size_t line,column;
bool checked;
};
std::string previewText;
uint64_t previewRevision{};
int renderedScroll{};
std::optional<int> sessionScroll;
std::optional<MarkdownTask> pendingTask;
std::optional<size_t> taskOffset;
std::string previewFragment;
struct PreviewLocation
{
std::filesystem::path path;
std::string fragment;
int scroll{};
};
struct PreviewLink
{
PreviewLocation target;
int direction{}, scroll{};
bool newWindow{};
};
std::vector<PreviewLocation> navigationHistory;
size_t navigationIndex{};
std::optional<size_t> destinationIndex;
PreviewLocation destination;
std::future<std::unique_ptr<RemoteTextFile>> navigation;
std::shared_ptr<std::atomic<bool>> cancelNavigation;
bool restoreScroll{};
std::deque<PreviewLink> previewLinks;
struct ImageRequest
{
std::filesystem::path path;
uint64_t index{}, generation{};
};
std::deque<ImageRequest> imageQueue;
std::future<std::string> image;
ImageRequest activeImage;
std::shared_ptr<std::atomic<bool>> cancelImages;
std::atomic<bool> cancelOpen{},cancelElevatedSave{};
std::future<void> opening;
std::future<bool> saving;
bool elevatedOpen{},elevatedSave{};
static constexpr UINT_PTR saveTimer = 1;
static constexpr UINT_PTR openTimer = 2;
static constexpr UINT_PTR previewTimer = 3;
static constexpr UINT_PTR navigationTimer = 4;
static constexpr UINT_PTR quickViewTimer = 5;
static constexpr UINT_PTR bookmarkTimer = 6;
static constexpr UINT_PTR savedViewerTimer = 7;
static constexpr UINT_PTR externalChangeTimer = 8;
struct BookmarkLocation
{
std::filesystem::path path;
uint64_t line{};
bool adding{};
std::optional<TextLineLocation> position;
std::unique_ptr<TextDocument> source;
};
std::future<BookmarkLocation> bookmarkTask;
std::stop_source bookmarkStop;
enum class QuickKind { text, html, binary };
struct QuickDocument
{
std::unique_ptr<TextDocument> document;
std::string firstPage;
std::optional<std::string> previewCode;
QuickKind kind{};
size_t binaryBytes{};
};
std::future<QuickDocument> quickLoading;
std::filesystem::path quickPath;
std::wstring quickTextTitle;
bool quickTextVisible{},quickTextDiff{};
uint64_t quickRequest{}, quickReading{};
ULONGLONG quickReadyAt{};
std::wstring quickError;
std::optional<std::string> quickPreviewCode;
QuickKind quickKind{};
bool quickHtmlRendered{}, binaryRepresentations{};
size_t quickBinaryBytes{};
static constexpr int quickModeControl=159;
void applySourceLayoutOptions();
void toggleQuickHtml();
void pollQuickView();
static constexpr UINT trimUndo = WM_APP + 1;
static constexpr UINT previewFailed = WM_APP + 2;
static constexpr UINT openPreviewLink = WM_APP + 3;
static constexpr UINT previewRendered = WM_APP + 4;
static constexpr UINT cycleWindow = WM_APP + 5;
static constexpr UINT savePreviewTask = WM_APP + 6;
LRESULT send(UINT message, WPARAM wparam = 0, LPARAM lparam = 0) const
{
return SendMessageW(editor, message, wparam, lparam);
}
COLORREF color(TextColor role) const { return prefs.colors[static_cast<size_t>(role)]; }
int scale(int value) const { return MulDiv(value, GetDpiForWindow(window), 96); }
int chromeHeight() const { return scale(std::max(21, (filesFont.tenthsOfPoint + 9) / 10 + 12)); }
std::string_view pageText() const
{
const auto length = static_cast<size_t>(send(SCI_GETLENGTH));
return {reinterpret_cast<const char *>(send(SCI_GETCHARACTERPOINTER)), length};
}
bool currentChanged() const { return edit && !loading && send(SCI_GETMODIFY) && pageText() != cleanPage; }
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(std::optional<std::string> firstPage={});
void startRemoteOpen(bool elevated=false);
void finishOpen();
void createMenu();
void releaseMenu();
void reloadPreferences();
void styleMenu(HMENU menu);
void openMenu(int index);
bool measureMenu(MEASUREITEMSTRUCT &item);
bool drawMenu(const DRAWITEMSTRUCT &item);
LRESULT menuKey(HMENU menu, wchar_t key) const;
HFONT createChromeFont() const;
void updateMenus();
void applyPreferences();
void updateLineNumberMargin();
void applyLineEnding();
void installLexer();
void replaceEditorText(std::string_view data);
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,bool elevated=false);
void finishSave();
void requestClose();
void toggleMode();
void changeMode();
ViewerPosition currentPosition() const;
void restorePosition(const ViewerPosition &position);
void showTextMode(const ViewerPosition &position,std::string contents,bool takeFocus=true);
void suspendEditor(std::unique_ptr<RemoteTextFile> saved={});
void restoreEditor();
void finishSavedViewer();
void cancelSavedViewerLoad();
bool needsSave() const;
bool canPreview() const;
void updatePreview();
bool startPreviewBrowser();
void stopPreview(bool refresh=true,bool keepBrowser=false);
void renderPreview(bool keepPosition=false);
void applyMarkdownPreferences(const MarkdownPreferences &preferences);
std::optional<LocalFileVersion> previewFileStamp() const;
void rememberLocalVersion();
void pollExternalChanges();
void refreshPreview();
void startMarkdownTask();
void finishMarkdownTask();
void reportMarkdownTask(uint64_t revision,bool saved);
void cancelPreviewImages();
void previewMessage(const std::wstring &value);
void navigatePreview(PreviewLink request);
void finishNavigation();
void showLocation(std::unique_ptr<RemoteTextFile> fetched);
void syncNavigation();
void updateTitle();
void updateIcons(UINT dpi);
void updateTaskbarGroup(bool closing=false);
void pollImages();
void focusContent();
void layout();
void paint();
void command(UINT id);
void openFind();
void find(bool down, DWORD flags);
void notify(const SCNotification &notice);
};
void addItem(HMENU menu, UINT command, const wchar_t *text)
{
AppendMenuW(menu, MF_STRING, command, text);
}
HMENU addGroup(HMENU parent, const wchar_t *title)
{
const auto menu = CreatePopupMenu();
AppendMenuW(parent, MF_POPUP, reinterpret_cast<UINT_PTR>(menu), title);
return menu;
}
void TextWindow::createMenu()
{
const auto menu = CreateMenu();
const auto file = addGroup(menu, L"&File");
if (edit) addItem(file, save, L"&Save\tF2");
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)
{
addItem(actions, undo, L"&Undo\tCtrl+Z");
addItem(actions, redo, L"&Redo\tCtrl+Y");
AppendMenuW(actions, MF_SEPARATOR, 0, nullptr);
addItem(actions, cut, L"Cu&t\tCtrl+X");
addItem(actions, paste, L"&Paste\tCtrl+V");
}
addItem(actions, copy, L"&Copy\tCtrl+C");
addItem(actions, selectAll, L"Select &page\tCtrl+A");
const auto navigation = addGroup(menu, L"&Navigate");
if (!edit && !hex)
{
addItem(navigation, historyBack, L"&Back\tAlt+Left");
addItem(navigation, historyForward, L"F&orward\tAlt+Right");
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 = hex?nullptr:addGroup(menu, L"S&yntax");
if(syntax)
{
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)
{
auto name = wide(lexers[i]);
const auto letter = std::towlower(name.front());
while (groupIndex + 1 < std::size(groups) && letter > lastLetters[groupIndex])
{
++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(menu, options, L"&Options…");
menuRoot = menu;
menuSurface = CreateSolidBrush(color(TextColor::chromebg));
MENUINFO background{sizeof(background), MIM_BACKGROUND | MIM_APPLYTOSUBMENUS};
background.hbrBack = menuSurface;
SetMenuInfo(menu, &background);
for (int index = 0; index < GetMenuItemCount(menu); ++index)
{
wchar_t label[64]{};
GetMenuStringW(menu, index, label, static_cast<int>(std::size(label)), MF_BYPOSITION);
menuBarLabels.emplace_back(label);
if (const auto group = GetSubMenu(menu, index)) styleMenu(group);
}
}
void TextWindow::openMenu(int index)
{
if (GetMenuItemID(menuRoot, index) == options) { command(options); return; }
updateMenus();
menuSelection = index;
invalidate();
UpdateWindow(window);
POINT anchor{menuBounds[index].left, menuBounds[index].bottom};
ClientToScreen(window, &anchor);
const auto selected = TrackPopupMenu(GetSubMenu(menuRoot, index), TPM_RETURNCMD | TPM_RIGHTBUTTON,
anchor.x, anchor.y, 0, window, nullptr);
menuSelection = -1;
if (pendingPreferences) reloadPreferences();
invalidate();
if (selected) command(selected);
}
void TextWindow::styleMenu(HMENU menu)
{
for (int index = 0; index < GetMenuItemCount(menu); ++index)
{
wchar_t label[256]{};
MENUITEMINFOW entry{sizeof(entry), MIIM_FTYPE | MIIM_STRING | MIIM_SUBMENU};
entry.dwTypeData = label;
entry.cch = static_cast<UINT>(std::size(label));
if (!GetMenuItemInfoW(menu, index, TRUE, &entry)) continue;
auto &stored = menuLabels.emplace_back(label);
entry.fMask = MIIM_FTYPE | MIIM_DATA;
entry.fType |= MFT_OWNERDRAW;
entry.dwItemData = reinterpret_cast<ULONG_PTR>(&stored);
SetMenuItemInfoW(menu, index, TRUE, &entry);
if (entry.hSubMenu) styleMenu(entry.hSubMenu);
}
}
HFONT TextWindow::createChromeFont() const
{
auto font = filesFont.font;
font.lfHeight = -MulDiv(filesFont.tenthsOfPoint, GetDpiForWindow(window), 720);
font.lfWidth = 0;
return CreateFontIndirectW(&font);
}
bool TextWindow::measureMenu(MEASUREITEMSTRUCT &item)
{
if (item.CtlType != ODT_MENU || !item.itemData) return false;
const auto &label = *reinterpret_cast<const MenuLabel *>(item.itemData);
const auto dc = GetDC(window);
const auto font = createChromeFont();
const auto previous = SelectObject(dc, font);
SIZE title{}, shortcut{};
GetTextExtentPoint32W(dc, label.title.c_str(), static_cast<int>(label.title.size()), &title);
if (!label.shortcut.empty())
GetTextExtentPoint32W(dc, label.shortcut.c_str(), static_cast<int>(label.shortcut.size()), &shortcut);
SelectObject(dc, previous);
DeleteObject(font);
ReleaseDC(window, dc);
item.itemWidth = static_cast<UINT>(title.cx + shortcut.cx + scale(label.shortcut.empty() ? 32 : 56));
item.itemHeight = label.title.empty() ? scale(7) : chromeHeight();
return true;
}
bool TextWindow::drawMenu(const DRAWITEMSTRUCT &item)
{
if (item.CtlType != ODT_MENU || !item.itemData) return false;
const auto &label = *reinterpret_cast<const MenuLabel *>(item.itemData);
const bool selected = (item.itemState & (ODS_SELECTED | ODS_HOTLIGHT)) != 0;
const auto dc = item.hDC;
const auto saved = SaveDC(dc);
const auto font = createChromeFont();
SelectObject(dc, font);
SetBkMode(dc, TRANSPARENT);
const auto surface = static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
SetDCBrushColor(dc, color(selected ? TextColor::menuHighlight : TextColor::chromebg));
FillRect(dc, &item.rcItem, surface);
const auto ink = color(selected ? TextColor::menuHighlightText : TextColor::chrome);
const bool enabled = !(item.itemState & (ODS_DISABLED | ODS_GRAYED));
SetTextColor(dc, enabled ? ink : tintText(ink, color(TextColor::chromebg), 50));
auto rect = item.rcItem;
if (label.title.empty())
{
const auto y = (rect.top + rect.bottom) / 2;
RECT line{rect.left + scale(4), y, rect.right - scale(4), y + 1};
SetDCBrushColor(dc, ink);
FillRect(dc, &line, surface);
}
else
{
rect.left += scale(18);
rect.right -= scale(14);
if (item.itemState & ODS_CHECKED)
{
auto mark = item.rcItem;
mark.left += scale(4);
DrawTextW(dc, L"✓", 1, &mark, DT_SINGLELINE | DT_VCENTER);
}
drawMenuTitle(dc, rect, label, color(TextColor::menuAccessKey), enabled);
if (!label.shortcut.empty())
DrawTextW(dc, label.shortcut.c_str(), -1, &rect, DT_SINGLELINE | DT_VCENTER | DT_RIGHT | DT_NOPREFIX);
}
RestoreDC(dc, saved);
DeleteObject(font);
return true;
}
LRESULT TextWindow::menuKey(HMENU menu, wchar_t key) const
{
for (int index = 0; index < GetMenuItemCount(menu); ++index)
{
MENUITEMINFOW entry{sizeof(entry), MIIM_DATA | MIIM_STATE};
if (!GetMenuItemInfoW(menu, index, TRUE, &entry) || !entry.dwItemData ||
(entry.fState & (MFS_DISABLED | MFS_GRAYED))) continue;
const auto &label = *reinterpret_cast<const MenuLabel *>(entry.dwItemData);
if (label.matches(key))
return MAKELRESULT(index, MNC_EXECUTE);
}
return MAKELRESULT(0, MNC_IGNORE);
}
void TextWindow::updateMenus()
{
const auto menu = menuRoot;
const auto enable = [&](UINT command, bool enabled) {
EnableMenuItem(menu, command, MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED));
};
enable(save, edit && !busy() && dirty());
enable(undo, edit && !busy() && send(SCI_CANUNDO));
enable(redo, edit && !busy() && send(SCI_CANREDO));
for (const auto command : {previousPage, firstPage}) enable(command, !busy() && page > 0);
for (const auto command : {nextPage, lastPage}) enable(command, !busy() && page + 1 < pageTotal);
enable(goToPage, !busy() && pageTotal > 1);
enable(historyBack, !navigation.valid() && navigationIndex>0);
enable(historyForward, !navigation.valid() && navigationIndex+1<navigationHistory.size());
}
void TextWindow::installLexer()
{
lexer = hex?nullptr:createTextLexer(language);
send(SCI_SETILEXER, 0, reinterpret_cast<LPARAM>(lexer));
applyPreferences();
send(SCI_COLOURISE, 0, -1);
}
void TextWindow::releaseMenu()
{
if (menuRoot) DestroyMenu(std::exchange(menuRoot, nullptr));
if (menuSurface) DeleteObject(std::exchange(menuSurface, nullptr));
menuLabels.clear();
menuBarLabels.clear();
}
void TextWindow::reloadPreferences()
{
if (menuSelection >= 0)
{
pendingPreferences = true;
return;
}
pendingPreferences = false;
auto settings = loadTextPreferences();
applyMarkdownPreferences(settings.markdown);
auto profile=resolvedTextProfile(settings,edit);
const auto font=scaledDocumentFont(search.style,edit);
const bool fontChanged = font.tenthsOfPoint != filesFont.tenthsOfPoint ||
std::memcmp(&font.font, &filesFont.font, sizeof(LOGFONTW)) != 0;
if (!fontChanged && profile == prefs) return;
prefs = std::move(profile);
filesFont = font;
if (fontChanged && !embedded)
{
releaseMenu();
createMenu();
}
applyPreferences();
}
void TextWindow::applyPreferences()
{
if (menuSurface)
{
const auto previous = menuSurface;
menuSurface = CreateSolidBrush(color(TextColor::chromebg));
MENUINFO info{sizeof(info), MIM_BACKGROUND | MIM_APPLYTOSUBMENUS};
info.hbrBack = menuSurface;
SetMenuInfo(menuRoot, &info);
DeleteObject(previous);
}
const auto &font = filesFont.font;
const auto face = utf8(font.lfFaceName);
send(SCI_STYLESETFONT, STYLE_DEFAULT, reinterpret_cast<LPARAM>(face.c_str()));
send(SCI_STYLESETSIZEFRACTIONAL, STYLE_DEFAULT, filesFont.tenthsOfPoint * (SC_FONT_SIZE_MULTIPLIER / 10));
send(SCI_STYLESETWEIGHT, STYLE_DEFAULT, font.lfWeight ? font.lfWeight : FW_NORMAL);
send(SCI_STYLESETITALIC, STYLE_DEFAULT, font.lfItalic != 0);
send(SCI_STYLESETUNDERLINE, STYLE_DEFAULT, font.lfUnderline != 0);
send(SCI_STYLESETCHARACTERSET, STYLE_DEFAULT, font.lfCharSet);
const auto quality = font.lfQuality == CLEARTYPE_QUALITY || font.lfQuality == CLEARTYPE_NATURAL_QUALITY
? SC_EFF_QUALITY_LCD_OPTIMIZED : font.lfQuality == ANTIALIASED_QUALITY ? SC_EFF_QUALITY_ANTIALIASED
: font.lfQuality == NONANTIALIASED_QUALITY ? SC_EFF_QUALITY_NON_ANTIALIASED : SC_EFF_QUALITY_DEFAULT;
send(SCI_SETFONTQUALITY, quality);
send(SCI_STYLESETFORE, STYLE_DEFAULT, color(TextColor::text));
send(SCI_STYLESETBACK, STYLE_DEFAULT, color(TextColor::background));
send(SCI_STYLECLEARALL);
if (lexer)
{
for (int style = 0; style < 256; ++style)
{
const auto role = syntaxColor(*lexer, language.lexer, style);
send(SCI_STYLESETFORE, style, color(role));
if (role == TextColor::keyword) send(SCI_STYLESETBOLD, style, TRUE);
}
}
const auto gutter = color(TextColor::chromebg);
send(SCI_STYLESETFORE, STYLE_LINENUMBER, tintText(color(TextColor::chrome), gutter, 70));
send(SCI_STYLESETBACK, STYLE_LINENUMBER, gutter);
send(SCI_SETELEMENTCOLOUR, SC_ELEMENT_SELECTION_TEXT, RGB(255,255,255) | 0xff000000);
send(SCI_SETELEMENTCOLOUR, SC_ELEMENT_SELECTION_BACK, color(TextColor::selection) | 0xff000000);
send(SCI_SETCARETFORE, color(TextColor::text));
send(SCI_SETCARETLINEVISIBLE, prefs.caretLine);
send(SCI_SETCARETLINEBACK, color(TextColor::chrome));
send(SCI_SETCARETLINEBACKALPHA, 24);
send(SCI_SETTABWIDTH, prefs.tabWidth);
send(SCI_SETINDENT, prefs.tabWidth);
send(SCI_SETUSETABS, !prefs.tabsAsSpaces);
send(SCI_SETTABINDENTS, TRUE);
send(SCI_SETBACKSPACEUNINDENTS, TRUE);
applySourceLayoutOptions();
applyLineEnding();
updateLineNumberMargin();
layout();
invalidate();
}
void TextWindow::applySourceLayoutOptions()
{
const bool binary=embedded && quickKind==QuickKind::binary;
if(std::exchange(binaryRepresentations,binary)!=binary)
{
constexpr char digits[]="0123456789ABCDEF";
for(int byte=0;byte<256;++byte)
{
const auto marker=binarySymbolMarker(static_cast<unsigned char>(byte));
if(!marker) continue;
const auto key=utf8(std::wstring(1,marker));
const auto index=reinterpret_cast<WPARAM>(key.c_str());
if(binary)
{
const char value[]{'\\','x',digits[byte>>4],digits[byte&15],0};
send(SCI_SETREPRESENTATION,index,reinterpret_cast<LPARAM>(byte=='\\'?"\\\\":value));
send(SCI_SETREPRESENTATIONAPPEARANCE,index,SC_REPRESENTATION_PLAIN);
}
else send(SCI_CLEARREPRESENTATION,index);
}
}
send(SCI_SETWRAPMODE,binary?SC_WRAP_CHAR:!hex && prefs.wrap?SC_WRAP_WORD:SC_WRAP_NONE);
send(SCI_SETHSCROLLBAR,!binary);
send(SCI_SETVIEWWS,!binary && !hex && prefs.whitespace?SCWS_VISIBLEALWAYS:SCWS_INVISIBLE);
send(SCI_SETVIEWEOL,!binary && !hex && prefs.whitespace);
}
void TextWindow::updateLineNumberMargin()
{
LRESULT width{};
if (prefs.numbers && !hex && (!embedded || quickKind!=QuickKind::binary))
{
const auto digits = std::to_string(send(SCI_GETLINECOUNT)).size();
const std::string sample(digits, '9');
width = send(SCI_TEXTWIDTH, STYLE_LINENUMBER, reinterpret_cast<LPARAM>(sample.c_str())) + scale(7);
}
if (send(SCI_GETMARGINWIDTHN, 0) != width)
send(SCI_SETMARGINWIDTHN, 0, width);
const auto textInset = prefs.numbers ? scale(8) : 1;
if (send(SCI_GETMARGINLEFT) != textInset)
send(SCI_SETMARGINLEFT, 0, textInset);
}
void TextWindow::applyLineEnding()
{
const int choices[] = {pageEol, SC_EOL_CRLF, SC_EOL_LF, SC_EOL_CR};
send(SCI_SETEOLMODE, choices[prefs.lineEnding]);
}
void TextWindow::loadPage(uint64_t index,std::optional<std::string> cached)
{
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;
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 :
eol + 1 < data.size() && data[eol + 1] == '\n' ? SC_EOL_CRLF : SC_EOL_CR;
replaceEditorText(data);
cleanPage = std::move(data);
}
void TextWindow::replaceEditorText(std::string_view data)
{
loading = true;
send(SCI_SETREADONLY, FALSE);
send(SCI_SETUNDOCOLLECTION, FALSE);
send(SCI_CLEARALL);
send(SCI_ADDTEXT, data.size(), reinterpret_cast<LPARAM>(data.data()));
send(SCI_EMPTYUNDOBUFFER);
send(SCI_SETUNDOCOLLECTION, edit);
applyLineEnding();
send(SCI_SETSAVEPOINT);
send(SCI_SETREADONLY, !edit);
send(SCI_GOTOPOS, 0);
send(SCI_SETXOFFSET, 0);
send(SCI_SETFIRSTVISIBLELINE, 0);
loading = false;
updateLineNumberMargin();
undoBytes = 0;
insertRejected = false;
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;
auto text = std::string(pageText());
document->stage(page, text);
cleanPage = std::move(text);
stagedDirty = document->modified();
send(SCI_SETSAVEPOINT);
}
void TextWindow::go(uint64_t index)
{
if (index >= pageTotal || index == page) return;
stagePage();
loadPage(index);
}
void TextWindow::initializeDocument(std::optional<std::string> firstPage)
{
rememberLocalVersion();
if(hex)
{
releaseMenu();
createMenu();
installLexer();
loadPage(0);
updateTitle();
return;
}
if(!firstPage) firstPage=document->readPage(0);
automatic=embedded && quickKind==QuickKind::binary?TextLanguage{}:detectLanguage(original,*firstPage);
language=automatic;
if(embedded) applySourceLayoutOptions();
if(canPreview()) ShowWindow(editor,SW_HIDE);
if(!embedded)
{
releaseMenu();
createMenu();
if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment});
}
installLexer();
loadPage(0,std::move(firstPage));
updatePreview();
if(initialBookmark) locateBookmark(std::exchange(initialBookmark,0));
}
std::string readMarkdownDocument(TextDocument &document)
{
std::string text;
for(uint64_t index=0;index<document.pages();++index) text+=document.readPage(index);
return text;
}
void TextWindow::previewFile(const std::filesystem::path &path)
{
if(quickTextTitle.empty() && path==quickPath) return;
quickTextVisible=false;
quickTextTitle.clear();
quickPath=path;
++quickRequest;
quickReadyAt=GetTickCount64()+80;
stopPreview(false,true);
document.reset();
quickPreviewCode.reset();
quickKind=QuickKind::text;
quickHtmlRendered=false;
quickBinaryBytes=0;
quickError.clear();
layout();
SetTimer(window,quickViewTimer,30,nullptr);
}
void TextWindow::previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff)
{
if(!embedded) return;
if(quickTextTitle.empty())
{
++quickRequest;
KillTimer(window,quickViewTimer);
quickLoading={};
quickPath.clear();
quickError.clear();
stopPreview(false,true);
document.reset();
quickPreviewCode.reset();
quickKind=QuickKind::text;
quickHtmlRendered=false;
quickBinaryBytes=0;
applySourceLayoutOptions();
}
if(quickTextTitle.empty() || quickTextDiff!=diff)
{
language=automatic=diff?detectLanguage(L"preview.diff",contents):TextLanguage{};
installLexer();
}
quickTextTitle=title;
quickTextVisible=!contents.empty();
quickTextDiff=diff;
pageEol=SC_EOL_LF;
replaceEditorText(contents);
send(SCI_COLOURISE,0,-1);
layout();
}
void TextWindow::pollQuickView()
{
if(quickLoading.valid())
{
if(quickLoading.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
const bool current=quickRequest==quickReading;
try
{
auto loaded=quickLoading.get();
if(current)
{
original=quickPath;
filename=original.filename().wstring();
document=std::move(loaded.document);
quickPreviewCode=std::move(loaded.previewCode);
quickKind=loaded.kind;
quickHtmlRendered=quickKind==QuickKind::html && quickPreviewCode.has_value();
quickBinaryBytes=loaded.binaryBytes;
initializeDocument(std::move(loaded.firstPage));
}
}
catch(const std::exception &error)
{
if(current)
{
quickError=wide(error.what());
document.reset();
layout();
}
}
if(current)
{
KillTimer(window,quickViewTimer);
return;
}
}
if(quickPath.empty())
{
KillTimer(window,quickViewTimer);
return;
}
if(GetTickCount64()<quickReadyAt) return;
quickReading=quickRequest;
std::packaged_task<QuickDocument()> task([path=quickPath] {
auto source=std::make_unique<TextDocument>(path,false);
auto first=source->readPage(0);
const auto extension=lower(path.extension().wstring());
const auto html=extension==L".html" || extension==L".htm" || extension==L".xhtml";
const auto binary=std::any_of(first.begin(),first.end(),[](unsigned char c) {
return (c<32 && c!='\t' && c!='\r' && c!='\n' && c!='\f') || c==127;
});
if(binary && !html)
{
constexpr size_t limit=4096;
const auto bytes=source->readBytes(0,limit);
source->releaseReadHandle();
return QuickDocument{std::move(source),formatBinarySymbols(bytes),{},QuickKind::binary,bytes.size()};
}
std::optional<std::string> markup;
if(source->size()<=TextDocument::editLimit && (html || detectLanguage(path,first).lexer=="markdown"))
markup=readMarkdownDocument(*source);
source->releaseReadHandle();
return QuickDocument{std::move(source),std::move(first),std::move(markup),html?QuickKind::html:QuickKind::text};
});
quickLoading=task.get_future();
std::thread(std::move(task)).detach();
}
void TextWindow::startRemoteOpen(bool elevated)
{
elevatedOpen=elevated;
if(!SetTimer(window,openTimer,75,nullptr)) throw std::runtime_error("Cannot start the remote file timer.");
try
{
opening=std::async(std::launch::async,[this,elevated]
{
remote->download(edit,[this](uint64_t,uint64_t){return !cancelOpen;},UINT64_MAX,elevated);
});
}
catch(...)
{
KillTimer(window,openTimer);
throw;
}
}
void TextWindow::finishOpen()
{
if(!opening.valid() || opening.wait_for(std::chrono::milliseconds(0))!=std::future_status::ready) return;
KillTimer(window,openTimer);
try
{
opening.get();
if(cancelOpen) { DestroyWindow(window); return; }
document=std::make_unique<TextDocument>(remote->cache,edit,hex?TextEncoding::utf8:TextEncoding::automatic);
initializeDocument();
invalidate();
}
catch(const RemoteAccessDenied &error)
{
if(!cancelOpen && !edit && !elevatedOpen && remote->source.elevation)
{
if(remote->source.elevation->approve(window,original,false))
startRemoteOpen(true);
else DestroyWindow(window);
return;
}
if(!cancelOpen) search.style.message(window,wide(error.what()).c_str());
DestroyWindow(window);
}
catch(const std::exception &error)
{
if(!cancelOpen) search.style.message(window,wide(error.what()).c_str());
DestroyWindow(window);
}
}
void TextWindow::saveFile(bool closeWhenDone,bool elevated)
{
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);
return;
}
pendingCaret = send(SCI_GETCURRENTPOS);
if(draft) pendingSavePath=destination;
closeAfterSave = closeWhenDone;
elevatedSave=elevated;
cancelElevatedSave=false;
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,destination=std::move(destination),elevated]
{
const auto reopened=draft?document->saveNew(destination,newFormat):document->save();
if(remote)
{
uploadPending=true;
const auto progress=elevated?RemoteTextSource::Progress([this](uint64_t,uint64_t) {
return !cancelElevatedSave;
}):RemoteTextSource::Progress{};
remote->upload(progress);
uploadPending=false;
}
return reopened;
});
}
catch (...)
{
KillTimer(window, saveTimer);
send(SCI_SETREADONLY, !edit);
throw;
}
invalidate();
}
void TextWindow::finishSave()
{
if (!busy() || saving.wait_for(std::chrono::milliseconds(0)) != std::future_status::ready) return;
KillTimer(window, saveTimer);
if(taskOffset)
{
finishMarkdownTask();
return;
}
send(SCI_SETREADONLY, !edit);
bool reopened{};
try {reopened=saving.get();}
catch(const RemoteAccessDenied &)
{
if(!remote || elevatedSave || !remote->source.elevation) throw;
if(remote->source.elevation->approve(window,original,true)) saveFile(closeAfterSave,true);
else {closeAfterSave=false;invalidate();}
return;
}
catch(const std::system_error &error)
{
if(!elevatedSave || error.code().value()!=ERROR_CANCELLED) throw;
closeAfterSave=false;
invalidate();
return;
}
stagedDirty = false;
const bool created=std::exchange(draft,false);
if(created)
{
original=std::move(pendingSavePath);
filename=original.filename().wstring();
navigationHistory.clear();
updateTitle();
}
rememberLocalVersion();
if (!reopened)
{
search.style.message(window, L"The file was saved. Reopen it to continue editing.");
DestroyWindow(window);
return;
}
if (closeAfterSave) { DestroyWindow(window); return; }
if(created)
{
initializeDocument();
send(SCI_GOTOPOS,std::min<LRESULT>(pendingCaret,send(SCI_GETLENGTH)));
return;
}
if (pageTotal == 1 && document->pages() == 1)
{
fileSize = document->size();
invalidate();
return;
}
loadPage(std::min(page, document->pages() - 1));
send(SCI_GOTOPOS, std::min<LRESULT>(pendingCaret, send(SCI_GETLENGTH)));
}
void TextWindow::requestClose()
{
if (opening.valid()) { cancelOpen=true; return; }
if (busy())
{
if(elevatedSave) cancelElevatedSave=true;
return;
}
cancelSavedViewerLoad();
if (needsSave())
{
const auto answer = search.style.confirmSave(window,draft);
if (answer == IDCANCEL) return;
if (answer == IDYES)
{
if(suspendedEditor) restoreEditor();
saveFile(true);
return;
}
if (answer != IDNO) return;
}
DestroyWindow(window);
}
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() || savedViewerLoad.valid()) return;
if(suspendedEditor)
{
restoreEditor();
return;
}
if(edit && (draft || needsSave()))
{
if(!uploadPending) suspendEditor();
else
{
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();
}
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 writeDocumentPlacement(nlohmann::json &state,HWND window)
{
WINDOWPLACEMENT placement{sizeof(placement)};
if(GetWindowPlacement(window,&placement))
{
const auto &rect=placement.rcNormalPosition;
state["rect"]={rect.left,rect.top,rect.right,rect.bottom};
state["maximized"]=placement.showCmd==SW_SHOWMAXIMIZED ||
(placement.flags&WPF_RESTORETOMAXIMIZED)!=0;
}
}
RECT readDocumentBounds(const nlohmann::json &state)
{
if(!state.contains("rect")) return {};
const auto rect=state.at("rect").get<std::array<LONG,4>>();
return {rect[0],rect[1],rect[2],rect[3]};
}
int restoreDocumentPlacement(HWND window,HWND owner,const RECT &bounds,bool maximized)
{
if(bounds.left>=bounds.right || bounds.top>=bounds.bottom || !MonitorFromRect(&bounds,MONITOR_DEFAULTTONULL))
return IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW;
WINDOWPLACEMENT placement{sizeof(placement)};
placement.rcNormalPosition=bounds;
placement.showCmd=maximized?SW_SHOWMAXIMIZED:SW_SHOWNORMAL;
SetWindowPlacement(window,&placement);
return maximized?SW_MAXIMIZE:SW_SHOWNORMAL;
}
nlohmann::json TextWindow::sessionState() const
{
if(embedded || remote || draft || !document || !isLocalDocumentPath(original)) return nullptr;
const auto position=currentPosition();
nlohmann::json state{{"path",utf8(original.native())},{"editor",edit},{"hex",hex},
{"page",position.page},{"anchor",position.anchor},{"caret",position.caret},
{"firstLine",position.firstLine},{"horizontal",position.horizontal}};
if(previewVisible) state["renderedScroll"]=renderedScroll;
writeDocumentPlacement(state,window);
return state;
}
void TextWindow::restoreSession(const nlohmann::json &state)
{
ViewerPosition position{std::min(state.value("page",uint64_t{}),pageTotal?pageTotal-1:0),
state.value("anchor",LRESULT{}),state.value("caret",LRESULT{}),
std::max<LRESULT>(0,state.value("firstLine",LRESULT{})),std::max<LRESULT>(0,state.value("horizontal",LRESULT{}))};
if(position.page!=page) loadPage(position.page);
restorePosition(position);
if(state.contains("renderedScroll")) sessionScroll=std::max(0,state.at("renderedScroll").get<int>());
}
void TextWindow::showTextMode(const ViewerPosition &position,std::string contents,bool takeFocus)
{
rememberLocalVersion();
if(canPreview()) ShowWindow(editor,SW_HIDE);
prefs=resolvedTextProfile(loadTextPreferences(),edit);
filesFont=scaledDocumentFont(search.style,edit);
releaseMenu();
createMenu();
installLexer();
loadPage(position.page,std::move(contents));
restorePosition(position);
updateTitle();
updateIcons(GetDpiForWindow(window));
updateTaskbarGroup();
updatePreview();
layout();
if(takeFocus) 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(),
!remote && isLocalDocumentPath(original));
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 — " : hex ? L"Hex Viewer — " : L"Viewer — ") +
(remote ? remote->source.name + L" · " : std::wstring{}) + original.wstring();
SetWindowTextW(window,title.c_str());
}
void TextWindow::updateIcons(UINT dpi)
{
const auto instance=GetModuleHandleW(nullptr);
const auto resource=MAKEINTRESOURCEW(edit?IDI_FILES_EDITOR:IDI_FILES_VIEWER);
const auto set=[&](HICON &current,WPARAM kind,int width,int height)
{
const auto icon=static_cast<HICON>(LoadImageW(instance,resource,IMAGE_ICON,
GetSystemMetricsForDpi(width,dpi),GetSystemMetricsForDpi(height,dpi),0));
if(!icon) return;
SendMessageW(window,WM_SETICON,kind,reinterpret_cast<LPARAM>(icon));
if(const auto previous=std::exchange(current,icon)) DestroyIcon(previous);
};
set(smallIcon,ICON_SMALL,SM_CXSMICON,SM_CYSMICON);
set(largeIcon,ICON_BIG,SM_CXICON,SM_CYICON);
}
}
void setFileWindowTaskbar(HWND window,int iconResource,const wchar_t *identity)
{
setWindowTaskbarIdentity(window, iconResource, identity);
}
namespace
{
void TextWindow::updateTaskbarGroup(bool closing)
{
setFileWindowTaskbar(window,edit?IDI_FILES_EDITOR:IDI_FILES_VIEWER,closing?nullptr:
edit?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer");
}
bool TextWindow::canPreview() const
{
if(edit || hex || showBookmarkSource || !document || document->size()>TextDocument::editLimit) return false;
if(embedded && quickKind==QuickKind::html) return quickHtmlRendered;
return automatic.lexer=="markdown";
}
void TextWindow::toggleQuickHtml()
{
if(!embedded || quickKind!=QuickKind::html || !document || !quickPreviewCode) return;
quickHtmlRendered=!quickHtmlRendered;
if(quickHtmlRendered) updatePreview();
else stopPreview(true,true);
}
void TextWindow::updatePreview()
{
if(!canPreview())
{
stopPreview(true,true);
return;
}
previewWanted=true;
previewRetried=false;
previewStamp=previewFileStamp();
nextFileCheck=GetTickCount64()+350;
cancelImages=std::make_shared<std::atomic<bool>>(false);
if(!SetTimer(window,previewTimer,50,nullptr)) { stopPreview(); return; }
if(preview.initialized()) renderPreview();
else if(!startPreviewBrowser()) { stopPreview(); return; }
layout();
}
bool TextWindow::startPreviewBrowser()
{
previewDeadline=GetTickCount64()+8000;
return preview.create(window,[this](const auto &value){previewMessage(value);},
[this]{previewDeadline=GetTickCount64()+300;},true,[this](UINT key)
{
const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0;
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
if(key==VK_F1 && !ctrl && !alt && !((GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000))
{
PostMessageW(window,filesHelpRequest,0,0);
return true;
}
if(embedded)
{
if(!ctrl && !alt && !(GetKeyState(VK_SHIFT)&0x8000) && key==VK_F6 && quickKind==QuickKind::html)
{
PostMessageW(window,WM_COMMAND,quickModeControl,0);
return true;
}
if(!ctrl || alt || key!='Q') return false;
PostMessageW(GetParent(window),quickViewToggleMessage,0,0);
return true;
}
if(!alt && ((ctrl && key=='F') || key==VK_F3))
{
const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0;
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);
return true;
}
if(key==VK_BROWSER_BACK || key==VK_BROWSER_FORWARD || (alt && (key==VK_LEFT || key==VK_RIGHT)))
{
PostMessageW(window,WM_COMMAND,key==VK_LEFT || key==VK_BROWSER_BACK?historyBack:historyForward,0);
return true;
}
if(key!=VK_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;
});
}
void TextWindow::stopPreview(bool refresh,bool keepBrowser)
{
KillTimer(window,previewTimer);
previewWanted=previewVisible=false;
if(embedded && refresh && quickKind==QuickKind::html) quickHtmlRendered=false;
previewStamp.reset();
++previewRevision;
previewText.clear();
pendingTask.reset();
cancelPreviewImages();
previewLinks.clear();
if(keepBrowser && preview.initialized()) preview.post(L"{\"action\":\"clear\"}");
else preview.close();
if(refresh)
{
layout();
if(GetForegroundWindow()==window) focusContent();
}
}
void TextWindow::cancelPreviewImages()
{
if(cancelImages) *cancelImages=true;
imageQueue.clear();
image={};
}
void TextWindow::focusContent()
{
if(previewVisible) preview.focus();
else if(!previewWanted) SetFocus(editor);
}
void TextWindow::goToFragment(std::string_view fragment)
{
if(fragment.empty()) return;
if(previewVisible)
preview.post(wide(nlohmann::json{{"action","anchor"},{"fragment",fragment}}.dump()));
else previewFragment=fragment;
}
std::optional<LocalFileVersion> TextWindow::previewFileStamp() const
{
if(remote || !isLocalDocumentPath(original)) return {};
const auto file=CreateFileW(original.c_str(),FILE_READ_ATTRIBUTES,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if(file==INVALID_HANDLE_VALUE) return {};
std::optional<LocalFileVersion> stamp;
try {stamp=fileVersion(file);} catch(const std::system_error &) {}
CloseHandle(file);
return stamp;
}
void TextWindow::rememberLocalVersion()
{
if(embedded || remote || !document) return;
observedVersion=edit?document->expectedVersion():previewFileStamp();
diskChanged=false;
}
void TextWindow::pollExternalChanges()
{
if(embedded || remote || draft || !document || busy() || previewWanted || navigation.valid() || !observedVersion)
return;
const auto stamp=previewFileStamp();
if(!stamp || stamp==observedVersion) return;
if(edit && (GetForegroundWindow()!=window || !IsWindowEnabled(window) || !search.style.reloadChanged)) return;
try
{
if(edit)
{
observedVersion=stamp;
diskChanged=true;
invalidate();
if(!search.style.reloadChanged(window)) return;
}
auto replacement=std::make_unique<TextDocument>(original,edit,hex?TextEncoding::utf8:TextEncoding::automatic,edit);
auto position=currentPosition();
const auto pages=hex?1+(replacement->size()?replacement->size()-1:0)/hexPageBytes:replacement->pages();
position.page=std::min(position.page,pages-1);
auto contents=hex?formatHexPage(replacement->readBytes(position.page*hexPageBytes,hexPageBytes),
position.page*hexPageBytes):replacement->readPage(position.page);
if(!hex) language=automatic=detectLanguage(original,contents);
document=std::move(replacement);
showTextMode(position,std::move(contents),edit);
}
catch(const std::exception &error)
{
if(edit) search.style.message(window,wide(error.what()).c_str());
}
}
void TextWindow::renderPreview(bool keepPosition)
{
applyMarkdownPreferences(loadTextPreferences().markdown);
previewDeadline=GetTickCount64()+30000;
previewText=quickPreviewCode?*quickPreviewCode:readMarkdownDocument(*document);
if(!remote) document->releaseReadHandle();
nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision},
{"canSave",!embedded && !suspendedEditor && (!remote || remote->revision.editable)},{"compact",embedded},
{"html",embedded && quickKind==QuickKind::html},
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
{"keepPosition",keepPosition}};
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
if(sessionScroll) message["scroll"]=*std::exchange(sessionScroll,{});
restoreScroll=false;
preview.post(wide(message.dump(-1,' ',false,nlohmann::json::error_handler_t::replace)));
}
void TextWindow::applyMarkdownPreferences(const MarkdownPreferences &preferences)
{
if(!preview.initialized()) return;
const auto scale=textAreaScale(search.style,AppearanceArea::markdown);
preview.post(wide(nlohmann::json{{"action","appearance"},{"width",preferences.width},
{"fontSize",preferences.fontSize*scale/100.0},{"font",utf8(preferences.font)}}.dump()));
}
void TextWindow::refreshPreview()
{
if(embedded || remote || !previewVisible || navigation.valid() || busy() || pendingTask || GetTickCount64()<nextFileCheck) return;
nextFileCheck=GetTickCount64()+350;
const auto stamp=previewFileStamp();
if(!stamp || stamp==previewStamp) return;
try
{
auto reopened=std::make_unique<TextDocument>(original,false);
if(!reopened->pages()) return;
document=std::move(reopened);
previewStamp=stamp;
loadPage(std::min(page,document->pages()-1));
if(!canPreview()) { stopPreview(); return; }
cancelPreviewImages();
cancelImages=std::make_shared<std::atomic<bool>>(false);
previewVisible=false;
renderPreview(true);
}
catch(const std::runtime_error &)
{
// The file may be locked or incomplete while another application saves it.
previewStamp.reset();
}
}
void TextWindow::reportMarkdownTask(uint64_t revision,bool saved)
{
preview.post(wide(nlohmann::json{{"action","task-result"},{"revision",revision},{"saved",saved}}.dump()));
}
void TextWindow::startMarkdownTask()
{
const auto task=std::exchange(pendingTask,{});
if(!task) return;
if(!previewVisible || edit || suspendedEditor || busy() || navigation.valid() || task->revision!=previewRevision ||
(remote && !remote->revision.editable))
{
reportMarkdownTask(task->revision,false);
return;
}
size_t lineStart=0;
const auto reject=[&]{reportMarkdownTask(task->revision,false);};
for(size_t line=0;line<task->line;++line)
{
const auto end=previewText.find_first_of("\r\n",lineStart);
if(end==previewText.npos) { reject(); return; }
lineStart=end+1;
if(previewText[end]=='\r' && lineStart<previewText.size() && previewText[lineStart]=='\n') ++lineStart;
}
if(!task->column || task->column>=previewText.size()-lineStart) { reject(); return; }
const auto offset=lineStart+task->column;
const auto lineEnd=previewText.find_first_of("\r\n",lineStart);
if((lineEnd!=previewText.npos && offset>=lineEnd) || offset+1>=previewText.size() ||
previewText[offset-1]!='[' || previewText[offset+1]!=']' ||
(previewText[offset]!=' ' && previewText[offset]!='x' && previewText[offset]!='X'))
{
reject();
return;
}
const auto next=task->checked?'x':' ';
if((previewText[offset]!=' ')==task->checked) { reportMarkdownTask(task->revision,true); return; }
if(!SetTimer(window,saveTimer,75,nullptr)) { reject(); return; }
const auto encoding=document->encoding();
try
{
saving=std::async(std::launch::async,[this,expected=previewText,offset,next,encoding]
{
const auto path=remote?remote->cache:original;
std::filesystem::path candidate;
struct RemoveCandidate
{
std::filesystem::path &path;
~RemoveCandidate(){if(!path.empty()){std::error_code ec;std::filesystem::remove(path,ec);}}
} cleanup{candidate};
if(remote)
{
const auto stage=path.parent_path()/(path.filename()==L"content"?L"task-update":L"content");
std::filesystem::copy_file(path,stage);
candidate=stage;
}
TextDocument fresh(remote?candidate:path,true,encoding);
if(fresh.size()>TextDocument::editLimit)
throw std::runtime_error("The Markdown file grew outside KSwitcher.");
size_t start=0;
for(uint64_t index=0;index<fresh.pages();++index)
{
auto text=fresh.readPage(index);
if(std::string_view(expected).substr(start,text.size())!=text)
throw std::runtime_error("The Markdown text changed outside KSwitcher.");
const auto end=start+text.size();
if(offset>=start && offset<end)
{
text[offset-start]=next;
fresh.stage(index,text);
}
start=end;
}
if(start!=expected.size()) throw std::runtime_error("The Markdown text changed outside KSwitcher.");
fresh.save();
if(remote)
{
remote->revision=remote->source.upload(original,candidate,remote->revision);
remote->cache.swap(candidate);
}
return next=='x';
});
taskOffset=offset;
}
catch(...)
{
KillTimer(window,saveTimer);
reject();
throw;
}
}
void TextWindow::finishMarkdownTask()
{
const auto offset=*std::exchange(taskOffset,{});
const auto revision=previewRevision;
bool checked{};
try {checked=saving.get();}
catch(const std::exception &error)
{
reportMarkdownTask(revision,false);
search.style.message(window,(L"Could not save the Markdown checkbox. "+wide(error.what())).c_str());
return;
}
if(offset<previewText.size()) previewText[offset]=checked?'x':' ';
reportMarkdownTask(revision,true);
const auto encoding=document->encoding();
document=std::make_unique<TextDocument>(remote?remote->cache:original,false,encoding);
loadPage(std::min(page,document->pages()-1));
if(!remote)
{
previewStamp=previewFileStamp();
document->releaseReadHandle();
}
}
void TextWindow::previewMessage(const std::wstring &value)
{
if(!previewWanted) return;
try
{
if(value==L"ready")
{
renderPreview();
return;
}
const auto message=nlohmann::json::parse(utf8(value));
const auto action=message.at("action").get<std::string>();
if(embedded && quickKind==QuickKind::html && action!="rendered" && action!="failed") return;
if(action=="cycle")
{
PostMessageW(window,cycleWindow,message.value("reverse",false),0);
return;
}
if(embedded && action!="image" && action!="rendered" && action!="failed") return;
const auto revision=message.value("revision",previewRevision);
if(embedded && revision!=previewRevision) return;
if(action=="scroll")
{
if(!embedded && revision==previewRevision) renderedScroll=std::max(0,message.at("top").get<int>());
return;
}
if(action=="failed")
{
PostMessageW(window,previewFailed,static_cast<WPARAM>(revision),0);
return;
}
if(action=="rendered")
{
PostMessageW(window,previewRendered,static_cast<WPARAM>(revision),0);
return;
}
if(action=="save-task")
{
if(!pendingTask && !busy())
{
pendingTask=MarkdownTask{message.at("revision"),message.at("line"),message.at("column"),
message.at("checked")};
PostMessageW(window,savePreviewTask,0,0);
}
return;
}
// Defer transitions until WebView2 returns from its event callback.
if(action=="edit" || action=="close")
{
PostMessageW(window,WM_COMMAND,action=="edit"?switchMode:close,0);
return;
}
if(action=="back" || action=="forward")
{
previewLinks.push_back({{},action=="back"?-1:1,message.value("scroll",0),false});
PostMessageW(window,openPreviewLink,0,0);
return;
}
if(action!="image" && action!="link") return;
const auto url=message.at("path").get<std::string>();
if(action=="link" && (url.starts_with("https://") || url.starts_with("http://")))
{
ShellExecuteW(window,L"open",wide(url).c_str(),nullptr,nullptr,SW_SHOWNORMAL);
return;
}
const auto target=action=="link" && url.starts_with('#') ? original : markdownTarget(original,url);
if(action=="link")
{
if(!target.empty())
{
const auto hash=url.find('#');
previewLinks.push_back({{target,hash==url.npos?std::string{}:url.substr(hash+1)},
0,message.value("scroll",0),message.value("newWindow",false)});
PostMessageW(window,openPreviewLink,0,0);
}
}
else if(imageQueue.size()<256)
{
imageQueue.push_back({target,message.at("index").get<uint64_t>(),message.at("generation").get<uint64_t>()});
}
}
catch(const std::exception &error)
{
if(!previewVisible) PostMessageW(window,previewFailed,0,0);
else log(L"Markdown preview message: "+wide(error.what()));
}
}
void TextWindow::syncNavigation()
{
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)
openRemoteTextWindow(window,request.target.path,false,search.style,remote->source,request.target.fragment,true);
else
openTextWindow(window,request.target.path,false,search.style,nullptr,request.target.fragment,true);
return;
}
if((request.direction<0 && navigationIndex==0) ||
(request.direction>0 && navigationIndex+1==navigationHistory.size())) return;
navigationHistory[navigationIndex].scroll=request.scroll;
destinationIndex.reset();
if(request.direction)
{
destinationIndex=request.direction<0 ? navigationIndex-1 : navigationIndex+1;
destination=navigationHistory[*destinationIndex];
}
else destination=std::move(request.target);
if(destination.path==original || !remote) { showLocation(nullptr); return; }
auto cancel=std::make_shared<std::atomic<bool>>(false);
if(!SetTimer(window,navigationTimer,75,nullptr))
throw std::runtime_error("Cannot start the remote navigation timer.");
try
{
navigation=fetchRemoteText(remote->source,destination.path,cancel);
cancelNavigation=std::move(cancel);
}
catch(...) { KillTimer(window,navigationTimer); throw; }
}
void TextWindow::finishNavigation()
{
if(!navigation.valid() || navigation.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
KillTimer(window,navigationTimer);
showLocation(navigation.get());
}
void TextWindow::showLocation(std::unique_ptr<RemoteTextFile> fetched)
{
const bool sameDocument=destination.path==original;
std::unique_ptr<TextDocument> next;
if(!sameDocument) next=std::make_unique<TextDocument>(fetched?fetched->cache:destination.path,false);
if(destinationIndex) navigationIndex=*destinationIndex;
else if(!sameDocument || navigationHistory[navigationIndex].fragment!=destination.fragment)
{
navigationHistory.resize(navigationIndex+1);
navigationHistory.push_back(destination);
++navigationIndex;
}
if(sameDocument)
{
nlohmann::json message{{"action","anchor"},{"fragment",destination.fragment}};
if(destinationIndex) message["scroll"]=destination.scroll;
preview.post(wide(message.dump()));
syncNavigation();
return;
}
stopPreview(false,true);
document=std::move(next);
if(fetched) remote=std::move(fetched);
original=destination.path;
filename=original.filename().wstring();
previewFragment=destination.fragment;
restoreScroll=destinationIndex.has_value();
initializeDocument();
updateTitle();
layout();
focusContent();
}
void TextWindow::pollImages()
{
refreshPreview();
if(!previewVisible && GetTickCount64()>=previewDeadline)
{
if(!preview.initialized() && !previewRetried)
{
// The previous window's WebView2 process may still be shutting down.
previewRetried=true;
preview.close();
if(startPreviewBrowser()) return;
}
stopPreview();
return;
}
if(image.valid())
{
if(image.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
std::string source;
try { source=image.get(); } catch(const std::exception &) {}
const nlohmann::json message{{"action","image"},{"index",activeImage.index},
{"generation",activeImage.generation},{"source",std::move(source)}};
preview.post(wide(message.dump()));
}
if(imageQueue.empty()) return;
activeImage=std::move(imageQueue.front());
imageQueue.pop_front();
std::packaged_task<std::string()> task(
[path=activeImage.path,backend=remote?std::optional(remote->source):std::nullopt,cancel=cancelImages] {
return markdownImage(path,backend?&*backend:nullptr,cancel);
});
image=task.get_future();
std::thread(std::move(task)).detach();
}
void TextWindow::layout()
{
if (!editor) return;
RECT area{};
GetClientRect(window, &area);
const auto row = chromeHeight();
const int top=embedded?row:2*row;
const LONG bottom=std::max<LONG>(top,area.bottom-(embedded?0:row));
MoveWindow(editor,0,top,area.right,bottom-top,TRUE);
if(quickModeButton)
{
const int width=std::min(static_cast<int>(area.right),scale(108));
MoveWindow(quickModeButton,area.right-width,0,width,row,TRUE);
SetWindowTextW(quickModeButton,quickHtmlRendered?L"Show Source":L"Show Rendered");
ShowWindow(quickModeButton,quickKind==QuickKind::html && quickPreviewCode && document?SW_SHOWNA:SW_HIDE);
}
preview.layout({0,top,area.right,bottom},previewWanted && (!embedded || previewVisible));
ShowWindow(editor,(document || quickTextVisible) && !previewWanted?SW_SHOWNA:SW_HIDE);
invalidate();
}
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{};
const auto dc = BeginPaint(window, &paint);
RECT client{};
GetClientRect(window, &client);
const auto row = chromeHeight();
const auto brush = static_cast<HBRUSH>(GetStockObject(DC_BRUSH));
SetDCBrushColor(dc, color(TextColor::background));
if(embedded)
{
FillRect(dc,&client,brush);
auto font=filesFont.font;
font.lfHeight=-MulDiv(filesFont.tenthsOfPoint,GetDpiForWindow(window),720);
const auto chromeFont=CreateFontIndirectW(&font);
std::wstring label=L"Quick View";
if(!quickPath.empty()) label+=L" · "+quickPath.filename().native();
if(!quickError.empty()) label+=L" · "+quickError;
else if(quickPath.empty()) label+=L" · Select a local file";
else if(!document || (previewWanted && !previewVisible)) label+=L" · Loading…";
else if(quickKind==QuickKind::binary)
label=L"Binary · "+std::to_wstring(quickBinaryBytes)+L" / "+std::to_wstring(fileSize)+L" B · "+
quickPath.filename().native();
else
{
if(quickKind==QuickKind::html) label+=previewVisible?L" · Rendered":L" · Source";
if(!previewVisible && pageTotal>1) label+=L" · First page";
}
if(quickModeButton && IsWindowVisible(quickModeButton))
client.right=std::max(0L,client.right-scale(108));
if(!quickTextTitle.empty()) label=quickTextTitle;
drawEditorStatus(dc,{0,0,client.right,row},chromeFont,color(TextColor::chromebg),
color(TextColor::chrome),scale(6),label);
if(chromeFont) DeleteObject(chromeFont);
EndPaint(window,&paint);
return;
}
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};
const RECT top=statusBounds();
RECT bottom{0, client.bottom - row, client.right, client.bottom};
FillRect(dc, &bottom, brush);
FillRect(dc, &menuBar, brush);
const auto chromeFont = createChromeFont();
const auto previous = SelectObject(dc, chromeFont);
SetTextColor(dc, color(TextColor::chrome));
SetBkMode(dc, TRANSPARENT);
LONG left{};
for (size_t index = 0; index < menuBarLabels.size(); ++index)
{
const auto &label = menuBarLabels[index];
SIZE extent{};
GetTextExtentPoint32W(dc, label.title.c_str(), static_cast<int>(label.title.size()), &extent);
const auto inset = scale(9);
menuBounds[index] = {left, 0, left + extent.cx + 2 * inset, row};
const bool active = menuSelection == static_cast<int>(index);
if (active)
{
SetDCBrushColor(dc, color(TextColor::menuHighlight));
FillRect(dc, &menuBounds[index], brush);
}
auto bounds = menuBounds[index];
bounds.left += inset;
SetTextColor(dc, color(active ? TextColor::menuHighlightText : TextColor::menuText));
drawMenuTitle(dc, bounds, label, color(TextColor::menuAccessKey), true);
left = bounds.right;
}
SetTextColor(dc, color(TextColor::chrome));
bottom.left += scale(7);
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;
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);
if(diskChanged && edit) status+=L" │ Disk changed";
status+=L" │ "+std::to_wstring(fileSize)+L" B";
if(bookmarkTask.valid()) status+=L" │ Locating line…";
drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status);
}
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"F4 Hex F6 Edit Ctrl+W Close" :
previewWanted ? L"Rendering Markdown… Ctrl+W 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);
DeleteObject(chromeFont);
EndPaint(window, &paint);
}
void TextWindow::openFind()
{
const auto searchText = [this](LRESULT start, LRESULT end) -> std::wstring {
if (start < 0 || end <= start || end - start > 4 * searchQueryLimit) return {};
const auto value = pageText().substr(start, end - start);
if (value.find_first_of("\r\n\0", 0, 3) != value.npos) return {};
auto text = wide(std::string(value));
return text.size() <= searchQueryLimit ? std::move(text) : std::wstring{};
};
const auto caret = send(SCI_GETCURRENTPOS);
search.word = searchText(send(SCI_WORDSTARTPOSITION, caret, TRUE), send(SCI_WORDENDPOSITION, caret, TRUE));
search.selection = searchText(send(SCI_GETSELECTIONSTART), send(SCI_GETSELECTIONEND));
search.history = readFarHistory(FarHistoryKind::search);
search.historyPalette = search.style.dropDownPalette();
if (search.style.run(GetModuleHandleW(nullptr), MAKEINTRESOURCEW(604), window, searchDialog,
reinterpret_cast<LPARAM>(&search)) == IDOK)
find((search.flags & FR_DOWN) != 0, search.flags);
}
void TextWindow::find(bool down, DWORD flags)
{
const auto needle = utf8(this->search.text);
if (needle.empty()) { openFind(); return; }
const auto length = send(SCI_GETLENGTH);
const auto start = send(down ? SCI_GETSELECTIONEND : SCI_GETSELECTIONSTART);
send(SCI_SETSEARCHFLAGS, ((flags & FR_MATCHCASE) ? SCFIND_MATCHCASE : 0) |
((flags & FR_WHOLEWORD) ? SCFIND_WHOLEWORD : 0));
const auto search = [&](LRESULT from, LRESULT to) {
send(SCI_SETTARGETRANGE, from, to);
return send(SCI_SEARCHINTARGET, needle.size(), reinterpret_cast<LPARAM>(needle.data())) >= 0;
};
if (search(start, down ? length : 0) || search(down ? 0 : length, start))
{
send(SCI_SETSEL, send(SCI_GETTARGETSTART), send(SCI_GETTARGETEND));
send(SCI_SCROLLCARET);
}
else MessageBeep(MB_ICONINFORMATION);
}
void TextWindow::command(UINT id)
{
if(!document && id!=close) return;
if (busy() && id!=close) 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)
preview.post(wide(nlohmann::json{{"action",id==historyBack?"back":"forward"}}.dump()));
else navigatePreview({{},id==historyBack?-1:1,0,false});
return;
case previousPage: if (page) go(page - 1); return;
case nextPage: go(page + 1); return;
case firstPage: go(0); return;
case lastPage: go(pageTotal - 1); return;
case goToPage:
{
if (pageTotal <= 1) return;
PagePrompt prompt{search.style, page, pageTotal};
if (prompt.style.run(GetModuleHandleW(nullptr), MAKEINTRESOURCEW(602), window, pageDialog,
reinterpret_cast<LPARAM>(&prompt)) == IDOK) go(prompt.page);
return;
}
case findText:
if(previewVisible) preview.post(L"{\"action\":\"find\"}");
else openFind();
return;
case findNext:
case findPrevious:
if(previewVisible)
preview.post(id==findNext?L"{\"action\":\"find-next\"}":L"{\"action\":\"find-next\",\"previous\":true}");
else if(id==findNext) find((search.flags & FR_DOWN) != 0, search.flags);
return;
case previewEscape:
if(previewVisible) preview.post(L"{\"action\":\"escape\"}");
else requestClose();
return;
case undo: if (edit) send(SCI_UNDO); return;
case redo: if (edit) send(SCI_REDO); return;
case cut: if (edit) send(SCI_CUT); return;
case copy: send(SCI_COPY); return;
case paste: if (edit) send(SCI_PASTE); return;
case selectAll: send(SCI_SELECTALL); return;
case lexerAuto: language = automatic; installLexer(); return;
case lexerPlain: language = {}; installLexer(); return;
case options:
search.style.options(window,appearanceArea());
SetFocus(editor);
return;
default:
if (id >= lexerStart && id - lexerStart < lexers.size())
{
const auto &name = lexers[id - lexerStart];
language = name == automatic.lexer ? automatic : TextLanguage{name};
installLexer();
return;
}
return;
}
}
void TextWindow::notify(const SCNotification &notice)
{
if(!document) return;
if (loading) return;
switch (notice.nmhdr.code)
{
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>(""));
insertRejected = true;
MessageBeep(MB_ICONWARNING);
}
else insertRejected = false;
if(hadWarning!=insertRejected) invalidateHints();
}
if (notice.modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
{
if (notice.linesAdded) updateLineNumberMargin();
undoBytes += static_cast<size_t>(notice.length) + 64;
if (undoBytes >= 32 * TextDocument::pageBytes)
PostMessageW(window, trimUndo, 0, 0);
invalidateStatus();
}
break;
case SCN_CHARADDED:
if (edit && prefs.autoIndent && (notice.ch == '\n' || (notice.ch == '\r' && send(SCI_GETEOLMODE) == SC_EOL_CR)))
{
const auto position = send(SCI_GETCURRENTPOS);
const auto line = send(SCI_LINEFROMPOSITION, position);
if (line)
{
send(SCI_SETLINEINDENTATION, line, send(SCI_GETLINEINDENTATION, line - 1));
send(SCI_GOTOPOS, send(SCI_GETLINEINDENTPOSITION, line));
}
}
break;
case SCN_ZOOM:
updateLineNumberMargin();
break;
case SCN_UPDATEUI:
case SCN_SAVEPOINTREACHED:
case SCN_SAVEPOINTLEFT:
invalidateStatus();
break;
}
}
bool TextWindow::handleKey(const MSG &message)
{
if(embedded)
{
if(quickKind!=QuickKind::html || message.message!=WM_KEYDOWN || message.wParam!=VK_F6 ||
((GetKeyState(VK_CONTROL)|GetKeyState(VK_SHIFT)|GetKeyState(VK_MENU))&0x8000)) return false;
if(!(message.lParam&(1LL<<30))) toggleQuickHtml();
return true;
}
const auto key = message.wParam;
if (message.hwnd != editor) return false;
if (message.message == WM_SYSKEYDOWN && (message.lParam & (1LL << 29)))
{
if (!edit && (key==VK_LEFT || key==VK_RIGHT))
{
SendMessageW(window,WM_COMMAND,key==VK_LEFT?historyBack:historyForward,0);
return true;
}
for (size_t index = 0; index < menuBarLabels.size(); ++index)
if (menuBarLabels[index].matches(static_cast<wchar_t>(key)))
{
SendMessageW(window, WM_COMMAND, 600 + index, 0);
return true;
}
}
if (message.message == WM_KEYDOWN ||
(message.message == WM_SYSKEYDOWN && key == VK_F10 && !(message.lParam & (1LL << 29))))
{
const bool ctrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
const bool shift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
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) 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;
if (ctrl && shift && key == VK_END) id = lastPage;
if (id) { SendMessageW(window, WM_COMMAND, id, 0); return true; }
}
return false;
}
LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, LPARAM lparam)
{
if(message==WM_NCCREATE)
{
const auto create=reinterpret_cast<const CREATESTRUCTW *>(lparam);
const auto &state=*static_cast<const std::shared_ptr<TextWindow> *>(create->lpCreateParams);
state->window=window;
textWindows.emplace(window,state);
if(!state->embedded) textWindowOrder.push_back(window);
}
const auto found=textWindows.find(window);
if(found==textWindows.end()) return DefWindowProcW(window,message,wparam,lparam);
const auto self=found->second;
try
{
if(message==preferencesChanged || windowsAppThemeChanged(message,lparam))
{
self->reloadPreferences();
return 0;
}
switch (message)
{
case WM_COPYDATA:
{
if(!lparam) return FALSE;
const auto &query=*reinterpret_cast<const COPYDATASTRUCT *>(lparam);
if(query.dwData!=openDocumentQuery || !query.lpData || query.cbData>65536 ||
query.cbData<sizeof(wchar_t) || query.cbData%sizeof(wchar_t)) return FALSE;
const std::wstring_view candidate(static_cast<const wchar_t *>(query.lpData),query.cbData/sizeof(wchar_t));
const auto identity=documentIdentity(self->original,self->peerId);
return CompareStringOrdinal(candidate.data(),static_cast<int>(candidate.size()),
identity.data(),static_cast<int>(identity.size()),TRUE)==CSTR_EQUAL;
}
case WM_CREATE:
self->editor = CreateWindowExW(0, L"Scintilla", L"", WS_CHILD | WS_TABSTOP |
WS_VSCROLL | WS_HSCROLL, 0, 0, 0, 0, window, nullptr, GetModuleHandleW(nullptr), nullptr);
if (!self->editor) throw std::runtime_error("Cannot create the text control.");
if(self->embedded)
{
self->quickModeButton=CreateWindowW(L"BUTTON",L"Show Source",WS_CHILD|WS_TABSTOP|BS_PUSHBUTTON,
0,0,0,0,window,reinterpret_cast<HMENU>(quickModeControl),GetModuleHandleW(nullptr),nullptr);
if(!self->quickModeButton) throw std::runtime_error("Cannot create the Quick View mode button.");
}
self->send(SCI_SETCODEPAGE, SC_CP_UTF8);
self->send(SCI_SETMARGINS, 1);
self->send(SCI_SETMODEVENTMASK, SC_MOD_INSERTCHECK | SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT);
SetWindowSubclass(self->editor,[](HWND child,UINT msg,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR data)
->LRESULT
{
auto *state=reinterpret_cast<TextWindow *>(data);
if(msg==WM_KEYDOWN || msg==WM_SYSKEYDOWN)
{
MSG key{child,msg,wp,lp};
if(state->handleKey(key)) return 0;
}
if(msg==WM_XBUTTONUP && !state->edit && !state->embedded)
{
SendMessageW(state->window,WM_COMMAND,
GET_XBUTTON_WPARAM(wp)==XBUTTON1?historyBack:historyForward,0);
return TRUE;
}
return DefSubclassProc(child,msg,wp,lp);
},1,reinterpret_cast<DWORD_PTR>(self.get()));
if(self->remote)
{
self->applyPreferences();
self->send(SCI_SETREADONLY,TRUE);
self->startRemoteOpen();
}
else if(self->embedded) self->applyPreferences();
else self->initializeDocument();
if(!self->embedded)
{
if(!self->remote) SetTimer(window,externalChangeTimer,500,nullptr);
self->updateIcons(GetDpiForWindow(window));
self->updateTaskbarGroup();
}
self->layout();
return 0;
case WM_ERASEBKGND: return 1;
case WM_PAINT: self->paint(); return 0;
case WM_SIZE: self->layout(); return 0;
case WM_DPICHANGED:
{
const auto area = reinterpret_cast<RECT *>(lparam);
SetWindowPos(window, nullptr, area->left, area->top, area->right - area->left,
area->bottom - area->top, SWP_NOZORDER | SWP_NOACTIVATE);
self->updateLineNumberMargin();
self->updateIcons(LOWORD(wparam));
self->layout();
return 0;
}
case WM_SETFOCUS: if(!self->embedded) self->focusContent(); return 0;
case cycleWindow: cycleTextWindows(window,wparam!=0); return 0;
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();
return 0;
}
break;
case previewFailed:
if(!self->embedded || !wparam || wparam==self->previewRevision) self->stopPreview();
return 0;
case savePreviewTask: self->startMarkdownTask(); return 0;
case previewRendered:
if(self->previewWanted && (!self->embedded || wparam==self->previewRevision))
{
self->previewVisible=true;
if(!self->embedded) self->syncNavigation();
self->layout();
if(GetForegroundWindow()==window) self->focusContent();
}
return 0;
case openPreviewLink:
if(!self->previewLinks.empty())
{
const auto target=std::move(self->previewLinks.front());
self->previewLinks.pop_front();
self->navigatePreview(std::move(target));
}
return 0;
case WM_INITMENU: self->updateMenus(); return 0;
case WM_MENUCHAR: return self->menuKey(reinterpret_cast<HMENU>(lparam), LOWORD(wparam));
case WM_MEASUREITEM:
if (self->measureMenu(*reinterpret_cast<MEASUREITEMSTRUCT *>(lparam))) return TRUE;
break;
case WM_DRAWITEM:
if (self->drawMenu(*reinterpret_cast<DRAWITEMSTRUCT *>(lparam))) return TRUE;
break;
case WM_LBUTTONDOWN:
{
const POINT point{static_cast<short>(LOWORD(lparam)), static_cast<short>(HIWORD(lparam))};
for (size_t index = 0; index < self->menuBounds.size(); ++index)
if (PtInRect(&self->menuBounds[index], point)) self->openMenu(static_cast<int>(index));
return 0;
}
case WM_COMMAND:
if(self->embedded)
{
if(LOWORD(wparam)==quickModeControl) self->toggleQuickHtml();
return 0;
}
if (LOWORD(wparam) >= 600 && LOWORD(wparam) < 605) self->openMenu(LOWORD(wparam) - 600);
else self->command(LOWORD(wparam));
return 0;
case WM_CLOSE:
if (!self->search.style.dismissOwned(window)) self->requestClose();
return 0;
case WM_NOTIFY:
if (reinterpret_cast<NMHDR *>(lparam)->hwndFrom == self->editor)
self->notify(*reinterpret_cast<SCNotification *>(lparam));
return 0;
case WM_TIMER:
if (wparam == saveTimer) self->finishSave();
if (wparam == openTimer) self->finishOpen();
if (wparam == previewTimer) self->pollImages();
if (wparam == externalChangeTimer) self->pollExternalChanges();
if (wparam == navigationTimer) self->finishNavigation();
if (wparam == quickViewTimer) self->pollQuickView();
if (wparam == bookmarkTimer) self->finishBookmark();
if (wparam == savedViewerTimer) self->finishSavedViewer();
return 0;
case trimUndo:
if (self->undoBytes >= 32 * TextDocument::pageBytes)
{
const bool changed = self->send(SCI_GETMODIFY);
self->send(SCI_EMPTYUNDOBUFFER);
if (changed) self->send(SCI_SETUNDOSAVEPOINT, static_cast<WPARAM>(-1));
self->undoBytes = 0;
}
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);
self->releaseMenu();
return 0;
case WM_NCDESTROY:
self->window=nullptr;
textWindows.erase(window);
std::erase(textWindowOrder,window);
quitWhenFilesWindowsClose();
break;
}
}
catch (const std::exception &error)
{
if(self->embedded) self->quickError=wide(error.what());
else self->search.style.message(window, wide(error.what()).c_str());
self->invalidate();
return message == WM_CREATE ? -1 : 0;
}
return DefWindowProcW(window, message, wparam, lparam);
}
}
std::vector<FarHistoryEntry> loadFarHistory(FarHistoryKind kind)
{
return readFarHistory(kind);
}
void installFarHistoryKey(HWND field,int arrowId)
{
SetWindowSubclass(field,searchFieldKeys,1,arrowId);
}
void rememberFarHistory(FarHistoryKind kind,std::wstring_view text)
{
writeFarHistory(kind,text);
}
int chooseFarDropDown(HWND anchor,const std::vector<FarHistoryEntry> &entries,int selected,
FarDropDownPalette palette,int rightInset)
{
const auto owner=GetAncestor(anchor,GA_ROOT);
if(entries.empty() || !owner || GetPropW(owner,farDropDownProperty)) return -1;
selected=std::clamp(selected,0,static_cast<int>(entries.size())-1);
FarPopup state{};
state.palette=palette;
state.font=reinterpret_cast<HFONT>(SendMessageW(anchor,WM_GETFONT,0,0));
const auto dpi=GetDpiForWindow(anchor);
state.inset=std::max(2,MulDiv(5,dpi,96));
RECT field{};
GetWindowRect(anchor,&field);
state.rowHeight=std::max(1L,field.bottom-field.top);
if(const auto dc=GetDC(anchor))
{
const auto old=SelectObject(dc,state.font);
TEXTMETRICW metrics{};
if(GetTextMetricsW(dc,&metrics)) state.rowHeight=metrics.tmHeight;
SelectObject(dc,old);
ReleaseDC(anchor,dc);
}
std::wstring_view previous;
for(size_t index=0;index<entries.size();++index)
{
const auto &entry=entries[index];
if(!entry.date.empty() && entry.date!=previous) state.rows.push_back({entry.date,-1});
previous=entry.date;
if(static_cast<int>(index)==selected) state.current=static_cast<int>(state.rows.size());
state.rows.push_back({entry.text,static_cast<int>(index)});
}
MONITORINFO monitor{sizeof(monitor)};
if(!GetMonitorInfoW(MonitorFromWindow(anchor,MONITOR_DEFAULTTONEAREST),&monitor)) return -1;
const auto &work=monitor.rcWork;
const bool above=work.bottom-field.bottom<4*state.rowHeight+2*state.inset &&
field.top-work.top>work.bottom-field.bottom;
const auto space=above?field.top-work.top:work.bottom-field.bottom;
state.visible=std::clamp<int>((space-state.rowTop()-state.bottomMargin())/state.rowHeight,1,
std::min(9,static_cast<int>(state.rows.size())));
state.select(state.current);
const auto height=state.visible*state.rowHeight+state.rowTop()+state.bottomMargin();
const auto width=std::clamp(field.right-field.left-rightInset,1L,work.right-work.left);
const auto left=std::clamp(field.left,work.left,work.right-width);
const auto instance=GetModuleHandleW(nullptr);
WNDCLASSW type{};
type.lpfnWndProc=farPopupWindow;
type.hInstance=instance;
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
type.lpszClassName=L"KSwitcher.Files.DropDown";
RegisterClassW(&type);
const auto window=CreateWindowExW(WS_EX_TOOLWINDOW,type.lpszClassName,L"",WS_POPUP,
left,above?field.top-height:field.bottom,width,height,owner,nullptr,instance,&state);
if(!window) return -1;
SetPropW(owner,farDropDownProperty,window);
ShowWindow(window,SW_SHOW);
SetFocus(window);
SetCapture(window);
MSG message{};
while(!state.done)
{
const auto status=GetMessageW(&message,nullptr,0,0);
if(status<=0)
{
if(status==0) PostQuitMessage(static_cast<int>(message.wParam));
break;
}
if(message.hwnd!=window && message.message==WM_KEYDOWN)
message.hwnd=window;
TranslateMessage(&message);
DispatchMessageW(&message);
}
if(GetCapture()==window) ReleaseCapture();
RemovePropW(owner,farDropDownProperty);
if(IsWindow(window)) DestroyWindow(window);
if(IsWindow(anchor)) SetFocus(anchor);
return state.result;
}
void showFarHistory(HWND dialog,int fieldId,const std::vector<FarHistoryEntry> &history,
FarDropDownPalette palette)
{
showHistoryPopup(dialog,fieldId,history,palette);
}
void textWindowOwnerClosed()
{
filesOwner=nullptr;
textOwnerClosed=true;
quitWhenFilesWindowsClose();
}
void standaloneFilesWindowOpened()
{
++standaloneFilesWindows;
}
void standaloneFilesWindowClosed()
{
if(standaloneFilesWindows) --standaloneFilesWindows;
quitWhenFilesWindowsClose();
}
bool cycleTextWindows(HWND current,bool reverse)
{
if(!current) return false;
std::vector<HWND> windows;
if(filesOwner && IsWindowVisible(filesOwner)) windows.push_back(filesOwner);
for(const auto window:textWindowOrder)
if(IsWindowVisible(window)) windows.push_back(window);
if(windows.size()<2) return false;
const auto from=std::find(windows.begin(),windows.end(),current);
if(from==windows.end()) return false;
const auto index=static_cast<size_t>(from-windows.begin());
const auto step=reverse?windows.size()-1:1;
const auto target=windows[(index+step)%windows.size()];
if(IsIconic(target)) ShowWindow(target,SW_RESTORE);
SetForegroundWindow(target);
if(target!=filesOwner) SendMessageW(target,WM_SETFOCUS,0,0);
return true;
}
HWND findOpenDocument(const std::filesystem::path &path,std::string_view id)
{
const auto identity=documentIdentity(path,id);
struct Search
{
COPYDATASTRUCT query;
HWND match{};
} search{{openDocumentQuery,static_cast<DWORD>(identity.size()*sizeof(wchar_t)),
const_cast<wchar_t *>(identity.data())}};
EnumWindows([](HWND window,LPARAM parameter)->BOOL
{
wchar_t name[40]{};
if(!GetClassNameW(window,name,40) || lstrcmpW(name,windowClass)!=0) return TRUE;
auto &search=*reinterpret_cast<Search *>(parameter);
DWORD_PTR matched{};
if(SendMessageTimeoutW(window,WM_COPYDATA,0,reinterpret_cast<LPARAM>(&search.query),
SMTO_ABORTIFHUNG|SMTO_BLOCK,200,&matched) && matched)
{
search.match=window;
return FALSE;
}
return TRUE;
},reinterpret_cast<LPARAM>(&search));
return search.match;
}
bool registerTextWindowClass(HINSTANCE instance)
{
static const bool registered=[instance]
{
WNDCLASSW type{};
type.hInstance=instance;
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
type.hIcon=LoadIconW(instance,MAKEINTRESOURCEW(1));
type.lpfnWndProc=TextWindow::procedure;
type.lpszClassName=windowClass;
return Scintilla_RegisterClasses(instance) && RegisterClassW(&type);
}();
return registered;
}
HWND createQuickView(HWND owner,TextDialogs dialogs)
{
const auto instance=GetModuleHandleW(nullptr);
if(!registerTextWindowClass(instance)) return nullptr;
auto state=std::make_shared<TextWindow>(std::filesystem::path{},false,dialogs,nullptr,
std::string_view{},TextOpenOptions{},true);
return CreateWindowExW(0,windowClass,L"Quick View",WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,
0,0,0,0,owner,reinterpret_cast<HMENU>(158),instance,&state);
}
void previewQuickViewFile(HWND window,const std::filesystem::path &path)
{
if(const auto preview=textWindows.find(window);preview!=textWindows.end())
preview->second->previewFile(path);
}
std::optional<AppearanceArea> textWindowAppearanceArea(HWND window)
{
const auto entry=textWindows.find(window);
if(entry==textWindows.end()) return {};
return entry->second->appearanceArea();
}
void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff)
{
if(const auto preview=textWindows.find(window);preview!=textWindows.end())
preview->second->previewEmbeddedText(title,contents,diff);
}
ImageViewStyle imageViewStyle(TextDialogs dialogs,bool edit=false)
{
const auto font=scaledDocumentFont(dialogs,edit);
const auto colors=resolvedTextProfile(loadTextPreferences(),edit).colors;
return {font.font,font.tenthsOfPoint,colors[0],colors[1],colors[2],colors[3],colors[4]};
}
HWND createImageQuickView(HWND owner,TextDialogs dialogs)
{
return createImageView(owner,true,imageViewStyle(dialogs),{},{});
}
void previewImageQuickViewFile(HWND window,const std::filesystem::path &path)
{
showImageViewFile(window,path);
}
void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const std::filesystem::path &path,
TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source,const ImageEditDialogs *editor,
const ImageWindowSession *session)
{
try
{
const auto backend=source?std::optional(*source):peer?std::optional(lanTextSource(*peer)):std::nullopt;
ImageLoad load;
ImageLoadRetry retry;
if(backend)
{
const auto reader=[&](bool elevated) -> ImageLoad
{
return [backend=*backend,elevated](const std::filesystem::path &original,std::stop_token stop)
{
RemoteTextFile file(backend,original);
file.download(false,[&](uint64_t,uint64_t){return !stop.stop_requested();},imageSourceLimit,elevated);
return decodeImage(file.cache,original,stop);
};
};
load=reader(false);
if(backend->elevation)
{
retry.load=reader(true);
retry.approve=[approve=backend->elevation->approve](HWND window,
const std::filesystem::path &file,const std::exception &failure)
{
return dynamic_cast<const RemoteAccessDenied*>(&failure) && approve(window,file,false);
};
}
}
if(!textWindows.contains(owner)) filesOwner=owner;
const auto window=createImageView(owner,false,imageViewStyle(dialogs,editor!=nullptr),std::move(images),path,std::move(load),
[](HWND closed) {
std::erase(textWindowOrder,closed);
quitWhenFilesWindowsClose();
},std::move(retry),editor);
if(!window) throw std::runtime_error(editor?"Could not open the image editor.":"Could not open the image viewer.");
textWindowOrder.push_back(window);
const auto instance=GetModuleHandleW(nullptr);
const int iconId=editor?IDI_FILES_EDITOR:IDI_FILES_VIEWER;
const auto icon=LoadImageW(instance,MAKEINTRESOURCEW(iconId),IMAGE_ICON,0,0,LR_SHARED|LR_DEFAULTSIZE);
if(icon) SendMessageW(window,WM_SETICON,ICON_BIG,reinterpret_cast<LPARAM>(icon));
setFileWindowTaskbar(window,iconId,editor?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer");
if(session) restoreImageWindowSession(window,*session);
ShowWindow(window,session?restoreDocumentPlacement(window,owner,session->bounds,session->maximized):
IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
SetFocus(window);
}
catch(const std::exception &error)
{
if(!session) dialogs.message(owner,wide(error.what()).c_str());
else log(L"Restore Files image: "+wide(error.what()));
}
}
static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options,
const nlohmann::json *session=nullptr)
{
HWND created{};
if(!edit && !options.draft && !options.hex && !options.line && isImagePath(path))
{
openImageWindow(owner,{path},path,dialogs,nullptr,backend);
return;
}
try
{
if(!textWindows.contains(owner)) filesOwner=owner;
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 || options.hex || options.line?nullptr:
findOpenDocument(original,backend?backend->id:""))
{
if(dialogs.confirmExisting(owner) && IsWindow(existing))
{
if(IsIconic(existing)) ShowWindowAsync(existing,SW_RESTORE);
SetForegroundWindow(existing);
if(const auto open=textWindows.find(existing); open!=textWindows.end())
open->second->goToFragment(fragment);
}
return;
}
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 — ":options.hex?L"Hex Viewer — ":L"Viewer — ")+
(backend?backend->name+L" · ":std::wstring{})+path.wstring();
RECT bounds{};
GetWindowRect(owner,&bounds);
const auto window=CreateWindowExW(WS_EX_APPWINDOW,windowClass,title.c_str(),
WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN,bounds.left,bounds.top,bounds.right-bounds.left,
bounds.bottom-bounds.top,nullptr,nullptr,instance,&state);
if(!window) return;
created=window;
int show=IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW;
if(session)
{
state->restoreSession(*session);
show=restoreDocumentPlacement(window,owner,readDocumentBounds(*session),session->value("maximized",false));
}
ShowWindow(window,show);
SendMessageW(window,WM_SETFOCUS,0,0);
}
catch(const std::exception &error)
{
if(!session) dialogs.message(owner,wide(error.what()).c_str());
else
{
if(created) DestroyWindow(created);
log(L"Restore Files document: "+wide(error.what()));
}
}
}
constexpr wchar_t localSessionKey[]=L"LocalDocumentsV1";
void saveLocalDocumentSession(const wchar_t *registryKey,bool enabled)
{
if(!enabled)
{
RegDeleteKeyValueW(HKEY_CURRENT_USER,registryKey,localSessionKey);
return;
}
auto session=nlohmann::json::array();
for(const auto window:textWindowOrder)
{
if(session.size()>=128) break;
if(const auto found=textWindows.find(window);found!=textWindows.end())
{
auto state=found->second->sessionState();
if(!state.is_null()) session.push_back(std::move(state));
}
else if(const auto image=imageWindowSession(window))
{
nlohmann::json state{{"path",utf8(image->path.native())},{"editor",image->editor},{"image",true},
{"fit",image->fit},{"zoom",image->zoom},{"x",image->x},{"y",image->y}};
writeDocumentPlacement(state,window);
session.push_back(std::move(state));
}
}
const auto text=session.dump();
if(text.size()<=1024*1024)
RegSetKeyValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,REG_BINARY,text.data(),static_cast<DWORD>(text.size()));
}
void restoreLocalDocumentSession(HWND owner,TextDialogs dialogs,const wchar_t *registryKey,
const ImageEditDialogs &imageEditor)
{
DWORD bytes{};
if(RegGetValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
!bytes || bytes>1024*1024) return;
std::string text(bytes,'\0');
if(RegGetValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,RRF_RT_REG_BINARY,nullptr,text.data(),&bytes)!=ERROR_SUCCESS)
return;
const auto session=nlohmann::json::parse(text.begin(),text.begin()+bytes,nullptr,false);
if(!session.is_array()) return;
for(size_t i=0;i<std::min<size_t>(128,session.size());++i)
{
try
{
const auto &state=session[i];
const std::filesystem::path path=wide(state.at("path").get<std::string>());
if(!isLocalDocumentPath(path)) continue;
const auto attributes=GetFileAttributesW(path.c_str());
if(attributes==INVALID_FILE_ATTRIBUTES || (attributes&FILE_ATTRIBUTE_DIRECTORY)) continue;
const bool editor=state.value("editor",false);
if(state.value("image",false))
{
if(!isImagePath(path) || (editor && !isEditableImagePath(path))) continue;
ImageWindowSession image{path,editor,state.value("fit",true),state.value("zoom",1.0),
state.value("x",0.0),state.value("y",0.0),readDocumentBounds(state),state.value("maximized",false)};
openImageWindow(owner,{path},path,dialogs,nullptr,nullptr,editor?&imageEditor:nullptr,&image);
}
else openTextWindowImpl(owner,path,editor,dialogs,nullptr,{},true,{.hex=state.value("hex",false)},&state);
}
catch(const std::exception &error) {log(L"Restore Files document: "+wide(error.what()));}
}
}
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const lan::FilesPeer *peer,std::string_view fragment,bool newWindow,TextOpenOptions options)
{
const auto backend=peer?std::optional(lanTextSource(*peer)):std::nullopt;
openTextWindowImpl(owner,path,edit,dialogs,backend?&*backend:nullptr,fragment,newWindow,options);
}
void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
const RemoteTextSource &source,std::string_view fragment,bool newWindow,TextOpenOptions options)
{
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());}
}
}