#include "files_text_window.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 #include #include #include #include #include #include #include #include #include #include #include "../vendor/json.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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(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::copy(documentColors.begin(), documentColors.end(), prefs.colors.begin()); } if (data.contains("menuColors")) { const auto menuColors = data.at("menuColors").get>(); std::copy(menuColors.begin(), menuColors.end(), prefs.colors.begin() + documentColorCount); } for (auto &color : prefs.colors) color &= 0xffffff; } } 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(); if (const auto size=markdown->find("fontSize");size!=markdown->end() && size->is_number_unsigned() && *size>=8 && *size<=72) settings.markdown.fontSize=size->get(); if (const auto family=markdown->find("font");family!=markdown->end() && family->is_string()) settings.markdown.font=wide(family->get()).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()); if (name.empty() || name.size() > maxTextPaletteName) continue; auto colors = entry.at("colors").get(); for (auto &color : colors) color &= 0xffffff; settings.schemes.push_back({std::move(name), colors}); } catch (const std::exception &) {} } 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(p.colors.begin(), p.colors.begin() + documentColorCount)}, {"menuColors", std::vector(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)}}; 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(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, 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); } INT_PTR CALLBACK pageDialog(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) { if (message == WM_INITDIALOG) { auto *prompt = reinterpret_cast(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(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(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 readFarHistory(FarHistoryKind kind) { std::vector 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()); auto text = wide(item["text"].get()); 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 history; FarDropDownPalette historyPalette{}; }; struct FarPopup { struct Row { std::wstring_view text; int index; }; std::vector 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(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(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(rows.size())) break; if(rows[row].index<0) continue; select(row); --count; } } void stepMenu(int direction) { select(adjacentMenuRow(current,static_cast(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(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(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(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(reinterpret_cast(lp)->lpCreateParams)); auto *state=reinterpret_cast(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(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(state->rows.size())); break; case VK_END: state->step(1,static_cast(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(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() && offsetvisible) { 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 &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(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(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(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; } struct RemoteTextFile { lan::FilesPeer peer; std::filesystem::path original,cache; lan::FileRevision revision{}; bool editable{}; ~RemoteTextFile() { if(cache.empty()) return; std::error_code ignored; std::filesystem::remove(cache,ignored); std::filesystem::remove(cache.parent_path(),ignored); } static lan::FileRevision stat(lan::FilesConnection &host,const std::filesystem::path &path) { const auto reply=host.call(lan::fileRequest("stat",path)); lan::checkFileReply(reply); return {reply.at("size").get(),reply.at("modified").get()}; } void download(bool edit,const lan::FileProgress &progress,uint64_t sizeLimit=UINT64_MAX) { 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 LAN 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 LAN file."); cache=directory/original.filename(); lan::FilesConnection source(&peer),target; const auto info=source.call(lan::fileRequest("stat",original)); lan::checkFileReply(info); editable=info.value("editCommit",false) && !(info.at("attributes").get()&FILE_ATTRIBUTE_READONLY); if(edit && !info.value("editCommit",false)) throw std::runtime_error("Update KSwitcher on the remote computer to edit this file."); if(edit && (info.at("attributes").get()&FILE_ATTRIBUTE_READONLY)) throw std::runtime_error("The remote file is read-only."); revision={info.at("size"),info.at("modified")}; if(revision.size>sizeLimit) throw std::runtime_error("The image is too large to preview."); try { lan::streamFile(source,target,peer.id,original,cache,revision.size,revision.modified,false,false,progress); } catch(...) { target.call({{"action","abort"}}); throw; } } void upload() { lan::FilesConnection source,target(&peer); const auto local=stat(source,cache); try { lan::streamFile(source,target,"Files editor",cache,original,local.size,local.modified,true,false,{},&revision); } 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; } revision=local; } }; class TextWindow; std::map> textWindows; std::vector textWindowOrder; HWND filesOwner{}; bool textOwnerClosed=false; 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()) return {}; const auto high=hex(url[i+1]), low=hex(url[i+2]); if(high<0 || low<0) return {}; decoded+=static_cast(16*high+low); i+=2; } if(decoded.empty() || decoded.find_first_of(":\0",0,2)!=decoded.npos) return {}; const std::filesystem::path relative(wide(decoded)); if(relative.has_root_path()) return {}; return (document.parent_path()/relative).lexically_normal(); } std::string markdownImage(const std::filesystem::path &path,const lan::FilesPeer *peer, const std::shared_ptr> &cancel) { auto extension=path.extension().wstring(); std::transform(extension.begin(),extension.end(),extension.begin(),::towlower); const std::map 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 fetched; if(peer) { if(*cancel) return {}; fetched.emplace(RemoteTextFile{*peer,path}); fetched->download(false,[&](uint64_t,uint64_t){return !*cancel;},limit); source=fetched->cache; } if(*cancel) return {}; std::ifstream input(source,std::ios::binary|std::ios::ate); const auto size=input.tellg(); if(size<=0 || static_cast(size)>limit) return {}; std::string bytes(static_cast(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(bytes.data()); if(!CryptBinaryToStringA(data,static_cast(bytes.size()),flags,nullptr,&length)) return {}; std::string encoded(length,'\0'); if(!CryptBinaryToStringA(data,static_cast(bytes.size()),flags,encoded.data(),&length)) return {}; encoded.resize(length); return "data:image/"+type->second+";base64,"+encoded; } class TextWindow { public: TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const lan::FilesPeer *peer, std::string_view fragment,TextOpenOptions options) : original(std::move(path)), peerId(peer?peer->id:""), filename(original.filename().wstring()), edit(editable), draft(options.draft), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()), search{dialogs}, previewFragment(fragment) { if (peer) remote=std::make_unique(RemoteTextFile{*peer,original}); else document=std::make_unique(draft?std::filesystem::path{}:original,edit,options.encoding); if(options.encoding!=TextEncoding::automatic) { newFormat.encoding=options.encoding; newFormat.bom=options.encoding==TextEncoding::utf16le || options.encoding==TextEncoding::utf16be; } for (int index = 0; index < GetLexerCount(); ++index) { char name[128]{}; 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(smallIcon) DestroyIcon(smallIcon); if(largeIcon) DestroyIcon(largeIcon); } HWND window{}, editor{}; bool handleKey(const MSG &message); void goToFragment(std::string_view fragment); std::filesystem::path original; const std::string peerId; private: std::unique_ptr remote; std::unique_ptr document; std::wstring filename; bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{}; bool draft{}; TextSaveFormat newFormat; std::filesystem::path pendingSavePath; HICON smallIcon{},largeIcon{}; TextPreferences prefs; TextWindowFont filesFont; TextLanguage automatic, language; std::vector lexers; FindPrompt search; std::string cleanPage; std::deque menuLabels; std::vector menuBarLabels; HBRUSH menuSurface{}; HMENU menuRoot{}; std::array 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{}; bool switchAfterSave{}; FilesTerminalView preview; bool previewWanted{}, previewVisible{}; ULONGLONG previewDeadline{}; ULONGLONG nextFileCheck{}; struct FileStamp { uint64_t writeTime, fileIndex, size; DWORD volume; bool operator==(const FileStamp &) const = default; }; std::optional previewStamp; 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 navigationHistory; size_t navigationIndex{}; std::optional destinationIndex; PreviewLocation destination; std::future> navigation; std::shared_ptr> cancelNavigation; bool restoreScroll{}; std::deque previewLinks; struct ImageRequest { std::filesystem::path path; uint64_t index{}, generation{}; }; std::deque imageQueue; std::future image; ImageRequest activeImage; std::shared_ptr> cancelImages; std::atomic cancelOpen{}; std::future opening; std::future saving; 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 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; 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(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(send(SCI_GETLENGTH)); return {reinterpret_cast(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(); 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 loadPage(uint64_t index); void stagePage(); void go(uint64_t index); void saveFile(bool closeWhenDone); void finishSave(); void requestClose(); void toggleMode(); void changeMode(); bool needsSave() const; bool canPreview() const; void updatePreview(); void stopPreview(bool refresh=true,bool keepBrowser=false); void renderPreview(bool keepPosition=false); void applyMarkdownPreferences(const MarkdownPreferences &preferences); std::optional previewFileStamp() const; void refreshPreview(); void cancelPreviewImages(); void previewMessage(const std::wstring &value); void navigatePreview(PreviewLink request); void finishNavigation(); void showLocation(std::unique_ptr 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 ¬ice); }; 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(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"); addItem(file, switchMode, edit ? L"&View\tF6" : L"&Edit\tF6"); addItem(file, close, L"&Close\tF10"); const auto actions = addGroup(menu, edit ? L"&Edit" : L"&Selection"); if (edit) { 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) { addItem(navigation, historyBack, L"&Back\tAlt+Left"); addItem(navigation, historyForward, L"F&orward\tAlt+Right"); AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr); } addItem(navigation, findText, L"&Find on page…\tCtrl+F"); addItem(navigation, findNext, L"Find &next\tF3"); AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr); addItem(navigation, previousPage, L"&Previous page\tCtrl+PgUp"); addItem(navigation, nextPage, L"N&ext page\tCtrl+PgDn"); addItem(navigation, firstPage, L"F&irst page\tCtrl+Shift+Home"); addItem(navigation, lastPage, L"&Last page\tCtrl+Shift+End"); addItem(navigation, goToPage, L"&Go to page…\tF5"); const auto syntax = addGroup(menu, L"S&yntax"); addItem(syntax, lexerAuto, L"&Automatic"); addItem(syntax, lexerPlain, L"&Plain text"); constexpr std::wstring_view groups[] = {L"A–&F", L"G–&L", L"M–&R", L"S–&Z"}; const wchar_t lastLetters[] = {L'f', L'l', L'r', L'z'}; HMENU group{}; size_t groupIndex{}; std::wstring assignedKeys; for (size_t i = 0; i < lexers.size(); ++i) { 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(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(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(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(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(&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(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(label.title.size()), &title); if (!label.shortcut.empty()) GetTextExtentPoint32W(dc, label.shortcut.c_str(), static_cast(label.shortcut.size()), &shortcut); SelectObject(dc, previous); DeleteObject(font); ReleaseDC(window, dc); item.itemWidth = static_cast(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(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(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(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(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 = settings.profiles[edit]; const auto font = search.style.readFont(); 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) { 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(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); send(SCI_SETWRAPMODE, prefs.wrap ? SC_WRAP_WORD : SC_WRAP_NONE); send(SCI_SETVIEWWS, prefs.whitespace ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE); send(SCI_SETVIEWEOL, prefs.whitespace); applyLineEnding(); updateLineNumberMargin(); layout(); invalidate(); } void TextWindow::updateLineNumberMargin() { LRESULT width{}; if (prefs.numbers) { const auto digits = std::to_string(send(SCI_GETLINECOUNT)).size(); const std::string sample(digits, '9'); width = send(SCI_TEXTWIDTH, STYLE_LINENUMBER, reinterpret_cast(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) { auto data = document->readPage(index); const auto offset = document->boundary(index); page = index; pageOffset = offset; pageTotal = document->pages(); fileSize = document->size(); 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; loading = true; send(SCI_SETREADONLY, FALSE); send(SCI_SETUNDOCOLLECTION, FALSE); send(SCI_CLEARALL); send(SCI_ADDTEXT, data.size(), reinterpret_cast(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); cleanPage = std::move(data); loading = false; updateLineNumberMargin(); undoBytes = 0; insertRejected = false; invalidate(); } 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() { automatic=detectLanguage(original,document->readPage(0)); language=automatic; if(canPreview()) ShowWindow(editor,SW_HIDE); releaseMenu(); createMenu(); installLexer(); loadPage(0); if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment}); updatePreview(); } 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(remote->cache,edit); initializeDocument(); invalidate(); } catch(const std::exception &error) { if(!cancelOpen) search.style.message(window,wide(error.what()).c_str()); DestroyWindow(window); } } void TextWindow::saveFile(bool closeWhenDone) { if (busy() || !edit) return; auto destination=original; if(draft && !search.style.saveOptions(window,destination,newFormat)) return; stagePage(); if (!draft && !stagedDirty && !uploadPending) { if (closeWhenDone) DestroyWindow(window); else if (std::exchange(switchAfterSave, false)) changeMode(); return; } pendingCaret = send(SCI_GETCURRENTPOS); if(draft) pendingSavePath=destination; closeAfterSave = closeWhenDone; if (!SetTimer(window, saveTimer, 75, nullptr)) throw std::runtime_error("Cannot start the save timer."); send(SCI_SETREADONLY, TRUE); try { saving=std::async(std::launch::async,[this,destination=std::move(destination)] { const auto reopened=draft?document->saveNew(destination,newFormat):document->save(); if(remote) { uploadPending=true; remote->upload(); 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); send(SCI_SETREADONLY, !edit); const auto change = std::exchange(switchAfterSave, false); const auto reopened = saving.get(); stagedDirty = false; const bool created=std::exchange(draft,false); if(created) { original=std::move(pendingSavePath); filename=original.filename().wstring(); navigationHistory.clear(); updateTitle(); } if (!reopened) { search.style.message(window, L"The file was saved. Reopen it to continue editing."); DestroyWindow(window); return; } if (closeAfterSave) { DestroyWindow(window); return; } if (change) { changeMode(); return; } if(created) { initializeDocument(); send(SCI_GOTOPOS,std::min(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(pendingCaret, send(SCI_GETLENGTH))); } void TextWindow::requestClose() { if (opening.valid()) { cancelOpen=true; return; } if (busy()) return; if (needsSave()) { const auto answer = search.style.confirmSave(window,draft); if (answer == IDCANCEL) return; if (answer == IDYES) { saveFile(true); return; } if (answer != IDNO) return; } DestroyWindow(window); } bool TextWindow::needsSave() const { return uploadPending || (currentChanged() ? document->modifiedWith(page, pageText()) : stagedDirty); } void TextWindow::toggleMode() { if (busy() || navigation.valid()) return; if(draft) return; if (edit && needsSave()) { const auto answer = search.style.confirmSave(window,false); if (answer == IDYES) { switchAfterSave = true; try { saveFile(false); } catch (...) { switchAfterSave = false; throw; } return; } if (answer != IDNO) return; // The local LAN cache may already contain changes from a failed upload. if (uploadPending) { auto refreshed = std::make_unique(RemoteTextFile{remote->peer,original}); refreshed->download(false,{}); auto replacement = std::make_unique(refreshed->cache,false); document.reset(); remote = std::move(refreshed); document = std::move(replacement); uploadPending = false; } } changeMode(); } void TextWindow::changeMode() { if (!edit && remote && !remote->editable) throw std::runtime_error("The remote file does not support editing."); auto replacement = std::make_unique(remote ? remote->cache : original, !edit); const auto caret = send(SCI_GETCURRENTPOS); document = std::move(replacement); edit = !edit; if(canPreview()) ShowWindow(editor,SW_HIDE); prefs = loadTextPreferences().profiles[edit]; releaseMenu(); createMenu(); installLexer(); loadPage(std::min(page, document->pages() - 1)); send(SCI_GOTOPOS, std::min(caret, send(SCI_GETLENGTH))); updateTitle(); updateIcons(GetDpiForWindow(window)); updateTaskbarGroup(); updatePreview(); layout(); focusContent(); } void TextWindow::updateTitle() { const auto title = std::wstring(edit ? L"Editor — " : L"Viewer — ") + (remote ? remote->peer.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 ¤t,WPARAM kind,int width,int height) { const auto icon=static_cast(LoadImageW(instance,resource,IMAGE_ICON, GetSystemMetricsForDpi(width,dpi),GetSystemMetricsForDpi(height,dpi),0)); if(!icon) return; SendMessageW(window,WM_SETICON,kind,reinterpret_cast(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 TextWindow::updateTaskbarGroup(bool closing) { auto icon=closing?std::wstring{}:executable()+L",-"+std::to_wstring(edit?IDI_FILES_EDITOR:IDI_FILES_VIEWER); auto identity=std::wstring(edit?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer"); IPropertyStore *properties{}; if(FAILED(SHGetPropertyStoreForWindow(window,IID_PPV_ARGS(&properties)))) return; PROPVARIANT value{}; if(!closing) { value.vt=VT_LPWSTR; value.pwszVal=icon.data(); } properties->SetValue(PKEY_AppUserModel_RelaunchIconResource,value); if(!closing) value.pwszVal=identity.data(); // Setting the group ID tells Explorer to refresh the taskbar button. properties->SetValue(PKEY_AppUserModel_ID,value); properties->Release(); } bool TextWindow::canPreview() const { return !edit && automatic.lexer=="markdown" && document && document->size()<=TextDocument::editLimit; } void TextWindow::updatePreview() { if(!canPreview()) { stopPreview(true,true); return; } previewWanted=true; previewDeadline=GetTickCount64()+8000; previewStamp=previewFileStamp(); nextFileCheck=GetTickCount64()+350; cancelImages=std::make_shared>(false); if(!SetTimer(window,previewTimer,50,nullptr)) { stopPreview(); return; } if(preview.initialized()) renderPreview(); else if(!preview.create(window,[this](const auto &value){previewMessage(value);}, [this]{PostMessageW(window,previewFailed,0,0);},true,[this](UINT key) { const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0; const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0; 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==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_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false; PostMessageW(window,WM_COMMAND,key==VK_F6?switchMode:key==VK_ESCAPE?previewEscape:close,0); return true; })) stopPreview(); layout(); } void TextWindow::stopPreview(bool refresh,bool keepBrowser) { KillTimer(window,previewTimer); previewWanted=previewVisible=false; previewStamp.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 TextWindow::previewFileStamp() const { if(remote) return {}; const auto file=CreateFileW(original.c_str(),FILE_READ_ATTRIBUTES, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr); if(file==INVALID_HANDLE_VALUE) return {}; BY_HANDLE_FILE_INFORMATION state{}; const auto found=GetFileInformationByHandle(file,&state); CloseHandle(file); if(!found) return {}; const auto combine=[](DWORD high,DWORD low){return (uint64_t{high}<<32)|low;}; return FileStamp{combine(state.ftLastWriteTime.dwHighDateTime,state.ftLastWriteTime.dwLowDateTime), combine(state.nFileIndexHigh,state.nFileIndexLow), combine(state.nFileSizeHigh,state.nFileSizeLow),state.dwVolumeSerialNumber}; } void TextWindow::renderPreview(bool keepPosition) { applyMarkdownPreferences(loadTextPreferences().markdown); previewDeadline=GetTickCount64()+30000; std::string text; for(uint64_t index=0;indexpages();++index) text+=document->readPage(index); if(!remote) document->releaseReadHandle(); nlohmann::json message{{"action","render"},{"text",std::move(text)}, {"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)}, {"keepPosition",keepPosition}}; if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll; 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; preview.post(wide(nlohmann::json{{"action","appearance"},{"width",preferences.width}, {"fontSize",preferences.fontSize},{"font",utf8(preferences.font)}}.dump())); } void TextWindow::refreshPreview() { if(remote || !previewVisible || navigation.valid() || GetTickCount64()(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>(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::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(); if(action=="cycle") { PostMessageW(window,cycleWindow,message.value("reverse",false),0); return; } if(action=="failed") { PostMessageW(window,previewFailed,0,0); return; } if(action=="rendered") { PostMessageW(window,previewRendered,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(); 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(),message.at("generation").get()}); } } 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",navigationIndex>0}, {"forward",navigationIndex+1peer: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>(false); std::packaged_task()> task( [peer=remote->peer,path=destination.path,cancel] { auto file=std::make_unique(RemoteTextFile{peer,path}); file->download(false,[cancel](uint64_t,uint64_t){return !*cancel;}); return file; }); if(!SetTimer(window,navigationTimer,75,nullptr)) throw std::runtime_error("Cannot start the LAN navigation timer."); try { auto result=task.get_future(); std::thread(std::move(task)).detach(); navigation=std::move(result); 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 fetched) { const bool sameDocument=destination.path==original; std::unique_ptr next; if(!sameDocument) next=std::make_unique(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) { 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 task( [path=activeImage.path,peer=remote?std::optional(remote->peer):std::nullopt,cancel=cancelImages] { return markdownImage(path,peer?&*peer:nullptr,cancel); }); image=task.get_future(); std::thread(std::move(task)).detach(); } void TextWindow::layout() { if (!editor) return; RECT area{}; GetClientRect(window, &area); const auto row = chromeHeight(); MoveWindow(editor, 0, 2 * row, area.right, std::max(0L, area.bottom - 3 * row), TRUE); preview.layout({0,2*row,area.right,std::max(2*row,area.bottom-row)},previewWanted); ShowWindow(editor,document && !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(GetStockObject(DC_BRUSH))); SetBkMode(target,TRANSPARENT); SetTextColor(target,foreground); row.left+=inset; row.right-=inset; if(row.left(GetStockObject(DC_BRUSH)); SetDCBrushColor(dc, color(TextColor::background)); const RECT body{0,2*row,client.right,std::max(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(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(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; auto status=filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+ L" │ "+(document?document->encodingName():L"Loading…")+L" │ "+textLanguageLabel(language)+ L" │ Ln "+std::to_wstring(line)+L":"+std::to_wstring(column); if(pageTotal>1) status+=L" │ Page "+std::to_wstring(page+1)+L"/"+std::to_wstring(pageTotal)+ L" @ "+std::to_wstring(pageOffset); status+=L" │ "+std::to_wstring(fileSize)+L" B"; drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status); } const auto hints = busy() ? L"Saving…" : insertRejected ? L"Page edit limit: 8 MiB" : edit ? L"F2 Save F3 Find next F5 Go to page F6 View Ctrl+PgUp/PgDn Pages F10 Close" : previewVisible ? L"F6 Edit Ctrl+W Close" : previewWanted ? L"Rendering Markdown… Ctrl+W Close" : L"F3 Find next F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close"; constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX; 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(&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(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()) return; switch (id) { case save: saveFile(false); return; case close: requestClose(); return; case switchMode: toggleMode(); 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(&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, edit); 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 ¬ice) { 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(TextDocument::editLimit)) { send(SCI_CHANGEINSERTION, 0, reinterpret_cast("")); 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(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) { 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(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_F5 || (ctrl && key == 'G')) id = goToPage; if (key == VK_F6) id = switchMode; if (key == VK_F9) id = 600; if (key == VK_ESCAPE || key == VK_F10 || (!edit && ctrl && key=='W')) id = close; if (!edit && key==VK_BROWSER_BACK) id=historyBack; if (!edit && key==VK_BROWSER_FORWARD) id=historyForward; if (ctrl && key == 'F') id = findText; 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(lparam); const auto &state=*static_cast *>(create->lpCreateParams); state->window=window; textWindows.emplace(window,state); 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) { self->reloadPreferences(); return 0; } switch (message) { case WM_COPYDATA: { if(!lparam) return FALSE; const auto &query=*reinterpret_cast(lparam); if(query.dwData!=openDocumentQuery || !query.lpData || query.cbData>65536 || query.cbData(query.lpData),query.cbData/sizeof(wchar_t)); const auto identity=documentIdentity(self->original,self->peerId); return CompareStringOrdinal(candidate.data(),static_cast(candidate.size()), identity.data(),static_cast(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."); 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(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) { SendMessageW(state->window,WM_COMMAND, GET_XBUTTON_WPARAM(wp)==XBUTTON1?historyBack:historyForward,0); return TRUE; } return DefSubclassProc(child,msg,wp,lp); },1,reinterpret_cast(self.get())); if(self->remote) { self->applyPreferences(); self->send(SCI_SETREADONLY,TRUE); if(!SetTimer(window,openTimer,75,nullptr)) throw std::runtime_error("Cannot start the LAN file timer."); self->opening=std::async(std::launch::async,[state=self.get()] { state->remote->download(state->edit,[state](uint64_t,uint64_t){return !state->cancelOpen;}); }); } else self->initializeDocument(); 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(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: self->focusContent(); return 0; case cycleWindow: cycleTextWindows(window,wparam!=0); return 0; case WM_KEYDOWN: if(self->previewWanted && !self->previewVisible) { 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: self->stopPreview(); return 0; case previewRendered: if(self->previewWanted) { self->previewVisible=true; 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(lparam), LOWORD(wparam)); case WM_MEASUREITEM: if (self->measureMenu(*reinterpret_cast(lparam))) return TRUE; break; case WM_DRAWITEM: if (self->drawMenu(*reinterpret_cast(lparam))) return TRUE; break; case WM_LBUTTONDOWN: { const POINT point{static_cast(LOWORD(lparam)), static_cast(HIWORD(lparam))}; for (size_t index = 0; index < self->menuBounds.size(); ++index) if (PtInRect(&self->menuBounds[index], point)) self->openMenu(static_cast(index)); return 0; } case WM_COMMAND: 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(lparam)->hwndFrom == self->editor) self->notify(*reinterpret_cast(lparam)); return 0; case WM_TIMER: if (wparam == saveTimer) self->finishSave(); if (wparam == openTimer) self->finishOpen(); if (wparam == previewTimer) self->pollImages(); if (wparam == navigationTimer) self->finishNavigation(); 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(-1)); self->undoBytes = 0; } return 0; case WM_DESTROY: if(self->cancelNavigation) *self->cancelNavigation=true; self->updateTaskbarGroup(true); self->stopPreview(false); self->releaseMenu(); return 0; case WM_NCDESTROY: self->window=nullptr; textWindows.erase(window); std::erase(textWindowOrder,window); if(textOwnerClosed && textWindows.empty()) PostQuitMessage(0); break; } } catch (const std::exception &error) { 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 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 &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(entries.size())-1); FarPopup state{}; state.palette=palette; state.font=reinterpret_cast(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(index)==selected) state.current=static_cast(state.rows.size()); state.rows.push_back({entry.text,static_cast(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((space-state.rowTop()-state.bottomMargin())/state.rowHeight,1, std::min(9,static_cast(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(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 &history, FarDropDownPalette palette) { showHistoryPopup(dialog,fieldId,history,palette); } void textWindowOwnerClosed() { filesOwner=nullptr; textOwnerClosed=true; if(textWindows.empty()) PostQuitMessage(0); } bool cycleTextWindows(HWND current,bool reverse) { if(!current || (current!=filesOwner && !textWindows.contains(current))) return false; std::vector 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(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,const lan::FilesPeer *peer) { const auto identity=documentIdentity(path,peer?peer->id:""); struct Search { COPYDATASTRUCT query; HWND match{}; } search{{openDocumentQuery,static_cast(identity.size()*sizeof(wchar_t)), const_cast(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(parameter); DWORD_PTR matched{}; if(SendMessageTimeoutW(window,WM_COPYDATA,0,reinterpret_cast(&search.query), SMTO_ABORTIFHUNG|SMTO_BLOCK,200,&matched) && matched) { search.match=window; return FALSE; } return TRUE; },reinterpret_cast(&search)); return search.match; } 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) { try { if(!textWindows.contains(owner)) filesOwner=owner; std::error_code error; const auto identity=peer?path.lexically_normal():std::filesystem::weakly_canonical(path,error); const auto &original=error?path:identity; if(const auto existing=newWindow?nullptr:findOpenDocument(original,peer)) { 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); 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); }(); if(!registered) throw std::runtime_error("Cannot register the text window."); auto state=std::make_shared(original,edit,dialogs,peer,fragment,options); const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+ (peer?peer->name+L" · ":std::wstring{})+path.wstring(); RECT bounds{}; 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; ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW); SendMessageW(window,WM_SETFOCUS,0,0); } catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());} } }