#include "files_text_window.h" #include "files_text_preferences.h" #include "files_menu_paint.h" #include "files_history_date.h" #include "files_text_document.h" #include "files_text_language.h" #include "platform.h" #include "lan_files.h" #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 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 (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}}); 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, 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; bool done{}; int rowTop() const { return inset+1+rowHeight/2; } int bottomMargin() const { return inset+1+rowHeight/4; } 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 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 LONG scrollWidth=static_cast(rows.size())>visible?rowHeight/2:0; const LONG rowRight=scrollWidth?bounds.right-scrollWidth: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(scrollWidth) { RECT up{rowRight,rowTop(),bounds.right,rowTop()+rowHeight}; RECT down{rowRight,y-rowHeight,bounds.right,y}; DrawTextW(dc,L"▲",1,&up,DT_SINGLELINE|DT_CENTER|DT_VCENTER); DrawTextW(dc,L"▼",1,&down,DT_SINGLELINE|DT_CENTER|DT_VCENTER); RECT track{up.left,up.bottom,up.right,down.top}; for(LONG line=track.top;line(rows.size())-visible); RECT thumb{track.left,thumbY,track.right,std::min(track.bottom,thumbY+rowHeight)}; SetDCBrushColor(dc,palette.text); FillRect(dc,&thumb,brush); } } }; 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->step(-1); break; case VK_DOWN: state->step(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)}; 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=static_cast(state->rows.size())>state->visible && point.x>=bounds.right-state->rowHeight/2; if(scroll && message==WM_LBUTTONDOWN) state->top=std::clamp(state->top+(offsetvisible/2?-1:1),0, static_cast(state->rows.size())-state->visible); 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{}; ~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) { 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); 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")}; 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; 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(); } class TextWindow { public: TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const lan::FilesPeer *peer) : original(std::move(path)), peerId(peer?peer->id:""), filename(original.filename().wstring()), edit(editable), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()), search{dialogs} { if (peer) remote=std::make_unique(RemoteTextFile{*peer,original}); else document=std::make_unique(original,edit); 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); HWND window{}, editor{}; bool handleKey(const MSG &message); const 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{}; 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{}; std::atomic cancelOpen{}; std::future opening; std::future saving; static constexpr UINT_PTR saveTimer = 1; static constexpr UINT_PTR openTimer = 2; static constexpr UINT trimUndo = WM_APP + 1; 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); } 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 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, 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"); 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); } void TextWindow::installLexer() { lexer = createTextLexer(language); send(SCI_SETILEXER, 0, reinterpret_cast(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 profile = loadTextPreferences().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; createMenu(); installLexer(); loadPage(0); } 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; stagePage(); if (!stagedDirty && !uploadPending) { if (closeWhenDone) DestroyWindow(window); return; } pendingCaret = send(SCI_GETCURRENTPOS); 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] { const auto reopened=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 reopened = saving.get(); stagedDirty = false; 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 (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 (uploadPending || (currentChanged() ? document->modifiedWith(page, pageText()) : stagedDirty)) { const auto answer = search.style.confirmSave(window); if (answer == IDCANCEL) return; if (answer == IDYES) { saveFile(true); return; } if (answer != IDNO) return; } DestroyWindow(window); } 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); invalidate(); } 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(GetStockObject(DC_BRUSH)); SetDCBrushColor(dc, color(TextColor::background)); FillRect(dc, &client, brush); SetDCBrushColor(dc, color(TextColor::chromebg)); RECT menuBar{0, 0, client.right, row}; RECT top{0, row, client.right, 2 * row}; RECT bottom{0, client.bottom - row, client.right, client.bottom}; FillRect(dc, &top, brush); FillRect(dc, &bottom, brush); FillRect(dc, &menuBar, brush); const auto chromeFont = createChromeFont(); 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); const auto position = send(SCI_GETCURRENTPOS); const auto line = send(SCI_LINEFROMPOSITION, position) + 1; const auto column = send(SCI_GETCOLUMN, position) + 1; const auto displayLanguage = textLanguageLabel(language); auto status = filename + (edit ? L" (Edit)" : L" (View)") + (dirty() ? L" *" : L"") + L" │ " + (document?document->encodingName():L"Loading…") + L" │ " + displayLanguage + L" │ Ln " + std::to_wstring(line) + L":" + std::to_wstring(column); if (pageTotal > 1) status += L" │ Page " + std::to_wstring(page + 1) + L"/" + std::to_wstring(pageTotal) + L" @ " + std::to_wstring(pageOffset); status += L" │ " + std::to_wstring(fileSize) + L" B"; const auto hints = busy() ? L"Saving…" : insertRejected ? L"Page edit limit: 8 MiB" : edit ? L"F2 Save F3 Find next F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close" : L"F3 Find next F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close"; constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX; top.left += scale(12); top.right -= scale(12); if (top.left < top.right) DrawTextW(dc, status.c_str(), -1, &top, format | DT_RIGHT); DrawTextW(dc, hints, -1, &bottom, format); SelectObject(dc, previous); DeleteObject(chromeFont); 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 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: openFind(); return; case findNext: find((search.flags & FR_DOWN) != 0, search.flags); 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) { 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 (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); } invalidate(); 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: invalidate(); 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))) { 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_F9) id = 600; if (key == VK_ESCAPE || key == VK_F10) id = close; 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); } 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; } 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->layout(); ShowWindow(self->editor,SW_SHOWNA); 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->layout(); return 0; } case WM_SETFOCUS: SetFocus(self->editor); 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(); 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: self->releaseMenu(); return 0; case WM_NCDESTROY: self->window=nullptr; textWindows.erase(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() { textOwnerClosed=true; if(textWindows.empty()) PostQuitMessage(0); } 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) { try { 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=findOpenDocument(original,peer)) { if(dialogs.confirmExisting(owner) && IsWindow(existing)) { if(IsIconic(existing)) ShowWindowAsync(existing,SW_RESTORE); SetForegroundWindow(existing); } 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); 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; IPropertyStore *properties{}; if(SUCCEEDED(SHGetPropertyStoreForWindow(window,IID_PPV_ARGS(&properties)))) { static unsigned sequence{}; auto identity=L"HrynCo.KSwitcher.Files.Text."+std::to_wstring(GetCurrentProcessId())+ L"."+std::to_wstring(++sequence); PROPVARIANT value{}; value.vt=VT_LPWSTR; value.pwszVal=identity.data(); properties->SetValue(PKEY_AppUserModel_ID,value); properties->Commit(); properties->Release(); } ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW); SetFocus(state->editor); } catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());} } }