Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc6199e9be | ||
|
|
a27ae96842 | ||
|
|
9158bf95a6 | ||
|
|
159b776199 | ||
|
|
ada198db24 | ||
|
|
fe1f818582 |
No files matched your search
+1
-1
@@ -35,7 +35,7 @@ add_custom_target(check-files-quick-view
|
||||
DEPENDS KSwitcherFiles
|
||||
VERBATIM)
|
||||
target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include")
|
||||
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet netapi32 mpr KSwitcherFilesImage libssh2::libssh2)
|
||||
target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet netapi32 mpr userenv KSwitcherFilesImage libssh2::libssh2)
|
||||
if(MSVC)
|
||||
target_compile_options(KSwitcherFiles PRIVATE /utf-8)
|
||||
else()
|
||||
|
||||
+29
@@ -766,6 +766,35 @@ Warning і початковий фокус на No.
|
||||
робочий файл у Viewer, **F4** відкриває його в Editor, якщо файл існує.
|
||||
**Ctrl+R** перечитує Git, **Esc** повертає обидві панелі. Для цього
|
||||
режиму потрібен Git for Windows. Перегляд залишає Git index без змін.
|
||||
- У Git Changes кнопка **History** або **F6** відкриває історію. **Branch**
|
||||
вибирає локальну чи remote-tracking гілку для перегляду. Зірочка
|
||||
позначає поточну гілку або detached HEAD. Вибір не змінює checkout.
|
||||
Сусідня панель показує повідомлення коміту та змінені шляхи.
|
||||
Для merge-коміту список шляхів відповідає різниці з першим батьком.
|
||||
**More** або **F7** додає наступні 50 комітів, **Ctrl+R** перечитує гілки,
|
||||
**F6** повертає до Git Changes, а **Esc** повертає до файлових панелей.
|
||||
- У Git Changes **Stage** та **Unstage** діють на вибраний запис.
|
||||
Unstage перейменування відновлює обидва індексні шляхи. Якщо шлях уже
|
||||
має staged-версію, Stage запитує підтвердження заміни.
|
||||
- **Commit** показує checkout-гілку й усі staged-шляхи, включно з
|
||||
прихованими фільтром. Якщо гілка, HEAD або staged-вміст змінилися
|
||||
після перегляду, Files зберігає повідомлення й вимагає нового перегляду.
|
||||
Після коміту показує хеш і перечитує Git Changes. Для detached HEAD,
|
||||
розв’язання конфліктів або продовження активної операції використовуй
|
||||
Git у терміналі.
|
||||
- Stage використовує clean-фільтри Git. Локальний Commit враховує
|
||||
**commit.gpgSign** і налаштований засіб підписування. Git hooks для
|
||||
цих операцій Files вимкнено. Для комітів із hooks або інтерактивним
|
||||
підписуванням використовуй Git у терміналі.
|
||||
- **F9 → Commands → Environment Variables** показує області **User**,
|
||||
**System** і **Process**, джерело, сире та розгорнуте значення.
|
||||
Process показує середовище поточного процесу Files лише для читання.
|
||||
**Edit** зберігає тип реєстрового значення. **Copy to User** і
|
||||
**Copy to System** переносять сире значення та його тип і запитують
|
||||
підтвердження, якщо визначення існує. Якщо значення змінилося після
|
||||
відкриття діалогу або Windows відмовила в доступі, Files показує причину.
|
||||
Запущені сеанси PowerShell зберігають своє середовище. Після зміни
|
||||
перезапусти Files, щоб вбудований PowerShell успадкував нові значення.
|
||||
- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення.
|
||||
- Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
|
||||
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
|
||||
|
||||
@@ -619,3 +619,55 @@ BEGIN
|
||||
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 95, 153, 80, 17
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 185, 153, 80, 17
|
||||
END
|
||||
|
||||
126 DIALOGEX 0, 0, 420, 213
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
CAPTION "Commit staged changes"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "", 594, 16, 15, 388, 13, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "", 595, 16, 31, 388, 13, SS_NOPREFIX
|
||||
LISTBOX 596, 16, 45, 388, 61, LBS_NOINTEGRALHEIGHT | WS_TABSTOP
|
||||
LTEXT "Commit &message", 597, 16, 112, 388, 13
|
||||
EDITTEXT 598, 16, 127, 388, 39, ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN
|
||||
LTEXT "", 599, 16, 170, 388, 13, SS_ENDELLIPSIS | SS_NOPREFIX | NOT WS_VISIBLE
|
||||
LTEXT "", 600, 10, 186, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Commit", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 125, 193, 80, 17
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 215, 193, 80, 17
|
||||
END
|
||||
|
||||
127 DIALOGEX 0, 0, 458, 224
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
CAPTION "Environment Variables"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "&Scope", 610, 16, 16, 58, 13
|
||||
COMBOBOX 611, 77, 15, 120, 75, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
|
||||
LTEXT "", 613, 16, 34, 426, 13, SS_PATHELLIPSIS | SS_NOPREFIX
|
||||
LISTBOX 612, 16, 50, 172, 119, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
|
||||
LTEXT "", 614, 197, 50, 245, 13, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "Ra&w value", 620, 197, 66, 245, 13
|
||||
EDITTEXT 615, 197, 80, 245, 30, ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY
|
||||
LTEXT "E&xpanded value", 621, 197, 115, 245, 13
|
||||
EDITTEXT 616, 197, 129, 245, 39, ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY
|
||||
LTEXT "", 617, 16, 174, 426, 24, SS_NOPREFIX
|
||||
LTEXT "", 618, 10, 199, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Edit", 622, "Button", BS_OWNERDRAW | WS_TABSTOP, 27, 204, 59, 15
|
||||
CONTROL "Copy to &User", 623, "Button", BS_OWNERDRAW | WS_TABSTOP, 89, 204, 89, 15
|
||||
CONTROL "Cop&y to System", 624, "Button", BS_OWNERDRAW | WS_TABSTOP, 181, 204, 100, 15
|
||||
CONTROL "&Refresh", 625, "Button", BS_OWNERDRAW | WS_TABSTOP, 285, 204, 66, 15
|
||||
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 354, 204, 65, 15
|
||||
END
|
||||
|
||||
128 DIALOGEX 0, 0, 366, 122
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
CAPTION "Edit environment definition"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "", 630, 16, 16, 334, 13, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "Ra&w value", 631, 16, 33, 334, 13
|
||||
EDITTEXT 632, 16, 47, 334, 42, ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN
|
||||
LTEXT "", 633, 10, 94, 1, 1, NOT WS_VISIBLE
|
||||
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 100, 78, 16
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 186, 100, 78, 16
|
||||
END
|
||||
@@ -0,0 +1,418 @@
|
||||
enum class EnvironmentScope { user, system, process };
|
||||
|
||||
constexpr wchar_t userEnvironmentPath[]=L"Environment";
|
||||
constexpr wchar_t systemEnvironmentPath[]=L"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
|
||||
constexpr unsigned environmentValueLimit=32767;
|
||||
|
||||
const wchar_t *environmentScopeName(EnvironmentScope scope)
|
||||
{
|
||||
switch(scope)
|
||||
{
|
||||
case EnvironmentScope::user: return L"User";
|
||||
case EnvironmentScope::system: return L"System";
|
||||
case EnvironmentScope::process: return L"Process";
|
||||
}
|
||||
return L"";
|
||||
}
|
||||
|
||||
std::wstring environmentSource(EnvironmentScope scope)
|
||||
{
|
||||
if(scope==EnvironmentScope::process) return L"Current KSwitcher.Files process";
|
||||
return scope==EnvironmentScope::user?L"HKCU\\"+std::wstring(userEnvironmentPath):
|
||||
L"HKLM\\"+std::wstring(systemEnvironmentPath);
|
||||
}
|
||||
|
||||
struct EnvironmentKey
|
||||
{
|
||||
HKEY value{};
|
||||
explicit EnvironmentKey(EnvironmentScope scope,bool write=false)
|
||||
{
|
||||
const bool user=scope==EnvironmentScope::user;
|
||||
const auto root=user?HKEY_CURRENT_USER:HKEY_LOCAL_MACHINE;
|
||||
const auto path=user?userEnvironmentPath:systemEnvironmentPath;
|
||||
const auto access=KEY_QUERY_VALUE|(write?KEY_SET_VALUE:0);
|
||||
const auto result=user && write?
|
||||
RegCreateKeyExW(root,path,0,nullptr,0,access,nullptr,&value,nullptr):
|
||||
RegOpenKeyExW(root,path,0,access,&value);
|
||||
if(result!=ERROR_SUCCESS && (result!=ERROR_FILE_NOT_FOUND || !user || write))
|
||||
throw std::system_error(result,std::system_category(),"Open the environment registry key");
|
||||
}
|
||||
EnvironmentKey(const EnvironmentKey &)=delete;
|
||||
~EnvironmentKey(){if(value) RegCloseKey(value);}
|
||||
};
|
||||
|
||||
struct EnvironmentValue
|
||||
{
|
||||
DWORD type{};
|
||||
std::wstring text;
|
||||
bool supported{};
|
||||
bool operator==(const EnvironmentValue &) const = default;
|
||||
};
|
||||
|
||||
struct EnvironmentVariable
|
||||
{
|
||||
std::wstring name;
|
||||
EnvironmentValue value;
|
||||
};
|
||||
|
||||
std::optional<EnvironmentValue> readEnvironmentValue(HKEY key,const std::wstring &name)
|
||||
{
|
||||
if(!key) return {};
|
||||
DWORD size{},type{};
|
||||
auto result=RegQueryValueExW(key,name.c_str(),nullptr,&type,nullptr,&size);
|
||||
if(result==ERROR_FILE_NOT_FOUND) return {};
|
||||
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"Read the environment definition");
|
||||
for(int attempt=0;attempt<4;++attempt)
|
||||
{
|
||||
if(type!=REG_SZ && type!=REG_EXPAND_SZ) return EnvironmentValue{type,{},false};
|
||||
if(size%sizeof(wchar_t) || size>2*(environmentValueLimit+1))
|
||||
return EnvironmentValue{type,{},false};
|
||||
std::wstring text(size/sizeof(wchar_t)+1,L'\0');
|
||||
result=RegQueryValueExW(key,name.c_str(),nullptr,&type,reinterpret_cast<BYTE*>(text.data()),&size);
|
||||
if(result==ERROR_FILE_NOT_FOUND) return {};
|
||||
if(result==ERROR_MORE_DATA) continue;
|
||||
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"Read the environment definition");
|
||||
if((type!=REG_SZ && type!=REG_EXPAND_SZ) || size%sizeof(wchar_t))
|
||||
return EnvironmentValue{type,{},false};
|
||||
text.resize(size/sizeof(wchar_t));
|
||||
while(!text.empty() && text.back()==L'\0') text.pop_back();
|
||||
if(text.find(L'\0')!=text.npos) return EnvironmentValue{type,{},false};
|
||||
return EnvironmentValue{type,std::move(text),true};
|
||||
}
|
||||
throw std::runtime_error("The environment definition changed while Windows was reading it.");
|
||||
}
|
||||
|
||||
std::vector<EnvironmentVariable> readEnvironmentScope(EnvironmentScope scope)
|
||||
{
|
||||
std::vector<EnvironmentVariable> entries;
|
||||
if(scope==EnvironmentScope::process)
|
||||
{
|
||||
const auto block=GetEnvironmentStringsW();
|
||||
if(!block) throw std::system_error(GetLastError(),std::system_category(),"Read the current process environment");
|
||||
const std::unique_ptr<wchar_t,decltype(&FreeEnvironmentStringsW)> owned(block,FreeEnvironmentStringsW);
|
||||
for(auto offset=block;*offset;)
|
||||
{
|
||||
const std::wstring_view line=offset;
|
||||
const auto equals=line.find(L'=');
|
||||
if(equals!=line.npos && equals>0)
|
||||
entries.push_back({std::wstring(line.substr(0,equals)),{REG_SZ,std::wstring(line.substr(equals+1)),true}});
|
||||
offset+=line.size()+1;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
const EnvironmentKey key(scope);
|
||||
if(!key.value) return {};
|
||||
std::vector<wchar_t> name(16384);
|
||||
for(DWORD index=0;;++index)
|
||||
{
|
||||
DWORD length=static_cast<DWORD>(name.size());
|
||||
const auto result=RegEnumValueW(key.value,index,name.data(),&length,nullptr,nullptr,nullptr,nullptr);
|
||||
if(result==ERROR_NO_MORE_ITEMS) break;
|
||||
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"List environment definitions");
|
||||
if(!length) continue;
|
||||
std::wstring label(name.data(),length);
|
||||
if(label.find(L'=')!=label.npos) continue;
|
||||
if(auto value=readEnvironmentValue(key.value,label);value && value->supported)
|
||||
entries.push_back({std::move(label),std::move(*value)});
|
||||
}
|
||||
}
|
||||
std::sort(entries.begin(),entries.end(),[](const auto &left,const auto &right) {
|
||||
return CompareStringOrdinal(left.name.c_str(),-1,right.name.c_str(),-1,TRUE)==CSTR_LESS_THAN;
|
||||
});
|
||||
return entries;
|
||||
}
|
||||
|
||||
std::wstring expandedEnvironmentValue(EnvironmentScope scope,const EnvironmentValue &value)
|
||||
{
|
||||
if(value.type!=REG_EXPAND_SZ) return value.text;
|
||||
Handle token{};
|
||||
if(scope==EnvironmentScope::user &&
|
||||
!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY|TOKEN_IMPERSONATE|TOKEN_DUPLICATE,&token.value))
|
||||
throw std::system_error(GetLastError(),std::system_category(),"Open the current user's environment");
|
||||
std::wstring expanded(environmentValueLimit+1,L'\0');
|
||||
if(!ExpandEnvironmentStringsForUserW(token.value,value.text.c_str(),expanded.data(),static_cast<DWORD>(expanded.size())))
|
||||
throw std::system_error(GetLastError(),std::system_category(),"Expand the environment definition");
|
||||
expanded.resize(wcslen(expanded.c_str()));
|
||||
return expanded;
|
||||
}
|
||||
|
||||
void writeEnvironmentValue(EnvironmentScope scope,const std::wstring &name,const EnvironmentValue &replacement,
|
||||
const std::optional<EnvironmentValue> &expected)
|
||||
{
|
||||
if(scope==EnvironmentScope::process) throw std::runtime_error("The current process environment is read-only here.");
|
||||
if(replacement.text.size()>environmentValueLimit) throw std::runtime_error("The value exceeds the Windows environment limit.");
|
||||
const EnvironmentKey key(scope,true);
|
||||
if(readEnvironmentValue(key.value,name)!=expected)
|
||||
throw std::runtime_error("Windows changed this definition while it was open. Reload and review the current value.");
|
||||
if(expected==replacement) return;
|
||||
const auto bytes=static_cast<DWORD>((replacement.text.size()+1)*sizeof(wchar_t));
|
||||
const auto result=RegSetValueExW(key.value,name.c_str(),0,replacement.type,
|
||||
reinterpret_cast<const BYTE*>(replacement.text.c_str()),bytes);
|
||||
if(result!=ERROR_SUCCESS) throw std::system_error(result,std::system_category(),"Save the environment definition");
|
||||
try
|
||||
{
|
||||
std::thread([] {
|
||||
DWORD_PTR reply{};
|
||||
SendMessageTimeoutW(HWND_BROADCAST,WM_SETTINGCHANGE,0,reinterpret_cast<LPARAM>(L"Environment"),
|
||||
SMTO_ABORTIFHUNG,250,&reply);
|
||||
}).detach();
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
}
|
||||
|
||||
const wchar_t *environmentValueType(const EnvironmentValue &value)
|
||||
{
|
||||
return value.type==REG_EXPAND_SZ?L"REG_EXPAND_SZ":L"REG_SZ";
|
||||
}
|
||||
|
||||
struct EnvironmentEdit
|
||||
{
|
||||
EnvironmentScope scope;
|
||||
EnvironmentVariable original;
|
||||
std::wstring replacement;
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK environmentEditDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
constexpr int label=630,body=632,footer=633;
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
const auto &editor=*reinterpret_cast<const EnvironmentEdit *>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareTextDialog(dialog);
|
||||
layoutDialogContent(dialog,label);
|
||||
const auto title=editor.original.name+L" · "+environmentScopeName(editor.scope)+L" · "+
|
||||
environmentValueType(editor.original.value);
|
||||
SetDlgItemTextW(dialog,label,title.c_str());
|
||||
SendDlgItemMessageW(dialog,body,EM_SETLIMITTEXT,environmentValueLimit,0);
|
||||
SetDlgItemTextW(dialog,body,editor.original.value.text.c_str());
|
||||
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
|
||||
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
|
||||
SetFocus(GetDlgItem(dialog,body));
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
|
||||
{
|
||||
auto &editor=*reinterpret_cast<EnvironmentEdit *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
editor.replacement=dialogFieldText(GetDlgItem(dialog,body));
|
||||
FilesModalDialog::finish(dialog,IDOK);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL))
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
return paintCopyDialog(dialog,message,wp,lp,L" Edit environment definition ",false,{footer});
|
||||
}
|
||||
|
||||
constexpr int envScope=611,envList=612,envSource=613,envSelected=614,envRaw=615,envExpanded=616,
|
||||
envStatus=617,envFooter=618,envEdit=622,envCopyUser=623,envCopySystem=624,envRefresh=625;
|
||||
|
||||
struct EnvironmentPanel
|
||||
{
|
||||
EnvironmentScope scope=EnvironmentScope::user;
|
||||
std::vector<EnvironmentVariable> entries;
|
||||
std::wstring readFailure,notice;
|
||||
};
|
||||
|
||||
std::wstring environmentErrorText(const std::exception &error)
|
||||
{
|
||||
if(const auto *system=dynamic_cast<const std::system_error *>(&error)) return fileError(*system);
|
||||
return ks::wide(error.what());
|
||||
}
|
||||
|
||||
const EnvironmentVariable *selectedEnvironmentVariable(HWND dialog,const EnvironmentPanel &panel)
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,envList,LB_GETCURSEL,0,0);
|
||||
if(row<0) return nullptr;
|
||||
const auto index=SendDlgItemMessageW(dialog,envList,LB_GETITEMDATA,row,0);
|
||||
return index>=0 && static_cast<size_t>(index)<panel.entries.size()?&panel.entries[index]:nullptr;
|
||||
}
|
||||
|
||||
void setEnvironmentDetails(HWND dialog,const EnvironmentPanel &panel)
|
||||
{
|
||||
const auto *entry=selectedEnvironmentVariable(dialog,panel);
|
||||
const bool registry=panel.scope!=EnvironmentScope::process;
|
||||
SetDlgItemTextW(dialog,envSource,environmentSource(panel.scope).c_str());
|
||||
SetDlgItemTextW(dialog,envSelected,entry?(entry->name+L" · "+
|
||||
(registry?environmentValueType(entry->value):L"Read-only")).c_str():L"");
|
||||
SetDlgItemTextW(dialog,envRaw,entry?entry->value.text.c_str():L"");
|
||||
std::wstring expanded;
|
||||
if(entry)
|
||||
{
|
||||
try {expanded=expandedEnvironmentValue(panel.scope,entry->value);}
|
||||
catch(const std::exception &error) {expanded=L"Unavailable · "+environmentErrorText(error);}
|
||||
}
|
||||
SetDlgItemTextW(dialog,envExpanded,expanded.c_str());
|
||||
EnableWindow(GetDlgItem(dialog,envEdit),entry && registry);
|
||||
EnableWindow(GetDlgItem(dialog,envCopyUser),entry && panel.scope!=EnvironmentScope::user);
|
||||
EnableWindow(GetDlgItem(dialog,envCopySystem),entry && panel.scope!=EnvironmentScope::system);
|
||||
const auto status=!panel.readFailure.empty()?panel.readFailure:!panel.notice.empty()?panel.notice:
|
||||
!entry?std::wstring(L"No environment variables in this scope."):
|
||||
registry?L"Existing PowerShell sessions keep their environment. Restart Files for embedded PowerShell.":
|
||||
L"These values belong to the running Files process.";
|
||||
SetDlgItemTextW(dialog,envStatus,status.c_str());
|
||||
}
|
||||
|
||||
void reloadEnvironmentPanel(HWND dialog,EnvironmentPanel &panel,const std::wstring &preferred={})
|
||||
{
|
||||
panel.readFailure.clear();
|
||||
try {panel.entries=readEnvironmentScope(panel.scope);}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
panel.entries.clear();
|
||||
panel.readFailure=environmentErrorText(error);
|
||||
}
|
||||
const auto list=GetDlgItem(dialog,envList);
|
||||
SendMessageW(list,WM_SETREDRAW,FALSE,0);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
LRESULT selected=0;
|
||||
for(size_t index=0;index<panel.entries.size();++index)
|
||||
{
|
||||
const auto &name=panel.entries[index].name;
|
||||
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(name.c_str()));
|
||||
if(row<0) continue;
|
||||
SendMessageW(list,LB_SETITEMDATA,row,index);
|
||||
if(CompareStringOrdinal(name.c_str(),-1,preferred.c_str(),-1,TRUE)==CSTR_EQUAL) selected=row;
|
||||
}
|
||||
if(!panel.entries.empty()) SendMessageW(list,LB_SETCURSEL,selected,0);
|
||||
SendMessageW(list,WM_SETREDRAW,TRUE,0);
|
||||
InvalidateRect(list,nullptr,TRUE);
|
||||
setEnvironmentDetails(dialog,panel);
|
||||
}
|
||||
|
||||
void saveEnvironmentDefinition(HWND dialog,EnvironmentPanel &panel,const EnvironmentVariable &entry,
|
||||
std::optional<EnvironmentScope> copyTo={})
|
||||
{
|
||||
try
|
||||
{
|
||||
if(copyTo)
|
||||
{
|
||||
const EnvironmentKey key(*copyTo);
|
||||
const auto previous=readEnvironmentValue(key.value,entry.name);
|
||||
if(previous && !previous->supported)
|
||||
throw std::runtime_error("The destination already has a registry value of an unsupported type.");
|
||||
const auto question=previous?L"Replace "+entry.name+L" in "+environmentScopeName(*copyTo)+L"?":
|
||||
L"Copy "+entry.name+L" to "+environmentScopeName(*copyTo)+L"?";
|
||||
if(showFilesNotice(dialog,question.c_str(),L"Copy environment definition",
|
||||
{.confirm=true,.tone=previous?FilesNoticeTone::warning:FilesNoticeTone::dialog})!=IDYES) return;
|
||||
if(panel.scope!=EnvironmentScope::process)
|
||||
{
|
||||
const EnvironmentKey source(panel.scope);
|
||||
if(readEnvironmentValue(source.value,entry.name)!=entry.value)
|
||||
throw std::runtime_error("The source definition changed. Reload and review it before copying.");
|
||||
}
|
||||
writeEnvironmentValue(*copyTo,entry.name,entry.value,previous);
|
||||
panel.scope=*copyTo;
|
||||
SendDlgItemMessageW(dialog,envScope,CB_SETCURSEL,static_cast<WPARAM>(panel.scope),0);
|
||||
}
|
||||
else
|
||||
{
|
||||
if(panel.scope==EnvironmentScope::process) return;
|
||||
EnvironmentEdit editor{panel.scope,entry};
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(128),dialog,environmentEditDialog,
|
||||
reinterpret_cast<LPARAM>(&editor))!=IDOK || editor.replacement==entry.value.text) return;
|
||||
writeEnvironmentValue(panel.scope,entry.name,{entry.value.type,editor.replacement,true},entry.value);
|
||||
}
|
||||
panel.notice=L"Saved. Restart Files for embedded PowerShell to inherit the new value.";
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
panel.notice.clear();
|
||||
const auto details=environmentErrorText(error);
|
||||
showFilesNotice(dialog,details.c_str(),L"Could not save environment definition",{.tone=FilesNoticeTone::warning});
|
||||
}
|
||||
reloadEnvironmentPanel(dialog,panel,entry.name);
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK environmentPanelDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &panel=*reinterpret_cast<EnvironmentPanel *>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareTextDialog(dialog);
|
||||
layoutDialogContent(dialog,610);
|
||||
const auto scope=GetDlgItem(dialog,envScope);
|
||||
for(const auto item:{EnvironmentScope::user,EnvironmentScope::system,EnvironmentScope::process})
|
||||
SendMessageW(scope,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(environmentScopeName(item)));
|
||||
SendMessageW(scope,CB_SETCURSEL,0,0);
|
||||
installFarCombo(scope,GetDlgItem(dialog,610));
|
||||
const auto list=GetDlgItem(dialog,envList);
|
||||
const auto bounds=dialogControlBounds(dialog,envList);
|
||||
SetWindowPos(list,nullptr,0,0,std::max(1L,bounds.right-bounds.left-scrollBarWidth(list)),
|
||||
bounds.bottom-bounds.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
installScrollBar(list,dialog);
|
||||
layoutDialogButtons(dialog,envFooter,{envEdit,envCopyUser,envCopySystem,envRefresh,IDOK});
|
||||
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
|
||||
reloadEnvironmentPanel(dialog,panel);
|
||||
SetFocus(scope);
|
||||
return FALSE;
|
||||
}
|
||||
auto *panel=reinterpret_cast<EnvironmentPanel *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!panel) return FALSE;
|
||||
if(message==WM_DRAWITEM && wp==envScope)
|
||||
{
|
||||
drawFarComboRow(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CTLCOLORLISTBOX && reinterpret_cast<HWND>(lp)!=GetDlgItem(dialog,envList))
|
||||
{
|
||||
const auto dc=reinterpret_cast<HDC>(wp);
|
||||
SetTextColor(dc,colors[Text]);
|
||||
SetBkColor(dc,colors[Dialog]);
|
||||
return reinterpret_cast<INT_PTR>(teal);
|
||||
}
|
||||
if(message==WM_COMMAND)
|
||||
{
|
||||
const auto id=LOWORD(wp),notification=HIWORD(wp);
|
||||
if(id==envScope && (notification==CBN_SELENDOK ||
|
||||
(notification==CBN_SELCHANGE && !SendDlgItemMessageW(dialog,envScope,CB_GETDROPPEDSTATE,0,0))))
|
||||
{
|
||||
const auto scope=SendDlgItemMessageW(dialog,envScope,CB_GETCURSEL,0,0);
|
||||
if(scope>=0 && scope<=static_cast<LRESULT>(EnvironmentScope::process) &&
|
||||
static_cast<EnvironmentScope>(scope)!=panel->scope)
|
||||
{
|
||||
const auto *entry=selectedEnvironmentVariable(dialog,*panel);
|
||||
const auto selected=entry?entry->name:std::wstring{};
|
||||
panel->scope=static_cast<EnvironmentScope>(scope);
|
||||
reloadEnvironmentPanel(dialog,*panel,selected);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
if(id==envRefresh || (id==envList && notification==LBN_SELCHANGE))
|
||||
{
|
||||
if(id==envRefresh)
|
||||
{
|
||||
const auto *entry=selectedEnvironmentVariable(dialog,*panel);
|
||||
const auto name=entry?entry->name:std::wstring{};
|
||||
reloadEnvironmentPanel(dialog,*panel,name);
|
||||
}
|
||||
else setEnvironmentDetails(dialog,*panel);
|
||||
return TRUE;
|
||||
}
|
||||
if(id==envEdit || id==envCopyUser || id==envCopySystem)
|
||||
{
|
||||
if(const auto *entry=selectedEnvironmentVariable(dialog,*panel))
|
||||
saveEnvironmentDefinition(dialog,*panel,EnvironmentVariable(*entry),id==envEdit?std::nullopt:
|
||||
std::optional(id==envCopyUser?EnvironmentScope::user:EnvironmentScope::system));
|
||||
return TRUE;
|
||||
}
|
||||
if(id==IDOK || id==IDCANCEL)
|
||||
{
|
||||
FilesModalDialog::finish(dialog,IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
if(message==WM_CLOSE) {FilesModalDialog::finish(dialog,IDCANCEL);return TRUE;}
|
||||
return paintCopyDialog(dialog,message,wp,lp,L" Environment Variables ",false,{envFooter},false,GetDlgItem(dialog,envList));
|
||||
}
|
||||
|
||||
void showEnvironmentPanel(HWND owner)
|
||||
{
|
||||
EnvironmentPanel panel;
|
||||
FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(127),owner,environmentPanelDialog,
|
||||
reinterpret_cast<LPARAM>(&panel));
|
||||
}
|
||||
+451
-18
@@ -4,6 +4,8 @@
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <objbase.h>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <system_error>
|
||||
#include <tuple>
|
||||
@@ -76,15 +78,16 @@ fs::path locateGit()
|
||||
throw std::runtime_error("Git for Windows was not found. Install it or add git.exe to PATH.");
|
||||
}
|
||||
|
||||
std::vector<wchar_t> gitEnvironment()
|
||||
std::vector<wchar_t> gitEnvironment(const fs::path &alternateIndex)
|
||||
{
|
||||
const auto environment=GetEnvironmentStringsW();
|
||||
if(!environment) gitWindowsError("Could not read the environment for Git");
|
||||
const std::unique_ptr<wchar_t,decltype(&FreeEnvironmentStringsW)> owned(environment,FreeEnvironmentStringsW);
|
||||
constexpr std::wstring_view overrides[]{
|
||||
L"GIT_DIR",L"GIT_WORK_TREE",L"GIT_COMMON_DIR",L"GIT_INDEX_FILE",L"GIT_PREFIX",
|
||||
L"GIT_OBJECT_DIRECTORY",L"GIT_ALTERNATE_OBJECT_DIRECTORIES",L"GIT_NAMESPACE",L"GIT_QUARANTINE_PATH",
|
||||
L"GIT_CEILING_DIRECTORIES",L"GIT_GLOB_PATHSPECS",L"GIT_NOGLOB_PATHSPECS",L"GIT_ICASE_PATHSPECS"};
|
||||
std::vector<wchar_t> result;
|
||||
std::vector<std::wstring> settings;
|
||||
for(auto entry=environment;*entry;)
|
||||
{
|
||||
const std::wstring_view setting=entry;
|
||||
@@ -94,9 +97,15 @@ std::vector<wchar_t> gitEnvironment()
|
||||
CompareStringOrdinal(name.data(),static_cast<int>(name.size()),key.data(),static_cast<int>(key.size()),TRUE)
|
||||
==CSTR_EQUAL;
|
||||
}))
|
||||
result.insert(result.end(),entry,entry+setting.size()+1);
|
||||
settings.emplace_back(setting);
|
||||
entry+=setting.size()+1;
|
||||
}
|
||||
if(!alternateIndex.empty()) settings.push_back(L"GIT_INDEX_FILE="+alternateIndex.native());
|
||||
std::sort(settings.begin(),settings.end(),[](const auto &left,const auto &right) {
|
||||
return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE)==CSTR_LESS_THAN;
|
||||
});
|
||||
std::vector<wchar_t> result;
|
||||
for(const auto &setting:settings) result.insert(result.end(),setting.c_str(),setting.c_str()+setting.size()+1);
|
||||
result.push_back(L'\0');
|
||||
if(result.size()==1) result.push_back(L'\0');
|
||||
return result;
|
||||
@@ -131,18 +140,33 @@ struct GitOutput
|
||||
DWORD exitCode{};
|
||||
};
|
||||
|
||||
struct GitCommandOptions
|
||||
{
|
||||
fs::path index;
|
||||
std::string_view input;
|
||||
std::function<void()> afterPrepare;
|
||||
ULONGLONG timeout=15000;
|
||||
};
|
||||
|
||||
GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector<std::wstring> &arguments,
|
||||
size_t maximum,std::stop_token stop)
|
||||
size_t maximum,std::stop_token stop,const GitCommandOptions &options={})
|
||||
{
|
||||
if(stop.stop_requested()) throw std::runtime_error("Git request canceled.");
|
||||
auto command=quoteWindowsArgument(git.native())+
|
||||
L" --no-pager --no-optional-locks --literal-pathspecs -c core.fsmonitor=false -c core.quotePath=false -C "+
|
||||
quoteWindowsArgument(directory.native());
|
||||
for(const auto &argument:arguments) command+=L' '+quoteWindowsArgument(argument);
|
||||
auto environment=gitEnvironment();
|
||||
auto environment=gitEnvironment(options.index);
|
||||
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
|
||||
const GitHandle input{CreateFileW(L"NUL",GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&inheritable,OPEN_EXISTING,0,nullptr)};
|
||||
if(input.value==INVALID_HANDLE_VALUE) gitWindowsError("Could not open Git input");
|
||||
GitHandle input,writeInput;
|
||||
if(options.input.empty())
|
||||
{
|
||||
input.value=CreateFileW(L"NUL",GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&inheritable,OPEN_EXISTING,0,nullptr);
|
||||
if(input.value==INVALID_HANDLE_VALUE) gitWindowsError("Could not open Git input");
|
||||
}
|
||||
else if(!CreatePipe(&input.value,&writeInput.value,&inheritable,65536) ||
|
||||
!SetHandleInformation(writeInput.value,HANDLE_FLAG_INHERIT,0))
|
||||
gitWindowsError("Could not open Git input");
|
||||
GitHandle out,childOut,error,childError;
|
||||
makeGitPipe(out,childOut,inheritable);
|
||||
makeGitPipe(error,childError,inheritable);
|
||||
@@ -169,10 +193,20 @@ GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector
|
||||
try
|
||||
{
|
||||
if(ResumeThread(thread.value)==DWORD(-1)) gitWindowsError("Could not resume Git");
|
||||
input.close();
|
||||
childOut.close();
|
||||
childError.close();
|
||||
const auto write=[&](std::string_view payload)
|
||||
{
|
||||
DWORD written{};
|
||||
if(payload.size()>65536 || !WriteFile(writeInput.value,payload.data(),
|
||||
static_cast<DWORD>(payload.size()),&written,nullptr) || written!=payload.size())
|
||||
gitWindowsError("Could not send input to Git");
|
||||
};
|
||||
if(writeInput.value) write(options.input);
|
||||
if(!options.afterPrepare) writeInput.close();
|
||||
GitOutput result;
|
||||
const auto deadline=GetTickCount64()+15000;
|
||||
auto deadline=GetTickCount64()+options.timeout;
|
||||
const auto read=[&](HANDLE pipe,std::string &data,size_t limit)
|
||||
{
|
||||
DWORD waiting{},readBytes{};
|
||||
@@ -195,6 +229,14 @@ GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector
|
||||
if(GetTickCount64()>=deadline) throw std::runtime_error("Git did not respond in time.");
|
||||
const bool readOutput=read(out.value,result.output,maximum);
|
||||
const bool readErrors=read(error.value,result.error,256*1024);
|
||||
if(writeInput.value && (result.output.find("prepare: ok\n")!=std::string::npos ||
|
||||
result.output.find("prepare: ok\r\n")!=std::string::npos))
|
||||
{
|
||||
options.afterPrepare();
|
||||
write("commit\n");
|
||||
writeInput.close();
|
||||
deadline=GetTickCount64()+options.timeout;
|
||||
}
|
||||
const auto state=WaitForSingleObject(process.value,readOutput || readErrors?0:20);
|
||||
if(state==WAIT_FAILED) gitWindowsError("Could not wait for Git");
|
||||
if(state==WAIT_OBJECT_0 && !readOutput && !readErrors)
|
||||
@@ -208,7 +250,10 @@ GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
TerminateProcess(process.value,ERROR_CANCELLED);
|
||||
const bool wasWaitingForInput=writeInput.value!=nullptr;
|
||||
writeInput.close(); // EOF aborts a prepared Git reference transaction.
|
||||
if(!wasWaitingForInput || WaitForSingleObject(process.value,2000)!=WAIT_OBJECT_0)
|
||||
TerminateProcess(process.value,ERROR_CANCELLED);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -221,10 +266,10 @@ void checkGit(const GitOutput &result,const char *operation,bool allowDifference
|
||||
throw std::runtime_error(detail.empty()?std::string(operation):std::string(operation)+"\r\n"+detail);
|
||||
}
|
||||
|
||||
std::string_view statusField(std::string_view &input)
|
||||
std::string_view nulField(std::string_view &input)
|
||||
{
|
||||
const auto separator=input.find('\0');
|
||||
if(separator==input.npos) throw std::runtime_error("Git returned incomplete status output.");
|
||||
if(separator==input.npos) throw std::runtime_error("Git returned incomplete output.");
|
||||
const auto field=input.substr(0,separator);
|
||||
input.remove_prefix(separator+1);
|
||||
return field;
|
||||
@@ -251,12 +296,12 @@ std::vector<GitChange> parseGitStatus(std::string_view output)
|
||||
std::vector<GitChange> result;
|
||||
while(!output.empty())
|
||||
{
|
||||
const auto row=statusField(output);
|
||||
const auto row=nulField(output);
|
||||
if(row.size()<4 || row[2]!=' ') throw std::runtime_error("Git returned an invalid status record.");
|
||||
const auto code=row.substr(0,2);
|
||||
const auto path=statusPath(row.substr(3));
|
||||
std::wstring origin;
|
||||
if(code.find_first_of("RC")!=code.npos) origin=statusPath(statusField(output));
|
||||
if(code.find_first_of("RC")!=code.npos) origin=statusPath(nulField(output));
|
||||
if(code=="??") result.push_back({GitChangeKind::untracked,path,{},L"?"});
|
||||
else if(code=="DD" || code=="AA" || code.find('U')!=code.npos)
|
||||
result.push_back({GitChangeKind::unstaged,path,{},wide(std::string(code))});
|
||||
@@ -271,6 +316,175 @@ std::vector<GitChange> parseGitStatus(std::string_view output)
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
std::wstring gitRevision(std::string_view value)
|
||||
{
|
||||
if((value.size()!=40 && value.size()!=64) || value.find_first_not_of("0123456789abcdef")!=value.npos)
|
||||
throw std::runtime_error("Git returned an invalid object ID.");
|
||||
return {value.begin(),value.end()};
|
||||
}
|
||||
|
||||
void trimGitLine(std::string &line)
|
||||
{
|
||||
while(!line.empty() && (line.back()=='\n' || line.back()=='\r')) line.pop_back();
|
||||
}
|
||||
|
||||
GitCheckout readCheckout(const fs::path &git,const fs::path &root,std::stop_token stop)
|
||||
{
|
||||
auto branch=runGit(git,root,{L"symbolic-ref",L"--quiet",L"HEAD"},64*1024,stop);
|
||||
checkGit(branch,"Could not read the checked-out branch.",true);
|
||||
auto head=runGit(git,root,{L"rev-parse",L"--verify",L"--quiet",L"HEAD"},64*1024,stop);
|
||||
checkGit(head,"Could not read Git HEAD.",true);
|
||||
trimGitLine(branch.output);
|
||||
trimGitLine(head.output);
|
||||
return {branch.exitCode?std::wstring{}:wide(branch.output),
|
||||
head.exitCode?std::wstring{}:gitRevision(head.output)};
|
||||
}
|
||||
|
||||
std::vector<GitChange> readStatus(const fs::path &git,const fs::path &root,std::stop_token stop)
|
||||
{
|
||||
const auto status=runGit(git,root,{L"status",L"--porcelain=v1",L"-z",L"--untracked-files=all",L"--renames"},
|
||||
8*1024*1024,stop);
|
||||
checkGit(status,"Could not read Git worktree status.");
|
||||
return parseGitStatus(status.output);
|
||||
}
|
||||
|
||||
struct GitWorktreeFiles
|
||||
{
|
||||
fs::path index;
|
||||
std::vector<std::pair<fs::path,const char *>> operations;
|
||||
};
|
||||
|
||||
GitWorktreeFiles findWorktreeFiles(const GitChanges &worktree,std::stop_token stop)
|
||||
{
|
||||
constexpr std::pair<const wchar_t *,const char *> markers[]{
|
||||
{L"MERGE_HEAD","merge"},{L"CHERRY_PICK_HEAD","cherry-pick"},{L"REVERT_HEAD","revert"},
|
||||
{L"rebase-merge","rebase"},{L"rebase-apply","rebase or am"},{L"sequencer","sequencer"},
|
||||
{L"BISECT_START","bisect"}};
|
||||
std::vector<std::wstring> args{L"rev-parse",L"--path-format=absolute",L"--git-path",L"index"};
|
||||
for(const auto &[name,operation]:markers)
|
||||
{
|
||||
args.push_back(L"--git-path");
|
||||
args.push_back(name);
|
||||
}
|
||||
const auto paths=runGit(worktree.executable,worktree.root,args,256*1024,stop);
|
||||
checkGit(paths,"Could not find the worktree index.");
|
||||
std::string_view lines=paths.output;
|
||||
const auto next=[&]
|
||||
{
|
||||
if(lines.empty()) throw std::runtime_error("Git returned incomplete worktree metadata.");
|
||||
const auto separator=lines.find('\n');
|
||||
auto line=lines.substr(0,separator);
|
||||
lines.remove_prefix(separator==lines.npos?lines.size():separator+1);
|
||||
if(line.ends_with('\r')) line.remove_suffix(1);
|
||||
auto path=fs::path(wide(std::string(line))).make_preferred();
|
||||
if(!path.is_absolute()) throw std::runtime_error("Git returned an invalid worktree path.");
|
||||
return path;
|
||||
};
|
||||
GitWorktreeFiles result{next(),{}};
|
||||
for(const auto &[name,operation]:markers) result.operations.emplace_back(next(),operation);
|
||||
return result;
|
||||
}
|
||||
|
||||
struct WorktreeIndexLock
|
||||
{
|
||||
GitHandle file;
|
||||
explicit WorktreeIndexLock(const fs::path &index)
|
||||
{
|
||||
auto name=index;
|
||||
name+=L".lock";
|
||||
file.value=CreateFileW(name.c_str(),GENERIC_WRITE|DELETE,0,nullptr,CREATE_NEW,
|
||||
FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,nullptr);
|
||||
if(file.value!=INVALID_HANDLE_VALUE) return;
|
||||
const auto error=GetLastError();
|
||||
if(error==ERROR_FILE_EXISTS || error==ERROR_ALREADY_EXISTS || error==ERROR_SHARING_VIOLATION)
|
||||
throw std::runtime_error("Git index is locked. Finish the other Git operation, then refresh.");
|
||||
throw std::system_error(error,std::system_category(),"Could not lock the Git index");
|
||||
}
|
||||
WorktreeIndexLock(const WorktreeIndexLock &)=delete;
|
||||
};
|
||||
|
||||
struct WorktreeIndexCopy
|
||||
{
|
||||
fs::path path;
|
||||
explicit WorktreeIndexCopy(const fs::path &index)
|
||||
{
|
||||
GUID id{};
|
||||
wchar_t name[40]{};
|
||||
if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,static_cast<int>(std::size(name))))
|
||||
throw std::runtime_error("Could not name the temporary Git index.");
|
||||
path=index;
|
||||
path+=std::wstring(L".kswitcher-")+name;
|
||||
if(CopyFileW(index.c_str(),path.c_str(),TRUE)) return;
|
||||
const auto error=GetLastError();
|
||||
if(error!=ERROR_FILE_NOT_FOUND)
|
||||
throw std::system_error(error,std::system_category(),"Could not copy the worktree index");
|
||||
}
|
||||
WorktreeIndexCopy(const WorktreeIndexCopy &)=delete;
|
||||
~WorktreeIndexCopy()
|
||||
{
|
||||
DeleteFileW(path.c_str());
|
||||
const auto lock=path.native()+L".lock";
|
||||
DeleteFileW(lock.c_str());
|
||||
}
|
||||
void publish(const fs::path &index) const
|
||||
{
|
||||
if(!MoveFileExW(path.c_str(),index.c_str(),MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH))
|
||||
gitWindowsError("Could not replace the Git index");
|
||||
}
|
||||
};
|
||||
|
||||
void requireWritableWorktree(const GitChanges &worktree,const GitWorktreeFiles &paths,
|
||||
const GitCheckout &checkout,std::stop_token stop)
|
||||
{
|
||||
if(!checkout.ref.starts_with(L"refs/heads/"))
|
||||
throw std::runtime_error("This worktree has detached HEAD. Check out a branch before writing Git changes.");
|
||||
for(const auto &[path,operation]:paths.operations)
|
||||
{
|
||||
if(GetFileAttributesW(path.c_str())!=INVALID_FILE_ATTRIBUTES)
|
||||
throw std::runtime_error(std::string("A Git ")+operation+" is in progress. Finish it before writing changes.");
|
||||
const auto error=GetLastError();
|
||||
if(error!=ERROR_FILE_NOT_FOUND && error!=ERROR_PATH_NOT_FOUND)
|
||||
throw std::system_error(error,std::system_category(),"Could not check for active Git operations");
|
||||
}
|
||||
const auto conflicts=runGit(worktree.executable,worktree.root,{L"ls-files",L"--unmerged",L"-z"},2*1024*1024,stop);
|
||||
checkGit(conflicts,"Could not check Git index conflicts.");
|
||||
if(!conflicts.output.empty()) throw std::runtime_error("The Git index contains conflicts. Resolve them before writing changes.");
|
||||
}
|
||||
|
||||
GitCommitReview captureGitReview(const GitChanges &worktree,const GitCheckout &checkout,std::stop_token stop,
|
||||
bool listPaths)
|
||||
{
|
||||
GitCommitReview review{worktree.root,checkout,{},{}};
|
||||
std::vector<std::wstring> args{L"diff",L"--cached",L"--no-color",L"--no-ext-diff",L"--no-textconv",
|
||||
L"--ita-invisible-in-index",L"-z"};
|
||||
if(!checkout.revision.empty()) args.push_back(checkout.revision);
|
||||
args.push_back(L"--");
|
||||
auto identityArgs=args;
|
||||
identityArgs.insert(identityArgs.begin()+1,{L"--raw",L"--no-renames",L"--abbrev=64"});
|
||||
auto identity=runGit(worktree.executable,worktree.root,identityArgs,16*1024*1024,stop);
|
||||
checkGit(identity,"Could not read the staged snapshot.");
|
||||
review.stagedIdentity=std::move(identity.output);
|
||||
if(!listPaths || review.stagedIdentity.empty()) return review;
|
||||
args.insert(args.begin()+1,{L"--name-status",L"--find-renames"});
|
||||
const auto changed=runGit(worktree.executable,worktree.root,args,8*1024*1024,stop);
|
||||
checkGit(changed,"Could not list all staged paths.");
|
||||
std::string_view records=changed.output;
|
||||
while(!records.empty())
|
||||
{
|
||||
const auto flags=nulField(records);
|
||||
if(flags.empty()) throw std::runtime_error("Git returned an invalid staged-path record.");
|
||||
auto path=statusPath(nulField(records));
|
||||
std::wstring old;
|
||||
if(flags.front()=='R' || flags.front()=='C')
|
||||
{
|
||||
old=std::move(path);
|
||||
path=statusPath(nulField(records));
|
||||
}
|
||||
review.staged.push_back({GitChangeKind::staged,std::move(path),std::move(old),wide(std::string(flags))});
|
||||
}
|
||||
return review;
|
||||
}
|
||||
}
|
||||
|
||||
GitChanges readGitChanges(const std::filesystem::path &directory,std::stop_token stop)
|
||||
@@ -279,13 +493,11 @@ GitChanges readGitChanges(const std::filesystem::path &directory,std::stop_token
|
||||
result.executable=locateGit();
|
||||
auto root=runGit(result.executable,directory,{L"rev-parse",L"--show-toplevel"},64*1024,stop);
|
||||
checkGit(root,"This folder is not inside a Git worktree.");
|
||||
while(!root.output.empty() && (root.output.back()=='\r' || root.output.back()=='\n')) root.output.pop_back();
|
||||
trimGitLine(root.output);
|
||||
result.root=fs::path(wide(root.output)).make_preferred();
|
||||
if(!result.root.is_absolute()) throw std::runtime_error("Git returned an invalid worktree root.");
|
||||
const auto status=runGit(result.executable,result.root,
|
||||
{L"status",L"--porcelain=v1",L"-z",L"--untracked-files=all",L"--renames"},8*1024*1024,stop);
|
||||
checkGit(status,"Could not read Git worktree status.");
|
||||
result.entries=parseGitStatus(status.output);
|
||||
result.checkout=readCheckout(result.executable,result.root,stop);
|
||||
result.entries=readStatus(result.executable,result.root,stop);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -304,4 +516,225 @@ std::string readGitPatch(const std::filesystem::path &git,const std::filesystem:
|
||||
checkGit(patch,"Could not read this Git diff.",untracked);
|
||||
return std::move(patch.output);
|
||||
}
|
||||
|
||||
std::vector<GitBranch> readGitBranches(const std::filesystem::path &git,const std::filesystem::path &root,
|
||||
std::stop_token stop)
|
||||
{
|
||||
const auto refs=runGit(git,root,{L"for-each-ref",L"--sort=refname",
|
||||
L"--format=%(objectname)%00%(refname)%00%(HEAD)%00%(symref)",L"refs/heads",L"refs/remotes"},
|
||||
4*1024*1024,stop);
|
||||
checkGit(refs,"Could not read Git branches.");
|
||||
constexpr std::string_view localPrefix="refs/heads/",remotePrefix="refs/remotes/";
|
||||
std::vector<GitBranch> branches;
|
||||
bool foundHead=false;
|
||||
for(std::string_view remaining=refs.output;!remaining.empty();)
|
||||
{
|
||||
const auto newline=remaining.find('\n');
|
||||
auto line=remaining.substr(0,newline);
|
||||
remaining.remove_prefix(newline==remaining.npos?remaining.size():newline+1);
|
||||
if(line.ends_with('\r')) line.remove_suffix(1);
|
||||
if(line.empty()) continue;
|
||||
const auto revision=gitRevision(nulField(line));
|
||||
const auto ref=nulField(line);
|
||||
const bool current=nulField(line)=="*";
|
||||
if(!line.empty()) continue; // Skip aliases such as origin/HEAD.
|
||||
const bool remote=ref.starts_with(remotePrefix);
|
||||
if(!remote && !ref.starts_with(localPrefix)) continue;
|
||||
const auto branch=wide(std::string(ref.substr(remote?remotePrefix.size():localPrefix.size())));
|
||||
branches.push_back({wide(std::string(ref)),(current?L"* ":remote?L"Tracking · ":L"Local · ")+branch,
|
||||
revision,current});
|
||||
foundHead|=current;
|
||||
}
|
||||
if(!foundHead)
|
||||
{
|
||||
auto head=runGit(git,root,{L"rev-parse",L"--verify",L"--quiet",L"HEAD"},64*1024,stop);
|
||||
checkGit(head,"Could not read Git HEAD.",true);
|
||||
if(!head.exitCode)
|
||||
{
|
||||
while(!head.output.empty() && (head.output.back()=='\n' || head.output.back()=='\r')) head.output.pop_back();
|
||||
branches.insert(branches.begin(),{L"HEAD",L"* Detached HEAD",gitRevision(head.output),true});
|
||||
}
|
||||
}
|
||||
return branches;
|
||||
}
|
||||
|
||||
GitHistoryPage readGitHistory(const std::filesystem::path &git,const std::filesystem::path &root,
|
||||
const std::wstring &revision,size_t offset,std::stop_token stop)
|
||||
{
|
||||
constexpr size_t pageSize=50;
|
||||
const auto log=runGit(git,root,{L"log",L"--no-decorate",L"--no-notes",L"--no-show-signature",
|
||||
L"--encoding=UTF-8",L"--date=short",L"--format=%H%x00%h%x00%ad%x00%s",L"-z",
|
||||
L"--max-count="+std::to_wstring(pageSize+1),L"--skip="+std::to_wstring(offset),revision,L"--"},
|
||||
2*1024*1024,stop);
|
||||
checkGit(log,"Could not read Git history.");
|
||||
GitHistoryPage page;
|
||||
std::string_view records=log.output;
|
||||
while(!records.empty() && page.commits.size()<pageSize)
|
||||
page.commits.push_back({gitRevision(nulField(records)),wide(std::string(nulField(records))),
|
||||
wide(std::string(nulField(records))),wide(std::string(nulField(records)))});
|
||||
page.more=!records.empty();
|
||||
return page;
|
||||
}
|
||||
|
||||
std::string readGitCommit(const std::filesystem::path &git,const std::filesystem::path &root,
|
||||
const std::wstring &revision,std::stop_token stop)
|
||||
{
|
||||
const auto metadata=runGit(git,root,{L"log",L"-1",L"--no-decorate",L"--no-notes",L"--no-show-signature",
|
||||
L"--encoding=UTF-8",L"--format=%H%x00%an%x00%ae%x00%aI%x00%B",L"-z",revision,L"--"},2*1024*1024,stop);
|
||||
checkGit(metadata,"Could not read the Git commit.");
|
||||
std::string_view parts=metadata.output;
|
||||
const auto id=nulField(parts);
|
||||
const auto author=nulField(parts);
|
||||
const auto email=nulField(parts);
|
||||
const auto date=nulField(parts);
|
||||
const auto message=nulField(parts);
|
||||
std::string text="Commit ";
|
||||
text.append(id).append("\nAuthor ").append(author);
|
||||
if(!email.empty()) text.append(" <").append(email).push_back('>');
|
||||
text.append("\nDate ").append(date).append("\n\n").append(message);
|
||||
while(!text.empty() && (text.back()=='\r' || text.back()=='\n')) text.pop_back();
|
||||
|
||||
const auto changes=runGit(git,root,{L"show",L"--no-notes",L"--no-show-signature",L"--format=",L"--name-status",
|
||||
L"-z",L"--root",L"--diff-merges=first-parent",L"--find-renames",L"--no-ext-diff",L"--no-textconv",
|
||||
revision,L"--"},2*1024*1024,stop);
|
||||
checkGit(changes,"Could not read changed paths.");
|
||||
text+="\n\nChanged paths\n";
|
||||
if(changes.output.empty()) text+="No changed paths.\n";
|
||||
std::string_view records=changes.output;
|
||||
while(!records.empty())
|
||||
{
|
||||
const auto code=nulField(records);
|
||||
if(code.empty()) throw std::runtime_error("Git returned an invalid changed-path record.");
|
||||
text.append(code).append(" ").append(nulField(records));
|
||||
if(code.front()=='R' || code.front()=='C')
|
||||
text.append(" → ").append(nulField(records));
|
||||
text.push_back('\n');
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
void changeGitIndex(const GitChanges &worktree,const GitChange &entry,bool replaceStaged,std::stop_token stop)
|
||||
{
|
||||
const auto paths=findWorktreeFiles(worktree,stop);
|
||||
const WorktreeIndexLock lock(paths.index);
|
||||
const auto checkout=readCheckout(worktree.executable,worktree.root,stop);
|
||||
requireWritableWorktree(worktree,paths,checkout,stop);
|
||||
if(checkout!=worktree.checkout)
|
||||
throw std::runtime_error("The checked-out branch or commit changed. Review the refreshed Git changes.");
|
||||
const auto entries=readStatus(worktree.executable,worktree.root,stop);
|
||||
if(std::find(entries.begin(),entries.end(),entry)==entries.end())
|
||||
throw std::runtime_error("The selected change is no longer current. Review the refreshed Git changes.");
|
||||
|
||||
const bool stage=entry.kind!=GitChangeKind::staged;
|
||||
const bool rename=entry.flags.starts_with(L"R") || entry.flags.starts_with(L"C");
|
||||
const auto overlaps=[&](const GitChange &other)
|
||||
{
|
||||
return other.kind==GitChangeKind::staged && (other.path==entry.path || other.oldPath==entry.path ||
|
||||
(rename && !entry.oldPath.empty() && (other.path==entry.oldPath || other.oldPath==entry.oldPath)));
|
||||
};
|
||||
if(stage && !replaceStaged && std::any_of(entries.begin(),entries.end(),overlaps))
|
||||
throw std::runtime_error("The selected path already has staged changes. Review and confirm the replacement.");
|
||||
if(stage)
|
||||
{
|
||||
const auto attributes=GetFileAttributesW((worktree.root/fs::path(entry.path)).c_str());
|
||||
if(entry.path.ends_with(L'/') || (attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY)))
|
||||
{
|
||||
const auto indexed=runGit(worktree.executable,worktree.root,{L"ls-files",L"--stage",L"--",entry.path},
|
||||
256*1024,stop);
|
||||
checkGit(indexed,"Could not identify the selected directory.");
|
||||
if(!indexed.output.starts_with("160000 "))
|
||||
throw std::runtime_error("This entry is a directory. Stage individual files or an existing submodule.");
|
||||
}
|
||||
}
|
||||
const WorktreeIndexCopy pending(paths.index);
|
||||
std::vector<std::wstring> args;
|
||||
if(stage) args={L"add",L"-A",L"--"};
|
||||
else if(checkout.revision.empty()) args={L"rm",L"--cached",L"-f",L"--ignore-unmatch",L"--"};
|
||||
else args={L"restore",L"--staged",L"--source="+checkout.revision,L"--"};
|
||||
if(rename && !entry.oldPath.empty()) args.push_back(entry.oldPath);
|
||||
args.push_back(entry.path);
|
||||
const auto result=runGit(worktree.executable,worktree.root,args,1024*1024,stop,{.index=pending.path});
|
||||
checkGit(result,stage?"Could not stage the selected path.":"Could not unstage the selected path.");
|
||||
if(readCheckout(worktree.executable,worktree.root,stop)!=checkout || stop.stop_requested())
|
||||
throw std::runtime_error("The checkout changed while Git was working. Review the refreshed Git changes.");
|
||||
requireWritableWorktree(worktree,paths,checkout,stop);
|
||||
if(stop.stop_requested()) throw std::runtime_error("Git request canceled.");
|
||||
pending.publish(paths.index);
|
||||
}
|
||||
|
||||
GitCommitReview reviewGitCommit(const GitChanges &worktree,std::stop_token stop)
|
||||
{
|
||||
const auto paths=findWorktreeFiles(worktree,stop);
|
||||
const WorktreeIndexLock lock(paths.index);
|
||||
const auto checkout=readCheckout(worktree.executable,worktree.root,stop);
|
||||
requireWritableWorktree(worktree,paths,checkout,stop);
|
||||
auto review=captureGitReview(worktree,checkout,stop,true);
|
||||
if(readCheckout(worktree.executable,worktree.root,stop)!=checkout)
|
||||
throw std::runtime_error("The checkout changed while reading the staged paths. Open a new review.");
|
||||
if(review.staged.empty()) throw std::runtime_error("Stage at least one change before committing.");
|
||||
return review;
|
||||
}
|
||||
|
||||
std::wstring createGitCommit(const GitChanges &worktree,const GitCommitReview &review,
|
||||
const std::wstring &message,std::stop_token stop)
|
||||
{
|
||||
if(message.find_first_not_of(L" \t\r\n")==message.npos)
|
||||
throw std::runtime_error("Enter a commit message.");
|
||||
if(worktree.root!=review.root || review.stagedIdentity.empty())
|
||||
throw std::runtime_error("The reviewed worktree changed. Open a new review.");
|
||||
const auto paths=findWorktreeFiles(worktree,stop);
|
||||
const WorktreeIndexLock lock(paths.index);
|
||||
const auto checkout=readCheckout(worktree.executable,worktree.root,stop);
|
||||
requireWritableWorktree(worktree,paths,checkout,stop);
|
||||
if(checkout!=review.checkout || captureGitReview(worktree,checkout,stop,false).stagedIdentity!=review.stagedIdentity)
|
||||
throw std::runtime_error("The checkout or staged changes changed after review. Review them again. The message was kept.");
|
||||
|
||||
const WorktreeIndexCopy pending(paths.index);
|
||||
auto tree=runGit(worktree.executable,worktree.root,{L"write-tree"},64*1024,stop,{.index=pending.path});
|
||||
checkGit(tree,"Could not write the reviewed Git tree.");
|
||||
trimGitLine(tree.output);
|
||||
const auto treeId=gitRevision(tree.output);
|
||||
auto signing=runGit(worktree.executable,worktree.root,{L"config",L"--type=bool",L"--get",L"commit.gpgSign"},64*1024,stop);
|
||||
checkGit(signing,"Could not read Git signing settings.",true);
|
||||
trimGitLine(signing.output);
|
||||
std::vector<std::wstring> args{L"commit-tree",treeId,L"-F",L"-"};
|
||||
if(!checkout.revision.empty()) args.insert(args.end(),{L"-p",checkout.revision});
|
||||
if(signing.output=="true") args.push_back(L"-S");
|
||||
auto contents=utf8(message);
|
||||
for(size_t pos=0;(pos=contents.find('\r',pos))!=contents.npos;)
|
||||
{
|
||||
if(pos+1<contents.size() && contents[pos+1]=='\n') contents.erase(pos,1);
|
||||
else contents[pos++]='\n';
|
||||
}
|
||||
auto created=runGit(worktree.executable,worktree.root,args,64*1024,stop,{.input=contents,.timeout=120000});
|
||||
checkGit(created,"Could not create the commit. Check your Git author identity and signing settings.");
|
||||
trimGitLine(created.output);
|
||||
const auto commit=gitRevision(created.output);
|
||||
const auto expected=checkout.revision.empty()?std::string(commit.size(),'0'):utf8(checkout.revision);
|
||||
const std::string transaction="start\nupdate HEAD "+created.output+" "+expected+"\nprepare\n";
|
||||
try
|
||||
{
|
||||
const auto update=runGit(worktree.executable,worktree.root,
|
||||
{L"-c",L"core.hooksPath=NUL",L"update-ref",L"-m",L"KSwitcher Files: local commit",L"--stdin"},
|
||||
64*1024,stop,{.input=transaction,.afterPrepare=[&] {
|
||||
// Git holds HEAD and its referent after prepare, while the index remains locked by Files.
|
||||
if(readCheckout(worktree.executable,worktree.root,stop)!=checkout)
|
||||
throw std::runtime_error("The checkout changed after review. Review it again. The message was kept.");
|
||||
requireWritableWorktree(worktree,paths,checkout,stop);
|
||||
}});
|
||||
checkGit(update,"Could not update the checked-out branch. Refresh and review the staged changes.");
|
||||
if(update.output.find("commit: ok")==std::string::npos)
|
||||
throw std::runtime_error("Git did not confirm the branch update.");
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(readCheckout(worktree.executable,worktree.root,{})==GitCheckout{checkout.ref,commit}) return commit;
|
||||
}
|
||||
catch(const std::exception &) {}
|
||||
throw;
|
||||
}
|
||||
return commit;
|
||||
}
|
||||
}
|
||||
@@ -17,13 +17,55 @@ struct GitChange
|
||||
bool operator==(const GitChange &) const = default;
|
||||
};
|
||||
|
||||
struct GitCheckout
|
||||
{
|
||||
std::wstring ref, revision;
|
||||
bool operator==(const GitCheckout &) const = default;
|
||||
};
|
||||
|
||||
struct GitChanges
|
||||
{
|
||||
std::filesystem::path executable, root;
|
||||
std::vector<GitChange> entries;
|
||||
GitCheckout checkout;
|
||||
};
|
||||
|
||||
struct GitBranch
|
||||
{
|
||||
std::wstring ref, label, revision;
|
||||
bool current{};
|
||||
};
|
||||
|
||||
struct GitCommit
|
||||
{
|
||||
std::wstring revision, abbreviated, date, subject;
|
||||
};
|
||||
|
||||
struct GitHistoryPage
|
||||
{
|
||||
std::vector<GitCommit> commits;
|
||||
bool more{};
|
||||
};
|
||||
|
||||
struct GitCommitReview
|
||||
{
|
||||
std::filesystem::path root;
|
||||
GitCheckout checkout;
|
||||
std::vector<GitChange> staged;
|
||||
std::string stagedIdentity;
|
||||
};
|
||||
|
||||
GitChanges readGitChanges(const std::filesystem::path &directory,std::stop_token stop);
|
||||
std::string readGitPatch(const std::filesystem::path &git,const std::filesystem::path &root,
|
||||
const GitChange &change,std::stop_token stop);
|
||||
std::vector<GitBranch> readGitBranches(const std::filesystem::path &git,const std::filesystem::path &root,
|
||||
std::stop_token stop);
|
||||
GitHistoryPage readGitHistory(const std::filesystem::path &git,const std::filesystem::path &root,
|
||||
const std::wstring &revision,size_t offset,std::stop_token stop);
|
||||
std::string readGitCommit(const std::filesystem::path &git,const std::filesystem::path &root,
|
||||
const std::wstring &revision,std::stop_token stop);
|
||||
void changeGitIndex(const GitChanges &worktree,const GitChange &entry,bool replaceStaged,std::stop_token stop);
|
||||
GitCommitReview reviewGitCommit(const GitChanges &worktree,std::stop_token stop);
|
||||
std::wstring createGitCommit(const GitChanges &worktree,const GitCommitReview &review,
|
||||
const std::wstring &message,std::stop_token stop);
|
||||
}
|
||||
+547
-55
@@ -1,24 +1,55 @@
|
||||
using ks::files::GitChange;
|
||||
using ks::files::GitChangeKind;
|
||||
using ks::files::GitChanges;
|
||||
using ks::files::GitBranch;
|
||||
using ks::files::GitCommit;
|
||||
using ks::files::GitCommitReview;
|
||||
using ks::files::GitHistoryPage;
|
||||
|
||||
struct GitPreview
|
||||
{
|
||||
std::wstring heading;
|
||||
std::variant<GitChange,std::wstring> item;
|
||||
};
|
||||
|
||||
struct GitHistoryUpdate
|
||||
{
|
||||
std::optional<std::vector<GitBranch>> branches;
|
||||
GitHistoryPage page;
|
||||
size_t branch=0;
|
||||
};
|
||||
|
||||
struct GitChangesView
|
||||
{
|
||||
HWND host{},heading{},filterLabel{},filter{},list{},status{},hints{},preview{};
|
||||
HWND host{},heading{},switchView{},filterLabel{},filter{},branchPicker{},list{},status{},hints{},preview{},moreButton{};
|
||||
HWND indexButton{},commitButton{};
|
||||
fs::path folder;
|
||||
GitChanges data;
|
||||
std::future<GitChanges> refresh;
|
||||
std::future<std::string> diff;
|
||||
std::stop_source stopRefresh,stopDiff;
|
||||
ULONGLONG diffAt{};
|
||||
std::optional<GitChange> requested;
|
||||
std::future<std::string> previewTask;
|
||||
std::stop_source stopRefresh,stopPreview;
|
||||
ULONGLONG previewAt{};
|
||||
std::optional<GitPreview> requested;
|
||||
std::string failure;
|
||||
bool historyMode{},moreHistory{};
|
||||
std::vector<GitBranch> branches;
|
||||
std::vector<GitCommit> commits;
|
||||
size_t branchIndex{};
|
||||
std::future<GitHistoryUpdate> historyTask;
|
||||
std::stop_source stopHistory;
|
||||
std::string historyFailure;
|
||||
std::future<GitCommitReview> commitReview;
|
||||
std::future<std::wstring> mutation;
|
||||
std::stop_source stopMutation;
|
||||
std::wstring commitDraft,operation,writeStatus;
|
||||
bool promptingWrite{};
|
||||
};
|
||||
|
||||
std::unique_ptr<GitChangesView> gitChangesView;
|
||||
constexpr wchar_t gitChangesClass[]=L"KSwitcher.Files.GitChanges";
|
||||
constexpr UINT_PTR gitChangesTimer=1;
|
||||
constexpr int gitHeading=570,gitFilter=571,gitList=572,gitStatus=573;
|
||||
constexpr int gitHeading=570,gitFilter=571,gitList=572,gitStatus=573,gitSwitch=574,gitBranch=575,gitMore=576;
|
||||
constexpr int gitIndexAction=577,gitCommitAction=578;
|
||||
|
||||
const wchar_t *gitChangeKindName(GitChangeKind kind)
|
||||
{
|
||||
@@ -39,34 +70,98 @@ const GitChange *selectedGitChange(const GitChangesView &view)
|
||||
return index>=0 && size_t(index)<view.data.entries.size()?&view.data.entries[index]:nullptr;
|
||||
}
|
||||
|
||||
const GitCommit *selectedGitCommit(const GitChangesView &view)
|
||||
{
|
||||
const auto row=SendMessageW(view.list,LB_GETCURSEL,0,0);
|
||||
if(row==LB_ERR) return nullptr;
|
||||
const auto index=SendMessageW(view.list,LB_GETITEMDATA,row,0);
|
||||
return index>=0 && size_t(index)<view.commits.size()?&view.commits[index]:nullptr;
|
||||
}
|
||||
|
||||
std::wstring gitChangePathLabel(const GitChange &entry)
|
||||
{
|
||||
return entry.oldPath.empty()?entry.path:entry.path+L" ← "+entry.oldPath;
|
||||
}
|
||||
|
||||
std::wstring gitCheckoutLabel(const ks::files::GitCheckout &checkout)
|
||||
{
|
||||
constexpr std::wstring_view prefix=L"refs/heads/";
|
||||
if(!checkout.ref.starts_with(prefix)) return L"Detached HEAD";
|
||||
auto label=checkout.ref.substr(prefix.size());
|
||||
if(checkout.revision.empty()) label+=L" (first commit)";
|
||||
return label;
|
||||
}
|
||||
|
||||
bool gitActionPending(const GitChangesView &view)
|
||||
{
|
||||
return view.commitReview.valid() || view.mutation.valid() || view.promptingWrite;
|
||||
}
|
||||
|
||||
void updateGitActionButtons(GitChangesView &view)
|
||||
{
|
||||
const bool ready=!view.historyMode && !view.data.root.empty() && !view.refresh.valid() && !gitActionPending(view);
|
||||
const auto *entry=view.historyMode?nullptr:selectedGitChange(view);
|
||||
SetWindowTextW(view.indexButton,entry && entry->kind==GitChangeKind::staged?L"Unstage":L"Stage");
|
||||
EnableWindow(view.indexButton,ready && entry);
|
||||
EnableWindow(view.commitButton,ready);
|
||||
EnableWindow(view.switchView,!view.data.root.empty() && !view.refresh.valid() && !gitActionPending(view));
|
||||
}
|
||||
|
||||
void updateGitChangesStatus(GitChangesView &view,LRESULT shown=-1)
|
||||
{
|
||||
if(gitActionPending(view)) {SetWindowTextW(view.status,view.operation.c_str());return;}
|
||||
if(view.refresh.valid()) {SetWindowTextW(view.status,L"Reading Git changes…");return;}
|
||||
if(!view.failure.empty()) {SetWindowTextW(view.status,L"Could not read Git changes.");return;}
|
||||
if(shown<0) shown=SendMessageW(view.list,LB_GETCOUNT,0,0);
|
||||
const auto count=view.data.entries.size();
|
||||
const std::wstring summary=!count?L"No Git changes.":shown<=0?L"No paths match the filter.":
|
||||
std::to_wstring(shown)+(static_cast<size_t>(shown)==count?L"":L" of "+std::to_wstring(count))+L" changes";
|
||||
SetWindowTextW(view.status,(view.writeStatus.empty()?summary:view.writeStatus+L" · "+summary).c_str());
|
||||
}
|
||||
|
||||
std::wstring gitDiffHeading(const GitChange &entry)
|
||||
{
|
||||
return std::wstring(gitChangeKindName(entry.kind))+L" diff · "+entry.path;
|
||||
}
|
||||
|
||||
void queueGitDiff(GitChangesView &view)
|
||||
void queueGitPreview(GitChangesView &view)
|
||||
{
|
||||
view.stopDiff.request_stop();
|
||||
view.diff={};
|
||||
view.diffAt=0;
|
||||
updateGitActionButtons(view);
|
||||
view.stopPreview.request_stop();
|
||||
view.previewTask={};
|
||||
view.previewAt=0;
|
||||
view.requested.reset();
|
||||
if(view.historyMode)
|
||||
{
|
||||
if(const auto *commit=selectedGitCommit(view))
|
||||
{
|
||||
view.requested=GitPreview{L"Commit · "+commit->abbreviated,commit->revision};
|
||||
view.previewAt=GetTickCount64()+100;
|
||||
ks::files::previewQuickViewText(view.preview,view.requested->heading+L" · Loading…",{});
|
||||
}
|
||||
else if(!view.historyFailure.empty())
|
||||
ks::files::previewQuickViewText(view.preview,L"Git history failed",view.historyFailure);
|
||||
else ks::files::previewQuickViewText(view.preview,
|
||||
view.historyTask.valid()?L"Commit · Reading history…":L"Commit · Select a commit",{});
|
||||
return;
|
||||
}
|
||||
if(view.refresh.valid())
|
||||
{
|
||||
ks::files::previewQuickViewDiff(view.preview,L"Diff · Reading Git changes…",{});
|
||||
ks::files::previewQuickViewText(view.preview,L"Diff · Reading Git changes…",{});
|
||||
return;
|
||||
}
|
||||
if(!view.failure.empty())
|
||||
{
|
||||
ks::files::previewQuickViewDiff(view.preview,L"Git status failed",view.failure);
|
||||
ks::files::previewQuickViewText(view.preview,L"Git status failed",view.failure);
|
||||
return;
|
||||
}
|
||||
if(const auto *entry=selectedGitChange(view))
|
||||
{
|
||||
view.requested=*entry;
|
||||
view.diffAt=GetTickCount64()+100;
|
||||
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*entry)+L" · Loading…",{});
|
||||
view.requested=GitPreview{gitDiffHeading(*entry),*entry};
|
||||
view.previewAt=GetTickCount64()+100;
|
||||
ks::files::previewQuickViewText(view.preview,view.requested->heading+L" · Loading…",{});
|
||||
}
|
||||
else ks::files::previewQuickViewDiff(view.preview,L"Diff · Select a change",{});
|
||||
else ks::files::previewQuickViewText(view.preview,L"Diff · Select a change",{});
|
||||
}
|
||||
|
||||
void renderGitChanges(GitChangesView &view,std::optional<GitChange> previous={})
|
||||
@@ -90,7 +185,7 @@ void renderGitChanges(GitChangesView &view,std::optional<GitChange> previous={})
|
||||
state.resize(10,L' ');
|
||||
state+=entry.flags;
|
||||
state.resize(13,L' ');
|
||||
const auto label=state+(entry.oldPath.empty()?entry.path:entry.path+L" ← "+entry.oldPath);
|
||||
const auto label=state+gitChangePathLabel(entry);
|
||||
const auto row=SendMessageW(view.list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
if(row<0) continue;
|
||||
++count;
|
||||
@@ -101,18 +196,13 @@ void renderGitChanges(GitChangesView &view,std::optional<GitChange> previous={})
|
||||
SendMessageW(view.list,WM_SETREDRAW,TRUE,0);
|
||||
InvalidateRect(view.list,nullptr,TRUE);
|
||||
InvalidateRect(view.host,nullptr,FALSE);
|
||||
const auto total=view.data.entries.size();
|
||||
const auto status=view.refresh.valid()?std::wstring(L"Reading Git changes…"):
|
||||
!view.failure.empty()?L"Could not read Git changes.":
|
||||
!total?L"No Git changes.":!count?L"No paths match the filter.":
|
||||
std::to_wstring(count)+(query.empty()?L"":L" of "+std::to_wstring(total))+L" changes";
|
||||
SetWindowTextW(view.status,status.c_str());
|
||||
queueGitDiff(view);
|
||||
updateGitChangesStatus(view,count);
|
||||
queueGitPreview(view);
|
||||
}
|
||||
|
||||
void refreshGitChanges(GitChangesView &view)
|
||||
{
|
||||
if(view.refresh.valid()) return;
|
||||
if(view.refresh.valid() || gitActionPending(view)) return;
|
||||
view.failure.clear();
|
||||
view.stopRefresh=std::stop_source{};
|
||||
try
|
||||
@@ -123,8 +213,8 @@ void refreshGitChanges(GitChangesView &view)
|
||||
auto pending=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
view.refresh=std::move(pending);
|
||||
SetWindowTextW(view.status,L"Reading Git changes…");
|
||||
queueGitDiff(view);
|
||||
updateGitChangesStatus(view);
|
||||
queueGitPreview(view);
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
@@ -133,9 +223,313 @@ void refreshGitChanges(GitChangesView &view)
|
||||
}
|
||||
}
|
||||
|
||||
struct GitCommitPrompt
|
||||
{
|
||||
const GitCommitReview &review;
|
||||
std::wstring message;
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK gitCommitDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
constexpr int branch=594,summary=595,staged=596,body=598,feedback=599,footer=600;
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &prompt=*reinterpret_cast<GitCommitPrompt *>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareTextDialog(dialog);
|
||||
layoutDialogContent(dialog,branch);
|
||||
SetDlgItemTextW(dialog,branch,(L"Branch "+gitCheckoutLabel(prompt.review.checkout)).c_str());
|
||||
SetDlgItemTextW(dialog,summary,(std::to_wstring(prompt.review.staged.size())+L" staged changes · all paths").c_str());
|
||||
const auto list=GetDlgItem(dialog,staged);
|
||||
for(const auto &entry:prompt.review.staged)
|
||||
{
|
||||
const auto label=entry.flags+L" "+gitChangePathLabel(entry);
|
||||
SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
}
|
||||
const auto bounds=dialogControlBounds(dialog,staged);
|
||||
SetWindowPos(list,nullptr,0,0,std::max(1L,bounds.right-bounds.left-scrollBarWidth(list)),
|
||||
bounds.bottom-bounds.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
installScrollBar(list,dialog);
|
||||
SendDlgItemMessageW(dialog,body,EM_SETLIMITTEXT,16000,0);
|
||||
SetDlgItemTextW(dialog,body,prompt.message.c_str());
|
||||
layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL});
|
||||
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
|
||||
SetFocus(GetDlgItem(dialog,body));
|
||||
return FALSE;
|
||||
}
|
||||
if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDCANCEL || LOWORD(wp)==IDOK)))
|
||||
{
|
||||
auto &prompt=*reinterpret_cast<GitCommitPrompt *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
prompt.message=dialogFieldText(GetDlgItem(dialog,body));
|
||||
const bool submit=message==WM_COMMAND && LOWORD(wp)==IDOK;
|
||||
if(submit && prompt.message.find_first_not_of(L" \t\r\n")==prompt.message.npos)
|
||||
{
|
||||
SetDlgItemTextW(dialog,feedback,L"Enter a commit message.");
|
||||
ShowWindow(GetDlgItem(dialog,feedback),SW_SHOWNA);
|
||||
SetFocus(GetDlgItem(dialog,body));
|
||||
return TRUE;
|
||||
}
|
||||
FilesModalDialog::finish(dialog,submit?IDOK:IDCANCEL);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_COMMAND && LOWORD(wp)==body && HIWORD(wp)==EN_CHANGE)
|
||||
{
|
||||
ShowWindow(GetDlgItem(dialog,feedback),SW_HIDE);
|
||||
SetDlgItemTextW(dialog,feedback,L"");
|
||||
return TRUE;
|
||||
}
|
||||
return paintCopyDialog(dialog,message,wp,lp,L" Commit staged changes ",false,{footer},false,GetDlgItem(dialog,staged));
|
||||
}
|
||||
|
||||
GitChanges gitWorktreeTarget(const GitChangesView &view)
|
||||
{
|
||||
return {view.data.executable,view.data.root,{},view.data.checkout};
|
||||
}
|
||||
|
||||
bool gitActionAvailable(const GitChangesView &view)
|
||||
{
|
||||
return !view.historyMode && !view.refresh.valid() && !gitActionPending(view) && !view.data.root.empty();
|
||||
}
|
||||
|
||||
void showGitWriteError(GitChangesView &view,const std::exception &error)
|
||||
{
|
||||
std::wstring detail;
|
||||
if(const auto *system=dynamic_cast<const std::system_error *>(&error)) detail=fileError(*system);
|
||||
else
|
||||
{
|
||||
try {detail=ks::wide(error.what());}
|
||||
catch(const std::exception &) {detail=L"Git returned an error in an unsupported encoding.";}
|
||||
}
|
||||
view.promptingWrite=true;
|
||||
updateGitActionButtons(view);
|
||||
showFilesNotice(GetParent(view.host),detail.c_str(),L"Git operation failed",{.tone=FilesNoticeTone::warning});
|
||||
view.promptingWrite=false;
|
||||
view.writeStatus=L"Git operation failed";
|
||||
refreshGitChanges(view);
|
||||
}
|
||||
|
||||
void runGitMutation(GitChangesView &view,std::wstring operation,
|
||||
std::function<std::wstring(std::stop_token)> action)
|
||||
{
|
||||
view.stopMutation=std::stop_source{};
|
||||
view.operation=std::move(operation);
|
||||
try
|
||||
{
|
||||
std::packaged_task<std::wstring()> task([action=std::move(action),stop=view.stopMutation.get_token()] {
|
||||
return action(stop);
|
||||
});
|
||||
auto pending=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
view.mutation=std::move(pending);
|
||||
updateGitActionButtons(view);
|
||||
updateGitChangesStatus(view);
|
||||
}
|
||||
catch(const std::exception &error) {showGitWriteError(view,error);}
|
||||
}
|
||||
|
||||
void changeSelectedGitIndex(GitChangesView &view)
|
||||
{
|
||||
if(!gitActionAvailable(view)) return;
|
||||
const auto *selected=selectedGitChange(view);
|
||||
if(!selected) return;
|
||||
const auto entry=*selected;
|
||||
const bool stage=entry.kind!=GitChangeKind::staged;
|
||||
const bool replace=stage && std::any_of(view.data.entries.begin(),view.data.entries.end(),[&](const auto &other) {
|
||||
return other.kind==GitChangeKind::staged && (other.path==entry.path || other.oldPath==entry.path ||
|
||||
(!entry.oldPath.empty() && (other.path==entry.oldPath || other.oldPath==entry.oldPath)));
|
||||
});
|
||||
if(replace)
|
||||
{
|
||||
view.promptingWrite=true;
|
||||
updateGitActionButtons(view);
|
||||
const auto message=L"Replace the staged version of "+entry.path+L" with the current working version?";
|
||||
const auto answer=showFilesNotice(GetParent(view.host),message.c_str(),L"Replace staged changes",
|
||||
{.confirm=true,.tone=FilesNoticeTone::warning});
|
||||
view.promptingWrite=false;
|
||||
updateGitActionButtons(view);
|
||||
if(answer!=IDYES) return;
|
||||
}
|
||||
runGitMutation(view,stage?L"Staging the selected path…":L"Unstaging the selected path…",
|
||||
[worktree=gitWorktreeTarget(view),entry,replace,stage](std::stop_token stop) {
|
||||
ks::files::changeGitIndex(worktree,entry,replace,stop);
|
||||
return stage?std::wstring(L"Path staged"):std::wstring(L"Path unstaged");
|
||||
});
|
||||
}
|
||||
|
||||
void openGitCommitReview(GitChangesView &view)
|
||||
{
|
||||
if(!gitActionAvailable(view)) return;
|
||||
view.stopMutation=std::stop_source{};
|
||||
view.operation=L"Reading all staged changes…";
|
||||
try
|
||||
{
|
||||
std::packaged_task<GitCommitReview()> task([worktree=gitWorktreeTarget(view),stop=view.stopMutation.get_token()] {
|
||||
return ks::files::reviewGitCommit(worktree,stop);
|
||||
});
|
||||
auto pending=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
view.commitReview=std::move(pending);
|
||||
updateGitActionButtons(view);
|
||||
updateGitChangesStatus(view);
|
||||
}
|
||||
catch(const std::exception &error) {showGitWriteError(view,error);}
|
||||
}
|
||||
|
||||
void finishGitCommitReview(GitChangesView &view)
|
||||
{
|
||||
try
|
||||
{
|
||||
auto review=view.commitReview.get();
|
||||
GitCommitPrompt prompt{review,view.commitDraft};
|
||||
view.promptingWrite=true;
|
||||
const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(126),
|
||||
GetParent(view.host),gitCommitDialog,reinterpret_cast<LPARAM>(&prompt));
|
||||
view.promptingWrite=false;
|
||||
view.commitDraft=std::move(prompt.message);
|
||||
if(answer==IDOK)
|
||||
runGitMutation(view,L"Creating the reviewed local commit…",
|
||||
[worktree=gitWorktreeTarget(view),review=std::move(review),message=view.commitDraft](std::stop_token stop) {
|
||||
return L"Commit "+ks::files::createGitCommit(worktree,review,message,stop).substr(0,12);
|
||||
});
|
||||
else
|
||||
{
|
||||
updateGitActionButtons(view);
|
||||
updateGitChangesStatus(view);
|
||||
}
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
view.promptingWrite=false;
|
||||
showGitWriteError(view,error);
|
||||
}
|
||||
}
|
||||
|
||||
void finishGitMutation(GitChangesView &view)
|
||||
{
|
||||
try
|
||||
{
|
||||
view.writeStatus=view.mutation.get();
|
||||
if(view.writeStatus.starts_with(L"Commit ")) view.commitDraft.clear();
|
||||
refreshGitChanges(view);
|
||||
}
|
||||
catch(const std::exception &error) {showGitWriteError(view,error);}
|
||||
}
|
||||
|
||||
void updateGitHistoryStatus(GitChangesView &view)
|
||||
{
|
||||
const auto status=view.historyTask.valid()?std::wstring(L"Reading Git history…"):
|
||||
!view.historyFailure.empty()?L"Could not read Git history.":
|
||||
view.commits.empty()?L"No commits yet.":std::to_wstring(view.commits.size())+L" commits";
|
||||
SetWindowTextW(view.status,status.c_str());
|
||||
EnableWindow(view.moreButton,view.moreHistory && !view.historyTask.valid());
|
||||
}
|
||||
|
||||
void renderGitHistory(GitChangesView &view,std::wstring_view preserve={},LRESULT top=0)
|
||||
{
|
||||
SendMessageW(view.list,WM_SETREDRAW,FALSE,0);
|
||||
SendMessageW(view.list,LB_RESETCONTENT,0,0);
|
||||
LRESULT selected=0;
|
||||
for(size_t i=0;i<view.commits.size();++i)
|
||||
{
|
||||
const auto &commit=view.commits[i];
|
||||
const auto label=commit.date+L" "+commit.abbreviated+L" "+commit.subject;
|
||||
const auto row=SendMessageW(view.list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()));
|
||||
if(row<0) continue;
|
||||
SendMessageW(view.list,LB_SETITEMDATA,row,i);
|
||||
if(preserve==commit.revision) selected=row;
|
||||
}
|
||||
if(!view.commits.empty())
|
||||
{
|
||||
SendMessageW(view.list,LB_SETCURSEL,selected,0);
|
||||
if(top>0) SendMessageW(view.list,LB_SETTOPINDEX,top,0);
|
||||
}
|
||||
SendMessageW(view.list,WM_SETREDRAW,TRUE,0);
|
||||
InvalidateRect(view.list,nullptr,TRUE);
|
||||
InvalidateRect(view.host,nullptr,FALSE);
|
||||
updateGitHistoryStatus(view);
|
||||
queueGitPreview(view);
|
||||
}
|
||||
|
||||
void loadGitHistory(GitChangesView &view,bool refreshBranches,bool append=false)
|
||||
{
|
||||
if(append && (view.historyTask.valid() || !view.moreHistory)) return;
|
||||
view.stopHistory.request_stop();
|
||||
view.historyTask={};
|
||||
view.stopHistory=std::stop_source{};
|
||||
view.historyFailure.clear();
|
||||
const auto offset=append?view.commits.size():0;
|
||||
const auto haveBranch=view.branchIndex<view.branches.size();
|
||||
const auto branch=haveBranch?view.branches[view.branchIndex]:GitBranch{};
|
||||
if(!append)
|
||||
{
|
||||
view.commits.clear();
|
||||
view.moreHistory=false;
|
||||
}
|
||||
try
|
||||
{
|
||||
std::packaged_task<GitHistoryUpdate()> task([git=view.data.executable,root=view.data.root,
|
||||
refreshBranches,offset,branch,index=view.branchIndex,stop=view.stopHistory.get_token()]
|
||||
{
|
||||
GitHistoryUpdate result;
|
||||
result.branch=index;
|
||||
auto revision=branch.revision;
|
||||
if(refreshBranches)
|
||||
{
|
||||
result.branches=ks::files::readGitBranches(git,root,stop);
|
||||
const auto &branches=*result.branches;
|
||||
if(branches.empty()) return result;
|
||||
auto chosen=std::find_if(branches.begin(),branches.end(),[&](const auto &entry){return entry.ref==branch.ref;});
|
||||
if(chosen==branches.end())
|
||||
chosen=std::find_if(branches.begin(),branches.end(),[](const auto &entry){return entry.current;});
|
||||
if(chosen==branches.end()) chosen=branches.begin();
|
||||
result.branch=static_cast<size_t>(chosen-branches.begin());
|
||||
revision=chosen->revision;
|
||||
}
|
||||
if(!revision.empty()) result.page=ks::files::readGitHistory(git,root,revision,offset,stop);
|
||||
return result;
|
||||
});
|
||||
auto pending=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
view.historyTask=std::move(pending);
|
||||
}
|
||||
catch(const std::exception &error) {view.historyFailure=error.what();}
|
||||
if(!append) renderGitHistory(view);
|
||||
else updateGitHistoryStatus(view);
|
||||
}
|
||||
|
||||
void finishGitHistory(GitChangesView &view)
|
||||
{
|
||||
const auto *entry=selectedGitCommit(view);
|
||||
const auto selected=entry?entry->revision:std::wstring{};
|
||||
const auto top=SendMessageW(view.list,LB_GETTOPINDEX,0,0);
|
||||
try
|
||||
{
|
||||
auto result=view.historyTask.get();
|
||||
view.branchIndex=result.branch;
|
||||
if(result.branches)
|
||||
{
|
||||
view.branches=std::move(*result.branches);
|
||||
SendMessageW(view.branchPicker,CB_RESETCONTENT,0,0);
|
||||
for(const auto &branch:view.branches)
|
||||
SendMessageW(view.branchPicker,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(branch.label.c_str()));
|
||||
if(!view.branches.empty()) SendMessageW(view.branchPicker,CB_SETCURSEL,view.branchIndex,0);
|
||||
EnableWindow(view.branchPicker,!view.branches.empty());
|
||||
}
|
||||
view.commits.insert(view.commits.end(),std::make_move_iterator(result.page.commits.begin()),
|
||||
std::make_move_iterator(result.page.commits.end()));
|
||||
view.moreHistory=result.page.more;
|
||||
}
|
||||
catch(const std::exception &error) {view.historyFailure=error.what();}
|
||||
renderGitHistory(view,selected,top);
|
||||
}
|
||||
|
||||
void pollGitChanges(GitChangesView &view)
|
||||
{
|
||||
using namespace std::chrono_literals;
|
||||
if(view.commitReview.valid() && view.commitReview.wait_for(0ms)==std::future_status::ready)
|
||||
finishGitCommitReview(view);
|
||||
if(view.mutation.valid() && view.mutation.wait_for(0ms)==std::future_status::ready)
|
||||
finishGitMutation(view);
|
||||
if(view.refresh.valid() && view.refresh.wait_for(0ms)==std::future_status::ready)
|
||||
{
|
||||
const auto *entry=selectedGitChange(view);
|
||||
@@ -153,36 +547,41 @@ void pollGitChanges(GitChangesView &view)
|
||||
renderGitChanges(view);
|
||||
}
|
||||
}
|
||||
if(view.diffAt && GetTickCount64()>=view.diffAt)
|
||||
if(view.historyTask.valid() && view.historyTask.wait_for(0ms)==std::future_status::ready)
|
||||
finishGitHistory(view);
|
||||
if(view.previewAt && GetTickCount64()>=view.previewAt)
|
||||
{
|
||||
view.diffAt=0;
|
||||
view.stopDiff=std::stop_source{};
|
||||
view.previewAt=0;
|
||||
view.stopPreview=std::stop_source{};
|
||||
try
|
||||
{
|
||||
std::packaged_task<std::string()> task([git=view.data.executable,root=view.data.root,
|
||||
entry=*view.requested,stop=view.stopDiff.get_token()] {
|
||||
return ks::files::readGitPatch(git,root,entry,stop);
|
||||
item=view.requested->item,stop=view.stopPreview.get_token()] {
|
||||
if(const auto *change=std::get_if<GitChange>(&item))
|
||||
return ks::files::readGitPatch(git,root,*change,stop);
|
||||
return ks::files::readGitCommit(git,root,std::get<std::wstring>(item),stop);
|
||||
});
|
||||
auto pending=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
view.diff=std::move(pending);
|
||||
view.previewTask=std::move(pending);
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),"Could not start Git diff.");
|
||||
ks::files::previewQuickViewText(view.preview,view.requested->heading,"Could not start the Git preview.");
|
||||
}
|
||||
}
|
||||
if(view.diff.valid() && view.diff.wait_for(0ms)==std::future_status::ready)
|
||||
if(view.previewTask.valid() && view.previewTask.wait_for(0ms)==std::future_status::ready)
|
||||
{
|
||||
try
|
||||
{
|
||||
const auto patch=view.diff.get();
|
||||
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),
|
||||
patch.empty()?std::string_view("No differences. Refresh if the worktree has changed."):std::string_view(patch));
|
||||
const auto contents=view.previewTask.get();
|
||||
ks::files::previewQuickViewText(view.preview,view.requested->heading,
|
||||
contents.empty()?std::string_view("No differences. Refresh if the worktree has changed."):std::string_view(contents),
|
||||
std::holds_alternative<GitChange>(view.requested->item));
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),error.what());
|
||||
ks::files::previewQuickViewText(view.preview,view.requested->heading,error.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -190,7 +589,7 @@ void pollGitChanges(GitChangesView &view)
|
||||
void openGitWorkingFile(GitChangesView &view,bool edit)
|
||||
{
|
||||
const auto *entry=selectedGitChange(view);
|
||||
if(!entry || view.refresh.valid() || !view.failure.empty()) return;
|
||||
if(view.historyMode || !entry || view.refresh.valid() || !view.failure.empty() || gitActionPending(view)) return;
|
||||
auto relative=fs::path(entry->path);
|
||||
for(const auto &component:relative)
|
||||
if(!validFileName(component.native()))
|
||||
@@ -219,22 +618,58 @@ void layoutGitChildren(GitChangesView &view)
|
||||
{
|
||||
SetWindowPos(control,nullptr,x,y,std::max(0,width),std::max(0,height),SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
};
|
||||
const int inset=6, top=4, filterLabel=8*cellWidth;
|
||||
const int inset=6,top=4,filterLabel=8*cellWidth,buttonWidth=12*cellWidth;
|
||||
const int filterTop=top+textHeight+6, listTop=filterTop+textHeight+6;
|
||||
const int bottom=std::max(listTop,static_cast<int>(bounds.bottom)-textHeight-5);
|
||||
const int leftWidth=std::max(0,middle-2*inset);
|
||||
place(view.heading,inset,top,leftWidth,textHeight);
|
||||
place(view.heading,inset,top,leftWidth-buttonWidth-4,textHeight);
|
||||
place(view.switchView,inset+leftWidth-buttonWidth,top,buttonWidth,textHeight);
|
||||
place(view.filterLabel,inset,filterTop,filterLabel,textHeight);
|
||||
place(view.filter,inset+filterLabel,filterTop,leftWidth-filterLabel,textHeight);
|
||||
place(view.branchPicker,inset+filterLabel,filterTop,leftWidth-filterLabel,11*textHeight);
|
||||
place(view.list,inset,listTop,leftWidth-scrollBarWidth(view.list),bottom-listTop);
|
||||
place(view.status,inset,bottom+3,leftWidth,textHeight);
|
||||
place(view.status,inset,bottom+3,leftWidth-(view.historyMode?1:2)*(buttonWidth+4),textHeight);
|
||||
place(view.moreButton,inset+leftWidth-buttonWidth,bottom+3,buttonWidth,textHeight);
|
||||
place(view.indexButton,inset+leftWidth-2*buttonWidth-4,bottom+3,buttonWidth,textHeight);
|
||||
place(view.commitButton,inset+leftWidth-buttonWidth,bottom+3,buttonWidth,textHeight);
|
||||
place(view.preview,middle+inset,top,bounds.right-middle-2*inset,bottom-top);
|
||||
place(view.hints,middle+inset,bottom+3,bounds.right-middle-2*inset,textHeight);
|
||||
for(const auto control:{view.heading,view.filterLabel,view.filter,view.list,view.status,view.hints})
|
||||
for(const auto control:{view.heading,view.switchView,view.filterLabel,view.filter,view.branchPicker,
|
||||
view.list,view.status,view.hints,view.moreButton,view.indexButton,view.commitButton})
|
||||
SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
SendMessageW(view.list,LB_SETITEMHEIGHT,0,textHeight);
|
||||
}
|
||||
|
||||
void switchGitView(GitChangesView &view)
|
||||
{
|
||||
if(view.data.root.empty() || view.refresh.valid() || gitActionPending(view)) return;
|
||||
view.historyMode=!view.historyMode;
|
||||
const auto title=view.historyMode?L"Git History · ":L"Git Changes · ";
|
||||
SetWindowTextW(view.heading,(title+view.data.root.native()).c_str());
|
||||
SetWindowTextW(view.switchView,view.historyMode?L"Changes":L"History");
|
||||
SetWindowTextW(view.filterLabel,view.historyMode?L"Branch":L"Filter");
|
||||
SetWindowTextW(view.hints,view.historyMode?L"F6 Changes F7 More Ctrl+R Refresh Esc Back":
|
||||
L"F3 View F4 Edit F6 History Ctrl+R Refresh Esc Back");
|
||||
ShowWindow(view.filter,view.historyMode?SW_HIDE:SW_SHOWNA);
|
||||
ShowWindow(view.branchPicker,view.historyMode?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(view.moreButton,view.historyMode?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(view.indexButton,view.historyMode?SW_HIDE:SW_SHOWNA);
|
||||
ShowWindow(view.commitButton,view.historyMode?SW_HIDE:SW_SHOWNA);
|
||||
layoutGitChildren(view);
|
||||
if(view.historyMode)
|
||||
{
|
||||
EnableWindow(view.branchPicker,FALSE);
|
||||
loadGitHistory(view,true);
|
||||
}
|
||||
else
|
||||
{
|
||||
view.stopHistory.request_stop();
|
||||
view.historyTask={};
|
||||
renderGitChanges(view);
|
||||
}
|
||||
SetFocus(view.list);
|
||||
}
|
||||
|
||||
LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_NCCREATE)
|
||||
@@ -255,17 +690,29 @@ LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM l
|
||||
reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),GetModuleHandleW(nullptr),nullptr);
|
||||
};
|
||||
view->heading=make(L"STATIC",L"Git Changes",SS_PATHELLIPSIS|SS_NOPREFIX,gitHeading);
|
||||
view->switchView=make(L"BUTTON",L"History",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitSwitch);
|
||||
view->filterLabel=make(L"STATIC",L"Filter",SS_NOPREFIX);
|
||||
view->filter=make(farEditClass,L"",ES_MULTILINE|ES_AUTOHSCROLL|WS_TABSTOP,gitFilter);
|
||||
view->branchPicker=make(L"COMBOBOX",L"",CBS_DROPDOWNLIST|CBS_OWNERDRAWFIXED|CBS_HASSTRINGS|WS_TABSTOP|WS_VSCROLL,
|
||||
gitBranch);
|
||||
view->list=make(L"LISTBOX",L"",LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT|LBS_NOTIFY|WS_TABSTOP,gitList);
|
||||
view->status=make(L"STATIC",L"",SS_ENDELLIPSIS|SS_NOPREFIX,gitStatus);
|
||||
view->hints=make(L"STATIC",L"F3 View F4 Edit Ctrl+R Refresh Esc Back",SS_ENDELLIPSIS|SS_NOPREFIX);
|
||||
view->hints=make(L"STATIC",L"F3 View F4 Edit F6 History Ctrl+R Refresh Esc Back",SS_ENDELLIPSIS|SS_NOPREFIX);
|
||||
view->moreButton=make(L"BUTTON",L"More",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitMore);
|
||||
view->indexButton=make(L"BUTTON",L"Stage",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitIndexAction);
|
||||
view->commitButton=make(L"BUTTON",L"Commit",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitCommitAction);
|
||||
try {view->preview=ks::files::createQuickView(window,textWindowDialogs());}
|
||||
catch(const std::exception &) {}
|
||||
if(!view->heading || !view->filterLabel || !view->filter || !view->list || !view->status ||
|
||||
!view->hints || !view->preview || !SetTimer(window,gitChangesTimer,35,nullptr)) return -1;
|
||||
if(!view->heading || !view->switchView || !view->filterLabel || !view->filter || !view->branchPicker ||
|
||||
!view->list || !view->status || !view->hints || !view->moreButton || !view->indexButton ||
|
||||
!view->commitButton || !view->preview ||
|
||||
!SetTimer(window,gitChangesTimer,35,nullptr)) return -1;
|
||||
prepareDialogEdit(view->filter);
|
||||
SendMessageW(view->filter,EM_SETLIMITTEXT,1024,0);
|
||||
ShowWindow(view->branchPicker,SW_HIDE);
|
||||
ShowWindow(view->moreButton,SW_HIDE);
|
||||
layoutGitChildren(*view);
|
||||
installFarCombo(view->branchPicker,view->filter);
|
||||
installScrollBar(view->list,window);
|
||||
return 0;
|
||||
}
|
||||
@@ -276,13 +723,28 @@ LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM l
|
||||
if(wp==gitChangesTimer) pollGitChanges(*view);
|
||||
return 0;
|
||||
case WM_COMMAND:
|
||||
if(view->preview && LOWORD(wp)==gitFilter && HIWORD(wp)==EN_CHANGE)
|
||||
if(!view->historyMode && view->preview && LOWORD(wp)==gitFilter && HIWORD(wp)==EN_CHANGE)
|
||||
{
|
||||
const auto *entry=selectedGitChange(*view);
|
||||
renderGitChanges(*view,entry?std::optional(*entry):std::nullopt);
|
||||
}
|
||||
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_SELCHANGE) queueGitDiff(*view);
|
||||
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_SELCHANGE) queueGitPreview(*view);
|
||||
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_DBLCLK) openGitWorkingFile(*view,false);
|
||||
else if(LOWORD(wp)==gitSwitch && HIWORD(wp)==BN_CLICKED) switchGitView(*view);
|
||||
else if(view->historyMode && LOWORD(wp)==gitMore && HIWORD(wp)==BN_CLICKED) loadGitHistory(*view,false,true);
|
||||
else if(LOWORD(wp)==gitIndexAction && HIWORD(wp)==BN_CLICKED) changeSelectedGitIndex(*view);
|
||||
else if(LOWORD(wp)==gitCommitAction && HIWORD(wp)==BN_CLICKED) openGitCommitReview(*view);
|
||||
else if(view->historyMode && LOWORD(wp)==gitBranch &&
|
||||
(HIWORD(wp)==CBN_SELENDOK || (HIWORD(wp)==CBN_SELCHANGE &&
|
||||
!SendMessageW(view->branchPicker,CB_GETDROPPEDSTATE,0,0))))
|
||||
{
|
||||
const auto index=SendMessageW(view->branchPicker,CB_GETCURSEL,0,0);
|
||||
if(index>=0 && size_t(index)<view->branches.size() && size_t(index)!=view->branchIndex)
|
||||
{
|
||||
view->branchIndex=static_cast<size_t>(index);
|
||||
loadGitHistory(*view,false);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
case WM_MEASUREITEM:
|
||||
reinterpret_cast<MEASUREITEMSTRUCT *>(lp)->itemHeight=textHeight;
|
||||
@@ -290,6 +752,8 @@ LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM l
|
||||
case WM_DRAWITEM:
|
||||
{
|
||||
const auto &item=*reinterpret_cast<const DRAWITEMSTRUCT *>(lp);
|
||||
if(item.CtlID==gitBranch) {drawFarComboRow(item);return TRUE;}
|
||||
if(item.CtlType==ODT_BUTTON) {paintDialogButton(item,colors[Dialog],colors[Text]);return TRUE;}
|
||||
if(item.itemID==static_cast<UINT>(-1)) return TRUE;
|
||||
const auto count=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0);
|
||||
if(count<0) return TRUE;
|
||||
@@ -305,7 +769,8 @@ LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM l
|
||||
case WM_CTLCOLORLISTBOX:
|
||||
{
|
||||
const auto dc=reinterpret_cast<HDC>(wp);
|
||||
const bool input=message==WM_CTLCOLOREDIT;
|
||||
const bool input=message==WM_CTLCOLOREDIT ||
|
||||
(message==WM_CTLCOLORLISTBOX && reinterpret_cast<HWND>(lp)!=view->list);
|
||||
SetTextColor(dc,colors[Text]);
|
||||
SetBkColor(dc,colors[input?Dialog:PanelBlue]);
|
||||
return reinterpret_cast<LRESULT>(input?teal:blue);
|
||||
@@ -339,10 +804,13 @@ bool showingGitChanges()
|
||||
|
||||
void closeGitChanges(HWND owner,bool restore=true)
|
||||
{
|
||||
if(restore && gitChangesView && gitActionPending(*gitChangesView)) return;
|
||||
auto view=std::move(gitChangesView);
|
||||
if(!view) return;
|
||||
view->stopRefresh.request_stop();
|
||||
view->stopDiff.request_stop();
|
||||
view->stopPreview.request_stop();
|
||||
view->stopHistory.request_stop();
|
||||
view->stopMutation.request_stop();
|
||||
if(IsWindow(view->host)) DestroyWindow(view->host);
|
||||
if(restore)
|
||||
{
|
||||
@@ -398,11 +866,35 @@ bool handleGitChangesKey(HWND owner,const MSG &message)
|
||||
const bool control=GetKeyState(VK_CONTROL)&0x8000;
|
||||
const bool alt=GetKeyState(VK_MENU)&0x8000;
|
||||
if(alt) return false;
|
||||
const auto selector=view.historyMode?view.branchPicker:view.filter;
|
||||
if(view.historyMode && SendMessageW(view.branchPicker,CB_GETDROPPEDSTATE,0,0)) return false;
|
||||
if(!control && key==VK_ESCAPE) closeGitChanges(owner);
|
||||
else if(control && key=='R') refreshGitChanges(view);
|
||||
else if(control && key=='F') SetFocus(view.filter);
|
||||
else if(!control && key==VK_TAB) SetFocus(GetFocus()==view.filter?view.list:view.filter);
|
||||
else if(!control && (key==VK_F3 || key==VK_F4 || (key==VK_RETURN && GetFocus()==view.list)))
|
||||
else if(control && key=='R')
|
||||
{
|
||||
if(view.historyMode) loadGitHistory(view,true);
|
||||
else refreshGitChanges(view);
|
||||
}
|
||||
else if(control && key=='F') SetFocus(selector);
|
||||
else if(!control && key==VK_TAB)
|
||||
{
|
||||
std::vector<HWND> focusOrder;
|
||||
for(const auto controlWindow:{view.list,selector,view.indexButton,view.commitButton,view.switchView,view.moreButton})
|
||||
if(IsWindowVisible(controlWindow) && IsWindowEnabled(controlWindow)) focusOrder.push_back(controlWindow);
|
||||
const auto current=std::find(focusOrder.begin(),focusOrder.end(),GetFocus());
|
||||
if(!focusOrder.empty())
|
||||
{
|
||||
const bool reverse=GetKeyState(VK_SHIFT)&0x8000;
|
||||
const auto index=current==focusOrder.end()?0:static_cast<size_t>(current-focusOrder.begin());
|
||||
const auto next=reverse?focusOrder.size()-1:1;
|
||||
SetFocus(focusOrder[(index+next)%focusOrder.size()]);
|
||||
}
|
||||
}
|
||||
else if(!control && key==VK_F6) switchGitView(view);
|
||||
else if(!control && view.historyMode && key==VK_F7) loadGitHistory(view,false,true);
|
||||
else if(!control && key==VK_RETURN &&
|
||||
(GetFocus()==view.indexButton || GetFocus()==view.commitButton || GetFocus()==view.switchView || GetFocus()==view.moreButton))
|
||||
SendMessageW(GetFocus(),BM_CLICK,0,0);
|
||||
else if(!control && !view.historyMode && (key==VK_F3 || key==VK_F4 || (key==VK_RETURN && GetFocus()==view.list)))
|
||||
openGitWorkingFile(view,key==VK_F4);
|
||||
else if(!control && GetFocus()==view.filter &&
|
||||
(key==VK_UP || key==VK_DOWN || key==VK_PRIOR || key==VK_NEXT))
|
||||
|
||||
+7
-1
@@ -11,6 +11,7 @@
|
||||
#include <sddl.h>
|
||||
#include <tlhelp32.h>
|
||||
#include <psapi.h>
|
||||
#include <userenv.h>
|
||||
#include <cmath>
|
||||
#include <numbers>
|
||||
#include <algorithm>
|
||||
@@ -3848,6 +3849,7 @@ void showPanelLockProcesses(HWND owner,Panel &panel);
|
||||
void showProcesses(HWND owner,std::vector<fs::path> paths={});
|
||||
bool gitChangesAvailable(const Panel &panel);
|
||||
void openGitChanges(HWND owner,const Panel &panel);
|
||||
void showEnvironmentPanel(HWND owner);
|
||||
|
||||
bool selectablePickerRow(LRESULT row)
|
||||
{
|
||||
@@ -3897,6 +3899,7 @@ void selectDrive()
|
||||
else if(menuIndex==2 && row==14) ks::files::showAllViewerBookmarks(owner,textWindowDialogs());
|
||||
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==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]);
|
||||
@@ -7904,6 +7907,7 @@ bool loadFilesPreferences(HWND window)
|
||||
#include "files_options.inl"
|
||||
#include "files_panel_columns_dialog.inl"
|
||||
#include "files_space_analyzer.inl"
|
||||
#include "files_environment.inl"
|
||||
|
||||
void openMenu(HWND window, int index)
|
||||
{
|
||||
@@ -7958,7 +7962,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"Git Changes…",L"Environment Variables…"};
|
||||
}
|
||||
const auto &panel=panels[active];
|
||||
const bool remoteResults=remoteSearchResults(panel);
|
||||
@@ -7986,6 +7990,7 @@ void openMenu(HWND window, int index)
|
||||
commandActions={0,3,11,-1,1,13,14,2,4,5,8};
|
||||
if(!terminalVisible) commandActions.push_back(15);
|
||||
if(gitChangesAvailable(panel)) commandActions.push_back(16);
|
||||
if(!terminalVisible) commandActions.push_back(17);
|
||||
if(!terminalVisible && canFindFiles(panels[active])) commandActions.insert(commandActions.begin()+1,9);
|
||||
if(!terminalVisible && !panels[active].peer && !panels[active].ftp)
|
||||
commandActions.insert(commandActions.begin()+2,12);
|
||||
@@ -8967,6 +8972,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
return 0;
|
||||
case WM_CLOSE:
|
||||
if(!activeCopy && FilesModalDialog::dismissOwned(window)) return 0;
|
||||
if(gitChangesView && gitActionPending(*gitChangesView)) return 0;
|
||||
if(activeCopy)
|
||||
{
|
||||
if(FilesModalDialog::activeFor(window)!=activeCopy->window)
|
||||
|
||||
+20
-16
@@ -804,7 +804,7 @@ public:
|
||||
bool handleKey(const MSG &message);
|
||||
void goToFragment(std::string_view fragment);
|
||||
void previewFile(const std::filesystem::path &path);
|
||||
void previewDiff(const std::wstring &title,std::string_view patch);
|
||||
void previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff);
|
||||
bool openBookmark(const ViewerBookmark &bookmark);
|
||||
std::filesystem::path original;
|
||||
const std::string peerId;
|
||||
@@ -936,8 +936,8 @@ private:
|
||||
};
|
||||
std::future<QuickDocument> quickLoading;
|
||||
std::filesystem::path quickPath;
|
||||
std::wstring quickDiffTitle;
|
||||
bool quickDiffVisible{};
|
||||
std::wstring quickTextTitle;
|
||||
bool quickTextVisible{},quickTextDiff{};
|
||||
uint64_t quickRequest{}, quickReading{};
|
||||
ULONGLONG quickReadyAt{};
|
||||
std::wstring quickError;
|
||||
@@ -1625,9 +1625,9 @@ std::string readMarkdownDocument(TextDocument &document)
|
||||
|
||||
void TextWindow::previewFile(const std::filesystem::path &path)
|
||||
{
|
||||
if(quickDiffTitle.empty() && path==quickPath) return;
|
||||
quickDiffVisible=false;
|
||||
quickDiffTitle.clear();
|
||||
if(quickTextTitle.empty() && path==quickPath) return;
|
||||
quickTextVisible=false;
|
||||
quickTextTitle.clear();
|
||||
quickPath=path;
|
||||
++quickRequest;
|
||||
quickReadyAt=GetTickCount64()+80;
|
||||
@@ -1639,10 +1639,10 @@ void TextWindow::previewFile(const std::filesystem::path &path)
|
||||
SetTimer(window,quickViewTimer,30,nullptr);
|
||||
}
|
||||
|
||||
void TextWindow::previewDiff(const std::wstring &title,std::string_view patch)
|
||||
void TextWindow::previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff)
|
||||
{
|
||||
if(!embedded) return;
|
||||
if(quickDiffTitle.empty())
|
||||
if(quickTextTitle.empty())
|
||||
{
|
||||
++quickRequest;
|
||||
KillTimer(window,quickViewTimer);
|
||||
@@ -1652,13 +1652,17 @@ void TextWindow::previewDiff(const std::wstring &title,std::string_view patch)
|
||||
stopPreview(false,true);
|
||||
document.reset();
|
||||
quickMarkdown.reset();
|
||||
language=automatic=detectLanguage(L"preview.diff",patch);
|
||||
}
|
||||
if(quickTextTitle.empty() || quickTextDiff!=diff)
|
||||
{
|
||||
language=automatic=diff?detectLanguage(L"preview.diff",contents):TextLanguage{};
|
||||
installLexer();
|
||||
}
|
||||
quickDiffTitle=title;
|
||||
quickDiffVisible=!patch.empty();
|
||||
quickTextTitle=title;
|
||||
quickTextVisible=!contents.empty();
|
||||
quickTextDiff=diff;
|
||||
pageEol=SC_EOL_LF;
|
||||
replaceEditorText(patch);
|
||||
replaceEditorText(contents);
|
||||
send(SCI_COLOURISE,0,-1);
|
||||
layout();
|
||||
}
|
||||
@@ -2555,7 +2559,7 @@ void TextWindow::layout()
|
||||
const LONG bottom=std::max<LONG>(top,area.bottom-(embedded?0:row));
|
||||
MoveWindow(editor,0,top,area.right,bottom-top,TRUE);
|
||||
preview.layout({0,top,area.right,bottom},previewWanted && (!embedded || previewVisible));
|
||||
ShowWindow(editor,(document || quickDiffVisible) && !previewWanted?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(editor,(document || quickTextVisible) && !previewWanted?SW_SHOWNA:SW_HIDE);
|
||||
invalidate();
|
||||
}
|
||||
|
||||
@@ -2632,7 +2636,7 @@ void TextWindow::paint()
|
||||
else if(quickPath.empty()) label+=L" · Select a local text file";
|
||||
else if(!document || (previewWanted && !previewVisible)) label+=L" · Loading…";
|
||||
else if(!previewVisible && pageTotal>1) label+=L" · First page";
|
||||
if(!quickDiffTitle.empty()) label=quickDiffTitle;
|
||||
if(!quickTextTitle.empty()) label=quickTextTitle;
|
||||
drawEditorStatus(dc,{0,0,client.right,row},chromeFont,color(TextColor::chromebg),
|
||||
color(TextColor::chrome),scale(6),label);
|
||||
if(chromeFont) DeleteObject(chromeFont);
|
||||
@@ -3295,10 +3299,10 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path)
|
||||
preview->second->previewFile(path);
|
||||
}
|
||||
|
||||
void previewQuickViewDiff(HWND window,const std::wstring &title,std::string_view patch)
|
||||
void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff)
|
||||
{
|
||||
if(const auto preview=textWindows.find(window);preview!=textWindows.end())
|
||||
preview->second->previewDiff(title,patch);
|
||||
preview->second->previewEmbeddedText(title,contents,diff);
|
||||
}
|
||||
|
||||
ImageViewStyle imageViewStyle(TextDialogs dialogs)
|
||||
|
||||
@@ -106,7 +106,7 @@ RemoteTextSource createLanTextSource(const lan::FilesPeer &peer);
|
||||
inline constexpr UINT quickViewToggleMessage=WM_APP+31;
|
||||
HWND createQuickView(HWND owner,TextDialogs dialogs);
|
||||
void previewQuickViewFile(HWND window,const std::filesystem::path &path);
|
||||
void previewQuickViewDiff(HWND window,const std::wstring &title,std::string_view patch);
|
||||
void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff=false);
|
||||
HWND createImageQuickView(HWND owner,TextDialogs dialogs);
|
||||
void previewImageQuickViewFile(HWND window,const std::filesystem::path &path);
|
||||
void openImageWindow(HWND owner,std::vector<std::filesystem::path> images,const std::filesystem::path &path,
|
||||
|
||||
Reference in new issue
Block a user