From e852fde4f46e230e20cfb527c7daaf53548ebeb8 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 23:35:15 +0200 Subject: [PATCH] Open recent Files diagnostics in a safe native viewer Refs #132 --- FILES-UI.md | 2 +- resources/files.rc | 14 ++++ src/files_help.h | 2 +- src/files_help.inl | 7 +- src/files_log_view.inl | 177 +++++++++++++++++++++++++++++++++++++++++ src/files_main.cpp | 8 +- src/platform.cpp | 35 ++++++++ src/platform.h | 1 + 8 files changed, 241 insertions(+), 5 deletions(-) create mode 100644 src/files_log_view.inl diff --git a/FILES-UI.md b/FILES-UI.md index 4032daf..6d5907e 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -635,7 +635,7 @@ Warning і початковий фокус на No. розміру, а список має однаковий внутрішній відступ зліва і справа. - Тайм-аут запиту дисків відображається як Connection timed out. Якщо ввімкнено Write log, Files записує помилки запитів пар і дисків в окремий - журнал `data/kswitcher-files.log`. Системні помилки містять код Windows. + журнал `data/kswitcher-files.log`. Системні помилки містять код Windows. Commands → Files log відкриває до 200 останніх записів поточного або попереднього журналу. Refresh оновлює список. Copy selected або Ctrl+C копіює дату й безпечний опис вибраного запису. Довільні текстові деталі приховано. - Застосовані налаштування Files одразу підхоплюють інші відкриті вікна. Apply зберігає поля, змінені в поточній чернетці. Якщо два вікна одночасно diff --git a/resources/files.rc b/resources/files.rc index 0445bd6..816e3fc 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -214,6 +214,20 @@ BEGIN DEFPUSHBUTTON "&Close", IDOK, 403, 216, 56, 16 END +619 DIALOGEX 0, 0, 435, 211 +STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Files log" +FONT 9, "Segoe UI" +BEGIN + LTEXT "&Log", -1, 9, 12, 40, 11 + COMBOBOX 680, 51, 9, 115, 70, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL + LTEXT "", 681, 9, 31, 415, 28 + LISTBOX 682, 9, 62, 417, 117, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP + PUSHBUTTON "&Copy selected", 683, 9, 187, 90, 15 + PUSHBUTTON "&Refresh", 684, 107, 187, 66, 15 + DEFPUSHBUTTON "Close", IDOK, 370, 187, 56, 15 +END + 101 DIALOGEX 0, 0, 397, 310 STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN CAPTION "KSwitcher Files Options" diff --git a/src/files_help.h b/src/files_help.h index 6aef6a6..7884c19 100644 --- a/src/files_help.h +++ b/src/files_help.h @@ -8,6 +8,6 @@ inline constexpr UINT filesHelpRequest=WM_APP+273; enum class FilesHelpTopic { panels, menus, navigation, find, transfer, deleteFiles, archive, space, properties, connections, - terminal, viewer, editor, markdown, images, comparison, git, environment, options, keys, appearance, portability, count + terminal, viewer, editor, markdown, images, comparison, git, environment, options, keys, appearance, portability, log, count }; } diff --git a/src/files_help.inl b/src/files_help.inl index 257c1be..5f0ccff 100644 --- a/src/files_help.inl +++ b/src/files_help.inl @@ -69,7 +69,10 @@ constexpr struct L"Viewer and Editor can use System (Windows). Assign either a stock or named palette to each Windows mode under Appearance → System themes."}, {L"Import and export settings",L"json portable backup restore transfer option groups", L"Select the saved settings groups to include in an export. The supported groups cover colors and file styles, panel layout and keyboard schemes.\r\n\r\n" - L"Import stages chosen groups in Options. Files asks before replacing differing schemes with the same name. Apply saves the new values."} + L"Import stages chosen groups in Options. Files asks before replacing differing schemes with the same name. Apply saves the new values."}, + {L"Files log",L"diagnostic journal error logging rotate copy record", + L"Open Files log from Commands to see recent entries. Switch between the current and previous rotated log, or use Refresh to read newer entries.\r\n\r\n" + L"Select an entry to copy its timestamp and summary. The viewer shows only supported diagnostic details."} }; static_assert(std::size(filesHelpTopics)==static_cast(FilesHelpTopic::count)); @@ -185,6 +188,7 @@ FilesHelpTopic filesMenuHelpTopic() case 19: return FilesHelpTopic::terminal; case 20: return FilesHelpTopic::keys; case 21: return FilesHelpTopic::appearance; + case 23: return FilesHelpTopic::log; default: return FilesHelpTopic::menus; } } @@ -229,6 +233,7 @@ std::optional filesHelpForWindow(HWND root,HWND target) case 608: return FilesHelpTopic::appearance; case 615: case 616: return FilesHelpTopic::keys; case 617: return FilesHelpTopic::portability; + case 619: return FilesHelpTopic::log; case 604: case 607: if(const auto owner=GetWindow(root,GW_OWNER);owner && owner!=root) return filesHelpForWindow(owner,owner); diff --git a/src/files_log_view.inl b/src/files_log_view.inl new file mode 100644 index 0000000..0a053cc --- /dev/null +++ b/src/files_log_view.inl @@ -0,0 +1,177 @@ +constexpr int filesLogSource=680,filesLogStatus=681,filesLogEntries=682,filesLogCopy=683,filesLogRefresh=684; +constexpr size_t filesLogEntryLimit=200,filesLogReadLimit=256*1024; + +std::optional filesLogError(std::string_view message,std::string_view marker) +{ + const auto last=message.rfind(marker); + if(last==message.npos) return {}; + const auto value=message.substr(last+marker.size()); + unsigned error{}; + const auto parsed=std::from_chars(value.data(),value.data()+value.size(),error); + if(parsed.ec!=std::errc{} || parsed.ptr!=value.data()+value.size()) return {}; + return error; +} + +std::wstring safeFilesLogEntry(std::string_view line) +{ + if(line.ends_with('\r')) line.remove_suffix(1); + std::wstring stamp; + constexpr std::string_view format="0000-00-00 00:00:00 "; + if(line.size()>=format.size()) + { + bool valid=true; + for(size_t i=0;i='0' && line[i]<='9'):line[i]==format[i]; + if(valid) + { + stamp=ks::wide(std::string(line.substr(0,format.size()-1)))+L" · "; + line.remove_prefix(format.size()); + } + } + + // Only fixed descriptions and numeric Windows result codes cross into the UI or clipboard. + std::wstring text; + std::optional error; + if(line=="LAN Files peer lookup failed: local KSwitcher window not found") + text=L"LAN peer lookup failed. KSwitcher is unavailable."; + else if(line.starts_with("LAN Files peer lookup failed: delivered=")) + { + text=L"LAN peer lookup failed"; + error=filesLogError(line,", Windows error="); + } + else if(line=="LAN Files drive query failed: unexpected error") + text=L"LAN drive query failed. Unexpected error."; + else if(line.starts_with("LAN Files drive query for ")) + { + text=L"LAN drive query failed"; + error=filesLogError(line,") failed: Windows error "); + if(error==WSAETIMEDOUT) text=L"LAN drive query timed out"; + } + else text=L"Diagnostic entry · details hidden"; + if(error && *error) text+=L" (Windows error "+std::to_wstring(*error)+L")"; + return stamp+text; +} + +std::vector recentFilesLogEntries(const ks::Bytes &bytes) +{ + std::vector entries; + if(bytes.empty()) return entries; + const std::string_view text(reinterpret_cast(bytes.data()),bytes.size()); + auto end=text.size(); + while(end && entries.size() entries; +}; + +void refreshFilesLog(HWND dialog,FilesLogDraft &draft) +{ + const bool previous=SendDlgItemMessageW(dialog,filesLogSource,CB_GETCURSEL,0,0)==1; + const auto list=GetDlgItem(dialog,filesLogEntries); + SendMessageW(list,LB_RESETCONTENT,0,0); + SendMessageW(list,LB_SETHORIZONTALEXTENT,0,0); + draft.entries.clear(); + try + { + if(const auto data=ks::readActiveLogTail(previous,filesLogReadLimit)) + { + draft.entries=recentFilesLogEntries(*data); + SetDlgItemTextW(dialog,filesLogStatus,draft.entries.empty()?L"The Files log has no entries.": + L"Most recent first. Select an entry to copy its timestamp and description."); + } + else SetDlgItemTextW(dialog,filesLogStatus,previous?L"No previous Files log is available yet.": + L"No Files log yet. Entries appear when Write log is enabled and Files records a problem."); + } + catch(const std::exception &) + { + SetDlgItemTextW(dialog,filesLogStatus,L"Could not read the Files log. Use Refresh to try again."); + } + int width=0; + const auto dc=GetDC(list); + const auto font=reinterpret_cast(SendMessageW(list,WM_GETFONT,0,0)); + const auto oldFont=dc && font?SelectObject(dc,font):nullptr; + for(const auto &entry:draft.entries) + { + SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast(entry.c_str())); + if(dc) + { + SIZE extent{}; + GetTextExtentPoint32W(dc,entry.c_str(),static_cast(entry.size()),&extent); + width=std::max(width,static_cast(extent.cx)+12); + } + } + if(oldFont) SelectObject(dc,oldFont); + if(dc) ReleaseDC(list,dc); + if(width) SendMessageW(list,LB_SETHORIZONTALEXTENT,width,0); + if(!draft.entries.empty()) SendMessageW(list,LB_SETCURSEL,0,0); + EnableWindow(GetDlgItem(dialog,filesLogCopy),!draft.entries.empty()); +} + +LRESULT CALLBACK filesLogListKeys(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +{ + if(message==WM_KEYDOWN && wp=='C' && (GetKeyState(VK_CONTROL)&0x8000) && + !((GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) + { + if(!(lp&(1LL<<30))) SendMessageW(GetParent(list),WM_COMMAND,MAKEWPARAM(filesLogCopy,BN_CLICKED),0); + return 0; + } + return DefSubclassProc(list,message,wp,lp); +} + +INT_PTR CALLBACK filesLogDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_INITDIALOG) + { + auto &draft=*reinterpret_cast(lp); + SetWindowLongPtrW(dialog,DWLP_USER,lp); + for(const auto name:{L"Current",L"Previous"}) + SendDlgItemMessageW(dialog,filesLogSource,CB_ADDSTRING,0,reinterpret_cast(name)); + SendDlgItemMessageW(dialog,filesLogSource,CB_SETCURSEL,0,0); + SetWindowSubclass(GetDlgItem(dialog,filesLogEntries),filesLogListKeys,1,0); + refreshFilesLog(dialog,draft); + return TRUE; + } + if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL))) + { + FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + if(message!=WM_COMMAND) return FALSE; + auto &draft=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + if(LOWORD(wp)==filesLogRefresh || (LOWORD(wp)==filesLogSource && HIWORD(wp)==CBN_SELCHANGE)) + { + refreshFilesLog(dialog,draft); + return TRUE; + } + if(LOWORD(wp)==filesLogCopy) + { + const auto row=SendDlgItemMessageW(dialog,filesLogEntries,LB_GETCURSEL,0,0); + if(row>=0 && static_cast(row)(&draft),false,false); + dialog.runModal(); +} diff --git a/src/files_main.cpp b/src/files_main.cpp index 4c45980..4d24f1f 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -3940,6 +3941,7 @@ bool gitChangesAvailable(const Panel &panel); void openGitChanges(HWND owner,const Panel &panel); void showEnvironmentPanel(HWND owner); void showFilesHelp(HWND owner,ks::files::FilesHelpTopic topic); +void showFilesLog(HWND owner); void editFilesKeySchemes(HWND owner,FilesKey initial,FilesKeySettings *pending=nullptr); void showCommandHistory(HWND owner); @@ -3997,6 +3999,7 @@ void selectDrive() else if(menuIndex==2 && row==20) editFilesKeySchemes(owner,FilesKey::Refresh); else if(menuIndex==2 && row==21) editFilesAppearance(owner,terminalVisible?AppearanceArea::terminal:AppearanceArea::panels); else if(menuIndex==2 && row==22) showFilesHelp(owner,terminalVisible?ks::files::FilesHelpTopic::terminal:ks::files::FilesHelpTopic::panels); + else if(menuIndex==2 && row==23) showFilesLog(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]); @@ -8346,7 +8349,7 @@ void openMenu(HWND window, int index) filesKeyMenuLabel(FilesKey::FullPath),L"Space Analyzer",filesKeyMenuLabel(FilesKey::HexView), L"Viewer bookmarks…",L"Processes…",L"Git Changes…",L"Environment Variables…",filesKeyMenuLabel(FilesKey::Swap), filesKeyMenuLabel(FilesKey::History),L"Keyboard shortcuts…", - terminalVisible?L"Terminal appearance…":L"Panel appearance…",L"Help…\tF1"}; + terminalVisible?L"Terminal appearance…":L"Panel appearance…",L"Help…\tF1",L"Files log…"}; } const auto &panel=panels[active]; const bool remoteResults=remoteSearchResults(panel); @@ -8393,7 +8396,7 @@ void openMenu(HWND window, int index) } if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10); if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7}); - commandActions.insert(commandActions.end(),{-1,19,20,21,22}); + commandActions.insert(commandActions.end(),{-1,19,20,21,23,22}); } else for(size_t i=0;i(i)); @@ -9461,6 +9464,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) return DefWindowProcW(window, message, wp, lp); } +#include "files_log_view.inl" #include "files_help.inl" } diff --git a/src/platform.cpp b/src/platform.cpp index fd9f044..7e01680 100644 --- a/src/platform.cpp +++ b/src/platform.cpp @@ -899,6 +899,41 @@ void setLoggingEnabled(bool enabled) if (!enabled) diagnosticBuffer.clear(); } +std::optional readActiveLogTail(bool previous,size_t byteLimit) +{ + std::lock_guard lock(logGate); + auto path=logDirectory()/logFilename; + if(previous) path+=L".1"; + const auto raw=CreateFileW(path.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, + nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr); + if(raw==INVALID_HANDLE_VALUE) + { + const auto error=GetLastError(); + if(error==ERROR_FILE_NOT_FOUND || error==ERROR_PATH_NOT_FOUND) return {}; + throw std::runtime_error("Cannot open the diagnostic log"); + } + const std::unique_ptr file(raw,CloseHandle); + LARGE_INTEGER size{}; + if(!GetFileSizeEx(raw,&size) || size.QuadPart<0) throw std::runtime_error("Cannot measure the diagnostic log"); + const auto limit=std::min(byteLimit,2*1024*1024); + if(!limit || !size.QuadPart) return Bytes{}; + const auto offset=std::max(0,size.QuadPart-static_cast(limit)); + LARGE_INTEGER position{}; + position.QuadPart=offset?offset-1:0; + if(!SetFilePointerEx(raw,position,nullptr,FILE_BEGIN)) throw std::runtime_error("Cannot seek in the diagnostic log"); + Bytes contents(static_cast(size.QuadPart-position.QuadPart)); + DWORD read{}; + if(!ReadFile(raw,contents.data(),static_cast(contents.size()),&read,nullptr)) + throw std::runtime_error("Cannot read the diagnostic log"); + contents.resize(read); + if(offset && !contents.empty()) + { + const auto newline=std::find(contents.begin(),contents.end(),'\n'); + contents.erase(contents.begin(),newline==contents.end()?newline:std::next(newline)); + } + return contents; +} + std::wstring readDiagnosticLog(bool previous) { std::lock_guard lock(logGate); diff --git a/src/platform.h b/src/platform.h index 7e0b1e4..7060e7f 100644 --- a/src/platform.h +++ b/src/platform.h @@ -107,5 +107,6 @@ void expireDiagnostics(ULONGLONG now); void diagnosticEvent(const std::wstring &message, bool problem = false); void diagnosticOperation(const std::string &json); std::wstring readDiagnosticLog(bool previous); +std::optional readActiveLogTail(bool previous,size_t byteLimit); void clearDiagnosticLog(bool previous); } // namespace ks