Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1edd0343ef | ||
|
|
6c0e8f0736 | ||
|
|
934521f404 | ||
|
|
2db50fcd0e |
No files matched your search
+11
-1
@@ -686,10 +686,12 @@ Warning і початковий фокус на No.
|
||||
- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший.
|
||||
|
||||
- **Commands → Quick View** або **Ctrl+Q** вмикає перегляд локального
|
||||
тексту, Markdown і зображень у сусідній панелі. Перегляд слідує за курсором активної
|
||||
тексту, Markdown, HTML, зображень і двійкових файлів у сусідній панелі. Перегляд слідує за курсором активної
|
||||
панелі. Повторна команда повертає сусідній каталог, курсор і позначки.
|
||||
Під час перегляду файлові операції з призначенням у сусідній панелі
|
||||
пропонують спершу закрити Quick View.
|
||||
- Для локальних HTML-файлів до 8 МіБ Quick View відкриває **Rendered**. **Show Source** показує початковий текст, **Show Rendered** повертає форматований вигляд. F6 перемикає режими, коли фокус у самому перегляді. Quick View відображає статичне форматування й текст локально. Виконання скриптів, перехід за посиланнями і завантаження ресурсів заблоковані. Для зображень HTML показує їхній альтернативний текст. Більші HTML-файли починаються з першої сторінки вихідного тексту.
|
||||
- Двійковий режим показує до 4096 початкових байтів, зі звичайними символами для друкованих байтів та позначенням `\xNN` для контрольних кодів. Рядки переносяться за шириною панелі. Shift+F3 відкриває повний Hex Viewer.
|
||||
- **F3** відкриває PNG, JPEG, GIF, WebP і BMP у Viewer. Стрілки вліво й
|
||||
вправо, Page Up і Page Down та кнопки Previous і Next гортають видимі
|
||||
зображення в порядку вихідної панелі на момент відкриття Viewer.
|
||||
@@ -858,6 +860,14 @@ Warning і початковий фокус на No.
|
||||
- F8 переміщує підтверджені елементи в кошик Windows. Shift+Delete видаляє підтверджене дерево від вкладених елементів до батьківської папки. Прогрес і підсумок окремо показують успішні, пропущені й невдалі дії.
|
||||
- Cancel і Esc у вікні прогресу відкривають спільне червоне підтвердження скасування. Yes зупиняє операцію, а No або Esc у підтвердженні повертає до прогресу. Початковий фокус стоїть на No.
|
||||
|
||||
## Обмін і компонування панелей
|
||||
|
||||
- **Commands → Swap panels** або **Ctrl+U** міняє панелі місцями. Активна панель, шлях, курсор, прокручування, позначки, поточний режим і Quick View переходять разом.
|
||||
- **Options → File panel modes → Panel layout** містить незалежні параметри для правої кнопки, кнопок дисків і компактного компонування. За замовчуванням ці параметри вимкнені.
|
||||
- **Mark items with the right mouse button** перемикає позначку рядка. **Shift+права кнопка**, **Shift+F10** і клавіша **Menu** відкривають контекстне меню. Права кнопка на порожньому місці також відкриває контекстне меню панелі.
|
||||
- **Show drive buttons** додає наявні локальні диски над панелями. Кнопка відкриває корінь диска в активній панелі. Якщо всі диски не поміщаються, **…** відкриває Change drive.
|
||||
- **Compact commander layout** скорочує проміжки між шляхом, рядками та станом, зберігаючи розмір шрифту, командний рядок і клавіші дій.
|
||||
|
||||
## Перевірка змін
|
||||
|
||||
Відкрий Copy і Warning в одній збірці та порівняй висоту нижніх секцій, центрування, повноту підписів і видимість фокуса. Перевір Tab, стрілки й Esc. Після узгодження нового правила онови відповідний розділ цього документа.
|
||||
@@ -169,6 +169,10 @@ BEGIN
|
||||
COMBOBOX 273, 132, 40, 108, 74, CBS_DROPDOWNLIST | WS_TABSTOP
|
||||
LTEXT "&Right panel", 507, 251, 27, 117, 11
|
||||
COMBOBOX 274, 251, 40, 117, 74, CBS_DROPDOWNLIST | WS_TABSTOP
|
||||
AUTOCHECKBOX "Mark items with the right mouse button", 520, 132, 64, 245, 13
|
||||
AUTOCHECKBOX "Show drive buttons", 521, 132, 81, 245, 13
|
||||
AUTOCHECKBOX "Compact commander layout", 522, 132, 98, 245, 13
|
||||
LTEXT "Shift+right-click opens the Windows context menu.", 523, 132, 115, 245, 13
|
||||
GROUPBOX "Wide panel columns", 275, 129, 27, 259, 59
|
||||
LTEXT "Size column &width (6–16 characters)", 276, 138, 44, 175, 10
|
||||
EDITTEXT 201, 335, 41, 43, 14, ES_NUMBER | ES_AUTOHSCROLL
|
||||
|
||||
@@ -27,7 +27,7 @@ nav button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px;
|
||||
::highlight(markdown-search-active) { background: #ffab45; color: #171717; }
|
||||
:is(h1,h2,h3,h4,h5,h6) { scroll-margin-top: 2.5em; }
|
||||
h1, h2 { border-bottom: 1px solid GrayText; padding-bottom: .25em; }
|
||||
a { color: LinkText; }
|
||||
a[href] { color: LinkText; }
|
||||
pre, table, figure { overflow: auto; }
|
||||
pre, code { background: color-mix(in srgb, CanvasText 8%, Canvas); border-radius: 4px; }
|
||||
pre { padding: .75em; }
|
||||
|
||||
@@ -73,7 +73,7 @@ markdown.renderer.rules.image = (tokens, i) => {
|
||||
|
||||
const htmlTags = new Set(`a abbr address article aside b blockquote br caption code col colgroup dd del
|
||||
details div dl dt em figcaption figure footer h1 h2 h3 h4 h5 h6 header hr i img input ins kbd li
|
||||
mark ol p pre s samp section small span strong sub summary sup table tbody td tfoot th thead time
|
||||
main mark nav ol p pre s samp section small span strong sub summary sup table tbody td tfoot th thead time
|
||||
tr u ul var wbr`.split(/\s+/));
|
||||
const htmlAttributes = new Set(['id', 'class', 'title', 'lang', 'dir', 'aria-label']);
|
||||
const tagAttributes = {
|
||||
@@ -88,21 +88,25 @@ function relativeResource(path) {
|
||||
return path && !/^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path) && !/[\u0000-\u001f\u007f]/.test(path);
|
||||
}
|
||||
|
||||
function renderContent(text, canSave) {
|
||||
function renderContent(text, canSave, html) {
|
||||
// Parse in an inert template and allow only document markup before attaching it to the preview.
|
||||
const template = document.createElement('template');
|
||||
const taskKey = [...crypto.getRandomValues(new Uint32Array(4))].join('-');
|
||||
taskMarkers = new WeakMap();
|
||||
pendingTask = undefined;
|
||||
template.innerHTML = markdown.render(text, { taskKey });
|
||||
template.innerHTML = html ? text : markdown.render(text, { taskKey });
|
||||
for (const element of template.content.querySelectorAll('*')) {
|
||||
const tag = element.localName;
|
||||
if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !htmlTags.has(tag) ||
|
||||
(tag === 'input' && element.type !== 'checkbox')) {
|
||||
(tag === 'input' && (html || element.type !== 'checkbox'))) {
|
||||
element.remove();
|
||||
continue;
|
||||
}
|
||||
const imagePath = tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
|
||||
const imagePath = !html && tag === 'img' && (element.getAttribute('src') ?? element.getAttribute('data-path'))?.trim();
|
||||
if (html && tag === 'img') {
|
||||
element.replaceWith(document.createTextNode(element.getAttribute('alt') ?? ''));
|
||||
continue;
|
||||
}
|
||||
const task = tag === 'input' && element.getAttribute('data-task');
|
||||
if (task && task.startsWith(taskKey + ':')) {
|
||||
const [, line, column] = task.split(':');
|
||||
@@ -112,7 +116,8 @@ function renderContent(text, canSave) {
|
||||
const styles = element.hasAttribute('style')
|
||||
? inlineStyles.map(name => [name, element.style.getPropertyValue(name)]) : [];
|
||||
for (const { name } of [...element.attributes]) {
|
||||
if (!htmlAttributes.has(name) && !tagAttributes[tag]?.includes(name)) element.removeAttribute(name);
|
||||
const blockedInHtml = html && (name === 'id' || name === 'class' || name === 'href');
|
||||
if (blockedInHtml || (!htmlAttributes.has(name) && !tagAttributes[tag]?.includes(name))) element.removeAttribute(name);
|
||||
}
|
||||
for (const [name, value] of styles) {
|
||||
if (value) element.style.setProperty(name, value);
|
||||
@@ -247,7 +252,7 @@ searchPrevious.addEventListener('click', () => stepSearch(-1));
|
||||
searchNext.addEventListener('click', () => stepSearch(1));
|
||||
content.addEventListener('toggle', () => { if (!search.hidden) updateSearch(false); }, true);
|
||||
|
||||
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave, compact }) {
|
||||
async function render({ text, fragment, scroll, title, keepPosition, revision, canSave, compact, html }) {
|
||||
const current = ++generation;
|
||||
if (keepPosition) scroll = window.scrollY;
|
||||
else closeSearch();
|
||||
@@ -255,7 +260,14 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c
|
||||
document.title = title;
|
||||
document.documentElement.classList.toggle('quick-view', Boolean(compact));
|
||||
previewRevision = revision;
|
||||
renderContent(text, canSave);
|
||||
renderContent(text, canSave, html);
|
||||
images = [];
|
||||
if (html) {
|
||||
window.scrollTo(0, 0);
|
||||
document.documentElement.classList.add('rendered');
|
||||
send('rendered', { revision });
|
||||
return;
|
||||
}
|
||||
const headings = new Set();
|
||||
for (const heading of content.querySelectorAll('h1,h2,h3,h4,h5,h6')) {
|
||||
const base = heading.id || heading.textContent.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
|
||||
|
||||
+119
-13
@@ -834,6 +834,11 @@ constexpr DWORD defaultStatusFields=15;
|
||||
int sizeWidth=defaultSizeWidth;
|
||||
bool alignExtensions=defaultAlignExtensions, showDetails=defaultShowDetails;
|
||||
bool alignFolders=defaultAlignFolders;
|
||||
bool rightClickMarks{}, showDriveButtons{}, compactLayout{};
|
||||
constexpr wchar_t rightClickMarksKey[]=L"RightClickMarks", driveButtonsKey[]=L"ShowDriveButtons",
|
||||
compactLayoutKey[]=L"CompactPanelLayout";
|
||||
constexpr int firstDriveButton=660, moreDriveButton=firstDriveButton+26;
|
||||
std::array<HWND,27> driveButtons{};
|
||||
DWORD statusFields=defaultStatusFields;
|
||||
std::vector<fs::path> drivePaths;
|
||||
bool lanDrivePicker{};
|
||||
@@ -1594,6 +1599,8 @@ void swapPanels(HWND window)
|
||||
}
|
||||
notifyFilesPreferences(window);
|
||||
layout(window);
|
||||
showFileDetails(panels[active]);
|
||||
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
}
|
||||
|
||||
bool hasSelectionSummary()
|
||||
@@ -1631,7 +1638,12 @@ void layout(HWND window,bool activeOnly)
|
||||
const bool gitMode=showingGitChanges();
|
||||
const int terminalBottom=std::max(4,inputTop);
|
||||
const int summaryHeight=!terminalVisible && hasSelectionSummary()?textHeight:0;
|
||||
const int detailsHeight=terminalVisible?0:textHeight+12+summaryHeight;
|
||||
const int detailsInset=compactLayout?2:4;
|
||||
const int detailsHeight=terminalVisible?0:textHeight+(compactLayout?4:12)+summaryHeight;
|
||||
const DWORD driveMask=showDriveButtons && !terminalVisible && !gitMode?GetLogicalDrives():0;
|
||||
const int driveHeight=driveMask?textHeight+2:0;
|
||||
const int panelMargin=compactLayout?4:5;
|
||||
const int pathTop=driveHeight+(compactLayout?1:4);
|
||||
const int terminalTop=terminalVisible?4:std::max(4,terminalBottom-
|
||||
std::min(terminalRows,std::max(0,(terminalBottom-detailsHeight)/textHeight-4))*textHeight);
|
||||
const int panelBottom=terminalTop-detailsHeight;
|
||||
@@ -1645,21 +1657,41 @@ void layout(HWND window,bool activeOnly)
|
||||
};
|
||||
if(!activeOnly)
|
||||
{
|
||||
const int buttonWidth=std::max(4*cellWidth,32);
|
||||
const int maxButtons=std::max(1,(width-8)/buttonWidth);
|
||||
int drives=0;
|
||||
for(int letter=0;letter<26;++letter) if(driveMask&(1UL<<letter)) ++drives;
|
||||
const int visibleDrives=drives>maxButtons?maxButtons-1:drives;
|
||||
int slot=0;
|
||||
for(int letter=0;letter<26;++letter)
|
||||
{
|
||||
const auto button=driveButtons[letter];
|
||||
if(!button) continue;
|
||||
const bool visible=(driveMask&(1UL<<letter)) && slot<visibleDrives;
|
||||
if(visible) place(button,4+slot++*buttonWidth,0,buttonWidth,textHeight);
|
||||
ShowWindow(button,visible?SW_SHOWNA:SW_HIDE);
|
||||
}
|
||||
if(const auto more=driveButtons.back())
|
||||
{
|
||||
place(more,4+slot*buttonWidth,0,buttonWidth,textHeight);
|
||||
ShowWindow(more,drives>maxButtons?SW_SHOWNA:SW_HIDE);
|
||||
}
|
||||
const int headingTop=pathTop+textHeight+(compactLayout?2:6);
|
||||
for (int i = 0; i < 2; ++i)
|
||||
{
|
||||
int x = i ? middle + 2 : 0;
|
||||
int end = i ? width : middle - 2;
|
||||
place(panels[i].path, x + 5, 4, std::max(0, end - x - 10), textHeight);
|
||||
place(panels[i].path, x+panelMargin,pathTop,std::max(0,end-x-2*panelMargin),textHeight);
|
||||
int headingHeight=detailedPanel(panels[i])?textHeight:0;
|
||||
const int listWidth=std::max(0,end-x-8-scrollBarWidth(panels[i].list));
|
||||
const int listWidth=std::max(0,end-x-panelMargin-3-scrollBarWidth(panels[i].list));
|
||||
const bool panelVisible=!gitMode && !terminalVisible && (!quickViewWindow || i==quickViewSource);
|
||||
ShowWindow(panels[i].path,panelVisible?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(panels[i].list,panelVisible?SW_SHOWNA:SW_HIDE);
|
||||
place(panels[i].heading,x+5,textHeight+10,listWidth,headingHeight);
|
||||
place(panels[i].heading,x+panelMargin,headingTop,listWidth,headingHeight);
|
||||
ShowWindow(panels[i].heading,panelVisible && detailedPanel(panels[i])?SW_SHOWNA:SW_HIDE);
|
||||
place(panels[i].list, x + 5, textHeight+10+headingHeight,listWidth,
|
||||
std::max(0, panelBottom-textHeight-10-headingHeight));
|
||||
place(panels[i].selectionSummary,x+8,panelBottom+4,std::max(0,end-x-16),summaryHeight);
|
||||
place(panels[i].list,x+panelMargin,headingTop+headingHeight,listWidth,
|
||||
std::max(0,panelBottom-headingTop-headingHeight));
|
||||
place(panels[i].selectionSummary,x+8,panelBottom+detailsInset,std::max(0,end-x-16),summaryHeight);
|
||||
ShowWindow(panels[i].selectionSummary,panelVisible && summaryHeight?SW_SHOWNA:SW_HIDE);
|
||||
}
|
||||
place(menuBar,0,0,width,textHeight+4);
|
||||
@@ -1669,7 +1701,7 @@ void layout(HWND window,bool activeOnly)
|
||||
}
|
||||
const int detailsLeft=active?middle+2:0;
|
||||
const int detailsRight=active?width:middle-2;
|
||||
place(status,detailsLeft+8,panelBottom+4+summaryHeight,std::max(0,detailsRight-detailsLeft-16),textHeight);
|
||||
place(status,detailsLeft+8,panelBottom+detailsInset+summaryHeight,std::max(0,detailsRight-detailsLeft-16),textHeight);
|
||||
const auto ¤t=panels[active];
|
||||
const auto prompt=panelLocation(current)+(terminalVisible?L"> ":L">");
|
||||
SetWindowTextW(terminalPrompt,prompt.c_str());
|
||||
@@ -1686,7 +1718,13 @@ void layout(HWND window,bool activeOnly)
|
||||
place(terminalInput,4+promptWidth,inputTop,std::max(0,width-8-promptWidth),textHeight);
|
||||
if(activeOnly)
|
||||
{
|
||||
const RECT details{0,panelBottom+4+summaryHeight,width,panelBottom+4+summaryHeight+textHeight};
|
||||
const RECT details{0,panelBottom+detailsInset+summaryHeight,width,
|
||||
panelBottom+detailsInset+summaryHeight+textHeight};
|
||||
if(driveHeight)
|
||||
{
|
||||
const RECT drives{0,0,width,driveHeight};
|
||||
RedrawWindow(window,&drives,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
}
|
||||
const RECT commandLine{0,inputTop,width,inputTop+textHeight};
|
||||
if(!terminalVisible) RedrawWindow(window,&details,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
RedrawWindow(window,&commandLine,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
@@ -1723,8 +1761,9 @@ void layout(HWND window,bool activeOnly)
|
||||
for(const auto preview:{quickViewWindow,quickImageWindow})
|
||||
{
|
||||
if(!preview) continue;
|
||||
SetWindowPos(preview,nullptr,left+5,4,std::max(0,right-left-10),
|
||||
std::max(0,panelBottom+summaryHeight+textHeight),SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
const int bottom=panelBottom+summaryHeight+textHeight+detailsInset;
|
||||
SetWindowPos(preview,nullptr,left+panelMargin,pathTop,std::max(0,right-left-2*panelMargin),
|
||||
std::max(0,bottom-pathTop),SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
const bool current=quickViewDisplaysImage==(preview==quickImageWindow);
|
||||
ShowWindow(preview,!gitMode && !terminalVisible && current?SW_SHOWNA:SW_HIDE);
|
||||
}
|
||||
@@ -3900,6 +3939,7 @@ void selectDrive()
|
||||
else if(menuIndex==2 && row==15) showProcesses(owner);
|
||||
else if(menuIndex==2 && row==16) openGitChanges(owner,panels[active]);
|
||||
else if(menuIndex==2 && row==17) showEnvironmentPanel(owner);
|
||||
else if(menuIndex==2 && row==18) swapPanels(owner);
|
||||
else if(menuIndex==1 && row==4) createArchive(owner,panels[active]);
|
||||
else if(menuIndex==1 && row==5) showPanelItemProperties(owner,panels[active]);
|
||||
else if(menuIndex==1 && row==6) showPanelLockProcesses(owner,panels[active]);
|
||||
@@ -7876,6 +7916,27 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT
|
||||
if(message==WM_RBUTTONUP)
|
||||
{
|
||||
POINT screen{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||||
if(rightClickMarks && !(wp&MK_SHIFT) && commandLineAvailable(GetParent(window)))
|
||||
{
|
||||
auto &panel=panels[index];
|
||||
const auto row=panelRowAt(window,screen,SendMessageW(window,LB_GETTOPINDEX,0,0),panel.rows.size());
|
||||
if(row!=LB_ERR && panel.sizes[row]!=L"Up" && !transferProfileList(panel))
|
||||
{
|
||||
closePanelSearch();
|
||||
SetFocus(window);
|
||||
activatePanel(index);
|
||||
panelClipboardContext=true;
|
||||
clearTerminalSelection();
|
||||
const auto previous=currentPanelRow(panel);
|
||||
SendMessageW(window,LB_SETCURSEL,row,0);
|
||||
markPanelRow(panel,row,!panel.marked[row]);
|
||||
invalidatePanelRow(window,row);
|
||||
if(previous!=row) invalidatePanelRow(window,previous);
|
||||
updateSelectionSummary(panel);
|
||||
showFileDetails(panel);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
ClientToScreen(window,&screen);
|
||||
showPanelContextMenu(window,MAKELPARAM(screen.x,screen.y));
|
||||
return 0;
|
||||
@@ -8098,6 +8159,9 @@ bool loadFilesPreferences(HWND window)
|
||||
alignExtensions=preference(L"AlignExtensions",defaultAlignExtensions)!=0;
|
||||
showDetails=preference(L"ShowDetails",defaultShowDetails)!=0;
|
||||
alignFolders=preference(L"AlignFolders",defaultAlignFolders)!=0;
|
||||
rightClickMarks=preference(rightClickMarksKey,0)!=0;
|
||||
showDriveButtons=preference(driveButtonsKey,0)!=0;
|
||||
compactLayout=preference(compactLayoutKey,0)!=0;
|
||||
statusFields=preference(L"StatusFields",defaultStatusFields)&15;
|
||||
loadCommandHistoryKeys();
|
||||
loadComparisonShortcut();
|
||||
@@ -8163,7 +8227,7 @@ void openMenu(HWND window, int index)
|
||||
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"View as hex\tShift+F3",L"Viewer bookmarks…",L"Processes…",
|
||||
L"Git Changes…",L"Environment Variables…"};
|
||||
L"Git Changes…",L"Environment Variables…",L"Swap panels\tCtrl+U"};
|
||||
}
|
||||
const auto &panel=panels[active];
|
||||
const bool remoteResults=remoteSearchResults(panel);
|
||||
@@ -8189,6 +8253,7 @@ void openMenu(HWND window, int index)
|
||||
else if(index==2)
|
||||
{
|
||||
commandActions={0,3,11,-1,1,13,14,2,4,5,8};
|
||||
if(!terminalVisible) commandActions.insert(commandActions.begin()+1,18);
|
||||
if(!terminalVisible) commandActions.push_back(15);
|
||||
if(gitChangesAvailable(panel)) commandActions.push_back(16);
|
||||
if(!terminalVisible) commandActions.push_back(17);
|
||||
@@ -8567,6 +8632,13 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
for (int i = 0; i < static_cast<int>(std::size(commands)); ++i)
|
||||
commands[i] = CreateWindowW(L"BUTTON", keyBar[i].label, WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
|
||||
0, 0, 0, 0, window, reinterpret_cast<HMENU>(static_cast<INT_PTR>(keyBar[i].id)), instance, nullptr);
|
||||
for(int i=0;i<static_cast<int>(driveButtons.size());++i)
|
||||
{
|
||||
const wchar_t letter[]{static_cast<wchar_t>(L'A'+i),L':',0};
|
||||
driveButtons[i]=CreateWindowW(L"BUTTON",i==26?L"…":letter,WS_CHILD|BS_OWNERDRAW|WS_CLIPSIBLINGS,
|
||||
0,0,0,0,window,reinterpret_cast<HMENU>(static_cast<INT_PTR>(firstDriveButton+i)),instance,nullptr);
|
||||
if(!driveButtons[i]) return -1;
|
||||
}
|
||||
for (int i = 0; i < 2; ++i)
|
||||
{
|
||||
auto &panel = panels[i];
|
||||
@@ -8610,6 +8682,13 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
return 0;
|
||||
}
|
||||
case WM_DEVICECHANGE:
|
||||
if(showDriveButtons)
|
||||
{
|
||||
layout(window);
|
||||
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ALLCHILDREN);
|
||||
}
|
||||
break;
|
||||
case WM_SIZE:
|
||||
hideCompletion();
|
||||
hidePicker();
|
||||
@@ -8690,7 +8769,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
GetWindowRect(status,&details);
|
||||
MapWindowPoints(nullptr,window,reinterpret_cast<POINT*>(&details),2);
|
||||
const RECT divider{box.left+1,box.bottom-2,box.right-1,box.bottom-1};
|
||||
box.bottom=std::max(box.bottom,details.bottom+6);
|
||||
box.bottom=std::max(box.bottom,details.bottom+(compactLayout?2:6));
|
||||
FrameRect(dc,&box,border);
|
||||
if(IsWindowVisible(panel.list)) paintScrollPosition(window,dc,panel.list,colors[PanelBlue]);
|
||||
InflateRect(&box,-3,-3);
|
||||
@@ -8862,6 +8941,21 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
GetWindowTextW(item.hwndItem,label,64);
|
||||
text=label;
|
||||
}
|
||||
if(item.CtlID>=firstDriveButton && item.CtlID<=moreDriveButton)
|
||||
{
|
||||
const auto &panel=panels[active];
|
||||
const auto drive=panel.directory.root_name().native();
|
||||
const bool selected=item.CtlID!=moreDriveButton && !panel.peer && !panel.ftp && !panel.archive &&
|
||||
drive.size()==2 && towupper(drive.front())==L'A'+item.CtlID-firstDriveButton;
|
||||
auto bounds=item.rcItem;
|
||||
FillRect(item.hDC,&bounds,selected?teal:blue);
|
||||
SelectObject(item.hDC,mono);
|
||||
SetBkMode(item.hDC,TRANSPARENT);
|
||||
SetTextColor(item.hDC,colors[selected?Text:Frame]);
|
||||
DrawTextW(item.hDC,text.c_str(),-1,&bounds,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX);
|
||||
if(item.itemState&ODS_FOCUS) DrawFocusRect(item.hDC,&bounds);
|
||||
return TRUE;
|
||||
}
|
||||
if(std::find(std::begin(commands),std::end(commands),item.hwndItem)!=std::end(commands))
|
||||
{
|
||||
if(item.CtlID==114 && remoteSearchResults(panels[active]) && panels[active].ftp)
|
||||
@@ -9151,6 +9245,18 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(HIWORD(wp)==BN_CLICKED && LOWORD(wp)>=firstDriveButton && LOWORD(wp)<=moreDriveButton)
|
||||
{
|
||||
const auto id=LOWORD(wp);
|
||||
if(id==moreDriveButton) chooseDrive(active);
|
||||
else
|
||||
{
|
||||
const wchar_t root[]{static_cast<wchar_t>(L'A'+id-firstDriveButton),L':',L'\\',0};
|
||||
openOn(panels[active],root,false,{});
|
||||
restoreCommandFocus();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(LOWORD(wp)==121 && HIWORD(wp)==LBN_DBLCLK) selectDrive();
|
||||
if(LOWORD(wp)>=130 && LOWORD(wp)<=134 && HIWORD(wp)==BN_CLICKED)
|
||||
{
|
||||
|
||||
+19
-2
@@ -11,7 +11,8 @@ constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Pop
|
||||
L"Menu selection",L"Command bar",L"File cursor"};
|
||||
enum PanelSection { PanelLayout, WideColumns, StatusColumns };
|
||||
constexpr const wchar_t *panelSectionNames[]{L"Panel layout",L"Wide panel columns",L"Status line columns"};
|
||||
constexpr int panelLayoutControls[]{506,273,507,274};
|
||||
constexpr int rightClickMarksControl=520, driveButtonsControl=521, compactLayoutControl=522;
|
||||
constexpr int panelLayoutControls[]{506,273,507,274,rightClickMarksControl,driveButtonsControl,compactLayoutControl,523};
|
||||
constexpr int wideColumnControls[]{275,276,201,202,204};
|
||||
constexpr int statusColumnControls[]{277,203,205,206,207,208};
|
||||
constexpr int colorOptionControls[]{279,280};
|
||||
@@ -67,6 +68,9 @@ struct PanelProperty
|
||||
};
|
||||
constexpr PanelProperty panelProperties[]{
|
||||
{PanelLayout,273,L"Left panel mode",defaultWide?1u:0u},{PanelLayout,274,L"Right panel mode",defaultWide?1u:0u},
|
||||
{PanelLayout,rightClickMarksControl,L"Mark items with the right mouse button",0},
|
||||
{PanelLayout,driveButtonsControl,L"Show drive buttons",0},
|
||||
{PanelLayout,compactLayoutControl,L"Compact commander layout",0},
|
||||
{WideColumns,201,L"Size column width",defaultSizeWidth},
|
||||
{WideColumns,202,L"Align file extensions",defaultAlignExtensions},
|
||||
{WideColumns,204,L"Align folder extensions",defaultAlignFolders},
|
||||
@@ -107,6 +111,7 @@ struct OptionsBaseline
|
||||
bool remoteUpdate=ks::lan::remoteUpdateAllowed();
|
||||
DWORD width=static_cast<DWORD>(sizeWidth), fields=statusFields;
|
||||
bool extensions=alignExtensions, folders=alignFolders, details=showDetails;
|
||||
bool mouseMarks=rightClickMarks, drives=showDriveButtons, compact=compactLayout;
|
||||
std::array<PanelMode,2> modes{panels[0].mode,panels[1].mode};
|
||||
ks::files::TextSettings text=ks::files::loadTextPreferences();
|
||||
ComparisonAppearance comparison=readComparisonAppearance();
|
||||
@@ -181,6 +186,8 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft)
|
||||
const bool dirty=!valid || draft.markdownError || width!=base.width ||
|
||||
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 ||
|
||||
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 ||
|
||||
@@ -679,6 +686,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,202,alignExtensions);
|
||||
CheckDlgButton(dialog,203,showDetails);
|
||||
CheckDlgButton(dialog,204,alignFolders);
|
||||
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
|
||||
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
|
||||
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
|
||||
showPanelModeOptions(dialog);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
@@ -898,7 +908,8 @@ 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 optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
|
||||
case 273: case 274: case rightClickMarksControl: case driveButtonsControl: case compactLayoutControl:
|
||||
case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate:
|
||||
updateOptionsApply(dialog,*draft);
|
||||
return TRUE;
|
||||
case 321: case 323: case comparisonShortcutControl:
|
||||
@@ -1050,6 +1061,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
saveChanged(L"AlignExtensions",checked(202),base.extensions);
|
||||
saveChanged(L"AlignFolders",checked(204),base.folders);
|
||||
saveChanged(L"ShowDetails",checked(203),base.details);
|
||||
saveChanged(rightClickMarksKey,checked(rightClickMarksControl),base.mouseMarks);
|
||||
saveChanged(driveButtonsKey,checked(driveButtonsControl),base.drives);
|
||||
saveChanged(compactLayoutKey,checked(compactLayoutControl),base.compact);
|
||||
DWORD fields=preference(L"StatusFields",defaultStatusFields)&15;
|
||||
const auto initialFields=fields;
|
||||
for(int i=0;i<4;++i)
|
||||
@@ -1092,6 +1106,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
CheckDlgButton(dialog,202,alignExtensions);
|
||||
CheckDlgButton(dialog,203,showDetails);
|
||||
CheckDlgButton(dialog,204,alignFolders);
|
||||
CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks);
|
||||
CheckDlgButton(dialog,driveButtonsControl,showDriveButtons);
|
||||
CheckDlgButton(dialog,compactLayoutControl,compactLayout);
|
||||
showPanelModeOptions(dialog);
|
||||
for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u);
|
||||
setOptionHistoryKeys(dialog,commandHistoryKeys);
|
||||
|
||||
@@ -133,6 +133,18 @@ std::wstring decodeMultibyte(std::string_view bytes,UINT codePage,DWORD flags)
|
||||
return units;
|
||||
}
|
||||
|
||||
std::string encodeUtf8(std::wstring_view units)
|
||||
{
|
||||
if(units.empty()) return {};
|
||||
const auto length=static_cast<int>(units.size());
|
||||
const int required=WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,units.data(),length,nullptr,0,nullptr,nullptr);
|
||||
if(!required) fail("Decode UTF-16");
|
||||
std::string result(required,'\0');
|
||||
if(!WideCharToMultiByte(CP_UTF8,WC_ERR_INVALID_CHARS,units.data(),length,result.data(),required,nullptr,nullptr))
|
||||
fail("Decode UTF-16");
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string encode(std::string_view utf8,TextEncoding encoding)
|
||||
{
|
||||
if(encoding==TextEncoding::utf8 || utf8.empty()) return std::string(utf8);
|
||||
@@ -289,13 +301,7 @@ std::string TextDocument::decode(std::string bytes) const
|
||||
units[i] = static_cast<wchar_t>(encoding_ == TextEncoding::utf16le ? a | (b << 8) : (a << 8) | b);
|
||||
}
|
||||
}
|
||||
const auto length = static_cast<int>(units.size());
|
||||
const int required = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, nullptr, 0, nullptr, nullptr);
|
||||
if (!required) fail("Decode UTF-16");
|
||||
std::string result(required, '\0');
|
||||
if (!WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, units.data(), length, result.data(), required, nullptr, nullptr))
|
||||
fail("Decode UTF-16");
|
||||
return result;
|
||||
return encodeUtf8(units);
|
||||
}
|
||||
|
||||
std::string TextDocument::readPage(uint64_t page) const
|
||||
@@ -377,6 +383,15 @@ std::string formatHexAddress(uint64_t offset)
|
||||
return address;
|
||||
}
|
||||
|
||||
std::string formatBinarySymbols(std::string_view bytes)
|
||||
{
|
||||
if(bytes.empty()) return {};
|
||||
auto symbols=decodeMultibyte(bytes,437,0);
|
||||
for(size_t i=0;i<bytes.size();++i)
|
||||
if(const auto marker=binarySymbolMarker(static_cast<unsigned char>(bytes[i]))) symbols[i]=marker;
|
||||
return encodeUtf8(symbols);
|
||||
}
|
||||
|
||||
std::string formatHexPage(std::string_view bytes,uint64_t offset)
|
||||
{
|
||||
constexpr char digits[]="0123456789ABCDEF";
|
||||
|
||||
@@ -17,6 +17,11 @@ 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);
|
||||
constexpr wchar_t binarySymbolMarker(unsigned char byte)
|
||||
{
|
||||
return byte<0x20 || byte==0x7f || byte==0xff || byte=='\\' ? static_cast<wchar_t>(0xe000+byte) : 0;
|
||||
}
|
||||
std::string formatBinarySymbols(std::string_view bytes);
|
||||
|
||||
struct TextSaveFormat
|
||||
{
|
||||
|
||||
+128
-24
@@ -800,7 +800,7 @@ public:
|
||||
if(smallIcon) DestroyIcon(smallIcon);
|
||||
if(largeIcon) DestroyIcon(largeIcon);
|
||||
}
|
||||
HWND window{}, editor{};
|
||||
HWND window{}, editor{}, quickModeButton{};
|
||||
bool handleKey(const MSG &message);
|
||||
void goToFragment(std::string_view fragment);
|
||||
void previewFile(const std::filesystem::path &path);
|
||||
@@ -928,11 +928,14 @@ private:
|
||||
};
|
||||
std::future<BookmarkLocation> bookmarkTask;
|
||||
std::stop_source bookmarkStop;
|
||||
enum class QuickKind { text, html, binary };
|
||||
struct QuickDocument
|
||||
{
|
||||
std::unique_ptr<TextDocument> document;
|
||||
std::string firstPage;
|
||||
std::optional<std::string> markdown;
|
||||
std::optional<std::string> previewCode;
|
||||
QuickKind kind{};
|
||||
size_t binaryBytes{};
|
||||
};
|
||||
std::future<QuickDocument> quickLoading;
|
||||
std::filesystem::path quickPath;
|
||||
@@ -941,7 +944,13 @@ private:
|
||||
uint64_t quickRequest{}, quickReading{};
|
||||
ULONGLONG quickReadyAt{};
|
||||
std::wstring quickError;
|
||||
std::optional<std::string> quickMarkdown;
|
||||
std::optional<std::string> quickPreviewCode;
|
||||
QuickKind quickKind{};
|
||||
bool quickHtmlRendered{}, binaryRepresentations{};
|
||||
size_t quickBinaryBytes{};
|
||||
static constexpr int quickModeControl=159;
|
||||
void applySourceLayoutOptions();
|
||||
void toggleQuickHtml();
|
||||
void pollQuickView();
|
||||
static constexpr UINT trimUndo = WM_APP + 1;
|
||||
static constexpr UINT previewFailed = WM_APP + 2;
|
||||
@@ -1371,19 +1380,44 @@ void TextWindow::applyPreferences()
|
||||
send(SCI_SETUSETABS, !prefs.tabsAsSpaces);
|
||||
send(SCI_SETTABINDENTS, TRUE);
|
||||
send(SCI_SETBACKSPACEUNINDENTS, TRUE);
|
||||
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);
|
||||
applySourceLayoutOptions();
|
||||
applyLineEnding();
|
||||
updateLineNumberMargin();
|
||||
layout();
|
||||
invalidate();
|
||||
}
|
||||
|
||||
void TextWindow::applySourceLayoutOptions()
|
||||
{
|
||||
const bool binary=embedded && quickKind==QuickKind::binary;
|
||||
if(std::exchange(binaryRepresentations,binary)!=binary)
|
||||
{
|
||||
constexpr char digits[]="0123456789ABCDEF";
|
||||
for(int byte=0;byte<256;++byte)
|
||||
{
|
||||
const auto marker=binarySymbolMarker(static_cast<unsigned char>(byte));
|
||||
if(!marker) continue;
|
||||
const auto key=utf8(std::wstring(1,marker));
|
||||
const auto index=reinterpret_cast<WPARAM>(key.c_str());
|
||||
if(binary)
|
||||
{
|
||||
const char value[]{'\\','x',digits[byte>>4],digits[byte&15],0};
|
||||
send(SCI_SETREPRESENTATION,index,reinterpret_cast<LPARAM>(byte=='\\'?"\\\\":value));
|
||||
send(SCI_SETREPRESENTATIONAPPEARANCE,index,SC_REPRESENTATION_PLAIN);
|
||||
}
|
||||
else send(SCI_CLEARREPRESENTATION,index);
|
||||
}
|
||||
}
|
||||
send(SCI_SETWRAPMODE,binary?SC_WRAP_CHAR:!hex && prefs.wrap?SC_WRAP_WORD:SC_WRAP_NONE);
|
||||
send(SCI_SETHSCROLLBAR,!binary);
|
||||
send(SCI_SETVIEWWS,!binary && !hex && prefs.whitespace?SCWS_VISIBLEALWAYS:SCWS_INVISIBLE);
|
||||
send(SCI_SETVIEWEOL,!binary && !hex && prefs.whitespace);
|
||||
}
|
||||
|
||||
void TextWindow::updateLineNumberMargin()
|
||||
{
|
||||
LRESULT width{};
|
||||
if (prefs.numbers && !hex)
|
||||
if (prefs.numbers && !hex && (!embedded || quickKind!=QuickKind::binary))
|
||||
{
|
||||
const auto digits = std::to_string(send(SCI_GETLINECOUNT)).size();
|
||||
const std::string sample(digits, '9');
|
||||
@@ -1601,8 +1635,9 @@ void TextWindow::initializeDocument(std::optional<std::string> firstPage)
|
||||
return;
|
||||
}
|
||||
if(!firstPage) firstPage=document->readPage(0);
|
||||
automatic=detectLanguage(original,*firstPage);
|
||||
automatic=embedded && quickKind==QuickKind::binary?TextLanguage{}:detectLanguage(original,*firstPage);
|
||||
language=automatic;
|
||||
if(embedded) applySourceLayoutOptions();
|
||||
if(canPreview()) ShowWindow(editor,SW_HIDE);
|
||||
if(!embedded)
|
||||
{
|
||||
@@ -1633,7 +1668,10 @@ void TextWindow::previewFile(const std::filesystem::path &path)
|
||||
quickReadyAt=GetTickCount64()+80;
|
||||
stopPreview(false,true);
|
||||
document.reset();
|
||||
quickMarkdown.reset();
|
||||
quickPreviewCode.reset();
|
||||
quickKind=QuickKind::text;
|
||||
quickHtmlRendered=false;
|
||||
quickBinaryBytes=0;
|
||||
quickError.clear();
|
||||
layout();
|
||||
SetTimer(window,quickViewTimer,30,nullptr);
|
||||
@@ -1651,7 +1689,11 @@ void TextWindow::previewEmbeddedText(const std::wstring &title,std::string_view
|
||||
quickError.clear();
|
||||
stopPreview(false,true);
|
||||
document.reset();
|
||||
quickMarkdown.reset();
|
||||
quickPreviewCode.reset();
|
||||
quickKind=QuickKind::text;
|
||||
quickHtmlRendered=false;
|
||||
quickBinaryBytes=0;
|
||||
applySourceLayoutOptions();
|
||||
}
|
||||
if(quickTextTitle.empty() || quickTextDiff!=diff)
|
||||
{
|
||||
@@ -1681,7 +1723,10 @@ void TextWindow::pollQuickView()
|
||||
original=quickPath;
|
||||
filename=original.filename().wstring();
|
||||
document=std::move(loaded.document);
|
||||
quickMarkdown=std::move(loaded.markdown);
|
||||
quickPreviewCode=std::move(loaded.previewCode);
|
||||
quickKind=loaded.kind;
|
||||
quickHtmlRendered=quickKind==QuickKind::html && quickPreviewCode.has_value();
|
||||
quickBinaryBytes=loaded.binaryBytes;
|
||||
initializeDocument(std::move(loaded.firstPage));
|
||||
}
|
||||
}
|
||||
@@ -1710,13 +1755,23 @@ void TextWindow::pollQuickView()
|
||||
std::packaged_task<QuickDocument()> task([path=quickPath] {
|
||||
auto source=std::make_unique<TextDocument>(path,false);
|
||||
auto first=source->readPage(0);
|
||||
if(first.find('\0')!=std::string::npos)
|
||||
throw std::runtime_error("Binary preview is unavailable.");
|
||||
std::optional<std::string> markdown;
|
||||
if(source->size()<=TextDocument::editLimit && detectLanguage(path,first).lexer=="markdown")
|
||||
markdown=readMarkdownDocument(*source);
|
||||
const auto extension=lower(path.extension().wstring());
|
||||
const auto html=extension==L".html" || extension==L".htm" || extension==L".xhtml";
|
||||
const auto binary=std::any_of(first.begin(),first.end(),[](unsigned char c) {
|
||||
return (c<32 && c!='\t' && c!='\r' && c!='\n' && c!='\f') || c==127;
|
||||
});
|
||||
if(binary && !html)
|
||||
{
|
||||
constexpr size_t limit=4096;
|
||||
const auto bytes=source->readBytes(0,limit);
|
||||
source->releaseReadHandle();
|
||||
return QuickDocument{std::move(source),formatBinarySymbols(bytes),{},QuickKind::binary,bytes.size()};
|
||||
}
|
||||
std::optional<std::string> markup;
|
||||
if(source->size()<=TextDocument::editLimit && (html || detectLanguage(path,first).lexer=="markdown"))
|
||||
markup=readMarkdownDocument(*source);
|
||||
source->releaseReadHandle();
|
||||
return QuickDocument{std::move(source),std::move(first),std::move(markdown)};
|
||||
return QuickDocument{std::move(source),std::move(first),std::move(markup),html?QuickKind::html:QuickKind::text};
|
||||
});
|
||||
quickLoading=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
@@ -2064,8 +2119,17 @@ void TextWindow::updateTaskbarGroup(bool closing)
|
||||
|
||||
bool TextWindow::canPreview() const
|
||||
{
|
||||
return !edit && !hex && !showBookmarkSource && automatic.lexer=="markdown" && document &&
|
||||
document->size()<=TextDocument::editLimit;
|
||||
if(edit || hex || showBookmarkSource || !document || document->size()>TextDocument::editLimit) return false;
|
||||
if(embedded && quickKind==QuickKind::html) return quickHtmlRendered;
|
||||
return automatic.lexer=="markdown";
|
||||
}
|
||||
|
||||
void TextWindow::toggleQuickHtml()
|
||||
{
|
||||
if(!embedded || quickKind!=QuickKind::html || !document || !quickPreviewCode) return;
|
||||
quickHtmlRendered=!quickHtmlRendered;
|
||||
if(quickHtmlRendered) updatePreview();
|
||||
else stopPreview(true,true);
|
||||
}
|
||||
|
||||
void TextWindow::updatePreview()
|
||||
@@ -2096,6 +2160,11 @@ bool TextWindow::startPreviewBrowser()
|
||||
const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0;
|
||||
if(embedded)
|
||||
{
|
||||
if(!ctrl && !alt && !(GetKeyState(VK_SHIFT)&0x8000) && key==VK_F6 && quickKind==QuickKind::html)
|
||||
{
|
||||
PostMessageW(window,WM_COMMAND,quickModeControl,0);
|
||||
return true;
|
||||
}
|
||||
if(!ctrl || alt || key!='Q') return false;
|
||||
PostMessageW(GetParent(window),quickViewToggleMessage,0,0);
|
||||
return true;
|
||||
@@ -2131,6 +2200,7 @@ void TextWindow::stopPreview(bool refresh,bool keepBrowser)
|
||||
{
|
||||
KillTimer(window,previewTimer);
|
||||
previewWanted=previewVisible=false;
|
||||
if(embedded && refresh && quickKind==QuickKind::html) quickHtmlRendered=false;
|
||||
previewStamp.reset();
|
||||
++previewRevision;
|
||||
previewText.clear();
|
||||
@@ -2187,10 +2257,11 @@ void TextWindow::renderPreview(bool keepPosition)
|
||||
{
|
||||
applyMarkdownPreferences(loadTextPreferences().markdown);
|
||||
previewDeadline=GetTickCount64()+30000;
|
||||
previewText=quickMarkdown?*quickMarkdown:readMarkdownDocument(*document);
|
||||
previewText=quickPreviewCode?*quickPreviewCode:readMarkdownDocument(*document);
|
||||
if(!remote) document->releaseReadHandle();
|
||||
nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision},
|
||||
{"canSave",!embedded && !suspendedEditor && (!remote || remote->revision.editable)},{"compact",embedded},
|
||||
{"html",embedded && quickKind==QuickKind::html},
|
||||
{"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)},
|
||||
{"keepPosition",keepPosition}};
|
||||
if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll;
|
||||
@@ -2358,6 +2429,7 @@ void TextWindow::previewMessage(const std::wstring &value)
|
||||
}
|
||||
const auto message=nlohmann::json::parse(utf8(value));
|
||||
const auto action=message.at("action").get<std::string>();
|
||||
if(embedded && quickKind==QuickKind::html && action!="rendered" && action!="failed") return;
|
||||
if(action=="cycle")
|
||||
{
|
||||
PostMessageW(window,cycleWindow,message.value("reverse",false),0);
|
||||
@@ -2558,6 +2630,13 @@ void TextWindow::layout()
|
||||
const int top=embedded?row:2*row;
|
||||
const LONG bottom=std::max<LONG>(top,area.bottom-(embedded?0:row));
|
||||
MoveWindow(editor,0,top,area.right,bottom-top,TRUE);
|
||||
if(quickModeButton)
|
||||
{
|
||||
const int width=std::min(static_cast<int>(area.right),scale(108));
|
||||
MoveWindow(quickModeButton,area.right-width,0,width,row,TRUE);
|
||||
SetWindowTextW(quickModeButton,quickHtmlRendered?L"Show Source":L"Show Rendered");
|
||||
ShowWindow(quickModeButton,quickKind==QuickKind::html && quickPreviewCode && document?SW_SHOWNA:SW_HIDE);
|
||||
}
|
||||
preview.layout({0,top,area.right,bottom},previewWanted && (!embedded || previewVisible));
|
||||
ShowWindow(editor,(document || quickTextVisible) && !previewWanted?SW_SHOWNA:SW_HIDE);
|
||||
invalidate();
|
||||
@@ -2633,9 +2712,18 @@ void TextWindow::paint()
|
||||
std::wstring label=L"Quick View";
|
||||
if(!quickPath.empty()) label+=L" · "+quickPath.filename().native();
|
||||
if(!quickError.empty()) label+=L" · "+quickError;
|
||||
else if(quickPath.empty()) label+=L" · Select a local text file";
|
||||
else if(quickPath.empty()) label+=L" · Select a local file";
|
||||
else if(!document || (previewWanted && !previewVisible)) label+=L" · Loading…";
|
||||
else if(!previewVisible && pageTotal>1) label+=L" · First page";
|
||||
else if(quickKind==QuickKind::binary)
|
||||
label=L"Binary · "+std::to_wstring(quickBinaryBytes)+L" / "+std::to_wstring(fileSize)+L" B · "+
|
||||
quickPath.filename().native();
|
||||
else
|
||||
{
|
||||
if(quickKind==QuickKind::html) label+=previewVisible?L" · Rendered":L" · Source";
|
||||
if(!previewVisible && pageTotal>1) label+=L" · First page";
|
||||
}
|
||||
if(quickModeButton && IsWindowVisible(quickModeButton))
|
||||
client.right=std::max(0L,client.right-scale(108));
|
||||
if(!quickTextTitle.empty()) label=quickTextTitle;
|
||||
drawEditorStatus(dc,{0,0,client.right,row},chromeFont,color(TextColor::chromebg),
|
||||
color(TextColor::chrome),scale(6),label);
|
||||
@@ -2872,7 +2960,13 @@ void TextWindow::notify(const SCNotification ¬ice)
|
||||
|
||||
bool TextWindow::handleKey(const MSG &message)
|
||||
{
|
||||
if(embedded) return false;
|
||||
if(embedded)
|
||||
{
|
||||
if(quickKind!=QuickKind::html || message.message!=WM_KEYDOWN || message.wParam!=VK_F6 ||
|
||||
((GetKeyState(VK_CONTROL)|GetKeyState(VK_SHIFT)|GetKeyState(VK_MENU))&0x8000)) return false;
|
||||
if(!(message.lParam&(1LL<<30))) toggleQuickHtml();
|
||||
return true;
|
||||
}
|
||||
const auto key = message.wParam;
|
||||
if (message.hwnd != editor) return false;
|
||||
if (message.message == WM_SYSKEYDOWN && (message.lParam & (1LL << 29)))
|
||||
@@ -2953,6 +3047,12 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
self->editor = CreateWindowExW(0, L"Scintilla", L"", WS_CHILD | WS_TABSTOP |
|
||||
WS_VSCROLL | WS_HSCROLL, 0, 0, 0, 0, window, nullptr, GetModuleHandleW(nullptr), nullptr);
|
||||
if (!self->editor) throw std::runtime_error("Cannot create the text control.");
|
||||
if(self->embedded)
|
||||
{
|
||||
self->quickModeButton=CreateWindowW(L"BUTTON",L"Show Source",WS_CHILD|WS_TABSTOP|BS_PUSHBUTTON,
|
||||
0,0,0,0,window,reinterpret_cast<HMENU>(quickModeControl),GetModuleHandleW(nullptr),nullptr);
|
||||
if(!self->quickModeButton) throw std::runtime_error("Cannot create the Quick View mode button.");
|
||||
}
|
||||
self->send(SCI_SETCODEPAGE, SC_CP_UTF8);
|
||||
self->send(SCI_SETMARGINS, 1);
|
||||
self->send(SCI_SETMODEVENTMASK, SC_MOD_INSERTCHECK | SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT);
|
||||
@@ -3050,7 +3150,11 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam,
|
||||
return 0;
|
||||
}
|
||||
case WM_COMMAND:
|
||||
if(self->embedded) return 0;
|
||||
if(self->embedded)
|
||||
{
|
||||
if(LOWORD(wparam)==quickModeControl) self->toggleQuickHtml();
|
||||
return 0;
|
||||
}
|
||||
if (LOWORD(wparam) >= 600 && LOWORD(wparam) < 605) self->openMenu(LOWORD(wparam) - 600);
|
||||
else self->command(LOWORD(wparam));
|
||||
return 0;
|
||||
|
||||
@@ -99,6 +99,23 @@ try {
|
||||
: { key:'Enter', code:'Enter', windowsVirtualKeyCode:13 };
|
||||
await command('Input.dispatchKeyEvent', { type:'keyDown', ...key });
|
||||
await command('Input.dispatchKeyEvent', { type:'keyUp', ...key });
|
||||
} else if (scenario === 'html-quick') {
|
||||
await waitFor(() => evaluate(`document.documentElement.classList.contains('rendered') &&
|
||||
document.querySelector('main h1')?.textContent === 'Offline HTML fixture'`), 'rendered HTML');
|
||||
assert.equal(await evaluate(`document.querySelector('main td strong')?.textContent`), 'Formatted table');
|
||||
assert.equal(await evaluate(`document.querySelector('main h1').style.color`), 'teal');
|
||||
assert.equal(await evaluate(`document.querySelector('main h1').style.position`), '');
|
||||
assert.equal(await evaluate(`document.querySelectorAll(
|
||||
'main :is(script, style, link, meta, iframe, object, img, input, [href], [src], [onload], [onclick])'
|
||||
).length`), 0);
|
||||
assert.equal(await evaluate(`document.querySelector('main').textContent.includes('Image description')`), true);
|
||||
assert.equal(await evaluate(`window.documentScriptRan`), undefined);
|
||||
await evaluate(`document.querySelector('main a').click()`);
|
||||
assert.equal(await evaluate('location.href'), 'https://kswitcher-markdown.invalid/markdown.html');
|
||||
if (artifact) {
|
||||
const screenshot = await command('Page.captureScreenshot', { format: 'png' });
|
||||
await writeFile(artifact, Buffer.from(screenshot.data, 'base64'));
|
||||
}
|
||||
} else if (scenario === 'render') {
|
||||
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
|
||||
!!document.querySelector('figure svg') &&
|
||||
|
||||
+173
-32
@@ -1,60 +1,133 @@
|
||||
param(
|
||||
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe"
|
||||
[string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe",
|
||||
[string]$ProfileSubkey = 'Software\KSwitcher\Files',
|
||||
[string]$Node = (Get-Command node -ErrorAction SilentlyContinue).Source,
|
||||
[string]$RenderedImage = '',
|
||||
[string]$BinaryImage = ''
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. "$PSScriptRoot/files_commands_ui.ps1"
|
||||
$browserProbe = $Node -and ((& $Node -p "typeof WebSocket === 'function'") -eq 'true')
|
||||
if($RenderedImage -and !$browserProbe){throw 'A Node runtime with WebSocket is required for a rendered screenshot'}
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class FilesQuickViewProbe {
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr parent, int id);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr window);
|
||||
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra);
|
||||
public static bool Activate(IntPtr window) {
|
||||
if (GetForegroundWindow() == window) return true;
|
||||
keybd_event(0x12, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(0x12, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(window);
|
||||
return GetForegroundWindow() == window;
|
||||
}
|
||||
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr window, IntPtr after, int x,
|
||||
int y, int width, int height, uint flags);
|
||||
[DllImport("user32.dll", EntryPoint="PostMessageW")]
|
||||
public static extern bool Post(IntPtr window, uint msg, IntPtr wp, IntPtr lp);
|
||||
[DllImport("user32.dll", EntryPoint="SendMessageW")]
|
||||
public static extern IntPtr Send(IntPtr window, uint msg, IntPtr wp, IntPtr lp);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
|
||||
public static extern IntPtr FindRow(IntPtr window, uint msg, IntPtr wp, string name);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")]
|
||||
public static extern IntPtr Read(IntPtr window, uint msg, IntPtr wp, StringBuilder text);
|
||||
[DllImport("user32.dll", CharSet=CharSet.Unicode)]
|
||||
public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title);
|
||||
}
|
||||
'@
|
||||
|
||||
function Wait-Until([scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 100; $attempt++) {
|
||||
if (& $Condition) { return }
|
||||
function Wait-Until([string]$Label,[scriptblock]$Condition) {
|
||||
for ($attempt = 0; $attempt -lt 150; $attempt++) {
|
||||
$result = & $Condition
|
||||
if ($result) { return $result }
|
||||
Start-Sleep -Milliseconds 50
|
||||
}
|
||||
throw "Timed out waiting for: $Condition"
|
||||
throw "Timed out waiting for $Label"
|
||||
}
|
||||
function Text([IntPtr]$Handle) {
|
||||
$buffer = [Text.StringBuilder]::new(256)
|
||||
[void][FilesQuickViewProbe]::Read($Handle, 13, [IntPtr]$buffer.Capacity, $buffer)
|
||||
$buffer.ToString()
|
||||
}
|
||||
function Select-File([string]$Name) {
|
||||
$row = [FilesQuickViewProbe]::FindRow($leftList, 0x1A2, [IntPtr](-1), $Name)
|
||||
if ($row.ToInt64() -lt 0) { throw "Missing row $Name" }
|
||||
[void][FilesQuickViewProbe]::Send($leftList, 0x186, $row, 0)
|
||||
[void][FilesQuickViewProbe]::Post($window, 273, [IntPtr](0x10000+102), $leftList)
|
||||
}
|
||||
function Preview-Bytes([int]$Count) {
|
||||
[byte[]]$bytes = @(
|
||||
for($i=0; $i -lt $Count; ++$i) {
|
||||
[byte]([FilesQuickViewProbe]::Send($editor, 2007, [IntPtr]$i, 0).ToInt32() -band 255)
|
||||
}
|
||||
)
|
||||
[Text.Encoding]::UTF8.GetString($bytes)
|
||||
}
|
||||
function Browser {
|
||||
& $Node (Join-Path $PSScriptRoot 'files_markdown_browser.mjs') $port 'html-quick' $RenderedImage 'preview.html'
|
||||
if ($LASTEXITCODE) { throw 'WebView2 verification failed for rendered HTML' }
|
||||
}
|
||||
|
||||
$exe = (Resolve-Path $Executable).Path
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files')
|
||||
$names = 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement'
|
||||
$source = Split-Path $exe
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($ProfileSubkey)
|
||||
$names = 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor',
|
||||
'LeftPanelMode', 'RightPanelMode', 'WindowPlacement'
|
||||
$saved = @{}
|
||||
foreach ($name in $names) {
|
||||
if ($name -in $key.GetValueNames()) { $saved[$name] = @($key.GetValue($name), $key.GetValueKind($name)) }
|
||||
}
|
||||
$flags = $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
|
||||
$profile = $env:WEBVIEW2_USER_DATA_FOLDER
|
||||
$fixture = [IO.Directory]::CreateTempSubdirectory('ks-files-quick-view-')
|
||||
$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4))
|
||||
try {
|
||||
$network = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
|
||||
$network.Start()
|
||||
$probe = "http://127.0.0.1:$($network.LocalEndpoint.Port)/should-not-load"
|
||||
$debug = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,0)
|
||||
$debug.Start()
|
||||
$port = $debug.LocalEndpoint.Port
|
||||
$debug.Stop()
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = "--remote-debugging-port=$port --disable-background-networking"
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER = Join-Path $fixture.FullName 'webview'
|
||||
$app = $fixture.CreateSubdirectory('app')
|
||||
Copy-Item -LiteralPath $exe,"$source\WebView2Loader.dll","$source\terminal" -Destination $app.FullName -Recurse
|
||||
$left = $fixture.CreateSubdirectory('left')
|
||||
$right = $fixture.CreateSubdirectory('right')
|
||||
$document = Join-Path $left.FullName 'preview.txt'
|
||||
[IO.File]::WriteAllText($document, 'Quick View fixture')
|
||||
$key.SetValue('LeftWide', 1, 'DWord')
|
||||
$key.SetValue('RightWide', 1, 'DWord')
|
||||
[IO.File]::WriteAllText((Join-Path $left.FullName 'preview.html'), @"
|
||||
<!doctype html>
|
||||
<html><head><title>Document title</title>
|
||||
<meta http-equiv="refresh" content="0;url=$probe">
|
||||
<link rel="stylesheet" href="$probe">
|
||||
<style>@import url('$probe');</style>
|
||||
<script>window.documentScriptRan = true;</script></head>
|
||||
<body onload="window.documentScriptRan = true;"><main>
|
||||
<h1 style="color: teal; position: fixed" onclick="window.documentScriptRan = true;">Offline HTML fixture</h1>
|
||||
<table><tr><td><strong>Formatted table</strong></td></tr></table>
|
||||
<a href="$probe">External link</a>
|
||||
<img src="$probe" alt="Image description"><iframe src="$probe"></iframe>
|
||||
<form action="$probe"><input type="submit"></form>
|
||||
</main></body></html>
|
||||
"@)
|
||||
$data = [byte[]]::new(5000)
|
||||
[byte[]]$header = 0,1,9,10,13,27,31,32,65,127,128,255
|
||||
$header.CopyTo($data,0)
|
||||
for ($i=$header.Length; $i -lt $data.Length; ++$i) { $data[$i] = 66 }
|
||||
[IO.File]::WriteAllBytes((Join-Path $left.FullName 'symbols.bin'), $data)
|
||||
$expectedSymbols = -join ([char[]]@(0xe000,0xe001,0xe009,0xe00a,0xe00d,0xe01b,0xe01f,
|
||||
0x20,0x41,0xe07f,0xC7,0xe0ff))
|
||||
$key.SetValue('LeftPanelMode', 1, 'DWord')
|
||||
$key.SetValue('RightPanelMode', 1, 'DWord')
|
||||
$key.SetValue('LeftPath', $left.FullName, 'String')
|
||||
$key.SetValue('RightPath', $right.FullName, 'String')
|
||||
$key.SetValue('LeftCursor', $document, 'String')
|
||||
$key.DeleteValue('RightCursor', $false)
|
||||
$key.DeleteValue('WindowPlacement', $false)
|
||||
|
||||
$process = Start-Process -FilePath $exe -PassThru
|
||||
Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero }
|
||||
$window = $process.MainWindowHandle
|
||||
Wait-Until { [FilesQuickViewProbe]::Activate($window) }
|
||||
$keyboard = New-Object -ComObject WScript.Shell
|
||||
$process = Start-Process -FilePath (Join-Path $app.FullName (Split-Path -Leaf $exe)) -PassThru -WindowStyle Normal
|
||||
$window = Wait-Until 'the Files window' {
|
||||
$process.Refresh()
|
||||
if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle }
|
||||
}
|
||||
[void][FilesQuickViewProbe]::SetWindowPos($window,0,40,50,1500,920,20)
|
||||
$leftList = [FilesQuickViewProbe]::GetDlgItem($window, 102)
|
||||
$rightList = [FilesQuickViewProbe]::GetDlgItem($window, 103)
|
||||
$rightHeading = [FilesQuickViewProbe]::GetDlgItem($window, 141)
|
||||
@@ -62,12 +135,16 @@ try {
|
||||
if (!($leftList -and $rightList -and $rightHeading -and $rightPath)) {
|
||||
throw 'Expected both file panels in the test window.'
|
||||
}
|
||||
Wait-Until { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) }
|
||||
$keyboard.SendKeys('^q')
|
||||
Wait-Until {
|
||||
[void](Wait-Until 'both panels' { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) })
|
||||
Invoke-FilesCommand $window 'Quick View*'
|
||||
$preview = Wait-Until 'Quick View' {
|
||||
$hostWindow = [FilesQuickViewProbe]::GetDlgItem($window, 158)
|
||||
$hostWindow -ne [IntPtr]::Zero -and [FilesQuickViewProbe]::IsWindowVisible($hostWindow)
|
||||
if ([FilesQuickViewProbe]::IsWindowVisible($hostWindow)) { $hostWindow }
|
||||
}
|
||||
$editor = [FilesQuickViewProbe]::FindWindowEx($preview,0,'Scintilla',[NullString]::Value)
|
||||
[void](Wait-Until 'the text preview' { [FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -eq 18 })
|
||||
$initialWrap = [FilesQuickViewProbe]::Send($editor,2269,0,0)
|
||||
$initialScrollbar = [FilesQuickViewProbe]::Send($editor,2131,0,0)
|
||||
foreach ($control in $rightList, $rightHeading, $rightPath) {
|
||||
if ([FilesQuickViewProbe]::IsWindowVisible($control)) {
|
||||
throw 'A file panel control can draw over the Quick View content.'
|
||||
@@ -75,19 +152,75 @@ try {
|
||||
}
|
||||
if (![FilesQuickViewProbe]::IsWindowVisible($leftList)) { throw 'Quick View hid the source panel.' }
|
||||
|
||||
$keyboard.SendKeys('^q')
|
||||
Wait-Until { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero }
|
||||
Select-File 'preview.html'
|
||||
$mode = [FilesQuickViewProbe]::GetDlgItem($preview,159)
|
||||
[void](Wait-Until 'the HTML mode switch' { [FilesQuickViewProbe]::IsWindowVisible($mode) -and (Text $mode) -eq 'Show Source' })
|
||||
if ($browserProbe) { Browser }
|
||||
[void][FilesQuickViewProbe]::Post($preview,273,159,$mode)
|
||||
[void](Wait-Until 'the HTML source' {
|
||||
[FilesQuickViewProbe]::IsWindowVisible($editor) -and (Text $mode) -eq 'Show Rendered' -and
|
||||
(Preview-Bytes 15) -eq '<!doctype html>'
|
||||
})
|
||||
[void][FilesQuickViewProbe]::Post($editor,0x100,117,0)
|
||||
[void](Wait-Until 'keyboard switch back to Rendered' { (Text $mode) -eq 'Show Source' })
|
||||
if ($browserProbe) { Browser }
|
||||
if ($network.Pending()) { throw 'Rendering HTML attempted an outbound resource request' }
|
||||
|
||||
Select-File 'symbols.bin'
|
||||
[void](Wait-Until 'binary glyphs in the embedded view' {
|
||||
[FilesQuickViewProbe]::IsWindowVisible($editor) -and [FilesQuickViewProbe]::Send($editor,2269,0,0).ToInt32() -eq 2
|
||||
})
|
||||
if ((Preview-Bytes ([Text.Encoding]::UTF8.GetByteCount($expectedSymbols))) -cne $expectedSymbols) {
|
||||
throw 'Binary control bytes were lost or decoded as text'
|
||||
}
|
||||
$expectedLength = [Text.Encoding]::UTF8.GetByteCount($expectedSymbols) + 4096 - $header.Length
|
||||
if ([FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -ne $expectedLength -or
|
||||
[FilesQuickViewProbe]::Send($editor,2131,0,0).ToInt32() -ne 0) {
|
||||
throw 'Binary preview exceeded its byte limit or enabled horizontal scrolling'
|
||||
}
|
||||
$escapeWidth = [FilesQuickViewProbe]::Send($editor,2164,0,3).ToInt32() -
|
||||
[FilesQuickViewProbe]::Send($editor,2164,0,0).ToInt32()
|
||||
if($escapeWidth -le [FilesQuickViewProbe]::Send($editor,2279,0,0).ToInt32()){
|
||||
throw 'The control byte did not render as a full visible escape'
|
||||
}
|
||||
if($BinaryImage){
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
$bounds = [FilesCommandsUi+Rect]::new()
|
||||
[void][FilesCommandsUi]::GetClientRect($preview,[ref]$bounds)
|
||||
$bitmap = [Drawing.Bitmap]::new($bounds.Right,$bounds.Bottom)
|
||||
$graphics = [Drawing.Graphics]::FromImage($bitmap)
|
||||
try {
|
||||
$dc = $graphics.GetHdc()
|
||||
try { if(![FilesCommandsUi]::PrintWindow($preview,$dc,3)){throw 'Could not render binary preview'} }
|
||||
finally { $graphics.ReleaseHdc($dc) }
|
||||
$bitmap.Save($BinaryImage,[Drawing.Imaging.ImageFormat]::Png)
|
||||
} finally { $graphics.Dispose(); $bitmap.Dispose() }
|
||||
}
|
||||
$wideRows = [FilesQuickViewProbe]::Send($editor,2235,0,0).ToInt32()
|
||||
[void][FilesQuickViewProbe]::SetWindowPos($window,0,40,50,840,920,20)
|
||||
[void](Wait-Until 'binary rows wrap in a narrower pane' { [FilesQuickViewProbe]::Send($editor,2235,0,0).ToInt32() -gt $wideRows })
|
||||
|
||||
Select-File 'preview.txt'
|
||||
[void](Wait-Until 'ordinary text preview restored' { [FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -eq 18 })
|
||||
if ([FilesQuickViewProbe]::IsWindowVisible($mode) -or [FilesQuickViewProbe]::Send($editor,2269,0,0) -ne $initialWrap -or
|
||||
[FilesQuickViewProbe]::Send($editor,2131,0,0) -ne $initialScrollbar) { throw 'Preview mode leaked into a text file' }
|
||||
[void][FilesQuickViewProbe]::Post($window,0x801F,0,0)
|
||||
[void](Wait-Until 'Quick View closed' { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero })
|
||||
foreach ($control in $rightList, $rightHeading, $rightPath) {
|
||||
if (![FilesQuickViewProbe]::IsWindowVisible($control)) {
|
||||
throw 'A file panel control remained hidden after closing Quick View.'
|
||||
}
|
||||
}
|
||||
'Quick View hides the covered list and chrome, then restores the same controls.'
|
||||
'Quick View verified with offline HTML, source switching, bounded binary glyphs and restored file panels.'
|
||||
} finally {
|
||||
if ($process -and !$process.HasExited) {
|
||||
[void]$process.CloseMainWindow()
|
||||
if (!$process.WaitForExit(3000)) { $process.Kill(); $process.WaitForExit() }
|
||||
}
|
||||
if ($network) { $network.Stop() }
|
||||
if ($dpi) { [void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi) }
|
||||
$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = $flags
|
||||
$env:WEBVIEW2_USER_DATA_FOLDER = $profile
|
||||
foreach ($name in $names) {
|
||||
if ($saved.ContainsKey($name)) { $key.SetValue($name, $saved[$name][0], $saved[$name][1]) }
|
||||
else { $key.DeleteValue($name, $false) }
|
||||
@@ -96,6 +229,14 @@ try {
|
||||
$path = [IO.Path]::GetFullPath($fixture.FullName)
|
||||
if ([IO.Path]::GetDirectoryName($path) -eq [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath()) -and
|
||||
[IO.Path]::GetFileName($path).StartsWith('ks-files-quick-view-')) {
|
||||
[IO.Directory]::Delete($path, $true)
|
||||
for($attempt=0; $attempt -lt 50; ++$attempt){
|
||||
try {
|
||||
[IO.Directory]::Delete($path, $true)
|
||||
break
|
||||
} catch [System.IO.IOException] {
|
||||
if($attempt -eq 49){throw}
|
||||
Start-Sleep -Milliseconds 100
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -160,6 +160,12 @@ void hexBytes(const fs::path &file)
|
||||
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 controls("\x00\x01\x09\x0A\x0D\x1B\x1F A\x7F\x80\xFF",12);
|
||||
const std::string symbols(reinterpret_cast<const char *>(u8"\ue000\ue001\ue009\ue00a\ue00d\ue01b\ue01f A\ue07f\u00c7\ue0ff"));
|
||||
check(ks::files::formatBinarySymbols(controls)==symbols,"Quick View displays all control and high bytes as glyphs");
|
||||
const std::string slash(reinterpret_cast<const char *>(u8"\ue05c"));
|
||||
check(ks::files::formatBinarySymbols("\\x00")==slash+"x00","Binary preview distinguishes literal escapes");
|
||||
check(ks::files::formatBinarySymbols({}).empty(),"An empty symbol preview stays empty");
|
||||
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");
|
||||
|
||||
Reference in new issue
Block a user