Show original file bytes in Hex Viewer

Refs #102
This commit is contained in:
agrynco committed 2026-11-25 16:20:52 +02:00
1 parent dc4e503c84
commit 6f2f1f38e2
7 files changed
+241 -70

No files matched your search

+135 -57
View File
@@ -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<RemoteTextFile>(*backend,original);
else if(!embedded) document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
else if(!embedded) document=std::make_unique<TextDocument>(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<ViewerPosition> 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<std::string> 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<wchar_t>(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<wchar_t>(std::towlower(name[position]));
if (((key >= L'a' && key <= L'z') || (key >= L'0' && key <= L'9')) &&
assignedKeys.find(key) == assignedKeys.npos)
{
assignedKeys += key;
name.insert(position, 1, L'&');
break;
}
}
addItem(group, static_cast<UINT>(lexerStart + i), name.c_str());
}
addItem(group, static_cast<UINT>(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<LPARAM>(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<std::string> 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<std::string> 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<TextDocument>(remote?remote->cache:original,false);
auto text=(normal?normal.get():document.get())->readPage(index);
if(normal)
{
document=std::move(normal);
language=automatic=detectLanguage(original,text);
if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment});
}
hex=false;
beforeHex.reset();
installLexer();
loadPage(index,std::move(text));
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<std::string> 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<TextDocument>(remote->cache,edit);
document=std::make_unique<TextDocument>(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<std::filesystem::path> 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<TextWindow>(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);
}
}