From 46b4b51cea08dfa804e97dfac65acab83ac9ec4e Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Sat, 14 Nov 2026 14:42:48 +0200 Subject: [PATCH] feat(files): add searchable command history Persist command recall and align keyboard, mouse, and dialog behavior. Refs #18 --- FILES-UI.md | 50 +++- resources/files.rc | 43 +++- src/files_command_history.inl | 103 ++++++++ src/files_command_history_dialog.inl | 365 +++++++++++++++++++++++++++ src/files_dialog_input.inl | 128 ++++++++++ src/files_folder_shortcuts.inl | 39 +-- src/files_main.cpp | 273 ++++++++++++++------ src/files_options.inl | 38 ++- src/files_styles.inl | 2 +- 9 files changed, 914 insertions(+), 127 deletions(-) create mode 100644 src/files_command_history.inl create mode 100644 src/files_command_history_dialog.inl create mode 100644 src/files_dialog_input.inl diff --git a/FILES-UI.md b/FILES-UI.md index e8b5c0d..ecb7b40 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -4,6 +4,43 @@ Far Manager є зразком для оформлення файлового м ## Скорочення +- У командному рядку Ctrl+V і Shift+Insert вставляють текст із буфера обміну + в позицію курсора або замінюють виділення. Якщо фокус на файловій панелі, + ці клавіші переводять його до командного рядка й вставляють текст там. + Enter запускає команду. Escape очищає поле й залишає фокус у командному рядку. + Промпт і текст команди вирівняні по спільній базовій лінії. + +- Ctrl+E підставляє останню команду та переводить фокус із файлової панелі + до командного рядка. Повторне натискання + підставляє старішу, доки не досягне початку історії. Alt+F8 відкриває історію + з групуванням за датами. Enter або подвійний клік у списку підставляє вибрану + команду в поле. Для запуску натисни Enter у самому полі. +- Історія зберігає 1000 останніх непорожніх команд, надісланих із поля KSwitcher + Files, включно з повторами. Вона зберігається локально в профілі Windows між + запусками. Options → Command line → Command history змінює обидві комбінації, + перевіряє конфлікти та дозволяє відновити типові значення. +- Ширина історії підлаштовується під найдовшу команду в межах робочої області + монітора. Рядок, який не вміщується, закінчується трьома крапками. Вибір + підставляє до командного рядка повний текст. +- Пошук в історії фільтрує команди за всіма введеними словами, незалежно від + регістру. Збіги за текстом або датою йдуть перед тематичними. Тематичні + ключові слова визначаються локально й використовуються лише для пошуку, + зокрема в раніше збережених записах. Кожна команда відображається один + раз, за датою останнього запуску. +- Історія використовує оформлення діалогів Delete і Copy та спільне поле Far. + Підпис, поле й список вирівнюються за відступами Dialog frame. Рядки команд + і роздільники дат мають власний внутрішній відступ. + Вікно історії бірюзове, поле пошуку сіро-бірюзове. Поки історія відкрита, + дії в панелях, меню й командному рядку заблоковано. Заголовок і рамка + головного вікна доступні для переміщення, зміни розміру та керування вікном. + Escape або клік поза діалогом закриває історію. Заголовок і рамка головного + вікна залишають історію відкритою під час керування вікном. + Історія центрується відносно головного вікна й рухається разом із ним. + Tab циклічно переводить фокус між пошуком і списком. + Стрілка вгору або вниз із пошуку одразу пересуває вибір у списку. + Висота списку залежить від кількості результатів. Коли місця бракує, + прокручується список. + - Короткий Alt перемикає головне меню Files при відпусканні. F9 також перемикає меню. Після закриття фокус повертається до активної панелі. Alt з літерою верхнього рівня спрацьовує одразу при натисканні літери. Alt+O відкриває Options, а відпускання Alt після комбінації не перемикає меню. - Коли головне меню відкрите, L, F, C, O та R відкривають Left, Files, Commands, Options та Right. У підменю підсвічена літера викликає відповідну команду. Літери унікальні в межах поточного рівня. Усталені мнемоніки мають пріоритет, зокрема X для Exit. - Глобальне скорочення **Open KSwitcher Files** можна змінити або очистити в налаштуваннях. Для профілю без цього поля пропонується Ctrl+Alt+F, якщо Windows реєструє комбінацію і вона вільна серед прив’язок KSwitcher. @@ -28,6 +65,8 @@ Far Manager є зразком для оформлення файлового м ## Панелі +- Типовий колір тексту для ZIP-архівів — світлий коралово-рожевий. + - Меню Change drive показує літеру, тип, загальний обсяг і вільне місце. Відкриття меню запускає нове LAN-виявлення. Секція KSwitcher LAN показує збережені пари, зокрема офлайн. Після кожного відкриття меню асинхронно запитує диски й показує їх під назвою відповідного ПК. Поки триває запит, видно стан завантаження. Якщо запит не вдався, видно помилку. Повторне відкриття запускає новий запит. Кожна панель має власний диск і шлях, а в заголовку віддаленої панелі перед шляхом показано назву ПК. - Список дисків і файлові операції використовують права облікового запису Windows, під яким працює віддалений KSwitcher. Достатньо спарювання й доступного TCP 45885, спільні папки налаштовувати не потрібно. @@ -38,12 +77,18 @@ Far Manager є зразком для оформлення файлового м - У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size. -- Бірюзовий курсор поточного рядка видно лише в активній панелі. Кожна панель зберігає свою позицію курсора. +- Бірюзовий курсор поточного рядка видно лише в активній панелі, зокрема коли клавіатурний фокус переходить у командний рядок. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель. +- Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший. - Поточний шлях відображається по центру верхньої подвійної лінії панелі. Лінію видно з обох боків напису. Бірюзове тло активної панелі охоплює лише напис шляху з невеликими відступами. Довгий шлях скорочується в межах панелі. ## Спільні елементи діалогів +- Власні діалоги Files блокують дії панелей і командного рядка, залишаючи + системний заголовок і рамку головного вікна доступними. Клік поза діалогом + діє як Cancel. Для прогресу копіювання, переміщення й видалення це відкриває + підтвердження скасування. + - Enter активує кнопку у фокусі. Для кнопок із власним малюванням використовуй спільний обробник `dialogButtonEnter`. У підтвердженні скасування початковий фокус стоїть на No. - При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання. @@ -73,6 +118,9 @@ Far Manager є зразком для оформлення файлового м ## Попередження про конфлікт +- Для однойменних файлів Warning показує точний розмір у байтах із розділенням тисяч і місцевий + час останньої зміни окремо для вхідного файла та файла в папці призначення. + - Після розрахунку остаточної висоти центр Warning збігається з центром вікна прогресу. - Remember choice стоїть по вертикальному центру власної секції. Кнопки Overwrite, Skip і Cancel стоять по центру нижньої секції. - Tab проходить Remember choice, Overwrite, Skip і Cancel. Стрілки вліво та вправо циклічно перемикають три кнопки в порядку їх розташування. diff --git a/resources/files.rc b/resources/files.rc index 0be16d1..750d5e1 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -39,6 +39,10 @@ BEGIN COMBOBOX 305, 311, 51, 56, 125, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL LTEXT "&Row text padding (characters)", 306, 131, 77, 173, 12 COMBOBOX 307, 311, 74, 56, 76, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL + LTEXT "Previous command", 320, 131, 30, 120, 12 + CONTROL "", 321, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 27, 110, 15 + LTEXT "Open command history", 322, 131, 53, 120, 12 + CONTROL "", 323, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 50, 110, 15 PUSHBUTTON "Reset selected to defaults", 284, 131, 181, 125, 15 COMBOBOX 285, 131, 183, 139, 95, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL PUSHBUTTON "Reset property", 286, 278, 183, 108, 15 @@ -62,18 +66,19 @@ BEGIN PUSHBUTTON "&Apply", 283, 338, 289, 50, 14 END -102 DIALOGEX 0, 0, 350, 114 +102 DIALOGEX 0, 0, 350, 145 STYLE DS_SETFONT | DS_CENTER | WS_POPUP CAPTION "Copy" FONT 10, "Consolas" BEGIN LTEXT "Copy to", 210, 14, 15, 322, 12, SS_PATHELLIPSIS FAR_EDIT(211, ES_MULTILINE, 14, 29, 322, 18) - LTEXT "Existing files:", 212, 14, 61, 122, 14, SS_CENTERIMAGE - COMBOBOX 213, 140, 61, 196, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP - CONTROL "Also ask on read-only files", 214, "Button", BS_OWNERDRAW | WS_TABSTOP, 14, 81, 322, 14 - CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 96, 86, 18 - CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 96, 86, 18 + LTEXT "", 328, 14, 49, 322, 35, SS_NOPREFIX + LTEXT "Existing files:", 212, 14, 92, 122, 14, SS_CENTERIMAGE + COMBOBOX 213, 140, 92, 196, 100, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP + CONTROL "Also ask on read-only files", 214, "Button", BS_OWNERDRAW | WS_TABSTOP, 14, 112, 322, 14 + CONTROL "&Copy", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 87, 127, 86, 18 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 177, 127, 86, 18 END 103 DIALOGEX 0, 0, 460, 126 @@ -92,7 +97,7 @@ BEGIN CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 187, 106, 86, 18 END -104 DIALOGEX 0, 0, 360, 106 +104 DIALOGEX 0, 0, 360, 139 STYLE DS_SETFONT | DS_CENTER | WS_POPUP CAPTION "Warning" FONT 10, "Consolas" @@ -100,11 +105,16 @@ BEGIN LTEXT "", 230, 12, 16, 336, 12 LTEXT "", 231, 12, 33, 336, 12, SS_PATHELLIPSIS LTEXT "", 233, 12, 55, 1, 1 - LTEXT "", 234, 12, 81, 1, 1 - CONTROL "Remember choice", 232, "Button", BS_OWNERDRAW | WS_TABSTOP, 12, 57, 336, 18 - CONTROL "&Overwrite", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 42, 89, 110, 18 - CONTROL "&Skip", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 158, 89, 68, 18 - CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 232, 89, 86, 18 + LTEXT "New", 329, 12, 58, 65, 13 + RTEXT "", 330, 78, 58, 270, 13 + LTEXT "Existing", 331, 12, 72, 65, 13 + RTEXT "", 332, 78, 72, 270, 13 + LTEXT "", 333, 12, 88, 1, 1 + LTEXT "", 234, 12, 114, 1, 1 + CONTROL "Remember choice", 232, "Button", BS_OWNERDRAW | WS_TABSTOP, 12, 90, 336, 18 + CONTROL "&Overwrite", IDYES, "Button", BS_OWNERDRAW | WS_TABSTOP, 42, 122, 110, 18 + CONTROL "&Skip", IDNO, "Button", BS_OWNERDRAW | WS_TABSTOP, 158, 122, 68, 18 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 232, 122, 86, 18 END 105 DIALOGEX 0, 0, 310, 65 @@ -165,3 +175,12 @@ BEGIN CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 97, 86, 86, 18 CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 187, 86, 86, 18 END + +111 DIALOGEX 0, 0, 385, 220 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +FONT 9, "Consolas" +BEGIN + LTEXT "&Search commands or topics", 326, 12, 14, 361, 12 + FAR_EDIT(325, ES_MULTILINE, 12, 28, 361, 16) + LISTBOX 324, 12, 49, 361, 155, LBS_NOTIFY | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOINTEGRALHEIGHT | WS_TABSTOP +END diff --git a/src/files_command_history.inl b/src/files_command_history.inl new file mode 100644 index 0000000..3936e58 --- /dev/null +++ b/src/files_command_history.inl @@ -0,0 +1,103 @@ +constexpr std::array defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MAKEWORD(VK_F8,HOTKEYF_ALT)}; +auto commandHistoryKeys=defaultHistoryKeys; +constexpr size_t commandHistoryLimit=1000; + +bool validHistoryKeys(const std::array &keys) +{ + if(keys[0]==keys[1]) return false; + return std::all_of(keys.begin(),keys.end(),[](WORD binding) + { + const auto key=LOBYTE(binding), modifiers=HIBYTE(binding); + const bool letter=key>='A' && key<='Z'; + const bool function=key>=VK_F1 && key<=VK_F12; + if(!letter && !function) return false; + if(modifiers==HOTKEYF_CONTROL) return (letter && key!='C' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y') || function; + if(modifiers==HOTKEYF_ALT) return function && key!=VK_F1 && key!=VK_F2 && key!=VK_F4 && key!=VK_F10; + return false; + }); +} + +std::array optionHistoryKeys(HWND dialog) +{ + return {static_cast(SendDlgItemMessageW(dialog,321,HKM_GETHOTKEY,0,0)), + static_cast(SendDlgItemMessageW(dialog,323,HKM_GETHOTKEY,0,0))}; +} + +void setOptionHistoryKeys(HWND dialog,const std::array &keys) +{ + SendDlgItemMessageW(dialog,321,HKM_SETHOTKEY,keys[0],0); + SendDlgItemMessageW(dialog,323,HKM_SETHOTKEY,keys[1],0); +} + +void loadCommandHistory() +{ + const std::array keys{static_cast(preference(L"PreviousCommandKey",defaultHistoryKeys[0])), + static_cast(preference(L"CommandHistoryKey",defaultHistoryKeys[1]))}; + if(validHistoryKeys(keys)) commandHistoryKeys=keys; + + DWORD bytes{}; + if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,L"CommandHistory",RRF_RT_REG_BINARY,nullptr,nullptr,&bytes) + !=ERROR_SUCCESS || bytes>16*1024*1024 || bytes%sizeof(wchar_t)) return; + std::wstring data(bytes/sizeof(wchar_t),L'\0'); + if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,L"CommandHistory",RRF_RT_REG_BINARY,nullptr,data.data(),&bytes) + !=ERROR_SUCCESS) return; + size_t start{}; + while(startcommandHistoryLimit) terminalHistory.erase(terminalHistory.begin()); + std::wstring data; + for(const auto &entry:terminalHistory) + { + data.append(entry.date).push_back(L'\0'); + data.append(entry.command).push_back(L'\0'); + } + if(RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,L"CommandHistory",REG_BINARY,data.data(), + static_cast(data.size()*sizeof(wchar_t)))!=ERROR_SUCCESS) + setStatus(L"Could not save command history."); + refreshCommandHistory(); +} + +void recallCommand(size_t index) +{ + terminalHistoryIndex=index; + SetWindowTextW(terminalInput,index(data)->pt; + const auto clicked=WindowFromPoint(point); + const auto owner=GetWindow(dialog,GW_OWNER); + if(clicked!=dialog && !IsChild(dialog,clicked)) + { + POINT local=point; + RECT client{}; + GetClientRect(owner,&client); + ScreenToClient(owner,&local); + const bool ownerClient=clicked==owner || IsChild(owner,clicked); + if(!ownerClient || PtInRect(&client,local)) + { + const auto focusPanel=clicked==panels[0].list?panels[0].list: + clicked==panels[1].list?panels[1].list:panels[active].list; + if(PostMessageW(dialog,WM_CLOSE,reinterpret_cast(ownerClient?focusPanel:nullptr),0) + && ownerClient) return 1; + } + } + } + return CallNextHookEx(nullptr,code,message,data); +} + +std::wstring historyLower(std::wstring value) +{ + if(!value.empty()) CharLowerBuffW(value.data(),static_cast(value.size())); + return value; +} + +std::wstring_view commandTopicKeywords(const std::wstring &command) +{ + const auto start=command.find_first_not_of(L" \t"); + if(start==command.npos) return L""; + const auto end=command.find_first_of(L" \t",start); + auto tool=command.substr(start,end-start); + if(tool.ends_with(L".exe")) tool.resize(tool.size()-4); + const auto args=end==command.npos?L"":command.substr(end); + if(tool==L"ipconfig" && args.find(L"/flushdns")!=args.npos) + return L"network tools мережа dns flush clear cache очистити кеш"; + if(tool==L"nslookup" || tool==L"resolve-dnsname") + return L"network tools мережа dns lookup запит"; + if(tool==L"ping" || tool==L"tracert" || tool==L"ipconfig" || tool==L"test-netconnection" || + tool==L"netstat" || tool==L"curl" || tool==L"invoke-webrequest") + return L"network tools мережа з’єднання connectivity address адреса"; + if(tool==L"cls" || tool==L"clear" || tool==L"clear-host") + return L"terminal clear screen очистити екран консоль"; + if(tool==L"git") + { + const auto first=args.find_first_not_of(L" \t"); + const auto action=first==args.npos?L"":args.substr(first,args.find_first_of(L" \t",first)-first); + if(action==L"pull" || action==L"fetch" || action==L"update") + return L"git version control repository update fetch pull оновити репозиторій синхронізація"; + return L"git version control repository репозиторій контроль версій"; + } + return L""; +} + +void populateCommandHistory(HWND dialog) +{ + const auto search=GetDlgItem(dialog,historySearch); + std::wstring query(GetWindowTextLengthW(search)+1,L'\0'); + query.resize(GetWindowTextW(search,query.data(),static_cast(query.size()))); + query=historyLower(std::move(query)); + std::wistringstream stream(query); + std::vector words; + for(std::wstring word;stream>>word;) words.push_back(word); + + const auto list=GetDlgItem(dialog,historyList); + SendMessageW(list,WM_SETREDRAW,FALSE,0); + SendMessageW(list,LB_RESETCONTENT,0,0); + const auto add=[&](const std::wstring &label,LPARAM index) + { + const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast(label.c_str())); + if(row>=0) SendMessageW(list,LB_SETITEMDATA,row,index); + return row; + }; + std::array,2> matches; + std::set seen; + for(size_t index=terminalHistory.size();index-- > 0;) + { + const auto &entry=terminalHistory[index]; + if(!seen.insert(entry.command).second) continue; + const auto command=historyLower(entry.command); + const auto containsAll=[&](const std::wstring &text) + { + return std::all_of(words.begin(),words.end(),[&](const auto &word){return text.find(word)!=text.npos;}); + }; + if(containsAll(command+L" "+entry.date)) + { + matches[0].push_back(index); + continue; + } + const auto keywords=commandTopicKeywords(command); + if(!keywords.empty() && containsAll(command+L" "+entry.date+L" "+std::wstring(keywords))) + matches[1].push_back(index); + } + LRESULT selected=LB_ERR; + for(const auto &group:matches) + { + std::wstring lastDate; + bool first=true; + for(auto match=group.rbegin();match!=group.rend();++match) + { + const auto index=*match; + const auto &entry=terminalHistory[index]; + const auto &date=entry.date; + if(first || date!=lastDate) add(date,-1); + first=false; + lastDate=date; + const auto row=add(entry.command,index); + if(row>=0 && (words.empty() || selected==LB_ERR)) selected=row; + } + } + if(selected==LB_ERR) add(words.empty()?L"No commands yet":L"No matching commands",-2); + else SendMessageW(list,LB_SETCURSEL,selected,0); + SendMessageW(list,WM_SETREDRAW,TRUE,0); + InvalidateRect(list,nullptr,TRUE); +} + +LRESULT CALLBACK historySearchKeys(HWND search,UINT message,WPARAM key,LPARAM flags,UINT_PTR,DWORD_PTR) +{ + if(message==WM_GETDLGCODE) + { + const auto code=DefSubclassProc(search,message,key,flags); + if(key==VK_RETURN || key==VK_TAB || key==VK_ESCAPE) return code&~DLGC_WANTALLKEYS; + return code|DLGC_WANTARROWS; + } + if(message==WM_KEYDOWN && (key==VK_UP || key==VK_DOWN)) + { + const auto list=GetDlgItem(GetParent(search),historyList); + SetFocus(list); + SendMessageW(list,message,key,flags); + return 0; + } + return DefSubclassProc(search,message,key,flags); +} + + +int historyRowInset(UINT dpi) +{ + return std::max(MulDiv(4,dpi,96),dialogFrameMetrics(dpi).inner)+dialogRowTextInset(cellWidth); +} + +LRESULT CALLBACK historyListScroll(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +{ + if(message==LB_GETTOPINDEX || message==WM_NCDESTROY) + return DefSubclassProc(list,message,wp,lp); + const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0); + const auto result=scrollList(list,message,wp,lp); + if(top!=SendMessageW(list,LB_GETTOPINDEX,0,0)) + InvalidateRect(GetParent(list),nullptr,FALSE); + return result; +} + +void sizeCommandHistory(HWND dialog,HWND list,bool movingOwner=false) +{ + const auto owner=GetWindow(dialog,GW_OWNER); + RECT ownerBounds{}; + if(!GetWindowRect(owner,&ownerBounds) || IsIconic(owner)) return; + MONITORINFO monitor{sizeof(monitor)}; + if(!GetMonitorInfoW(MonitorFromWindow(owner,MONITOR_DEFAULTTONEAREST),&monitor)) return; + RECT area{}; + if(!IntersectRect(&area,&ownerBounds,&monitor.rcWork)) area=monitor.rcWork; + + const auto dc=GetDC(list); + if(!dc) return; + const auto previous=SelectObject(dc,mono); + LONG longest{}; + for(const auto &entry:terminalHistory) + { + SIZE size{}; + if(GetTextExtentPoint32W(dc,entry.command.c_str(),static_cast(entry.command.size()),&size)) + longest=std::max(longest,size.cx); + } + SelectObject(dc,previous); + ReleaseDC(list,dc); + + const auto dpi=GetDpiForWindow(dialog); + const auto frame=dialogFrameMetrics(dpi); + const int inset=frame.content(); + const int top=dialogListInset(frame,textHeight); + const int gap=MulDiv(4,dpi,96); + const int listTop=top+2*textHeight+2*gap; + const LONG desired=std::max(MulDiv(320,dpi,96), + longest+2*cellWidth+2*historyRowInset(dpi)+GetSystemMetricsForDpi(SM_CXVSCROLL,dpi))+2*inset; + const auto target=std::min(desired,area.right-area.left); + const auto rows=std::max(1,SendMessageW(list,LB_GETCOUNT,0,0)); + RECT listWindow{},listClient{}; + GetWindowRect(list,&listWindow); + GetClientRect(list,&listClient); + const auto listBorder=listWindow.bottom-listWindow.top-listClient.bottom; + const auto height=std::min(listTop+rows*textHeight+listBorder+inset, + area.bottom-area.top); + const auto left=std::clamp((ownerBounds.left+ownerBounds.right-target)/2,area.left,area.right-target); + const auto y=std::clamp((ownerBounds.top+ownerBounds.bottom-height)/2,area.top,area.bottom-height); + RECT current{}; + if(movingOwner && GetWindowRect(dialog,¤t) && + current.right-current.left==target && current.bottom-current.top==height) + { + if(current.left!=left || current.top!=y) + SetWindowPos(dialog,nullptr,left,y,0,0,SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE); + return; + } + SetWindowPos(dialog,nullptr,left,y,target,height,SWP_NOZORDER|SWP_NOACTIVATE); + const auto place=[&](HWND control,int rowTop,int rowHeight) + { + SetWindowPos(control,nullptr,inset,rowTop,std::max(1L,target-2*inset),rowHeight, + SWP_NOZORDER|SWP_NOACTIVATE); + }; + place(GetDlgItem(dialog,historySearchLabel),top,textHeight); + place(GetDlgItem(dialog,historySearch),top+textHeight+gap,textHeight); + SetWindowPos(list,nullptr,inset,listTop,std::max(1L,target-2*inset-5), + std::max(1L,height-listTop-inset),SWP_NOZORDER|SWP_NOACTIVATE); + GetClientRect(list,&listClient); + if(rows*textHeight<=listClient.bottom) SendMessageW(list,LB_SETTOPINDEX,0,0); + InvalidateRect(dialog,nullptr,FALSE); +} + +void layoutOpenCommandHistory(bool movingOwner=false) +{ + if(commandHistoryWindow) + sizeCommandHistory(commandHistoryWindow,GetDlgItem(commandHistoryWindow,historyList),movingOwner); +} + +INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_INITDIALOG) + { + prepareCopyDialog(dialog); + const auto list=GetDlgItem(dialog,historyList); + SetWindowSubclass(list,historyListScroll,1,0); + SendMessageW(list,WM_SETFONT,reinterpret_cast(mono),TRUE); + SendMessageW(list,LB_SETITEMHEIGHT,0,std::max(1,textHeight)); + const auto search=GetDlgItem(dialog,historySearch); + SendDlgItemMessageW(dialog,historySearchLabel,WM_SETFONT,reinterpret_cast(mono),TRUE); + SetWindowSubclass(search,historySearchKeys,1,0); + populateCommandHistory(dialog); + sizeCommandHistory(dialog,list); + SetFocus(search); + return FALSE; + } + if(message==WM_COMMAND && LOWORD(wp)==historySearch && HIWORD(wp)==EN_CHANGE) + { + populateCommandHistory(dialog); + sizeCommandHistory(dialog,GetDlgItem(dialog,historyList)); + return TRUE; + } + if(message==WM_NCDESTROY && commandHistoryWindow==dialog) + { + if(historyMouseHook) UnhookWindowsHookEx(historyMouseHook); + historyMouseHook=nullptr; + commandHistoryWindow=nullptr; + } + if(message==WM_CTLCOLORLISTBOX || message==WM_CTLCOLOREDIT) + { + const auto dc=reinterpret_cast(wp); + const bool search=message==WM_CTLCOLOREDIT; + SetTextColor(dc,search?RGB(0,0,0):colors[Text]); + const auto background=search?historySearchSurface:colors[Dialog]; + SetBkColor(dc,background); + if(search) SetDCBrushColor(dc,background); + return reinterpret_cast(search?GetStockObject(DC_BRUSH):teal); + } + if(message!=WM_DRAWITEM || wp!=historyList) + if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" History ",false,{},true, + GetDlgItem(dialog,historyList))) + return painted; + if(message==WM_DRAWITEM && wp==historyList) + { + const auto &item=*reinterpret_cast(lp); + if(item.itemID==UINT(-1)) return TRUE; + const auto count=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0); + if(count<0) return TRUE; + std::wstring label(static_cast(count)+1,L'\0'); + SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast(label.data())); + label.resize(count); + const bool selected=(item.itemState&ODS_SELECTED)!=0 && item.itemData(-1)) + { + auto bounds=item.rcItem; + InflateRect(&bounds,-historyRowInset(GetDpiForWindow(dialog)),0); + const auto saved=SaveDC(item.hDC); + SelectObject(item.hDC,mono); + SetBkColor(item.hDC,background); + SetTextColor(item.hDC,ink); + ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&bounds,nullptr,0,nullptr); + const auto middle=(bounds.top+bounds.bottom)/2; + RECT rule{bounds.left,middle,bounds.right,middle+1}; + SetBkColor(item.hDC,ink); + ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&rule,nullptr,0,nullptr); + SIZE size{}; + GetTextExtentPoint32W(item.hDC,label.c_str(),static_cast(label.size()),&size); + const auto left=(bounds.left+bounds.right-size.cx)/2; + RECT caption{left-cellWidth,bounds.top,left+size.cx+cellWidth,bounds.bottom}; + SetBkColor(item.hDC,background); + ExtTextOutW(item.hDC,left,middle-size.cy/2,ETO_OPAQUE,&caption,label.c_str(), + static_cast(label.size()),nullptr); + RestoreDC(item.hDC,saved); + } + else paintDialogListRow(item.hDC,item.rcItem,label,mono,ink,background, + historyRowInset(GetDpiForWindow(dialog)),DT_END_ELLIPSIS); + if(selected && (item.itemState&ODS_FOCUS)) DrawFocusRect(item.hDC,&item.rcItem); + return TRUE; + } + if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) + { + const auto owner=GetWindow(dialog,GW_OWNER); + const auto focusPanel=message==WM_CLOSE?reinterpret_cast(wp):panels[active].list; + DestroyWindow(dialog); + if(focusPanel && IsWindow(owner) && !IsIconic(owner)) + { + SetActiveWindow(owner); + SetFocus(focusPanel); + } + return TRUE; + } + if(message==WM_COMMAND && (LOWORD(wp)==IDOK || (LOWORD(wp)==historyList && HIWORD(wp)==LBN_DBLCLK))) + { + const auto row=SendDlgItemMessageW(dialog,historyList,LB_GETCURSEL,0,0); + const auto index=SendDlgItemMessageW(dialog,historyList,LB_GETITEMDATA,row,0); + if(index>=0 && static_cast(index)(index)); + } + return TRUE; + } + return FALSE; +} + +void refreshCommandHistory() +{ + if(commandHistoryWindow) populateCommandHistory(commandHistoryWindow); + layoutOpenCommandHistory(); +} + +void showCommandHistory(HWND owner) +{ + if(!commandHistoryWindow) + commandHistoryWindow=CreateDialogParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(111),owner,commandHistoryDialog,0); + if(!commandHistoryWindow) return; + if(!historyMouseHook) + historyMouseHook=SetWindowsHookExW(WH_MOUSE_LL,dismissHistoryOnOutsideClick,GetModuleHandleW(nullptr),0); + ShowWindow(commandHistoryWindow,SW_SHOW); + SetActiveWindow(commandHistoryWindow); + SetFocus(GetDlgItem(commandHistoryWindow,historySearch)); +} diff --git a/src/files_dialog_input.inl b/src/files_dialog_input.inl new file mode 100644 index 0000000..5dce923 --- /dev/null +++ b/src/files_dialog_input.inl @@ -0,0 +1,128 @@ +HWND activeFilesDialog{}; +HHOOK filesDialogMouseHook{}; + +bool filesMouseDown(UINT message) +{ + return message==WM_LBUTTONDOWN || message==WM_RBUTTONDOWN || + message==WM_MBUTTONDOWN || message==WM_XBUTTONDOWN; +} + +LRESULT CALLBACK filesDialogMouse(int code,WPARAM message,LPARAM data) +{ + const auto dialog=activeFilesDialog; + if(code==HC_ACTION && dialog && IsWindowVisible(dialog) && filesMouseDown(static_cast(message))) + { + const auto point=reinterpret_cast(data)->pt; + const auto clicked=WindowFromPoint(point); + const auto root=GetAncestor(dialog,GA_ROOTOWNER); + if(clicked!=dialog && !IsChild(dialog,clicked)) + { + RECT client{}; + POINT local=point; + GetClientRect(root,&client); + ScreenToClient(root,&local); + if(clicked!=root || PtInRect(&client,local)) + { + const bool internal=clicked==root || IsChild(root,clicked) || + (clicked && GetAncestor(clicked,GA_ROOTOWNER)==root); + if(PostMessageW(dialog,WM_COMMAND,IDCANCEL,0) && internal) return 1; + } + } + } + return CallNextHookEx(nullptr,code,message,data); +} + +struct FilesDialogInput +{ + HWND previous=activeFilesDialog; + explicit FilesDialogInput(HWND dialog) + { + activeFilesDialog=dialog; + if(!filesDialogMouseHook) + filesDialogMouseHook=SetWindowsHookExW(WH_MOUSE_LL,filesDialogMouse,GetModuleHandleW(nullptr),0); + } + + ~FilesDialogInput() + { + activeFilesDialog=previous; + if(!previous && filesDialogMouseHook) + { + UnhookWindowsHookEx(filesDialogMouseHook); + filesDialogMouseHook=nullptr; + } + } +}; + +bool filesDialogHandlesMessage(HWND dialog,MSG &message) +{ + if(message.hwnd==dialog || IsChild(dialog,message.hwnd)) return IsDialogMessageW(dialog,&message); + if(!message.hwnd || GetAncestor(message.hwnd,GA_ROOTOWNER)!=GetAncestor(dialog,GA_ROOTOWNER)) return false; + const bool input=(message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST) || + (message.message>=WM_MOUSEFIRST && message.message<=WM_MOUSELAST) || + message.message==WM_CONTEXTMENU; + if(input && message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE) + PostMessageW(dialog,WM_COMMAND,IDCANCEL,0); + return input; +} + +struct FilesDialogResult +{ + DLGPROC procedure; + LPARAM argument; + INT_PTR result=IDCANCEL; + bool finished=false; +}; + +constexpr wchar_t filesDialogResultProperty[]=L"KSwitcher.Files.DialogResult"; + +INT_PTR CALLBACK filesDialogProcedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + auto *result=reinterpret_cast(GetPropW(dialog,filesDialogResultProperty)); + if(message==WM_INITDIALOG) + { + result=reinterpret_cast(lp); + if(!SetPropW(dialog,filesDialogResultProperty,result)) return FALSE; + lp=result->argument; + } + if(!result) return FALSE; + const auto handled=result->procedure(dialog,message,wp,lp); + if(message==WM_NCDESTROY) RemovePropW(dialog,filesDialogResultProperty); + return handled; +} + +void finishFilesDialog(HWND dialog,INT_PTR answer) +{ + auto *result=reinterpret_cast(GetPropW(dialog,filesDialogResultProperty)); + if(!result) return; + result->result=answer; + result->finished=true; + ShowWindow(dialog,SW_HIDE); +} + +INT_PTR runFilesDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument) +{ + FilesDialogResult result{procedure,argument}; + const auto dialog=CreateDialogParamW(instance,resource,owner,filesDialogProcedure, + reinterpret_cast(&result)); + if(!dialog) return -1; + GetWindowRect(GetAncestor(owner,GA_ROOTOWNER),&previousOwnerBounds); + FilesDialogInput input(dialog); + ShowWindow(dialog,SW_SHOW); + SetActiveWindow(dialog); + MSG message{}; + while(!result.finished && IsWindow(dialog)) + { + const auto status=GetMessageW(&message,nullptr,0,0); + if(status<=0) + { + if(status==0) PostQuitMessage(static_cast(message.wParam)); + break; + } + if(filesDialogHandlesMessage(dialog,message)) continue; + TranslateMessage(&message); + DispatchMessageW(&message); + } + if(IsWindow(dialog)) DestroyWindow(dialog); + if(IsWindow(owner) && !IsIconic(GetAncestor(owner,GA_ROOTOWNER))) SetActiveWindow(owner); + return result.result; +} diff --git a/src/files_folder_shortcuts.inl b/src/files_folder_shortcuts.inl index b6ea0f9..0d4a7d3 100644 --- a/src/files_folder_shortcuts.inl +++ b/src/files_folder_shortcuts.inl @@ -104,7 +104,7 @@ INT_PTR CALLBACK folderShortcutEditDialog(HWND dialog,UINT message,WPARAM wp,LPA } if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) { - EndDialog(dialog,IDCANCEL); + finishFilesDialog(dialog,IDCANCEL); return TRUE; } if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE; @@ -139,13 +139,13 @@ INT_PTR CALLBACK folderShortcutEditDialog(HWND dialog,UINT message,WPARAM wp,LPA return TRUE; } folderShortcuts=std::move(updated); - EndDialog(dialog,IDOK); + finishFilesDialog(dialog,IDOK); return TRUE; } bool editFolderShortcut(HWND owner,FolderShortcutEdit &edit) { - return DialogBoxParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(110),owner, + return runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(110),owner, folderShortcutEditDialog,reinterpret_cast(&edit))==IDOK; } @@ -186,7 +186,6 @@ struct FolderShortcutView std::vector digits; int rowHeight{}; Panel *panel{}; - HHOOK mouseHook{}; }; void layoutQuickFolders(HWND dialog,FolderShortcutView &view,int selection) @@ -275,26 +274,6 @@ LRESULT CALLBACK quickFolderKeys(HWND list,UINT message,WPARAM key,LPARAM flags, return scrollList(list,message,key,flags); } -HWND quickFolderWindow{}; - -bool dismissQuickFoldersAt(HWND dialog,POINT point) -{ - RECT bounds{}; - if(!dialog || !IsWindowVisible(dialog) || !IsWindowEnabled(dialog) || - GetForegroundWindow()!=dialog || !GetWindowRect(dialog,&bounds) || PtInRect(&bounds,point)) - return false; - return PostMessageW(dialog,WM_COMMAND,IDCANCEL,0)!=FALSE; -} - -LRESULT CALLBACK quickFolderMouse(int code,WPARAM message,LPARAM data) -{ - if(code==HC_ACTION && (message==WM_LBUTTONDOWN || message==WM_RBUTTONDOWN || - message==WM_MBUTTONDOWN || message==WM_XBUTTONDOWN) && - dismissQuickFoldersAt(quickFolderWindow,reinterpret_cast(data)->pt)) - return 1; - return CallNextHookEx(nullptr,code,message,data); -} - INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) { if(message==WM_INITDIALOG) @@ -305,8 +284,6 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) layoutQuickFolders(dialog,view,0); const auto list=GetDlgItem(dialog,shortcutList); SetWindowSubclass(list,quickFolderKeys,1,0); - quickFolderWindow=dialog; - view.mouseHook=SetWindowsHookExW(WH_MOUSE_LL,quickFolderMouse,GetModuleHandleW(nullptr),0); SetFocus(list); return FALSE; } @@ -314,8 +291,6 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) if(!view) return FALSE; if(message==WM_DESTROY) { - if(view->mouseHook) UnhookWindowsHookEx(view->mouseHook); - quickFolderWindow=nullptr; return FALSE; } if(message==WM_PAINT) @@ -347,7 +322,7 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) } if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) { - EndDialog(dialog,IDCANCEL); + finishFilesDialog(dialog,IDCANCEL); return TRUE; } if(message!=WM_COMMAND) return FALSE; @@ -408,12 +383,12 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) return TRUE; } folderShortcuts=std::move(updated); - if(folderShortcuts[view->digit].empty()) EndDialog(dialog,IDCANCEL); + if(folderShortcuts[view->digit].empty()) finishFilesDialog(dialog,IDCANCEL); else layoutQuickFolders(dialog,*view,static_cast(row)); return TRUE; } view->chosen=group[row]; - EndDialog(dialog,IDOK); + finishFilesDialog(dialog,IDOK); return TRUE; } @@ -441,7 +416,7 @@ void showFolderShortcuts(Panel &panel,int digit) } FolderShortcutView view{digit}; view.panel=&panel; - const auto result=DialogBoxParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(109),GetParent(panel.list), + const auto result=runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(109),GetParent(panel.list), quickFolderDialog,reinterpret_cast(&view)); SetFocus(panel.list); if(result==IDOK && view.chosen) openFolderShortcut(panel,*view.chosen); diff --git a/src/files_main.cpp b/src/files_main.cpp index 3f79861..c81611e 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -270,7 +270,8 @@ HWND terminalInput{},terminalOutput{},terminalPrompt{}; constexpr UINT_PTR terminalTimer=2; bool terminalVisible{}; int terminalRows{}; -std::vector terminalHistory; +struct CommandEntry { std::wstring date, command; }; +std::vector terminalHistory; size_t terminalHistoryIndex{}; constexpr UINT_PTR transferHighlightTimer=1; unsigned transferHighlightPhase{}; @@ -369,6 +370,9 @@ void savePreference(const wchar_t *name, DWORD value) } #include "files_styles.inl" +void setStatus(const std::wstring &message); +void refreshCommandHistory(); +#include "files_command_history.inl" constexpr const wchar_t *panelPathKeys[]{L"LeftPath",L"RightPath"}; constexpr const wchar_t *panelCursorKeys[]{L"LeftCursor",L"RightCursor"}; @@ -620,7 +624,7 @@ int dialogRowTextInset(int characterWidth,DialogFramePadding padding=dialogFrame } void paintDialogListRow(HDC dc,RECT bounds,std::wstring_view label,HFONT font, - COLORREF foreground,COLORREF background,int inset) + COLORREF foreground,COLORREF background,int inset,UINT ellipsis=DT_PATH_ELLIPSIS) { const auto saved=SaveDC(dc); SetBkColor(dc,background); @@ -631,7 +635,7 @@ void paintDialogListRow(HDC dc,RECT bounds,std::wstring_view label,HFONT font, InflateRect(&bounds,-inset,0); if(bounds.right>bounds.left) DrawTextW(dc,label.data(),static_cast(label.size()),&bounds, - DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|DT_PATH_ELLIPSIS); + DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|ellipsis); if(saved) RestoreDC(dc,saved); } @@ -856,6 +860,17 @@ void updateTerminalOutput() } LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) { + if(message==WM_CHAR && wp==VK_ESCAPE) + { + recallCommand(terminalHistory.size()); + return 0; + } + if((message==WM_CHAR && wp==22) || + (message==WM_KEYDOWN && wp==VK_INSERT && (GetKeyState(VK_SHIFT)&0x8000))) + { + SendMessageW(input,WM_PASTE,0,0); + return 0; + } // The edit control receives Ctrl+Backspace as DEL. if(message==WM_CHAR && wp==127) { @@ -884,11 +899,7 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U std::wstring value(GetWindowTextLengthW(input)+1,L'\0'); value.resize(GetWindowTextW(input,value.data(),static_cast(value.size()))); if(!terminal.write(value+L"\r")) { setStatus(L"Could not send PowerShell input."); return 0; } - if(!value.empty() && (terminalHistory.empty() || terminalHistory.back()!=value)) - { - if(terminalHistory.size()==100) terminalHistory.erase(terminalHistory.begin()); - terminalHistory.push_back(value); - } + if(value.find_first_not_of(L" \t\r\n")!=std::wstring::npos) rememberCommand(value); terminalHistoryIndex=terminalHistory.size(); SetWindowTextW(input,L""); return 0; @@ -914,11 +925,8 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U } if(message==WM_KEYDOWN && (wp==VK_UP || wp==VK_DOWN)) { - if(wp==VK_UP && terminalHistoryIndex) --terminalHistoryIndex; - if(wp==VK_DOWN && terminalHistoryIndex(mono),FALSE); - const auto margin=MulDiv(2,GetDpiForWindow(field),96); - SendMessageW(field,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,MAKELPARAM(margin,margin)); - if(!(GetWindowLongPtrW(field,GWL_STYLE)&ES_MULTILINE)) return; - - // A single-line Edit centers its own text. Copy uses a multiline Edit for - // its formatting rectangle and keeps its existing dialog key handling. RECT edit{}; GetClientRect(field,&edit); if(const auto dc=GetDC(field)) @@ -1496,6 +1500,25 @@ void prepareDialogEdit(HWND field) SendMessageW(field,EM_SETRECTNP,0,reinterpret_cast(&edit)); } +LRESULT CALLBACK dialogEditLayout(HWND field,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +{ + const auto result=DefSubclassProc(field,message,wp,lp); + if(message==WM_SIZE || message==WM_SETFONT) centerDialogEditText(field); + return result; +} + +void prepareDialogEdit(HWND field) +{ + SendMessageW(field,WM_SETFONT,reinterpret_cast(mono),FALSE); + const auto margin=MulDiv(2,GetDpiForWindow(field),96); + SendMessageW(field,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,MAKELPARAM(margin,margin)); + if(GetWindowLongPtrW(field,GWL_STYLE)&ES_MULTILINE) + { + SetWindowSubclass(field,dialogEditLayout,1,0); + centerDialogEditText(field); + } +} + void prepareCopyDialog(HWND dialog) { installDialogButtonKeys(dialog); @@ -1554,10 +1577,10 @@ LONG dialogDividerY(HWND dialog,int id) if(id==214) { const auto combo=dialogControlBounds(dialog,213); - const auto name=dialogControlBounds(dialog,211); - return bounds.bottom+std::max(0L,(combo.top-name.bottom-1)/2); + const auto validation=dialogControlBounds(dialog,328); + return bounds.bottom+std::max(0L,(combo.top-validation.bottom-1)/2); } - if(id==213) return (dialogControlBounds(dialog,211).bottom+bounds.top-1)/2; + if(id==213) return (dialogControlBounds(dialog,328).bottom+bounds.top-1)/2; return bounds.top-4; } @@ -1619,11 +1642,12 @@ void paintDialogButton(const DRAWITEMSTRUCT &item,COLORREF surface,COLORREF fore } INT_PTR paintCopyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp, - const wchar_t *caption, bool warning, std::initializer_list dividers) + const wchar_t *caption, bool warning, std::initializer_list dividers, bool useDialogPalette=false, + HWND scrollListControl=nullptr) { - const auto foreground=warning?RGB(255,255,255):RGB(0,0,0); - const auto surface=warning?RGB(128,0,0):RGB(192,192,192); - const auto brush=warning?warningBrush:static_cast(GetStockObject(LTGRAY_BRUSH)); + const auto foreground=useDialogPalette?colors[Text]:warning?RGB(255,255,255):RGB(0,0,0); + const auto surface=useDialogPalette?colors[Dialog]:warning?RGB(128,0,0):RGB(192,192,192); + const auto brush=useDialogPalette?teal:warning?warningBrush:static_cast(GetStockObject(LTGRAY_BRUSH)); if(message==WM_CTLCOLORDLG) return reinterpret_cast(brush); if(message==WM_CTLCOLORSTATIC || message==WM_CTLCOLOREDIT || message==WM_CTLCOLORBTN) { @@ -1641,7 +1665,8 @@ INT_PTR paintCopyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp, RECT bounds{}; GetClientRect(dialog,&bounds); const auto client=bounds; - const auto black=static_cast(GetStockObject(warning?WHITE_BRUSH:BLACK_BRUSH)); + const auto black=static_cast(GetStockObject(useDialogPalette?DC_BRUSH:warning?WHITE_BRUSH:BLACK_BRUSH)); + if(useDialogPalette) SetDCBrushColor(dc,foreground); bounds=paintDialogFrame(dc,client,dialogFrameMetrics(GetDpiForWindow(dialog)),brush,black); for(const auto control:dividers) { @@ -1650,6 +1675,7 @@ INT_PTR paintCopyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp, FillRect(dc,÷r,black); } paintDialogFrameCaptions(dc,client,bounds,caption,brush,foreground,mono); + if(scrollListControl) paintScrollPosition(dialog,dc,scrollListControl,surface); EndPaint(dialog,&paint); return TRUE; } @@ -1744,6 +1770,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) SendDlgItemMessageW(dialog,pathField,EM_SETREADONLY,!single && !request.move,0); if(request.move) SetDlgItemTextW(dialog,IDOK,L"&Rename"); layoutDialogButtons(dialog,214,{IDOK,IDCANCEL}); + SendDlgItemMessageW(dialog,328,WM_SETFONT,reinterpret_cast(mono),FALSE); SendDlgItemMessageW(dialog,summary,WM_SETFONT,reinterpret_cast(mono),FALSE); SendDlgItemMessageW(dialog,conflicts,WM_SETFONT,reinterpret_cast(mono),FALSE); for(const auto control:{213,214}) @@ -1765,7 +1792,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) } if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) { - EndDialog(dialog,IDCANCEL); + finishFilesDialog(dialog,IDCANCEL); return TRUE; } if(message!=WM_COMMAND) return FALSE; @@ -1781,7 +1808,17 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) InvalidateRect(GetDlgItem(dialog,213),nullptr,FALSE); return FALSE; } + if(LOWORD(wp)==pathField && HIWORD(wp)==EN_CHANGE) + { + SetDlgItemTextW(dialog,328,L""); + return TRUE; + } if(LOWORD(wp)!=IDOK) return FALSE; + const auto showError=[&](const wchar_t *message) + { + SetDlgItemTextW(dialog,328,message); + SetFocus(GetDlgItem(dialog,pathField)); + }; try { if(request.move) @@ -1801,9 +1838,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) (!directoryExists(peer,target) && (request.sources.size()!=1 || !target.has_filename() || !directoryExists(peer,target.parent_path())))) { - MessageBoxW(dialog,L"Enter an existing destination folder, or a new name for one item.", - L"Rename/Move",MB_OK|MB_ICONWARNING); - SetFocus(field); + showError(L"Enter an existing destination folder, or a new name for one item."); return TRUE; } request.destinationPeer=peer; @@ -1829,8 +1864,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) name.find_first_of(L"<>:\"/\\|?*")!=name.npos || std::any_of(name.begin(),name.end(),[](wchar_t ch){return ch<32;})) { - MessageBoxW(dialog,L"Enter a valid name for the copy.",L"Copy",MB_OK|MB_ICONWARNING); - SetFocus(field); + showError(L"Enter a valid name for the copy."); return TRUE; } if(CompareStringOrdinal(name.c_str(),-1,request.sources.front().filename().c_str(),-1,TRUE)!=CSTR_EQUAL) @@ -1843,7 +1877,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) const auto peer=request.move || request.newName.empty()?request.destinationPeer:request.sourcePeer; if(!directoryExists(peer,destination)) { - MessageBoxW(dialog,L"The destination folder is unavailable.",L"Copy",MB_OK|MB_ICONWARNING); + showError(L"The destination folder is unavailable."); return TRUE; } const bool sameHost=(!peer && !request.sourcePeer) || @@ -1853,22 +1887,21 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) fs::equivalent(destination,sourceDirectory,error)); if(request.newName.empty() && sameFolder) { - MessageBoxW(dialog,L"Open a different folder in the other panel, or enter a new name for a single item.", - request.move?L"Rename/Move":L"Copy",MB_OK|MB_ICONWARNING); + showError(L"Open a different folder in the other panel, or enter a new name for a single item."); return TRUE; } const auto mode=SendDlgItemMessageW(dialog,213,CB_GETCURSEL,0,0); if(mode!=CB_ERR) request.conflictMode=static_cast( request.move && mode==static_cast(ConflictMode::append)?static_cast(ConflictMode::newer):mode); - EndDialog(dialog,IDOK); + finishFilesDialog(dialog,IDOK); } catch(const std::system_error &e) { - MessageBoxW(dialog,fileError(e).c_str(),L"Destination unavailable",MB_OK|MB_ICONWARNING); + showError(fileError(e).c_str()); } catch(const std::exception &) { - MessageBoxW(dialog,L"The remote destination is unavailable.",L"Copy",MB_OK|MB_ICONWARNING); + showError(L"The remote destination is unavailable."); } return TRUE; } @@ -1890,7 +1923,6 @@ struct CopyProgress }; bool copyInProgress{}; CopyProgress *activeCopy{}; -RECT previousOwnerBounds{}; struct OwnedWindowMove { @@ -2010,7 +2042,7 @@ INT_PTR CALLBACK cancelOperationDialog(HWND window,UINT message,WPARAM wp,LPARAM if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDYES || LOWORD(wp)==IDNO || LOWORD(wp)==IDCANCEL))) { - EndDialog(window,message==WM_COMMAND && LOWORD(wp)==IDYES?IDYES:IDNO); + finishFilesDialog(window,message==WM_COMMAND && LOWORD(wp)==IDYES?IDYES:IDNO); return TRUE; } return FALSE; @@ -2020,7 +2052,7 @@ bool confirmOperationCancellation(HWND owner,const wchar_t *question) { const auto previous=warningBrush; if(!previous) warningBrush=CreateSolidBrush(RGB(128,0,0)); - const auto answer=DialogBoxParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(105),owner, + const auto answer=runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(105),owner, cancelOperationDialog,reinterpret_cast(question)); if(!previous) { @@ -2134,9 +2166,28 @@ struct WarningPrompt const wchar_t *details; const wchar_t *accept; const wchar_t *decline; + FileInfo incoming,existing; bool remember{}; }; +std::wstring conflictFileDetails(const FileInfo &file) +{ + const FILETIME stamp{static_cast(file.modified),static_cast(file.modified>>32)}; + SYSTEMTIME utc{},local{}; + wchar_t date[32]=L"—"; + if(file.modified && FileTimeToSystemTime(&stamp,&utc) && SystemTimeToTzSpecificLocalTime(nullptr,&utc,&local)) + swprintf_s(date,L"%04u-%02u-%02u %02u:%02u:%02u",unsigned(local.wYear), + unsigned(local.wMonth),unsigned(local.wDay),unsigned(local.wHour), + unsigned(local.wMinute),unsigned(local.wSecond)); + auto bytes=std::to_wstring(file.size); + for(auto position=bytes.size();position>3;) + { + position-=3; + bytes.insert(position,1,L'\u202F'); + } + return bytes+L" B "+date; +} + LRESULT CALLBACK warningButtonKeys(HWND button,UINT message,WPARAM wp,LPARAM lp, UINT_PTR,DWORD_PTR index) { @@ -2173,7 +2224,7 @@ INT_PTR CALLBACK warningDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) if(item.itemState&ODS_FOCUS) DrawFocusRect(item.hDC,&item.rcItem); return TRUE; } - if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Warning ",true,{233,234})) + if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Warning ",true,{233,333,234})) return painted; if(message==WM_INITDIALOG) { @@ -2183,11 +2234,13 @@ INT_PTR CALLBACK warningDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) const auto &warning=*reinterpret_cast(lp); SetDlgItemTextW(window,230,warning.message); SetDlgItemTextW(window,231,warning.details); + SetDlgItemTextW(window,330,conflictFileDetails(warning.incoming).c_str()); + SetDlgItemTextW(window,332,conflictFileDetails(warning.existing).c_str()); SetDlgItemTextW(window,IDYES,warning.accept); SetDlgItemTextW(window,IDNO,warning.decline); - for(const auto control:{230,231,232}) + for(const auto control:{230,231,232,329,330,331,332}) SendDlgItemMessageW(window,control,WM_SETFONT,reinterpret_cast(mono),FALSE); - centerDialogRow(window,233,234,{232}); + centerDialogRow(window,333,234,{232}); layoutDialogButtons(window,234,{IDYES,IDNO,IDCANCEL}); SendMessageW(window,DM_SETDEFID,IDNO,0); constexpr int buttons[]{IDYES,IDNO,IDCANCEL}; @@ -2199,7 +2252,7 @@ INT_PTR CALLBACK warningDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) } if(message==WM_CLOSE) { - EndDialog(window,IDCANCEL); + finishFilesDialog(window,IDCANCEL); return TRUE; } if(message==WM_COMMAND && LOWORD(wp)==232 && HIWORD(wp)==BN_CLICKED) @@ -2212,7 +2265,7 @@ INT_PTR CALLBACK warningDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) if(message==WM_COMMAND && (LOWORD(wp)==IDYES || LOWORD(wp)==IDNO || LOWORD(wp)==IDCANCEL)) { const auto choice=LOWORD(wp); - EndDialog(window,choice); + finishFilesDialog(window,choice); return TRUE; } return FALSE; @@ -2235,7 +2288,7 @@ bool pumpCopy(CopyProgress &progress) ((message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST) || (message.message>=WM_MOUSEFIRST && message.message<=WM_MOUSELAST))) { - if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE) + if(filesMouseDown(message.message) || (message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE)) SendMessageW(progress.window,WM_COMMAND,IDCANCEL,0); else if(message.message==WM_SYSKEYDOWN && message.wParam==VK_F4) SendMessageW(owner,WM_CLOSE,0,0); @@ -2416,9 +2469,9 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa if(!answer) { WarningPrompt warning{readOnly?L"Existing file is read-only":L"File already exists", - to.c_str(),L"&Overwrite",L"&Skip"}; + to.c_str(),L"&Overwrite",L"&Skip",*incoming,*existing}; warningBrush=CreateSolidBrush(RGB(128,0,0)); - answer=DialogBoxParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(104),progress.window, + answer=runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(104),progress.window, warningDialog,reinterpret_cast(&warning)); if(warning.remember && (answer==IDYES || answer==IDNO)) progress.conflictChoice=static_cast(answer); @@ -2454,7 +2507,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) if(row<0 || static_cast(row)>=source.rows.size() || source.sizes[row]==L"Up") return; request.sources.push_back(source.rows[row]); } - const auto result=DialogBoxParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(102),owner,copyDialog, + const auto result=runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(102),owner,copyDialog, reinterpret_cast(&request)); if(result==-1) setStatus(L"Could not open the Copy dialog."); if(result!=IDOK) return; @@ -2475,6 +2528,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) setStatus(L"Could not open copy progress."); return; } + FilesDialogInput progressInput(progress.window); copyInProgress=true; activeCopy=&progress; for(auto &panel:panels) EnableWindow(panel.list,FALSE); @@ -2702,14 +2756,14 @@ INT_PTR CALLBACK deleteConfirmationDialog(HWND window,UINT message,WPARAM wp,LPA } if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) { - EndDialog(window,IDCANCEL); + finishFilesDialog(window,IDCANCEL); return TRUE; } if(message==WM_COMMAND && (LOWORD(wp)==IDYES || ((data->folderPrompt || data->readOnlyPrompt) && (LOWORD(wp)==244 || LOWORD(wp)==IDNO)) || (data->readOnlyPrompt && LOWORD(wp)==249))) { - EndDialog(window,LOWORD(wp)); + finishFilesDialog(window,LOWORD(wp)); return TRUE; } return FALSE; @@ -2751,7 +2805,7 @@ bool pumpDeletion(HWND window,bool &canceled) canceled=true; break; } - if(!IsDialogMessageW(window,&message)) + if(!filesDialogHandlesMessage(window,message)) { TranslateMessage(&message); DispatchMessageW(&message); @@ -2801,7 +2855,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) } DeleteConfirmation confirmation{message,entries,static_cast(shown+(shown(&confirmation))!=IDYES) { DeleteObject(warningBrush); @@ -2815,7 +2869,8 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) reinterpret_cast(&canceled)); if(window) { - EnableWindow(owner,FALSE); + GetWindowRect(owner,&previousOwnerBounds); + FilesDialogInput progressInput(window); ShowWindow(window,SW_SHOW); size_t done=0, skipped=0, failed=0, total=0; bool all=false; @@ -2879,7 +2934,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) if(group.size()>1 && !all) { DeleteConfirmation folder{L"The following folder will be deleted:",group.front().wstring(),1,true,true}; - const auto answer=DialogBoxParamW(instance,MAKEINTRESOURCEW(106),window,deleteConfirmationDialog, + const auto answer=runFilesDialog(instance,MAKEINTRESOURCEW(106),window,deleteConfirmationDialog, reinterpret_cast(&folder)); if(answer==244) all=true; else if(answer==IDNO) @@ -2906,7 +2961,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) if(!answer) { DeleteConfirmation warning{L"Delete this read-only file?",current.wstring(),1,true,false,true}; - answer=DialogBoxParamW(instance,MAKEINTRESOURCEW(106),window,deleteConfirmationDialog, + answer=runFilesDialog(instance,MAKEINTRESOURCEW(106),window,deleteConfirmationDialog, reinterpret_cast(&warning)); if(answer==244 || answer==249) readOnlyChoice=static_cast(answer); } @@ -2950,7 +3005,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) catch(const std::system_error &e){++failed;failure=fileError(e);} catch(const std::exception &){++failed;failure=L"File connection interrupted.";} RedrawWindow(window,nullptr,nullptr,RDW_UPDATENOW|RDW_ALLCHILDREN); - EnableWindow(owner,TRUE); + DestroyWindow(window); for(auto &visible:panels) if(!visible.directory.empty()) open(visible,visible.directory); @@ -2964,8 +3019,29 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) warningBrush=nullptr; } +void selectPanelEdge(Panel &panel,bool first) +{ + SetFocus(panel.list); + const auto count=SendMessageW(panel.list,LB_GETCOUNT,0,0); + if(count<=0) return; + SendMessageW(panel.list,LB_SETCURSEL,first?0:count-1,0); + InvalidateRect(panel.list,nullptr,FALSE); + showFileDetails(panel); +} + LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR index) { + if(message==WM_LBUTTONDOWN) + { + const auto count=SendMessageW(window,LB_GETCOUNT,0,0); + RECT last{}; + if(count>0 && SendMessageW(window,LB_GETITEMRECT,count-1,reinterpret_cast(&last))!=LB_ERR && + GET_Y_LPARAM(lp)>=last.bottom) + { + selectPanelEdge(panels[index],false); + return 0; + } + } const bool rangeKey=wp==VK_UP || wp==VK_DOWN || wp==VK_LEFT || wp==VK_RIGHT; if(message==WM_KEYDOWN && (wp==VK_INSERT || (rangeKey && (GetKeyState(VK_SHIFT)&0x8000)))) { @@ -2994,7 +3070,6 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT } if (message == WM_KEYDOWN && (wp == VK_LEFT || wp == VK_RIGHT)) return scrollList(window, message, wp == VK_LEFT ? VK_HOME : VK_END, lp); - if(message==WM_KILLFOCUS || message==WM_SETFOCUS) InvalidateRect(window,nullptr,FALSE); if (message == WM_SETFOCUS) { const auto previous=active; @@ -3068,6 +3143,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT } #include "files_folder_shortcuts.inl" +#include "files_command_history_dialog.inl" #include "files_options.inl" void openMenu(HWND window, int index) @@ -3264,7 +3340,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) 0, 0, 0, 0, window, nullptr, instance, nullptr); terminalInput=CreateWindowW(L"EDIT",L"",WS_CHILD|WS_VISIBLE|ES_AUTOHSCROLL, 0,0,0,0,window,nullptr,instance,nullptr); - terminalPrompt=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_VISIBLE|SS_PATHELLIPSIS|SS_CENTERIMAGE, + terminalPrompt=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_VISIBLE|SS_PATHELLIPSIS, 0,0,0,0,window,nullptr,instance,nullptr); terminalOutput=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPCHILDREN, 0,0,0,0,window,nullptr,instance,nullptr); @@ -3325,7 +3401,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) return 0; } case WM_MOVE: - if(copyInProgress && !IsIconic(window)) + layoutOpenCommandHistory(true); + if((copyInProgress || activeFilesDialog) && !IsIconic(window)) { RECT bounds{}; if(GetWindowRect(window,&bounds)) @@ -3341,6 +3418,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) case WM_SIZE: hidePicker(); layout(window); + layoutOpenCommandHistory(); return 0; case WM_GETMINMAXINFO: reinterpret_cast(lp)->ptMinTrackSize = {540, 220}; @@ -3361,6 +3439,20 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) if (message == WM_LBUTTONDOWN) { dragging = true; SetCapture(window); } return TRUE; } + if(message==WM_LBUTTONDOWN && !terminalVisible) + { + for(auto &panel:panels) + { + RECT list{}; + if(!GetWindowRect(panel.list,&list)) continue; + MapWindowPoints(nullptr,window,reinterpret_cast(&list),2); + if(point.x>=list.left && point.x=0 && point.y=130 && item.CtlID<=134 && static_cast(item.CtlID)-130==menuIndex) background=Selection; - if(item.CtlID==102 || item.CtlID==103) + const bool panelRow=item.CtlID==102 || item.CtlID==103; + const bool activePanelRow=panelRow && item.hwndItem==panels[active].list; + if(panelRow) { const auto cursor=SendMessageW(item.hwndItem,LB_GETCURSEL,0,0); - if(GetFocus()==item.hwndItem && cursor!=LB_ERR && + if(activePanelRow && cursor!=LB_ERR && static_cast(cursor)==item.itemID) background=PanelCursor; } else if(item.itemState&(ODS_SELECTED|ODS_FOCUS)) background=Selection; COLORREF rowBackground=colors[background]; HFONT rowFont{}; - if(item.CtlID==102 || item.CtlID==103) + if(panelRow) { const auto &panel=panels[item.CtlID-102]; if(item.itemID=130 && LOWORD(wp)<=134 && HIWORD(wp)==BN_CLICKED) { @@ -3720,9 +3814,14 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } return 0; case WM_CLOSE: + if(activeFilesDialog && !activeCopy) + { + PostMessageW(activeFilesDialog,WM_CLOSE,0,0); + return 0; + } if(activeCopy) { - if(!IsWindowEnabled(activeCopy->window)) + if(activeFilesDialog!=activeCopy->window) { setStatus(L"Resolve the copy prompt before closing."); return 0; @@ -3780,8 +3879,9 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) } LocalFree(args); } - INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_STANDARD_CLASSES|ICC_PROGRESS_CLASS|ICC_TREEVIEW_CLASSES}; + INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_STANDARD_CLASSES|ICC_PROGRESS_CLASS|ICC_TREEVIEW_CLASSES|ICC_HOTKEY_CLASS}; InitCommonControlsEx(&controls); + loadCommandHistory(); WNDCLASSW type{}; type.hInstance = instance; type.lpfnWndProc = filesWindow; @@ -3799,6 +3899,21 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) MSG message{}; while (GetMessageW(&message, nullptr, 0, 0) > 0) { + if(commandHistoryWindow) + { + if(message.message==WM_KEYDOWN && (message.wParam==VK_RETURN || message.wParam==VK_ESCAPE) && + (message.hwnd==commandHistoryWindow || IsChild(commandHistoryWindow,message.hwnd))) + { + SendMessageW(commandHistoryWindow,WM_COMMAND,message.wParam==VK_RETURN?IDOK:IDCANCEL,0); + continue; + } + if(IsDialogMessageW(commandHistoryWindow,&message)) continue; + const bool ownerClient=message.hwnd==window || IsChild(window,message.hwnd); + const bool clientInput=(message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST) || + (message.message>=WM_MOUSEFIRST && message.message<=WM_MOUSELAST) || + message.message==WM_CONTEXTMENU; + if(ownerClient && clientInput) continue; + } if(message.message==WM_KEYDOWN && (message.wParam==VK_UP || message.wParam==VK_DOWN) && (GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) && (message.hwnd==window || IsChild(window,message.hwnd)) && !terminalVisible && !copyInProgress) @@ -3839,6 +3954,22 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) continue; } const bool filesMessage=message.hwnd==window || IsChild(window,message.hwnd); + const bool panelFocused=message.hwnd==panels[0].list || message.hwnd==panels[1].list; + if(panelFocused && !copyInProgress && message.message==WM_KEYDOWN && + !(GetKeyState(VK_MENU)&0x8000) && + !(GetKeyState(VK_LWIN)&0x8000) && !(GetKeyState(VK_RWIN)&0x8000)) + { + const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0; + const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0; + if((message.wParam=='V' && ctrl && !shift) || + (message.wParam==VK_INSERT && shift && !ctrl)) + { + SetFocus(terminalInput); + SendMessageW(terminalInput,WM_PASTE,0,0); + continue; + } + } + if(filesMessage && !copyInProgress && handleCommandHistoryKey(window,message)) continue; const bool modified=(GetKeyState(VK_CONTROL)&0x8000) || (GetKeyState(VK_SHIFT)&0x8000) || (GetKeyState(VK_LWIN)&0x8000) || (GetKeyState(VK_RWIN)&0x8000); if(filesMessage && !copyInProgress && diff --git a/src/files_options.inl b/src/files_options.inl index 4aa4218..d929aa1 100644 --- a/src/files_options.inl +++ b/src/files_options.inl @@ -1,7 +1,7 @@ constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286; -constexpr int allOptions=3; -enum OptionsPage { PanelModes, PanelColors, Appearance }; -constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance"}; +constexpr int allOptions=4; +enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine }; +constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line"}; constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Popup background", L"Menu selection",L"Command bar",L"File cursor"}; enum PanelSection { PanelLayout, WideColumns, StatusColumns }; @@ -101,7 +101,8 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft) checked(273)!=panels[0].wide || checked(274)!=panels[1].wide || checked(202)!=alignExtensions || checked(204)!=alignFolders || checked(203)!=showDetails || fields!=statusFields || draft.palette!=colors || draft.styles!=fileStyles || - draft.framePadding!=dialogFramePadding || optionsFontChanged(draft); + draft.framePadding!=dialogFramePadding || optionsFontChanged(draft) || + optionHistoryKeys(dialog)!=commandHistoryKeys; EnableWindow(GetDlgItem(dialog,optionsApply),dirty); InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE); } @@ -181,7 +182,7 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) if(section>=0) title=page==PanelModes?panelSectionNames[section]:page==PanelColors? (section==fileStyleSection?L"File type styles":colorNames[section]): - section==DialogFrame?L"Dialog frame":L"Font"; + page==CommandLine?L"Command history":section==DialogFrame?L"Dialog frame":L"Font"; } SetDlgItemTextW(dialog,optionsTitle,title); const auto show=[&](auto &controls,bool visible) @@ -215,11 +216,13 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) for(const auto &option:frameOptions) SendDlgItemMessageW(dialog,option.id,CB_SETCURSEL,draft.framePadding.*option.value,0); } + constexpr int commandLineControls[]{320,321,322,323}; + show(commandLineControls,page==CommandLine && section==0); const bool fileTypes=page==PanelColors && section==fileStyleSection; constexpr int fileStyleControls[]{287,288,289,290,291,292,293,294,295,296,297,298,300,fileStyleState}; show(fileStyleControls,fileTypes); const auto preview=GetDlgItem(dialog,fileStylePreview); - ShowWindow(preview,page>=0 && page=0?SW_SHOW:SW_HIDE); + ShowWindow(preview,page>=0 && page=0?SW_SHOW:SW_HIDE); layoutOptionsPreview(dialog); RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN); show(colorOptionControls,page==PanelColors && section>=0 && !fileTypes); @@ -275,7 +278,7 @@ void filterOptions(HWND dialog,OptionsDraft &draft) draft.wideColumnsNode=nullptr; const auto root=add(L"All settings",allOptions,-1,TVI_ROOT); HTREEITEM first{},selected{}; - for(int page=PanelModes;page<=Appearance;++page) + for(int page=PanelModes;page<=CommandLine;++page) { HTREEITEM category{}; const bool wholeCategory=matches(optionsTitles[page]) || (!query.empty() && matches(L"All settings")); @@ -305,6 +308,7 @@ void filterOptions(HWND dialog,OptionsDraft &draft) addSection(L"File type styles",fileStyleSection,extensionMatches || matches(L"System and hidden") || matches(L"Underline") || matches(L"Strikethrough") || matches(L"Foreground")); } + else if(page==CommandLine) addSection(L"Command history",0,matches(L"Previous command")); else { addSection(L"Font",Font,matches(L"Display font")); @@ -349,6 +353,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) CheckDlgButton(dialog,273,panels[0].wide); CheckDlgButton(dialog,274,panels[1].wide); for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u); + setOptionHistoryKeys(dialog,commandHistoryKeys); filterOptions(dialog,draft); updateOptionsApply(dialog,draft); return TRUE; @@ -388,7 +393,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) } if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) { - EndDialog(dialog,IDCANCEL); + finishFilesDialog(dialog,IDCANCEL); return TRUE; } if(message!=WM_COMMAND) return FALSE; @@ -461,6 +466,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) } return TRUE; case optionsReset: + if(draft->page==allOptions || draft->page==CommandLine) setOptionHistoryKeys(dialog,defaultHistoryKeys); if(draft->page==allOptions || draft->page==PanelModes) for(const auto &property:panelProperties) if(draft->section<0 || property.section==draft->section) resetPanelProperty(dialog,property); @@ -498,6 +504,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) case 273: case 274: updateOptionsApply(dialog,*draft); return TRUE; + case 321: case 323: + updateOptionsApply(dialog,*draft); + return TRUE; case optionsApply: case IDOK: { @@ -512,6 +521,12 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) SendDlgItemMessageW(dialog,201,EM_SETSEL,0,-1); return TRUE; } + const auto keys=optionHistoryKeys(dialog); + if(!validHistoryKeys(keys)) + { + MessageBoxW(dialog,L"Choose distinct shortcuts using Ctrl or Alt that are free in Files.",L"Command history",MB_OK|MB_ICONWARNING); + return TRUE; + } const auto owner=GetWindow(dialog,GW_OWNER); const bool stylesChanged=draft->styles!=fileStyles; if(stylesChanged && !saveFileStyles(draft->styles)) @@ -526,6 +541,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) MessageBoxW(dialog,L"Could not apply the selected font.",optionsTitles[Appearance],MB_OK|MB_ICONWARNING); return TRUE; } + commandHistoryKeys=keys; + savePreference(L"PreviousCommandKey",keys[0]); + savePreference(L"CommandHistoryKey",keys[1]); if(stylesChanged) fileStyles=draft->styles; sizeWidth=static_cast(width); alignExtensions=IsDlgButtonChecked(dialog,202)==BST_CHECKED; @@ -567,7 +585,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) layout(owner); showFileDetails(panels[active]); RedrawWindow(owner,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN|RDW_UPDATENOW); - if(LOWORD(wp)==IDOK) EndDialog(dialog,IDOK); + if(LOWORD(wp)==IDOK) finishFilesDialog(dialog,IDOK); else updateOptionsApply(dialog,*draft); return TRUE; } @@ -580,7 +598,7 @@ void editOptions(HWND owner) const auto panel=panels[active].list; OptionsDraft draft; std::copy(std::begin(colors),std::end(colors),draft.palette.begin()); - const auto result=DialogBoxParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(101),owner,optionsDialog, + const auto result=runFilesDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(101),owner,optionsDialog, reinterpret_cast(&draft)); SetFocus(panel); if(result==-1) setStatus(L"Could not open Files Options."); diff --git a/src/files_styles.inl b/src/files_styles.inl index a61a820..a12b390 100644 --- a/src/files_styles.inl +++ b/src/files_styles.inl @@ -15,7 +15,7 @@ struct FileStyle const std::vector defaultFileStyles{ {L"@system-hidden"},{L".exe",RGB(85,255,85)},{L".md",RGB(231,192,247)}, - {L".7z",RGB(255,210,128)},{L".zip",RGB(255,210,128)},{L".rar",RGB(255,210,128)}, + {L".7z",RGB(255,210,128)},{L".zip",RGB(255,155,170)},{L".rar",RGB(255,210,128)}, {L".tar",RGB(255,210,128)},{L".gz",RGB(255,210,128)}, {L".png",RGB(165,230,255)},{L".jpg",RGB(165,230,255)},{L".jpeg",RGB(165,230,255)}, {L".gif",RGB(165,230,255)},{L".webp",RGB(165,230,255)},{L".svg",RGB(165,230,255)},