28#include <wx/richmsgdlg.h>
29#include <wx/stdpaths.h>
32#include <wx/textdlg.h>
34#include <wx/wupdlock.h>
36#include <wx/dcclient.h>
37#include <wx/progdlg.h>
38#include <wx/settings.h>
39#include <wx/weakref.h>
108 return aTask.valid() && aTask.wait_for( std::chrono::seconds( 0 ) ) != std::future_status::ready;
117 wxT(
"^.*\\.kicad_pro$" ),
120 wxT(
"^.*\\.kicad_sch$" ),
121 wxT(
"^[^$].*\\.brd$" ),
122 wxT(
"^[^$].*\\.kicad_pcb$" ),
123 wxT(
"^[^$].*\\.kicad_dru$" ),
124 wxT(
"^[^$].*\\.kicad_wks$" ),
125 wxT(
"^[^$].*\\.kicad_mod$" ),
129 wxT(
"^.*\\.kicad_sym$" ),
134 wxT(
"^.*\\.gbrjob$" ),
135 wxT(
"^.*\\.gb[alops]$" ),
136 wxT(
"^.*\\.gt[alops]$" ),
137 wxT(
"^.*\\.g[0-9]{1,2}$" ),
138 wxT(
"^.*\\.gm[0-9]{1,2}$" ),
142 wxT(
"^.*\\.html$" ),
153 wxT(
"^.*\\.kicad_jobset" ),
217 wxSashLayoutWindow( parent,
ID_LEFT_FRAME, wxDefaultPosition, wxDefaultSize, wxNO_BORDER | wxTAB_TRAVERSAL ),
228 Bind( wxEVT_FSWATCHER,
231 Bind( wxEVT_SYS_COLOUR_CHANGED,
245 m_filters.emplace_back( wxT(
"^no KiCad files found" ) );
255 Unbind( wxEVT_FSWATCHER,
257 Unbind( wxEVT_SYS_COLOUR_CHANGED,
267 common->RemoveRefreshListener(
this );
293 if( tree_data.size() != 1 )
296 wxString prj_filename = tree_data[0]->GetFileName();
298 m_Parent->LoadProject( prj_filename );
310 wxString curr_dir = item_data->GetDir();
312 if( curr_dir.IsEmpty() )
315 curr_dir = wxPathOnly(
m_Parent->GetProjectFileName() );
318 if( curr_dir.IsEmpty() || !wxFileName::DirExists( curr_dir ) )
321 if( !curr_dir.IsEmpty() )
322 curr_dir += wxFileName::GetPathSeparator();
337 wxString prj_dir = wxPathOnly(
m_Parent->GetProjectFileName() );
340 wxString curr_dir = item_data->GetDir();
342 if( curr_dir.IsEmpty() )
345 wxString new_dir = wxGetTextFromUser(
_(
"Directory name:" ),
_(
"Create New Directory" ) );
347 if( new_dir.IsEmpty() )
350 wxString full_dirname = curr_dir + wxFileName::GetPathSeparator() + new_dir;
352 if( !wxMkdir( full_dirname ) )
400 return wxEmptyString;
406 std::vector<wxString> projects;
407 wxString dir_filename;
408 bool haveFile = dir.GetFirst( &dir_filename );
412 wxFileName file( dir_filename );
416 projects.push_back( file.GetName() );
418 haveFile = dir.GetNext( &dir_filename );
429 const wxTreeItemId& aParent,
430 std::vector<wxString>* aProjectNames,
434 wxFileName fn( aName );
437 return wxTreeItemId();
440 if( fn.GetFullName().IsSameAs( wxS(
".git" ),
false ) )
441 return wxTreeItemId();
443 if( wxDirExists( aName ) )
451 bool addFile =
false;
453 for(
const wxString& m_filter :
m_filters )
455 wxCHECK2_MSG( reg.Compile( m_filter, wxRE_ICASE ),
continue,
456 wxString::Format(
"Regex %s failed to compile.", m_filter ) );
458 if( reg.Matches( aName ) )
466 return wxTreeItemId();
473 if( ext == wxT(
"" ) )
476 if( reg.Compile( wxString::FromAscii(
"^.*\\." ) + ext + wxString::FromAscii(
"$" ), wxRE_ICASE )
477 && reg.Matches( aName ) )
485 wxString file = wxFileNameFromPath( aName );
486 wxFileName currfile( file );
488 bool showAllSchematics =
gitRepo() !=
nullptr;
492 && ( currfile.GetName().CmpNoCase(
project.GetName() ) == 0 ) )
494 return wxTreeItemId();
503 return wxTreeItemId();
509 if( !parentTreeItem )
510 return wxTreeItemId();
512 wxDir parentDir( parentTreeItem->
GetDir() );
513 std::vector<wxString> projects =
getProjects( parentDir );
516 return wxTreeItemId();
521 wxTreeItemIdValue cookie;
522 wxTreeItemId kid =
m_TreeProject->GetFirstChild( aParent, cookie );
529 return itemData->GetId();
550 if( fname.GetName().CmpNoCase( currfile.GetName() ) == 0 )
556 return wxTreeItemId();
562 return wxTreeItemId();
589 wxTreeItemId newItemId =
m_TreeProject->AppendItem( aParent, file );
596 wxString fileName = currfile.GetName().Lower();
597 wxString projName =
project.GetName().Lower();
599 if( fileName == projName || fileName.StartsWith( projName +
"-" ) )
603 bool subdir_populated =
false;
614 std::vector<wxString> projects =
getProjects( dir );
615 wxString dir_filename;
616 bool haveFile = dir.GetFirst( &dir_filename );
621 subdir_populated = aRecurse;
627 wxString
path = aName + wxFileName::GetPathSeparator() + dir_filename;
630 haveFile = dir.GetNext( &dir_filename );
639 if( subdir_populated )
659 wxString pro_dir =
m_Parent->GetProjectFileName();
673 if( !
Pgm().GetCommonSettings()->m_Git.enableGit )
679 wxFileName fn = pro_dir;
680 bool prjReset =
false;
691 bool prjOpened = fn.FileExists();
693 if(
Pgm().GetCommonSettings()->m_Git.enableGit )
701 if( !prjOpened && !prjReset )
704 prjOpened = fn.FileExists();
724 pro_dir = wxPathOnly(
m_Parent->GetProjectFileName() );
725 wxDir dir( pro_dir );
729 std::vector<wxString> projects =
getProjects( dir );
731 bool haveFile = dir.GetFirst( &filename );
735 if( filename != fn.GetFullName() )
737 wxString
name = dir.GetName() + wxFileName::GetPathSeparator() + filename;
744 haveFile = dir.GetNext( &filename );
761 wxLogTrace(
traceGit,
"PROJECT_TREE_PANE::ReCreateTreePrj: starting timers" );
770 wxTreeItemId curr_item = Event.GetItem();
789 bool can_switch_to_project =
true;
790 bool can_create_new_directory =
true;
791 bool can_open_this_directory =
true;
792 bool can_edit =
true;
793 bool can_rename =
true;
794 bool can_delete =
true;
795 bool run_jobs =
false;
798 bool vcs_enabled = !gitIntegrationDisabled;
799 bool vcs_has_repo =
gitRepo() !=
nullptr;
800 bool vcs_can_init = vcs_enabled && !vcs_has_repo;
801 bool vcs_can_set_remote = vcs_enabled && vcs_has_repo;
804 bool vcs_can_remove = vcs_has_repo || gitIntegrationDisabled;
805 bool vcs_can_switch = vcs_enabled && vcs_has_repo;
806 bool vcs_can_show_history = vcs_enabled && vcs_has_repo;
812 vcs_menu &= libgit_init;
814 if( selection.size() == 0 )
818 if( selection.size() != 1 )
820 can_switch_to_project =
false;
821 can_create_new_directory =
false;
830 can_switch_to_project =
false;
836 can_delete = item->CanDelete();
837 can_rename = item->CanRename();
839 switch( item->GetType() )
847 can_switch_to_project =
false;
851 can_create_new_directory =
false;
852 can_open_this_directory =
false;
857 can_switch_to_project =
false;
864 can_switch_to_project =
false;
865 can_create_new_directory =
false;
866 can_open_this_directory =
false;
879 can_switch_to_project =
false;
880 can_create_new_directory =
false;
881 can_open_this_directory =
false;
891 if( can_switch_to_project )
894 _(
"Close all editors, and switch to the selected project" ),
896 popup_menu.AppendSeparator();
899 if( can_create_new_directory )
905 if( can_open_this_directory )
907 if( selection.size() == 1 )
910 text =
_(
"Reveal in Finder" );
911 help_text =
_(
"Reveals the directory in a Finder window" );
913 text =
_(
"Open Directory in File Explorer" );
914 help_text =
_(
"Opens the directory in the default system file manager" );
920 text =
_(
"Reveal in Finder" );
921 help_text =
_(
"Reveals the directories in a Finder window" );
923 text =
_(
"Open Directories in File Explorer" );
924 help_text =
_(
"Opens the directories in the default system file manager" );
934 if( selection.size() == 1 )
935 help_text =
_(
"Open the file in a Text Editor" );
937 help_text =
_(
"Open files in a Text Editor" );
943 if( run_jobs && selection.size() == 1 )
951 if( selection.size() == 1 )
953 text =
_(
"Rename File..." );
954 help_text =
_(
"Rename file" );
958 text =
_(
"Rename Files..." );
959 help_text =
_(
"Rename files" );
968 if( selection.size() == 1 )
969 help_text =
_(
"Delete the file and its content" );
971 help_text =
_(
"Delete the files and their contents" );
973 if( can_switch_to_project
974 || can_create_new_directory
975 || can_open_this_directory
979 popup_menu.AppendSeparator();
993 wxMenu* vcs_submenu =
new wxMenu();
994 wxMenu* branch_submenu =
new wxMenu();
995 wxMenuItem* vcs_menuitem =
nullptr;
998 _(
"Add Project to Version Control..." ),
999 _(
"Initialize a new repository" ) );
1000 vcs_menuitem->Enable( vcs_can_init );
1003 _(
"Set or change the default remote URL and credentials" ) );
1004 vcs_menuitem->Enable( vcs_can_set_remote );
1008 vcs_submenu->AppendSeparator();
1010 vcs_menuitem = vcs_submenu->Append(
ID_GIT_HISTORY,
_(
"Version History..." ),
1011 _(
"Show the commits made to this project" ) );
1012 vcs_menuitem->Enable( vcs_can_show_history );
1016 std::shared_ptr<KIGIT_COMMON> common =
gitCommon();
1019 std::vector<KIGIT_BRANCH_INFO> branches;
1022 std::unique_lock<std::mutex> branchLock = common->TryLockAction();
1024 if( branchLock.owns_lock() )
1025 branches = common->GetBranches();
1032 if( branch.isRemote || branch.isCurrent )
1045 vcs_menuitem->Enable( vcs_can_switch );
1049 _(
"Switch to a different branch" ) );
1050 vcs_menuitem->Enable( vcs_can_switch );
1052 vcs_menuitem = vcs_submenu->Append(
ID_GIT_SWITCH_BRANCH,
_(
"Switch to Branch" ), branch_submenu );
1053 vcs_menuitem->Enable( vcs_can_switch );
1055 vcs_submenu->AppendSeparator();
1057 if( gitIntegrationDisabled )
1059 vcs_menuitem = vcs_submenu->Append(
ID_GIT_REMOVE_VCS,
_(
"Enable Git Integration" ),
1060 _(
"Re-enable Git integration for this project" ) );
1064 vcs_menuitem = vcs_submenu->Append(
ID_GIT_REMOVE_VCS,
_(
"Disable Git Integration" ),
1065 _(
"Disable Git integration for this project" ) );
1068 vcs_menuitem->Enable( vcs_can_remove );
1070 popup_menu.AppendSeparator();
1071 popup_menu.AppendSubMenu( vcs_submenu,
_(
"Version Control" ) );
1074 if( popup_menu.GetMenuItemCount() > 0 )
1075 PopupMenu( &popup_menu );
1083 if( editorname.IsEmpty() )
1085 wxMessageBox(
_(
"No text editor selected in KiCad. Please choose one." ) );
1093 wxString fullFileName = item_data->GetFileName();
1095 if( !fullFileName.IsEmpty() )
1097 ExecuteFile( editorname, fullFileName.wc_str(),
nullptr,
false );
1108 item_data->Delete();
1118 if( tree_data.size() != 1 )
1122 wxString msg = wxString::Format(
_(
"Change filename: '%s'" ),
1123 tree_data[0]->GetFileName() );
1124 wxTextEntryDialog dlg( wxGetTopLevelParent(
this ), msg,
_(
"Change filename" ), buffer );
1126 if( dlg.ShowModal() != wxID_OK )
1129 buffer = dlg.GetValue();
1130 buffer.Trim(
true );
1131 buffer.Trim(
false );
1133 if( buffer.IsEmpty() )
1136 tree_data[0]->Rename( buffer,
true );
1145 if( tree_data.size() != 1 )
1168 std::vector<wxTreeItemId> validItemIds;
1171 for( wxTreeItemId
id : validItemIds )
1190 wxTreeItemId itemId = Event.GetItem();
1200 wxTreeItemIdValue cookie;
1201 wxTreeItemId kid =
m_TreeProject->GetFirstChild( itemId, cookie );
1204 bool subdir_populated =
false;
1207 for( ; kid.IsOk(); kid =
m_TreeProject->GetNextChild( itemId, cookie ) )
1218 wxDir dir( fileName );
1220 if( dir.IsOpened() )
1222 std::vector<wxString> projects =
getProjects( dir );
1223 wxString dir_filename;
1224 bool haveFile = dir.GetFirst( &dir_filename );
1229 wxString
name = fileName + wxFileName::GetPathSeparator() + dir_filename;
1232 haveFile = dir.GetNext( &dir_filename );
1238 subdir_populated =
true;
1247 if( subdir_populated )
1255 wxArrayTreeItemIds selection;
1256 std::vector<PROJECT_TREE_ITEM*> data;
1260 for(
const wxTreeItemId itemId : selection )
1266 wxLogTrace(
traceGit, wxS(
"Null tree item returned for selection, dynamic_cast failed?" ) );
1270 data.push_back( item );
1285 wxString prj_dir = wxPathOnly(
m_Parent->GetProjectFileName() );
1289 if( prj_dir == aSubDir )
1293 wxTreeItemIdValue cookie;
1294 wxTreeItemId root_id =
m_root;
1295 std::stack<wxTreeItemId> subdirs_id;
1297 wxTreeItemId child =
m_TreeProject->GetFirstChild( root_id, cookie );
1301 if( ! child.IsOk() )
1303 if( subdirs_id.empty() )
1310 root_id = subdirs_id.top();
1331 subdirs_id.push( child );
1349 if( !( event.GetChangeType() & ( wxFSW_EVENT_CREATE |
1350 wxFSW_EVENT_DELETE |
1351 wxFSW_EVENT_RENAME |
1352 wxFSW_EVENT_MODIFY ) ) )
1357 const wxFileName& pathModified =
event.GetPath();
1360 if( pathModified.GetFullPath().Contains( wxS(
".history" ) ) )
1363 wxString subdir = pathModified.GetPath();
1364 wxString fn = pathModified.GetFullPath();
1367 if( pathModified.GetFullName().IsEmpty() )
1369 subdir = subdir.BeforeLast(
'/' );
1370 fn = fn.BeforeLast(
'/' );
1375 if( !root_id.IsOk() )
1378 CallAfter( [
this] ()
1380 wxLogTrace(
traceGit, wxS(
"File system event detected, updating tree cache" ) );
1384 wxTreeItemIdValue cookie;
1385 wxTreeItemId kid =
m_TreeProject->GetFirstChild( root_id, cookie );
1387 switch( event.GetChangeType() )
1389 case wxFSW_EVENT_CREATE:
1404 case wxFSW_EVENT_DELETE:
1418 case wxFSW_EVENT_RENAME :
1420 const wxFileName& newpath =
event.GetNewPath();
1421 wxString newdir = newpath.GetPath();
1422 wxString newfn = newpath.GetFullPath();
1446 if( rootData && newpath.Exists() && ( newfn != rootData->
GetFileName() ) )
1452 if( newitem.IsOk() )
1473 wxString prj_dir = wxPathOnly(
m_Parent->GetProjectFileName() );
1475#if defined( _WIN32 )
1482 m_Parent->m_FileWatcherInfo =
_(
"Network path: not monitoring folder changes" );
1488 m_Parent->m_FileWatcherInfo =
_(
"Local path: monitoring folder changes" );
1506 class WatcherLogHandler :
public wxLog
1509 explicit WatcherLogHandler(
bool* err ) :
1517 void DoLogTextAtLevel( wxLogLevel level,
const wxString&
text )
override
1519 if( m_err && ( level == wxLOG_Error || level == wxLOG_FatalError ) )
1527 bool watcherHasError =
false;
1528 WatcherLogHandler tmpLog( &watcherHasError );
1537 if( watcherHasError )
1545 fn.AssignDir( prj_dir );
1546 fn.DontFollowLink();
1560 TO_UTF8( fn.GetFullPath() ) );
1568 TO_UTF8( fn.GetFullPath() ) );
1573 if( m_TreeProject->IsEmpty() )
1577 wxTreeItemIdValue cookie;
1578 wxTreeItemId root_id = m_root;
1580 std::stack < wxTreeItemId > subdirs_id;
1582 wxTreeItemId kid = m_TreeProject->GetFirstChild( root_id, cookie );
1583 int total_watch_count = 0;
1589 if( subdirs_id.empty() )
1595 root_id = subdirs_id.top();
1597 kid = m_TreeProject->GetFirstChild( root_id, cookie );
1612 if(
path.Contains( wxS(
".history" ) ) )
1614 kid = m_TreeProject->GetNextChild( root_id, cookie );
1620 if( wxFileName::IsDirReadable(
path ) )
1625 fn.AssignDir(
path );
1626 m_watcher->Add( fn );
1627 total_watch_count++;
1631 if( itemData->
IsPopulated() && m_TreeProject->GetChildrenCount( kid ) )
1632 subdirs_id.push( kid );
1636 kid = m_TreeProject->GetNextChild( root_id, cookie );
1643#if defined(DEBUG) && 1
1644 wxArrayString paths;
1645 m_watcher->GetWatchedPaths( &paths );
1648 for(
unsigned ii = 0; ii < paths.GetCount(); ii++ )
1674 std::shared_ptr<KIGIT_COMMON> common =
gitCommon();
1675 common->SetShuttingDown(
true );
1677 std::unique_lock<std::mutex> lock = common->TryLockAction();
1679 constexpr auto kGraceMs = std::chrono::seconds( 2 );
1680 auto graceEnd = std::chrono::steady_clock::now() + kGraceMs;
1682 while( !lock.owns_lock() && std::chrono::steady_clock::now() < graceEnd )
1684 if( lock.try_lock() )
1686 std::this_thread::sleep_for( std::chrono::milliseconds( 50 ) );
1689 constexpr auto kCheckInterval = std::chrono::seconds( 30 );
1690 bool userAbandoned =
false;
1692 while( !lock.owns_lock() && !userAbandoned )
1694 auto intervalEnd = std::chrono::steady_clock::now() + kCheckInterval;
1697 wxProgressDialog progress(
_(
"Please wait" ),
1698 _(
"Closing project..." ),
1700 wxPD_APP_MODAL | wxPD_SMOOTH );
1702 while( !lock.try_lock()
1703 && std::chrono::steady_clock::now() < intervalEnd )
1706 std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) );
1711 if( lock.owns_lock() )
1714 wxMessageDialog ask(
this,
1715 _(
"A Git operation is still running.\n"
1716 "Keep waiting, or abandon?" ),
1717 _(
"Git Operation Delayed" ),
1718 wxYES_NO | wxICON_QUESTION );
1719 ask.SetYesNoLabels(
_(
"Keep Waiting" ),
_(
"Abandon" ) );
1721 if( ask.ShowModal() == wxID_NO )
1722 userAbandoned =
true;
1736 common->SetRepo(
nullptr );
1759 std::shared_ptr<KIGIT_COMMON> common =
gitCommon();
1770 previous->RemoveRefreshListener(
this );
1774 common->AddRefreshListener(
this,
1803 wxRect
rect( wxPoint( 0, 0 ), GetClientSize() );
1804 wxPaintDC
dc(
this );
1806 dc.SetBrush( wxSystemSettings::GetColour( wxSYS_COLOUR_FRAMEBK ) );
1807 dc.SetPen( wxPen( wxSystemSettings::GetColour( wxSYS_COLOUR_ACTIVEBORDER ), 1 ) );
1851 wxString dir = tree_data->
GetDir();
1855 wxLogError(
"Failed to initialize git project: project directory is empty." );
1860 wxWindow* topLevelParent = wxGetTopLevelParent(
this );
1865 _(
"The selected directory is already a Git project." ) );
1881 const char* canonicalWorkDir = git_repository_workdir( initHandler.
GetRepo() );
1883 if( canonicalWorkDir )
1886 dir, wxString::FromUTF8( canonicalWorkDir ) );
1891 dlg.SetTitle(
_(
"Set default remote" ) );
1918 bool retriedAfterTrust =
false;
1924 std::make_unique<WX_PROGRESS_REPORTER>(
this,
_(
"Fetch Remote" ), 1,
PR_NO_ABORT ) );
1932 if( std::optional<KIGIT::HOST_KEY_FAILURE> hostKey = handler.
GetHostKeyFailure() )
1937 retriedAfterTrust =
true;
1975 wxString existingURL;
1981 if( !lock.owns_lock() )
1984 git_remote* remote =
nullptr;
1986 if( git_remote_lookup( &remote, repo,
"origin" ) == GIT_OK )
1990 if(
const char* url = git_remote_url( remote ) )
1991 existingURL = wxString::FromUTF8( url );
2006 wxWeakRef<PROJECT_TREE_PANE> self(
this );
2007 std::shared_ptr<KIGIT_COMMON> session =
gitCommon();
2013 [self, session, existingURL, username](
bool aFound,
const wxString& aSecret )
2015 if( !self || self->gitCommon() != session || session->IsShuttingDown() || !session->GetRepo() )
2018 self->showGitRemoteSettings( existingURL, username, aFound ? aSecret : wxString() );
2024 const wxString& aPassword )
2032 wxWindow* topLevelParent = wxGetTopLevelParent(
this );
2034 dlg.SetTitle(
_(
"Configure Default Remote" ) );
2051 bool setupOk =
false;
2052 wxString setupError;
2053 wxString setupDetails;
2059 if( !lock.owns_lock() )
2062 setupOk = initHandler.
SetupRemote( remoteConfig );
2085 std::shared_ptr<KIGIT_COMMON> common =
gitCommon();
2087 if( !common->GetRepo() || common->IsShuttingDown() )
2094 std::vector<KIGIT_BRANCH_INFO> entries;
2095 bool loaded =
false;
2098 auto branches = std::make_shared<BRANCHES>();
2099 wxWeakRef<PROJECT_TREE_PANE> self(
this );
2106 branches->loaded =
true;
2108 [self, common, branches]()
2110 if( !branches->loaded || !self || self->IsBeingDeleted() || self->m_Parent->IsBeingDeleted()
2111 || common->IsShuttingDown() || self->gitCommon() != common
2112 || !
Pgm().GetCommonSettings()->m_Git.enableGit
2113 ||
Prj().GetLocalSettings().m_GitIntegrationDisabled )
2118 DIALOG_GIT_SWITCH dlg( wxGetTopLevelParent( self->m_Parent ), std::move( branches->entries ) );
2121 if( !self || self->IsBeingDeleted() || common->IsShuttingDown() || self->gitCommon() != common )
2124 if( retval == wxID_OK || retval == wxID_ADD )
2125 self->switchGitBranch( common, dlg.
GetBranchName(), retval == wxID_ADD );
2146 if( IsBeingDeleted() ||
m_Parent->IsBeingDeleted() ||
gitCommon() != aCommon || aCommon->IsShuttingDown()
2147 || !
Pgm().GetCommonSettings()->m_Git.enableGit ||
Prj().GetLocalSettings().m_GitIntegrationDisabled )
2168 if( IsBeingDeleted() ||
m_Parent->IsBeingDeleted() ||
gitCommon() != aCommon || aCommon->IsShuttingDown()
2169 || !
Pgm().GetCommonSettings()->m_Git.enableGit ||
Prj().GetLocalSettings().m_GitIntegrationDisabled )
2180 if( !lock.owns_lock() )
2194 aCommon->NotifyRefreshListeners();
2208 wxLogTrace(
traceGit, wxS(
"onGitRemoveVCS: Git integration %s" ),
2218 std::stack<wxTreeItemId> items;
2221 while( !items.empty() )
2223 wxTreeItemId current = items.top();
2226 m_TreeProject->SetItemState( current, wxTREE_ITEMSTATE_NONE );
2228 wxTreeItemIdValue cookie;
2229 wxTreeItemId child =
m_TreeProject->GetFirstChild( current, cookie );
2231 while( child.IsOk() )
2233 items.push( child );
2251 wxLogTrace(
traceGit, wxS(
"updateGitStatusIcons: Updating git status icons" ) );
2254 if( !lock.owns_lock() )
2256 wxLogTrace(
traceGit, wxS(
"updateGitStatusIcons: Failed to acquire lock for git status icon update" ) );
2263 wxLogTrace(
traceGit, wxS(
"updateGitStatusIcons: Git is disabled or tree control is null" ) );
2267 std::stack<wxTreeItemId> items;
2270 while( !items.empty() )
2272 wxTreeItemId current = items.top();
2275 if( current.IsOk() &&
m_TreeProject->ItemHasChildren( current ) )
2277 wxTreeItemIdValue cookie;
2278 wxTreeItemId child =
m_TreeProject->GetFirstChild( current, cookie );
2280 while( child.IsOk() )
2282 items.push( child );
2285 m_TreeProject->SetItemState( child,
static_cast<int>( it->second ) );
2299 wxString filename = wxFileNameFromPath( rootItem->
GetFileName() );
2308 wxLogTrace(
traceGit, wxS(
"updateGitStatusIcons: Git status icons updated" ) );
2314 wxLogTrace(
traceGit, wxS(
"updateTreeCache: Updating tree cache" ) );
2318 if( !lock.owns_lock() )
2320 wxLogTrace(
traceGit, wxS(
"updateTreeCache: Failed to acquire lock for tree cache update" ) );
2326 wxLogTrace(
traceGit, wxS(
"updateTreeCache: Tree control is null" ) );
2337 std::stack<wxTreeItemId> items;
2340 while( !items.empty() )
2352 gitAbsPath.Replace( wxS(
"\\" ), wxS(
"/" ) );
2356 wxTreeItemIdValue cookie;
2357 wxTreeItemId child =
m_TreeProject->GetFirstChild( kid, cookie );
2359 while( child.IsOk() )
2361 items.push( child );
2369 const wxString& aProjectFullName )
2371 wxLogTrace(
traceGit, wxS(
"updateGitStatusIconMap: Updating git status icons" ) );
2372#if defined( _WIN32 )
2394 if( !lock1.owns_lock() || !lock2.owns_lock() )
2396 wxLogTrace(
traceGit, wxS(
"updateGitStatusIconMap: Failed to acquire locks for git status icon update" ) );
2402 if( !aGitCommon || !aGitCommon->GetRepo() )
2404 wxLogTrace(
traceGit, wxS(
"updateGitStatusIconMap: No git repository found" ) );
2410 std::unique_lock<std::mutex> gitLock = aGitCommon->TryLockAction();
2412 if( !gitLock.owns_lock() )
2414 wxLogTrace(
traceGit, wxS(
"updateGitStatusIconMap: Failed to acquire git action mutex" ) );
2419 if( aGitCommon->IsShuttingDown() )
2421 wxLogTrace(
traceGit, wxS(
"updateGitStatusIconMap: Cancelled" ) );
2429 wxFileName rootFilename( aProjectFullName );
2432 wxFileName relative = rootFilename;
2433 relative.MakeRelativeTo( repoWorkDir );
2434 wxString pathspecStr = relative.GetPath( wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR );
2437 pathspecStr.Replace( wxS(
"\\" ), wxS(
"/" ) );
2441 auto fileStatusMap = statusHandler.
GetFileStatus( pathspecStr );
2442 auto [localChanges, remoteChanges] = aGitCommon->GetDifferentFiles();
2445 std::map<wxString, unsigned int> currentStatus;
2447 for(
const auto& [absPath, fileStatus] : fileStatusMap )
2448 currentStatus.emplace( absPath, fileStatus.gitStatus );
2455 for(
const auto& [absPath, fileStatus] : fileStatusMap )
2460 wxLogTrace(
traceGit, wxS(
"File '%s' not found in tree cache" ), absPath );
2464 auto [it, inserted] =
m_gitStatusIcons.try_emplace( iter->second, fileStatus.status );
2465 if( inserted || it->second != fileStatus.status )
2467 it->second = fileStatus.status;
2478 wxLogTrace(
traceGit, wxS(
"updateGitStatusIconMap: Updated git status icons" ) );
2484 [
this, aGitCommon]()
2491 aGitCommon->NotifyRefreshListeners();
2504 wxLogTrace(
traceGit,
"onGitSyncTimer" );
2514 wxLogTrace(
traceGit,
"onGitSyncTimer: previous fetch still running, skipping" );
2521 std::shared_ptr<KIGIT_COMMON> common =
gitCommon();
2528 if( !common->GetRepo() )
2530 wxLogTrace(
traceGit,
"onGitSyncTimer: No git repository found" );
2535 if( common->IsShuttingDown() )
2537 wxLogTrace(
traceGit,
"onGitSyncTimer: Cancelled" );
2547 if( !common->IsShuttingDown() )
2549 [
this, common, fetched, kind, summary]()
2552 if( common->IsShuttingDown() || common !=
gitCommon() )
2560 common->NotifyRefreshListeners();
2564 wxLogTrace(
traceGit,
"onGitSyncTimer: Restarting git sync timer" );
2571 const wxString& aSummary )
2591 if( existing.GetTitle() == aSummary )
2609 std::shared_ptr<KIGIT_COMMON> common =
gitCommon();
2611 if( common->IsShuttingDown() )
2625 [
this, common, projectFullName]()
2633 wxLogTrace(
traceGit,
"onGitStatusTimer" );
wxBitmap KiBitmap(BITMAPS aBitmap, int aHeightTag)
Construct a wxBitmap from an image identifier Returns the image from the active theme if the image ha...
BITMAP_STORE * GetBitmapStore()
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
void ThemeChanged()
Notifies the store that the icon theme has been changed by the user, so caches must be invalidated.
void SetRepoSSHPath(const wxString &aPath)
KIGIT_COMMON::GIT_CONN_TYPE GetRepoType() const
void SetPassword(const wxString &aPassword)
wxString GetRepoSSHPath() const
The private key, also when its .pub was picked.
wxString GetRepoURL() const
wxString GetUsername() const
void SetUsername(const wxString &aUsername)
wxString GetPassword() const
void SetSkipButtonLabel(const wxString &aLabel)
wxString GetBranchName() const
virtual bool IsLibraryAvailable()=0
bool IsRepository(const wxString &aPath)
Check if a directory is already a git repository.
InitResult InitializeRepository(const wxString &aPath)
Initialize a new git repository in the specified directory.
bool SetupRemote(const RemoteConfig &aConfig)
Set up a remote for the repository.
void SetProgressReporter(std::unique_ptr< PROGRESS_REPORTER > aProgressReporter)
bool PerformFetch(bool aSkipLock=false)
std::map< wxString, FileStatus > GetFileStatus(const wxString &aPathspec=wxEmptyString, bool aChangedOnly=false)
Get detailed file status for all files in the specified path.
wxString GetCurrentBranchName()
Get the current branch name.
void UpdateRemoteStatus(const std::set< wxString > &aLocalChanges, const std::set< wxString > &aRemoteChanges, std::map< wxString, FileStatus > &aFileStatus)
Get status for modified files based on local/remote changes.
wxString GetWorkingDirectory()
Get the repository working directory path.
The main KiCad project manager frame.
void OnChangeWatchedPaths(wxCommandEvent &aEvent)
Called by sending a event with id = ID_INIT_WATCHED_PATHS rebuild the list of watched paths.
PROJECT_TREE_PANE * m_projectTreePane
static wxString ComputeSymlinkPreservingWorkDir(const wxString &aUserProjectPath, const wxString &aCanonicalWorkDir)
Compute a working directory path that preserves symlinks from the user's project path.
static bool RemoveVCS(git_repository *&aRepo, const wxString &aProjectPath=wxEmptyString, bool aRemoveGitDir=false, wxString *aErrors=nullptr)
Remove version control from a directory by freeing the repository and optionally removing the ....
static int CreateBranch(git_repository *aRepo, const wxString &aBranchName)
Create a new branch based on HEAD.
The project's git session.
wxString GetRemote() const
void SetUsername(const wxString &aUsername)
git_repository * GetRepo() const
void SetProjectDir(const wxString &aProjectDir)
Keep symlinks in the repository path so Git status paths match the project tree.
static constexpr std::chrono::milliseconds ACTION_LOCK_WAIT
Long enough for a status read to finish, short enough that a window does not look hung.
wxString GetUsername() const
void SetShuttingDown(bool aCancel)
Stop the operation running now and keep later ones from starting.
static wxString GetLastGitError()
libgit2's last message, without credentials from any URL it quotes, so it is safe to show or trace.
void UpdateCurrentBranchInfo()
static REMOTE_URL ParseRemoteURL(const wxString &aURL)
wxString GetPassword()
The secret for the remote, read without ever prompting, so it is safe on a transfer worker.
std::vector< KIGIT_BRANCH_INFO > GetBranches() const
Local and remote branches with their tip commits.
void SetRemote(const wxString &aRemote)
bool SecretRead() const
False while the keyring has not been read for the current remote.
KIGIT_ERROR_MESSAGE PopError()
Take the newest error with its details. Both are empty when none is queued.
Read repository state without blocking the UI.
std::optional< KIGIT::HOST_KEY_FAILURE > GetHostKeyFailure() const
The host key this operation's transfer refused, for the UI to offer to trust or to report.
git_repository * GetRepo() const
Get a pointer to the git repository.
void SetActionLockWait(std::chrono::milliseconds aWait)
A UI caller retrying confirmed input waits this long for a background read instead of failing at once...
std::optional< KIGIT_FAILURE > GetFailureKind() const
The kind of the last failure ReportTransferFailure classified, or none.
bool WasAuthFailure() const
Set when the server refused every credential offered, so the caller can prompt and retry.
KISTATUSBAR is a wxStatusBar suitable for Kicad manager.
void AddWarningMessages(const wxString &aSource, const wxString &aMessages)
Add warning/error messages (not thread-safe, use the std::vector<KI_ERROR> variant from other threads...
std::map< wxString, std::vector< KI_ERROR > > GetWarningMessages() const
Get a copy of all stored warning/error messages, grouped by source and sorted by source name for stab...
Holds a structured error message.
KI_ERROR & SetSeverity(SEVERITY aSeverity)
KI_ERROR & SetTitle(const wxString &aTitle)
static wxString GetDefaultUserProjectsPath()
Gets the default path we point users to create projects.
virtual COMMON_SETTINGS * GetCommonSettings() const
virtual const wxString & GetTextEditor(bool aCanShowFileChooser=true)
Return the path to the preferred text editor application.
The project local settings are things that are attached to a particular project, but also might be pa...
bool m_GitIntegrationDisabled
If true, KiCad will not use Git integration for this project even if a .git directory exists.
bool SaveToFile(const wxString &aDirectory="", bool aForce=false) override
Calls Store() and then writes the contents of the JSON document to a file.
wxString m_GitRepoUsername
Handle one item (a file or a directory name) for the tree file.
void SetRootFile(bool aValue)
const wxString & GetFileName() const
void SetPopulated(bool aValue)
TREE_FILE_TYPE GetType() const
const wxString GetDir() const
void Activate(PROJECT_TREE_PANE *aTreePrjFrame)
Window to display the tree files.
PROJECT_TREE_ITEM * m_selectedItem
void switchGitBranch(std::shared_ptr< KIGIT_COMMON > aCommon, const wxString &aBranchName, bool aCreate)
void syncGitListener()
Follow the project's git session with a refresh listener, so operations started from the version cont...
std::unordered_map< wxString, wxTreeItemId > m_gitTreeCache
std::map< wxTreeItemId, KIGIT_COMMON::GIT_STATUS > m_gitStatusIcons
void onGitInitializeProject(wxCommandEvent &event)
Initialize a new git repository in the current project directory.
void showGitRemoteSettings(const wxString &aExistingURL, const wxString &aUsername, const wxString &aPassword)
git_repository * gitRepo() const
void onDeleteFile(wxCommandEvent &event)
Delete the selected file or directory in the tree project.
void onGitRemoveVCS(wxCommandEvent &event)
Remove the git repository from the current project directory.
void EmptyTreePrj()
Delete all m_TreeProject entries.
void FileWatcherReset()
Reinit the watched paths Should be called after opening a new project to rebuild the list of watched ...
wxString m_gitCurrentBranchName
std::vector< PROJECT_TREE_ITEM * > GetSelectedData()
Return the item data from item currently selected (highlighted)
void onOpenDirectory(wxCommandEvent &event)
Handles the right-click menu for opening a directory in the current system file browser.
void onFileSystemEvent(wxFileSystemWatcherEvent &event)
called when a file or directory is modified/created/deleted The tree project is modified when a file ...
wxFileSystemWatcher * m_watcher
void WaitForGitOperations()
Give a running background git operation a chance to finish, asking the user to keep waiting or abando...
void onRight(wxTreeEvent &Event)
Called on a right click on an item.
void onSelect(wxTreeEvent &Event)
Called on a double click on an item.
PROJECT_TREE * m_TreeProject
PROJECT_TREE_PANE(KICAD_MANAGER_FRAME *parent)
std::weak_ptr< KIGIT_COMMON > m_gitMenuSession
KICAD_MANAGER_FRAME * m_Parent
std::future< void > m_gitSyncTask
void onExpand(wxTreeEvent &Event)
Called on a click on the + or - button of an item with children.
std::weak_ptr< KIGIT_COMMON > m_gitListenerSession
std::map< wxString, unsigned int > m_gitLastStatus
Raw status of every file in the last pass, so a change with no tree item still reaches the panels.
std::vector< wxString > m_gitMenuBranches
Preserve the shortcut targets while the context menu runs its event loop.
void onGitSyncTimer(wxTimerEvent &event)
void onGitHistory(wxCommandEvent &event)
Open the advanced Git window on its History page.
void onIdle(wxIdleEvent &aEvent)
Idle event handler, used process the selected items at a point in time when all other events have bee...
void updateTreeCache()
Updates the map of the wxtreeitemid to the name of each file for use in the thread.
void gitStatusTimerHandler()
std::mutex m_gitStatusMutex
static wxString GetFileExt(TREE_FILE_TYPE type)
friend class PROJECT_TREE_ITEM
wxTreeItemId findSubdirTreeItem(const wxString &aSubDir)
Search for the item in tree project which is the node of the subdirectory aSubDir.
void ReCreateTreePrj()
Create or modify the tree showing project file names.
void onThemeChanged(wxSysColourChangedEvent &aEvent)
void onRunSelectedJobsFile(wxCommandEvent &event)
Run a selected jobs file.
void onGitStatusTimer(wxTimerEvent &event)
void shutdownFileWatcher()
Shutdown the file watcher.
std::mutex m_gitTreeCacheMutex
std::shared_ptr< KIGIT_COMMON > gitCommon() const
The current project's git session, created empty on first use.
void updateGitStatusIconMap(std::shared_ptr< KIGIT_COMMON > aGitCommon, const wxString &aProjectFullName)
This is a threaded call that will change the map of git status icons for use in the main thread.
wxTreeItemId addItemToProjectTree(const wxString &aName, const wxTreeItemId &aParent, std::vector< wxString > *aProjectNames, bool aRecurse)
Add the file or directory aName to the project tree.
void onGitRemoteSettings(wxCommandEvent &event)
Configure (or change) the default remote on an already-initialized repository.
void onOpenSelectedFileWithTextEditor(wxCommandEvent &event)
Call the text editor to open the selected file in the tree project.
void updateGitStatusIcons()
Updates the icons shown in the tree project to reflect the current git status.
bool m_gitIconsInitialized
std::future< void > m_gitStatusIconTask
PROJECT_TREE_ITEM * GetItemIdData(wxTreeItemId aId)
Return the item data corresponding to a wxTreeItemId identifier.
std::unique_ptr< KIGIT_QUERY > m_branchQuery
Owns the branch-switch preflight and suppresses callbacks when the project closes.
void reportGitSyncResult(bool aFetched, std::optional< KIGIT_FAILURE > aKind, const wxString &aSummary)
Background fetches have no window to answer, so each failure goes to the status bar's warnings once,...
void onGitSwitchBranch(wxCommandEvent &event)
Switch to a different branch in the git repository.
void onCreateNewDirectory(wxCommandEvent &event)
Creates a new subdirectory inside the current kicad project directory the user is prompted to enter a...
void onSwitchToSelectedProject(wxCommandEvent &event)
Switch to a other project selected from the tree project (by selecting an other .pro file inside the ...
void onPaint(wxPaintEvent &aEvent)
We don't have uniform borders so we have to draw them ourselves.
void onRenameFile(wxCommandEvent &event)
Rename the selected file or directory in the tree project.
void releaseGitRepo()
Releases the git repository handle, deferring the free to the orphan registry while a background git ...
std::vector< wxString > m_filters
PROJECT_TREE This is the class to show (as a tree) the files in the project directory.
Container for project specific data.
virtual std::shared_ptr< KIGIT_COMMON > GetGitCommon() const
This project's Git session, created empty on first use.
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
virtual bool AttachGitRepository()
Find the Git repository containing the project directory and bind it to the session.
virtual PROJECT_LOCAL_SETTINGS & GetLocalSettings() const
virtual void ReleaseGitCommon()
Safely release the session's repository handle and drop the session.
A scoped application of a wxLog target.
void DisplayInfoMessage(wxWindow *aParent, const wxString &aMessage, const wxString &aExtraInfo)
Display an informational message box with aMessage.
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
This file is part of the common library.
wxDECLARE_EVENT(wxEVT_REFRESH_CUSTOM_COMMAND, wxCommandEvent)
EVT_MENU_RANGE(ID_GERBVIEW_DRILL_FILE1, ID_GERBVIEW_DRILL_FILEMAX, GERBVIEW_FRAME::OnDrlFileHistory) EVT_MENU_RANGE(ID_GERBVIEW_ZIP_FILE1
int ExecuteFile(const wxString &aEditorName, const wxString &aFileName, wxProcess *aCallback, bool aFileForKicad)
Call the executable file aEditorName with the parameter aFileName.
GIT_BACKEND * GetGitBackend()
void ProjectClearOfUncommittedWork(EDA_BASE_FRAME *aFrame, wxWindow *aParent, KIGIT_QUERY &aQuery, std::function< void(const GIT_WORKTREE_STATUS &)> aReady)
Check the working tree and Git LFS on a worker, then run aReady on the UI thread when the operation c...
void SwitchProjectToBranch(EDA_BASE_FRAME *aFrame, wxWindow *aParent, const wxString &aBranch, KIGIT_QUERY &aQuery, std::function< void()> aFinished)
Check the working tree on a worker, then confirm switching to aBranch and recheck unsaved editors.
int m_GitIconRefreshInterval
The interval in milliseconds to refresh the git icons in the project tree.
static const std::string LegacySchematicFileExtension
static const std::string HtmlFileExtension
static const wxString GerberFileExtensionsRegex
static const std::string NetlistFileExtension
static const std::string GerberJobFileExtension
static const std::string ReportFileExtension
static const std::string ProjectFileExtension
static const std::string FootprintPlaceFileExtension
static const std::string LegacyPcbFileExtension
static const std::string LegacyProjectFileExtension
static const std::string KiCadSchematicFileExtension
static const std::string LegacySymbolLibFileExtension
static const std::string CsvFileExtension
static const std::string KiCadSymbolLibFileExtension
static const std::string SpiceFileExtension
static const std::string PdfFileExtension
static const std::string TextFileExtension
static const std::string DrawingSheetFileExtension
static const std::string KiCadJobSetFileExtension
static const std::string FootprintAssignmentFileExtension
static const std::string SVGFileExtension
static const std::string DrillFileExtension
static const std::string DesignRulesFileExtension
static const std::string MarkdownFileExtension
static const std::string KiCadFootprintFileExtension
static const std::string ArchiveFileExtension
static const std::string KiCadPcbFileExtension
const wxChar *const tracePathsAndFiles
Flag to enable path and file name debug output.
const wxChar *const traceGit
Flag to enable Git debugging output.
EVT_MENU(ID_COMPARE_PROJECT_BRANCHES, KICAD_MANAGER_FRAME::OnCompareProjectBranches) KICAD_MANAGER_FRAME
bool LaunchExternal(const wxString &aPath)
Launches the given file or folder in the host OS.
This file contains miscellaneous commonly used macros and functions.
#define KI_FALLTHROUGH
The KI_FALLTHROUGH macro is to be used when switch statement cases should purposely fallthrough from ...
void ClearSyncWarnings(wxWindow *aWindow)
Clear the background fetch's warnings from the frame holding aWindow.
void SortBranchesForDisplay(std::vector< KIGIT_BRANCH_INFO > &aBranches)
Put the current branch first, then local and remote branches with the newest tips first.
wxString BranchNameError(const wxString &aName)
Empty when aName is a branch name git would accept, otherwise why it would not, in the words to show ...
constexpr const wxChar * SYNC_WARNING_SOURCE
The status bar source under which background fetch failures are listed.
std::unique_lock< std::mutex > WaitForActionLock(KIGIT_COMMON &aCommon, wxWindow *aParent)
TryLockAction that first waits a moment for a status read or fetch to let go.
PROMPT_ANSWER PromptForCredentials(wxWindow *aParent, KIGIT_COMMON *aCommon, PROJECT *aProject=nullptr, const wxString &aExplanation=wxEmptyString)
Ask the user for the credentials of the session's remote and apply them to the session.
std::unique_lock< std::mutex > TryLockAction(KIGIT_COMMON &aCommon, wxWindow *aParent)
Try the action lock and show a busy message if it is unavailable.
PROMPT_ANSWER PromptToTrustHost(wxWindow *aParent, const HOST_KEY_FAILURE &aFailure, bool aRetriedAfterTrust)
Ask whether to trust a server seen for the first time, and remember its key when the user agrees.
std::unique_ptr< git_remote, decltype([](git_remote *aRemote) { git_remote_free(aRemote); })> GitRemotePtr
A unique pointer for git_remote objects with automatic cleanup.
KICOMMON_API wxMenuItem * AddMenuItem(wxMenu *aMenu, int aId, const wxString &aText, const wxBitmapBundle &aImage, wxItemKind aType=wxITEM_NORMAL)
Create and insert a menu item with an icon into aMenu.
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
PGM_BASE & Pgm()
The global program "get" accessor.
#define NAMELESS_PROJECT
default name for nameless projects
static bool gitTaskStillRunning(const std::future< void > &aTask)
project_tree_ids
The frame that shows the tree list of files and subdirectories inside the working directory.
@ ID_PROJECT_SWITCH_TO_OTHER
@ ID_GIT_INITIALIZE_PROJECT
static bool promptForGitCredentials(wxWindow *aParent, KIGIT_COMMON *aCommon, const wxString &aExplanation)
static void saveAcceptedRemoteSettings(PROJECT &aProject, const RemoteConfig &aConfig)
std::vector< wxString > getProjects(const wxDir &dir)
static const wxChar * s_allowedExtensionsToList[]
#define wxFileSystemWatcher
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Repository state used before an operation that requires a clean working tree.
A summary the user can act on, with the raw text that explains it kept apart for the details.
KIGIT_COMMON::GIT_CONN_TYPE connType
DATABASE_CONNECTION dc(odbcBackend(cs))
wxString result
Test unit parsing edge cases and error handling.
thread_pool & GetKiCadThreadPool()
Get a reference to the current thread pool.
BS::priority_thread_pool thread_pool
wxLogTrace helper definitions.
static PIECE rect(double aLeft, double aTop, double aRight, double aBottom, bool aMixed=false)
Definition of file extensions used in Kicad.