Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9158bf95a6 | ||
|
|
159b776199 | ||
|
|
ada198db24 | ||
|
|
fe1f818582 | ||
|
|
1217887e14 | ||
|
|
10847244f0 | ||
|
|
82f1179970 | ||
|
|
92bee6bb67 | ||
|
|
e1f45a0098 | ||
|
|
bc44e0c1fc |
No files matched your search
+1
-1
@@ -6,7 +6,7 @@ endif()
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
add_executable(KSwitcherFiles WIN32 src/files_main.cpp src/files_text_window.cpp
|
||||
src/files_text_document.cpp src/files_text_language.cpp src/files_archive.cpp resources/files.rc)
|
||||
src/files_text_document.cpp src/files_text_language.cpp src/files_archive.cpp src/files_git_changes.cpp resources/files.rc)
|
||||
set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files.ico"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-viewer.ico"
|
||||
|
||||
+48
-6
@@ -258,6 +258,14 @@ Warning і початковий фокус на No.
|
||||
рядок. Команда з меню оновлює панель і зберігає папку, курсор та
|
||||
актуальні позначки. Для LAN, FTP, SFTP, UNC та архівів контекстне меню
|
||||
показує доступні команди Files.
|
||||
- **Ctrl+A** або **F9 → Files → Properties** показує властивості поточного
|
||||
файла чи папки. У локальній панелі можна змінити прапорці **Read-only**,
|
||||
**Hidden**, **System**, **Archive** та **Not indexed**. **Save** застосовує
|
||||
лише змінені прапорці й перечитує панель. Помилка Windows з’являється
|
||||
окремим повідомленням. Прапорці папки застосовуються лише до самої папки.
|
||||
У LAN, FTP, SFTP, UNC та архіві команда **Properties** також є в
|
||||
контекстному меню й показує доступні метадані без редагування.
|
||||
Для SFTP власник відображається як числовий UID, якщо сервер його надає.
|
||||
- **F8 Delete** у нижньому рядку клавіш викликає той самий діалог видалення,
|
||||
що й клавіша F8.
|
||||
- У нижньому рядку, як у FAR, позначення клавіш сірі на чорному тлі,
|
||||
@@ -738,12 +746,46 @@ Warning і початковий фокус на No.
|
||||
діалог можна скасувати. Помилки шляху показує окремий червоний модальний діалог Far. Після його закриття фокус повертається до поля шляху.
|
||||
- Помилки копіювання, переміщення й видалення показуються в червоному
|
||||
модальному діалозі Far із причиною помилки та кнопкою OK.
|
||||
- Якщо локальне перейменування або видалення заблоковане, кнопка Processes… відкриває
|
||||
список процесів із назвою та PID. Перевірка папки включає вкладені елементи.
|
||||
End process завершує вибраний процес після окремого підтвердження, після
|
||||
чого список оновлюється. Якщо Windows обмежила доступ або перевірку
|
||||
великої папки завершено частково, про це повідомляється в діалозі.
|
||||
Операцію можна повторити після звільнення файла чи папки.
|
||||
- **F9 → Commands → Processes** показує локальні процеси, PID, частку
|
||||
загальної потужності CPU, робочий набір пам’яті та шлях виконуваного файла.
|
||||
**Filter** шукає за іменем, шляхом або PID. **Sort** змінює порядок,
|
||||
**Refresh** робить новий вимір. **Go to file** вибирає виконуваний файл
|
||||
в активній панелі. **End process** завершує процес лише після підтвердження.
|
||||
- **F9 → Files → Locking processes** перевіряє поточний локальний елемент або
|
||||
позначені елементи. Кнопка **Processes…** у повідомленні про заблоковане
|
||||
перейменування або видалення відкриває той самий список із фільтром за
|
||||
вихідним шляхом. Для папки перевіряються також її вкладені елементи.
|
||||
**Go to file** у цьому режимі відкриває виконуваний файл у другій панелі
|
||||
зі збереженням вихідного файла в першій. Після завершення процесу список
|
||||
перечитується. Якщо Windows обмежила доступ або перевірка великої папки
|
||||
завершилася частково, діалог повідомляє про це.
|
||||
- **F9 → Commands → Git Changes** відкриває зміни Git із кореня або
|
||||
вкладеної папки локального worktree. Список окремо показує **Staged**,
|
||||
**Unstaged** та **Untracked**, а сусідня панель відображає diff
|
||||
вибраного рядка. **Filter** шукає за шляхом. **F3** відкриває поточний
|
||||
робочий файл у 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 у терміналі.
|
||||
- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення.
|
||||
- Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
|
||||
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
|
||||
|
||||
+54
-7
@@ -124,16 +124,25 @@ BEGIN
|
||||
CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 275, 140, 58, 16
|
||||
END
|
||||
|
||||
609 DIALOGEX 0, 0, 350, 135
|
||||
609 DIALOGEX 0, 0, 430, 204
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "", 430, 14, 17, 322, 20
|
||||
LISTBOX 431, 14, 41, 322, 61, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
|
||||
CONTROL "", 432, "Static", NOT WS_VISIBLE, 14, 108, 1, 1
|
||||
CONTROL "&End process", 433, "Button", BS_OWNERDRAW | WS_TABSTOP, 56, 110, 80, 16
|
||||
CONTROL "&Refresh", 434, "Button", BS_OWNERDRAW | WS_TABSTOP, 140, 110, 74, 16
|
||||
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 218, 110, 65, 16
|
||||
LTEXT "", 430, 16, 15, 398, 13, SS_PATHELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "&Filter", 440, 16, 33, 38, 13
|
||||
FAR_EDIT(435, 0, 58, 32, 212, 15)
|
||||
LTEXT "&Sort", 441, 277, 33, 34, 13
|
||||
COMBOBOX 436, 312, 32, 102, 92, CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | WS_TABSTOP
|
||||
LTEXT "", 439, 17, 51, 397, 13, SS_NOPREFIX
|
||||
LISTBOX 431, 16, 65, 398, 70, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP
|
||||
LTEXT "E&xecutable", 442, 16, 144, 71, 13
|
||||
FAR_EDIT(438, ES_READONLY, 89, 143, 325, 15)
|
||||
LTEXT "", 443, 16, 162, 398, 12, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
CONTROL "", 432, "Static", NOT WS_VISIBLE, 16, 179, 1, 1
|
||||
CONTROL "&Go to file", 437, "Button", BS_OWNERDRAW | WS_TABSTOP, 35, 185, 90, 16
|
||||
CONTROL "&End process", 433, "Button", BS_OWNERDRAW | WS_TABSTOP, 130, 185, 90, 16
|
||||
CONTROL "&Refresh", 434, "Button", BS_OWNERDRAW | WS_TABSTOP, 225, 185, 78, 16
|
||||
CONTROL "&Close", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 308, 185, 72, 16
|
||||
END
|
||||
|
||||
608 DIALOGEX 0, 0, 220, 67
|
||||
@@ -588,3 +597,41 @@ BEGIN
|
||||
CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 270, 183, 60, 17
|
||||
CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 336, 183, 67, 17
|
||||
END
|
||||
|
||||
125 DIALOGEX 0, 0, 360, 178
|
||||
STYLE DS_SETFONT | DS_CENTER | WS_POPUP
|
||||
CAPTION "Properties"
|
||||
FONT 10, "Consolas"
|
||||
BEGIN
|
||||
LTEXT "", 580, 16, 15, 328, 13, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "", 581, 16, 32, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "", 582, 16, 45, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "", 583, 16, 58, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "", 584, 16, 71, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "", 585, 16, 84, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
LTEXT "", 586, 16, 99, 328, 12, SS_ENDELLIPSIS | SS_NOPREFIX
|
||||
AUTOCHECKBOX "&Read-only", 587, 16, 114, 106, 13
|
||||
AUTOCHECKBOX "&Hidden", 588, 128, 114, 106, 13
|
||||
AUTOCHECKBOX "S&ystem", 589, 240, 114, 104, 13
|
||||
AUTOCHECKBOX "&Archive", 590, 16, 128, 106, 13
|
||||
AUTOCHECKBOX "Not &indexed", 591, 128, 128, 106, 13
|
||||
LTEXT "", 592, 10, 146, 1, 1, NOT WS_VISIBLE
|
||||
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
|
||||
+17
-7
@@ -37,6 +37,13 @@ constexpr std::int64_t archiveEpochOffset=11644473600, archiveTicksPerSecond=100
|
||||
constexpr char unsafePath[]="The archive contains an unsafe or conflicting path.";
|
||||
constexpr char encryptedArchive[]="This archive requires a password. Password-protected entries cannot be opened in Files.";
|
||||
|
||||
uint64_t archiveTime(bool present,int64_t seconds,long nanos)
|
||||
{
|
||||
if(!present || seconds < -archiveEpochOffset || seconds>=INT64_MAX/archiveTicksPerSecond-archiveEpochOffset)
|
||||
return 0;
|
||||
return static_cast<uint64_t>((seconds+archiveEpochOffset)*archiveTicksPerSecond+nanos/100);
|
||||
}
|
||||
|
||||
struct ArchiveFileHandle
|
||||
{
|
||||
HANDLE value=INVALID_HANDLE_VALUE;
|
||||
@@ -100,11 +107,15 @@ std::pair<fs::path,ArchiveEntry> decodeEntry(archive_entry *entry)
|
||||
const auto size=archive_entry_size(entry);
|
||||
if(size<0 || (!folder && !archive_entry_size_is_set(entry)))
|
||||
throw std::runtime_error("The archive entry has an invalid size.");
|
||||
const int64_t seconds=archive_entry_mtime(entry);
|
||||
const auto modified=archive_entry_mtime_is_set(entry) && seconds>=-archiveEpochOffset &&
|
||||
seconds<(INT64_MAX/archiveTicksPerSecond-archiveEpochOffset)?
|
||||
static_cast<uint64_t>((seconds+archiveEpochOffset)*archiveTicksPerSecond+archive_entry_mtime_nsec(entry)/100):0;
|
||||
return {relative,{static_cast<uint64_t>(size),modified,folder,archive_entry_is_encrypted(entry)!=0}};
|
||||
ArchiveEntry metadata{
|
||||
static_cast<uint64_t>(size),
|
||||
archiveTime(archive_entry_mtime_is_set(entry),archive_entry_mtime(entry),archive_entry_mtime_nsec(entry)),
|
||||
folder,archive_entry_is_encrypted(entry)!=0};
|
||||
metadata.created=archiveTime(archive_entry_birthtime_is_set(entry),archive_entry_birthtime(entry),
|
||||
archive_entry_birthtime_nsec(entry));
|
||||
metadata.accessed=archiveTime(archive_entry_atime_is_set(entry),archive_entry_atime(entry),archive_entry_atime_nsec(entry));
|
||||
if(const auto *owner=archive_entry_uname_w(entry)) metadata.owner=owner;
|
||||
return {relative,std::move(metadata)};
|
||||
}
|
||||
|
||||
void registerEntry(ArchiveEntries &entries,const fs::path &path,const ArchiveEntry &entry)
|
||||
@@ -240,8 +251,7 @@ uint64_t archiveFileSize(const BY_HANDLE_FILE_INFORMATION &info)
|
||||
|
||||
bool sameArchiveFile(const BY_HANDLE_FILE_INFORMATION &left,const BY_HANDLE_FILE_INFORMATION &right)
|
||||
{
|
||||
return left.dwVolumeSerialNumber==right.dwVolumeSerialNumber && left.nFileIndexHigh==right.nFileIndexHigh &&
|
||||
left.nFileIndexLow==right.nFileIndexLow && archiveFileSize(left)==archiveFileSize(right) &&
|
||||
return sameFileIdentity(left,right) && archiveFileSize(left)==archiveFileSize(right) &&
|
||||
CompareFileTime(&left.ftLastWriteTime,&right.ftLastWriteTime)==0;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::files
|
||||
@@ -18,6 +19,8 @@ struct ArchiveEntry
|
||||
{
|
||||
uint64_t size{}, modified{};
|
||||
bool directory{}, encrypted{}, implicit{};
|
||||
uint64_t created{}, accessed{};
|
||||
std::wstring owner{};
|
||||
};
|
||||
|
||||
using ArchiveEntries=std::map<std::filesystem::path,ArchiveEntry,ArchiveNameOrder>;
|
||||
|
||||
@@ -92,7 +92,7 @@ void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen)
|
||||
const auto owner=GetParent(panel.list);
|
||||
ContextPopup popup;
|
||||
if(!popup.handle) return;
|
||||
constexpr UINT openItem=1,findItems=2,newProfile=3;
|
||||
constexpr UINT openItem=1,findItems=2,newProfile=3,properties=4;
|
||||
const auto add=[&](UINT id,const wchar_t *label){AppendMenuW(popup.handle,MF_STRING,id,label);};
|
||||
if(transferProfileList(panel))
|
||||
{
|
||||
@@ -119,6 +119,7 @@ void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen)
|
||||
if(!panel.archive && (panel.ftp || canCopy) && remoteSearchActionAvailable(114))
|
||||
add(114,panel.ftp?L"Rename":L"Move");
|
||||
if(!panel.archive && remoteSearchActionAvailable(117)) add(117,L"Delete");
|
||||
if(panelItemPropertiesAvailable(panel)) add(properties,L"Properties");
|
||||
}
|
||||
else if(!panel.findOrigin && !panel.archive && !panel.directory.empty()) add(115,L"Make folder");
|
||||
if(!panel.archive && !panel.directory.empty()) add(findItems,L"Find files");
|
||||
@@ -129,6 +130,7 @@ void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen)
|
||||
if(command==openItem) enter(panel);
|
||||
else if(command==findItems) findPanelFiles(owner,panel);
|
||||
else if(command==newProfile) editTransferProfile(panel,true);
|
||||
else if(command==properties) showPanelItemProperties(owner,panel);
|
||||
else if(command) SendMessageW(owner,WM_COMMAND,MAKEWPARAM(command,BN_CLICKED),0);
|
||||
}
|
||||
|
||||
@@ -175,7 +177,7 @@ void showPanelContextMenu(HWND list,LPARAM position)
|
||||
const auto directory=panel.directory;
|
||||
const auto item=row==LB_ERR?fs::path{}:panel.rows[row];
|
||||
const bool shell=!panel.peer && !panel.ftp && !panel.archive && !directory.empty() &&
|
||||
!directory.root_name().native().starts_with(L"\\\\");
|
||||
!windowsNetworkPath(directory);
|
||||
const auto result=shell?showShellPanelMenu(owner,directory,item,screen):ShellPanelMenuResult::unavailable;
|
||||
if(result==ShellPanelMenuResult::unavailable) showFilesPanelContext(panel,row,screen);
|
||||
else if(result==ShellPanelMenuResult::rename)
|
||||
|
||||
@@ -57,7 +57,10 @@ std::unique_ptr<Panel::ScanResult> scanFileMatches(const Panel::ScanRequest &req
|
||||
matchesFileMask(name,request.find->mask) &&
|
||||
result->metadata.emplace(path,FolderEntryMetadata{
|
||||
entry.attributes,entry.size,entry.modified}).second)
|
||||
{
|
||||
result->files.push_back(path);
|
||||
if(entry.transfer) result->columnMetadata[path].transfer=entry.transfer;
|
||||
}
|
||||
return true;
|
||||
})) break;
|
||||
}
|
||||
|
||||
+10
-10
@@ -330,17 +330,17 @@ DWORD listFtpDirectory(FtpSession &session,const fs::path &directory,const FileV
|
||||
const auto name=session.decodeName(entry.cFileName);
|
||||
if(name.empty() || name==L"." || name==L".." || name.find_first_of(L"/\\:\r\n")!=name.npos)
|
||||
continue;
|
||||
ULARGE_INTEGER modified{}, size{};
|
||||
FILETIME utc{};
|
||||
if(LocalFileTimeToFileTime(&entry.ftLastWriteTime,&utc))
|
||||
const auto ftpTime=[](const FILETIME &local) -> uint64_t
|
||||
{
|
||||
modified.HighPart=utc.dwHighDateTime;
|
||||
modified.LowPart=utc.dwLowDateTime;
|
||||
}
|
||||
size.HighPart=entry.nFileSizeHigh;
|
||||
size.LowPart=entry.nFileSizeLow;
|
||||
if(!visit(directory/name,{entry.dwFileAttributes,size.QuadPart,modified.QuadPart}))
|
||||
return ERROR_CANCELLED;
|
||||
FILETIME utc{};
|
||||
if((!local.dwLowDateTime && !local.dwHighDateTime) || !LocalFileTimeToFileTime(&local,&utc)) return 0;
|
||||
return (uint64_t(utc.dwHighDateTime)<<32)|utc.dwLowDateTime;
|
||||
};
|
||||
FileInfo info{entry.dwFileAttributes,(uint64_t(entry.nFileSizeHigh)<<32)|entry.nFileSizeLow,
|
||||
ftpTime(entry.ftLastWriteTime)};
|
||||
const TransferItemMetadata details{ftpTime(entry.ftCreationTime),ftpTime(entry.ftLastAccessTime)};
|
||||
if(details.created || details.accessed) info.transfer=details;
|
||||
if(!visit(directory/name,info)) return ERROR_CANCELLED;
|
||||
} while(!stop.stop_requested() && InternetFindNextFileA(search.value,&entry));
|
||||
return stop.stop_requested()?ERROR_CANCELLED:GetLastError();
|
||||
}
|
||||
@@ -0,0 +1,740 @@
|
||||
#include "files_git_changes.h"
|
||||
#include "core.h"
|
||||
#include "windows_command_line.h"
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <objbase.h>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <system_error>
|
||||
#include <tuple>
|
||||
#include <utility>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
namespace
|
||||
{
|
||||
namespace fs=std::filesystem;
|
||||
|
||||
struct GitHandle
|
||||
{
|
||||
HANDLE value{};
|
||||
void close()
|
||||
{
|
||||
if(value && value!=INVALID_HANDLE_VALUE) CloseHandle(value);
|
||||
value=nullptr;
|
||||
}
|
||||
~GitHandle(){close();}
|
||||
};
|
||||
|
||||
[[noreturn]] void gitWindowsError(const char *operation)
|
||||
{
|
||||
throw std::system_error(GetLastError(),std::system_category(),operation);
|
||||
}
|
||||
|
||||
void makeGitPipe(GitHandle &read,GitHandle &write,SECURITY_ATTRIBUTES &inheritable)
|
||||
{
|
||||
if(!CreatePipe(&read.value,&write.value,&inheritable,0) ||
|
||||
!SetHandleInformation(read.value,HANDLE_FLAG_INHERIT,0))
|
||||
gitWindowsError("Could not create the Git output pipe");
|
||||
}
|
||||
|
||||
fs::path locateGit()
|
||||
{
|
||||
const DWORD size=GetEnvironmentVariableW(L"PATH",nullptr,0);
|
||||
std::wstring paths(size,L'\0');
|
||||
if(size)
|
||||
{
|
||||
const auto count=GetEnvironmentVariableW(L"PATH",paths.data(),size);
|
||||
paths.resize(count<size?count:0);
|
||||
}
|
||||
std::wstring_view remaining=paths;
|
||||
while(!remaining.empty())
|
||||
{
|
||||
const auto end=remaining.find(L';');
|
||||
auto directory=remaining.substr(0,end);
|
||||
if(directory.size()>=2 && directory.front()==L'"' && directory.back()==L'"')
|
||||
directory=directory.substr(1,directory.size()-2);
|
||||
const auto path=fs::path(directory);
|
||||
if(path.is_absolute())
|
||||
{
|
||||
const auto candidate=path/L"git.exe";
|
||||
const auto attributes=GetFileAttributesW(candidate.c_str());
|
||||
if(attributes!=INVALID_FILE_ATTRIBUTES && !(attributes&FILE_ATTRIBUTE_DIRECTORY)) return candidate;
|
||||
}
|
||||
if(end==remaining.npos) break;
|
||||
remaining.remove_prefix(end+1);
|
||||
}
|
||||
for(const auto key:{HKEY_CURRENT_USER,HKEY_LOCAL_MACHINE})
|
||||
{
|
||||
wchar_t install[32768]{};
|
||||
DWORD bytes=sizeof(install);
|
||||
if(RegGetValueW(key,L"SOFTWARE\\GitForWindows",L"InstallPath",RRF_RT_REG_SZ,nullptr,install,&bytes)!=ERROR_SUCCESS)
|
||||
continue;
|
||||
const auto git=fs::path(install)/L"cmd"/L"git.exe";
|
||||
if(git.is_absolute() && GetFileAttributesW(git.c_str())!=INVALID_FILE_ATTRIBUTES) return git;
|
||||
}
|
||||
throw std::runtime_error("Git for Windows was not found. Install it or add git.exe to PATH.");
|
||||
}
|
||||
|
||||
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<std::wstring> settings;
|
||||
for(auto entry=environment;*entry;)
|
||||
{
|
||||
const std::wstring_view setting=entry;
|
||||
const auto name=setting.substr(0,setting.find(L'='));
|
||||
if(std::none_of(std::begin(overrides),std::end(overrides),[&](std::wstring_view key) {
|
||||
return name.size()==key.size() &&
|
||||
CompareStringOrdinal(name.data(),static_cast<int>(name.size()),key.data(),static_cast<int>(key.size()),TRUE)
|
||||
==CSTR_EQUAL;
|
||||
}))
|
||||
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;
|
||||
}
|
||||
|
||||
struct GitProcessAttributes
|
||||
{
|
||||
std::vector<std::byte> storage;
|
||||
LPPROC_THREAD_ATTRIBUTE_LIST list{};
|
||||
explicit GitProcessAttributes(HANDLE (&inherited)[3])
|
||||
{
|
||||
SIZE_T bytes{};
|
||||
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
|
||||
storage.resize(bytes);
|
||||
const auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
|
||||
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes))
|
||||
gitWindowsError("Could not initialize the Git process");
|
||||
if(!UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,inherited,sizeof(inherited),nullptr,nullptr))
|
||||
{
|
||||
const auto error=GetLastError();
|
||||
DeleteProcThreadAttributeList(attributes);
|
||||
throw std::system_error(error,std::system_category(),"Could not set Git process handles");
|
||||
}
|
||||
list=attributes;
|
||||
}
|
||||
~GitProcessAttributes(){DeleteProcThreadAttributeList(list);}
|
||||
};
|
||||
|
||||
struct GitOutput
|
||||
{
|
||||
std::string output, error;
|
||||
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,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(options.index);
|
||||
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
|
||||
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);
|
||||
HANDLE inherited[]{input.value,childOut.value,childError.value};
|
||||
GitProcessAttributes attributes(inherited);
|
||||
STARTUPINFOEXW startup{};
|
||||
startup.StartupInfo.cb=sizeof(startup);
|
||||
startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES;
|
||||
startup.StartupInfo.hStdInput=input.value;
|
||||
startup.StartupInfo.hStdOutput=childOut.value;
|
||||
startup.StartupInfo.hStdError=childError.value;
|
||||
startup.lpAttributeList=attributes.list;
|
||||
PROCESS_INFORMATION child{};
|
||||
if(!CreateProcessW(git.c_str(),command.data(),nullptr,nullptr,TRUE,
|
||||
CREATE_NO_WINDOW|CREATE_SUSPENDED|CREATE_UNICODE_ENVIRONMENT|EXTENDED_STARTUPINFO_PRESENT,
|
||||
environment.data(),directory.c_str(),&startup.StartupInfo,&child))
|
||||
gitWindowsError("Could not start Git");
|
||||
const GitHandle process{child.hProcess},thread{child.hThread};
|
||||
const GitHandle job{CreateJobObjectW(nullptr,nullptr)};
|
||||
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
|
||||
limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
if(job.value && SetInformationJobObject(job.value,JobObjectExtendedLimitInformation,&limits,sizeof(limits)))
|
||||
AssignProcessToJobObject(job.value,process.value);
|
||||
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;
|
||||
auto deadline=GetTickCount64()+options.timeout;
|
||||
const auto read=[&](HANDLE pipe,std::string &data,size_t limit)
|
||||
{
|
||||
DWORD waiting{},readBytes{};
|
||||
char buffer[8192];
|
||||
if(!PeekNamedPipe(pipe,nullptr,0,nullptr,&waiting,nullptr))
|
||||
{
|
||||
if(GetLastError()==ERROR_BROKEN_PIPE) return false;
|
||||
gitWindowsError("Could not read Git output");
|
||||
}
|
||||
if(!waiting) return false;
|
||||
if(!ReadFile(pipe,buffer,std::min<DWORD>(waiting,sizeof(buffer)),&readBytes,nullptr))
|
||||
gitWindowsError("Could not read Git output");
|
||||
if(data.size()+readBytes>limit) throw std::runtime_error("Git output was too large to display.");
|
||||
data.append(buffer,readBytes);
|
||||
return readBytes!=0;
|
||||
};
|
||||
for(;;)
|
||||
{
|
||||
if(stop.stop_requested()) throw std::runtime_error("Git request canceled.");
|
||||
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)
|
||||
{
|
||||
if(read(out.value,result.output,maximum) || read(error.value,result.error,256*1024))
|
||||
continue;
|
||||
if(!GetExitCodeProcess(process.value,&result.exitCode)) gitWindowsError("Could not read Git status");
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(...)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
void checkGit(const GitOutput &result,const char *operation,bool allowDifference=false)
|
||||
{
|
||||
if(!result.exitCode || (allowDifference && result.exitCode==1)) return;
|
||||
auto detail=result.error;
|
||||
while(!detail.empty() && (detail.back()=='\r' || detail.back()=='\n')) detail.pop_back();
|
||||
throw std::runtime_error(detail.empty()?std::string(operation):std::string(operation)+"\r\n"+detail);
|
||||
}
|
||||
|
||||
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 output.");
|
||||
const auto field=input.substr(0,separator);
|
||||
input.remove_prefix(separator+1);
|
||||
return field;
|
||||
}
|
||||
|
||||
std::wstring statusPath(std::string_view value)
|
||||
{
|
||||
if(value.empty() || value.starts_with('/') || value.find_first_of("\\:")!=value.npos)
|
||||
throw std::runtime_error("Git returned an unsupported worktree path.");
|
||||
for(auto suffix=value;!suffix.empty();)
|
||||
{
|
||||
const auto slash=suffix.find('/');
|
||||
const auto part=suffix.substr(0,slash);
|
||||
if(part=="." || part==".." || part.empty())
|
||||
throw std::runtime_error("Git returned an unsupported worktree path.");
|
||||
if(slash==suffix.npos) break;
|
||||
suffix.remove_prefix(slash+1);
|
||||
}
|
||||
return wide(std::string(value));
|
||||
}
|
||||
|
||||
std::vector<GitChange> parseGitStatus(std::string_view output)
|
||||
{
|
||||
std::vector<GitChange> result;
|
||||
while(!output.empty())
|
||||
{
|
||||
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(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))});
|
||||
else
|
||||
{
|
||||
if(code[0]!=' ') result.push_back({GitChangeKind::staged,path,origin,std::wstring(1,code[0])});
|
||||
if(code[1]!=' ') result.push_back({GitChangeKind::unstaged,path,origin,std::wstring(1,code[1])});
|
||||
}
|
||||
}
|
||||
std::sort(result.begin(),result.end(),[](const auto &left,const auto &right) {
|
||||
return std::tie(left.kind,left.path)<std::tie(right.kind,right.path);
|
||||
});
|
||||
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)
|
||||
{
|
||||
GitChanges result;
|
||||
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.");
|
||||
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.");
|
||||
result.checkout=readCheckout(result.executable,result.root,stop);
|
||||
result.entries=readStatus(result.executable,result.root,stop);
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string readGitPatch(const std::filesystem::path &git,const std::filesystem::path &root,
|
||||
const GitChange &change,std::stop_token stop)
|
||||
{
|
||||
std::vector<std::wstring> args{L"diff",L"--no-color",L"--no-ext-diff",L"--no-textconv",L"--find-renames"};
|
||||
const bool untracked=change.kind==GitChangeKind::untracked;
|
||||
if(untracked) args.push_back(L"--no-index");
|
||||
if(change.kind==GitChangeKind::staged) args.push_back(L"--cached");
|
||||
args.push_back(L"--");
|
||||
if(untracked) args.push_back(L"/dev/null");
|
||||
else if(!change.oldPath.empty()) args.push_back(change.oldPath);
|
||||
args.push_back(change.path);
|
||||
auto patch=runGit(git,root,args,2*1024*1024,stop);
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
#pragma once
|
||||
#include <filesystem>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
enum class GitChangeKind { staged, unstaged, untracked };
|
||||
|
||||
struct GitChange
|
||||
{
|
||||
GitChangeKind kind;
|
||||
std::wstring path;
|
||||
std::wstring oldPath;
|
||||
std::wstring flags;
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,904 @@
|
||||
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{},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> 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,gitSwitch=574,gitBranch=575,gitMore=576;
|
||||
constexpr int gitIndexAction=577,gitCommitAction=578;
|
||||
|
||||
const wchar_t *gitChangeKindName(GitChangeKind kind)
|
||||
{
|
||||
switch(kind)
|
||||
{
|
||||
case GitChangeKind::staged: return L"Staged";
|
||||
case GitChangeKind::unstaged: return L"Unstaged";
|
||||
case GitChangeKind::untracked: return L"Untracked";
|
||||
}
|
||||
return L"";
|
||||
}
|
||||
|
||||
const GitChange *selectedGitChange(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.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 queueGitPreview(GitChangesView &view)
|
||||
{
|
||||
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::previewQuickViewText(view.preview,L"Diff · Reading Git changes…",{});
|
||||
return;
|
||||
}
|
||||
if(!view.failure.empty())
|
||||
{
|
||||
ks::files::previewQuickViewText(view.preview,L"Git status failed",view.failure);
|
||||
return;
|
||||
}
|
||||
if(const auto *entry=selectedGitChange(view))
|
||||
{
|
||||
view.requested=GitPreview{gitDiffHeading(*entry),*entry};
|
||||
view.previewAt=GetTickCount64()+100;
|
||||
ks::files::previewQuickViewText(view.preview,view.requested->heading+L" · Loading…",{});
|
||||
}
|
||||
else ks::files::previewQuickViewText(view.preview,L"Diff · Select a change",{});
|
||||
}
|
||||
|
||||
void renderGitChanges(GitChangesView &view,std::optional<GitChange> previous={})
|
||||
{
|
||||
auto query=dialogFieldText(view.filter);
|
||||
std::replace(query.begin(),query.end(),L'\\',L'/');
|
||||
const auto matches=[&](std::wstring_view path)
|
||||
{
|
||||
return query.empty() || (!path.empty() && FindNLSStringEx(LOCALE_NAME_INVARIANT,FIND_FROMSTART|NORM_IGNORECASE,
|
||||
path.data(),static_cast<int>(path.size()),query.data(),static_cast<int>(query.size()),
|
||||
nullptr,nullptr,nullptr,0)>=0);
|
||||
};
|
||||
SendMessageW(view.list,WM_SETREDRAW,FALSE,0);
|
||||
SendMessageW(view.list,LB_RESETCONTENT,0,0);
|
||||
LRESULT selected=0,count=0;
|
||||
for(size_t index=0;index<view.data.entries.size();++index)
|
||||
{
|
||||
const auto &entry=view.data.entries[index];
|
||||
if(!matches(entry.path) && !matches(entry.oldPath)) continue;
|
||||
auto state=std::wstring(gitChangeKindName(entry.kind));
|
||||
state.resize(10,L' ');
|
||||
state+=entry.flags;
|
||||
state.resize(13,L' ');
|
||||
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;
|
||||
SendMessageW(view.list,LB_SETITEMDATA,row,index);
|
||||
if(previous && previous->path==entry.path && previous->kind==entry.kind) selected=row;
|
||||
}
|
||||
if(count) SendMessageW(view.list,LB_SETCURSEL,selected,0);
|
||||
SendMessageW(view.list,WM_SETREDRAW,TRUE,0);
|
||||
InvalidateRect(view.list,nullptr,TRUE);
|
||||
InvalidateRect(view.host,nullptr,FALSE);
|
||||
updateGitChangesStatus(view,count);
|
||||
queueGitPreview(view);
|
||||
}
|
||||
|
||||
void refreshGitChanges(GitChangesView &view)
|
||||
{
|
||||
if(view.refresh.valid() || gitActionPending(view)) return;
|
||||
view.failure.clear();
|
||||
view.stopRefresh=std::stop_source{};
|
||||
try
|
||||
{
|
||||
std::packaged_task<GitChanges()> task([folder=view.folder,stop=view.stopRefresh.get_token()] {
|
||||
return ks::files::readGitChanges(folder,stop);
|
||||
});
|
||||
auto pending=task.get_future();
|
||||
std::thread(std::move(task)).detach();
|
||||
view.refresh=std::move(pending);
|
||||
updateGitChangesStatus(view);
|
||||
queueGitPreview(view);
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
view.failure="Could not start Git.";
|
||||
renderGitChanges(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);
|
||||
const auto selected=entry?std::optional(*entry):std::nullopt;
|
||||
try
|
||||
{
|
||||
view.data=view.refresh.get();
|
||||
SetWindowTextW(view.heading,(L"Git Changes · "+view.data.root.native()).c_str());
|
||||
renderGitChanges(view,selected);
|
||||
}
|
||||
catch(const std::exception &error)
|
||||
{
|
||||
view.data={};
|
||||
view.failure=error.what();
|
||||
renderGitChanges(view);
|
||||
}
|
||||
}
|
||||
if(view.historyTask.valid() && view.historyTask.wait_for(0ms)==std::future_status::ready)
|
||||
finishGitHistory(view);
|
||||
if(view.previewAt && GetTickCount64()>=view.previewAt)
|
||||
{
|
||||
view.previewAt=0;
|
||||
view.stopPreview=std::stop_source{};
|
||||
try
|
||||
{
|
||||
std::packaged_task<std::string()> task([git=view.data.executable,root=view.data.root,
|
||||
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.previewTask=std::move(pending);
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
ks::files::previewQuickViewText(view.preview,view.requested->heading,"Could not start the Git preview.");
|
||||
}
|
||||
}
|
||||
if(view.previewTask.valid() && view.previewTask.wait_for(0ms)==std::future_status::ready)
|
||||
{
|
||||
try
|
||||
{
|
||||
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::previewQuickViewText(view.preview,view.requested->heading,error.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void openGitWorkingFile(GitChangesView &view,bool edit)
|
||||
{
|
||||
const auto *entry=selectedGitChange(view);
|
||||
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()))
|
||||
{
|
||||
SetWindowTextW(view.status,L"This path cannot be opened as a Windows file.");
|
||||
return;
|
||||
}
|
||||
auto path=view.data.root/relative.make_preferred();
|
||||
const auto attributes=GetFileAttributesW(path.c_str());
|
||||
if(attributes==INVALID_FILE_ATTRIBUTES || (attributes&FILE_ATTRIBUTE_DIRECTORY))
|
||||
{
|
||||
SetWindowTextW(view.status,L"No current working file for this change.");
|
||||
return;
|
||||
}
|
||||
const auto owner=GetParent(view.host);
|
||||
if(!edit && ks::files::isImagePath(path)) ks::files::openImageWindow(owner,{path},path,textWindowDialogs());
|
||||
else ks::files::openTextWindow(owner,path,edit,textWindowDialogs());
|
||||
}
|
||||
|
||||
void layoutGitChildren(GitChangesView &view)
|
||||
{
|
||||
RECT bounds{};
|
||||
GetClientRect(view.host,&bounds);
|
||||
const int middle=panelDivider(bounds.right);
|
||||
const auto place=[](HWND control,int x,int y,int width,int height)
|
||||
{
|
||||
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,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-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-(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.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)
|
||||
{
|
||||
const auto *create=reinterpret_cast<const CREATESTRUCTW *>(lp);
|
||||
SetWindowLongPtrW(window,GWLP_USERDATA,reinterpret_cast<LONG_PTR>(create->lpCreateParams));
|
||||
}
|
||||
const auto view=reinterpret_cast<GitChangesView *>(GetWindowLongPtrW(window,GWLP_USERDATA));
|
||||
if(!view) return DefWindowProcW(window,message,wp,lp);
|
||||
switch(message)
|
||||
{
|
||||
case WM_CREATE:
|
||||
{
|
||||
view->host=window;
|
||||
const auto make=[&](const wchar_t *type,const wchar_t *text,DWORD style,int id=0)
|
||||
{
|
||||
return CreateWindowW(type,text,WS_CHILD|WS_VISIBLE|style,0,0,0,0,window,
|
||||
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 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->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;
|
||||
}
|
||||
case WM_SIZE:
|
||||
if(view->preview) layoutGitChildren(*view);
|
||||
return 0;
|
||||
case WM_TIMER:
|
||||
if(wp==gitChangesTimer) pollGitChanges(*view);
|
||||
return 0;
|
||||
case WM_COMMAND:
|
||||
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) 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;
|
||||
return TRUE;
|
||||
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;
|
||||
std::wstring label(count+1,L'\0');
|
||||
if(SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast<LPARAM>(label.data()))==LB_ERR)
|
||||
return TRUE;
|
||||
const bool selected=item.itemState&ODS_SELECTED;
|
||||
paintText(item.hDC,item.rcItem,label.c_str(),colors[Text],colors[selected?PanelCursor:PanelBlue]);
|
||||
return TRUE;
|
||||
}
|
||||
case WM_CTLCOLORSTATIC:
|
||||
case WM_CTLCOLOREDIT:
|
||||
case WM_CTLCOLORLISTBOX:
|
||||
{
|
||||
const auto dc=reinterpret_cast<HDC>(wp);
|
||||
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);
|
||||
}
|
||||
case WM_PAINT:
|
||||
{
|
||||
PAINTSTRUCT paint{};
|
||||
const auto dc=BeginPaint(window,&paint);
|
||||
FillRect(dc,&paint.rcPaint,blue);
|
||||
if(view->list) paintScrollPosition(window,dc,view->list,colors[PanelBlue]);
|
||||
EndPaint(window,&paint);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return DefWindowProcW(window,message,wp,lp);
|
||||
}
|
||||
|
||||
void layoutGitChanges(HWND window)
|
||||
{
|
||||
if(!gitChangesView) return;
|
||||
RECT bounds{};
|
||||
GetClientRect(window,&bounds);
|
||||
SetWindowPos(gitChangesView->host,HWND_TOP,0,0,bounds.right,bounds.bottom,SWP_NOACTIVATE|SWP_SHOWWINDOW);
|
||||
layoutGitChildren(*gitChangesView);
|
||||
}
|
||||
|
||||
bool showingGitChanges()
|
||||
{
|
||||
return static_cast<bool>(gitChangesView);
|
||||
}
|
||||
|
||||
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->stopPreview.request_stop();
|
||||
view->stopHistory.request_stop();
|
||||
view->stopMutation.request_stop();
|
||||
if(IsWindow(view->host)) DestroyWindow(view->host);
|
||||
if(restore)
|
||||
{
|
||||
layout(owner);
|
||||
restoreCommandFocus();
|
||||
showFileDetails(panels[active]);
|
||||
}
|
||||
}
|
||||
|
||||
bool gitChangesAvailable(const Panel &panel)
|
||||
{
|
||||
return !terminalVisible && !panel.directory.empty() && !panel.ftp && !panel.peer && !panel.archive &&
|
||||
!windowsNetworkPath(panel.directory);
|
||||
}
|
||||
|
||||
void openGitChanges(HWND owner,const Panel &panel)
|
||||
{
|
||||
if(gitChangesView || !gitChangesAvailable(panel)) return;
|
||||
const auto instance=GetModuleHandleW(nullptr);
|
||||
static const bool registered=[instance]
|
||||
{
|
||||
WNDCLASSW type{};
|
||||
type.lpfnWndProc=gitChangesProcedure;
|
||||
type.hInstance=instance;
|
||||
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
|
||||
type.lpszClassName=gitChangesClass;
|
||||
return RegisterClassW(&type)!=0;
|
||||
}();
|
||||
if(!registered) return;
|
||||
auto view=std::make_unique<GitChangesView>();
|
||||
view->folder=panel.directory;
|
||||
if(!CreateWindowW(gitChangesClass,L"Git Changes",WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS,
|
||||
0,0,0,0,owner,nullptr,instance,view.get()))
|
||||
{
|
||||
setStatus(L"Could not open Git Changes.");
|
||||
return;
|
||||
}
|
||||
gitChangesView=std::move(view);
|
||||
closePanelSearch();
|
||||
hideCompletion();
|
||||
layout(owner);
|
||||
ShowWindow(gitChangesView->preview,SW_SHOWNA);
|
||||
SetFocus(gitChangesView->list);
|
||||
refreshGitChanges(*gitChangesView);
|
||||
}
|
||||
|
||||
bool handleGitChangesKey(HWND owner,const MSG &message)
|
||||
{
|
||||
auto &view=*gitChangesView;
|
||||
if(message.message!=WM_KEYDOWN || FilesModalDialog::activeFor(owner) ||
|
||||
(message.hwnd!=owner && message.hwnd!=view.host && !IsChild(view.host,message.hwnd))) return false;
|
||||
const auto key=message.wParam;
|
||||
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')
|
||||
{
|
||||
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))
|
||||
SendMessageW(view.list,WM_KEYDOWN,key,message.lParam);
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
+338
-97
@@ -12,15 +12,9 @@ DWORD probeDeleteAccess(const fs::path &path)
|
||||
return probe.value==INVALID_HANDLE_VALUE?GetLastError():ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
struct LockProcess
|
||||
{
|
||||
DWORD pid;
|
||||
FILETIME started{};
|
||||
std::wstring name;
|
||||
};
|
||||
struct LockScan
|
||||
{
|
||||
std::vector<LockProcess> processes;
|
||||
std::set<DWORD> pids;
|
||||
bool incomplete{};
|
||||
};
|
||||
|
||||
@@ -30,7 +24,6 @@ LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token st
|
||||
const auto query=reinterpret_cast<decltype(&NtQueryInformationFile)>(
|
||||
GetProcAddress(GetModuleHandleW(L"ntdll.dll"),"NtQueryInformationFile"));
|
||||
if(!query) { result.incomplete=true; return result; }
|
||||
std::set<DWORD> pids;
|
||||
std::vector<ULONG_PTR> buffer(128);
|
||||
const auto inspect=[&](const fs::path &path) {
|
||||
const auto error=probeDeleteAccess(path);
|
||||
@@ -63,7 +56,7 @@ LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token st
|
||||
}
|
||||
for(ULONG i=0;i<count;++i)
|
||||
if(const auto pid=buffer[i+1];pid && pid<=MAXDWORD && pid!=GetCurrentProcessId())
|
||||
pids.insert(static_cast<DWORD>(pid));
|
||||
result.pids.insert(static_cast<DWORD>(pid));
|
||||
};
|
||||
auto remaining=8192u;
|
||||
const auto deadline=GetTickCount64()+4000;
|
||||
@@ -90,162 +83,410 @@ LockScan scanLockProcesses(const std::vector<fs::path> &paths,std::stop_token st
|
||||
}
|
||||
if(error) result.incomplete=true;
|
||||
}
|
||||
for(const auto pid:pids)
|
||||
return result;
|
||||
}
|
||||
|
||||
struct ProcessIdentity
|
||||
{
|
||||
DWORD pid{};
|
||||
uint64_t started{};
|
||||
bool operator==(const ProcessIdentity &) const = default;
|
||||
};
|
||||
|
||||
struct ProcessEntry
|
||||
{
|
||||
ProcessIdentity identity;
|
||||
std::wstring name;
|
||||
fs::path image;
|
||||
std::optional<uint64_t> workingSet;
|
||||
std::optional<double> cpu;
|
||||
};
|
||||
|
||||
struct ProcessScan
|
||||
{
|
||||
std::vector<ProcessEntry> entries;
|
||||
bool incomplete{};
|
||||
};
|
||||
|
||||
constexpr uint64_t processTimeTicks(const FILETIME &time)
|
||||
{
|
||||
return (uint64_t(time.dwHighDateTime)<<32)|time.dwLowDateTime;
|
||||
}
|
||||
|
||||
struct ProcessTimes
|
||||
{
|
||||
uint64_t started, busy;
|
||||
std::chrono::steady_clock::time_point measured;
|
||||
};
|
||||
|
||||
std::optional<ProcessTimes> readProcessTimes(HANDLE process)
|
||||
{
|
||||
FILETIME started{},exited{},kernel{},user{};
|
||||
if(!GetProcessTimes(process,&started,&exited,&kernel,&user)) return {};
|
||||
return ProcessTimes{processTimeTicks(started),processTimeTicks(kernel)+processTimeTicks(user),
|
||||
std::chrono::steady_clock::now()};
|
||||
}
|
||||
|
||||
ProcessScan scanProcesses(const std::vector<fs::path> &files,std::stop_token stop)
|
||||
{
|
||||
ProcessScan result;
|
||||
LockScan locks;
|
||||
if(!files.empty())
|
||||
{
|
||||
Handle process{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,pid)};
|
||||
LockProcess entry{pid};
|
||||
if(process.value)
|
||||
locks=scanLockProcesses(files,stop);
|
||||
result.incomplete=locks.incomplete;
|
||||
if(locks.pids.empty() || stop.stop_requested()) return result;
|
||||
}
|
||||
const Handle snapshot{CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0)};
|
||||
if(snapshot.value==INVALID_HANDLE_VALUE)
|
||||
throw std::system_error(GetLastError(),std::system_category());
|
||||
PROCESSENTRY32W process{sizeof(PROCESSENTRY32W)};
|
||||
if(!Process32FirstW(snapshot.value,&process))
|
||||
throw std::system_error(GetLastError(),std::system_category());
|
||||
do
|
||||
{
|
||||
const auto pid=process.th32ProcessID;
|
||||
if(files.empty() || locks.pids.contains(pid))
|
||||
result.entries.push_back({{pid},process.szExeFile});
|
||||
} while(!stop.stop_requested() && Process32NextW(snapshot.value,&process));
|
||||
if(!stop.stop_requested() && GetLastError()!=ERROR_NO_MORE_FILES) result.incomplete=true;
|
||||
|
||||
std::map<DWORD,ProcessTimes> initial;
|
||||
for(const auto &entry:result.entries)
|
||||
{
|
||||
if(stop.stop_requested()) return {};
|
||||
const Handle handle{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,entry.identity.pid)};
|
||||
if(handle.value)
|
||||
if(const auto time=readProcessTimes(handle.value)) initial.emplace(entry.identity.pid,*time);
|
||||
}
|
||||
if(!initial.empty()) std::this_thread::sleep_for(std::chrono::milliseconds(350));
|
||||
const auto logicalCpus=std::max(1ul,static_cast<unsigned long>(GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)));
|
||||
std::array<wchar_t,32768> image;
|
||||
for(auto &entry:result.entries)
|
||||
{
|
||||
if(stop.stop_requested()) return {};
|
||||
const Handle handle{OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,entry.identity.pid)};
|
||||
if(!handle.value) continue;
|
||||
const auto current=readProcessTimes(handle.value);
|
||||
const auto before=initial.find(entry.identity.pid);
|
||||
if(current && before!=initial.end() && current->started!=before->second.started) continue;
|
||||
if(current)
|
||||
{
|
||||
FILETIME exit{},kernel{},user{};
|
||||
GetProcessTimes(process.value,&entry.started,&exit,&kernel,&user);
|
||||
wchar_t path[32768];
|
||||
DWORD count=std::size(path);
|
||||
if(QueryFullProcessImageNameW(process.value,0,path,&count))
|
||||
entry.name=fs::path(std::wstring_view(path,count)).filename().wstring();
|
||||
entry.identity.started=current->started;
|
||||
if(before!=initial.end() && current->busy>=before->second.busy)
|
||||
{
|
||||
const auto elapsed=std::chrono::duration<double>(current->measured-before->second.measured).count();
|
||||
if(elapsed>0)
|
||||
entry.cpu=std::clamp((current->busy-before->second.busy)*0.00001/(elapsed*logicalCpus),0.0,100.0);
|
||||
}
|
||||
}
|
||||
if(entry.name.empty()) entry.name=L"Unknown process";
|
||||
result.processes.push_back(std::move(entry));
|
||||
DWORD count=image.size();
|
||||
if(QueryFullProcessImageNameW(handle.value,0,image.data(),&count))
|
||||
entry.image=std::wstring_view(image.data(),count);
|
||||
PROCESS_MEMORY_COUNTERS memory{sizeof(memory)};
|
||||
if(K32GetProcessMemoryInfo(handle.value,&memory,sizeof(memory))) entry.workingSet=memory.WorkingSetSize;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
struct LockDialog
|
||||
constexpr int processScope=430,processList=431,processDivider=432,processEnd=433,processRefresh=434,
|
||||
processFilter=435,processSort=436,processReveal=437,processImage=438,processColumns=439,processStatus=443;
|
||||
constexpr UINT_PTR processScanTimer=1;
|
||||
enum class ProcessOrder { pid, cpu, memory, name, image };
|
||||
|
||||
struct ProcessDialog
|
||||
{
|
||||
std::vector<fs::path> paths;
|
||||
std::vector<LockProcess> processes;
|
||||
std::future<LockScan> scan;
|
||||
std::vector<fs::path> files;
|
||||
std::vector<ProcessEntry> entries;
|
||||
std::future<ProcessScan> scan;
|
||||
std::stop_source stop;
|
||||
std::wstring failure;
|
||||
fs::path reveal;
|
||||
bool incomplete{};
|
||||
};
|
||||
|
||||
constexpr UINT_PTR lockScanTimer=1;
|
||||
const ProcessEntry *selectedProcess(HWND dialog,const ProcessDialog &state)
|
||||
{
|
||||
const auto row=SendDlgItemMessageW(dialog,processList,LB_GETCURSEL,0,0);
|
||||
if(row==LB_ERR) return nullptr;
|
||||
const auto index=SendDlgItemMessageW(dialog,processList,LB_GETITEMDATA,row,0);
|
||||
return index>=0 && size_t(index)<state.entries.size()?&state.entries[index]:nullptr;
|
||||
}
|
||||
|
||||
void refreshLockProcesses(HWND window,LockDialog &state,std::shared_ptr<Handle> terminated={})
|
||||
bool mayEndProcess(ProcessIdentity identity)
|
||||
{
|
||||
return identity.pid && identity.pid!=GetCurrentProcessId() && identity.started;
|
||||
}
|
||||
|
||||
void updateSelectedProcess(HWND dialog,const ProcessDialog &state)
|
||||
{
|
||||
const auto *entry=selectedProcess(dialog,state);
|
||||
const bool hasImage=entry && !entry->image.empty();
|
||||
SetDlgItemTextW(dialog,processImage,hasImage?entry->image.c_str():entry?L"Unavailable":L"");
|
||||
EnableWindow(GetDlgItem(dialog,processReveal),!state.scan.valid() && hasImage);
|
||||
EnableWindow(GetDlgItem(dialog,processEnd),!state.scan.valid() && entry && mayEndProcess(entry->identity));
|
||||
}
|
||||
|
||||
std::wstring processColumnsText(std::wstring_view pid,std::wstring_view cpu,std::wstring_view memory,
|
||||
std::wstring_view name)
|
||||
{
|
||||
std::wostringstream fields;
|
||||
fields<<std::right<<std::setw(10)<<pid<<L" "<<std::setw(7)<<cpu<<L" "<<std::setw(12)<<memory<<L" "<<name;
|
||||
return fields.str();
|
||||
}
|
||||
|
||||
int compareProcessNames(const std::wstring &left,const std::wstring &right)
|
||||
{
|
||||
return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE);
|
||||
}
|
||||
|
||||
void renderProcessList(HWND dialog,const ProcessDialog &state,std::optional<ProcessIdentity> preferred={})
|
||||
{
|
||||
const auto field=GetDlgItem(dialog,processFilter);
|
||||
std::wstring query(GetWindowTextLengthW(field)+1,L'\0');
|
||||
query.resize(GetWindowTextW(field,query.data(),static_cast<int>(query.size())));
|
||||
const auto contains=[&](std::wstring_view value)
|
||||
{
|
||||
return query.empty() || (!value.empty() && FindNLSStringEx(LOCALE_NAME_INVARIANT,FIND_FROMSTART|NORM_IGNORECASE,
|
||||
value.data(),static_cast<int>(value.size()),query.c_str(),static_cast<int>(query.size()),nullptr,
|
||||
nullptr,nullptr,0)>=0);
|
||||
};
|
||||
std::vector<size_t> rows;
|
||||
for(size_t i=0;i<state.entries.size();++i)
|
||||
{
|
||||
const auto &entry=state.entries[i];
|
||||
if(contains(entry.name) || contains(entry.image.native()) || contains(std::to_wstring(entry.identity.pid)))
|
||||
rows.push_back(i);
|
||||
}
|
||||
const auto order=static_cast<ProcessOrder>(SendDlgItemMessageW(dialog,processSort,CB_GETCURSEL,0,0));
|
||||
std::sort(rows.begin(),rows.end(),[&](size_t a,size_t b)
|
||||
{
|
||||
const auto &left=state.entries[a],&right=state.entries[b];
|
||||
if(order==ProcessOrder::cpu && left.cpu!=right.cpu) return left.cpu>right.cpu;
|
||||
if(order==ProcessOrder::memory && left.workingSet!=right.workingSet) return left.workingSet>right.workingSet;
|
||||
if(order==ProcessOrder::name || order==ProcessOrder::image)
|
||||
{
|
||||
const auto names=order==ProcessOrder::name?compareProcessNames(left.name,right.name):
|
||||
compareProcessNames(left.image.native(),right.image.native());
|
||||
if(names!=CSTR_EQUAL) return names==CSTR_LESS_THAN;
|
||||
}
|
||||
return left.identity.pid<right.identity.pid;
|
||||
});
|
||||
const auto list=GetDlgItem(dialog,processList);
|
||||
SendMessageW(list,WM_SETREDRAW,FALSE,0);
|
||||
SendMessageW(list,LB_RESETCONTENT,0,0);
|
||||
LRESULT selected=0;
|
||||
for(const auto index:rows)
|
||||
{
|
||||
const auto &entry=state.entries[index];
|
||||
wchar_t cpu[16]=L"—";
|
||||
if(entry.cpu) swprintf_s(cpu,L"%.1f%%",*entry.cpu);
|
||||
const auto text=processColumnsText(std::to_wstring(entry.identity.pid),cpu,
|
||||
entry.workingSet?formatSize(*entry.workingSet):L"—",entry.name);
|
||||
const auto row=SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(text.c_str()));
|
||||
if(row<0) continue;
|
||||
SendMessageW(list,LB_SETITEMDATA,row,index);
|
||||
if(preferred==entry.identity) selected=row;
|
||||
}
|
||||
if(!rows.empty()) SendMessageW(list,LB_SETCURSEL,selected,0);
|
||||
SendMessageW(list,WM_SETREDRAW,TRUE,0);
|
||||
InvalidateRect(list,nullptr,TRUE);
|
||||
updateSelectedProcess(dialog,state);
|
||||
|
||||
std::wstring status;
|
||||
if(state.scan.valid()) status=state.files.empty()?L"Sampling processes…":L"Checking files for locking processes…";
|
||||
else if(!state.failure.empty()) status=state.failure;
|
||||
else if(state.entries.empty()) status=state.files.empty()?L"No processes found.":L"No locking processes found.";
|
||||
else if(rows.empty()) status=L"No processes match the filter.";
|
||||
else status=std::to_wstring(rows.size())+(query.empty()?L"":L" of "+std::to_wstring(state.entries.size()))+L" shown";
|
||||
if(state.incomplete && !state.scan.valid() && state.failure.empty()) status+=L" Some items could not be checked.";
|
||||
SetDlgItemTextW(dialog,processStatus,status.c_str());
|
||||
}
|
||||
|
||||
void refreshProcesses(HWND dialog,ProcessDialog &state,std::shared_ptr<Handle> ended={})
|
||||
{
|
||||
if(state.scan.valid()) return;
|
||||
state.processes.clear();
|
||||
SendDlgItemMessageW(window,431,LB_RESETCONTENT,0,0);
|
||||
EnableWindow(GetDlgItem(window,433),FALSE);
|
||||
EnableWindow(GetDlgItem(window,434),FALSE);
|
||||
SetDlgItemTextW(window,430,L"Checking which processes are using the file or folder…");
|
||||
const auto *entry=selectedProcess(dialog,state);
|
||||
const auto selected=entry?std::optional(entry->identity):std::nullopt;
|
||||
state.failure.clear();
|
||||
try
|
||||
{
|
||||
std::packaged_task<LockScan()> task([paths=state.paths,stop=state.stop.get_token(),terminated=std::move(terminated)] {
|
||||
if(terminated) WaitForSingleObject(terminated->value,2500);
|
||||
return scanLockProcesses(paths,stop);
|
||||
std::packaged_task<ProcessScan()> task([files=state.files,stop=state.stop.get_token(),ended=std::move(ended)] {
|
||||
if(ended) WaitForSingleObject(ended->value,2500);
|
||||
return scanProcesses(files,stop);
|
||||
});
|
||||
auto future=task.get_future();
|
||||
if(!SetTimer(window,lockScanTimer,50,nullptr))
|
||||
if(!SetTimer(dialog,processScanTimer,50,nullptr))
|
||||
throw std::runtime_error("Could not start the process scan.");
|
||||
std::thread(std::move(task)).detach();
|
||||
state.scan=std::move(future);
|
||||
}
|
||||
catch(const std::exception &)
|
||||
{
|
||||
KillTimer(window,lockScanTimer);
|
||||
EnableWindow(GetDlgItem(window,434),TRUE);
|
||||
SetDlgItemTextW(window,430,L"Could not start the process scan.");
|
||||
KillTimer(dialog,processScanTimer);
|
||||
state.failure=L"Could not start the process scan.";
|
||||
}
|
||||
EnableWindow(GetDlgItem(dialog,processRefresh),!state.scan.valid());
|
||||
renderProcessList(dialog,state,selected);
|
||||
}
|
||||
|
||||
void endLockProcess(HWND window,LockDialog &state)
|
||||
void endFileProcess(HWND dialog,ProcessDialog &state)
|
||||
{
|
||||
const auto index=SendDlgItemMessageW(window,431,LB_GETCURSEL,0,0);
|
||||
if(index<0 || size_t(index)>=state.processes.size()) return;
|
||||
const auto &entry=state.processes[index];
|
||||
auto error=[&](const wchar_t *message) {
|
||||
showFilesNotice(window,message,L"End process",{.tone=FilesNoticeTone::warning});
|
||||
const auto *entry=selectedProcess(dialog,state);
|
||||
if(state.scan.valid() || !entry || !mayEndProcess(entry->identity)) return;
|
||||
const auto error=[&](const wchar_t *message)
|
||||
{
|
||||
showFilesNotice(dialog,message,L"End process",{.tone=FilesNoticeTone::warning});
|
||||
};
|
||||
auto process=std::make_shared<Handle>();
|
||||
process->value=OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,entry.pid);
|
||||
FILETIME started{},exited{},kernel{},user{};
|
||||
const auto process=std::make_shared<Handle>();
|
||||
process->value=OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE,FALSE,entry->identity.pid);
|
||||
const auto current=process->value?readProcessTimes(process->value):std::nullopt;
|
||||
BOOL critical{};
|
||||
if(!process->value || !(entry.started.dwHighDateTime || entry.started.dwLowDateTime) ||
|
||||
!GetProcessTimes(process->value,&started,&exited,&kernel,&user) ||
|
||||
CompareFileTime(&started,&entry.started)!=0 || !IsProcessCritical(process->value,&critical) || critical)
|
||||
if(!current || current->started!=entry->identity.started ||
|
||||
!IsProcessCritical(process->value,&critical) || critical)
|
||||
{
|
||||
error(L"This process has exited, is protected, or cannot be identified.");
|
||||
return;
|
||||
}
|
||||
const auto question=L"End "+entry.name+L" (PID "+std::to_wstring(entry.pid)+
|
||||
const auto question=L"End "+entry->name+L" (PID "+std::to_wstring(entry->identity.pid)+
|
||||
L")?\r\nUnsaved work in the process may be lost.";
|
||||
if(showFilesNotice(window,question.c_str(),L"End process",{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES)
|
||||
if(showFilesNotice(dialog,question.c_str(),L"End process",{.confirm=true,.tone=FilesNoticeTone::warning})!=IDYES)
|
||||
return;
|
||||
if(WaitForSingleObject(process->value,0)==WAIT_TIMEOUT && !TerminateProcess(process->value,1))
|
||||
const auto alive=WaitForSingleObject(process->value,0);
|
||||
if(alive!=WAIT_OBJECT_0 && (alive!=WAIT_TIMEOUT || !TerminateProcess(process->value,1)))
|
||||
{
|
||||
const auto message=ks::lastError(L"Could not end the process");
|
||||
error(message.c_str());
|
||||
const auto reason=ks::lastError(L"Could not end the process");
|
||||
error(reason.c_str());
|
||||
return;
|
||||
}
|
||||
refreshLockProcesses(window,state,std::move(process));
|
||||
refreshProcesses(dialog,state,process);
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK lockProcessesDialog(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||||
INT_PTR CALLBACK processesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
SetWindowLongPtrW(window,DWLP_USER,lp);
|
||||
prepareCopyDialog(window);
|
||||
for(const auto id:{430,431}) SendDlgItemMessageW(window,id,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
|
||||
const auto list=GetDlgItem(window,431);
|
||||
RECT bounds{};
|
||||
GetWindowRect(list,&bounds);
|
||||
auto &state=*reinterpret_cast<ProcessDialog *>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareTextDialog(dialog);
|
||||
layoutDialogContent(dialog,processScope);
|
||||
if(state.files.empty()) SetDlgItemTextW(dialog,processScope,L"This PC");
|
||||
else
|
||||
{
|
||||
auto scope=L"Locks for "+state.files.front().native();
|
||||
if(state.files.size()>1) scope+=L" (+"+std::to_wstring(state.files.size()-1)+L" more)";
|
||||
SetDlgItemTextW(dialog,processScope,scope.c_str());
|
||||
}
|
||||
const auto filterField=GetDlgItem(dialog,processFilter);
|
||||
SendMessageW(filterField,EM_SETLIMITTEXT,1024,0);
|
||||
const auto sortField=GetDlgItem(dialog,processSort);
|
||||
for(const auto name:{L"PID",L"CPU",L"Memory",L"Name",L"Executable"})
|
||||
SendMessageW(sortField,CB_ADDSTRING,0,reinterpret_cast<LPARAM>(name));
|
||||
SendMessageW(sortField,CB_SETCURSEL,1,0);
|
||||
installFarCombo(sortField,filterField);
|
||||
SetDlgItemTextW(dialog,processColumns,processColumnsText(L"PID",L"CPU",L"Working set",L"Process").c_str());
|
||||
const auto list=GetDlgItem(dialog,processList);
|
||||
const auto bounds=dialogControlBounds(dialog,processList);
|
||||
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,window);
|
||||
layoutDialogButtons(window,432,{433,434,IDOK});
|
||||
SendMessageW(window,DM_SETDEFID,IDOK,0);
|
||||
SetFocus(GetDlgItem(window,IDOK));
|
||||
refreshLockProcesses(window,*reinterpret_cast<LockDialog *>(lp));
|
||||
installScrollBar(list,dialog);
|
||||
layoutDialogButtons(dialog,processDivider,{processReveal,processEnd,processRefresh,IDOK});
|
||||
SendMessageW(dialog,DM_SETDEFID,IDOK,0);
|
||||
SetFocus(filterField);
|
||||
refreshProcesses(dialog,state);
|
||||
return FALSE;
|
||||
}
|
||||
auto *data=reinterpret_cast<LockDialog *>(GetWindowLongPtrW(window,DWLP_USER));
|
||||
auto *data=reinterpret_cast<ProcessDialog *>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
if(!data) return FALSE;
|
||||
auto &state=*data;
|
||||
if(message==WM_TIMER && wp==lockScanTimer)
|
||||
if(message==WM_TIMER && wp==processScanTimer)
|
||||
{
|
||||
if(!state.scan.valid() || state.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready)
|
||||
return TRUE;
|
||||
KillTimer(window,lockScanTimer);
|
||||
EnableWindow(GetDlgItem(window,434),TRUE);
|
||||
KillTimer(dialog,processScanTimer);
|
||||
EnableWindow(GetDlgItem(dialog,processRefresh),TRUE);
|
||||
const auto *entry=selectedProcess(dialog,state);
|
||||
const auto selected=entry?std::optional(entry->identity):std::nullopt;
|
||||
try
|
||||
{
|
||||
auto result=state.scan.get();
|
||||
for(auto &entry:result.processes)
|
||||
{
|
||||
const auto label=entry.name+L" (PID "+std::to_wstring(entry.pid)+L")";
|
||||
if(SendDlgItemMessageW(window,431,LB_ADDSTRING,0,reinterpret_cast<LPARAM>(label.c_str()))>=0)
|
||||
state.processes.push_back(std::move(entry));
|
||||
}
|
||||
SetDlgItemTextW(window,430,state.processes.empty()?
|
||||
(result.incomplete?L"No processes found. Some items could not be checked.":L"No locking processes found."):
|
||||
(result.incomplete?L"Possible locking processes. The scan was incomplete.":L"Processes using locked files or folders."));
|
||||
if(!state.processes.empty())
|
||||
{
|
||||
SendDlgItemMessageW(window,431,LB_SETCURSEL,0,0);
|
||||
EnableWindow(GetDlgItem(window,433),TRUE);
|
||||
}
|
||||
state.entries=std::move(result.entries);
|
||||
state.incomplete=result.incomplete;
|
||||
}
|
||||
catch(const std::exception &) {SetDlgItemTextW(window,430,L"Could not check for locking processes.");}
|
||||
catch(const std::system_error &e) {state.failure=fileError(e);}
|
||||
catch(const std::exception &) {state.failure=L"Could not read the process list.";}
|
||||
renderProcessList(dialog,state,selected);
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_DRAWITEM && wp==processSort)
|
||||
{
|
||||
drawFarComboRow(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_CTLCOLORLISTBOX && reinterpret_cast<HWND>(lp)!=GetDlgItem(dialog,processList))
|
||||
{
|
||||
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)
|
||||
{
|
||||
switch(LOWORD(wp))
|
||||
const auto id=LOWORD(wp),notification=HIWORD(wp);
|
||||
if((id==processFilter && notification==EN_CHANGE) || (id==processSort && notification==CBN_SELCHANGE))
|
||||
{
|
||||
case 433: endLockProcess(window,state); return TRUE;
|
||||
case 434: refreshLockProcesses(window,state); return TRUE;
|
||||
const auto *entry=selectedProcess(dialog,state);
|
||||
renderProcessList(dialog,state,entry?std::optional(entry->identity):std::nullopt);
|
||||
return TRUE;
|
||||
}
|
||||
if(id==processList && notification==LBN_SELCHANGE)
|
||||
{
|
||||
updateSelectedProcess(dialog,state);
|
||||
return TRUE;
|
||||
}
|
||||
if(id==processReveal || (id==processList && notification==LBN_DBLCLK))
|
||||
{
|
||||
const auto *entry=selectedProcess(dialog,state);
|
||||
if(!state.scan.valid() && entry && !entry->image.empty())
|
||||
{
|
||||
state.reveal=entry->image;
|
||||
FilesModalDialog::finish(dialog,processReveal);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
switch(id)
|
||||
{
|
||||
case processEnd: endFileProcess(dialog,state); return TRUE;
|
||||
case processRefresh: refreshProcesses(dialog,state); return TRUE;
|
||||
case IDOK:
|
||||
case IDCANCEL: FilesModalDialog::finish(window,IDCANCEL); return TRUE;
|
||||
case IDCANCEL: FilesModalDialog::finish(dialog,IDCANCEL); return TRUE;
|
||||
}
|
||||
}
|
||||
if(message==WM_CLOSE) {FilesModalDialog::finish(window,IDCANCEL);return TRUE;}
|
||||
return paintCopyDialog(window,message,wp,lp,L" Locking processes ",false,{432},false,GetDlgItem(window,431));
|
||||
if(message==WM_CLOSE) {FilesModalDialog::finish(dialog,IDCANCEL);return TRUE;}
|
||||
const auto title=state.files.empty()?L" Processes ":L" Locking processes ";
|
||||
return paintCopyDialog(dialog,message,wp,lp,title,false,{processDivider},false,GetDlgItem(dialog,processList));
|
||||
}
|
||||
|
||||
void showLockProcesses(HWND owner,std::vector<fs::path> paths)
|
||||
void showProcesses(HWND owner,std::vector<fs::path> paths)
|
||||
{
|
||||
LockDialog state{std::move(paths)};
|
||||
FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(609),owner,lockProcessesDialog,
|
||||
const auto source=active;
|
||||
ProcessDialog state{std::move(paths)};
|
||||
const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(609),owner,processesDialog,
|
||||
reinterpret_cast<LPARAM>(&state));
|
||||
state.stop.request_stop();
|
||||
if(result!=processReveal) return;
|
||||
const auto destination=state.files.empty()?source:1-source;
|
||||
if(quickViewWindow && destination!=quickViewSource) toggleQuickView(owner);
|
||||
revealLocalFile(panels[destination],state.reveal);
|
||||
}
|
||||
|
||||
bool panelLockSearchAvailable(const Panel &panel)
|
||||
{
|
||||
return !terminalVisible && panelItemPropertiesAvailable(panel) && !panel.ftp && !panel.peer &&
|
||||
!panel.archive && !windowsNetworkPath(panel.directory);
|
||||
}
|
||||
|
||||
void showPanelLockProcesses(HWND owner,Panel &panel)
|
||||
{
|
||||
if(panelLockSearchAvailable(panel)) showProcesses(owner,selectedPanelPaths(panel));
|
||||
}
|
||||
+92
-7
@@ -9,6 +9,8 @@
|
||||
#include <commdlg.h>
|
||||
#include <aclapi.h>
|
||||
#include <sddl.h>
|
||||
#include <tlhelp32.h>
|
||||
#include <psapi.h>
|
||||
#include <cmath>
|
||||
#include <numbers>
|
||||
#include <algorithm>
|
||||
@@ -36,9 +38,11 @@
|
||||
#include <libssh2_sftp.h>
|
||||
#include "files_terminal.h"
|
||||
#include "files_archive.h"
|
||||
#include "files_git_changes.h"
|
||||
#include "files_compare_text.h"
|
||||
#include "files_image_decode.h"
|
||||
#include "files_win32_directory.h"
|
||||
#include "files_win32_replace.h"
|
||||
#include "files_command_completion.h"
|
||||
#include "files_text_window.h"
|
||||
#include "files_menu_navigation.h"
|
||||
@@ -67,11 +71,18 @@ using ks::lan::filePath;
|
||||
using ks::lan::checkFileReply;
|
||||
using ks::files::validFileName;
|
||||
|
||||
struct TransferItemMetadata
|
||||
{
|
||||
uint64_t created{}, accessed{};
|
||||
std::optional<uint32_t> owner, permissions;
|
||||
};
|
||||
|
||||
struct FileInfo
|
||||
{
|
||||
DWORD attributes;
|
||||
uint64_t size, modified;
|
||||
std::optional<uint64_t> allocated{};
|
||||
std::optional<TransferItemMetadata> transfer{};
|
||||
};
|
||||
FileInfo fileInfo(const Json &row)
|
||||
{
|
||||
@@ -383,6 +394,20 @@ fs::path folderPathWithoutSeparator(fs::path path)
|
||||
return path;
|
||||
}
|
||||
|
||||
bool windowsNetworkPath(const fs::path &path)
|
||||
{
|
||||
std::wstring_view name=path.native();
|
||||
if(name.starts_with(L"\\\\?\\"))
|
||||
{
|
||||
name.remove_prefix(4);
|
||||
if(name.size()>=4 && CompareStringOrdinal(name.data(),4,L"UNC\\",4,TRUE)==CSTR_EQUAL) return true;
|
||||
return name.size()>=3 && name[1]==L':' && name[2]==L'\\' &&
|
||||
GetDriveTypeW(std::wstring(name.substr(0,3)).c_str())==DRIVE_REMOTE;
|
||||
}
|
||||
return name.starts_with(L"\\\\") || name.starts_with(L"//") ||
|
||||
GetDriveTypeW(path.root_path().c_str())==DRIVE_REMOTE;
|
||||
}
|
||||
|
||||
fs::path panelParentPath(const fs::path &directory,bool local)
|
||||
{
|
||||
if(!directory.has_relative_path()) return {};
|
||||
@@ -504,6 +529,7 @@ struct ColumnMetadata
|
||||
std::wstring owner;
|
||||
std::optional<uint64_t> allocated;
|
||||
std::optional<DWORD> links;
|
||||
std::optional<TransferItemMetadata> transfer;
|
||||
};
|
||||
|
||||
using ColumnMetadataMap=std::map<fs::path,ColumnMetadata>;
|
||||
@@ -1592,19 +1618,23 @@ void setPanelDivider(HWND window,int width,int position)
|
||||
layout(window);
|
||||
}
|
||||
|
||||
void layoutGitChanges(HWND window);
|
||||
bool showingGitChanges();
|
||||
|
||||
void layout(HWND window,bool activeOnly)
|
||||
{
|
||||
RECT rect{};
|
||||
GetClientRect(window, &rect);
|
||||
int width = rect.right, height = rect.bottom;
|
||||
const int inputTop=height-2*textHeight;
|
||||
const bool gitMode=showingGitChanges();
|
||||
const int terminalBottom=std::max(4,inputTop);
|
||||
const int summaryHeight=!terminalVisible && hasSelectionSummary()?textHeight:0;
|
||||
const int detailsHeight=terminalVisible?0:textHeight+12+summaryHeight;
|
||||
const int terminalTop=terminalVisible?4:std::max(4,terminalBottom-
|
||||
std::min(terminalRows,std::max(0,(terminalBottom-detailsHeight)/textHeight-4))*textHeight);
|
||||
const int panelBottom=terminalTop-detailsHeight;
|
||||
const bool showOutput=terminalTop<terminalBottom;
|
||||
const bool showOutput=!gitMode && terminalTop<terminalBottom;
|
||||
traceTerminal("layout",terminalRows,terminalTop,terminalBottom,showOutput,terminalVisible);
|
||||
const int middle=panelDivider(width);
|
||||
auto place=[](HWND control, int x, int y, int width, int height)
|
||||
@@ -1621,7 +1651,7 @@ void layout(HWND window,bool activeOnly)
|
||||
place(panels[i].path, x + 5, 4, std::max(0, end - x - 10), textHeight);
|
||||
int headingHeight=detailedPanel(panels[i])?textHeight:0;
|
||||
const int listWidth=std::max(0,end-x-8-scrollBarWidth(panels[i].list));
|
||||
const bool panelVisible=!terminalVisible && (!quickViewWindow || i==quickViewSource);
|
||||
const bool panelVisible=!gitMode && !terminalVisible && (!quickViewWindow || i==quickViewSource);
|
||||
ShowWindow(panels[i].path,panelVisible?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(panels[i].list,panelVisible?SW_SHOWNA:SW_HIDE);
|
||||
place(panels[i].heading,x+5,textHeight+10,listWidth,headingHeight);
|
||||
@@ -1670,7 +1700,9 @@ void layout(HWND window,bool activeOnly)
|
||||
}
|
||||
if(!showOutput) clearTerminalSelection();
|
||||
ShowWindow(terminalOutput,showOutput?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(status,terminalVisible?SW_HIDE:SW_SHOWNA);
|
||||
ShowWindow(status,terminalVisible || gitMode?SW_HIDE:SW_SHOWNA);
|
||||
ShowWindow(terminalPrompt,gitMode?SW_HIDE:SW_SHOWNA);
|
||||
ShowWindow(terminalInput,gitMode?SW_HIDE:SW_SHOWNA);
|
||||
terminalView.layout(terminalOutput,showOutput && !sshPrompt,terminalBottom-4);
|
||||
sshView.layout(terminalOutput,showOutput && sshPrompt.has_value(),terminalBottom-4);
|
||||
constexpr int refreshExtra=4;
|
||||
@@ -1681,6 +1713,7 @@ void layout(HWND window,bool activeOnly)
|
||||
const int left=i?(i*unit+refreshExtra)*width/total:0;
|
||||
const int right=((i+1)*unit+refreshExtra)*width/total;
|
||||
place(commands[i],left,height-textHeight,right-left,textHeight);
|
||||
ShowWindow(commands[i],gitMode?SW_HIDE:SW_SHOWNA);
|
||||
}
|
||||
if(quickViewWindow)
|
||||
{
|
||||
@@ -1692,10 +1725,11 @@ void layout(HWND window,bool activeOnly)
|
||||
SetWindowPos(preview,nullptr,left+5,4,std::max(0,right-left-10),
|
||||
std::max(0,panelBottom+summaryHeight+textHeight),SWP_NOZORDER|SWP_NOACTIVATE);
|
||||
const bool current=quickViewDisplaysImage==(preview==quickImageWindow);
|
||||
ShowWindow(preview,!terminalVisible && current?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(preview,!gitMode && !terminalVisible && current?SW_SHOWNA:SW_HIDE);
|
||||
}
|
||||
}
|
||||
if(IsWindowVisible(panelSearchPopup)) placePanelSearch(window);
|
||||
layoutGitChanges(window);
|
||||
RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN);
|
||||
}
|
||||
|
||||
@@ -2881,6 +2915,7 @@ std::unique_ptr<Panel::ScanResult> scanDirectory(const Panel::ScanRequest &reque
|
||||
error=ftp.list(directory.empty()?ftpInitialDirectory:directory,[&](const fs::path &path,const FileInfo &info)
|
||||
{
|
||||
if(!metadata.emplace(path,FolderEntryMetadata{info.attributes,info.size,info.modified}).second) return true;
|
||||
if(info.transfer) columnMetadata[path].transfer=info.transfer;
|
||||
(info.attributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path);
|
||||
entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed);
|
||||
return !stop.stop_requested();
|
||||
@@ -3806,6 +3841,14 @@ bool driveSourceRow(LRESULT row)
|
||||
row==sftpDriveRow() || row==smbDriveRow() || row==recentDriveRow());
|
||||
}
|
||||
|
||||
bool panelItemPropertiesAvailable(const Panel &panel);
|
||||
void showPanelItemProperties(HWND owner,Panel &panel);
|
||||
bool panelLockSearchAvailable(const Panel &panel);
|
||||
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);
|
||||
|
||||
bool selectablePickerRow(LRESULT row)
|
||||
{
|
||||
if(row<0) return false;
|
||||
@@ -3852,7 +3895,11 @@ void selectDrive()
|
||||
else if(menuIndex==2 && row==12) openSpaceAnalyzer(owner,panels[active]);
|
||||
else if(menuIndex==2 && row==13) openSelectedText(panels[active],false,false,true);
|
||||
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==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]);
|
||||
else
|
||||
{
|
||||
const int command=menuIndex==1?113+static_cast<int>(row):110+static_cast<int>(row);
|
||||
@@ -5938,7 +5985,7 @@ void showFileOperationError(HWND owner,const wchar_t *title,const std::wstring &
|
||||
setStatus(L"");
|
||||
const auto choice=showFilesNotice(owner,message.c_str(),title,
|
||||
{.tone=FilesNoticeTone::warning,.processes=!lockPaths.empty()});
|
||||
if(choice==showProcessesButton) showLockProcesses(owner,std::move(lockPaths));
|
||||
if(choice==showProcessesButton) showProcesses(owner,std::move(lockPaths));
|
||||
}
|
||||
|
||||
void showTextMessage(HWND owner,const wchar_t *text)
|
||||
@@ -7609,6 +7656,7 @@ void openOrCreateText(HWND owner,const Panel &panel)
|
||||
void editTransferProfile(Panel &panel,bool create);
|
||||
|
||||
#include "files_drag_drop.inl"
|
||||
#include "files_properties.inl"
|
||||
#include "files_context_menu.inl"
|
||||
|
||||
LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
|
||||
@@ -7901,14 +7949,16 @@ void openMenu(HWND window, int index)
|
||||
if(detailedPanel(panel)) rows.push_back(L" Columns…");
|
||||
}
|
||||
}
|
||||
else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10",L"Pack files…\tAlt+F5"};
|
||||
else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10",L"Pack files…\tAlt+F5",
|
||||
L"Properties…\tCtrl+A",L"Locking processes…"};
|
||||
else if(index==2)
|
||||
{
|
||||
rows={L"Refresh panel\tCtrl+R",L"View\tF3",L"Edit\tF4",L"Folder shortcuts",
|
||||
L"View externally\tAlt+F3",L"Edit externally\tAlt+F4",
|
||||
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"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3",L"Viewer bookmarks…",L"Processes…",
|
||||
L"Git Changes…"};
|
||||
}
|
||||
const auto &panel=panels[active];
|
||||
const bool remoteResults=remoteSearchResults(panel);
|
||||
@@ -7923,10 +7973,19 @@ void openMenu(HWND window, int index)
|
||||
commandActions.push_back(1);
|
||||
}
|
||||
commandActions.push_back(3);
|
||||
if(panelItemPropertiesAvailable(panel)) commandActions.push_back(5);
|
||||
}
|
||||
else if(index==1)
|
||||
{
|
||||
commandActions={0,1,2,3,4};
|
||||
if(panelItemPropertiesAvailable(panel)) commandActions.push_back(5);
|
||||
if(panelLockSearchAvailable(panel)) commandActions.push_back(6);
|
||||
}
|
||||
else if(index==2)
|
||||
{
|
||||
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 && canFindFiles(panels[active])) commandActions.insert(commandActions.begin()+1,9);
|
||||
if(!terminalVisible && !panels[active].peer && !panels[active].ftp)
|
||||
commandActions.insert(commandActions.begin()+2,12);
|
||||
@@ -8129,8 +8188,16 @@ bool commandLineAvailable(HWND owner)
|
||||
!IsWindowVisible(menuBar) && !IsWindowVisible(picker);
|
||||
}
|
||||
|
||||
#include "files_git_panel.inl"
|
||||
|
||||
void restoreCommandFocus()
|
||||
{
|
||||
if(gitChangesView)
|
||||
{
|
||||
const auto focus=GetFocus();
|
||||
if(focus==GetParent(terminalInput)) SetFocus(gitChangesView->list);
|
||||
return;
|
||||
}
|
||||
if(GetFocus()!=terminalInput && !GetCapture() && commandLineAvailable(GetParent(terminalInput)))
|
||||
SetFocus(terminalInput);
|
||||
}
|
||||
@@ -8151,6 +8218,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
if(message==filesPreferencesChanged)
|
||||
{
|
||||
if(quickViewWindow) SendNotifyMessageW(quickViewWindow,message,wp,lp);
|
||||
if(gitChangesView) SendNotifyMessageW(gitChangesView->preview,message,wp,lp);
|
||||
if(reinterpret_cast<HWND>(wp)!=window)
|
||||
{
|
||||
loadFilesPreferences(window);
|
||||
@@ -8899,6 +8967,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)
|
||||
@@ -8928,6 +8997,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp)
|
||||
return 0;
|
||||
case WM_DESTROY:
|
||||
pendingPanelDrop.reset();
|
||||
closeGitChanges(window,false);
|
||||
for(auto &panel:panels)
|
||||
if(panel.folderSizeJob) panel.folderSizeJob->stop.request_stop();
|
||||
KillTimer(window,terminalTimer);
|
||||
@@ -9037,6 +9107,15 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
if(message.hwnd==window && message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST &&
|
||||
GetFocus()==terminalInput)
|
||||
message.hwnd=terminalInput;
|
||||
if(gitChangesView)
|
||||
{
|
||||
if(!handleGitChangesKey(window,message))
|
||||
{
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(handleQuickViewKey(window,message) || handlePanelPathKey(window,message)) continue;
|
||||
if((message.message==WM_KEYDOWN || message.message==WM_SYSKEYDOWN) &&
|
||||
!terminalVisible && commandLineAvailable(window) &&
|
||||
@@ -9230,6 +9309,12 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show)
|
||||
if(!(message.lParam & (1LL<<30))) copyFullPanelPath(window,panels[active]);
|
||||
continue;
|
||||
}
|
||||
if(ctrl && !shift && message.wParam=='A' && !terminalVisible && commandLineAvailable(window) &&
|
||||
(!GetWindowTextLengthW(terminalInput) || panelFocused) && panelItemPropertiesAvailable(panels[active]))
|
||||
{
|
||||
if(!(message.lParam&(1LL<<30))) showPanelItemProperties(window,panels[active]);
|
||||
continue;
|
||||
}
|
||||
if(shift && !ctrl && message.wParam==VK_F4 && !terminalVisible)
|
||||
{
|
||||
if(!(message.lParam & (1LL<<30)) && commandLineAvailable(window))
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
constexpr int propertiesName=580, propertiesFirstDetail=581, propertiesOtherFlags=586;
|
||||
constexpr int propertiesFirstFlag=587, propertiesDivider=592;
|
||||
constexpr DWORD propertyOpenFlags=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT;
|
||||
constexpr DWORD editablePropertyFlags[]{
|
||||
FILE_ATTRIBUTE_READONLY,FILE_ATTRIBUTE_HIDDEN,FILE_ATTRIBUTE_SYSTEM,FILE_ATTRIBUTE_ARCHIVE,
|
||||
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED};
|
||||
|
||||
struct FilePropertyFlag
|
||||
{
|
||||
DWORD flag;
|
||||
const wchar_t *name;
|
||||
};
|
||||
|
||||
std::wstring propertyFlagNames(DWORD flags)
|
||||
{
|
||||
constexpr FilePropertyFlag names[]{
|
||||
{FILE_ATTRIBUTE_READONLY,L"Read-only"},{FILE_ATTRIBUTE_HIDDEN,L"Hidden"},
|
||||
{FILE_ATTRIBUTE_SYSTEM,L"System"},{FILE_ATTRIBUTE_DIRECTORY,L"Directory"},
|
||||
{FILE_ATTRIBUTE_ARCHIVE,L"Archive"},{FILE_ATTRIBUTE_NORMAL,L"Normal"},
|
||||
{FILE_ATTRIBUTE_TEMPORARY,L"Temporary"},{FILE_ATTRIBUTE_SPARSE_FILE,L"Sparse"},
|
||||
{FILE_ATTRIBUTE_REPARSE_POINT,L"Reparse point"},{FILE_ATTRIBUTE_COMPRESSED,L"Compressed"},
|
||||
{FILE_ATTRIBUTE_OFFLINE,L"Offline"},{FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,L"Not indexed"},
|
||||
{FILE_ATTRIBUTE_ENCRYPTED,L"Encrypted"},{FILE_ATTRIBUTE_INTEGRITY_STREAM,L"Integrity stream"},
|
||||
{FILE_ATTRIBUTE_NO_SCRUB_DATA,L"No scrub"},{FILE_ATTRIBUTE_PINNED,L"Pinned"},
|
||||
{FILE_ATTRIBUTE_UNPINNED,L"Unpinned"}};
|
||||
std::wstring text;
|
||||
const auto append=[&](std::wstring_view name)
|
||||
{
|
||||
if(!text.empty()) text+=L", ";
|
||||
text+=name;
|
||||
};
|
||||
for(const auto &[flag,name]:names)
|
||||
if(flags&flag)
|
||||
{
|
||||
append(name);
|
||||
flags&=~flag;
|
||||
}
|
||||
if(flags)
|
||||
{
|
||||
wchar_t number[16]{};
|
||||
swprintf_s(number,L"0x%08lX",static_cast<unsigned long>(flags));
|
||||
append(number);
|
||||
}
|
||||
return text.empty()?L"—":text;
|
||||
}
|
||||
|
||||
std::wstring propertyDate(uint64_t ticks)
|
||||
{
|
||||
const auto time=localFileTime(ticks);
|
||||
if(!time) return L"—";
|
||||
wchar_t label[32]{};
|
||||
swprintf_s(label,L"%04u-%02u-%02u %02u:%02u:%02u",unsigned(time->wYear),unsigned(time->wMonth),
|
||||
unsigned(time->wDay),unsigned(time->wHour),unsigned(time->wMinute),unsigned(time->wSecond));
|
||||
return label;
|
||||
}
|
||||
|
||||
struct ItemProperties
|
||||
{
|
||||
std::wstring name, owner;
|
||||
uint64_t created{}, modified{}, accessed{}, changed{};
|
||||
DWORD flags{}, requested{};
|
||||
|
||||
std::vector<std::wstring> details(bool includeMissing) const
|
||||
{
|
||||
std::vector<std::wstring> rows;
|
||||
if(includeMissing || !owner.empty()) rows.push_back(L"Owner "+(owner.empty()?L"—":owner));
|
||||
const auto date=[&](const wchar_t *label,uint64_t value)
|
||||
{
|
||||
if(includeMissing || value) rows.push_back(label+propertyDate(value));
|
||||
};
|
||||
date(L"Created ",created);
|
||||
date(L"Modified ",modified);
|
||||
date(L"Accessed ",accessed);
|
||||
date(L"Changed ",changed);
|
||||
return rows;
|
||||
}
|
||||
};
|
||||
|
||||
INT_PTR CALLBACK itemPropertiesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp)
|
||||
{
|
||||
if(message==WM_INITDIALOG)
|
||||
{
|
||||
auto &properties=*reinterpret_cast<ItemProperties*>(lp);
|
||||
SetWindowLongPtrW(dialog,DWLP_USER,lp);
|
||||
prepareTextDialog(dialog);
|
||||
layoutDialogContent(dialog,propertiesName);
|
||||
SetDlgItemTextW(dialog,propertiesName,properties.name.c_str());
|
||||
const auto details=properties.details(true);
|
||||
for(size_t index=0;index<details.size();++index)
|
||||
SetDlgItemTextW(dialog,propertiesFirstDetail+static_cast<int>(index),details[index].c_str());
|
||||
auto other=properties.flags&~FILE_ATTRIBUTE_NORMAL;
|
||||
for(size_t index=0;index<std::size(editablePropertyFlags);++index)
|
||||
{
|
||||
const auto flag=editablePropertyFlags[index];
|
||||
const auto id=propertiesFirstFlag+static_cast<int>(index);
|
||||
installFarCheckbox(GetDlgItem(dialog,id),FarCheckboxSurface::gray);
|
||||
CheckDlgButton(dialog,id,(properties.flags&flag)?BST_CHECKED:BST_UNCHECKED);
|
||||
other&=~flag;
|
||||
}
|
||||
SetDlgItemTextW(dialog,propertiesOtherFlags,(L"Other flags "+propertyFlagNames(other)).c_str());
|
||||
layoutDialogButtons(dialog,propertiesDivider,{IDOK,IDCANCEL});
|
||||
return TRUE;
|
||||
}
|
||||
if(message==WM_COMMAND && LOWORD(wp)==IDOK)
|
||||
{
|
||||
auto &properties=*reinterpret_cast<ItemProperties*>(GetWindowLongPtrW(dialog,DWLP_USER));
|
||||
for(size_t index=0;index<std::size(editablePropertyFlags);++index)
|
||||
if(IsDlgButtonChecked(dialog,propertiesFirstFlag+static_cast<int>(index))==BST_CHECKED)
|
||||
properties.requested|=editablePropertyFlags[index];
|
||||
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" Properties ",false,{propertiesDivider});
|
||||
}
|
||||
|
||||
void showReadOnlyProperties(HWND owner,const ItemProperties &properties,const std::wstring &attributes)
|
||||
{
|
||||
auto text=properties.name+L"\r\n\r\n";
|
||||
for(const auto &line:properties.details(false)) text+=line+L"\r\n";
|
||||
text+=attributes;
|
||||
showFilesNotice(owner,text.c_str(),L"Properties",{.tone=FilesNoticeTone::neutral});
|
||||
}
|
||||
|
||||
bool panelItemPropertiesAvailable(const Panel &panel)
|
||||
{
|
||||
const auto row=currentPanelRow(panel);
|
||||
return row!=LB_ERR && panel.sizes[row]!=L"Up" && !transferProfileList(panel);
|
||||
}
|
||||
|
||||
void showSourceItemProperties(HWND owner,const Panel &panel,const fs::path &path,ItemProperties properties)
|
||||
{
|
||||
const auto found=panel.metadata.find(path);
|
||||
if(found==panel.metadata.end()) return;
|
||||
const auto &entry=found->second;
|
||||
properties.modified=entry.modified;
|
||||
if(panel.peer)
|
||||
{
|
||||
showReadOnlyProperties(owner,properties,L"Attributes "+propertyFlagNames(entry.attributes));
|
||||
return;
|
||||
}
|
||||
auto attributes=(entry.attributes&FILE_ATTRIBUTE_DIRECTORY)?std::wstring(L"Folder"):
|
||||
(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)?std::wstring(L"Special file"):std::wstring(L"File");
|
||||
if(panel.archive && panel.archive->entries)
|
||||
{
|
||||
const auto &members=*panel.archive->entries;
|
||||
if(const auto member=members.find(path.lexically_relative(panel.archive->file));member!=members.end())
|
||||
{
|
||||
properties.owner=member->second.owner;
|
||||
properties.created=member->second.created;
|
||||
properties.accessed=member->second.accessed;
|
||||
if(member->second.encrypted) attributes+=L", Encrypted";
|
||||
}
|
||||
}
|
||||
else if(const auto extra=panel.columnMetadata.find(path);
|
||||
extra!=panel.columnMetadata.end() && extra->second.transfer)
|
||||
{
|
||||
const auto &details=*extra->second.transfer;
|
||||
properties.created=details.created;
|
||||
properties.accessed=details.accessed;
|
||||
if(details.owner) properties.owner=L"UID "+std::to_wstring(*details.owner);
|
||||
if(details.permissions)
|
||||
{
|
||||
wchar_t mode[12]{};
|
||||
swprintf_s(mode,L"%04o",static_cast<unsigned>(*details.permissions));
|
||||
attributes+=std::wstring(L"\r\nPermissions ")+mode;
|
||||
}
|
||||
}
|
||||
if(panel.ftp && panel.ftp->protocol==TransferProtocol::ftp)
|
||||
{
|
||||
const auto flags=entry.attributes&~(FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_DIRECTORY);
|
||||
if(flags) attributes+=L"\r\nAttributes "+propertyFlagNames(flags);
|
||||
}
|
||||
showReadOnlyProperties(owner,properties,L"Type "+attributes);
|
||||
}
|
||||
|
||||
DWORD changeItemProperties(const fs::path &path,HANDLE original,const ItemProperties &properties)
|
||||
{
|
||||
DWORD editable{};
|
||||
for(const auto flag:editablePropertyFlags) editable|=flag;
|
||||
const DWORD changed=(properties.flags^properties.requested)&editable;
|
||||
if(!changed) return ERROR_SUCCESS;
|
||||
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES,columnFileShare,nullptr,
|
||||
OPEN_EXISTING,propertyOpenFlags,nullptr)};
|
||||
if(file.value==INVALID_HANDLE_VALUE) return GetLastError();
|
||||
BY_HANDLE_FILE_INFORMATION before{},current{};
|
||||
if(!GetFileInformationByHandle(original,&before) || !GetFileInformationByHandle(file.value,¤t))
|
||||
return GetLastError();
|
||||
if(!ks::files::sameFileIdentity(before,current)) return ERROR_FILE_INVALID;
|
||||
FILE_BASIC_INFO latest{};
|
||||
if(!GetFileInformationByHandleEx(file.value,FileBasicInfo,&latest,sizeof(latest))) return GetLastError();
|
||||
if(!((latest.FileAttributes^properties.requested)&changed)) return ERROR_SUCCESS;
|
||||
FILE_BASIC_INFO update{};
|
||||
update.FileAttributes=(latest.FileAttributes&~(changed|FILE_ATTRIBUTE_NORMAL))|(properties.requested&changed);
|
||||
if(!update.FileAttributes) update.FileAttributes=FILE_ATTRIBUTE_NORMAL;
|
||||
if(!SetFileInformationByHandle(file.value,FileBasicInfo,&update,sizeof(update))) return GetLastError();
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
void showPanelItemProperties(HWND owner,Panel &panel)
|
||||
{
|
||||
if(!panelItemPropertiesAvailable(panel)) return;
|
||||
const auto path=panel.rows[currentPanelRow(panel)];
|
||||
ItemProperties properties{path.filename().native()};
|
||||
if(panel.ftp || panel.peer || panel.archive)
|
||||
{
|
||||
showSourceItemProperties(owner,panel,path,std::move(properties));
|
||||
return;
|
||||
}
|
||||
const Handle file{CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,columnFileShare,nullptr,OPEN_EXISTING,
|
||||
propertyOpenFlags,nullptr)};
|
||||
FILE_BASIC_INFO info{};
|
||||
if(file.value==INVALID_HANDLE_VALUE || !GetFileInformationByHandleEx(file.value,FileBasicInfo,&info,sizeof(info)))
|
||||
{
|
||||
const auto error=GetLastError();
|
||||
refreshPanel(panel);
|
||||
showFileOperationError(owner,L"Could not read properties",fileError({static_cast<int>(error),std::system_category()}));
|
||||
return;
|
||||
}
|
||||
std::map<std::wstring,std::wstring> owners;
|
||||
properties.owner=localOwnerName(path,owners);
|
||||
properties.created=info.CreationTime.QuadPart;
|
||||
properties.modified=info.LastWriteTime.QuadPart;
|
||||
properties.accessed=info.LastAccessTime.QuadPart;
|
||||
properties.changed=info.ChangeTime.QuadPart;
|
||||
properties.flags=info.FileAttributes;
|
||||
if(windowsNetworkPath(path))
|
||||
{
|
||||
showReadOnlyProperties(owner,properties,L"Attributes "+propertyFlagNames(properties.flags));
|
||||
return;
|
||||
}
|
||||
if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(125),owner,itemPropertiesDialog,
|
||||
reinterpret_cast<LPARAM>(&properties))!=IDOK) return;
|
||||
const auto error=changeItemProperties(path,file.value,properties);
|
||||
refreshPanel(panel);
|
||||
if(error!=ERROR_SUCCESS)
|
||||
showFileOperationError(owner,L"Could not save attributes",error==ERROR_FILE_INVALID?
|
||||
L"The item was replaced while the properties were open.":
|
||||
fileError({static_cast<int>(error),std::system_category()}));
|
||||
}
|
||||
+12
-3
@@ -354,9 +354,18 @@ public:
|
||||
else if(!LIBSSH2_SFTP_S_ISREG(attrs.permissions)) attributes=FILE_ATTRIBUTE_REPARSE_POINT;
|
||||
if(!(attrs.permissions&0222)) attributes|=FILE_ATTRIBUTE_READONLY;
|
||||
}
|
||||
const auto modified=(attrs.flags&LIBSSH2_SFTP_ATTR_ACMODTIME)?
|
||||
(uint64_t(attrs.mtime)+11644473600ULL)*10000000ULL:0;
|
||||
if(!visit(directory/child,{attributes,attrs.filesize,modified})) return ERROR_CANCELLED;
|
||||
const auto sftpTime=[](unsigned long seconds){return (uint64_t(seconds)+11644473600ULL)*10000000ULL;};
|
||||
FileInfo info{attributes,attrs.filesize,0};
|
||||
TransferItemMetadata details;
|
||||
if(attrs.flags&LIBSSH2_SFTP_ATTR_ACMODTIME)
|
||||
{
|
||||
info.modified=sftpTime(attrs.mtime);
|
||||
details.accessed=sftpTime(attrs.atime);
|
||||
}
|
||||
if(attrs.flags&LIBSSH2_SFTP_ATTR_UIDGID) details.owner=attrs.uid;
|
||||
if(attrs.flags&LIBSSH2_SFTP_ATTR_PERMISSIONS) details.permissions=attrs.permissions&07777;
|
||||
if(details.accessed || details.owner || details.permissions) info.transfer=details;
|
||||
if(!visit(directory/child,info)) return ERROR_CANCELLED;
|
||||
}
|
||||
return ERROR_CANCELLED;
|
||||
}
|
||||
|
||||
@@ -87,8 +87,7 @@ bool sameFile(HANDLE a, HANDLE b)
|
||||
BY_HANDLE_FILE_INFORMATION first{}, second{};
|
||||
if (!GetFileInformationByHandle(a, &first) || !GetFileInformationByHandle(b, &second))
|
||||
fail("Check file identity");
|
||||
return first.dwVolumeSerialNumber == second.dwVolumeSerialNumber &&
|
||||
first.nFileIndexHigh == second.nFileIndexHigh && first.nFileIndexLow == second.nFileIndexLow;
|
||||
return sameFileIdentity(first,second);
|
||||
}
|
||||
|
||||
std::filesystem::path temporaryPath(const std::filesystem::path &directory)
|
||||
|
||||
@@ -804,6 +804,7 @@ public:
|
||||
bool handleKey(const MSG &message);
|
||||
void goToFragment(std::string_view fragment);
|
||||
void previewFile(const std::filesystem::path &path);
|
||||
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;
|
||||
@@ -935,6 +936,8 @@ private:
|
||||
};
|
||||
std::future<QuickDocument> quickLoading;
|
||||
std::filesystem::path quickPath;
|
||||
std::wstring quickTextTitle;
|
||||
bool quickTextVisible{},quickTextDiff{};
|
||||
uint64_t quickRequest{}, quickReading{};
|
||||
ULONGLONG quickReadyAt{};
|
||||
std::wstring quickError;
|
||||
@@ -985,6 +988,7 @@ private:
|
||||
void updateLineNumberMargin();
|
||||
void applyLineEnding();
|
||||
void installLexer();
|
||||
void replaceEditorText(std::string_view data);
|
||||
void loadPage(uint64_t index,std::optional<std::string> cached={});
|
||||
void toggleHex();
|
||||
void locateBookmark(uint64_t line);
|
||||
@@ -1411,6 +1415,12 @@ void TextWindow::loadPage(uint64_t index,std::optional<std::string> cached)
|
||||
const auto eol = data.find_first_of("\r\n");
|
||||
pageEol = eol == data.npos ? SC_EOL_CRLF : data[eol] == '\n' ? SC_EOL_LF :
|
||||
eol + 1 < data.size() && data[eol + 1] == '\n' ? SC_EOL_CRLF : SC_EOL_CR;
|
||||
replaceEditorText(data);
|
||||
cleanPage = std::move(data);
|
||||
}
|
||||
|
||||
void TextWindow::replaceEditorText(std::string_view data)
|
||||
{
|
||||
loading = true;
|
||||
send(SCI_SETREADONLY, FALSE);
|
||||
send(SCI_SETUNDOCOLLECTION, FALSE);
|
||||
@@ -1424,7 +1434,6 @@ void TextWindow::loadPage(uint64_t index,std::optional<std::string> cached)
|
||||
send(SCI_GOTOPOS, 0);
|
||||
send(SCI_SETXOFFSET, 0);
|
||||
send(SCI_SETFIRSTVISIBLELINE, 0);
|
||||
cleanPage = std::move(data);
|
||||
loading = false;
|
||||
updateLineNumberMargin();
|
||||
undoBytes = 0;
|
||||
@@ -1616,7 +1625,9 @@ std::string readMarkdownDocument(TextDocument &document)
|
||||
|
||||
void TextWindow::previewFile(const std::filesystem::path &path)
|
||||
{
|
||||
if(path==quickPath) return;
|
||||
if(quickTextTitle.empty() && path==quickPath) return;
|
||||
quickTextVisible=false;
|
||||
quickTextTitle.clear();
|
||||
quickPath=path;
|
||||
++quickRequest;
|
||||
quickReadyAt=GetTickCount64()+80;
|
||||
@@ -1628,6 +1639,34 @@ void TextWindow::previewFile(const std::filesystem::path &path)
|
||||
SetTimer(window,quickViewTimer,30,nullptr);
|
||||
}
|
||||
|
||||
void TextWindow::previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff)
|
||||
{
|
||||
if(!embedded) return;
|
||||
if(quickTextTitle.empty())
|
||||
{
|
||||
++quickRequest;
|
||||
KillTimer(window,quickViewTimer);
|
||||
quickLoading={};
|
||||
quickPath.clear();
|
||||
quickError.clear();
|
||||
stopPreview(false,true);
|
||||
document.reset();
|
||||
quickMarkdown.reset();
|
||||
}
|
||||
if(quickTextTitle.empty() || quickTextDiff!=diff)
|
||||
{
|
||||
language=automatic=diff?detectLanguage(L"preview.diff",contents):TextLanguage{};
|
||||
installLexer();
|
||||
}
|
||||
quickTextTitle=title;
|
||||
quickTextVisible=!contents.empty();
|
||||
quickTextDiff=diff;
|
||||
pageEol=SC_EOL_LF;
|
||||
replaceEditorText(contents);
|
||||
send(SCI_COLOURISE,0,-1);
|
||||
layout();
|
||||
}
|
||||
|
||||
void TextWindow::pollQuickView()
|
||||
{
|
||||
if(quickLoading.valid())
|
||||
@@ -2520,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 && !previewWanted?SW_SHOWNA:SW_HIDE);
|
||||
ShowWindow(editor,(document || quickTextVisible) && !previewWanted?SW_SHOWNA:SW_HIDE);
|
||||
invalidate();
|
||||
}
|
||||
|
||||
@@ -2597,6 +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(!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);
|
||||
@@ -3259,6 +3299,12 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path)
|
||||
preview->second->previewFile(path);
|
||||
}
|
||||
|
||||
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->previewEmbeddedText(title,contents,diff);
|
||||
}
|
||||
|
||||
ImageViewStyle imageViewStyle(TextDialogs dialogs)
|
||||
{
|
||||
const auto font=dialogs.readFont();
|
||||
|
||||
@@ -106,6 +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 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,
|
||||
|
||||
@@ -7,6 +7,12 @@
|
||||
|
||||
namespace ks::files
|
||||
{
|
||||
inline bool sameFileIdentity(const BY_HANDLE_FILE_INFORMATION &left,const BY_HANDLE_FILE_INFORMATION &right)
|
||||
{
|
||||
return left.dwVolumeSerialNumber==right.dwVolumeSerialNumber && left.nFileIndexHigh==right.nFileIndexHigh &&
|
||||
left.nFileIndexLow==right.nFileIndexLow;
|
||||
}
|
||||
|
||||
inline DWORD replaceFileWithBackup(const std::filesystem::path &original,const std::filesystem::path &replacement,
|
||||
const std::filesystem::path &backup)
|
||||
{
|
||||
|
||||
+8
-22
@@ -1,5 +1,6 @@
|
||||
#include "update.h"
|
||||
#include "json.hpp"
|
||||
#include "windows_command_line.h"
|
||||
|
||||
namespace ks
|
||||
{
|
||||
@@ -10,21 +11,6 @@ struct Handle
|
||||
HANDLE value{};
|
||||
~Handle() { if (value) CloseHandle(value); }
|
||||
};
|
||||
std::wstring quoteArgument(const std::wstring &value)
|
||||
{
|
||||
// Windows argv escaping, including a path ending with a backslash.
|
||||
std::wstring out = L"\"";
|
||||
size_t slashes = 0;
|
||||
for (auto ch : value)
|
||||
{
|
||||
if (ch == L'\\') { ++slashes; continue; }
|
||||
out.append(ch == L'"' ? slashes * 2 + 1 : slashes, L'\\');
|
||||
slashes = 0;
|
||||
out += ch;
|
||||
}
|
||||
out.append(slashes * 2, L'\\');
|
||||
return out + L'"';
|
||||
}
|
||||
}
|
||||
UpdateResult runUpdate(bool install, const std::wstring &expectedVersion, bool showProgress)
|
||||
{
|
||||
@@ -50,16 +36,16 @@ UpdateResult runUpdate(bool install, const std::wstring &expectedVersion, bool s
|
||||
wchar_t system[MAX_PATH]{};
|
||||
if (!GetSystemDirectoryW(system, MAX_PATH)) throw std::runtime_error("Cannot locate Windows PowerShell");
|
||||
auto powershell = std::filesystem::path(system) / L"WindowsPowerShell/v1.0/powershell.exe";
|
||||
std::wstring command = quoteArgument(powershell.wstring()) + L" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File " +
|
||||
quoteArgument((work / L"update.ps1").wstring()) + L" -Mode " + (install ? L"Install" : L"Check") +
|
||||
L" -CurrentVersion " + quoteArgument(AppVersion) + L" -WorkDirectory " + quoteArgument(work.wstring()) +
|
||||
L" -InstallDirectory " + quoteArgument(std::filesystem::path(executable()).parent_path().wstring()) +
|
||||
L" -ParentProcessId " + std::to_wstring(GetCurrentProcessId()) + L" -ReadyEvent " + quoteArgument(readyName);
|
||||
std::wstring command = quoteWindowsArgument(powershell.wstring()) + L" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File " +
|
||||
quoteWindowsArgument((work / L"update.ps1").wstring()) + L" -Mode " + (install ? L"Install" : L"Check") +
|
||||
L" -CurrentVersion " + quoteWindowsArgument(AppVersion) + L" -WorkDirectory " + quoteWindowsArgument(work.wstring()) +
|
||||
L" -InstallDirectory " + quoteWindowsArgument(std::filesystem::path(executable()).parent_path().wstring()) +
|
||||
L" -ParentProcessId " + std::to_wstring(GetCurrentProcessId()) + L" -ReadyEvent " + quoteWindowsArgument(readyName);
|
||||
if (install)
|
||||
{
|
||||
command += L" -Journal " + quoteArgument((dataDirectory() / L"kswitcher.log").wstring());
|
||||
command += L" -Journal " + quoteWindowsArgument((dataDirectory() / L"kswitcher.log").wstring());
|
||||
if (expectedVersion.empty()) command += L" -Unattended";
|
||||
else command += L" -ExpectedVersion " + quoteArgument(expectedVersion);
|
||||
else command += L" -ExpectedVersion " + quoteWindowsArgument(expectedVersion);
|
||||
}
|
||||
if (showProgress) command += L" -ShowProgress";
|
||||
STARTUPINFOW startup{sizeof(startup)};
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace ks
|
||||
{
|
||||
inline std::wstring quoteWindowsArgument(std::wstring_view value)
|
||||
{
|
||||
std::wstring quoted=L"\"";
|
||||
size_t slashes=0;
|
||||
for(const auto character:value)
|
||||
{
|
||||
if(character==L'\\') {++slashes;continue;}
|
||||
quoted.append(character==L'"'?slashes*2+1:slashes,L'\\');
|
||||
slashes=0;
|
||||
quoted+=character;
|
||||
}
|
||||
quoted.append(slashes*2,L'\\');
|
||||
return quoted+L'"';
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user