KiCad PCB EDA Suite
Loading...
Searching...
No Matches
project_tree_pane.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2012 SoftPLC Corporation, Dick Hollenbeck <[email protected]>
5 * Copyright (C) 2012 Jean-Pierre Charras, jp.charras at wanadoo.fr
6 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22#include <stack>
25#include <git/git_backend.h>
26
27#include <wx/regex.h>
28#include <wx/richmsgdlg.h>
29#include <wx/stdpaths.h>
30#include <wx/string.h>
31#include <wx/msgdlg.h>
32#include <wx/textdlg.h>
33#include <wx/timer.h>
34#include <wx/wupdlock.h>
35#include <wx/log.h>
36#include <wx/dcclient.h>
37#include <wx/progdlg.h>
38#include <wx/settings.h>
39#include <wx/weakref.h>
40
41#include <frame_type.h>
42#include <kiway.h>
43#include <mail_type.h>
45
47#include <advanced_config.h>
48#include <bitmaps.h>
49#include <bitmap_store.h>
50#include <confirm.h>
56#include <gestfich.h>
57#include <macros.h>
58#include <trace_helpers.h>
61#include <core/kicad_algo.h>
62#include <paths.h>
64#include <scoped_set_reset.h>
65#include <string_utils.h>
66#include <thread_pool.h>
67#include <launch_ext.h>
68#include <wx_log_utils.h>
69
77
79
80#include "project_tree_item.h"
81#include "project_tree.h"
82#include "pgm_kicad.h"
83#include "kicad_id.h"
84#include "kicad_manager_frame.h"
85
86#include "project_tree_pane.h"
87#include <widgets/kistatusbar.h>
88
89#include <kiplatform/io.h>
90#include <kiplatform/secrets.h>
91
92
93/* Note about the project tree build process:
94 * Building the project tree can be *very* long if there are a lot of subdirectories in the
95 * working directory. Unfortunately, this happens easily if the project file *.pro is in the
96 * user's home directory.
97 * So the tree project is built "on demand":
98 * First the tree is built from the current directory and shows files and subdirs.
99 * > First level subdirs trees are built (i.e subdirs contents are not read)
100 * > When expanding a subdir, each subdir contains is read, and the corresponding sub tree is
101 * populated on the fly.
102 */
103
104// The pool's future does not block on destruction, so replacing one still running would abandon
105// the task rather than wait for it.
106static bool gitTaskStillRunning( const std::future<void>& aTask )
107{
108 return aTask.valid() && aTask.wait_for( std::chrono::seconds( 0 ) ) != std::future_status::ready;
109}
110
111
112// list of files extensions listed in the tree project window
113// Add extensions in a compatible regex format to see others files types
114static const wxChar* s_allowedExtensionsToList[] =
115{
116 wxT( "^.*\\.pro$" ),
117 wxT( "^.*\\.kicad_pro$" ),
118 wxT( "^.*\\.pdf$" ),
119 wxT( "^.*\\.sch$" ), // Legacy Eeschema files
120 wxT( "^.*\\.kicad_sch$" ), // S-expr Eeschema files
121 wxT( "^[^$].*\\.brd$" ), // Legacy Pcbnew files
122 wxT( "^[^$].*\\.kicad_pcb$" ), // S format Pcbnew board files
123 wxT( "^[^$].*\\.kicad_dru$" ), // Design rule files
124 wxT( "^[^$].*\\.kicad_wks$" ), // S format kicad drawing sheet files
125 wxT( "^[^$].*\\.kicad_mod$" ), // S format kicad footprint files, currently not listed
126 wxT( "^.*\\.net$" ), // pcbnew netlist file
127 wxT( "^.*\\.cir$" ), // Spice netlist file
128 wxT( "^.*\\.lib$" ), // Legacy schematic library file
129 wxT( "^.*\\.kicad_sym$" ), // S-expr symbol libraries
130 wxT( "^.*\\.txt$" ), // Text files
131 wxT( "^.*\\.md$" ), // Markdown files
132 wxT( "^.*\\.pho$" ), // Gerber file (Old Kicad extension)
133 wxT( "^.*\\.gbr$" ), // Gerber file
134 wxT( "^.*\\.gbrjob$" ), // Gerber job file
135 wxT( "^.*\\.gb[alops]$" ), // Gerber back (or bottom) layer file (deprecated Protel ext)
136 wxT( "^.*\\.gt[alops]$" ), // Gerber front (or top) layer file (deprecated Protel ext)
137 wxT( "^.*\\.g[0-9]{1,2}$" ), // Gerber inner layer file (deprecated Protel ext)
138 wxT( "^.*\\.gm[0-9]{1,2}$" ), // Gerber mechanical layer file (deprecated Protel ext)
139 wxT( "^.*\\.gko$" ), // Gerber keepout layer file (deprecated Protel ext)
140 wxT( "^.*\\.odt$" ),
141 wxT( "^.*\\.htm$" ),
142 wxT( "^.*\\.html$" ),
143 wxT( "^.*\\.rpt$" ), // Report files
144 wxT( "^.*\\.csv$" ), // Report files in comma separated format
145 wxT( "^.*\\.pos$" ), // Footprint position files
146 wxT( "^.*\\.cmp$" ), // CvPcb cmp/footprint link files
147 wxT( "^.*\\.drl$" ), // Excellon drill files
148 wxT( "^.*\\.nc$" ), // Excellon NC drill files (alternate file ext)
149 wxT( "^.*\\.xnc$" ), // Excellon NC drill files (alternate file ext)
150 wxT( "^.*\\.svg$" ), // SVG print/plot files
151 wxT( "^.*\\.ps$" ), // PostScript plot files
152 wxT( "^.*\\.zip$" ), // Zip archive files
153 wxT( "^.*\\.kicad_jobset" ), // KiCad jobs file
154 nullptr // end of list
155};
156
157
163
164
166{
167 ID_PROJECT_TXTEDIT = 8700, // Start well above wxIDs
173
174 ID_GIT_INITIALIZE_PROJECT, // Initialize a new git repository in an existing project
175 ID_GIT_REMOTE_SETTINGS, // Configure (or set) the default remote on an existing repo
176 ID_GIT_HISTORY, // Show the commit history in the advanced Git window
177 ID_GIT_REMOVE_VCS, // Toggle Git integration for this project (preference in kicad_prl)
178 ID_GIT_SWITCH_BRANCH, // Switch the local repository to a different branch
179 ID_GIT_SWITCH_QUICK1, // Switch the local repository to the first quick branch
180 ID_GIT_SWITCH_QUICK2, // Switch the local repository to the second quick branch
181 ID_GIT_SWITCH_QUICK3, // Switch the local repository to the third quick branch
182 ID_GIT_SWITCH_QUICK4, // Switch the local repository to the fourth quick branch
183 ID_GIT_SWITCH_QUICK5, // Switch the local repository to the fifth quick branch
184
186};
187
188
189BEGIN_EVENT_TABLE( PROJECT_TREE_PANE, wxSashLayoutWindow )
190 EVT_TREE_ITEM_ACTIVATED( ID_PROJECT_TREE, PROJECT_TREE_PANE::onSelect )
191 EVT_TREE_ITEM_EXPANDED( ID_PROJECT_TREE, PROJECT_TREE_PANE::onExpand )
192 EVT_TREE_ITEM_RIGHT_CLICK( ID_PROJECT_TREE, PROJECT_TREE_PANE::onRight )
199
206
208
209 EVT_IDLE( PROJECT_TREE_PANE::onIdle )
210 EVT_PAINT( PROJECT_TREE_PANE::onPaint )
211END_EVENT_TABLE()
212
213
214wxDECLARE_EVENT( UPDATE_ICONS, wxCommandEvent );
215
217 wxSashLayoutWindow( parent, ID_LEFT_FRAME, wxDefaultPosition, wxDefaultSize, wxNO_BORDER | wxTAB_TRAVERSAL ),
218 m_branchQuery( std::make_unique<KIGIT_QUERY>() )
219{
220 m_Parent = parent;
221 m_TreeProject = nullptr;
222 m_isRenaming = false;
223 m_selectedItem = nullptr;
224 m_watcherNeedReset = false;
225 m_watcher = nullptr;
226 m_gitIconsInitialized = false;
227
228 Bind( wxEVT_FSWATCHER,
229 wxFileSystemWatcherEventHandler( PROJECT_TREE_PANE::onFileSystemEvent ), this );
230
231 Bind( wxEVT_SYS_COLOUR_CHANGED,
232 wxSysColourChangedEventHandler( PROJECT_TREE_PANE::onThemeChanged ), this );
233
234 m_gitSyncTimer.SetOwner( this );
235 m_gitStatusTimer.SetOwner( this );
236 Bind( wxEVT_TIMER, wxTimerEventHandler( PROJECT_TREE_PANE::onGitSyncTimer ), this, m_gitSyncTimer.GetId() );
237 Bind( wxEVT_TIMER, wxTimerEventHandler( PROJECT_TREE_PANE::onGitStatusTimer ), this, m_gitStatusTimer.GetId() );
238 /*
239 * Filtering is now inverted: the filters are actually used to _enable_ support
240 * for a given file type.
241 */
242 for( int ii = 0; s_allowedExtensionsToList[ii] != nullptr; ii++ )
243 m_filters.emplace_back( s_allowedExtensionsToList[ii] );
244
245 m_filters.emplace_back( wxT( "^no KiCad files found" ) );
246
248}
249
250
252{
253 m_branchQuery->Cancel();
254
255 Unbind( wxEVT_FSWATCHER,
256 wxFileSystemWatcherEventHandler( PROJECT_TREE_PANE::onFileSystemEvent ), this );
257 Unbind( wxEVT_SYS_COLOUR_CHANGED,
258 wxSysColourChangedEventHandler( PROJECT_TREE_PANE::onThemeChanged ), this );
259
260 m_gitSyncTimer.Stop();
261 m_gitStatusTimer.Stop();
262 Unbind( wxEVT_TIMER, wxTimerEventHandler( PROJECT_TREE_PANE::onGitSyncTimer ), this, m_gitSyncTimer.GetId() );
263 Unbind( wxEVT_TIMER, wxTimerEventHandler( PROJECT_TREE_PANE::onGitStatusTimer ), this, m_gitStatusTimer.GetId() );
265
266 if( std::shared_ptr<KIGIT_COMMON> common = m_gitListenerSession.lock() )
267 common->RemoveRefreshListener( this );
268
269 if( m_gitSyncTask.valid() )
270 m_gitSyncTask.wait();
271
272 if( m_gitStatusIconTask.valid() )
273 m_gitStatusIconTask.wait();
274}
275
276
278{
279 if( m_watcher )
280 {
281 m_watcher->RemoveAll();
282 m_watcher->SetOwner( nullptr );
283 delete m_watcher;
284 m_watcher = nullptr;
285 }
286}
287
288
290{
291 std::vector<PROJECT_TREE_ITEM*> tree_data = GetSelectedData();
292
293 if( tree_data.size() != 1 )
294 return;
295
296 wxString prj_filename = tree_data[0]->GetFileName();
297
298 m_Parent->LoadProject( prj_filename );
299}
300
301
302void PROJECT_TREE_PANE::onOpenDirectory( wxCommandEvent& event )
303{
304 // Get the root directory name:
305 std::vector<PROJECT_TREE_ITEM*> tree_data = GetSelectedData();
306
307 for( PROJECT_TREE_ITEM* item_data : tree_data )
308 {
309 // Ask for the new sub directory name
310 wxString curr_dir = item_data->GetDir();
311
312 if( curr_dir.IsEmpty() )
313 {
314 // Use project path if the tree view path was empty.
315 curr_dir = wxPathOnly( m_Parent->GetProjectFileName() );
316
317 // As a last resort use the user's documents folder.
318 if( curr_dir.IsEmpty() || !wxFileName::DirExists( curr_dir ) )
320
321 if( !curr_dir.IsEmpty() )
322 curr_dir += wxFileName::GetPathSeparator();
323 }
324
325 LaunchExternal( curr_dir );
326 }
327}
328
329
330void PROJECT_TREE_PANE::onCreateNewDirectory( wxCommandEvent& event )
331{
332 // Get the root directory name:
333 std::vector<PROJECT_TREE_ITEM*> tree_data = GetSelectedData();
334
335 for( PROJECT_TREE_ITEM* item_data : tree_data )
336 {
337 wxString prj_dir = wxPathOnly( m_Parent->GetProjectFileName() );
338
339 // Ask for the new sub directory name
340 wxString curr_dir = item_data->GetDir();
341
342 if( curr_dir.IsEmpty() )
343 curr_dir = prj_dir;
344
345 wxString new_dir = wxGetTextFromUser( _( "Directory name:" ), _( "Create New Directory" ) );
346
347 if( new_dir.IsEmpty() )
348 return;
349
350 wxString full_dirname = curr_dir + wxFileName::GetPathSeparator() + new_dir;
351
352 if( !wxMkdir( full_dirname ) )
353 return;
354
355 addItemToProjectTree( full_dirname, item_data->GetId(), nullptr, false );
356 }
357}
358
359
361{
362 switch( type )
363 {
382 case TREE_FILE_TYPE::DRILL_NC: return "nc";
383 case TREE_FILE_TYPE::DRILL_XNC: return "xnc";
393
397 case TREE_FILE_TYPE::DIRECTORY: break;
398 }
399
400 return wxEmptyString;
401}
402
403
404std::vector<wxString> getProjects( const wxDir& dir )
405{
406 std::vector<wxString> projects;
407 wxString dir_filename;
408 bool haveFile = dir.GetFirst( &dir_filename );
409
410 while( haveFile )
411 {
412 wxFileName file( dir_filename );
413
414 if( file.GetExt() == FILEEXT::LegacyProjectFileExtension
415 || file.GetExt() == FILEEXT::ProjectFileExtension )
416 projects.push_back( file.GetName() );
417
418 haveFile = dir.GetNext( &dir_filename );
419 }
420
421 return projects;
422}
423
424
425
426
427
428wxTreeItemId PROJECT_TREE_PANE::addItemToProjectTree( const wxString& aName,
429 const wxTreeItemId& aParent,
430 std::vector<wxString>* aProjectNames,
431 bool aRecurse )
432{
434 wxFileName fn( aName );
435
436 if( KIPLATFORM::IO::IsFileHidden( aName ) )
437 return wxTreeItemId();
438
439 // Windows only hides .git when it carries the hidden attribute
440 if( fn.GetFullName().IsSameAs( wxS( ".git" ), false ) )
441 return wxTreeItemId();
442
443 if( wxDirExists( aName ) )
444 {
446 }
447 else
448 {
449 // Filter
450 wxRegEx reg;
451 bool addFile = false;
452
453 for( const wxString& m_filter : m_filters )
454 {
455 wxCHECK2_MSG( reg.Compile( m_filter, wxRE_ICASE ), continue,
456 wxString::Format( "Regex %s failed to compile.", m_filter ) );
457
458 if( reg.Matches( aName ) )
459 {
460 addFile = true;
461 break;
462 }
463 }
464
465 if( !addFile )
466 return wxTreeItemId();
467
468 for( int i = static_cast<int>( TREE_FILE_TYPE::LEGACY_PROJECT );
469 i < static_cast<int>( TREE_FILE_TYPE::MAX ); i++ )
470 {
471 wxString ext = GetFileExt( (TREE_FILE_TYPE) i );
472
473 if( ext == wxT( "" ) )
474 continue;
475
476 if( reg.Compile( wxString::FromAscii( "^.*\\." ) + ext + wxString::FromAscii( "$" ), wxRE_ICASE )
477 && reg.Matches( aName ) )
478 {
479 type = (TREE_FILE_TYPE) i;
480 break;
481 }
482 }
483 }
484
485 wxString file = wxFileNameFromPath( aName );
486 wxFileName currfile( file );
487 wxFileName project( m_Parent->GetProjectFileName() );
488 bool showAllSchematics = gitRepo() != nullptr;
489
490 // Ignore legacy projects with the same name as the current project
491 if( ( type == TREE_FILE_TYPE::LEGACY_PROJECT )
492 && ( currfile.GetName().CmpNoCase( project.GetName() ) == 0 ) )
493 {
494 return wxTreeItemId();
495 }
496
497 if( !showAllSchematics && ( currfile.GetExt() == GetFileExt( TREE_FILE_TYPE::LEGACY_SCHEMATIC )
498 || currfile.GetExt() == GetFileExt( TREE_FILE_TYPE::SEXPR_SCHEMATIC ) ) )
499 {
500 if( aProjectNames )
501 {
502 if( !alg::contains( *aProjectNames, currfile.GetName() ) )
503 return wxTreeItemId();
504 }
505 else
506 {
507 PROJECT_TREE_ITEM* parentTreeItem = GetItemIdData( aParent );
508
509 if( !parentTreeItem )
510 return wxTreeItemId();
511
512 wxDir parentDir( parentTreeItem->GetDir() );
513 std::vector<wxString> projects = getProjects( parentDir );
514
515 if( !alg::contains( projects, currfile.GetName() ) )
516 return wxTreeItemId();
517 }
518 }
519
520 // also check to see if it is already there.
521 wxTreeItemIdValue cookie;
522 wxTreeItemId kid = m_TreeProject->GetFirstChild( aParent, cookie );
523
524 while( kid.IsOk() )
525 {
526 PROJECT_TREE_ITEM* itemData = GetItemIdData( kid );
527
528 if( itemData && itemData->GetFileName() == aName )
529 return itemData->GetId(); // well, we would have added it, but it is already here!
530
531 kid = m_TreeProject->GetNextChild( aParent, cookie );
532 }
533
534 // Only show current files if both legacy and current files are present
539 {
540 kid = m_TreeProject->GetFirstChild( aParent, cookie );
541
542 while( kid.IsOk() )
543 {
544 PROJECT_TREE_ITEM* itemData = GetItemIdData( kid );
545
546 if( itemData )
547 {
548 wxFileName fname( itemData->GetFileName() );
549
550 if( fname.GetName().CmpNoCase( currfile.GetName() ) == 0 )
551 {
552 switch( type )
553 {
555 if( itemData->GetType() == TREE_FILE_TYPE::JSON_PROJECT )
556 return wxTreeItemId();
557
558 break;
559
561 if( itemData->GetType() == TREE_FILE_TYPE::SEXPR_SCHEMATIC )
562 return wxTreeItemId();
563
564 break;
565
567 if( itemData->GetType() == TREE_FILE_TYPE::LEGACY_PROJECT )
568 m_TreeProject->Delete( kid );
569
570 break;
571
573 if( itemData->GetType() == TREE_FILE_TYPE::LEGACY_SCHEMATIC )
574 m_TreeProject->Delete( kid );
575
576 break;
577
578 default:
579 break;
580 }
581 }
582 }
583
584 kid = m_TreeProject->GetNextChild( aParent, cookie );
585 }
586 }
587
588 // Append the item (only appending the filename not the full path):
589 wxTreeItemId newItemId = m_TreeProject->AppendItem( aParent, file );
590 PROJECT_TREE_ITEM* data = new PROJECT_TREE_ITEM( type, aName, m_TreeProject );
591
592 m_TreeProject->SetItemData( newItemId, data );
593 data->SetState( 0 );
594
595 // Mark root files (files which have the same aName as the project)
596 wxString fileName = currfile.GetName().Lower();
597 wxString projName = project.GetName().Lower();
598
599 if( fileName == projName || fileName.StartsWith( projName + "-" ) )
600 data->SetRootFile( true );
601
602#ifndef __WINDOWS__
603 bool subdir_populated = false;
604#endif
605
606 // This section adds dirs and files found in the subdirs
607 // in this case AddFile is recursive, but for the first level only.
608 if( TREE_FILE_TYPE::DIRECTORY == type && aRecurse )
609 {
610 wxDir dir( aName );
611
612 if( dir.IsOpened() ) // protected dirs will not open properly.
613 {
614 std::vector<wxString> projects = getProjects( dir );
615 wxString dir_filename;
616 bool haveFile = dir.GetFirst( &dir_filename );
617
618 data->SetPopulated( true );
619
620#ifndef __WINDOWS__
621 subdir_populated = aRecurse;
622#endif
623
624 while( haveFile )
625 {
626 // Add name in tree, but do not recurse
627 wxString path = aName + wxFileName::GetPathSeparator() + dir_filename;
628 addItemToProjectTree( path, newItemId, &projects, false );
629
630 haveFile = dir.GetNext( &dir_filename );
631 }
632 }
633
634 // Sort filenames by alphabetic order
635 m_TreeProject->SortChildren( newItemId );
636 }
637
638#ifndef __WINDOWS__
639 if( subdir_populated )
640 m_watcherNeedReset = true;
641#endif
642
643 return newItemId;
644}
645
646
648{
649 std::lock_guard<std::mutex> lock1( m_gitStatusMutex );
650 std::lock_guard<std::mutex> lock2( m_gitTreeCacheMutex );
651
652 m_gitStatusTimer.Stop();
653 m_gitSyncTimer.Stop();
654
655 m_gitTreeCache.clear();
656 m_gitStatusIcons.clear();
657 m_gitLastStatus.clear();
658
659 wxString pro_dir = m_Parent->GetProjectFileName();
660
661 if( !m_TreeProject )
662 m_TreeProject = new PROJECT_TREE( this );
663 else
664 m_TreeProject->DeleteAllItems();
665
666 if( !pro_dir ) // This is empty from PROJECT_TREE_PANE constructor
667 return;
668
669 // Releasing here would cancel a push or pull running from an editor panel on every tree
670 // refresh, and a project switch already disposes of the session.
671 if( gitRepo() )
672 {
673 if( !Pgm().GetCommonSettings()->m_Git.enableGit )
675
676 m_gitIconsInitialized = false;
677 }
678
679 wxFileName fn = pro_dir;
680 bool prjReset = false;
681
682 if( !fn.IsOk() )
683 {
684 fn.Clear();
685 fn.SetPath( PATHS::GetDefaultUserProjectsPath() );
686 fn.SetName( NAMELESS_PROJECT );
688 prjReset = true;
689 }
690
691 bool prjOpened = fn.FileExists();
692
693 if( Pgm().GetCommonSettings()->m_Git.enableGit )
694 {
697 }
698
699 // We may have opened a legacy project, in which case GetProjectFileName will return the
700 // name of the migrated (new format) file, which may not have been saved to disk yet.
701 if( !prjOpened && !prjReset )
702 {
704 prjOpened = fn.FileExists();
705
706 // Set the ext back so that in the tree view we see the (not-yet-saved) new file
708 }
709
710 // root tree:
711 m_root = m_TreeProject->AddRoot( fn.GetFullName(), static_cast<int>( TREE_FILE_TYPE::ROOT ),
712 static_cast<int>( TREE_FILE_TYPE::ROOT ) );
713 m_TreeProject->SetItemBold( m_root, true );
714
715 // The main project file is now a JSON file
718
719 m_TreeProject->SetItemData( m_root, data );
720
721 // Now adding all current files if available
722 if( prjOpened )
723 {
724 pro_dir = wxPathOnly( m_Parent->GetProjectFileName() );
725 wxDir dir( pro_dir );
726
727 if( dir.IsOpened() ) // protected dirs will not open, see "man opendir()"
728 {
729 std::vector<wxString> projects = getProjects( dir );
730 wxString filename;
731 bool haveFile = dir.GetFirst( &filename );
732
733 while( haveFile )
734 {
735 if( filename != fn.GetFullName() )
736 {
737 wxString name = dir.GetName() + wxFileName::GetPathSeparator() + filename;
738
739 // Add items living in the project directory, and populate the item
740 // if it is a directory (sub directories will be not populated)
741 addItemToProjectTree( name, m_root, &projects, true );
742 }
743
744 haveFile = dir.GetNext( &filename );
745 }
746 }
747 }
748 else
749 {
750 m_TreeProject->AppendItem( m_root, wxT( "Empty project" ) );
751 }
752
753 m_TreeProject->Expand( m_root );
754
755 // Sort filenames by alphabetic order
756 m_TreeProject->SortChildren( m_root );
757
758 CallAfter(
759 [this] ()
760 {
761 wxLogTrace( traceGit, "PROJECT_TREE_PANE::ReCreateTreePrj: starting timers" );
762 m_gitSyncTimer.Start( 100, wxTIMER_ONE_SHOT );
763 m_gitStatusTimer.Start( 500, wxTIMER_ONE_SHOT );
764 } );
765}
766
767
768void PROJECT_TREE_PANE::onRight( wxTreeEvent& Event )
769{
770 wxTreeItemId curr_item = Event.GetItem();
771
772 // Ensure item is selected (Under Windows right click does not select the item)
773 m_TreeProject->SelectItem( curr_item );
774
775 // The tree control still uses the clicked item after this returns, so a menu command
776 // that closes the project must not run inside the click.
777 CallAfter(
778 [this]
779 {
781 } );
782}
783
784
786{
787 std::vector<PROJECT_TREE_ITEM*> selection = GetSelectedData();
788
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;
796
797 bool gitIntegrationDisabled = Prj().GetLocalSettings().m_GitIntegrationDisabled;
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;
802 // Disable/Enable is a per-project preference toggle, so it's available whenever we
803 // detected a repository for this project or integration is currently disabled.
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;
807 bool vcs_menu = Pgm().GetCommonSettings()->m_Git.enableGit;
808
809 // Check if the libgit2 library is available via backend
810 bool libgit_init = GetGitBackend() && GetGitBackend()->IsLibraryAvailable();
811
812 vcs_menu &= libgit_init;
813
814 if( selection.size() == 0 )
815 return;
816
817 // Remove things that don't make sense for multiple selections
818 if( selection.size() != 1 )
819 {
820 can_switch_to_project = false;
821 can_create_new_directory = false;
822 can_rename = false;
823 }
824
825 for( PROJECT_TREE_ITEM* item : selection )
826 {
827 // Check for empty project
828 if( !item )
829 {
830 can_switch_to_project = false;
831 can_edit = false;
832 can_rename = false;
833 continue;
834 }
835
836 can_delete = item->CanDelete();
837 can_rename = item->CanRename();
838
839 switch( item->GetType() )
840 {
843 can_rename = false;
844
845 if( item->GetId() == m_TreeProject->GetRootItem() )
846 {
847 can_switch_to_project = false;
848 }
849 else
850 {
851 can_create_new_directory = false;
852 can_open_this_directory = false;
853 }
854 break;
855
857 can_switch_to_project = false;
858 can_edit = false;
859 break;
860
863 can_edit = false;
864 can_switch_to_project = false;
865 can_create_new_directory = false;
866 can_open_this_directory = false;
867 break;
868
870 run_jobs = true;
871 can_edit = false;
873
877
878 default:
879 can_switch_to_project = false;
880 can_create_new_directory = false;
881 can_open_this_directory = false;
882
883 break;
884 }
885 }
886
887 wxMenu popup_menu;
888 wxString text;
889 wxString help_text;
890
891 if( can_switch_to_project )
892 {
893 KIUI::AddMenuItem( &popup_menu, ID_PROJECT_SWITCH_TO_OTHER, _( "Switch to this Project" ),
894 _( "Close all editors, and switch to the selected project" ),
896 popup_menu.AppendSeparator();
897 }
898
899 if( can_create_new_directory )
900 {
901 KIUI::AddMenuItem( &popup_menu, ID_PROJECT_NEWDIR, _( "New Directory..." ),
902 _( "Create a New Directory" ), KiBitmap( BITMAPS::directory ) );
903 }
904
905 if( can_open_this_directory )
906 {
907 if( selection.size() == 1 )
908 {
909#ifdef __APPLE__
910 text = _( "Reveal in Finder" );
911 help_text = _( "Reveals the directory in a Finder window" );
912#else
913 text = _( "Open Directory in File Explorer" );
914 help_text = _( "Opens the directory in the default system file manager" );
915#endif
916 }
917 else
918 {
919#ifdef __APPLE__
920 text = _( "Reveal in Finder" );
921 help_text = _( "Reveals the directories in a Finder window" );
922#else
923 text = _( "Open Directories in File Explorer" );
924 help_text = _( "Opens the directories in the default system file manager" );
925#endif
926 }
927
928 KIUI::AddMenuItem( &popup_menu, ID_PROJECT_OPEN_DIR, text, help_text,
930 }
931
932 if( can_edit )
933 {
934 if( selection.size() == 1 )
935 help_text = _( "Open the file in a Text Editor" );
936 else
937 help_text = _( "Open files in a Text Editor" );
938
939 KIUI::AddMenuItem( &popup_menu, ID_PROJECT_TXTEDIT, _( "Edit in a Text Editor" ), help_text,
941 }
942
943 if( run_jobs && selection.size() == 1 )
944 {
945 KIUI::AddMenuItem( &popup_menu, ID_JOBS_RUN, _( "Run Jobs" ), help_text,
947 }
948
949 if( can_rename )
950 {
951 if( selection.size() == 1 )
952 {
953 text = _( "Rename File..." );
954 help_text = _( "Rename file" );
955 }
956 else
957 {
958 text = _( "Rename Files..." );
959 help_text = _( "Rename files" );
960 }
961
962 KIUI::AddMenuItem( &popup_menu, ID_PROJECT_RENAME, text, help_text,
964 }
965
966 if( can_delete )
967 {
968 if( selection.size() == 1 )
969 help_text = _( "Delete the file and its content" );
970 else
971 help_text = _( "Delete the files and their contents" );
972
973 if( can_switch_to_project
974 || can_create_new_directory
975 || can_open_this_directory
976 || can_edit
977 || can_rename )
978 {
979 popup_menu.AppendSeparator();
980 }
981
982#ifdef __WINDOWS__
983 KIUI::AddMenuItem( &popup_menu, ID_PROJECT_DELETE, _( "Delete" ), help_text,
985#else
986 KIUI::AddMenuItem( &popup_menu, ID_PROJECT_DELETE, _( "Move to Trash" ), help_text,
988#endif
989 }
990
991 if( vcs_menu )
992 {
993 wxMenu* vcs_submenu = new wxMenu();
994 wxMenu* branch_submenu = new wxMenu();
995 wxMenuItem* vcs_menuitem = nullptr;
996
997 vcs_menuitem = vcs_submenu->Append( ID_GIT_INITIALIZE_PROJECT,
998 _( "Add Project to Version Control..." ),
999 _( "Initialize a new repository" ) );
1000 vcs_menuitem->Enable( vcs_can_init );
1001
1002 vcs_menuitem = vcs_submenu->Append( ID_GIT_REMOTE_SETTINGS, _( "Configure Default Remote..." ),
1003 _( "Set or change the default remote URL and credentials" ) );
1004 vcs_menuitem->Enable( vcs_can_set_remote );
1005
1006 // Committing, pushing and pulling are done from the docked Version Control panel, so
1007 // the version-control submenu keeps only repository setup, history and branch operations.
1008 vcs_submenu->AppendSeparator();
1009
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 );
1013
1014 // Reading the branch list walks the repository. On contention the submenu is built
1015 // without the shortcuts rather than reading it concurrently.
1016 std::shared_ptr<KIGIT_COMMON> common = gitCommon();
1017 m_gitMenuBranches.clear();
1018 m_gitMenuSession = common;
1019 std::vector<KIGIT_BRANCH_INFO> branches;
1020
1021 {
1022 std::unique_lock<std::mutex> branchLock = common->TryLockAction();
1023
1024 if( branchLock.owns_lock() )
1025 branches = common->GetBranches();
1026 }
1027
1029
1030 for( const KIGIT_BRANCH_INFO& branch : branches )
1031 {
1032 if( branch.isRemote || branch.isCurrent )
1033 continue;
1034
1035 m_gitMenuBranches.push_back( branch.name );
1036
1037 if( m_gitMenuBranches.size() == 5 )
1038 break;
1039 }
1040
1041 for( size_t ii = 0; ii < m_gitMenuBranches.size(); ++ii )
1042 {
1043 wxString msg = _( "Switch to branch " ) + m_gitMenuBranches[ii];
1044 vcs_menuitem = branch_submenu->Append( ID_GIT_SWITCH_QUICK1 + ii, m_gitMenuBranches[ii], msg );
1045 vcs_menuitem->Enable( vcs_can_switch );
1046 }
1047
1048 vcs_menuitem = branch_submenu->Append( ID_GIT_SWITCH_BRANCH, _( "Other..." ),
1049 _( "Switch to a different branch" ) );
1050 vcs_menuitem->Enable( vcs_can_switch );
1051
1052 vcs_menuitem = vcs_submenu->Append( ID_GIT_SWITCH_BRANCH, _( "Switch to Branch" ), branch_submenu );
1053 vcs_menuitem->Enable( vcs_can_switch );
1054
1055 vcs_submenu->AppendSeparator();
1056
1057 if( gitIntegrationDisabled )
1058 {
1059 vcs_menuitem = vcs_submenu->Append( ID_GIT_REMOVE_VCS, _( "Enable Git Integration" ),
1060 _( "Re-enable Git integration for this project" ) );
1061 }
1062 else
1063 {
1064 vcs_menuitem = vcs_submenu->Append( ID_GIT_REMOVE_VCS, _( "Disable Git Integration" ),
1065 _( "Disable Git integration for this project" ) );
1066 }
1067
1068 vcs_menuitem->Enable( vcs_can_remove );
1069
1070 popup_menu.AppendSeparator();
1071 popup_menu.AppendSubMenu( vcs_submenu, _( "Version Control" ) );
1072 }
1073
1074 if( popup_menu.GetMenuItemCount() > 0 )
1075 PopupMenu( &popup_menu );
1076}
1077
1078
1080{
1081 wxString editorname = Pgm().GetTextEditor();
1082
1083 if( editorname.IsEmpty() )
1084 {
1085 wxMessageBox( _( "No text editor selected in KiCad. Please choose one." ) );
1086 return;
1087 }
1088
1089 std::vector<PROJECT_TREE_ITEM*> tree_data = GetSelectedData();
1090
1091 for( PROJECT_TREE_ITEM* item_data : tree_data )
1092 {
1093 wxString fullFileName = item_data->GetFileName();
1094
1095 if( !fullFileName.IsEmpty() )
1096 {
1097 ExecuteFile( editorname, fullFileName.wc_str(), nullptr, false );
1098 }
1099 }
1100}
1101
1102
1103void PROJECT_TREE_PANE::onDeleteFile( wxCommandEvent& event )
1104{
1105 std::vector<PROJECT_TREE_ITEM*> tree_data = GetSelectedData();
1106
1107 for( PROJECT_TREE_ITEM* item_data : tree_data )
1108 item_data->Delete();
1109}
1110
1111
1112void PROJECT_TREE_PANE::onRenameFile( wxCommandEvent& event )
1113{
1114 wxTreeItemId curr_item = m_TreeProject->GetFocusedItem();
1115 std::vector<PROJECT_TREE_ITEM*> tree_data = GetSelectedData();
1116
1117 // XXX: Unnecessary?
1118 if( tree_data.size() != 1 )
1119 return;
1120
1121 wxString buffer = m_TreeProject->GetItemText( curr_item );
1122 wxString msg = wxString::Format( _( "Change filename: '%s'" ),
1123 tree_data[0]->GetFileName() );
1124 wxTextEntryDialog dlg( wxGetTopLevelParent( this ), msg, _( "Change filename" ), buffer );
1125
1126 if( dlg.ShowModal() != wxID_OK )
1127 return; // canceled by user
1128
1129 buffer = dlg.GetValue();
1130 buffer.Trim( true );
1131 buffer.Trim( false );
1132
1133 if( buffer.IsEmpty() )
1134 return; // empty file name not allowed
1135
1136 tree_data[0]->Rename( buffer, true );
1137 m_isRenaming = true;
1138}
1139
1140
1141void PROJECT_TREE_PANE::onSelect( wxTreeEvent& Event )
1142{
1143 std::vector<PROJECT_TREE_ITEM*> tree_data = GetSelectedData();
1144
1145 if( tree_data.size() != 1 )
1146 return;
1147
1148 // Bookmark the selected item but don't try and activate it until later. If we do it now,
1149 // there will be more events at least on Windows in this frame that will steal focus from
1150 // any newly launched windows
1151 m_selectedItem = tree_data[0];
1152}
1153
1154
1155void PROJECT_TREE_PANE::onIdle( wxIdleEvent& aEvent )
1156{
1157 // Idle executes once all other events finished processing. This makes it ideal to launch
1158 // a new window without starting Focus wars.
1159 if( m_watcherNeedReset )
1160 {
1161 m_selectedItem = nullptr;
1163 }
1164
1165 if( m_selectedItem != nullptr && m_TreeProject->GetRootItem().IsOk() )
1166 {
1167 // Make sure m_selectedItem still exists in the tree before activating it.
1168 std::vector<wxTreeItemId> validItemIds;
1169 m_TreeProject->GetItemsRecursively( m_TreeProject->GetRootItem(), validItemIds );
1170
1171 for( wxTreeItemId id : validItemIds )
1172 {
1173 if( GetItemIdData( id ) == m_selectedItem )
1174 {
1175 // Activate launches a window which may run the event loop on top of us and cause
1176 // onIdle to get called again, so be sure to null out m_selectedItem first.
1178 m_selectedItem = nullptr;
1179
1180 item->Activate( this );
1181 break;
1182 }
1183 }
1184 }
1185}
1186
1187
1188void PROJECT_TREE_PANE::onExpand( wxTreeEvent& Event )
1189{
1190 wxTreeItemId itemId = Event.GetItem();
1191 PROJECT_TREE_ITEM* tree_data = GetItemIdData( itemId );
1192
1193 if( !tree_data )
1194 return;
1195
1196 if( tree_data->GetType() != TREE_FILE_TYPE::DIRECTORY )
1197 return;
1198
1199 // explore list of non populated subdirs, and populate them
1200 wxTreeItemIdValue cookie;
1201 wxTreeItemId kid = m_TreeProject->GetFirstChild( itemId, cookie );
1202
1203#ifndef __WINDOWS__
1204 bool subdir_populated = false;
1205#endif
1206
1207 for( ; kid.IsOk(); kid = m_TreeProject->GetNextChild( itemId, cookie ) )
1208 {
1209 PROJECT_TREE_ITEM* itemData = GetItemIdData( kid );
1210
1211 if( !itemData || itemData->GetType() != TREE_FILE_TYPE::DIRECTORY )
1212 continue;
1213
1214 if( itemData->IsPopulated() )
1215 continue;
1216
1217 wxString fileName = itemData->GetFileName();
1218 wxDir dir( fileName );
1219
1220 if( dir.IsOpened() )
1221 {
1222 std::vector<wxString> projects = getProjects( dir );
1223 wxString dir_filename;
1224 bool haveFile = dir.GetFirst( &dir_filename );
1225
1226 while( haveFile )
1227 {
1228 // Add name to tree item, but do not recurse in subdirs:
1229 wxString name = fileName + wxFileName::GetPathSeparator() + dir_filename;
1230 addItemToProjectTree( name, kid, &projects, false );
1231
1232 haveFile = dir.GetNext( &dir_filename );
1233 }
1234
1235 itemData->SetPopulated( true ); // set state to populated
1236
1237#ifndef __WINDOWS__
1238 subdir_populated = true;
1239#endif
1240 }
1241
1242 // Sort filenames by alphabetic order
1243 m_TreeProject->SortChildren( kid );
1244 }
1245
1246#ifndef __WINDOWS__
1247 if( subdir_populated )
1248 m_watcherNeedReset = true;
1249#endif
1250}
1251
1252
1253std::vector<PROJECT_TREE_ITEM*> PROJECT_TREE_PANE::GetSelectedData()
1254{
1255 wxArrayTreeItemIds selection;
1256 std::vector<PROJECT_TREE_ITEM*> data;
1257
1258 m_TreeProject->GetSelections( selection );
1259
1260 for( const wxTreeItemId itemId : selection )
1261 {
1262 PROJECT_TREE_ITEM* item = GetItemIdData( itemId );
1263
1264 if( !item )
1265 {
1266 wxLogTrace( traceGit, wxS( "Null tree item returned for selection, dynamic_cast failed?" ) );
1267 continue;
1268 }
1269
1270 data.push_back( item );
1271 }
1272
1273 return data;
1274}
1275
1276
1278{
1279 return dynamic_cast<PROJECT_TREE_ITEM*>( m_TreeProject->GetItemData( aId ) );
1280}
1281
1282
1283wxTreeItemId PROJECT_TREE_PANE::findSubdirTreeItem( const wxString& aSubDir )
1284{
1285 wxString prj_dir = wxPathOnly( m_Parent->GetProjectFileName() );
1286
1287 // If the subdir is the current working directory, return m_root
1288 // in main list:
1289 if( prj_dir == aSubDir )
1290 return m_root;
1291
1292 // The subdir is in the main tree or in a subdir: Locate it
1293 wxTreeItemIdValue cookie;
1294 wxTreeItemId root_id = m_root;
1295 std::stack<wxTreeItemId> subdirs_id;
1296
1297 wxTreeItemId child = m_TreeProject->GetFirstChild( root_id, cookie );
1298
1299 while( true )
1300 {
1301 if( ! child.IsOk() )
1302 {
1303 if( subdirs_id.empty() ) // all items were explored
1304 {
1305 root_id = child; // Not found: return an invalid wxTreeItemId
1306 break;
1307 }
1308 else
1309 {
1310 root_id = subdirs_id.top();
1311 subdirs_id.pop();
1312 child = m_TreeProject->GetFirstChild( root_id, cookie );
1313
1314 if( !child.IsOk() )
1315 continue;
1316 }
1317 }
1318
1319 PROJECT_TREE_ITEM* itemData = GetItemIdData( child );
1320
1321 if( itemData && ( itemData->GetType() == TREE_FILE_TYPE::DIRECTORY ) )
1322 {
1323 if( itemData->GetFileName() == aSubDir ) // Found!
1324 {
1325 root_id = child;
1326 break;
1327 }
1328
1329 // child is a subdir, push in list to explore it later
1330 if( itemData->IsPopulated() )
1331 subdirs_id.push( child );
1332 }
1333
1334 child = m_TreeProject->GetNextChild( root_id, cookie );
1335 }
1336
1337 return root_id;
1338}
1339
1340
1341void PROJECT_TREE_PANE::onFileSystemEvent( wxFileSystemWatcherEvent& event )
1342{
1343 // No need to process events when we're shutting down
1344 if( !m_watcher )
1345 return;
1346
1347 // Ignore events that are not file creation, deletion, renaming or modification because
1348 // they are not relevant to the project tree.
1349 if( !( event.GetChangeType() & ( wxFSW_EVENT_CREATE |
1350 wxFSW_EVENT_DELETE |
1351 wxFSW_EVENT_RENAME |
1352 wxFSW_EVENT_MODIFY ) ) )
1353 {
1354 return;
1355 }
1356
1357 const wxFileName& pathModified = event.GetPath();
1358
1359 // Ignore events from .history directory (local backup)
1360 if( pathModified.GetFullPath().Contains( wxS( ".history" ) ) )
1361 return;
1362
1363 wxString subdir = pathModified.GetPath();
1364 wxString fn = pathModified.GetFullPath();
1365
1366 // Adjust directories to look like a file item (path and name).
1367 if( pathModified.GetFullName().IsEmpty() )
1368 {
1369 subdir = subdir.BeforeLast( '/' );
1370 fn = fn.BeforeLast( '/' );
1371 }
1372
1373 wxTreeItemId root_id = findSubdirTreeItem( subdir );
1374
1375 if( !root_id.IsOk() )
1376 return;
1377
1378 CallAfter( [this] ()
1379 {
1380 wxLogTrace( traceGit, wxS( "File system event detected, updating tree cache" ) );
1381 m_gitStatusTimer.Start( 1500, wxTIMER_ONE_SHOT );
1382 } );
1383
1384 wxTreeItemIdValue cookie; // dummy variable needed by GetFirstChild()
1385 wxTreeItemId kid = m_TreeProject->GetFirstChild( root_id, cookie );
1386
1387 switch( event.GetChangeType() )
1388 {
1389 case wxFSW_EVENT_CREATE:
1390 {
1391 wxTreeItemId newitem = addItemToProjectTree( fn, root_id, nullptr, true );
1392
1393 // If we are in the process of renaming a file, select the new one
1394 // This is needed for MSW and OSX, since we don't get RENAME events from them, just a
1395 // pair of DELETE and CREATE events.
1396 if( m_isRenaming && newitem.IsOk() )
1397 {
1398 m_TreeProject->SelectItem( newitem );
1399 m_isRenaming = false;
1400 }
1401 }
1402 break;
1403
1404 case wxFSW_EVENT_DELETE:
1405 while( kid.IsOk() )
1406 {
1407 PROJECT_TREE_ITEM* itemData = GetItemIdData( kid );
1408
1409 if( itemData && itemData->GetFileName() == fn )
1410 {
1411 m_TreeProject->Delete( kid );
1412 return;
1413 }
1414 kid = m_TreeProject->GetNextChild( root_id, cookie );
1415 }
1416 break;
1417
1418 case wxFSW_EVENT_RENAME :
1419 {
1420 const wxFileName& newpath = event.GetNewPath();
1421 wxString newdir = newpath.GetPath();
1422 wxString newfn = newpath.GetFullPath();
1423
1424 while( kid.IsOk() )
1425 {
1426 PROJECT_TREE_ITEM* itemData = GetItemIdData( kid );
1427
1428 if( itemData && itemData->GetFileName() == fn )
1429 {
1430 m_TreeProject->Delete( kid );
1431 break;
1432 }
1433
1434 kid = m_TreeProject->GetNextChild( root_id, cookie );
1435 }
1436
1437 // Add the new item only if it is not the current project file (root item).
1438 // Remember: this code is called by a wxFileSystemWatcherEvent event, and not always
1439 // called after an actual file rename, and the cleanup code does not explore the
1440 // root item, because it cannot be renamed by the user. Also, ensure the new file
1441 // actually exists on the file system before it is readded. On Linux, moving a file
1442 // to the trash can cause the same path to be returned in both the old and new paths
1443 // of the event, even though the file isn't there anymore.
1444 PROJECT_TREE_ITEM* rootData = GetItemIdData( root_id );
1445
1446 if( rootData && newpath.Exists() && ( newfn != rootData->GetFileName() ) )
1447 {
1448 wxTreeItemId newroot_id = findSubdirTreeItem( newdir );
1449 wxTreeItemId newitem = addItemToProjectTree( newfn, newroot_id, nullptr, true );
1450
1451 // If the item exists, select it
1452 if( newitem.IsOk() )
1453 m_TreeProject->SelectItem( newitem );
1454 }
1455
1456 m_isRenaming = false;
1457 }
1458 break;
1459
1460 default:
1461 return;
1462 }
1463
1464 // Sort filenames by alphabetic order
1465 m_TreeProject->SortChildren( root_id );
1466}
1467
1468
1470{
1471 m_watcherNeedReset = false;
1472
1473 wxString prj_dir = wxPathOnly( m_Parent->GetProjectFileName() );
1474
1475#if defined( _WIN32 )
1476 if( KIPLATFORM::ENV::IsNetworkPath( prj_dir ) )
1477 {
1478 // Due to a combination of a bug in SAMBA sending bad change event IDs and wxWidgets
1479 // choosing to fault on an invalid event ID instead of sanely ignoring them we need to
1480 // avoid spawning a filewatcher. Unfortunately this punishes corporate environments with
1481 // Windows Server shares :/
1482 m_Parent->m_FileWatcherInfo = _( "Network path: not monitoring folder changes" );
1483 m_Parent->SetStatusText( m_Parent->m_FileWatcherInfo, 1 );
1484 return;
1485 }
1486 else
1487 {
1488 m_Parent->m_FileWatcherInfo = _( "Local path: monitoring folder changes" );
1489 m_Parent->SetStatusText( m_Parent->m_FileWatcherInfo, 1 );
1490 }
1491#endif
1492
1493 // Prepare file watcher:
1494 if( m_watcher )
1495 {
1496 m_watcher->RemoveAll();
1497 }
1498 else
1499 {
1500 // Create a wxWidgets log handler to catch errors during watcher creation
1501 // We need to to this because we cannot get error codes from the wxFileSystemWatcher
1502 // constructor. On Linux, if inotify cannot be initialized (usually due to resource limits),
1503 // wxWidgets will throw a system error and then, we throw another error below, trying to
1504 // add paths to a null watcher. We skip this by installing a temporary log handler that
1505 // catches errors during watcher creation and aborts if any error is detected.
1506 class WatcherLogHandler : public wxLog
1507 {
1508 public:
1509 explicit WatcherLogHandler( bool* err ) :
1510 m_err( err )
1511 {
1512 if( m_err )
1513 *m_err = false;
1514 }
1515
1516 protected:
1517 void DoLogTextAtLevel( wxLogLevel level, const wxString& text ) override
1518 {
1519 if( m_err && ( level == wxLOG_Error || level == wxLOG_FatalError ) )
1520 *m_err = true;
1521 }
1522
1523 private:
1524 bool* m_err;
1525 };
1526
1527 bool watcherHasError = false;
1528 WatcherLogHandler tmpLog( &watcherHasError );
1529
1530 {
1531 SCOPED_WXLOG_TARGET logOverride( &tmpLog );
1532
1534 m_watcher->SetOwner( this );
1535 }
1536
1537 if( watcherHasError )
1538 {
1539 return;
1540 }
1541 }
1542
1543 // We can see wxString under a debugger, not a wxFileName
1544 wxFileName fn;
1545 fn.AssignDir( prj_dir );
1546 fn.DontFollowLink();
1547
1548 // Add directories which should be monitored.
1549 // under windows, we add the curr dir and all subdirs
1550 // under unix, we add only the curr dir and the populated subdirs
1551 // see http://docs.wxwidgets.org/trunk/classwx_file_system_watcher.htm
1552 // under unix, the file watcher needs more work to be efficient
1553 // moreover, under wxWidgets 2.9.4, AddTree does not work properly.
1554 {
1555 wxLogNull logNo; // avoid log messages
1556#ifdef __WINDOWS__
1557 if( ! m_watcher->AddTree( fn ) )
1558 {
1559 wxLogTrace( tracePathsAndFiles, "%s: failed to add '%s'\n", __func__,
1560 TO_UTF8( fn.GetFullPath() ) );
1561 return;
1562 }
1563 }
1564#else
1565 if( !m_watcher->Add( fn ) )
1566 {
1567 wxLogTrace( tracePathsAndFiles, "%s: failed to add '%s'\n", __func__,
1568 TO_UTF8( fn.GetFullPath() ) );
1569 return;
1570 }
1571 }
1572
1573 if( m_TreeProject->IsEmpty() )
1574 return;
1575
1576 // Add subdirs
1577 wxTreeItemIdValue cookie;
1578 wxTreeItemId root_id = m_root;
1579
1580 std::stack < wxTreeItemId > subdirs_id;
1581
1582 wxTreeItemId kid = m_TreeProject->GetFirstChild( root_id, cookie );
1583 int total_watch_count = 0;
1584
1585 while( total_watch_count < ADVANCED_CFG::GetCfg().m_MaxFilesystemWatchers )
1586 {
1587 if( !kid.IsOk() )
1588 {
1589 if( subdirs_id.empty() ) // all items were explored
1590 {
1591 break;
1592 }
1593 else
1594 {
1595 root_id = subdirs_id.top();
1596 subdirs_id.pop();
1597 kid = m_TreeProject->GetFirstChild( root_id, cookie );
1598
1599 if( !kid.IsOk() )
1600 continue;
1601 }
1602 }
1603
1604 PROJECT_TREE_ITEM* itemData = GetItemIdData( kid );
1605
1606 if( itemData && itemData->GetType() == TREE_FILE_TYPE::DIRECTORY )
1607 {
1608 // we can see wxString under a debugger, not a wxFileName
1609 const wxString& path = itemData->GetFileName();
1610
1611 // Skip .history directory and its descendants (local backup)
1612 if( path.Contains( wxS( ".history" ) ) )
1613 {
1614 kid = m_TreeProject->GetNextChild( root_id, cookie );
1615 continue;
1616 }
1617
1618 wxLogTrace( tracePathsAndFiles, "%s: add '%s'\n", __func__, TO_UTF8( path ) );
1619
1620 if( wxFileName::IsDirReadable( path ) ) // linux whines about watching protected dir
1621 {
1622 {
1623 // Silence OS errors that come from the watcher
1624 wxLogNull silence;
1625 fn.AssignDir( path );
1626 m_watcher->Add( fn );
1627 total_watch_count++;
1628 }
1629
1630 // if kid is a subdir, push in list to explore it later
1631 if( itemData->IsPopulated() && m_TreeProject->GetChildrenCount( kid ) )
1632 subdirs_id.push( kid );
1633 }
1634 }
1635
1636 kid = m_TreeProject->GetNextChild( root_id, cookie );
1637 }
1638
1639 if( total_watch_count >= ADVANCED_CFG::GetCfg().m_MaxFilesystemWatchers )
1640 wxLogTrace( tracePathsAndFiles, "%s: too many directories to watch\n", __func__ );
1641#endif
1642
1643#if defined(DEBUG) && 1
1644 wxArrayString paths;
1645 m_watcher->GetWatchedPaths( &paths );
1646 wxLogTrace( tracePathsAndFiles, "%s: watched paths:", __func__ );
1647
1648 for( unsigned ii = 0; ii < paths.GetCount(); ii++ )
1649 wxLogTrace( tracePathsAndFiles, " %s\n", TO_UTF8( paths[ii] ) );
1650#endif
1651 }
1652
1653
1655{
1656 m_branchQuery->Cancel();
1657 m_gitMenuBranches.clear();
1658 m_gitMenuSession.reset();
1660
1661 // Make sure we don't try to inspect the tree after we've deleted its items.
1663
1664 m_TreeProject->DeleteAllItems();
1665}
1666
1667
1669{
1670 m_branchQuery->Cancel();
1671
1672 if( gitRepo() )
1673 {
1674 std::shared_ptr<KIGIT_COMMON> common = gitCommon();
1675 common->SetShuttingDown( true );
1676
1677 std::unique_lock<std::mutex> lock = common->TryLockAction();
1678
1679 constexpr auto kGraceMs = std::chrono::seconds( 2 );
1680 auto graceEnd = std::chrono::steady_clock::now() + kGraceMs;
1681
1682 while( !lock.owns_lock() && std::chrono::steady_clock::now() < graceEnd )
1683 {
1684 if( lock.try_lock() )
1685 break;
1686 std::this_thread::sleep_for( std::chrono::milliseconds( 50 ) );
1687 }
1688
1689 constexpr auto kCheckInterval = std::chrono::seconds( 30 );
1690 bool userAbandoned = false;
1691
1692 while( !lock.owns_lock() && !userAbandoned )
1693 {
1694 auto intervalEnd = std::chrono::steady_clock::now() + kCheckInterval;
1695
1696 {
1697 wxProgressDialog progress( _( "Please wait" ),
1698 _( "Closing project..." ),
1699 100, this,
1700 wxPD_APP_MODAL | wxPD_SMOOTH );
1701
1702 while( !lock.try_lock()
1703 && std::chrono::steady_clock::now() < intervalEnd )
1704 {
1705 progress.Pulse();
1706 std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) );
1707 wxYield();
1708 }
1709 }
1710
1711 if( lock.owns_lock() )
1712 break;
1713
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" ) );
1720
1721 if( ask.ShowModal() == wxID_NO )
1722 userAbandoned = true;
1723 }
1724
1725 if( userAbandoned )
1726 {
1727 // Cancellation was requested above, so a running fetch exits at its next
1728 // callback. The release defers the actual free to the orphan registry.
1729 common.reset();
1731 }
1732 else
1733 {
1734 git_repository* repo = common->GetRepo();
1736 common->SetRepo( nullptr );
1737 }
1738 }
1739}
1740
1741
1743{
1744 m_branchQuery->Cancel();
1745 m_gitMenuBranches.clear();
1746 m_gitMenuSession.reset();
1748}
1749
1750
1751std::shared_ptr<KIGIT_COMMON> PROJECT_TREE_PANE::gitCommon() const
1752{
1753 return Prj().GetGitCommon();
1754}
1755
1756
1758{
1759 std::shared_ptr<KIGIT_COMMON> common = gitCommon();
1760
1761 if( m_gitListenerSession.lock() == common )
1762 return;
1763
1764 m_branchQuery->Cancel();
1765 m_gitMenuBranches.clear();
1766 m_gitMenuSession.reset();
1768
1769 if( std::shared_ptr<KIGIT_COMMON> previous = m_gitListenerSession.lock() )
1770 previous->RemoveRefreshListener( this );
1771
1772 // The status timer coalesces several notifications into one pass, and reads the repository
1773 // locally without fetching.
1774 common->AddRefreshListener( this,
1775 [this]()
1776 {
1777 if( m_TreeProject )
1778 m_gitStatusTimer.Start( 500, wxTIMER_ONE_SHOT );
1779 } );
1780
1781 m_gitListenerSession = common;
1782}
1783
1784
1786{
1787 return gitCommon()->GetRepo();
1788}
1789
1790
1791void PROJECT_TREE_PANE::onThemeChanged( wxSysColourChangedEvent &aEvent )
1792{
1794 m_TreeProject->LoadIcons();
1795 m_TreeProject->Refresh();
1796
1797 aEvent.Skip();
1798}
1799
1800
1801void PROJECT_TREE_PANE::onPaint( wxPaintEvent& event )
1802{
1803 wxRect rect( wxPoint( 0, 0 ), GetClientSize() );
1804 wxPaintDC dc( this );
1805
1806 dc.SetBrush( wxSystemSettings::GetColour( wxSYS_COLOUR_FRAMEBK ) );
1807 dc.SetPen( wxPen( wxSystemSettings::GetColour( wxSYS_COLOUR_ACTIVEBORDER ), 1 ) );
1808
1809 dc.DrawLine( rect.GetLeft(), rect.GetTop(), rect.GetLeft(), rect.GetBottom() );
1810 dc.DrawLine( rect.GetRight(), rect.GetTop(), rect.GetRight(), rect.GetBottom() );
1811}
1812
1813
1814void KICAD_MANAGER_FRAME::OnChangeWatchedPaths( wxCommandEvent& aEvent )
1815{
1816 m_projectTreePane->FileWatcherReset();
1817}
1818
1819
1820// Prompts for git credentials after an auth failure. Returns false if cancelled.
1821static bool promptForGitCredentials( wxWindow* aParent, KIGIT_COMMON* aCommon, const wxString& aExplanation )
1822{
1823 return KIGIT::PromptForCredentials( aParent, aCommon, &Prj(), aExplanation ) == KIGIT::PROMPT_ANSWER::ACCEPTED;
1824}
1825
1826
1827// Persist a remote configuration the user accepted, to the secret store and the project
1828// local settings. Runs only after the remote itself was set up successfully.
1829static void saveAcceptedRemoteSettings( PROJECT& aProject, const RemoteConfig& aConfig )
1830{
1831 // Keyed like the attach-time lookup, which never sees credentials embedded in the address. Async so an
1832 // unlock prompt cannot hold the event loop
1834 aConfig.password );
1835 aProject.GetLocalSettings().m_GitRepoUsername = aConfig.username;
1836 aProject.GetLocalSettings().m_GitSSHKey = aConfig.sshKey;
1837
1839 aProject.GetLocalSettings().m_GitRepoType = "ssh";
1841 aProject.GetLocalSettings().m_GitRepoType = "https";
1842 else
1843 aProject.GetLocalSettings().m_GitRepoType = "local";
1844}
1845
1846
1847void PROJECT_TREE_PANE::onGitInitializeProject( wxCommandEvent& aEvent )
1848{
1849 PROJECT_TREE_ITEM* tree_data = GetItemIdData( m_TreeProject->GetRootItem() );
1850
1851 wxString dir = tree_data->GetDir();
1852
1853 if( dir.empty() )
1854 {
1855 wxLogError( "Failed to initialize git project: project directory is empty." );
1856 return;
1857 }
1858
1859 GIT_INIT_HANDLER initHandler( gitCommon().get() );
1860 wxWindow* topLevelParent = wxGetTopLevelParent( this );
1861
1862 if( initHandler.IsRepository( dir ) )
1863 {
1864 DisplayInfoMessage( topLevelParent,
1865 _( "The selected directory is already a Git project." ) );
1866 return;
1867 }
1868
1869 InitResult result = initHandler.InitializeRepository( dir );
1871 {
1872 KIGIT_ERROR_MESSAGE error = initHandler.PopError();
1873 DisplayErrorMessage( m_parent, error.summary, error.details );
1874 return;
1875 }
1876
1878
1879 gitCommon()->SetShuttingDown( false );
1880
1881 const char* canonicalWorkDir = git_repository_workdir( initHandler.GetRepo() );
1882
1883 if( canonicalWorkDir )
1884 {
1886 dir, wxString::FromUTF8( canonicalWorkDir ) );
1887 gitCommon()->SetProjectDir( symlinkWorkDir );
1888 }
1889
1890 DIALOG_GIT_REPOSITORY dlg( topLevelParent, initHandler.GetRepo() );
1891 dlg.SetTitle( _( "Set default remote" ) );
1892 dlg.SetSkipButtonLabel( _( "Skip" ) );
1893
1894 if( dlg.ShowModal() != wxID_OK )
1895 return;
1896
1897 // Set up the remote
1898 RemoteConfig remoteConfig;
1899 remoteConfig.url = dlg.GetRepoURL();
1900 remoteConfig.username = dlg.GetUsername();
1901 remoteConfig.password = dlg.GetPassword();
1902 remoteConfig.sshKey = dlg.GetRepoSSHPath();
1903 remoteConfig.connType = dlg.GetRepoType();
1904
1905 if( !initHandler.SetupRemote( remoteConfig ) )
1906 {
1907 KIGIT_ERROR_MESSAGE error = initHandler.PopError();
1908 DisplayErrorMessage( m_parent, error.summary, error.details );
1909 return;
1910 }
1911
1913
1914 // Before the fetch, so a corrected login from the prompt below is the one that stays saved
1915 saveAcceptedRemoteSettings( Prj(), remoteConfig );
1916
1917 KIGIT_COMMON* common = gitCommon().get();
1918 bool retriedAfterTrust = false;
1919
1920 while( true )
1921 {
1922 GIT_PULL_HANDLER handler( common );
1923 handler.SetProgressReporter(
1924 std::make_unique<WX_PROGRESS_REPORTER>( this, _( "Fetch Remote" ), 1, PR_NO_ABORT ) );
1925
1926 // A status read can hold the lock briefly, and the login or key just confirmed must not be dropped
1928
1929 if( handler.PerformFetch() )
1930 break;
1931
1932 if( std::optional<KIGIT::HOST_KEY_FAILURE> hostKey = handler.GetHostKeyFailure() )
1933 {
1934 if( KIGIT::PromptToTrustHost( m_parent, *hostKey, retriedAfterTrust ) != KIGIT::PROMPT_ANSWER::ACCEPTED )
1935 break;
1936
1937 retriedAfterTrust = true;
1938 continue;
1939 }
1940
1941 KIGIT_ERROR_MESSAGE error = handler.PopError();
1942
1943 if( handler.WasAuthFailure() )
1944 {
1945 if( promptForGitCredentials( m_parent, common, error.summary ) )
1946 continue;
1947
1948 break;
1949 }
1950
1951 // The remote is saved either way, so this only says why its first fetch did not happen. A cancelled
1952 // fetch needs no dialog
1953 if( !error.summary.IsEmpty() && handler.GetFailureKind() != KIGIT_FAILURE::CANCELLED )
1954 DisplayErrorMessage( m_parent, error.summary, error.details );
1955
1956 break;
1957 }
1958}
1959
1960
1961void PROJECT_TREE_PANE::onGitHistory( wxCommandEvent& aEvent )
1962{
1963 m_Parent->ShowGitHistory();
1964}
1965
1966
1967void PROJECT_TREE_PANE::onGitRemoteSettings( wxCommandEvent& aEvent )
1968{
1969 KIGIT_COMMON* common = gitCommon().get();
1970 git_repository* repo = common ? common->GetRepo() : nullptr;
1971
1972 if( !repo )
1973 return;
1974
1975 wxString existingURL;
1976
1977 {
1978 // Read the remote under the lock, then release it before opening the dialog.
1979 std::unique_lock<std::mutex> lock = KIGIT::TryLockAction( *common, this );
1980
1981 if( !lock.owns_lock() )
1982 return;
1983
1984 git_remote* remote = nullptr;
1985
1986 if( git_remote_lookup( &remote, repo, "origin" ) == GIT_OK )
1987 {
1988 KIGIT::GitRemotePtr remotePtr( remote );
1989
1990 if( const char* url = git_remote_url( remote ) )
1991 existingURL = wxString::FromUTF8( url );
1992 }
1993 }
1994
1995 // Credentials are stored separately from the remote URL.
1996 KIGIT_COMMON credentials( nullptr );
1997 credentials.SetUsername( common->GetUsername() );
1998 credentials.SetRemote( existingURL );
1999
2000 if( credentials.SecretRead() )
2001 {
2002 showGitRemoteSettings( existingURL, credentials.GetUsername(), credentials.GetPassword() );
2003 return;
2004 }
2005
2006 wxWeakRef<PROJECT_TREE_PANE> self( this );
2007 std::shared_ptr<KIGIT_COMMON> session = gitCommon();
2008 wxString username = credentials.GetUsername();
2009
2010 // Saving the dialog stores its password, so a locked keyring must unlock rather than read as empty
2012 credentials.GetRemote(), username,
2013 [self, session, existingURL, username]( bool aFound, const wxString& aSecret )
2014 {
2015 if( !self || self->gitCommon() != session || session->IsShuttingDown() || !session->GetRepo() )
2016 return;
2017
2018 self->showGitRemoteSettings( existingURL, username, aFound ? aSecret : wxString() );
2019 } );
2020}
2021
2022
2023void PROJECT_TREE_PANE::showGitRemoteSettings( const wxString& aExistingURL, const wxString& aUsername,
2024 const wxString& aPassword )
2025{
2026 KIGIT_COMMON* common = gitCommon().get();
2027 git_repository* repo = common ? common->GetRepo() : nullptr;
2028
2029 if( !repo )
2030 return;
2031
2032 wxWindow* topLevelParent = wxGetTopLevelParent( this );
2033 DIALOG_GIT_REPOSITORY dlg( topLevelParent, repo, aExistingURL );
2034 dlg.SetTitle( _( "Configure Default Remote" ) );
2035 dlg.SetUsername( aUsername );
2036 dlg.SetPassword( aPassword );
2037 dlg.SetRepoSSHPath( Prj().GetLocalSettings().m_GitSSHKey );
2038
2039 if( dlg.ShowModal() != wxID_OK )
2040 return;
2041
2042 GIT_INIT_HANDLER initHandler( common );
2043
2044 RemoteConfig remoteConfig;
2045 remoteConfig.url = dlg.GetRepoURL();
2046 remoteConfig.username = dlg.GetUsername();
2047 remoteConfig.password = dlg.GetPassword();
2048 remoteConfig.sshKey = dlg.GetRepoSSHPath();
2049 remoteConfig.connType = dlg.GetRepoType();
2050
2051 bool setupOk = false;
2052 wxString setupError;
2053 wxString setupDetails;
2054
2055 {
2056 // Update the remote config and cached branch info under the same lock.
2057 std::unique_lock<std::mutex> lock = KIGIT::WaitForActionLock( *common, this );
2058
2059 if( !lock.owns_lock() )
2060 return;
2061
2062 setupOk = initHandler.SetupRemote( remoteConfig );
2063 KIGIT_ERROR_MESSAGE error = initHandler.PopError();
2064 setupError = error.summary;
2065 setupDetails = error.details;
2066
2067 if( setupOk )
2068 common->UpdateCurrentBranchInfo();
2069 }
2070
2071 if( !setupOk )
2072 {
2073 DisplayErrorMessage( topLevelParent, setupError, setupDetails );
2074 return;
2075 }
2076
2077 saveAcceptedRemoteSettings( Prj(), remoteConfig );
2078
2079 m_gitStatusTimer.Start( 500, wxTIMER_ONE_SHOT );
2080}
2081
2082
2083void PROJECT_TREE_PANE::onGitSwitchBranch( wxCommandEvent& aEvent )
2084{
2085 std::shared_ptr<KIGIT_COMMON> common = gitCommon();
2086
2087 if( !common->GetRepo() || common->IsShuttingDown() )
2088 return;
2089
2090 if( aEvent.GetId() == ID_GIT_SWITCH_BRANCH )
2091 {
2092 struct BRANCHES
2093 {
2094 std::vector<KIGIT_BRANCH_INFO> entries;
2095 bool loaded = false;
2096 };
2097
2098 auto branches = std::make_shared<BRANCHES>();
2099 wxWeakRef<PROJECT_TREE_PANE> self( this );
2100
2101 m_branchQuery->Run(
2102 common,
2103 [branches]( KIGIT_COMMON& aCommon )
2104 {
2105 branches->entries = aCommon.GetBranches();
2106 branches->loaded = true;
2107 },
2108 [self, common, branches]()
2109 {
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 )
2114 {
2115 return;
2116 }
2117
2118 DIALOG_GIT_SWITCH dlg( wxGetTopLevelParent( self->m_Parent ), std::move( branches->entries ) );
2119 int retval = dlg.ShowModal();
2120
2121 if( !self || self->IsBeingDeleted() || common->IsShuttingDown() || self->gitCommon() != common )
2122 return;
2123
2124 if( retval == wxID_OK || retval == wxID_ADD )
2125 self->switchGitBranch( common, dlg.GetBranchName(), retval == wxID_ADD );
2126 } );
2127
2128 return;
2129 }
2130
2131 int branchIndex = aEvent.GetId() - ID_GIT_SWITCH_QUICK1;
2132
2133 if( m_gitMenuSession.lock() != common || branchIndex < 0
2134 || static_cast<size_t>( branchIndex ) >= m_gitMenuBranches.size() )
2135 {
2136 return;
2137 }
2138
2139 switchGitBranch( common, m_gitMenuBranches[branchIndex], false );
2140}
2141
2142
2143void PROJECT_TREE_PANE::switchGitBranch( std::shared_ptr<KIGIT_COMMON> aCommon, const wxString& aBranchName,
2144 bool aCreate )
2145{
2146 if( IsBeingDeleted() || m_Parent->IsBeingDeleted() || gitCommon() != aCommon || aCommon->IsShuttingDown()
2147 || !Pgm().GetCommonSettings()->m_Git.enableGit || Prj().GetLocalSettings().m_GitIntegrationDisabled )
2148 {
2149 return;
2150 }
2151
2152 if( !aCreate )
2153 {
2154 SwitchProjectToBranch( m_Parent, this, aBranchName, *m_branchQuery );
2155 return;
2156 }
2157
2158 if( wxString nameError = KIGIT::BranchNameError( aBranchName ); !nameError.IsEmpty() )
2159 {
2160 DisplayErrorMessage( this, nameError );
2161 return;
2162 }
2163
2164 // Keep Add subject to the same worktree checks before creating the branch. The shared
2165 // switch helper then owns confirmation, editor checks, checkout, and reload.
2166 auto createBranch = [this, aCommon, aBranchName]( const GIT_WORKTREE_STATUS& )
2167 {
2168 if( IsBeingDeleted() || m_Parent->IsBeingDeleted() || gitCommon() != aCommon || aCommon->IsShuttingDown()
2169 || !Pgm().GetCommonSettings()->m_Git.enableGit || Prj().GetLocalSettings().m_GitIntegrationDisabled )
2170 {
2171 return;
2172 }
2173
2174 int result;
2175 wxString error;
2176
2177 {
2178 std::unique_lock<std::mutex> lock = KIGIT::WaitForActionLock( *aCommon, this );
2179
2180 if( !lock.owns_lock() )
2181 return;
2182
2183 result = KIGIT::PROJECT_GIT_UTILS::CreateBranch( aCommon->GetRepo(), aBranchName );
2185 }
2186
2187 if( result != GIT_OK )
2188 {
2189 DisplayErrorMessage( this, _( "Could not create the branch." ), error );
2190 return;
2191 }
2192
2193 SwitchProjectToBranch( m_Parent, this, aBranchName, *m_branchQuery );
2194 aCommon->NotifyRefreshListeners();
2195 };
2196
2197 ProjectClearOfUncommittedWork( m_Parent, this, *m_branchQuery, std::move( createBranch ) );
2198}
2199
2200
2201void PROJECT_TREE_PANE::onGitRemoveVCS( wxCommandEvent& aEvent )
2202{
2203 PROJECT_LOCAL_SETTINGS& localSettings = Prj().GetLocalSettings();
2204
2205 // Toggle the Git integration disabled preference
2206 localSettings.m_GitIntegrationDisabled = !localSettings.m_GitIntegrationDisabled;
2207
2208 wxLogTrace( traceGit, wxS( "onGitRemoveVCS: Git integration %s" ),
2209 localSettings.m_GitIntegrationDisabled ? wxS( "disabled" ) : wxS( "enabled" ) );
2210
2211 if( localSettings.m_GitIntegrationDisabled )
2212 {
2213 // Disabling Git integration - release the repo and clear item states
2215 m_gitIconsInitialized = false;
2216
2217 // Clear all item states to remove git status icons
2218 std::stack<wxTreeItemId> items;
2219 items.push( m_TreeProject->GetRootItem() );
2220
2221 while( !items.empty() )
2222 {
2223 wxTreeItemId current = items.top();
2224 items.pop();
2225
2226 m_TreeProject->SetItemState( current, wxTREE_ITEMSTATE_NONE );
2227
2228 wxTreeItemIdValue cookie;
2229 wxTreeItemId child = m_TreeProject->GetFirstChild( current, cookie );
2230
2231 while( child.IsOk() )
2232 {
2233 items.push( child );
2234 child = m_TreeProject->GetNextChild( current, cookie );
2235 }
2236 }
2237 }
2238 else
2239 {
2240 // Re-enabling Git integration - try to find and connect to the repository
2242 }
2243
2244 // Save the preference to the project local settings file
2245 localSettings.SaveToFile( Prj().GetProjectPath() );
2246}
2247
2248
2250{
2251 wxLogTrace( traceGit, wxS( "updateGitStatusIcons: Updating git status icons" ) );
2252 std::unique_lock<std::mutex> lock( m_gitStatusMutex, std::try_to_lock );
2253
2254 if( !lock.owns_lock() )
2255 {
2256 wxLogTrace( traceGit, wxS( "updateGitStatusIcons: Failed to acquire lock for git status icon update" ) );
2257 m_gitStatusTimer.Start( 500, wxTIMER_ONE_SHOT );
2258 return;
2259 }
2260
2261 if( !Pgm().GetCommonSettings()->m_Git.enableGit || !m_TreeProject )
2262 {
2263 wxLogTrace( traceGit, wxS( "updateGitStatusIcons: Git is disabled or tree control is null" ) );
2264 return;
2265 }
2266
2267 std::stack<wxTreeItemId> items;
2268 items.push(m_TreeProject->GetRootItem());
2269
2270 while( !items.empty() )
2271 {
2272 wxTreeItemId current = items.top();
2273 items.pop();
2274
2275 if( current.IsOk() && m_TreeProject->ItemHasChildren( current ) )
2276 {
2277 wxTreeItemIdValue cookie;
2278 wxTreeItemId child = m_TreeProject->GetFirstChild( current, cookie );
2279
2280 while( child.IsOk() )
2281 {
2282 items.push( child );
2283
2284 if( auto it = m_gitStatusIcons.find( child ); it != m_gitStatusIcons.end() )
2285 m_TreeProject->SetItemState( child, static_cast<int>( it->second ) );
2286
2287 child = m_TreeProject->GetNextChild( current, cookie );
2288 }
2289 }
2290 }
2291
2292 if( !m_gitCurrentBranchName.empty() )
2293 {
2294 wxTreeItemId kid = m_TreeProject->GetRootItem();
2295 PROJECT_TREE_ITEM* rootItem = kid.IsOk() ? GetItemIdData( kid ) : nullptr;
2296
2297 if( rootItem )
2298 {
2299 wxString filename = wxFileNameFromPath( rootItem->GetFileName() );
2300 m_TreeProject->SetItemText( kid, filename + " [" + m_gitCurrentBranchName + "]" );
2301 }
2302 }
2303
2304 // Set even without a branch name, or each pass on an unborn HEAD notifies the panels and their
2305 // refresh restarts the status timer
2306 m_gitIconsInitialized = true;
2307
2308 wxLogTrace( traceGit, wxS( "updateGitStatusIcons: Git status icons updated" ) );
2309}
2310
2311
2313{
2314 wxLogTrace( traceGit, wxS( "updateTreeCache: Updating tree cache" ) );
2315
2316 std::unique_lock<std::mutex> lock( m_gitTreeCacheMutex, std::try_to_lock );
2317
2318 if( !lock.owns_lock() )
2319 {
2320 wxLogTrace( traceGit, wxS( "updateTreeCache: Failed to acquire lock for tree cache update" ) );
2321 return;
2322 }
2323
2324 if( !m_TreeProject )
2325 {
2326 wxLogTrace( traceGit, wxS( "updateTreeCache: Tree control is null" ) );
2327 return;
2328 }
2329
2330 wxTreeItemId kid = m_TreeProject->GetRootItem();
2331
2332 if( !kid.IsOk() )
2333 return;
2334
2335 // Collect a map to easily set the state of each item
2336 m_gitTreeCache.clear();
2337 std::stack<wxTreeItemId> items;
2338 items.push( kid );
2339
2340 while( !items.empty() )
2341 {
2342 kid = items.top();
2343 items.pop();
2344
2345 PROJECT_TREE_ITEM* nextItem = GetItemIdData( kid );
2346
2347 if( !nextItem )
2348 continue;
2349
2350 wxString gitAbsPath = nextItem->GetFileName();
2351#ifdef _WIN32
2352 gitAbsPath.Replace( wxS( "\\" ), wxS( "/" ) );
2353#endif
2354 m_gitTreeCache[gitAbsPath] = kid;
2355
2356 wxTreeItemIdValue cookie;
2357 wxTreeItemId child = m_TreeProject->GetFirstChild( kid, cookie );
2358
2359 while( child.IsOk() )
2360 {
2361 items.push( child );
2362 child = m_TreeProject->GetNextChild( kid, cookie );
2363 }
2364 }
2365}
2366
2367
2368void PROJECT_TREE_PANE::updateGitStatusIconMap( std::shared_ptr<KIGIT_COMMON> aGitCommon,
2369 const wxString& aProjectFullName )
2370{
2371 wxLogTrace( traceGit, wxS( "updateGitStatusIconMap: Updating git status icons" ) );
2372#if defined( _WIN32 )
2374
2375 if( refresh != 0 && KIPLATFORM::ENV::IsNetworkPath( wxPathOnly( aProjectFullName ) ) )
2376 {
2377 // Need to treat windows network paths special here until we get the samba bug fixed
2378 // https://github.com/wxWidgets/wxWidgets/issues/18953
2379 CallAfter(
2380 [this, refresh]()
2381 {
2382 m_gitStatusTimer.Start( refresh, wxTIMER_ONE_SHOT );
2383 } );
2384 }
2385
2386#endif
2387
2388 if( !Pgm().GetCommonSettings()->m_Git.enableGit || !m_TreeProject )
2389 return;
2390
2391 std::unique_lock<std::mutex> lock1( m_gitStatusMutex, std::try_to_lock );
2392 std::unique_lock<std::mutex> lock2( m_gitTreeCacheMutex, std::try_to_lock );
2393
2394 if( !lock1.owns_lock() || !lock2.owns_lock() )
2395 {
2396 wxLogTrace( traceGit, wxS( "updateGitStatusIconMap: Failed to acquire locks for git status icon update" ) );
2397 return;
2398 }
2399
2400 // The caller pinned the session on the UI thread, so a concurrent release cannot
2401 // free it under us.
2402 if( !aGitCommon || !aGitCommon->GetRepo() )
2403 {
2404 wxLogTrace( traceGit, wxS( "updateGitStatusIconMap: No git repository found" ) );
2405 return;
2406 }
2407
2408 // Acquire the git action mutex to synchronize with EmptyTreePrj() shutdown.
2409 // This ensures the repository isn't freed while we're using it.
2410 std::unique_lock<std::mutex> gitLock = aGitCommon->TryLockAction();
2411
2412 if( !gitLock.owns_lock() )
2413 {
2414 wxLogTrace( traceGit, wxS( "updateGitStatusIconMap: Failed to acquire git action mutex" ) );
2415 return;
2416 }
2417
2418 // Check if cancellation was requested (e.g., during shutdown)
2419 if( aGitCommon->IsShuttingDown() )
2420 {
2421 wxLogTrace( traceGit, wxS( "updateGitStatusIconMap: Cancelled" ) );
2422 return;
2423 }
2424
2425 GIT_STATUS_HANDLER statusHandler( aGitCommon.get() );
2426
2427 // Set up pathspec for project files. The name is passed in from the UI thread
2428 // because Prj() must not be read here, the project can be unloaded concurrently.
2429 wxFileName rootFilename( aProjectFullName );
2430 wxString repoWorkDir = statusHandler.GetWorkingDirectory();
2431
2432 wxFileName relative = rootFilename;
2433 relative.MakeRelativeTo( repoWorkDir );
2434 wxString pathspecStr = relative.GetPath( wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR );
2435
2436#ifdef _WIN32
2437 pathspecStr.Replace( wxS( "\\" ), wxS( "/" ) );
2438#endif
2439
2440 // Get file status
2441 auto fileStatusMap = statusHandler.GetFileStatus( pathspecStr );
2442 auto [localChanges, remoteChanges] = aGitCommon->GetDifferentFiles();
2443 statusHandler.UpdateRemoteStatus( localChanges, remoteChanges, fileStatusMap );
2444
2445 std::map<wxString, unsigned int> currentStatus;
2446
2447 for( const auto& [absPath, fileStatus] : fileStatusMap )
2448 currentStatus.emplace( absPath, fileStatus.gitStatus );
2449
2450 // A file deleted outside KiCad loses its tree item, so no icon changes to say so
2451 bool updated = currentStatus != m_gitLastStatus;
2452 m_gitLastStatus = std::move( currentStatus );
2453
2454 // Update status icons based on file status
2455 for( const auto& [absPath, fileStatus] : fileStatusMap )
2456 {
2457 auto iter = m_gitTreeCache.find( absPath );
2458 if( iter == m_gitTreeCache.end() )
2459 {
2460 wxLogTrace( traceGit, wxS( "File '%s' not found in tree cache" ), absPath );
2461 continue;
2462 }
2463
2464 auto [it, inserted] = m_gitStatusIcons.try_emplace( iter->second, fileStatus.status );
2465 if( inserted || it->second != fileStatus.status )
2466 updated = true;
2467 it->second = fileStatus.status;
2468 }
2469
2470 // Get the current branch name
2471 wxString branchName = statusHandler.GetCurrentBranchName();
2472
2473 if( branchName != m_gitCurrentBranchName )
2474 updated = true;
2475
2476 m_gitCurrentBranchName = branchName;
2477
2478 wxLogTrace( traceGit, wxS( "updateGitStatusIconMap: Updated git status icons" ) );
2479
2480 // Update UI if icons changed
2481 if( updated || !m_gitIconsInitialized )
2482 {
2483 CallAfter(
2484 [this, aGitCommon]()
2485 {
2487
2488 // The docked panels read the same status, so they are stale until they
2489 // are told. Without this a file edited outside KiCad shows as changed in
2490 // the tree while the panel still says there is nothing to commit.
2491 aGitCommon->NotifyRefreshListeners();
2492 } );
2493 }
2494}
2495
2496
2497void PROJECT_TREE_PANE::onRunSelectedJobsFile( wxCommandEvent& event )
2498{
2499}
2500
2501
2502void PROJECT_TREE_PANE::onGitSyncTimer( wxTimerEvent& aEvent )
2503{
2504 wxLogTrace( traceGit, "onGitSyncTimer" );
2505 COMMON_SETTINGS::GIT& gitSettings = Pgm().GetCommonSettings()->m_Git;
2506
2507 if( !gitSettings.enableGit || gitSettings.updatInterval <= 0 || !m_TreeProject )
2508 return;
2509
2510 // Skip the tick rather than stack a second fetch. Assigning over a running std::async
2511 // future blocks in its destructor, here on the UI thread.
2513 {
2514 wxLogTrace( traceGit, "onGitSyncTimer: previous fetch still running, skipping" );
2515 m_gitSyncTimer.Start( gitSettings.updatInterval * 60 * 1000, wxTIMER_ONE_SHOT );
2516 return;
2517 }
2518
2519 // Pin the session on the UI thread, so a concurrent release cannot free it while
2520 // PerformFetch() is inside it.
2521 std::shared_ptr<KIGIT_COMMON> common = gitCommon();
2522
2523 // Never the shared compute pool. A libgit2 network read parked there stalls DRC, zone
2524 // filling and library loading.
2525 m_gitSyncTask = std::async( std::launch::async,
2526 [this, common]()
2527 {
2528 if( !common->GetRepo() )
2529 {
2530 wxLogTrace( traceGit, "onGitSyncTimer: No git repository found" );
2531 return;
2532 }
2533
2534 // Check if cancellation was requested (e.g., during shutdown)
2535 if( common->IsShuttingDown() )
2536 {
2537 wxLogTrace( traceGit, "onGitSyncTimer: Cancelled" );
2538 return;
2539 }
2540
2541 GIT_PULL_HANDLER handler( common.get() );
2542 bool fetched = handler.PerformFetch();
2543 std::optional<KIGIT_FAILURE> kind = handler.GetFailureKind();
2544 wxString summary = handler.PopError().summary;
2545
2546 // Only schedule the follow-up work if not cancelled
2547 if( !common->IsShuttingDown() )
2548 CallAfter(
2549 [this, common, fetched, kind, summary]()
2550 {
2551 // The project may have closed or changed while queued
2552 if( common->IsShuttingDown() || common != gitCommon() )
2553 return;
2554
2555 reportGitSyncResult( fetched, kind, summary );
2557
2558 // The panels show whether the remote is ahead, and the fetch
2559 // just moved the remote refs.
2560 common->NotifyRefreshListeners();
2561 } );
2562 } );
2563
2564 wxLogTrace( traceGit, "onGitSyncTimer: Restarting git sync timer" );
2565 // We store the timer interval in minutes but wxTimer uses milliseconds
2566 m_gitSyncTimer.Start( gitSettings.updatInterval * 60 * 1000, wxTIMER_ONE_SHOT );
2567}
2568
2569
2570void PROJECT_TREE_PANE::reportGitSyncResult( bool aFetched, std::optional<KIGIT_FAILURE> aKind,
2571 const wxString& aSummary )
2572{
2573 KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( m_Parent->GetStatusBar() );
2574
2575 if( aFetched )
2576 {
2578 return;
2579 }
2580
2581 // A busy repository or a closing project is not something to warn about
2582 if( !statusBar || !aKind || *aKind == KIGIT_FAILURE::CANCELLED )
2583 return;
2584
2585 // The timer fires every few minutes, and the same failure each time would bury every other warning. The list
2586 // itself is the record, so anything that clears it lets the next failure show again
2587 std::map<wxString, std::vector<KI_ERROR>> shown = statusBar->GetWarningMessages();
2588
2589 for( const KI_ERROR& existing : shown[KIGIT::SYNC_WARNING_SOURCE] )
2590 {
2591 if( existing.GetTitle() == aSummary )
2592 return;
2593 }
2594
2595 KI_ERROR warning;
2596 warning.SetTitle( aSummary );
2598 statusBar->AddWarningMessages( KIGIT::SYNC_WARNING_SOURCE, { warning } );
2599}
2600
2601
2603{
2604 if( !m_TreeProject )
2605 return;
2606
2607 // Pin the session on the UI thread, so a concurrent release cannot free it while
2608 // the status worker is using it.
2609 std::shared_ptr<KIGIT_COMMON> common = gitCommon();
2610
2611 if( common->IsShuttingDown() )
2612 return;
2613
2614 // See onGitSyncTimer: overwriting a still-running task's future abandons a task that holds
2615 // a raw pointer to this pane, and the destructor would no longer wait for it.
2617 return;
2618
2621
2622 wxString projectFullName = Prj().GetProjectFullName();
2623
2624 m_gitStatusIconTask = tp.submit_task(
2625 [this, common, projectFullName]()
2626 {
2627 updateGitStatusIconMap( common, projectFullName );
2628 } );
2629}
2630
2631void PROJECT_TREE_PANE::onGitStatusTimer( wxTimerEvent& aEvent )
2632{
2633 wxLogTrace( traceGit, "onGitStatusTimer" );
2634
2635 if( !Pgm().GetCommonSettings()->m_Git.enableGit || !m_TreeProject )
2636 return;
2637
2639}
const char * name
wxBitmap KiBitmap(BITMAPS aBitmap, int aHeightTag)
Construct a wxBitmap from an image identifier Returns the image from the active theme if the image ha...
Definition bitmap.cpp:100
BITMAP_STORE * GetBitmapStore()
Definition bitmap.cpp:88
@ directory_browser
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.
void SetUsername(const wxString &aUsername)
void SetSkipButtonLabel(const wxString &aLabel)
wxString GetBranchName() const
int ShowModal() override
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.
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.
Definition kistatusbar.h:50
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.
Definition ki_error.h:38
KI_ERROR & SetSeverity(SEVERITY aSeverity)
Definition ki_error.h:76
KI_ERROR & SetTitle(const wxString &aTitle)
Definition ki_error.h:58
static wxString GetDefaultUserProjectsPath()
Gets the default path we point users to create projects.
Definition paths.cpp:137
virtual COMMON_SETTINGS * GetCommonSettings() const
Definition pgm_base.cpp:569
virtual const wxString & GetTextEditor(bool aCanShowFileChooser=true)
Return the path to the preferred text editor application.
Definition pgm_base.cpp:240
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.
Handle one item (a file or a directory name) for the tree file.
void SetRootFile(bool aValue)
void SetState(int state)
const wxString & GetFileName() const
bool IsPopulated() 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 ...
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.
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.
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.
Definition project.h:63
virtual std::shared_ptr< KIGIT_COMMON > GetGitCommon() const
This project's Git session, created empty on first use.
Definition project.cpp:85
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition project.cpp:271
virtual bool AttachGitRepository()
Find the Git repository containing the project directory and bind it to the session.
Definition project.cpp:94
virtual PROJECT_LOCAL_SETTINGS & GetLocalSettings() const
Definition project.h:207
virtual void ReleaseGitCommon()
Safely release the session's repository handle and drop the session.
Definition project.cpp:166
A scoped application of a wxLog target.
void DisplayInfoMessage(wxWindow *aParent, const wxString &aMessage, const wxString &aExtraInfo)
Display an informational message box with aMessage.
Definition confirm.cpp:245
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
This file is part of the common library.
#define _(s)
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.
Definition gestfich.cpp:170
GIT_BACKEND * GetGitBackend()
InitResult
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.
PROJECT & Prj()
Definition kicad.cpp:743
@ ID_PROJECT_TREE
Definition kicad_id.h:32
@ ID_LEFT_FRAME
Definition kicad_id.h:31
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 ...
Definition macros.h:79
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.
bool IsNetworkPath(const wxString &aPath)
Determines if a given path is a network shared file apth On Windows for example, any form of path is ...
bool IsFileHidden(const wxString &aFileName)
Helper function to determine the status of the 'Hidden' file attribute.
Definition unix/io.cpp:109
void StoreSecretAsync(const wxString &aService, const wxString &aKey, const wxString &aSecret, std::function< void(bool)> aDone=nullptr)
Like StoreSecret(), but never blocks the event loop while the platform asks the user to unlock the st...
void GetSecretAsync(const wxString &aService, const wxString &aKey, std::function< void(bool, const wxString &)> aDone)
Like GetSecret(), but never blocks the event loop while the platform asks the user to unlock the stor...
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.
Definition kicad_algo.h:96
STL namespace.
PGM_BASE & Pgm()
The global program "get" accessor.
#define NAMELESS_PROJECT
default name for nameless projects
Definition project.h:40
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_OPEN_DIR
@ ID_JOBS_RUN
@ ID_PROJECT_SWITCH_TO_OTHER
@ ID_PROJECT_NEWDIR
@ ID_PROJECT_RENAME
@ ID_GIT_SWITCH_QUICK5
@ ID_GIT_REMOVE_VCS
@ ID_PROJECT_TXTEDIT
@ ID_GIT_SWITCH_QUICK2
@ ID_GIT_SWITCH_QUICK4
@ ID_GIT_SWITCH_QUICK3
@ ID_GIT_SWITCH_BRANCH
@ ID_GIT_HISTORY
@ ID_GIT_SWITCH_QUICK1
@ ID_GIT_INITIALIZE_PROJECT
@ ID_PROJECT_DELETE
@ ID_GIT_REMOTE_SETTINGS
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[]
@ RPT_SEVERITY_WARNING
#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))
std::string path
wxString result
Test unit parsing edge cases and error handling.
thread_pool & GetKiCadThreadPool()
Get a reference to the current thread pool.
static thread_pool * tp
BS::priority_thread_pool thread_pool
Definition thread_pool.h:27
wxLogTrace helper definitions.
TREE_FILE_TYPE
static PIECE rect(double aLeft, double aTop, double aRight, double aBottom, bool aMixed=false)
Definition of file extensions used in Kicad.
#define PR_NO_ABORT