Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1757450833 | ||
|
|
1066fbeab8 |
No files matched your search
@@ -695,6 +695,8 @@ Warning і початковий фокус на No.
|
||||
- **F3** відкриває PNG, JPEG, GIF, WebP і BMP у Viewer. Стрілки вліво й
|
||||
вправо, Page Up і Page Down та кнопки Previous і Next гортають видимі
|
||||
зображення в порядку вихідної панелі на момент відкриття Viewer.
|
||||
- **Options → Viewer → Restore local Viewer and Editor windows after restart** зберігає відкриті локальні вікна під час закриття Files. Під час наступного запуску наявні документи відкриваються в попередньому режимі й положенні. Текст відновлює сторінку, курсор і прокручування, а зображення — масштаб. Відновлення читає збережені файли з диска.
|
||||
- Локальний Viewer оновлює вміст після зміни файла. Активний Editor пропонує **Reload** або **Keep buffer**. Reload відкриває актуальну версію з диска, Keep buffer залишає відкриті редагування. Збереження після Keep buffer перевіряє початкову версію й зберігає чернетку, якщо файл уже змінився.
|
||||
- **F4** на локальному PNG або JPEG відкриває редактор зображень. Rotate left і Rotate right повертають зображення на 90°. Crop приймає цілі координати X і Y від нуля, ширину й висоту в пікселях поточного зображення. Undo або Ctrl+Z послідовно скасовує зміни.
|
||||
- **Save copy** або Ctrl+Shift+S створює окремий PNG чи JPEG. PNG зберігає прозорість, а JPEG використовує біле тло. **Replace** або Ctrl+S просить підтвердження й звіряє версію оригіналу. Якщо зовнішня зміна або помилка заважає запису, редактор зберігає чернетку. Закриття незбереженої чернетки просить підтвердження.
|
||||
- У Viewer і Quick View коліщатко та кнопки − і + змінюють масштаб,
|
||||
|
||||
@@ -236,6 +236,7 @@ BEGIN
|
||||
PUSHBUTTON "Change color…", 366, 257, 181, 82, 15
|
||||
LTEXT "", 367, 345, 184, 45, 12
|
||||
PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15
|
||||
AUTOCHECKBOX "Restore local Viewer and Editor windows after restart", 524, 131, 210, 250, 13
|
||||
LTEXT "Maximum &width (px, 0 = full window)", 373, 131, 31, 184, 12
|
||||
EDITTEXT 374, 318, 28, 64, 14, ES_NUMBER | ES_AUTOHSCROLL
|
||||
LTEXT "Font &family (blank = system default)", 375, 131, 54, 250, 12
|
||||
|
||||
@@ -355,6 +355,17 @@ document.addEventListener('keydown', event => {
|
||||
}
|
||||
});
|
||||
|
||||
let scrollTimer;
|
||||
window.addEventListener('scroll', () => {
|
||||
if (document.documentElement.classList.contains('quick-view')) return;
|
||||
clearTimeout(scrollTimer);
|
||||
const revision = previewRevision;
|
||||
scrollTimer = setTimeout(() => {
|
||||
if (revision === previewRevision && document.documentElement.classList.contains('rendered'))
|
||||
send('scroll', { revision, top: Math.round(window.scrollY) });
|
||||
}, 120);
|
||||
}, { passive: true });
|
||||
|
||||
bridge.addEventListener('message', ({ data }) => {
|
||||
const message = JSON.parse(data);
|
||||
if (message.action === 'clear') {
|
||||
|
||||
@@ -25,13 +25,9 @@ struct StagedImage
|
||||
|
||||
ImageRevision readRevision(HANDLE handle)
|
||||
{
|
||||
ImageRevision revision;
|
||||
FILE_BASIC_INFO basics{};
|
||||
if(!GetFileInformationByHandle(handle,&revision.identity) ||
|
||||
!GetFileInformationByHandleEx(handle,FileBasicInfo,&basics,sizeof(basics))) fail("Read image revision");
|
||||
if(basics.FileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT))
|
||||
const auto revision=fileVersion(handle);
|
||||
if(revision.info.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT))
|
||||
throw std::runtime_error("Choose a regular local image.");
|
||||
revision.changeTime=basics.ChangeTime.QuadPart;
|
||||
return revision;
|
||||
}
|
||||
|
||||
@@ -98,9 +94,7 @@ ImageRevision imageRevision(const std::filesystem::path &path)
|
||||
|
||||
bool sameImageRevision(const ImageRevision &first,const ImageRevision &second)
|
||||
{
|
||||
return sameFileIdentity(first.identity,second.identity) && first.changeTime==second.changeTime &&
|
||||
first.identity.nFileSizeHigh==second.identity.nFileSizeHigh && first.identity.nFileSizeLow==second.identity.nFileSizeLow &&
|
||||
CompareFileTime(&first.identity.ftLastWriteTime,&second.identity.ftLastWriteTime)==0;
|
||||
return first==second;
|
||||
}
|
||||
|
||||
ImageRevision saveImage(const ImageRaster &raster,const std::filesystem::path &path,const ImageRevision *expected)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "files_image_decode.h"
|
||||
#include <windows.h>
|
||||
#include "files_win32_replace.h"
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
@@ -18,11 +18,7 @@ struct ImageGeometry
|
||||
bool operator==(const ImageGeometry &) const = default;
|
||||
};
|
||||
|
||||
struct ImageRevision
|
||||
{
|
||||
BY_HANDLE_FILE_INFORMATION identity{};
|
||||
LONGLONG changeTime{};
|
||||
};
|
||||
using ImageRevision=LocalFileVersion;
|
||||
|
||||
ImageGeometry cropImage(ImageGeometry geometry,const ImageRegion &area);
|
||||
ImageRaster transformImage(const ImageRaster &original,const ImageGeometry &geometry);
|
||||
|
||||
@@ -104,6 +104,6 @@ ks::files::ImageEditDialogs imageEditDialogs()
|
||||
{
|
||||
showFilesNotice(owner,text,L"Image editor",{.tone=FilesNoticeTone::warning});
|
||||
},
|
||||
FilesModalDialog::dismissOwned
|
||||
FilesModalDialog::dismissOwned,textWindowDialogs().reloadChanged
|
||||
};
|
||||
}
|
||||
+59
-12
@@ -17,7 +17,7 @@ namespace
|
||||
{
|
||||
namespace fs=std::filesystem;
|
||||
constexpr wchar_t imageWindowClass[]=L"KSwitcherFilesImageViewer";
|
||||
constexpr UINT_PTR imageTimer=1;
|
||||
constexpr UINT_PTR imageTimer=1, externalImageTimer=2;
|
||||
enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize,
|
||||
rotateLeft, rotateRight, crop, undoEdit, saveCopy, replaceOriginal };
|
||||
|
||||
@@ -55,6 +55,7 @@ struct ImageView
|
||||
std::optional<ImageRevision> revision;
|
||||
};
|
||||
bool confirmingClose{};
|
||||
std::optional<ImageRevision> observedVersion;
|
||||
HFONT font{};
|
||||
UINT fontDpi{};
|
||||
int toolbarHeight{};
|
||||
@@ -164,18 +165,22 @@ struct ImageView
|
||||
if(button) InvalidateRect(button,nullptr,FALSE);
|
||||
}
|
||||
|
||||
void request(const fs::path &path)
|
||||
void request(const fs::path &path,bool reload=false)
|
||||
{
|
||||
if(requested==path) return;
|
||||
if(requested==path && !reload) return;
|
||||
requested=path;
|
||||
++revision;
|
||||
stop.request_stop();
|
||||
retried=false;
|
||||
error.clear();
|
||||
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
|
||||
width=height=0;
|
||||
fit=true;
|
||||
x=y=0;
|
||||
if(!reload)
|
||||
{
|
||||
observedVersion.reset();
|
||||
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
|
||||
width=height=0;
|
||||
fit=true;
|
||||
x=y=0;
|
||||
}
|
||||
if(!embedded && !draft)
|
||||
{
|
||||
const auto label=L"Viewer — "+path.filename().wstring();
|
||||
@@ -222,12 +227,15 @@ struct ImageView
|
||||
if(current)
|
||||
{
|
||||
show(image.raster);
|
||||
observedVersion=image.revision;
|
||||
if(draft)
|
||||
{
|
||||
draft->undo.clear();
|
||||
draft->version=image.revision;
|
||||
draft->original=std::move(image.raster);
|
||||
draft->geometry=draft->saved={{0,0,width,height},0};
|
||||
}
|
||||
clampOffset();
|
||||
updateButtons();
|
||||
}
|
||||
}
|
||||
@@ -258,12 +266,14 @@ struct ImageView
|
||||
stop=std::stop_source{};
|
||||
started=revision;
|
||||
std::packaged_task<Loaded()> task([path=requested,decoder=retried?retry.load:load,
|
||||
token=stop.get_token(),editing=draft.has_value()]
|
||||
token=stop.get_token(),watch=!embedded && !load && isLocalDocumentPath(requested),editing=draft.has_value()]
|
||||
{
|
||||
if(!editing) return Loaded{decoder?decoder(path,token):decodeImage(path,path,token),{}};
|
||||
const auto before=imageRevision(path);
|
||||
if(!watch) return Loaded{decoder?decoder(path,token):decodeImage(path,path,token),{}};
|
||||
std::optional<ImageRevision> before;
|
||||
try {before=imageRevision(path);}
|
||||
catch(const std::exception &) {if(editing) throw;}
|
||||
auto raster=decodeImage(path,path,token);
|
||||
if(!sameImageRevision(before,imageRevision(path)))
|
||||
if(before && *before!=imageRevision(path))
|
||||
throw std::runtime_error("The image changed while it was opening. Open it again.");
|
||||
return Loaded{std::move(raster),before};
|
||||
});
|
||||
@@ -278,6 +288,18 @@ struct ImageView
|
||||
}
|
||||
}
|
||||
|
||||
void pollExternal()
|
||||
{
|
||||
if(!observedVersion || requested.empty() || reading.valid()) return;
|
||||
std::optional<ImageRevision> revision;
|
||||
try {revision=imageRevision(requested);}
|
||||
catch(const std::exception &) {return;}
|
||||
if(revision==observedVersion) return;
|
||||
if(draft && (GetForegroundWindow()!=window || !IsWindowEnabled(window) || !draft->dialogs.reloadChanged)) return;
|
||||
observedVersion=revision;
|
||||
if(!draft || draft->dialogs.reloadChanged(window)) request(requested,true);
|
||||
}
|
||||
|
||||
double factor() const
|
||||
{
|
||||
if(!fit || !width || !height) return zoom;
|
||||
@@ -362,6 +384,7 @@ struct ImageView
|
||||
draft->dialogs.confirm(window,L"Replace the original image?\r\n\r\n"+requested.native(),L"Replace original"))
|
||||
{
|
||||
draft->version=saveImage(transformImage(draft->original,draft->geometry),requested,&*draft->version);
|
||||
observedVersion=draft->version;
|
||||
draft->saved=draft->geometry;
|
||||
updateButtons();
|
||||
}
|
||||
@@ -498,6 +521,7 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
view.layout();
|
||||
view.updateButtons();
|
||||
if(!view.embedded && !view.load) SetTimer(window,externalImageTimer,500,nullptr);
|
||||
return 0;
|
||||
}
|
||||
case WM_SIZE: view.layout(); return 0;
|
||||
@@ -514,7 +538,10 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
case WM_ERASEBKGND: return 1;
|
||||
case WM_PAINT: view.paint(); return 0;
|
||||
case WM_DRAWITEM: view.paintButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp)); return TRUE;
|
||||
case WM_TIMER: if(wp==imageTimer) view.poll(); return 0;
|
||||
case WM_TIMER:
|
||||
if(wp==imageTimer) view.poll();
|
||||
if(wp==externalImageTimer) view.pollExternal();
|
||||
return 0;
|
||||
case WM_COMMAND:
|
||||
if(HIWORD(wp)==BN_CLICKED) {view.action(LOWORD(wp)); SetFocus(window);}
|
||||
return 0;
|
||||
@@ -622,4 +649,24 @@ void showImageViewFile(HWND window,const std::filesystem::path &path)
|
||||
{
|
||||
if(const auto found=imageViews.find(window);found!=imageViews.end()) found->second->request(path);
|
||||
}
|
||||
|
||||
std::optional<ImageWindowSession> imageWindowSession(HWND window)
|
||||
{
|
||||
const auto found=imageViews.find(window);
|
||||
if(found==imageViews.end()) return {};
|
||||
const auto &view=*found->second;
|
||||
if(view.embedded || view.load || !isLocalDocumentPath(view.requested)) return {};
|
||||
return ImageWindowSession{view.requested,view.draft.has_value(),view.fit,view.zoom,view.x,view.y};
|
||||
}
|
||||
|
||||
void restoreImageWindowSession(HWND window,const ImageWindowSession &state)
|
||||
{
|
||||
const auto found=imageViews.find(window);
|
||||
if(found==imageViews.end()) return;
|
||||
auto &view=*found->second;
|
||||
view.fit=state.fit;
|
||||
view.zoom=std::isfinite(state.zoom)?std::clamp(state.zoom,0.05,32.0):1.0;
|
||||
view.x=std::isfinite(state.x)?state.x:0;
|
||||
view.y=std::isfinite(state.y)?state.y:0;
|
||||
}
|
||||
}
|
||||
@@ -30,10 +30,22 @@ struct ImageEditDialogs
|
||||
std::function<bool(HWND,const std::wstring &,const wchar_t *)> confirm;
|
||||
std::function<void(HWND,const wchar_t *)> report;
|
||||
std::function<bool(HWND)> dismissOwned;
|
||||
std::function<bool(HWND)> reloadChanged;
|
||||
};
|
||||
|
||||
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
|
||||
const std::filesystem::path &initial,ImageLoad load={},std::function<void(HWND)> onClose={},ImageLoadRetry retry={},
|
||||
const ImageEditDialogs *editor=nullptr);
|
||||
void showImageViewFile(HWND window,const std::filesystem::path &path);
|
||||
|
||||
struct ImageWindowSession
|
||||
{
|
||||
std::filesystem::path path;
|
||||
bool editor{}, fit=true;
|
||||
double zoom=1, x{}, y{};
|
||||
RECT bounds{};
|
||||
bool maximized{};
|
||||
};
|
||||
std::optional<ImageWindowSession> imageWindowSession(HWND window);
|
||||
void restoreImageWindowSession(HWND window,const ImageWindowSession &state);
|
||||
}
|
||||
+15
-3
@@ -834,9 +834,9 @@ constexpr DWORD defaultStatusFields=15;
|
||||
int sizeWidth=defaultSizeWidth;
|
||||
bool alignExtensions=defaultAlignExtensions, showDetails=defaultShowDetails;
|
||||
bool alignFolders=defaultAlignFolders;
|
||||
bool rightClickMarks{}, showDriveButtons{}, compactLayout{};
|
||||
bool rightClickMarks{}, showDriveButtons{}, compactLayout{}, restoreDocuments{};
|
||||
constexpr wchar_t rightClickMarksKey[]=L"RightClickMarks", driveButtonsKey[]=L"ShowDriveButtons",
|
||||
compactLayoutKey[]=L"CompactPanelLayout";
|
||||
compactLayoutKey[]=L"CompactPanelLayout",restoreDocumentsKey[]=L"RestoreLocalDocuments";
|
||||
constexpr int firstDriveButton=660, moreDriveButton=firstDriveButton+26;
|
||||
std::array<HWND,27> driveButtons{};
|
||||
DWORD statusFields=defaultStatusFields;
|
||||
@@ -920,6 +920,7 @@ struct FilesNoticeOptions
|
||||
FilesNoticeTone tone{FilesNoticeTone::dialog};
|
||||
bool processes{};
|
||||
bool saveChanges{}, chooseTransfer{};
|
||||
const wchar_t *accept{}, *decline{};
|
||||
};
|
||||
INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={});
|
||||
void openMenu(HWND window, int index);
|
||||
@@ -4516,7 +4517,13 @@ ks::files::TextDialogs textWindowDialogs()
|
||||
{
|
||||
return showFilesNotice(owner,L"This file is already open. Switch to its window?",L"Files",
|
||||
{.confirm=true})==IDYES;
|
||||
},chooseTextSaveOptions};
|
||||
},chooseTextSaveOptions,
|
||||
[](HWND owner)
|
||||
{
|
||||
return showFilesNotice(owner,L"The file changed outside Files. Reload the disk version?",
|
||||
L"File changed on disk",{.confirm=true,.tone=FilesNoticeTone::warning,
|
||||
.accept=L"&Reload",.decline=L"&Keep buffer"})==IDYES;
|
||||
}};
|
||||
}
|
||||
|
||||
void refreshQuickView(const Panel &panel)
|
||||
@@ -5995,6 +6002,8 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
ShowWindow(GetDlgItem(window,IDYES),SW_SHOW);
|
||||
ShowWindow(GetDlgItem(window,IDNO),SW_SHOW);
|
||||
}
|
||||
if(notice.options.accept) SetDlgItemTextW(window,IDYES,notice.options.accept);
|
||||
if(notice.options.decline) SetDlgItemTextW(window,IDNO,notice.options.decline);
|
||||
if(notice.options.saveChanges)
|
||||
{
|
||||
SetDlgItemTextW(window,IDYES,L"&Save");
|
||||
@@ -8169,6 +8178,7 @@ bool loadFilesPreferences(HWND window)
|
||||
rightClickMarks=preference(rightClickMarksKey,0)!=0;
|
||||
showDriveButtons=preference(driveButtonsKey,0)!=0;
|
||||
compactLayout=preference(compactLayoutKey,0)!=0;
|
||||
restoreDocuments=preference(restoreDocumentsKey,0)!=0;
|
||||
statusFields=preference(L"StatusFields",defaultStatusFields)&15;
|
||||
loadCommandHistoryKeys();
|
||||
loadComparisonShortcut();
|
||||
@@ -9299,6 +9309,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
return 0;
|
||||
}
|
||||
savePlacement(window);
|
||||
ks::files::saveLocalDocumentSession(schemeKey,restoreDocuments);
|
||||
for(int i=0;i<2;++i)
|
||||
{
|
||||
saveFtpPanelLocation(panels[i],i);
|
||||
@@ -9407,6 +9418,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
}
|
||||
if(!restorePlacement(window)) ShowWindow(window, show);
|
||||
SetFocus(terminalInput);
|
||||
if(restoreDocuments) ks::files::restoreLocalDocumentSession(window,textWindowDialogs(),schemeKey,imageEditDialogs());
|
||||
MSG message{};
|
||||
for(;;)
|
||||
{
|
||||
|
||||
+11
-1
@@ -20,6 +20,7 @@ constexpr int appearanceControls[]{281,282};
|
||||
enum AppearanceSection { Font, DialogFrame };
|
||||
constexpr int outerFramePadding=303,innerFramePadding=305,rowTextPadding=307;
|
||||
constexpr int dialogFrameControls[]{302,outerFramePadding,304,innerFramePadding,306,rowTextPadding};
|
||||
constexpr int restoreDocumentsControl=524;
|
||||
constexpr int textTabWidth=357,textLineEnding=359,
|
||||
textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368;
|
||||
constexpr int textControls[]{350,351,352,353,356,textTabWidth,
|
||||
@@ -112,6 +113,7 @@ struct OptionsBaseline
|
||||
DWORD width=static_cast<DWORD>(sizeWidth), fields=statusFields;
|
||||
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
|
||||
bool mouseMarks=rightClickMarks, drives=showDriveButtons, compact=compactLayout;
|
||||
bool restoreLocal=restoreDocuments;
|
||||
std::array<PanelMode,2> modes{panels[0].mode,panels[1].mode};
|
||||
ks::files::TextSettings text=ks::files::loadTextPreferences();
|
||||
ComparisonAppearance comparison=readComparisonAppearance();
|
||||
@@ -187,7 +189,7 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
|
||||
panelModeOption(dialog,0)!=base.modes[0] || panelModeOption(dialog,1)!=base.modes[1] ||
|
||||
checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details ||
|
||||
checked(rightClickMarksControl)!=base.mouseMarks || checked(driveButtonsControl)!=base.drives ||
|
||||
checked(compactLayoutControl)!=base.compact ||
|
||||
checked(compactLayoutControl)!=base.compact || checked(restoreDocumentsControl)!=base.restoreLocal ||
|
||||
fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles ||
|
||||
draft.framePadding!=base.padding || optionsFontChanged(draft) ||
|
||||
optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal ||
|
||||
@@ -508,6 +510,7 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section)
|
||||
show(commandLineControls,page==CommandLine && section==0);
|
||||
show(markdownControls,markdown);
|
||||
show(textControls,textOptionsPage(page) && !markdown);
|
||||
ShowWindow(GetDlgItem(dialog,restoreDocumentsControl),page==TextViewer && !markdown?SW_SHOW:SW_HIDE);
|
||||
show(editingControls,page==TextEditor);
|
||||
if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]);
|
||||
const bool fileTypes=page==PanelColors && section==fileStyleSection;
|
||||
@@ -618,6 +621,7 @@ void filterOptions(HWND dialog,OptionsDraft &draft)
|
||||
const bool propertyMatches=matches(L"Tab width") ||
|
||||
matches(L"Color scheme") || matches(L"Save scheme") || matches(L"Customize colors") ||
|
||||
(page==TextEditor && matches(L"Line endings for new lines")) ||
|
||||
(page==TextViewer && matches(L"Restore local Viewer and Editor windows after restart")) ||
|
||||
std::any_of(std::begin(textChecks),std::end(textChecks),[&](const auto &check)
|
||||
{return (page==TextEditor || check.id<354) && matches(check.name);}) ||
|
||||
std::any_of(std::begin(ks::files::textColorNames),std::end(ks::files::textColorNames),matches);
|
||||
@@ -689,6 +693,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
|
||||
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
|
||||
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
|
||||
CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments);
|
||||
showPanelModeOptions(dialog);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
@@ -885,6 +890,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
}
|
||||
if(draft->page==allOptions || (draft->page==Appearance && draft->section!=Font))
|
||||
draft->framePadding=defaultDialogFramePadding;
|
||||
if(draft->page==allOptions || (draft->page==TextViewer && draft->section!=markdownSection))
|
||||
CheckDlgButton(dialog,restoreDocumentsControl,BST_UNCHECKED);
|
||||
if(draft->page==allOptions || textOptionsPage(draft->page))
|
||||
for(int page=TextViewer;page<=TextEditor;++page)
|
||||
if(draft->page==allOptions || (draft->page==page && draft->section!=markdownSection))
|
||||
@@ -909,6 +916,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
case 201:
|
||||
case 202: case 203: case 204: case 205: case 206: case 207: case 208:
|
||||
case 273: case 274: case rightClickMarksControl: case driveButtonsControl: case compactLayoutControl:
|
||||
case restoreDocumentsControl:
|
||||
case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
@@ -1064,6 +1072,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
saveChanged(rightClickMarksKey,checked(rightClickMarksControl),base.mouseMarks);
|
||||
saveChanged(driveButtonsKey,checked(driveButtonsControl),base.drives);
|
||||
saveChanged(compactLayoutKey,checked(compactLayoutControl),base.compact);
|
||||
saveChanged(restoreDocumentsKey,checked(restoreDocumentsControl),base.restoreLocal);
|
||||
DWORD fields=preference(L"StatusFields",defaultStatusFields)&15;
|
||||
const auto initialFields=fields;
|
||||
for(int i=0;i<4;++i)
|
||||
@@ -1109,6 +1118,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
|
||||
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
|
||||
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
|
||||
CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments);
|
||||
showPanelModeOptions(dialog);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
|
||||
@@ -42,7 +42,7 @@ HANDLE openSource(const std::filesystem::path &path, bool editable)
|
||||
HANDLE trackReplacement(const std::filesystem::path &path)
|
||||
{
|
||||
// A metadata-only handle survives the rename without blocking ReplaceFile.
|
||||
const auto handle=CreateFileW(path.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
|
||||
const auto handle=CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
|
||||
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
|
||||
if(handle==INVALID_HANDLE_VALUE) fail("Track replacement file");
|
||||
return handle;
|
||||
@@ -98,6 +98,11 @@ std::filesystem::path createTemporary(const std::filesystem::path &directory, Fi
|
||||
return path;
|
||||
}
|
||||
|
||||
void createEditorSnapshot(File &file)
|
||||
{
|
||||
createTemporary(std::filesystem::temp_directory_path(),file,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE);
|
||||
}
|
||||
|
||||
bool isUtf16(TextEncoding encoding)
|
||||
{
|
||||
return encoding==TextEncoding::utf16le || encoding==TextEncoding::utf16be;
|
||||
@@ -182,8 +187,8 @@ std::string convertLineEndings(std::string_view text,TextLineEnding ending)
|
||||
}
|
||||
}
|
||||
|
||||
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding)
|
||||
: path_(std::move(path)), editable_(editable)
|
||||
TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding,bool snapshotEdits)
|
||||
: path_(std::move(path)), editable_(editable),snapshotEdits_(snapshotEdits && editable)
|
||||
{
|
||||
if(path_.empty())
|
||||
{
|
||||
@@ -213,7 +218,20 @@ TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding
|
||||
encoding_=encoding;
|
||||
if(prefix.starts_with(signature(encoding_))) bom_=signature(encoding_).size();
|
||||
if(isUtf16(encoding_) && size_%2) throw std::runtime_error("The UTF-16 file has an incomplete code unit.");
|
||||
source_ = source.release();
|
||||
if(snapshotEdits_)
|
||||
{
|
||||
version_=fileVersion(source.handle);
|
||||
File snapshot;
|
||||
createEditorSnapshot(snapshot);
|
||||
for(uint64_t offset=0;offset<size_;)
|
||||
{
|
||||
const auto block=read(source.handle,offset,static_cast<size_t>(std::min(pageBytes,size_-offset)));
|
||||
write(snapshot.handle,block);
|
||||
offset+=block.size();
|
||||
}
|
||||
source_=snapshot.release();
|
||||
}
|
||||
else source_ = source.release();
|
||||
}
|
||||
|
||||
TextDocument::~TextDocument()
|
||||
@@ -467,13 +485,26 @@ void TextDocument::stage(uint64_t page, std::string_view utf8)
|
||||
bool TextDocument::save()
|
||||
{
|
||||
if (!modified()) return true;
|
||||
const auto verify=[&](HANDLE current) {
|
||||
if(version_ && *version_!=fileVersion(current))
|
||||
throw std::runtime_error("The file changed outside Files. Your editor buffer was kept.");
|
||||
if(!version_ && !sameFile(source_,current))
|
||||
throw std::runtime_error("The file was replaced outside KSwitcher.");
|
||||
};
|
||||
if(version_)
|
||||
{
|
||||
File current{openSource(path_,true)};
|
||||
verify(current.handle);
|
||||
}
|
||||
PendingSave pending;
|
||||
File output;
|
||||
File output,snapshot;
|
||||
if(snapshotEdits_) createEditorSnapshot(snapshot);
|
||||
pending.path = createTemporary(path_.parent_path(), output, FILE_ATTRIBUTE_NORMAL);
|
||||
|
||||
uint64_t written{};
|
||||
const auto append = [&](std::string_view bytes) {
|
||||
write(output.handle, bytes);
|
||||
if(snapshotEdits_) write(snapshot.handle,bytes);
|
||||
written += bytes.size();
|
||||
};
|
||||
const auto copyUntil = [&](uint64_t &offset, uint64_t end) {
|
||||
@@ -497,7 +528,7 @@ bool TextDocument::save()
|
||||
|
||||
File replacement{trackReplacement(pending.path)};
|
||||
File current{openSource(path_, true)};
|
||||
if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher.");
|
||||
verify(current.handle);
|
||||
const auto backup = temporaryPath(path_.parent_path());
|
||||
if (const auto error=replaceFileWithBackup(path_,pending.path,backup))
|
||||
{
|
||||
@@ -505,7 +536,9 @@ bool TextDocument::save()
|
||||
fail("Replace original file");
|
||||
}
|
||||
pending.path.clear();
|
||||
const auto newSource = ReOpenFile(replacement.handle, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, 0);
|
||||
if(snapshotEdits_) version_=fileVersion(replacement.handle);
|
||||
const auto newSource=snapshotEdits_?snapshot.release():
|
||||
ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
|
||||
DeleteFileW(backup.c_str());
|
||||
CloseHandle(source_);
|
||||
source_ = newSource;
|
||||
@@ -523,10 +556,16 @@ bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
|
||||
const auto bytes=encode(convertLineEndings(readPage(0),format.lineEnding),format.encoding);
|
||||
const auto bom=format.bom?signature(format.encoding):std::string_view{};
|
||||
PendingSave pending;
|
||||
File output;
|
||||
File output,snapshot;
|
||||
pending.path=createTemporary(path.parent_path(),output,FILE_ATTRIBUTE_NORMAL);
|
||||
write(output.handle,bom);
|
||||
write(output.handle,bytes);
|
||||
if(snapshotEdits_)
|
||||
{
|
||||
createEditorSnapshot(snapshot);
|
||||
write(snapshot.handle,bom);
|
||||
write(snapshot.handle,bytes);
|
||||
}
|
||||
if(!FlushFileBuffers(output.handle)) fail("Flush saved file");
|
||||
CloseHandle(output.release());
|
||||
File replacement{trackReplacement(pending.path)};
|
||||
@@ -539,7 +578,8 @@ bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format)
|
||||
changes_.clear();
|
||||
if(spool_!=INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_,INVALID_HANDLE_VALUE));
|
||||
spoolSize_=0;
|
||||
source_=ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
|
||||
if(snapshotEdits_) version_=fileVersion(replacement.handle);
|
||||
source_=snapshotEdits_?snapshot.release():ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0);
|
||||
return source_!=INVALID_HANDLE_VALUE;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include "files_win32_replace.h"
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <map>
|
||||
@@ -43,7 +43,7 @@ public:
|
||||
static constexpr size_t editLimit = 8 * pageBytes;
|
||||
|
||||
explicit TextDocument(std::filesystem::path path, bool editable = true,
|
||||
TextEncoding encoding=TextEncoding::automatic);
|
||||
TextEncoding encoding=TextEncoding::automatic,bool snapshotEdits=false);
|
||||
~TextDocument();
|
||||
TextDocument(const TextDocument &) = delete;
|
||||
TextDocument &operator=(const TextDocument &) = delete;
|
||||
@@ -63,6 +63,7 @@ public:
|
||||
bool saveNew(std::filesystem::path path, TextSaveFormat format);
|
||||
const wchar_t *encodingName() const;
|
||||
TextEncoding encoding() const { return encoding_; }
|
||||
const std::optional<LocalFileVersion> &expectedVersion() const {return version_;}
|
||||
|
||||
private:
|
||||
struct Change { uint64_t offset; size_t size; };
|
||||
@@ -73,7 +74,8 @@ private:
|
||||
uint64_t size_{}, spoolSize_{};
|
||||
size_t bom_{};
|
||||
TextEncoding encoding_ = TextEncoding::utf8;
|
||||
bool editable_;
|
||||
bool editable_, snapshotEdits_;
|
||||
std::optional<LocalFileVersion> version_;
|
||||
std::map<uint64_t, Change> changes_;
|
||||
|
||||
std::string decode(std::string bytes) const;
|
||||
|
||||
+219
-28
@@ -776,7 +776,7 @@ public:
|
||||
{
|
||||
if (backend) remote=std::make_unique<RemoteTextFile>(*backend,original);
|
||||
else if(!embedded) document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,
|
||||
hex?TextEncoding::utf8:options.encoding);
|
||||
hex?TextEncoding::utf8:options.encoding,isLocalDocumentPath(original));
|
||||
if(options.encoding!=TextEncoding::automatic)
|
||||
{
|
||||
newFormat.encoding=options.encoding;
|
||||
@@ -806,6 +806,8 @@ public:
|
||||
void previewFile(const std::filesystem::path &path);
|
||||
void previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff);
|
||||
bool openBookmark(const ViewerBookmark &bookmark);
|
||||
nlohmann::json sessionState() const;
|
||||
void restoreSession(const nlohmann::json &state);
|
||||
std::filesystem::path original;
|
||||
const std::string peerId;
|
||||
|
||||
@@ -860,13 +862,8 @@ private:
|
||||
bool previewWanted{}, previewVisible{}, previewRetried{};
|
||||
ULONGLONG previewDeadline{};
|
||||
ULONGLONG nextFileCheck{};
|
||||
struct FileStamp
|
||||
{
|
||||
uint64_t writeTime, fileIndex, size;
|
||||
DWORD volume;
|
||||
bool operator==(const FileStamp &) const = default;
|
||||
};
|
||||
std::optional<FileStamp> previewStamp;
|
||||
std::optional<LocalFileVersion> previewStamp, observedVersion;
|
||||
bool diskChanged{};
|
||||
struct MarkdownTask
|
||||
{
|
||||
uint64_t revision;
|
||||
@@ -875,6 +872,8 @@ private:
|
||||
};
|
||||
std::string previewText;
|
||||
uint64_t previewRevision{};
|
||||
int renderedScroll{};
|
||||
std::optional<int> sessionScroll;
|
||||
std::optional<MarkdownTask> pendingTask;
|
||||
std::optional<size_t> taskOffset;
|
||||
std::string previewFragment;
|
||||
@@ -918,6 +917,7 @@ private:
|
||||
static constexpr UINT_PTR quickViewTimer = 5;
|
||||
static constexpr UINT_PTR bookmarkTimer = 6;
|
||||
static constexpr UINT_PTR savedViewerTimer = 7;
|
||||
static constexpr UINT_PTR externalChangeTimer = 8;
|
||||
struct BookmarkLocation
|
||||
{
|
||||
std::filesystem::path path;
|
||||
@@ -1012,7 +1012,7 @@ private:
|
||||
void changeMode();
|
||||
ViewerPosition currentPosition() const;
|
||||
void restorePosition(const ViewerPosition &position);
|
||||
void showTextMode(const ViewerPosition &position,std::string contents);
|
||||
void showTextMode(const ViewerPosition &position,std::string contents,bool takeFocus=true);
|
||||
void suspendEditor(std::unique_ptr<RemoteTextFile> saved={});
|
||||
void restoreEditor();
|
||||
void finishSavedViewer();
|
||||
@@ -1024,7 +1024,9 @@ private:
|
||||
void stopPreview(bool refresh=true,bool keepBrowser=false);
|
||||
void renderPreview(bool keepPosition=false);
|
||||
void applyMarkdownPreferences(const MarkdownPreferences &preferences);
|
||||
std::optional<FileStamp> previewFileStamp() const;
|
||||
std::optional<LocalFileVersion> previewFileStamp() const;
|
||||
void rememberLocalVersion();
|
||||
void pollExternalChanges();
|
||||
void refreshPreview();
|
||||
void startMarkdownTask();
|
||||
void finishMarkdownTask();
|
||||
@@ -1625,6 +1627,7 @@ void TextWindow::go(uint64_t index)
|
||||
|
||||
void TextWindow::initializeDocument(std::optional<std::string> firstPage)
|
||||
{
|
||||
rememberLocalVersion();
|
||||
if(hex)
|
||||
{
|
||||
releaseMenu();
|
||||
@@ -1905,6 +1908,7 @@ void TextWindow::finishSave()
|
||||
navigationHistory.clear();
|
||||
updateTitle();
|
||||
}
|
||||
rememberLocalVersion();
|
||||
if (!reopened)
|
||||
{
|
||||
search.style.message(window, L"The file was saved. Reopen it to continue editing.");
|
||||
@@ -2000,8 +2004,61 @@ void TextWindow::restorePosition(const ViewerPosition &position)
|
||||
send(SCI_SETXOFFSET,position.horizontal);
|
||||
}
|
||||
|
||||
void TextWindow::showTextMode(const ViewerPosition &position,std::string contents)
|
||||
void writeDocumentPlacement(nlohmann::json &state,HWND window)
|
||||
{
|
||||
WINDOWPLACEMENT placement{sizeof(placement)};
|
||||
if(GetWindowPlacement(window,&placement))
|
||||
{
|
||||
const auto &rect=placement.rcNormalPosition;
|
||||
state["rect"]={rect.left,rect.top,rect.right,rect.bottom};
|
||||
state["maximized"]=placement.showCmd==SW_SHOWMAXIMIZED ||
|
||||
(placement.flags&WPF_RESTORETOMAXIMIZED)!=0;
|
||||
}
|
||||
}
|
||||
|
||||
RECT readDocumentBounds(const nlohmann::json &state)
|
||||
{
|
||||
if(!state.contains("rect")) return {};
|
||||
const auto rect=state.at("rect").get<std::array<LONG,4>>();
|
||||
return {rect[0],rect[1],rect[2],rect[3]};
|
||||
}
|
||||
|
||||
int restoreDocumentPlacement(HWND window,HWND owner,const RECT &bounds,bool maximized)
|
||||
{
|
||||
if(bounds.left>=bounds.right || bounds.top>=bounds.bottom || !MonitorFromRect(&bounds,MONITOR_DEFAULTTONULL))
|
||||
return IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW;
|
||||
WINDOWPLACEMENT placement{sizeof(placement)};
|
||||
placement.rcNormalPosition=bounds;
|
||||
placement.showCmd=maximized?SW_SHOWMAXIMIZED:SW_SHOWNORMAL;
|
||||
SetWindowPlacement(window,&placement);
|
||||
return maximized?SW_MAXIMIZE:SW_SHOWNORMAL;
|
||||
}
|
||||
|
||||
nlohmann::json TextWindow::sessionState() const
|
||||
{
|
||||
if(embedded || remote || draft || !document || !isLocalDocumentPath(original)) return nullptr;
|
||||
const auto position=currentPosition();
|
||||
nlohmann::json state{{"path",utf8(original.native())},{"editor",edit},{"hex",hex},
|
||||
{"page",position.page},{"anchor",position.anchor},{"caret",position.caret},
|
||||
{"firstLine",position.firstLine},{"horizontal",position.horizontal}};
|
||||
if(previewVisible) state["renderedScroll"]=renderedScroll;
|
||||
writeDocumentPlacement(state,window);
|
||||
return state;
|
||||
}
|
||||
|
||||
void TextWindow::restoreSession(const nlohmann::json &state)
|
||||
{
|
||||
ViewerPosition position{std::min(state.value("page",uint64_t{}),pageTotal?pageTotal-1:0),
|
||||
state.value("anchor",LRESULT{}),state.value("caret",LRESULT{}),
|
||||
std::max<LRESULT>(0,state.value("firstLine",LRESULT{})),std::max<LRESULT>(0,state.value("horizontal",LRESULT{}))};
|
||||
if(position.page!=page) loadPage(position.page);
|
||||
restorePosition(position);
|
||||
if(state.contains("renderedScroll")) sessionScroll=std::max(0,state.at("renderedScroll").get<int>());
|
||||
}
|
||||
|
||||
void TextWindow::showTextMode(const ViewerPosition &position,std::string contents,bool takeFocus)
|
||||
{
|
||||
rememberLocalVersion();
|
||||
if(canPreview()) ShowWindow(editor,SW_HIDE);
|
||||
prefs = loadTextPreferences().profiles[edit];
|
||||
releaseMenu();
|
||||
@@ -2014,7 +2071,7 @@ void TextWindow::showTextMode(const ViewerPosition &position,std::string content
|
||||
updateTaskbarGroup();
|
||||
updatePreview();
|
||||
layout();
|
||||
focusContent();
|
||||
if(takeFocus) focusContent();
|
||||
}
|
||||
|
||||
void TextWindow::changeMode()
|
||||
@@ -2022,7 +2079,8 @@ 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());
|
||||
auto replacement=std::make_unique<TextDocument>(remote?remote->cache:original,!edit,document->encoding(),
|
||||
!remote && isLocalDocumentPath(original));
|
||||
position.page=std::min(position.page,replacement->pages()-1);
|
||||
auto contents=replacement->readPage(position.page);
|
||||
document=std::move(replacement);
|
||||
@@ -2237,20 +2295,55 @@ void TextWindow::goToFragment(std::string_view fragment)
|
||||
else previewFragment=fragment;
|
||||
}
|
||||
|
||||
std::optional<TextWindow::FileStamp> TextWindow::previewFileStamp() const
|
||||
std::optional<LocalFileVersion> TextWindow::previewFileStamp() const
|
||||
{
|
||||
if(remote) return {};
|
||||
if(remote || !isLocalDocumentPath(original)) return {};
|
||||
const auto file=CreateFileW(original.c_str(),FILE_READ_ATTRIBUTES,
|
||||
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
|
||||
if(file==INVALID_HANDLE_VALUE) return {};
|
||||
BY_HANDLE_FILE_INFORMATION state{};
|
||||
const auto found=GetFileInformationByHandle(file,&state);
|
||||
std::optional<LocalFileVersion> stamp;
|
||||
try {stamp=fileVersion(file);} catch(const std::system_error &) {}
|
||||
CloseHandle(file);
|
||||
if(!found) return {};
|
||||
const auto combine=[](DWORD high,DWORD low){return (uint64_t{high}<<32)|low;};
|
||||
return FileStamp{combine(state.ftLastWriteTime.dwHighDateTime,state.ftLastWriteTime.dwLowDateTime),
|
||||
combine(state.nFileIndexHigh,state.nFileIndexLow),
|
||||
combine(state.nFileSizeHigh,state.nFileSizeLow),state.dwVolumeSerialNumber};
|
||||
return stamp;
|
||||
}
|
||||
|
||||
void TextWindow::rememberLocalVersion()
|
||||
{
|
||||
if(embedded || remote || !document) return;
|
||||
observedVersion=edit?document->expectedVersion():previewFileStamp();
|
||||
diskChanged=false;
|
||||
}
|
||||
|
||||
void TextWindow::pollExternalChanges()
|
||||
{
|
||||
if(embedded || remote || draft || !document || busy() || previewWanted || navigation.valid() || !observedVersion)
|
||||
return;
|
||||
const auto stamp=previewFileStamp();
|
||||
if(!stamp || stamp==observedVersion) return;
|
||||
if(edit && (GetForegroundWindow()!=window || !IsWindowEnabled(window) || !search.style.reloadChanged)) return;
|
||||
try
|
||||
{
|
||||
if(edit)
|
||||
{
|
||||
observedVersion=stamp;
|
||||
diskChanged=true;
|
||||
invalidate();
|
||||
if(!search.style.reloadChanged(window)) return;
|
||||
}
|
||||
auto replacement=std::make_unique<TextDocument>(original,edit,hex?TextEncoding::utf8:TextEncoding::automatic,edit);
|
||||
auto position=currentPosition();
|
||||
const auto pages=hex?1+(replacement->size()?replacement->size()-1:0)/hexPageBytes:replacement->pages();
|
||||
position.page=std::min(position.page,pages-1);
|
||||
auto contents=hex?formatHexPage(replacement->readBytes(position.page*hexPageBytes,hexPageBytes),
|
||||
position.page*hexPageBytes):replacement->readPage(position.page);
|
||||
if(!hex) language=automatic=detectLanguage(original,contents);
|
||||
document=std::move(replacement);
|
||||
showTextMode(position,std::move(contents),edit);
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(edit) search.style.message(window,wide(error.what()).c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void TextWindow::renderPreview(bool keepPosition)
|
||||
@@ -2265,6 +2358,7 @@ void TextWindow::renderPreview(bool keepPosition)
|
||||
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
|
||||
{"keepPosition",keepPosition}};
|
||||
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
|
||||
if(sessionScroll) message["scroll"]=*std::exchange(sessionScroll,{});
|
||||
restoreScroll=false;
|
||||
preview.post(wide(message.dump(-1,' ',false,nlohmann::json::error_handler_t::replace)));
|
||||
}
|
||||
@@ -2438,6 +2532,11 @@ void TextWindow::previewMessage(const std::wstring &value)
|
||||
if(embedded && action!="image" && action!="rendered" && action!="failed") return;
|
||||
const auto revision=message.value("revision",previewRevision);
|
||||
if(embedded && revision!=previewRevision) return;
|
||||
if(action=="scroll")
|
||||
{
|
||||
if(!embedded && revision==previewRevision) renderedScroll=std::max(0,message.at("top").get<int>());
|
||||
return;
|
||||
}
|
||||
if(action=="failed")
|
||||
{
|
||||
PostMessageW(window,previewFailed,static_cast<WPARAM>(revision),0);
|
||||
@@ -2779,6 +2878,7 @@ void TextWindow::paint()
|
||||
if(pageTotal>1)
|
||||
status+=L" │ Page "+std::to_wstring(page+1)+L"/"+std::to_wstring(pageTotal)+
|
||||
L" @ "+std::to_wstring(pageOffset);
|
||||
if(diskChanged && edit) status+=L" │ Disk changed";
|
||||
status+=L" │ "+std::to_wstring(fileSize)+L" B";
|
||||
if(bookmarkTask.valid()) status+=L" │ Locating line…";
|
||||
drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status);
|
||||
@@ -3083,6 +3183,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
else self->initializeDocument();
|
||||
if(!self->embedded)
|
||||
{
|
||||
if(!self->remote) SetTimer(window,externalChangeTimer,500,nullptr);
|
||||
self->updateIcons(GetDpiForWindow(window));
|
||||
self->updateTaskbarGroup();
|
||||
}
|
||||
@@ -3169,6 +3270,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
if (wparam == saveTimer) self->finishSave();
|
||||
if (wparam == openTimer) self->finishOpen();
|
||||
if (wparam == previewTimer) self->pollImages();
|
||||
if (wparam == externalChangeTimer) self->pollExternalChanges();
|
||||
if (wparam == navigationTimer) self->finishNavigation();
|
||||
if (wparam == quickViewTimer) self->pollQuickView();
|
||||
if (wparam == bookmarkTimer) self->finishBookmark();
|
||||
@@ -3427,7 +3529,8 @@ void previewImageQuickViewFile(HWND window,const std::filesystem::path &path)
|
||||
}
|
||||
|
||||
void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const std::filesystem::path &path,
|
||||
TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source,const ImageEditDialogs *editor)
|
||||
TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source,const ImageEditDialogs *editor,
|
||||
const ImageWindowSession *session)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -3469,15 +3572,23 @@ void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const
|
||||
const auto icon=LoadImageW(instance,MAKEINTRESOURCEW(iconId),IMAGE_ICON,0,0,LR_SHARED|LR_DEFAULTSIZE);
|
||||
if(icon) SendMessageW(window,WM_SETICON,ICON_BIG,reinterpret_cast<LPARAM>(icon));
|
||||
setFileWindowTaskbar(window,iconId,editor?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer");
|
||||
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
|
||||
if(session) restoreImageWindowSession(window,*session);
|
||||
ShowWindow(window,session?restoreDocumentPlacement(window,owner,session->bounds,session->maximized):
|
||||
IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
|
||||
SetFocus(window);
|
||||
}
|
||||
catch(const std::exception &error) {dialogs.message(owner,wide(error.what()).c_str());}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(!session) dialogs.message(owner,wide(error.what()).c_str());
|
||||
else log(L"Restore Files image: "+wide(error.what()));
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options,
|
||||
const nlohmann::json *session=nullptr)
|
||||
{
|
||||
HWND created{};
|
||||
if(!edit && !options.draft && !options.hex && !options.line && isImagePath(path))
|
||||
{
|
||||
openImageWindow(owner,{path},path,dialogs,nullptr,backend);
|
||||
@@ -3513,10 +3624,90 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool
|
||||
WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN,bounds.left,bounds.top,bounds.right-bounds.left,
|
||||
bounds.bottom-bounds.top,nullptr,nullptr,instance,&state);
|
||||
if(!window) return;
|
||||
ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW);
|
||||
created=window;
|
||||
int show=IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW;
|
||||
if(session)
|
||||
{
|
||||
state->restoreSession(*session);
|
||||
show=restoreDocumentPlacement(window,owner,readDocumentBounds(*session),session->value("maximized",false));
|
||||
}
|
||||
ShowWindow(window,show);
|
||||
SendMessageW(window,WM_SETFOCUS,0,0);
|
||||
}
|
||||
catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
if(!session) dialogs.message(owner,wide(error.what()).c_str());
|
||||
else
|
||||
{
|
||||
if(created) DestroyWindow(created);
|
||||
log(L"Restore Files document: "+wide(error.what()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
constexpr wchar_t localSessionKey[]=L"LocalDocumentsV1";
|
||||
|
||||
void saveLocalDocumentSession(const wchar_t *registryKey,bool enabled)
|
||||
{
|
||||
if(!enabled)
|
||||
{
|
||||
RegDeleteKeyValueW(HKEY_CURRENT_USER,registryKey,localSessionKey);
|
||||
return;
|
||||
}
|
||||
auto session=nlohmann::json::array();
|
||||
for(const auto window:textWindowOrder)
|
||||
{
|
||||
if(session.size()>=128) break;
|
||||
if(const auto found=textWindows.find(window);found!=textWindows.end())
|
||||
{
|
||||
auto state=found->second->sessionState();
|
||||
if(!state.is_null()) session.push_back(std::move(state));
|
||||
}
|
||||
else if(const auto image=imageWindowSession(window))
|
||||
{
|
||||
nlohmann::json state{{"path",utf8(image->path.native())},{"editor",image->editor},{"image",true},
|
||||
{"fit",image->fit},{"zoom",image->zoom},{"x",image->x},{"y",image->y}};
|
||||
writeDocumentPlacement(state,window);
|
||||
session.push_back(std::move(state));
|
||||
}
|
||||
}
|
||||
const auto text=session.dump();
|
||||
if(text.size()<=1024*1024)
|
||||
RegSetKeyValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,REG_BINARY,text.data(),static_cast<DWORD>(text.size()));
|
||||
}
|
||||
|
||||
void restoreLocalDocumentSession(HWND owner,TextDialogs dialogs,const wchar_t *registryKey,
|
||||
const ImageEditDialogs &imageEditor)
|
||||
{
|
||||
DWORD bytes{};
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS ||
|
||||
!bytes || bytes>1024*1024) return;
|
||||
std::string text(bytes,'\0');
|
||||
if(RegGetValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,RRF_RT_REG_BINARY,nullptr,text.data(),&bytes)!=ERROR_SUCCESS)
|
||||
return;
|
||||
const auto session=nlohmann::json::parse(text.begin(),text.begin()+bytes,nullptr,false);
|
||||
if(!session.is_array()) return;
|
||||
for(size_t i=0;i<std::min<size_t>(128,session.size());++i)
|
||||
{
|
||||
try
|
||||
{
|
||||
const auto &state=session[i];
|
||||
const std::filesystem::path path=wide(state.at("path").get<std::string>());
|
||||
if(!isLocalDocumentPath(path)) continue;
|
||||
const auto attributes=GetFileAttributesW(path.c_str());
|
||||
if(attributes==INVALID_FILE_ATTRIBUTES || (attributes&FILE_ATTRIBUTE_DIRECTORY)) continue;
|
||||
const bool editor=state.value("editor",false);
|
||||
if(state.value("image",false))
|
||||
{
|
||||
if(!isImagePath(path) || (editor && !isEditableImagePath(path))) continue;
|
||||
ImageWindowSession image{path,editor,state.value("fit",true),state.value("zoom",1.0),
|
||||
state.value("x",0.0),state.value("y",0.0),readDocumentBounds(state),state.value("maximized",false)};
|
||||
openImageWindow(owner,{path},path,dialogs,nullptr,nullptr,editor?&imageEditor:nullptr,&image);
|
||||
}
|
||||
else openTextWindowImpl(owner,path,editor,dialogs,nullptr,{},true,{.hex=state.value("hex",false)},&state);
|
||||
}
|
||||
catch(const std::exception &error) {log(L"Restore Files document: "+wide(error.what()));}
|
||||
}
|
||||
}
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
|
||||
@@ -57,6 +57,7 @@ struct TextDialogs
|
||||
bool (*dismissOwned)(HWND);
|
||||
bool (*confirmExisting)(HWND);
|
||||
bool (*saveOptions)(HWND,std::filesystem::path &,TextSaveFormat &);
|
||||
bool (*reloadChanged)(HWND){};
|
||||
};
|
||||
|
||||
struct TextOpenOptions
|
||||
@@ -110,9 +111,10 @@ void previewQuickViewText(HWND window,const std::wstring &title,std::string_view
|
||||
HWND createImageQuickView(HWND owner,TextDialogs dialogs);
|
||||
void previewImageQuickViewFile(HWND window,const std::filesystem::path &path);
|
||||
struct ImageEditDialogs;
|
||||
struct ImageWindowSession;
|
||||
void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const std::filesystem::path &path,
|
||||
TextDialogs dialogs,const lan::FilesPeer *peer=nullptr,const RemoteTextSource *source=nullptr,
|
||||
const ImageEditDialogs *editor=nullptr);
|
||||
const ImageEditDialogs *editor=nullptr,const ImageWindowSession *session=nullptr);
|
||||
void showAllViewerBookmarks(HWND owner,TextDialogs dialogs);
|
||||
|
||||
void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs,
|
||||
@@ -120,6 +122,8 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD
|
||||
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,TextOpenOptions options={});
|
||||
void saveLocalDocumentSession(const wchar_t *registryKey,bool enabled);
|
||||
void restoreLocalDocumentSession(HWND owner,TextDialogs dialogs,const wchar_t *registryKey,const ImageEditDialogs &imageEditor);
|
||||
void textWindowOwnerClosed();
|
||||
void standaloneFilesWindowOpened();
|
||||
void standaloneFilesWindowClosed();
|
||||
|
||||
@@ -5,9 +5,20 @@
|
||||
#include <filesystem>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline bool isLocalDocumentPath(const std::filesystem::path &path)
|
||||
{
|
||||
std::wstring_view name=path.native();
|
||||
if(name.starts_with(L"\\\\?\\")) name.remove_prefix(4);
|
||||
if(name.size()<3 || name[1]!=L':' || (name[2]!=L'\\' && name[2]!=L'/')) return false;
|
||||
const auto type=GetDriveTypeW(std::wstring(name.substr(0,3)).c_str());
|
||||
return type==DRIVE_FIXED || type==DRIVE_REMOVABLE || type==DRIVE_RAMDISK || type==DRIVE_CDROM;
|
||||
}
|
||||
|
||||
inline std::filesystem::path temporaryPath(const std::filesystem::path &directory)
|
||||
{
|
||||
GUID id{};
|
||||
@@ -23,6 +34,31 @@ inline bool sameFileIdentity(const BY_HANDLE_FILE_INFORMATION &left,const BY_HAN
|
||||
left.nFileIndexLow==right.nFileIndexLow;
|
||||
}
|
||||
|
||||
|
||||
struct LocalFileVersion
|
||||
{
|
||||
BY_HANDLE_FILE_INFORMATION info{};
|
||||
LONGLONG changeTime{};
|
||||
|
||||
bool operator==(const LocalFileVersion &other) const
|
||||
{
|
||||
return sameFileIdentity(info,other.info) && changeTime==other.changeTime &&
|
||||
info.nFileSizeHigh==other.info.nFileSizeHigh && info.nFileSizeLow==other.info.nFileSizeLow &&
|
||||
CompareFileTime(&info.ftLastWriteTime,&other.info.ftLastWriteTime)==0;
|
||||
}
|
||||
};
|
||||
|
||||
inline LocalFileVersion fileVersion(HANDLE file)
|
||||
{
|
||||
LocalFileVersion version;
|
||||
if(!GetFileInformationByHandle(file,&version.info))
|
||||
throw std::system_error(static_cast<int>(GetLastError()),std::system_category(),"Read file revision");
|
||||
FILE_BASIC_INFO basics{};
|
||||
if(GetFileInformationByHandleEx(file,FileBasicInfo,&basics,sizeof(basics)))
|
||||
version.changeTime=basics.ChangeTime.QuadPart;
|
||||
return version;
|
||||
}
|
||||
|
||||
inline DWORD replaceFileWithBackup(const std::filesystem::path &original,const std::filesystem::path &replacement,
|
||||
const std::filesystem::path &backup)
|
||||
{
|
||||
|
||||
@@ -171,6 +171,29 @@ void hexBytes(const fs::path &file)
|
||||
"Hex offsets advance by the row width");
|
||||
}
|
||||
|
||||
void watchedEditor(const fs::path &file)
|
||||
{
|
||||
writeFile(file,"original bytes");
|
||||
TextDocument editor(file,true,TextEncoding::automatic,true);
|
||||
check(editor.expectedVersion().has_value(),"local editor captured the original version");
|
||||
writeFile(file,"external bytes");
|
||||
check(editor.readPage(0)=="original bytes","external edit replaced the editor snapshot");
|
||||
editor.stage(0,"editor buffer");
|
||||
bool rejected=false;
|
||||
try {editor.save();}
|
||||
catch(const std::runtime_error &error)
|
||||
{
|
||||
rejected=std::string_view(error.what()).find("changed outside Files")!=std::string_view::npos;
|
||||
}
|
||||
check(rejected && editor.readPage(0)=="editor buffer","external edit was overwritten or the draft was cleared");
|
||||
TextDocument reloaded(file,true,TextEncoding::automatic,true);
|
||||
check(reloaded.readPage(0)=="external bytes","reload did not take the external version");
|
||||
reloaded.stage(0,"confirmed write");
|
||||
check(reloaded.save() && reloaded.readPage(0)=="confirmed write","local save lost the new snapshot");
|
||||
writeFile(file,"next change");
|
||||
check(reloaded.readPage(0)=="confirmed write","the post-save editor lost snapshot isolation");
|
||||
}
|
||||
|
||||
void bookmarkedLines(const fs::path &file)
|
||||
{
|
||||
const auto longLine=std::string(TextDocument::pageBytes+32,'x');
|
||||
@@ -262,6 +285,7 @@ int main()
|
||||
rejectExternalReplacement(fixture.directory / L"external.txt");
|
||||
saveDraft(fixture.directory / L"created.txt");
|
||||
hexBytes(fixture.directory / L"raw.bin");
|
||||
watchedEditor(fixture.directory / L"watched.txt");
|
||||
bookmarkedLines(fixture.directory / L"bookmarks.txt");
|
||||
comparisonEdits();
|
||||
sparseFile(fixture.directory / L"5gib.log");
|
||||
|
||||
Reference in new issue
Block a user