diff --git a/FILES-UI.md b/FILES-UI.md index 390c3d8..f5607ed 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -766,6 +766,13 @@ Warning і початковий фокус на No. робочий файл у Viewer, **F4** відкриває його в Editor, якщо файл існує. **Ctrl+R** перечитує Git, **Esc** повертає обидві панелі. Для цього режиму потрібен Git for Windows. Перегляд залишає Git index без змін. +- У Git Changes кнопка **History** або **F6** відкриває історію. **Branch** + вибирає локальну чи remote-tracking гілку для перегляду. Зірочка + позначає поточну гілку або detached HEAD. Вибір не змінює checkout. + Сусідня панель показує повідомлення коміту та змінені шляхи. + Для merge-коміту список шляхів відповідає різниці з першим батьком. + **More** або **F7** додає наступні 50 комітів, **Ctrl+R** перечитує гілки, + **F6** повертає до Git Changes, а **Esc** повертає до файлових панелей. - Короткі червоні повідомлення використовують звичайний текст без смуги прокрутки. Висота діалогу залежить від кількості рядків повідомлення. - Для однорядкових полів Far використовуй спільний компонент `FAR_EDIT` і спільну підготовку та палітру діалогів. Компонент використовує нативний Win32 Edit без рамки й центрує текст вертикально. Його використовують Search, Copy/Rename, Title/Path і пошук в історії. Кольори Text і Popup background діють на всі ці поля, зокрема на поле Copy лише для читання. У відповідних розділах Options → Colors зміни видно на зразку поля. Existing files у Copy є списком без редагування. Поля та редагований список Windows Options мають системне оформлення. - Для позиціонування роздільника використовуй невидимий маркер, якщо межу не задає інший елемент секції. Спільний обробник малює лінію. diff --git a/src/files_git_changes.cpp b/src/files_git_changes.cpp index 10558cd..ebd9957 100644 --- a/src/files_git_changes.cpp +++ b/src/files_git_changes.cpp @@ -221,10 +221,10 @@ void checkGit(const GitOutput &result,const char *operation,bool allowDifference throw std::runtime_error(detail.empty()?std::string(operation):std::string(operation)+"\r\n"+detail); } -std::string_view statusField(std::string_view &input) +std::string_view nulField(std::string_view &input) { const auto separator=input.find('\0'); - if(separator==input.npos) throw std::runtime_error("Git returned incomplete status output."); + if(separator==input.npos) throw std::runtime_error("Git returned incomplete output."); const auto field=input.substr(0,separator); input.remove_prefix(separator+1); return field; @@ -251,12 +251,12 @@ std::vector parseGitStatus(std::string_view output) std::vector result; while(!output.empty()) { - const auto row=statusField(output); + const auto row=nulField(output); if(row.size()<4 || row[2]!=' ') throw std::runtime_error("Git returned an invalid status record."); const auto code=row.substr(0,2); const auto path=statusPath(row.substr(3)); std::wstring origin; - if(code.find_first_of("RC")!=code.npos) origin=statusPath(statusField(output)); + if(code.find_first_of("RC")!=code.npos) origin=statusPath(nulField(output)); if(code=="??") result.push_back({GitChangeKind::untracked,path,{},L"?"}); else if(code=="DD" || code=="AA" || code.find('U')!=code.npos) result.push_back({GitChangeKind::unstaged,path,{},wide(std::string(code))}); @@ -271,6 +271,13 @@ std::vector parseGitStatus(std::string_view output) }); return result; } + +std::wstring gitRevision(std::string_view value) +{ + if((value.size()!=40 && value.size()!=64) || value.find_first_not_of("0123456789abcdef")!=value.npos) + throw std::runtime_error("Git returned an invalid object ID."); + return {value.begin(),value.end()}; +} } GitChanges readGitChanges(const std::filesystem::path &directory,std::stop_token stop) @@ -304,4 +311,100 @@ std::string readGitPatch(const std::filesystem::path &git,const std::filesystem: checkGit(patch,"Could not read this Git diff.",untracked); return std::move(patch.output); } + +std::vector 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 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()'); + 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; +} } diff --git a/src/files_git_changes.h b/src/files_git_changes.h index 5e05d30..1b7e4af 100644 --- a/src/files_git_changes.h +++ b/src/files_git_changes.h @@ -23,7 +23,30 @@ struct GitChanges std::vector entries; }; +struct GitBranch +{ + std::wstring ref, label, revision; + bool current{}; +}; + +struct GitCommit +{ + std::wstring revision, abbreviated, date, subject; +}; + +struct GitHistoryPage +{ + std::vector commits; + bool more{}; +}; + 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 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); } diff --git a/src/files_git_panel.inl b/src/files_git_panel.inl index 3e54814..ea81f13 100644 --- a/src/files_git_panel.inl +++ b/src/files_git_panel.inl @@ -1,24 +1,47 @@ using ks::files::GitChange; using ks::files::GitChangeKind; using ks::files::GitChanges; +using ks::files::GitBranch; +using ks::files::GitCommit; +using ks::files::GitHistoryPage; + +struct GitPreview +{ + std::wstring heading; + std::variant item; +}; + +struct GitHistoryUpdate +{ + std::optional> branches; + GitHistoryPage page; + size_t branch=0; +}; struct GitChangesView { - HWND host{},heading{},filterLabel{},filter{},list{},status{},hints{},preview{}; + HWND host{},heading{},switchView{},filterLabel{},filter{},branchPicker{},list{},status{},hints{},preview{},moreButton{}; fs::path folder; GitChanges data; std::future refresh; - std::future diff; - std::stop_source stopRefresh,stopDiff; - ULONGLONG diffAt{}; - std::optional requested; + std::future previewTask; + std::stop_source stopRefresh,stopPreview; + ULONGLONG previewAt{}; + std::optional requested; std::string failure; + bool historyMode{},moreHistory{}; + std::vector branches; + std::vector commits; + size_t branchIndex{}; + std::future historyTask; + std::stop_source stopHistory; + std::string historyFailure; }; std::unique_ptr gitChangesView; constexpr wchar_t gitChangesClass[]=L"KSwitcher.Files.GitChanges"; constexpr UINT_PTR gitChangesTimer=1; -constexpr int gitHeading=570,gitFilter=571,gitList=572,gitStatus=573; +constexpr int gitHeading=570,gitFilter=571,gitList=572,gitStatus=573,gitSwitch=574,gitBranch=575,gitMore=576; const wchar_t *gitChangeKindName(GitChangeKind kind) { @@ -39,34 +62,56 @@ const GitChange *selectedGitChange(const GitChangesView &view) return index>=0 && size_t(index)=0 && size_t(index)abbreviated,commit->revision}; + view.previewAt=GetTickCount64()+100; + ks::files::previewQuickViewText(view.preview,view.requested->heading+L" · Loading…",{}); + } + else if(!view.historyFailure.empty()) + ks::files::previewQuickViewText(view.preview,L"Git history failed",view.historyFailure); + else ks::files::previewQuickViewText(view.preview, + view.historyTask.valid()?L"Commit · Reading history…":L"Commit · Select a commit",{}); + return; + } if(view.refresh.valid()) { - ks::files::previewQuickViewDiff(view.preview,L"Diff · Reading Git changes…",{}); + ks::files::previewQuickViewText(view.preview,L"Diff · Reading Git changes…",{}); return; } if(!view.failure.empty()) { - ks::files::previewQuickViewDiff(view.preview,L"Git status failed",view.failure); + ks::files::previewQuickViewText(view.preview,L"Git status failed",view.failure); return; } if(const auto *entry=selectedGitChange(view)) { - view.requested=*entry; - view.diffAt=GetTickCount64()+100; - ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*entry)+L" · Loading…",{}); + view.requested=GitPreview{gitDiffHeading(*entry),*entry}; + view.previewAt=GetTickCount64()+100; + ks::files::previewQuickViewText(view.preview,view.requested->heading+L" · Loading…",{}); } - else ks::files::previewQuickViewDiff(view.preview,L"Diff · Select a change",{}); + else ks::files::previewQuickViewText(view.preview,L"Diff · Select a change",{}); } void renderGitChanges(GitChangesView &view,std::optional previous={}) @@ -107,7 +152,7 @@ void renderGitChanges(GitChangesView &view,std::optional previous={}) !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); + queueGitPreview(view); } void refreshGitChanges(GitChangesView &view) @@ -124,7 +169,7 @@ void refreshGitChanges(GitChangesView &view) std::thread(std::move(task)).detach(); view.refresh=std::move(pending); SetWindowTextW(view.status,L"Reading Git changes…"); - queueGitDiff(view); + queueGitPreview(view); } catch(const std::exception &) { @@ -133,6 +178,114 @@ void refreshGitChanges(GitChangesView &view) } } +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(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 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(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(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; @@ -144,45 +297,52 @@ void pollGitChanges(GitChangesView &view) { view.data=view.refresh.get(); SetWindowTextW(view.heading,(L"Git Changes · "+view.data.root.native()).c_str()); + EnableWindow(view.switchView,TRUE); renderGitChanges(view,selected); } catch(const std::exception &error) { view.data={}; view.failure=error.what(); + EnableWindow(view.switchView,FALSE); renderGitChanges(view); } } - if(view.diffAt && GetTickCount64()>=view.diffAt) + if(view.historyTask.valid() && view.historyTask.wait_for(0ms)==std::future_status::ready) + finishGitHistory(view); + if(view.previewAt && GetTickCount64()>=view.previewAt) { - view.diffAt=0; - view.stopDiff=std::stop_source{}; + view.previewAt=0; + view.stopPreview=std::stop_source{}; try { std::packaged_task task([git=view.data.executable,root=view.data.root, - entry=*view.requested,stop=view.stopDiff.get_token()] { - return ks::files::readGitPatch(git,root,entry,stop); + item=view.requested->item,stop=view.stopPreview.get_token()] { + if(const auto *change=std::get_if(&item)) + return ks::files::readGitPatch(git,root,*change,stop); + return ks::files::readGitCommit(git,root,std::get(item),stop); }); auto pending=task.get_future(); std::thread(std::move(task)).detach(); - view.diff=std::move(pending); + view.previewTask=std::move(pending); } catch(const std::exception &) { - ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),"Could not start Git diff."); + ks::files::previewQuickViewText(view.preview,view.requested->heading,"Could not start the Git preview."); } } - if(view.diff.valid() && view.diff.wait_for(0ms)==std::future_status::ready) + if(view.previewTask.valid() && view.previewTask.wait_for(0ms)==std::future_status::ready) { try { - const auto patch=view.diff.get(); - ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested), - patch.empty()?std::string_view("No differences. Refresh if the worktree has changed."):std::string_view(patch)); + const auto contents=view.previewTask.get(); + ks::files::previewQuickViewText(view.preview,view.requested->heading, + contents.empty()?std::string_view("No differences. Refresh if the worktree has changed."):std::string_view(contents), + std::holds_alternative(view.requested->item)); } catch(const std::exception &error) { - ks::files::previewQuickViewDiff(view.preview,gitDiffHeading(*view.requested),error.what()); + ks::files::previewQuickViewText(view.preview,view.requested->heading,error.what()); } } } @@ -190,7 +350,7 @@ void pollGitChanges(GitChangesView &view) void openGitWorkingFile(GitChangesView &view,bool edit) { const auto *entry=selectedGitChange(view); - if(!entry || view.refresh.valid() || !view.failure.empty()) return; + if(view.historyMode || !entry || view.refresh.valid() || !view.failure.empty()) return; auto relative=fs::path(entry->path); for(const auto &component:relative) if(!validFileName(component.native())) @@ -219,22 +379,54 @@ void layoutGitChildren(GitChangesView &view) { SetWindowPos(control,nullptr,x,y,std::max(0,width),std::max(0,height),SWP_NOZORDER|SWP_NOACTIVATE); }; - const int inset=6, top=4, filterLabel=8*cellWidth; + const int inset=6,top=4,filterLabel=8*cellWidth,buttonWidth=12*cellWidth; const int filterTop=top+textHeight+6, listTop=filterTop+textHeight+6; const int bottom=std::max(listTop,static_cast(bounds.bottom)-textHeight-5); const int leftWidth=std::max(0,middle-2*inset); - place(view.heading,inset,top,leftWidth,textHeight); + place(view.heading,inset,top,leftWidth-buttonWidth-4,textHeight); + place(view.switchView,inset+leftWidth-buttonWidth,top,buttonWidth,textHeight); place(view.filterLabel,inset,filterTop,filterLabel,textHeight); place(view.filter,inset+filterLabel,filterTop,leftWidth-filterLabel,textHeight); + place(view.branchPicker,inset+filterLabel,filterTop,leftWidth-filterLabel,11*textHeight); place(view.list,inset,listTop,leftWidth-scrollBarWidth(view.list),bottom-listTop); - place(view.status,inset,bottom+3,leftWidth,textHeight); + place(view.status,inset,bottom+3,leftWidth-(view.historyMode?buttonWidth+4:0),textHeight); + place(view.moreButton,inset+leftWidth-buttonWidth,bottom+3,buttonWidth,textHeight); place(view.preview,middle+inset,top,bounds.right-middle-2*inset,bottom-top); place(view.hints,middle+inset,bottom+3,bounds.right-middle-2*inset,textHeight); - for(const auto control:{view.heading,view.filterLabel,view.filter,view.list,view.status,view.hints}) + for(const auto control:{view.heading,view.switchView,view.filterLabel,view.filter,view.branchPicker, + view.list,view.status,view.hints,view.moreButton}) SendMessageW(control,WM_SETFONT,reinterpret_cast(mono),FALSE); SendMessageW(view.list,LB_SETITEMHEIGHT,0,textHeight); } +void switchGitView(GitChangesView &view) +{ + if(view.data.root.empty() || view.refresh.valid()) 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); + layoutGitChildren(view); + if(view.historyMode) + { + EnableWindow(view.branchPicker,FALSE); + loadGitHistory(view,true); + } + else + { + view.stopHistory.request_stop(); + view.historyTask={}; + renderGitChanges(view); + } + SetFocus(view.list); +} + LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp) { if(message==WM_NCCREATE) @@ -255,17 +447,26 @@ LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM l reinterpret_cast(static_cast(id)),GetModuleHandleW(nullptr),nullptr); }; view->heading=make(L"STATIC",L"Git Changes",SS_PATHELLIPSIS|SS_NOPREFIX,gitHeading); + view->switchView=make(L"BUTTON",L"History",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitSwitch); view->filterLabel=make(L"STATIC",L"Filter",SS_NOPREFIX); view->filter=make(farEditClass,L"",ES_MULTILINE|ES_AUTOHSCROLL|WS_TABSTOP,gitFilter); + view->branchPicker=make(L"COMBOBOX",L"",CBS_DROPDOWNLIST|CBS_OWNERDRAWFIXED|CBS_HASSTRINGS|WS_TABSTOP|WS_VSCROLL, + gitBranch); view->list=make(L"LISTBOX",L"",LBS_OWNERDRAWFIXED|LBS_HASSTRINGS|LBS_NOINTEGRALHEIGHT|LBS_NOTIFY|WS_TABSTOP,gitList); view->status=make(L"STATIC",L"",SS_ENDELLIPSIS|SS_NOPREFIX,gitStatus); - view->hints=make(L"STATIC",L"F3 View F4 Edit Ctrl+R Refresh Esc Back",SS_ENDELLIPSIS|SS_NOPREFIX); + view->hints=make(L"STATIC",L"F3 View F4 Edit F6 History Ctrl+R Refresh Esc Back",SS_ENDELLIPSIS|SS_NOPREFIX); + view->moreButton=make(L"BUTTON",L"More",BS_OWNERDRAW|WS_TABSTOP|WS_DISABLED,gitMore); try {view->preview=ks::files::createQuickView(window,textWindowDialogs());} catch(const std::exception &) {} - if(!view->heading || !view->filterLabel || !view->filter || !view->list || !view->status || - !view->hints || !view->preview || !SetTimer(window,gitChangesTimer,35,nullptr)) return -1; + if(!view->heading || !view->switchView || !view->filterLabel || !view->filter || !view->branchPicker || + !view->list || !view->status || !view->hints || !view->moreButton || !view->preview || + !SetTimer(window,gitChangesTimer,35,nullptr)) return -1; prepareDialogEdit(view->filter); SendMessageW(view->filter,EM_SETLIMITTEXT,1024,0); + ShowWindow(view->branchPicker,SW_HIDE); + ShowWindow(view->moreButton,SW_HIDE); + layoutGitChildren(*view); + installFarCombo(view->branchPicker,view->filter); installScrollBar(view->list,window); return 0; } @@ -276,13 +477,26 @@ LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM l if(wp==gitChangesTimer) pollGitChanges(*view); return 0; case WM_COMMAND: - if(view->preview && LOWORD(wp)==gitFilter && HIWORD(wp)==EN_CHANGE) + if(!view->historyMode && view->preview && LOWORD(wp)==gitFilter && HIWORD(wp)==EN_CHANGE) { const auto *entry=selectedGitChange(*view); renderGitChanges(*view,entry?std::optional(*entry):std::nullopt); } - else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_SELCHANGE) queueGitDiff(*view); + else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_SELCHANGE) queueGitPreview(*view); else if(LOWORD(wp)==gitList && HIWORD(wp)==LBN_DBLCLK) openGitWorkingFile(*view,false); + else if(LOWORD(wp)==gitSwitch && HIWORD(wp)==BN_CLICKED) switchGitView(*view); + else if(view->historyMode && LOWORD(wp)==gitMore && HIWORD(wp)==BN_CLICKED) loadGitHistory(*view,false,true); + else if(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)branches.size() && size_t(index)!=view->branchIndex) + { + view->branchIndex=static_cast(index); + loadGitHistory(*view,false); + } + } return 0; case WM_MEASUREITEM: reinterpret_cast(lp)->itemHeight=textHeight; @@ -290,6 +504,8 @@ LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM l case WM_DRAWITEM: { const auto &item=*reinterpret_cast(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(-1)) return TRUE; const auto count=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0); if(count<0) return TRUE; @@ -305,7 +521,8 @@ LRESULT CALLBACK gitChangesProcedure(HWND window,UINT message,WPARAM wp,LPARAM l case WM_CTLCOLORLISTBOX: { const auto dc=reinterpret_cast(wp); - const bool input=message==WM_CTLCOLOREDIT; + const bool input=message==WM_CTLCOLOREDIT || + (message==WM_CTLCOLORLISTBOX && reinterpret_cast(lp)!=view->list); SetTextColor(dc,colors[Text]); SetBkColor(dc,colors[input?Dialog:PanelBlue]); return reinterpret_cast(input?teal:blue); @@ -342,7 +559,8 @@ void closeGitChanges(HWND owner,bool restore=true) auto view=std::move(gitChangesView); if(!view) return; view->stopRefresh.request_stop(); - view->stopDiff.request_stop(); + view->stopPreview.request_stop(); + view->stopHistory.request_stop(); if(IsWindow(view->host)) DestroyWindow(view->host); if(restore) { @@ -398,11 +616,19 @@ bool handleGitChangesKey(HWND owner,const MSG &message) const bool control=GetKeyState(VK_CONTROL)&0x8000; const bool alt=GetKeyState(VK_MENU)&0x8000; if(alt) return false; + const auto selector=view.historyMode?view.branchPicker:view.filter; + if(view.historyMode && SendMessageW(view.branchPicker,CB_GETDROPPEDSTATE,0,0)) return false; if(!control && key==VK_ESCAPE) closeGitChanges(owner); - else if(control && key=='R') refreshGitChanges(view); - else if(control && key=='F') SetFocus(view.filter); - else if(!control && key==VK_TAB) SetFocus(GetFocus()==view.filter?view.list:view.filter); - else if(!control && (key==VK_F3 || key==VK_F4 || (key==VK_RETURN && GetFocus()==view.list))) + else if(control && key=='R') + { + if(view.historyMode) loadGitHistory(view,true); + else refreshGitChanges(view); + } + else if(control && key=='F') SetFocus(selector); + else if(!control && key==VK_TAB) SetFocus(GetFocus()==selector?view.list:selector); + else if(!control && key==VK_F6) switchGitView(view); + else if(!control && view.historyMode && key==VK_F7) loadGitHistory(view,false,true); + 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)) diff --git a/src/files_text_window.cpp b/src/files_text_window.cpp index 33c11af..fc2f699 100644 --- a/src/files_text_window.cpp +++ b/src/files_text_window.cpp @@ -804,7 +804,7 @@ public: bool handleKey(const MSG &message); void goToFragment(std::string_view fragment); void previewFile(const std::filesystem::path &path); - void previewDiff(const std::wstring &title,std::string_view patch); + void previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff); bool openBookmark(const ViewerBookmark &bookmark); std::filesystem::path original; const std::string peerId; @@ -936,8 +936,8 @@ private: }; std::future quickLoading; std::filesystem::path quickPath; - std::wstring quickDiffTitle; - bool quickDiffVisible{}; + std::wstring quickTextTitle; + bool quickTextVisible{},quickTextDiff{}; uint64_t quickRequest{}, quickReading{}; ULONGLONG quickReadyAt{}; std::wstring quickError; @@ -1625,9 +1625,9 @@ std::string readMarkdownDocument(TextDocument &document) void TextWindow::previewFile(const std::filesystem::path &path) { - if(quickDiffTitle.empty() && path==quickPath) return; - quickDiffVisible=false; - quickDiffTitle.clear(); + if(quickTextTitle.empty() && path==quickPath) return; + quickTextVisible=false; + quickTextTitle.clear(); quickPath=path; ++quickRequest; quickReadyAt=GetTickCount64()+80; @@ -1639,10 +1639,10 @@ void TextWindow::previewFile(const std::filesystem::path &path) SetTimer(window,quickViewTimer,30,nullptr); } -void TextWindow::previewDiff(const std::wstring &title,std::string_view patch) +void TextWindow::previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff) { if(!embedded) return; - if(quickDiffTitle.empty()) + if(quickTextTitle.empty()) { ++quickRequest; KillTimer(window,quickViewTimer); @@ -1652,13 +1652,17 @@ void TextWindow::previewDiff(const std::wstring &title,std::string_view patch) stopPreview(false,true); document.reset(); quickMarkdown.reset(); - language=automatic=detectLanguage(L"preview.diff",patch); + } + if(quickTextTitle.empty() || quickTextDiff!=diff) + { + language=automatic=diff?detectLanguage(L"preview.diff",contents):TextLanguage{}; installLexer(); } - quickDiffTitle=title; - quickDiffVisible=!patch.empty(); + quickTextTitle=title; + quickTextVisible=!contents.empty(); + quickTextDiff=diff; pageEol=SC_EOL_LF; - replaceEditorText(patch); + replaceEditorText(contents); send(SCI_COLOURISE,0,-1); layout(); } @@ -2555,7 +2559,7 @@ void TextWindow::layout() const LONG bottom=std::max(top,area.bottom-(embedded?0:row)); MoveWindow(editor,0,top,area.right,bottom-top,TRUE); preview.layout({0,top,area.right,bottom},previewWanted && (!embedded || previewVisible)); - ShowWindow(editor,(document || quickDiffVisible) && !previewWanted?SW_SHOWNA:SW_HIDE); + ShowWindow(editor,(document || quickTextVisible) && !previewWanted?SW_SHOWNA:SW_HIDE); invalidate(); } @@ -2632,7 +2636,7 @@ void TextWindow::paint() else if(quickPath.empty()) label+=L" · Select a local text file"; else if(!document || (previewWanted && !previewVisible)) label+=L" · Loading…"; else if(!previewVisible && pageTotal>1) label+=L" · First page"; - if(!quickDiffTitle.empty()) label=quickDiffTitle; + if(!quickTextTitle.empty()) label=quickTextTitle; drawEditorStatus(dc,{0,0,client.right,row},chromeFont,color(TextColor::chromebg), color(TextColor::chrome),scale(6),label); if(chromeFont) DeleteObject(chromeFont); @@ -3295,10 +3299,10 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path) preview->second->previewFile(path); } -void previewQuickViewDiff(HWND window,const std::wstring &title,std::string_view patch) +void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff) { if(const auto preview=textWindows.find(window);preview!=textWindows.end()) - preview->second->previewDiff(title,patch); + preview->second->previewEmbeddedText(title,contents,diff); } ImageViewStyle imageViewStyle(TextDialogs dialogs) diff --git a/src/files_text_window.h b/src/files_text_window.h index 9ba8f9e..45461d6 100644 --- a/src/files_text_window.h +++ b/src/files_text_window.h @@ -106,7 +106,7 @@ RemoteTextSource createLanTextSource(const lan::FilesPeer &peer); inline constexpr UINT quickViewToggleMessage=WM_APP+31; HWND createQuickView(HWND owner,TextDialogs dialogs); void previewQuickViewFile(HWND window,const std::filesystem::path &path); -void previewQuickViewDiff(HWND window,const std::wstring &title,std::string_view patch); +void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff=false); HWND createImageQuickView(HWND owner,TextDialogs dialogs); void previewImageQuickViewFile(HWND window,const std::filesystem::path &path); void openImageWindow(HWND owner,std::vector images,const std::filesystem::path &path,