Compare commits

...
10 changed files with 869 additions and 31 deletions

No files matched your search

+1 -1
View File
@@ -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"
+7
View File
@@ -759,6 +759,13 @@ Warning і початковий фокус на No.
зі збереженням вихідного файла в першій. Після завершення процесу список
перечитується. Якщо 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 без змін.
- Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення.
- Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення.
- Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію.
+307
View File
@@ -0,0 +1,307 @@
#include "files_git_changes.h"
#include "core.h"
#include "windows_command_line.h"
#include <algorithm>
#include <cstddef>
#include <memory>
#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 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_CEILING_DIRECTORIES",L"GIT_GLOB_PATHSPECS",L"GIT_NOGLOB_PATHSPECS",L"GIT_ICASE_PATHSPECS"};
std::vector<wchar_t> result;
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;
}))
result.insert(result.end(),entry,entry+setting.size()+1);
entry+=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{};
};
GitOutput runGit(const fs::path &git,const fs::path &directory,const std::vector<std::wstring> &arguments,
size_t maximum,std::stop_token stop)
{
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();
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
const GitHandle input{CreateFileW(L"NUL",GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,&inheritable,OPEN_EXISTING,0,nullptr)};
if(input.value==INVALID_HANDLE_VALUE) gitWindowsError("Could not open Git input");
GitHandle 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");
childOut.close();
childError.close();
GitOutput result;
const auto deadline=GetTickCount64()+15000;
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);
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(...)
{
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 statusField(std::string_view &input)
{
const auto separator=input.find('\0');
if(separator==input.npos) throw std::runtime_error("Git returned incomplete status 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=statusField(output);
if(row.size()<4 || row[2]!=' ') throw std::runtime_error("Git returned an invalid status record.");
const auto code=row.substr(0,2);
const auto path=statusPath(row.substr(3));
std::wstring origin;
if(code.find_first_of("RC")!=code.npos) origin=statusPath(statusField(output));
if(code=="??") 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;
}
}
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.");
while(!root.output.empty() && (root.output.back()=='\r' || root.output.back()=='\n')) root.output.pop_back();
result.root=fs::path(wide(root.output)).make_preferred();
if(!result.root.is_absolute()) throw std::runtime_error("Git returned an invalid worktree root.");
const auto status=runGit(result.executable,result.root,
{L"status",L"--porcelain=v1",L"-z",L"--untracked-files=all",L"--renames"},8*1024*1024,stop);
checkGit(status,"Could not read Git worktree status.");
result.entries=parseGitStatus(status.output);
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);
}
}
+29
View File
@@ -0,0 +1,29 @@
#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 GitChanges
{
std::filesystem::path executable, root;
std::vector<GitChange> entries;
};
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);
}
+412
View File
@@ -0,0 +1,412 @@
using ks::files::GitChange;
using ks::files::GitChangeKind;
using ks::files::GitChanges;
struct GitChangesView
{
HWND host{},heading{},filterLabel{},filter{},list{},status{},hints{},preview{};
fs::path folder;
GitChanges data;
std::future<GitChanges> refresh;
std::future<std::string> diff;
std::stop_source stopRefresh,stopDiff;
ULONGLONG diffAt{};
std::optional<GitChange> requested;
std::string failure;
};
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;
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;
}
std::wstring gitDiffHeading(const GitChange &entry)
{
return std::wstring(gitChangeKindName(entry.kind))+L" diff · "+entry.path;
}
void queueGitDiff(GitChangesView &view)
{
view.stopDiff.request_stop();
view.diff={};
view.diffAt=0;
view.requested.reset();
if(view.refresh.valid())
{
ks::files::previewQuickViewDiff(view.preview,L"Diff · Reading Git changes…",{});
return;
}
if(!view.failure.empty())
{
ks::files::previewQuickViewDiff(view.preview,L"Git status failed",view.failure);
return;
}
if(const auto *entry=selectedGitChange(view))
{
view.requested=*entry;
view.diffAt=GetTickCount64()+100;
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*entry)+L" · Loading…",{});
}
else ks::files::previewQuickViewDiff(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+(entry.oldPath.empty()?entry.path:entry.path+L" ← "+entry.oldPath);
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);
const auto total=view.data.entries.size();
const auto status=view.refresh.valid()?std::wstring(L"Reading Git changes…"):
!view.failure.empty()?L"Could not read Git changes.":
!total?L"No Git changes.":!count?L"No paths match the filter.":
std::to_wstring(count)+(query.empty()?L"":L" of "+std::to_wstring(total))+L" changes";
SetWindowTextW(view.status,status.c_str());
queueGitDiff(view);
}
void refreshGitChanges(GitChangesView &view)
{
if(view.refresh.valid()) 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);
SetWindowTextW(view.status,L"Reading Git changes…");
queueGitDiff(view);
}
catch(const std::exception &)
{
view.failure="Could not start Git.";
renderGitChanges(view);
}
}
void pollGitChanges(GitChangesView &view)
{
using namespace std::chrono_literals;
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.diffAt && GetTickCount64()>=view.diffAt)
{
view.diffAt=0;
view.stopDiff=std::stop_source{};
try
{
std::packaged_task<std::string()> task([git=view.data.executable,root=view.data.root,
entry=*view.requested,stop=view.stopDiff.get_token()] {
return ks::files::readGitPatch(git,root,entry,stop);
});
auto pending=task.get_future();
std::thread(std::move(task)).detach();
view.diff=std::move(pending);
}
catch(const std::exception &)
{
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),"Could not start Git diff.");
}
}
if(view.diff.valid() && view.diff.wait_for(0ms)==std::future_status::ready)
{
try
{
const auto patch=view.diff.get();
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),
patch.empty()?std::string_view("No differences. Refresh if the worktree has changed."):std::string_view(patch));
}
catch(const std::exception &error)
{
ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),error.what());
}
}
}
void openGitWorkingFile(GitChangesView &view,bool edit)
{
const auto *entry=selectedGitChange(view);
if(!entry || view.refresh.valid() || !view.failure.empty()) 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;
const int filterTop=top+textHeight+6, listTop=filterTop+textHeight+6;
const int bottom=std::max(listTop,static_cast<int>(bounds.bottom)-textHeight-5);
const int leftWidth=std::max(0,middle-2*inset);
place(view.heading,inset,top,leftWidth,textHeight);
place(view.filterLabel,inset,filterTop,filterLabel,textHeight);
place(view.filter,inset+filterLabel,filterTop,leftWidth-filterLabel,textHeight);
place(view.list,inset,listTop,leftWidth-scrollBarWidth(view.list),bottom-listTop);
place(view.status,inset,bottom+3,leftWidth,textHeight);
place(view.preview,middle+inset,top,bounds.right-middle-2*inset,bottom-top);
place(view.hints,middle+inset,bottom+3,bounds.right-middle-2*inset,textHeight);
for(const auto control:{view.heading,view.filterLabel,view.filter,view.list,view.status,view.hints})
SendMessageW(control,WM_SETFONT,reinterpret_cast<WPARAM>(mono),FALSE);
SendMessageW(view.list,LB_SETITEMHEIGHT,0,textHeight);
}
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->filterLabel=make(L"STATIC",L"Filter",SS_NOPREFIX);
view->filter=make(farEditClass,L"",ES_MULTILINE|ES_AUTOHSCROLL|WS_TABSTOP,gitFilter);
view->list=make(L"LISTBOX",L"",LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT|LBS_NOTIFY|WS_TABSTOP,gitList);
view->status=make(L"STATIC",L"",SS_ENDELLIPSIS|SS_NOPREFIX,gitStatus);
view->hints=make(L"STATIC",L"F3 View F4 Edit Ctrl+R Refresh Esc Back",SS_ENDELLIPSIS|SS_NOPREFIX);
try {view->preview=ks::files::createQuickView(window,textWindowDialogs());}
catch(const std::exception &) {}
if(!view->heading || !view->filterLabel || !view->filter || !view->list || !view->status ||
!view->hints || !view->preview || !SetTimer(window,gitChangesTimer,35,nullptr)) return -1;
prepareDialogEdit(view->filter);
SendMessageW(view->filter,EM_SETLIMITTEXT,1024,0);
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->preview && LOWORD(wp)==gitFilter && HIWORD(wp)==EN_CHANGE)
{
const auto *entry=selectedGitChange(*view);
renderGitChanges(*view,entry?std::optional(*entry):std::nullopt);
}
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_SELCHANGE) queueGitDiff(*view);
else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_DBLCLK) openGitWorkingFile(*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.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;
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)
{
auto view=std::move(gitChangesView);
if(!view) return;
view->stopRefresh.request_stop();
view->stopDiff.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;
if(!control && key==VK_ESCAPE) closeGitChanges(owner);
else if(control && key=='R') refreshGitChanges(view);
else if(control && key=='F') SetFocus(view.filter);
else if(!control && key==VK_TAB) SetFocus(GetFocus()==view.filter?view.list:view.filter);
else if(!control && (key==VK_F3 || key==VK_F4 || (key==VK_RETURN && GetFocus()==view.list)))
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;
}
+38 -5
View File
@@ -38,6 +38,7 @@
#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"
@@ -1617,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)
@@ -1646,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);
@@ -1695,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;
@@ -1706,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)
{
@@ -1717,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);
}
@@ -3837,6 +3846,8 @@ 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)
{
@@ -3885,6 +3896,7 @@ void selectDrive()
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]);
@@ -7945,7 +7957,8 @@ void openMenu(HWND window, int index)
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"Processes…"};
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);
@@ -7972,6 +7985,7 @@ void openMenu(HWND window, int index)
{
commandActions={0,3,11,-1,1,13,14,2,4,5,8};
if(!terminalVisible) commandActions.push_back(15);
if(gitChangesAvailable(panel)) commandActions.push_back(16);
if(!terminalVisible && canFindFiles(panels[active])) commandActions.insert(commandActions.begin()+1,9);
if(!terminalVisible && !panels[active].peer && !panels[active].ftp)
commandActions.insert(commandActions.begin()+2,12);
@@ -8174,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);
}
@@ -8196,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);
@@ -8973,6 +8996,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);
@@ -9082,6 +9106,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) &&
+45 -3
View File
@@ -804,6 +804,7 @@ public:
bool handleKey(const MSG &message);
void goToFragment(std::string_view fragment);
void previewFile(const std::filesystem::path &path);
void previewDiff(const std::wstring &title,std::string_view patch);
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 quickDiffTitle;
bool quickDiffVisible{};
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(quickDiffTitle.empty() && path==quickPath) return;
quickDiffVisible=false;
quickDiffTitle.clear();
quickPath=path;
++quickRequest;
quickReadyAt=GetTickCount64()+80;
@@ -1628,6 +1639,30 @@ void TextWindow::previewFile(const std::filesystem::path &path)
SetTimer(window,quickViewTimer,30,nullptr);
}
void TextWindow::previewDiff(const std::wstring &title,std::string_view patch)
{
if(!embedded) return;
if(quickDiffTitle.empty())
{
++quickRequest;
KillTimer(window,quickViewTimer);
quickLoading={};
quickPath.clear();
quickError.clear();
stopPreview(false,true);
document.reset();
quickMarkdown.reset();
language=automatic=detectLanguage(L"preview.diff",patch);
installLexer();
}
quickDiffTitle=title;
quickDiffVisible=!patch.empty();
pageEol=SC_EOL_LF;
replaceEditorText(patch);
send(SCI_COLOURISE,0,-1);
layout();
}
void TextWindow::pollQuickView()
{
if(quickLoading.valid())
@@ -2520,7 +2555,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 || quickDiffVisible) && !previewWanted?SW_SHOWNA:SW_HIDE);
invalidate();
}
@@ -2597,6 +2632,7 @@ void TextWindow::paint()
else if(quickPath.empty()) label+=L" · Select a local text file";
else if(!document || (previewWanted && !previewVisible)) label+=L" · Loading…";
else if(!previewVisible && pageTotal>1) label+=L" · First page";
if(!quickDiffTitle.empty()) label=quickDiffTitle;
drawEditorStatus(dc,{0,0,client.right,row},chromeFont,color(TextColor::chromebg),
color(TextColor::chrome),scale(6),label);
if(chromeFont) DeleteObject(chromeFont);
@@ -3259,6 +3295,12 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path)
preview->second->previewFile(path);
}
void previewQuickViewDiff(HWND window,const std::wstring &title,std::string_view patch)
{
if(const auto preview=textWindows.find(window);preview!=textWindows.end())
preview->second->previewDiff(title,patch);
}
ImageViewStyle imageViewStyle(TextDialogs dialogs)
{
const auto font=dialogs.readFont();
+1
View File
@@ -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 previewQuickViewDiff(HWND window,const std::wstring &title,std::string_view patch);
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,
+8 -22
View File
@@ -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)};
+21
View File
@@ -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'"';
}
}