Files
hrynco-kswitcher/src/files_git_panel.inl
T

905 lines
38 KiB
C++

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;
}