Compare commits

...
2 changed files with 163 additions and 59 deletions

No files matched your search

+5 -2
View File
@@ -311,8 +311,11 @@ Warning і початковий фокус на No.
При повторному відкритті Files пропонує перейти до вже
відкритого вікна. Закриття менеджера залишає вікна файлів відкритими.
- У цьому вікні F6 перемикає перегляд і редагування для поточного файла.
За наявності змін перехід у перегляд пропонує Save, Discard або Cancel.
Помилка збереження залишає відкритим редактор зі змінами.
Viewer показує збережену версію, а чернетка зберігається в поточному
вікні з позначкою Draft retained. Повторне F6 повертає правки, сторінку,
виділення й прокрутку.
Для нового файла Viewer показує порожній документ. Закриття вікна
з чернеткою в обох режимах пропонує Save, Discard або Cancel.
- **Shift+F3** або **Commands → View as hex** відкриває файл у Hex Viewer.
**F4** у Viewer перемикає текстовий або форматований перегляд і Hex.
Hex показує 64-бітну адресу, 16 вихідних байтів у рядку й ASCII.
+158 -57
View File
@@ -666,6 +666,19 @@ struct RemoteTextFile
}
};
std::future<std::unique_ptr<RemoteTextFile>> fetchRemoteText(const RemoteTextSource &source,
const std::filesystem::path &path,const std::shared_ptr<std::atomic<bool>> &canceled)
{
std::packaged_task<std::unique_ptr<RemoteTextFile>()> task([source,path,canceled] {
auto file=std::make_unique<RemoteTextFile>(source,path);
file->download(false,[canceled](uint64_t,uint64_t){return !*canceled;});
return file;
});
auto result=task.get_future();
std::thread(std::move(task)).detach();
return result;
}
class TextWindow;
std::map<HWND,std::shared_ptr<TextWindow>> textWindows;
std::vector<HWND> textWindowOrder;
@@ -773,6 +786,7 @@ public:
static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM wparam, LPARAM lparam);
~TextWindow()
{
if(savedViewerFile) document.reset();
if(smallIcon) DestroyIcon(smallIcon);
if(largeIcon) DestroyIcon(largeIcon);
}
@@ -799,6 +813,16 @@ private:
LRESULT anchor{}, caret{}, firstLine{}, horizontal{};
};
std::optional<ViewerPosition> beforeHex;
struct SuspendedEditor
{
std::unique_ptr<TextDocument> document;
ViewerPosition position;
bool uploadPending{};
};
std::optional<SuspendedEditor> suspendedEditor;
std::unique_ptr<RemoteTextFile> savedViewerFile;
std::future<std::unique_ptr<RemoteTextFile>> savedViewerLoad;
std::shared_ptr<std::atomic<bool>> cancelSavedViewer;
TextSaveFormat newFormat;
std::filesystem::path pendingSavePath;
HICON smallIcon{},largeIcon{};
@@ -821,7 +845,6 @@ private:
int pageEol = SC_EOL_CRLF;
size_t undoBytes{};
bool uploadPending{};
bool switchAfterSave{};
FilesTerminalView preview;
bool previewWanted{}, previewVisible{}, previewRetried{};
ULONGLONG previewDeadline{};
@@ -882,6 +905,7 @@ private:
static constexpr UINT_PTR navigationTimer = 4;
static constexpr UINT_PTR quickViewTimer = 5;
static constexpr UINT_PTR bookmarkTimer = 6;
static constexpr UINT_PTR savedViewerTimer = 7;
struct BookmarkLocation
{
std::filesystem::path path;
@@ -961,6 +985,13 @@ private:
void requestClose();
void toggleMode();
void changeMode();
ViewerPosition currentPosition() const;
void restorePosition(const ViewerPosition &position);
void showTextMode(const ViewerPosition &position,std::string contents);
void suspendEditor(std::unique_ptr<RemoteTextFile> saved={});
void restoreEditor();
void finishSavedViewer();
void cancelSavedViewerLoad();
bool needsSave() const;
bool canPreview() const;
void updatePreview();
@@ -1408,9 +1439,7 @@ void TextWindow::toggleHex()
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);
restorePosition(restored);
updatePreview();
}
else
@@ -1418,8 +1447,7 @@ void TextWindow::toggleHex()
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)};
beforeHex=currentPosition();
hex=true;
stopPreview(false,true);
installLexer();
@@ -1664,14 +1692,13 @@ void TextWindow::finishOpen()
void TextWindow::saveFile(bool closeWhenDone)
{
if (busy() || !edit) return;
if (busy() || savedViewerLoad.valid() || !edit) return;
auto destination=original;
if(draft && !search.style.saveOptions(window,destination,newFormat)) return;
stagePage();
if (!draft && !stagedDirty && !uploadPending)
{
if (closeWhenDone) DestroyWindow(window);
else if (std::exchange(switchAfterSave, false)) changeMode();
return;
}
pendingCaret = send(SCI_GETCURRENTPOS);
@@ -1712,7 +1739,6 @@ void TextWindow::finishSave()
return;
}
send(SCI_SETREADONLY, !edit);
const auto change = std::exchange(switchAfterSave, false);
const auto reopened = saving.get();
stagedDirty = false;
const bool created=std::exchange(draft,false);
@@ -1730,7 +1756,6 @@ void TextWindow::finishSave()
return;
}
if (closeAfterSave) { DestroyWindow(window); return; }
if (change) { changeMode(); return; }
if(created)
{
initializeDocument();
@@ -1751,11 +1776,17 @@ void TextWindow::requestClose()
{
if (opening.valid()) { cancelOpen=true; return; }
if (busy()) return;
cancelSavedViewerLoad();
if (needsSave())
{
const auto answer = search.style.confirmSave(window,draft);
if (answer == IDCANCEL) return;
if (answer == IDYES) { saveFile(true); return; }
if (answer == IDYES)
{
if(suspendedEditor) restoreEditor();
saveFile(true);
return;
}
if (answer != IDNO) return;
}
DestroyWindow(window);
@@ -1763,54 +1794,61 @@ void TextWindow::requestClose()
bool TextWindow::needsSave() const
{
if(suspendedEditor) return suspendedEditor->uploadPending || suspendedEditor->document->modified();
return uploadPending || (currentChanged() ? document->modifiedWith(page, pageText()) : stagedDirty);
}
void TextWindow::toggleMode()
{
if (busy() || navigation.valid()) return;
if(draft) return;
if (edit && needsSave())
if (busy() || navigation.valid() || savedViewerLoad.valid()) return;
if(suspendedEditor)
{
const auto answer = search.style.confirmSave(window,false);
if (answer == IDYES)
restoreEditor();
return;
}
if(edit && (draft || needsSave()))
{
if(!uploadPending) suspendEditor();
else
{
switchAfterSave = true;
try { saveFile(false); }
catch (...) { switchAfterSave = false; throw; }
return;
}
if (answer != IDNO) return;
// The local LAN cache may already contain changes from a failed upload.
if (uploadPending)
{
auto refreshed = std::make_unique<RemoteTextFile>(remote->source,original);
refreshed->download(false,{});
auto replacement = std::make_unique<TextDocument>(refreshed->cache,false);
document.reset();
remote = std::move(refreshed);
document = std::move(replacement);
uploadPending = false;
auto cancel=std::make_shared<std::atomic<bool>>(false);
if(!SetTimer(window,savedViewerTimer,75,nullptr))
throw std::runtime_error("Cannot start loading the saved version.");
try
{
savedViewerLoad=fetchRemoteText(remote->source,original,cancel);
cancelSavedViewer=std::move(cancel);
}
catch(...) {KillTimer(window,savedViewerTimer); throw;}
invalidate();
}
return;
}
changeMode();
}
void TextWindow::changeMode()
TextWindow::ViewerPosition TextWindow::currentPosition() const
{
return {page,send(SCI_GETANCHOR),send(SCI_GETCURRENTPOS),send(SCI_GETFIRSTVISIBLELINE),send(SCI_GETXOFFSET)};
}
void TextWindow::restorePosition(const ViewerPosition &position)
{
const auto length=send(SCI_GETLENGTH);
send(SCI_SETSEL,std::clamp<LRESULT>(position.anchor,0,length),std::clamp<LRESULT>(position.caret,0,length));
send(SCI_SETFIRSTVISIBLELINE,position.firstLine);
send(SCI_SETXOFFSET,position.horizontal);
}
void TextWindow::showTextMode(const ViewerPosition &position,std::string contents)
{
if (!edit && remote && !remote->revision.editable)
throw std::runtime_error("The remote file does not support editing.");
auto replacement = std::make_unique<TextDocument>(remote ? remote->cache : original, !edit);
const auto caret = send(SCI_GETCURRENTPOS);
document = std::move(replacement);
edit = !edit;
if(canPreview()) ShowWindow(editor,SW_HIDE);
prefs = loadTextPreferences().profiles[edit];
releaseMenu();
createMenu();
installLexer();
loadPage(std::min(page, document->pages() - 1));
send(SCI_GOTOPOS, std::min(caret, send(SCI_GETLENGTH)));
loadPage(position.page,std::move(contents));
restorePosition(position);
updateTitle();
updateIcons(GetDpiForWindow(window));
updateTaskbarGroup();
@@ -1819,6 +1857,68 @@ void TextWindow::changeMode()
focusContent();
}
void TextWindow::changeMode()
{
if(!edit && remote && !remote->revision.editable)
throw std::runtime_error("The remote file does not support editing.");
auto position=currentPosition();
auto replacement=std::make_unique<TextDocument>(remote?remote->cache:original,!edit,document->encoding());
position.page=std::min(position.page,replacement->pages()-1);
auto contents=replacement->readPage(position.page);
document=std::move(replacement);
edit=!edit;
showTextMode(position,std::move(contents));
}
void TextWindow::suspendEditor(std::unique_ptr<RemoteTextFile> saved)
{
const auto position=currentPosition();
const auto path=draft?std::filesystem::path{}:saved?saved->cache:remote?remote->cache:original;
auto replacement=std::make_unique<TextDocument>(path,false,document->encoding());
auto viewing=position;
viewing.page=std::min(viewing.page,replacement->pages()-1);
auto contents=replacement->readPage(viewing.page);
stagePage();
suspendedEditor=SuspendedEditor{std::move(document),position,std::exchange(uploadPending,false)};
document=std::move(replacement);
savedViewerFile=std::move(saved);
edit=false;
showTextMode(viewing,std::move(contents));
}
void TextWindow::restoreEditor()
{
const auto position=suspendedEditor->position;
auto contents=suspendedEditor->document->readPage(position.page);
document=std::move(suspendedEditor->document);
uploadPending=suspendedEditor->uploadPending;
suspendedEditor.reset();
savedViewerFile.reset();
edit=true;
hex=false;
beforeHex.reset();
showTextMode(position,std::move(contents));
}
void TextWindow::finishSavedViewer()
{
if(!savedViewerLoad.valid() || savedViewerLoad.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
KillTimer(window,savedViewerTimer);
cancelSavedViewer.reset();
invalidate();
suspendEditor(savedViewerLoad.get());
}
void TextWindow::cancelSavedViewerLoad()
{
if(!savedViewerLoad.valid()) return;
*cancelSavedViewer=true;
cancelSavedViewer.reset();
savedViewerLoad={};
KillTimer(window,savedViewerTimer);
invalidate();
}
void TextWindow::updateTitle()
{
const auto title = std::wstring(edit ? L"Editor — " : hex ? L"Hex Viewer — " : L"Viewer — ") +
@@ -1985,7 +2085,7 @@ void TextWindow::renderPreview(bool keepPosition)
previewText=quickMarkdown?*quickMarkdown:readMarkdownDocument(*document);
if(!remote) document->releaseReadHandle();
nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision},
{"canSave",!embedded && (!remote || remote->revision.editable)},{"compact",embedded},
{"canSave",!embedded && !suspendedEditor && (!remote || remote->revision.editable)},{"compact",embedded},
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
{"keepPosition",keepPosition}};
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
@@ -2035,7 +2135,7 @@ void TextWindow::startMarkdownTask()
{
const auto task=std::exchange(pendingTask,{});
if(!task) return;
if(!previewVisible || edit || busy() || navigation.valid() || task->revision!=previewRevision ||
if(!previewVisible || edit || suspendedEditor || busy() || navigation.valid() || task->revision!=previewRevision ||
(remote && !remote->revision.editable))
{
reportMarkdownTask(task->revision,false);
@@ -2225,13 +2325,18 @@ void TextWindow::previewMessage(const std::wstring &value)
void TextWindow::syncNavigation()
{
preview.post(wide(nlohmann::json{{"action","history"},{"back",navigationIndex>0},
{"forward",navigationIndex+1<navigationHistory.size()}}.dump()));
preview.post(wide(nlohmann::json{{"action","history"},{"back",!suspendedEditor && navigationIndex>0},
{"forward",!suspendedEditor && navigationIndex+1<navigationHistory.size()}}.dump()));
}
void TextWindow::navigatePreview(PreviewLink request)
{
if(edit || busy() || pendingTask || navigation.valid() || navigationHistory.empty()) return;
if(suspendedEditor)
{
if(request.direction) return;
if(request.target.path!=original) request.newWindow=true;
}
if(request.newWindow)
{
if(remote)
@@ -2252,19 +2357,11 @@ void TextWindow::navigatePreview(PreviewLink request)
else destination=std::move(request.target);
if(destination.path==original || !remote) { showLocation(nullptr); return; }
auto cancel=std::make_shared<std::atomic<bool>>(false);
std::packaged_task<std::unique_ptr<RemoteTextFile>()> task(
[backend=remote->source,path=destination.path,cancel] {
auto file=std::make_unique<RemoteTextFile>(backend,path);
file->download(false,[cancel](uint64_t,uint64_t){return !*cancel;});
return file;
});
if(!SetTimer(window,navigationTimer,75,nullptr))
throw std::runtime_error("Cannot start the remote navigation timer.");
try
{
auto result=task.get_future();
std::thread(std::move(task)).detach();
navigation=std::move(result);
navigation=fetchRemoteText(remote->source,destination.path,cancel);
cancelNavigation=std::move(cancel);
}
catch(...) { KillTimer(window,navigationTimer); throw; }
@@ -2480,8 +2577,9 @@ 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=hex?filename+L" (Hex) │ 0x"+wide(formatHexAddress(pageOffset+(line-1)*16)):
filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+
const auto retained=suspendedEditor?L" │ Draft retained":L"";
auto status=hex?filename+L" (Hex)"+retained+L" │ 0x"+wide(formatHexAddress(pageOffset+(line-1)*16)):
filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+retained+
L" │ "+(document?document->encodingName():L"Loading…")+L" │ "+textLanguageLabel(language)+
L" │ Ln "+std::to_wstring(line)+L":"+std::to_wstring(column);
if(pageTotal>1)
@@ -2491,7 +2589,8 @@ void TextWindow::paint()
if(bookmarkTask.valid()) status+=L" │ Locating line…";
drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status);
}
const auto hints = busy() ? L"Saving…" : hex?L"F4 Text F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close":
const auto hints = busy() ? L"Saving…" : savedViewerLoad.valid()?L"Loading saved version…" :
hex?L"F4 Text F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close":
insertRejected ? L"Page edit limit: 8 MiB" :
edit ? L"F2 Save F3 Find next F5 Go to page F6 View Ctrl+PgUp/PgDn Pages F10 Close" :
previewVisible ? L"F4 Hex F6 Edit Ctrl+W Close" :
@@ -2868,6 +2967,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
if (wparam == navigationTimer) self->finishNavigation();
if (wparam == quickViewTimer) self->pollQuickView();
if (wparam == bookmarkTimer) self->finishBookmark();
if (wparam == savedViewerTimer) self->finishSavedViewer();
return 0;
case trimUndo:
if (self->undoBytes >= 32 * TextDocument::pageBytes)
@@ -2879,6 +2979,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
}
return 0;
case WM_DESTROY:
self->cancelSavedViewerLoad();
self->bookmarkStop.request_stop();
if(self->cancelNavigation) *self->cancelNavigation=true;
if(!self->embedded) self->updateTaskbarGroup(true);