diff --git a/FILES-UI.md b/FILES-UI.md index a4570bb..3c95cb0 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -313,6 +313,13 @@ Warning і початковий фокус на No. - У цьому вікні F6 перемикає перегляд і редагування для поточного файла. За наявності змін перехід у перегляд пропонує Save, Discard або Cancel. Помилка збереження залишає відкритим редактор зі змінами. +- **Shift+F3** або **Commands → View as hex** відкриває файл у Hex Viewer. + **F4** у Viewer перемикає текстовий або форматований перегляд і Hex. + Hex показує 64-бітну адресу, 16 вихідних байтів у рядку й ASCII. + Нульові й недруковані байти видно в hex, а в ASCII їх позначає крапка. + Блоки по 64 КіБ перемикаються через Ctrl+Page Up, Ctrl+Page Down або F5. + Esc повертає до попереднього режиму Viewer або, якщо файл відкрито + напряму в Hex, до файлової панелі. - Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному порядку. Коли відкрито лише Files, активна панель не змінюється. diff --git a/src/files_main.cpp b/src/files_main.cpp index c130a04..dc7f9c9 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -3381,7 +3381,7 @@ void collectFolderSizes(Panel &panel) if((finished || !completed.empty()) && &panel==&panels[active]) showFileDetails(panel); } -void openSelectedText(const Panel &panel, bool edit, bool external); +void openSelectedText(const Panel &panel, bool edit, bool external,bool hex=false); void findLocalFiles(HWND owner,Panel &panel); void compareSelectedFiles(HWND owner); void createArchive(HWND owner,Panel &panel); @@ -3537,6 +3537,7 @@ void selectDrive() else if(menuIndex==2 && row==10) toggleQuickView(owner); else if(menuIndex==2 && row==11) copyFullPanelPath(owner,panels[active]); else if(menuIndex==2 && row==12) openSpaceAnalyzer(owner,panels[active]); + else if(menuIndex==2 && row==13) openSelectedText(panels[active],false,false,true); else if(menuIndex==1 && row==4) createArchive(owner,panels[active]); else { @@ -4161,7 +4162,7 @@ void openPanelImage(const Panel &panel,const fs::path &path,const ks::files::Rem panel.peer?&*panel.peer:nullptr,source); } -void openArchiveText(const Panel &panel,const fs::path &path) +void openArchiveText(const Panel &panel,const fs::path &path,bool hex=false) { const auto file=panel.archive->file; const auto member=path.lexically_relative(file); @@ -4180,11 +4181,12 @@ void openArchiveText(const Panel &panel,const fs::path &path) const auto entry=ks::files::readArchiveMember(file,relative,cache,limit,progress); return ks::files::RemoteTextRevision{entry.size,entry.modified,false}; },{}}; - if(ks::files::isImagePath(path)) openPanelImage(panel,path,&archive); - else ks::files::openRemoteTextWindow(GetParent(panel.list),path,false,textWindowDialogs(),archive); + if(!hex && ks::files::isImagePath(path)) openPanelImage(panel,path,&archive); + else ks::files::openRemoteTextWindow(GetParent(panel.list),path,false,textWindowDialogs(),archive,{}, + false,{.hex=hex}); } -void openSelectedText(const Panel &panel, bool edit, bool external) +void openSelectedText(const Panel &panel, bool edit, bool external,bool hex) { if(ftpProfileList(panel)) return; const auto row=currentPanelRow(panel); @@ -4192,7 +4194,7 @@ void openSelectedText(const Panel &panel, bool edit, bool external) if(panel.archive) { if(edit || external) setStatus(L"Archive entries are read-only. Use F5 to extract them."); - else openArchiveText(panel,panel.rows[row]); + else openArchiveText(panel,panel.rows[row],hex); return; } if((panel.peer || panel.ftp) && external) @@ -4204,16 +4206,16 @@ void openSelectedText(const Panel &panel, bool edit, bool external) if(panel.ftp) { const auto ftp=ftpTextSource(*panel.ftp); - if(!edit && ks::files::isImagePath(path)) openPanelImage(panel,path,&ftp); - else ks::files::openRemoteTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),ftp); + if(!edit && !hex && ks::files::isImagePath(path)) openPanelImage(panel,path,&ftp); + else ks::files::openRemoteTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),ftp,{},false,{.hex=hex}); return; } if(external) openPanelFile(panel,path,edit?L"edit":L"open", edit?L"No editor is registered for this file.":L"Cannot open the selected file."); - else if(!edit && ks::files::isImagePath(path)) openPanelImage(panel,path); + else if(!edit && !hex && ks::files::isImagePath(path)) openPanelImage(panel,path); else ks::files::openTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(), - panel.peer?&*panel.peer:nullptr); + panel.peer?&*panel.peer:nullptr,{},false,{.hex=hex}); } void enter(Panel &panel) @@ -7510,12 +7512,12 @@ void openMenu(HWND window, int index) L"View externally\tAlt+F3",L"Edit externally\tAlt+F4", L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel(), L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q", - L"Copy full path\tCtrl+Shift+C",L"Space Analyzer"}; + L"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3"}; } commandActions.clear(); if(index==2) { - commandActions={0,3,11,-1,1,2,4,5,8}; + commandActions={0,3,11,-1,1,13,2,4,5,8}; if(!panels[active].peer && !panels[active].ftp) { commandActions.insert(commandActions.begin()+1,9); @@ -8795,6 +8797,11 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) } continue; } + if(shift && !ctrl && message.wParam==VK_F3 && !terminalVisible && commandLineAvailable(window)) + { + if(!(message.lParam&(1LL<<30))) openSelectedText(panels[active],false,false,true); + continue; + } if(ctrl && !shift && (message.wParam=='F' || message.wParam=='C' || message.wParam=='R' || (message.wParam=='U' && !terminalVisible) || diff --git a/src/files_text_document.cpp b/src/files_text_document.cpp index 7875f9d..553d423 100644 --- a/src/files_text_document.cpp +++ b/src/files_text_document.cpp @@ -306,6 +306,58 @@ std::string TextDocument::readPage(uint64_t page) const return readOriginal(page); } +std::string TextDocument::readBytes(uint64_t offset,size_t count) const +{ + if(path_.empty() || offset>=size_ || !count) return {}; + const auto length=static_cast(std::min({count,hexPageBytes,size_-offset})); + File temporary{source_==INVALID_HANDLE_VALUE?openSource(path_,false):INVALID_HANDLE_VALUE}; + return read(source_==INVALID_HANDLE_VALUE?temporary.handle:source_,offset,length); +} + +std::string formatHexAddress(uint64_t offset) +{ + constexpr char digits[]="0123456789ABCDEF"; + std::string address(16,'0'); + for(size_t i=address.size();i;offset>>=4) address[--i]=digits[offset&15]; + return address; +} + +std::string formatHexPage(std::string_view bytes,uint64_t offset) +{ + constexpr char digits[]="0123456789ABCDEF"; + constexpr size_t rowBytes=16; + std::string formatted; + formatted.reserve(((bytes.size()+rowBytes-1)/rowBytes)*88); + for(size_t row=0;row(bytes[row+column]); + formatted+=digits[value>>4]; + formatted+=digits[value&15]; + } + else formatted+=" "; + formatted+=' '; + } + formatted+=" |"; + for(size_t column=0;column(bytes[row+column]); + formatted+=value>=0x20 && value<=0x7e?static_cast(value):'.'; + } + formatted.append(rowBytes-length,' '); + formatted+="|\r\n"; + } + if(!formatted.empty()) formatted.resize(formatted.size()-2); + return formatted; +} + std::string TextDocument::readOriginal(uint64_t page) const { if(path_.empty()) return {}; diff --git a/src/files_text_document.h b/src/files_text_document.h index a793bca..00bfa8a 100644 --- a/src/files_text_document.h +++ b/src/files_text_document.h @@ -12,6 +12,10 @@ namespace ks::files enum class TextEncoding { automatic, utf8, utf16le, utf16be, windows1252 }; enum class TextLineEnding { preserve, crlf, lf, cr }; +inline constexpr uint64_t hexPageBytes=64*1024; +std::string formatHexAddress(uint64_t offset); +std::string formatHexPage(std::string_view bytes,uint64_t offset); + struct TextSaveFormat { TextEncoding encoding=TextEncoding::utf8; @@ -35,6 +39,7 @@ public: uint64_t size() const { return size_; } uint64_t boundary(uint64_t page) const; std::string readPage(uint64_t page) const; + std::string readBytes(uint64_t offset,size_t count) const; void releaseReadHandle(); void stage(uint64_t page, std::string_view utf8); bool modified() const { return !changes_.empty(); } diff --git a/src/files_text_window.cpp b/src/files_text_window.cpp index 56de86d..5c89af0 100644 --- a/src/files_text_window.cpp +++ b/src/files_text_window.cpp @@ -200,7 +200,7 @@ enum Command : UINT { save = 1, close, findText, findNext, previousPage, nextPage, firstPage, lastPage, goToPage, undo, redo, cut, copy, paste, selectAll, lexerAuto, lexerPlain, options, switchMode, - historyBack, historyForward, findPrevious, previewEscape, + historyBack, historyForward, findPrevious, previewEscape, switchHex, lexerStart = 1000, }; @@ -743,11 +743,13 @@ public: TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const RemoteTextSource *backend, std::string_view fragment,TextOpenOptions options,bool quickView=false) : original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()), - edit(editable), draft(options.draft), embedded(quickView), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()), + edit(editable), draft(options.draft), embedded(quickView), hex(options.hex && !editable), + prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()), search{dialogs}, previewFragment(fragment) { if (backend) remote=std::make_unique(*backend,original); - else if(!embedded) document=std::make_unique(draft?std::filesystem::path{}:original,edit,options.encoding); + else if(!embedded) document=std::make_unique(draft?std::filesystem::path{}:original,edit, + hex?TextEncoding::utf8:options.encoding); if(options.encoding!=TextEncoding::automatic) { newFormat.encoding=options.encoding; @@ -783,6 +785,13 @@ private: std::wstring filename; bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{}; bool draft{}, embedded{}; + bool hex{}; + struct ViewerPosition + { + uint64_t page{}; + LRESULT anchor{}, caret{}, firstLine{}, horizontal{}; + }; + std::optional beforeHex; TextSaveFormat newFormat; std::filesystem::path pendingSavePath; HICON smallIcon{},largeIcon{}; @@ -923,6 +932,7 @@ private: void applyLineEnding(); void installLexer(); void loadPage(uint64_t index,std::optional cached={}); + void toggleHex(); void stagePage(); void go(uint64_t index); void saveFile(bool closeWhenDone); @@ -978,7 +988,8 @@ void TextWindow::createMenu() const auto menu = CreateMenu(); const auto file = addGroup(menu, L"&File"); if (edit) addItem(file, save, L"&Save\tF2"); - addItem(file, switchMode, edit ? L"&View\tF6" : L"&Edit\tF6"); + if(!hex) addItem(file, switchMode, edit ? L"&View\tF6" : L"&Edit\tF6"); + if(!edit) addItem(file,switchHex,hex?L"&Text view\tF4":L"View as &hex\tF4"); addItem(file, close, L"&Close\tF10"); const auto actions = addGroup(menu, edit ? L"&Edit" : L"&Selection"); if (edit) @@ -992,52 +1003,58 @@ void TextWindow::createMenu() addItem(actions, copy, L"&Copy\tCtrl+C"); addItem(actions, selectAll, L"Select &page\tCtrl+A"); const auto navigation = addGroup(menu, L"&Navigate"); - if (!edit) + if (!edit && !hex) { addItem(navigation, historyBack, L"&Back\tAlt+Left"); addItem(navigation, historyForward, L"F&orward\tAlt+Right"); AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr); } - addItem(navigation, findText, L"&Find on page…\tCtrl+F"); - addItem(navigation, findNext, L"Find &next\tF3"); - AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr); + if(!hex) + { + addItem(navigation, findText, L"&Find on page…\tCtrl+F"); + addItem(navigation, findNext, L"Find &next\tF3"); + AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr); + } addItem(navigation, previousPage, L"&Previous page\tCtrl+PgUp"); addItem(navigation, nextPage, L"N&ext page\tCtrl+PgDn"); addItem(navigation, firstPage, L"F&irst page\tCtrl+Shift+Home"); addItem(navigation, lastPage, L"&Last page\tCtrl+Shift+End"); addItem(navigation, goToPage, L"&Go to page…\tF5"); - const auto syntax = addGroup(menu, L"S&yntax"); - addItem(syntax, lexerAuto, L"&Automatic"); - addItem(syntax, lexerPlain, L"&Plain text"); - constexpr std::wstring_view groups[] = {L"A–&F", L"G–&L", L"M–&R", L"S–&Z"}; - const wchar_t lastLetters[] = {L'f', L'l', L'r', L'z'}; - HMENU group{}; - size_t groupIndex{}; - std::wstring assignedKeys; - for (size_t i = 0; i < lexers.size(); ++i) + const auto syntax = hex?nullptr:addGroup(menu, L"S&yntax"); + if(syntax) { - auto name = wide(lexers[i]); - const auto letter = std::towlower(name.front()); - while (groupIndex + 1 < std::size(groups) && letter > lastLetters[groupIndex]) + addItem(syntax, lexerAuto, L"&Automatic"); + addItem(syntax, lexerPlain, L"&Plain text"); + constexpr std::wstring_view groups[] = {L"A–&F", L"G–&L", L"M–&R", L"S–&Z"}; + const wchar_t lastLetters[] = {L'f', L'l', L'r', L'z'}; + HMENU group{}; + size_t groupIndex{}; + std::wstring assignedKeys; + for (size_t i = 0; i < lexers.size(); ++i) { - ++groupIndex; - group = nullptr; - assignedKeys.clear(); - } - if (!group) group = addGroup(syntax, groups[groupIndex].data()); - for (size_t position = 0; position < name.size(); ++position) - { - const auto key = static_cast(std::towlower(name[position])); - if (((key >= L'a' && key <= L'z') || (key >= L'0' && key <= L'9')) && - assignedKeys.find(key) == assignedKeys.npos) + auto name = wide(lexers[i]); + const auto letter = std::towlower(name.front()); + while (groupIndex + 1 < std::size(groups) && letter > lastLetters[groupIndex]) { - assignedKeys += key; - name.insert(position, 1, L'&'); - break; + ++groupIndex; + group = nullptr; + assignedKeys.clear(); } + if (!group) group = addGroup(syntax, groups[groupIndex].data()); + for (size_t position = 0; position < name.size(); ++position) + { + const auto key = static_cast(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(group, static_cast(lexerStart + i), name.c_str()); } addItem(menu, options, L"&Options…"); menuRoot = menu; @@ -1191,7 +1208,7 @@ void TextWindow::updateMenus() void TextWindow::installLexer() { - lexer = createTextLexer(language); + lexer = hex?nullptr:createTextLexer(language); send(SCI_SETILEXER, 0, reinterpret_cast(lexer)); applyPreferences(); send(SCI_COLOURISE, 0, -1); @@ -1279,9 +1296,9 @@ void TextWindow::applyPreferences() send(SCI_SETUSETABS, !prefs.tabsAsSpaces); send(SCI_SETTABINDENTS, TRUE); send(SCI_SETBACKSPACEUNINDENTS, TRUE); - send(SCI_SETWRAPMODE, prefs.wrap ? SC_WRAP_WORD : SC_WRAP_NONE); - send(SCI_SETVIEWWS, prefs.whitespace ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE); - send(SCI_SETVIEWEOL, prefs.whitespace); + send(SCI_SETWRAPMODE, !hex && prefs.wrap ? SC_WRAP_WORD : SC_WRAP_NONE); + send(SCI_SETVIEWWS, !hex && prefs.whitespace ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE); + send(SCI_SETVIEWEOL, !hex && prefs.whitespace); applyLineEnding(); updateLineNumberMargin(); layout(); @@ -1291,7 +1308,7 @@ void TextWindow::applyPreferences() void TextWindow::updateLineNumberMargin() { LRESULT width{}; - if (prefs.numbers) + if (prefs.numbers && !hex) { const auto digits = std::to_string(send(SCI_GETLINECOUNT)).size(); const std::string sample(digits, '9'); @@ -1312,12 +1329,13 @@ void TextWindow::applyLineEnding() void TextWindow::loadPage(uint64_t index,std::optional cached) { - auto data=cached?std::move(*cached):document->readPage(index); - const auto offset = document->boundary(index); + const auto offset=hex?index*hexPageBytes:document->boundary(index); + auto data=cached?std::move(*cached):hex?formatHexPage(document->readBytes(offset,hexPageBytes),offset): + document->readPage(index); page = index; pageOffset = offset; - pageTotal = document->pages(); fileSize = document->size(); + pageTotal = hex?1+(fileSize?fileSize-1:0)/hexPageBytes:document->pages(); stagedDirty = document->modified(); const auto eol = data.find_first_of("\r\n"); pageEol = eol == data.npos ? SC_EOL_CRLF : data[eol] == '\n' ? SC_EOL_LF : @@ -1343,6 +1361,49 @@ void TextWindow::loadPage(uint64_t index,std::optional cached) invalidate(); } +void TextWindow::toggleHex() +{ + if(edit || embedded || !document) return; + if(hex) + { + const auto restored=beforeHex.value_or(ViewerPosition{}); + const auto index=std::min(restored.page,document->pages()-1); + auto normal=beforeHex?nullptr:std::make_unique(remote?remote->cache:original,false); + auto text=(normal?normal.get():document.get())->readPage(index); + if(normal) + { + document=std::move(normal); + language=automatic=detectLanguage(original,text); + if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment}); + } + hex=false; + beforeHex.reset(); + installLexer(); + loadPage(index,std::move(text)); + send(SCI_SETSEL,restored.anchor,restored.caret); + send(SCI_SETFIRSTVISIBLELINE,restored.firstLine); + send(SCI_SETXOFFSET,restored.horizontal); + updatePreview(); + } + else + { + const auto index=pageOffset/hexPageBytes; + const auto offset=index*hexPageBytes; + auto bytes=formatHexPage(document->readBytes(offset,hexPageBytes),offset); + beforeHex=ViewerPosition{page,send(SCI_GETANCHOR),send(SCI_GETCURRENTPOS), + send(SCI_GETFIRSTVISIBLELINE),send(SCI_GETXOFFSET)}; + hex=true; + stopPreview(false,true); + installLexer(); + loadPage(index,std::move(bytes)); + focusContent(); + } + releaseMenu(); + createMenu(); + updateTitle(); + invalidate(); +} + void TextWindow::stagePage() { if (!currentChanged()) return; @@ -1362,6 +1423,15 @@ void TextWindow::go(uint64_t index) void TextWindow::initializeDocument(std::optional firstPage) { + if(hex) + { + releaseMenu(); + createMenu(); + installLexer(); + loadPage(0); + updateTitle(); + return; + } if(!firstPage) firstPage=document->readPage(0); automatic=detectLanguage(original,*firstPage); language=automatic; @@ -1461,7 +1531,7 @@ void TextWindow::finishOpen() { opening.get(); if(cancelOpen) { DestroyWindow(window); return; } - document=std::make_unique(remote->cache,edit); + document=std::make_unique(remote->cache,edit,hex?TextEncoding::utf8:TextEncoding::automatic); initializeDocument(); invalidate(); } @@ -1631,7 +1701,7 @@ void TextWindow::changeMode() void TextWindow::updateTitle() { - const auto title = std::wstring(edit ? L"Editor — " : L"Viewer — ") + + const auto title = std::wstring(edit ? L"Editor — " : hex ? L"Hex Viewer — " : L"Viewer — ") + (remote ? remote->source.name + L" · " : std::wstring{}) + original.wstring(); SetWindowTextW(window,title.c_str()); } @@ -1669,7 +1739,7 @@ void TextWindow::updateTaskbarGroup(bool closing) bool TextWindow::canPreview() const { - return !edit && automatic.lexer=="markdown" && document && document->size()<=TextDocument::editLimit; + return !edit && !hex && automatic.lexer=="markdown" && document && document->size()<=TextDocument::editLimit; } void TextWindow::updatePreview() @@ -1720,8 +1790,8 @@ bool TextWindow::startPreviewBrowser() PostMessageW(window,WM_COMMAND,key==VK_LEFT || key==VK_BROWSER_BACK?historyBack:historyForward,0); return true; } - if(key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false; - PostMessageW(window,WM_COMMAND,key==VK_F6?switchMode:key==VK_ESCAPE?previewEscape:close,0); + if(key!=VK_F4 && key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false; + PostMessageW(window,WM_COMMAND,key==VK_F4?switchHex:key==VK_F6?switchMode:key==VK_ESCAPE?previewEscape:close,0); return true; }); } @@ -2284,7 +2354,8 @@ void TextWindow::paint() const auto position=send(SCI_GETCURRENTPOS); const auto line=send(SCI_LINEFROMPOSITION,position)+1; const auto column=send(SCI_GETCOLUMN,position)+1; - auto status=filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+ + auto status=hex?filename+L" (Hex) │ 0x"+wide(formatHexAddress(pageOffset+(line-1)*16)): + 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) @@ -2293,11 +2364,12 @@ void TextWindow::paint() 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" : + const auto hints = busy() ? L"Saving…" : hex?L"F4 Text F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close": + insertRejected ? L"Page edit limit: 8 MiB" : edit ? L"F2 Save F3 Find next F5 Go to page F6 View Ctrl+PgUp/PgDn Pages F10 Close" : - previewVisible ? L"F6 Edit Ctrl+W Close" : + previewVisible ? L"F4 Hex F6 Edit Ctrl+W Close" : previewWanted ? L"Rendering Markdown… Ctrl+W Close" : - L"F3 Find next F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close"; + L"F3 Find next F4 Hex F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close"; constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX; DrawTextW(dc, hints, -1, &bottom, format); SelectObject(dc, previous); @@ -2348,11 +2420,14 @@ void TextWindow::command(UINT id) { if(!document && id!=close) return; if (busy()) return; + if(hex && (id==switchMode || id==historyBack || id==historyForward || id==findText || id==findNext || + id==findPrevious || id==lexerAuto || id==lexerPlain || id>=lexerStart)) return; switch (id) { case save: saveFile(false); return; case close: requestClose(); return; case switchMode: toggleMode(); return; + case switchHex: toggleHex(); return; case historyBack: case historyForward: if(previewVisible) @@ -2487,10 +2562,12 @@ bool TextWindow::handleKey(const MSG &message) UINT id{}; if (key == VK_F2 || (ctrl && key == 'S')) id = save; if (key == VK_F3) id = findNext; + if (key == VK_F4 && !ctrl && !shift && !edit) id = switchHex; if (key == VK_F5 || (ctrl && key == 'G')) id = goToPage; if (key == VK_F6) id = switchMode; if (key == VK_F9) id = 600; - if (key == VK_ESCAPE || key == VK_F10 || (!edit && ctrl && key=='W')) id = close; + if (key == VK_ESCAPE) id = hex && beforeHex?switchHex:close; + if (key == VK_F10 || (!edit && ctrl && key=='W')) id = close; if (!edit && key==VK_BROWSER_BACK) id=historyBack; if (!edit && key==VK_BROWSER_FORWARD) id=historyForward; if (ctrl && key == 'F') id = findText; @@ -2598,6 +2675,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, case WM_KEYDOWN: if(!self->embedded && self->previewWanted && !self->previewVisible) { + if(wparam==VK_F4) self->command(switchHex); if(wparam==VK_F6) self->toggleMode(); if(wparam==VK_ESCAPE || wparam==VK_F10 || (wparam=='W' && (GetKeyState(VK_CONTROL)&0x8000))) self->requestClose(); @@ -2926,7 +3004,7 @@ void openImageWindow(HWND owner,std::vector images,const static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options) { - if(!edit && !options.draft && isImagePath(path)) + if(!edit && !options.draft && !options.hex && isImagePath(path)) { openImageWindow(owner,{path},path,dialogs,nullptr,backend); return; @@ -2937,7 +3015,7 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool std::error_code error; const auto identity=backend?path.lexically_normal():std::filesystem::weakly_canonical(path,error); const auto &original=error?path:identity; - if(const auto existing=newWindow?nullptr:findOpenDocument(original,backend?backend->id:"")) + if(const auto existing=newWindow || options.hex?nullptr:findOpenDocument(original,backend?backend->id:"")) { if(dialogs.confirmExisting(owner) && IsWindow(existing)) { @@ -2952,7 +3030,7 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool const auto instance=GetModuleHandleW(nullptr); if(!registerTextWindowClass(instance)) throw std::runtime_error("Cannot register the text window."); auto state=std::make_shared(original,edit,dialogs,backend,fragment,options); - const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+ + const auto title=std::wstring(edit?L"Editor — ":options.hex?L"Hex Viewer — ":L"Viewer — ")+ (backend?backend->name+L" · ":std::wstring{})+path.wstring(); RECT bounds{}; GetWindowRect(owner,&bounds); @@ -2974,8 +3052,8 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD } void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, - const RemoteTextSource &source,std::string_view fragment,bool newWindow) + const RemoteTextSource &source,std::string_view fragment,bool newWindow,TextOpenOptions options) { - openTextWindowImpl(owner,path,edit,dialogs,&source,fragment,newWindow,{}); + openTextWindowImpl(owner,path,edit,dialogs,&source,fragment,newWindow,options); } } diff --git a/src/files_text_window.h b/src/files_text_window.h index db7fe19..98c084a 100644 --- a/src/files_text_window.h +++ b/src/files_text_window.h @@ -61,6 +61,7 @@ struct TextOpenOptions { TextEncoding encoding=TextEncoding::automatic; bool draft{}; + bool hex{}; }; struct RemoteTextRevision @@ -92,7 +93,7 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false, TextOpenOptions options={}); void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, - const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false); + const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false,TextOpenOptions options={}); void textWindowOwnerClosed(); bool cycleTextWindows(HWND current,bool reverse); } diff --git a/tests/files_text_document.cpp b/tests/files_text_document.cpp index 5c7321b..4ff152e 100644 --- a/tests/files_text_document.cpp +++ b/tests/files_text_document.cpp @@ -140,8 +140,28 @@ void sparseFile(const fs::path &file) const auto index = document.pages() - 1; check(document.size() == offset + 4 && document.boundary(index) == offset, "Use 64-bit offsets"); check(document.readPage(index) == "last", "Read past 4 GiB"); + const auto raw=document.readBytes(offset-2,8); + check(raw==std::string("\0\0last",6),"Read original bytes across a sparse section beyond 4 GiB"); + check(ks::files::formatHexPage(raw,offset-2).starts_with("000000013FFFFFFE 00 00 6C 61 73 74"), + "Format a 64-bit hex offset and embedded NULs"); document.stage(index, "edited"); check(document.readPage(index) == "edited", "Stage an edit past 4 GiB"); + check(document.readBytes(offset,4)=="last","Hex reads original bytes instead of staged edits"); +} + +void hexBytes(const fs::path &file) +{ + const std::string bytes("\xef\xbb\xbf\0A\xff\x7f\r\n",9); + writeFile(file,bytes); + TextDocument document(file,false); + check(document.boundary(0)==3 && document.readBytes(0,64)==bytes,"Hex includes the original BOM"); + check(document.readBytes(9,40).empty(),"Reading at EOF returns an empty block"); + const auto text=ks::files::formatHexPage(bytes,0); + check(text.starts_with("0000000000000000 EF BB BF 00 41 FF 7F 0D 0A") && + text.ends_with("|....A.... |"),"Hex and ASCII columns retain unprintable bytes and alignment"); + const std::string twoRows(17,'a'); + check(ks::files::formatHexPage(twoRows,0).find("\r\n0000000000000010 61")!=std::string::npos, + "Hex offsets advance by the row width"); } void saveDraft(const fs::path &file) @@ -191,6 +211,7 @@ int main() unicodeBoundaries(fixture.directory / L"unicode.txt"); rejectExternalReplacement(fixture.directory / L"external.txt"); saveDraft(fixture.directory / L"created.txt"); + hexBytes(fixture.directory / L"raw.bin"); sparseFile(fixture.directory / L"5gib.log"); std::cout << "Files text document regressions passed.\n"; }