KiCad PCB EDA Suite
Loading...
Searching...
No Matches
dialog_template_selector.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 Brian Sidebotham <[email protected]>
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
22#include <bitmaps.h>
23#include <core/kicad_algo.h>
25#include <kiplatform/ui.h>
27#include <pgm_base.h>
31#include <widgets/ui_common.h>
32#include <algorithm>
33#include <wx_filename.h>
34#include <wx/dir.h>
35#include <wx/dirdlg.h>
36#include <wx/settings.h>
37#include <wx/bitmap.h>
38#include <wx/image.h>
39#include <wx/math.h>
40#include <wx/menu.h>
41#include <wx/textdlg.h>
42#include <wx/textfile.h>
43#include <wx/regex.h>
44#include <confirm.h>
47
48
49static const wxChar* traceTemplateSelector = wxT( "KICAD_TEMPLATE_SELECTOR" );
50
51static constexpr int ID_TOGGLE_PINNED = wxID_HIGHEST + 1;
52
53
55 m_dialog( aDialog )
56{
57 if( m_dialog->m_refreshPauseCount++ == 0 && m_dialog->m_refreshTimer.IsRunning() )
58 {
59 m_dialog->m_refreshTimer.Stop();
60 m_dialog->m_refreshPending = true;
61 }
62}
63
64
66{
67 wxASSERT( m_dialog->m_refreshPauseCount > 0 );
68
69 if( --m_dialog->m_refreshPauseCount == 0 && m_dialog->m_refreshPending )
70 {
71 m_dialog->m_refreshPending = false;
72 m_dialog->m_refreshTimer.StartOnce( 500 );
73 }
74}
75
76
78 const wxString& aPath, const wxString& aTitle,
79 const wxBitmap& aIcon ) :
80 wxPanel( aParent, wxID_ANY ),
81 m_dialog( aDialog ),
82 m_templatePath( aPath )
83{
84 SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE ) );
85
86 wxBoxSizer* sizer = new wxBoxSizer( wxHORIZONTAL );
87
88 wxStaticBitmap* icon = new wxStaticBitmap( this, wxID_ANY, aIcon );
89 icon->SetMinSize( FromDIP( wxSize( 16, 16 ) ) );
90 sizer->Add( icon, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxTOP | wxBOTTOM, 6 );
91
92 wxStaticText* label = new wxStaticText( this, wxID_ANY, aTitle );
93 label->SetFont( KIUI::GetInfoFont( this ) );
94 sizer->Add( label, 1, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT | wxTOP | wxBOTTOM, 6 );
95
96 SetSizer( sizer );
97 Layout();
98
99 Bind( wxEVT_LEFT_DOWN, &TEMPLATE_MRU_WIDGET::OnClick, this );
100 Bind( wxEVT_LEFT_DCLICK, &TEMPLATE_MRU_WIDGET::OnDoubleClick, this );
101 Bind( wxEVT_ENTER_WINDOW, &TEMPLATE_MRU_WIDGET::OnEnter, this );
102 Bind( wxEVT_LEAVE_WINDOW, &TEMPLATE_MRU_WIDGET::OnLeave, this );
103
104 icon->Bind( wxEVT_LEFT_DOWN, &TEMPLATE_MRU_WIDGET::OnClick, this );
105 icon->Bind( wxEVT_LEFT_DCLICK, &TEMPLATE_MRU_WIDGET::OnDoubleClick, this );
106 label->Bind( wxEVT_LEFT_DOWN, &TEMPLATE_MRU_WIDGET::OnClick, this );
107 label->Bind( wxEVT_LEFT_DCLICK, &TEMPLATE_MRU_WIDGET::OnDoubleClick, this );
108}
109
110
111void TEMPLATE_MRU_WIDGET::OnClick( wxMouseEvent& event )
112{
113 // Just select the template in the list without showing the preview pane
114 m_dialog->SelectTemplateByPath( m_templatePath, true );
115 event.Skip();
116}
117
118
119void TEMPLATE_MRU_WIDGET::OnDoubleClick( wxMouseEvent& event )
120{
121 m_dialog->SelectTemplateByPath( m_templatePath );
122 m_dialog->EndModal( wxID_OK );
123 event.Skip();
124}
125
126
127void TEMPLATE_MRU_WIDGET::OnEnter( wxMouseEvent& event )
128{
129 SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHT ).ChangeLightness( 150 ) );
130 Refresh();
131 event.Skip();
132}
133
134
135void TEMPLATE_MRU_WIDGET::OnLeave( wxMouseEvent& event )
136{
137 SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE ) );
138 Refresh();
139 event.Skip();
140}
141
142
144 TEMPLATE_WIDGET_BASE( aParent )
145{
146 m_parent = aParent;
147 m_dialog = aDialog;
148 m_pinned = false;
149 m_category = CATEGORY::SYSTEM;
150
151 // Set a small minimum size to allow the dialog to shrink
152 // The actual size will be determined by the parent sizer
153 SetMinSize( FromDIP( wxSize( 200, -1 ) ) );
154
155 m_bitmapIcon->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( TEMPLATE_WIDGET::OnMouse ), nullptr, this );
156 m_titleLabel->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( TEMPLATE_WIDGET::OnMouse ), nullptr, this );
157 m_descLabel->Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( TEMPLATE_WIDGET::OnMouse ), nullptr, this );
158
159 Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( TEMPLATE_WIDGET::OnMouse ), nullptr, this );
160
161 m_bitmapIcon->Connect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( TEMPLATE_WIDGET::onRightClick ), nullptr, this );
162 m_titleLabel->Connect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( TEMPLATE_WIDGET::onRightClick ), nullptr, this );
163 m_descLabel->Connect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( TEMPLATE_WIDGET::onRightClick ), nullptr, this );
164 Connect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( TEMPLATE_WIDGET::onRightClick ), nullptr, this );
165
166 m_bitmapIcon->Connect( wxEVT_LEFT_DCLICK, wxMouseEventHandler( TEMPLATE_WIDGET::OnDoubleClick ), nullptr, this );
167 m_titleLabel->Connect( wxEVT_LEFT_DCLICK, wxMouseEventHandler( TEMPLATE_WIDGET::OnDoubleClick ), nullptr, this );
168 m_descLabel->Connect( wxEVT_LEFT_DCLICK, wxMouseEventHandler( TEMPLATE_WIDGET::OnDoubleClick ), nullptr, this );
169 Connect( wxEVT_LEFT_DCLICK, wxMouseEventHandler( TEMPLATE_WIDGET::OnDoubleClick ), nullptr, this );
170
171 // Set description text to use a smaller font
172 m_descLabel->SetFont( KIUI::GetInfoFont( this ) );
173
174#if wxCHECK_VERSION( 3, 3, 2 )
175 m_descLabel->SetWindowStyle( wxST_WRAP );
176#endif
177
178 // Bind size event for dynamic text wrapping
179 Bind( wxEVT_SIZE, &TEMPLATE_WIDGET::OnSize, this );
180
181 Unselect();
182
183 m_currTemplate = nullptr;
184}
185
186
188{
189 m_dialog->SetWidget( this );
190 SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHT ) );
191 m_titleLabel->SetForegroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHTTEXT ) );
192 m_descLabel->SetForegroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHTTEXT ) );
193 m_selected = true;
194 Refresh();
195}
196
197
199{
200 SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHT ) );
201 m_titleLabel->SetForegroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHTTEXT ) );
202 m_descLabel->SetForegroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHTTEXT ) );
203 m_selected = true;
204 Refresh();
205}
206
207
209{
210 SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE ) );
211 m_titleLabel->SetForegroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNTEXT ) );
212 m_descLabel->SetForegroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNTEXT ) );
213 m_selected = false;
214 Refresh();
215}
216
217
219{
220 m_currTemplate = aTemplate;
221 m_titleLabel->SetFont( KIUI::GetInfoFont( this ).Bold() );
222 m_titleLabel->SetLabel( *aTemplate->GetTitle() );
223
224 // Generate bitmap bundle from template icon bitmap (64x64)
225 // so wxStaticBitmap can size itself to the closest match
226 const std::vector<int> c_bitmapSizes = { 48, 64, 96, 128 };
227
228 wxBitmapBundle bundle;
229 wxVector<wxBitmap> bitmaps;
230 wxBitmap* icon = aTemplate->GetIcon();
231
232 if( icon && icon->IsOk() )
233 bundle = *icon;
234 else
235 bundle = KiBitmapBundleDef( BITMAPS::icon_kicad, c_bitmapSizes[0] );
236
237 wxSize defSize = bundle.GetDefaultSize();
238
239 for( const int genSize : c_bitmapSizes )
240 {
241 double scale = std::min( (double) genSize / defSize.GetWidth(),
242 (double) genSize / defSize.GetHeight() );
243
244 wxSize scaledSize( wxRound( defSize.x * scale ),
245 wxRound( defSize.y * scale ) );
246
247 wxBitmap scaled = bundle.GetBitmap( scaledSize );
248 scaled.SetScaleFactor( 1.0 );
249
250 bitmaps.push_back( scaled );
251 }
252
253 m_bitmapIcon->SetBitmap( wxBitmapBundle::FromBitmaps( bitmaps ) );
254}
255
256
258{
259 if( !m_currTemplate )
260 return wxEmptyString;
261
262 wxFileName htmlFile = m_currTemplate->GetHtmlFile();
263 htmlFile.RemoveLastDir();
264 return htmlFile.GetPath();
265}
266
267
268void TEMPLATE_WIDGET::SetPinned( bool aPinned )
269{
270 m_pinned = aPinned;
271
272 if( !m_currTemplate )
273 return;
274
275 const wxString& title = *m_currTemplate->GetTitle();
276 m_titleLabel->SetLabel( aPinned ? LIB_TREE_MODEL_ADAPTER::GetPinningSymbol() + title : title );
277}
278
279
280void TEMPLATE_WIDGET::SetDescription( const wxString& aDescription )
281{
282 m_description = aDescription;
283
284 // Truncate long descriptions to approximately 3 lines worth
285 wxString displayDesc = aDescription;
286
287 if( displayDesc.Length() > 120 )
288 displayDesc = displayDesc.Left( 120 ) + wxS( "..." );
289
290 m_descLabel->SetLabel( displayDesc );
291}
292
293
294void TEMPLATE_WIDGET::OnSize( wxSizeEvent& event )
295{
296 event.Skip();
297
298 // wx 3.3.2+ can wrap automatically
299#if !wxCHECK_VERSION( 3, 3, 2 )
300 // Calculate available width for description text (widget width minus icon and padding)
301 int wrapWidth = GetClientSize().GetWidth() - 48 - 20; // 48px icon + 20px padding
302
303 if( wrapWidth > 100 )
304 {
305 // Recalculate the truncated description from the original stored description
306 // to avoid cumulative wrapping artifacts
307 wxString displayDesc = m_description;
308
309 if( displayDesc.Length() > 120 )
310 displayDesc = displayDesc.Left( 120 ) + wxS( "..." );
311
312 m_descLabel->SetLabel( displayDesc );
313 m_descLabel->Wrap( wrapWidth );
314 Layout();
315 }
316#endif
317}
318
319
320void TEMPLATE_WIDGET::OnMouse( wxMouseEvent& event )
321{
322 Select();
323 event.Skip();
324}
325
326
327void TEMPLATE_WIDGET::OnDoubleClick( wxMouseEvent& event )
328{
329 Select();
330 m_dialog->EndModal( wxID_OK );
331 event.Skip();
332}
333
334
335void TEMPLATE_WIDGET::onRightClick( wxMouseEvent& event )
336{
337 if( !m_currTemplate )
338 {
339 event.Skip();
340 return;
341 }
342
343 // A refresh fired from the popup's nested event loop would destroy this widget under the menu
345
346 wxMenu menu;
347 menu.Append( wxID_EDIT,
348 m_category == CATEGORY::USER ? _( "Edit Template" ) : _( "Open Template (Read-Only)" ) );
349 menu.Append( wxID_OPEN, _( "Open Template Folder" ) );
350 menu.Append( wxID_COPY, _( "Duplicate Template" ) );
351 menu.AppendSeparator();
352 menu.Append( ID_TOGGLE_PINNED, m_pinned ? _( "Unpin Template" ) : _( "Pin Template" ) );
353
354 menu.Bind( wxEVT_COMMAND_MENU_SELECTED,
355 [this]( wxCommandEvent& evt )
356 {
357 if( evt.GetId() == wxID_EDIT )
358 onEditTemplate( evt );
359 else if( evt.GetId() == wxID_OPEN )
360 onOpenFolder( evt );
361 else if( evt.GetId() == wxID_COPY )
362 onDuplicateTemplate( evt );
363 else if( evt.GetId() == ID_TOGGLE_PINNED )
364 onTogglePinned( evt );
365 } );
366
367 PopupMenu( &menu );
368}
369
370
371void TEMPLATE_WIDGET::onTogglePinned( wxCommandEvent& event )
372{
373 if( m_currTemplate )
374 m_dialog->SetTemplatePinned( GetTemplatePath(), !m_pinned );
375}
376
377
378void TEMPLATE_WIDGET::onEditTemplate( wxCommandEvent& event )
379{
380 if( !m_currTemplate )
381 return;
382
383 wxFileName templatePath = m_currTemplate->GetHtmlFile();
384 templatePath.RemoveLastDir();
385
386 wxDir dir( templatePath.GetPath() );
387
388 if( !dir.IsOpened() )
389 {
390 DisplayErrorMessage( m_dialog, _( "Could not open template directory." ) );
391 return;
392 }
393
394 wxString filename;
395 bool found = dir.GetFirst( &filename, "*.kicad_pro", wxDIR_FILES );
396
397 if( !found )
398 {
399 DisplayErrorMessage( m_dialog, _( "No project file found in template directory." ) );
400 return;
401 }
402
403 wxFileName projectFile( templatePath.GetPath(), filename );
404
405 m_dialog->SetProjectToEdit( projectFile.GetFullPath() );
406
407 m_dialog->EndModal( wxID_APPLY );
408}
409
410
411void TEMPLATE_WIDGET::onOpenFolder( wxCommandEvent& event )
412{
413 if( !m_currTemplate )
414 return;
415
416 wxFileName templatePath = m_currTemplate->GetHtmlFile();
417 templatePath.RemoveLastDir();
418
419 if( !wxLaunchDefaultApplication( templatePath.GetPath() ) )
420 DisplayError( this, wxString::Format( _( "Failed to open '%s'." ), templatePath.GetPath() ) );
421}
422
423
424void TEMPLATE_WIDGET::onDuplicateTemplate( wxCommandEvent& event )
425{
426 if( !m_currTemplate )
427 return;
428
429 wxFileName templatePath = m_currTemplate->GetHtmlFile();
430 templatePath.RemoveLastDir();
431 wxString srcTemplatePath = templatePath.GetPath();
432 wxString srcTemplateName = m_currTemplate->GetPrjDirName();
434
435 wxTextEntryDialog nameDlg( m_dialog, _( "Enter name for the new template:" ), _( "Duplicate Template" ),
436 srcTemplateName + _( "_copy" ) );
437
438 if( nameDlg.ShowModal() != wxID_OK )
439 return;
440
441 wxString newTemplateName = nameDlg.GetValue();
442
443 if( newTemplateName.IsEmpty() )
444 {
445 DisplayErrorMessage( m_dialog, _( "Template name cannot be empty." ) );
446 return;
447 }
448
449 wxString userTemplatesPath = m_dialog->GetUserTemplatesPath();
450
451 if( userTemplatesPath.IsEmpty() )
452 {
453 DisplayErrorMessage( m_dialog, _( "Could not find user templates directory." ) );
454 return;
455 }
456
457 wxFileName destPath( userTemplatesPath, wxEmptyString );
458 destPath.AppendDir( newTemplateName );
459 wxString newTemplatePath = destPath.GetPath();
460
461 if( destPath.DirExists() )
462 {
463 DisplayErrorMessage( m_dialog, wxString::Format( _( "Directory '%s' already exists." ), newTemplatePath ) );
464 return;
465 }
466
467 if( !destPath.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
468 {
469 DisplayErrorMessage( m_dialog, wxString::Format( _( "Could not create directory '%s'." ), newTemplatePath ) );
470 return;
471 }
472
473 wxDir sourceDir( srcTemplatePath );
474
475 if( !sourceDir.IsOpened() )
476 {
477 DisplayErrorMessage( m_dialog, _( "Could not open source template directory." ) );
478 return;
479 }
480
481 PROJECT_TREE_TRAVERSER traverser( nullptr, srcTemplatePath, srcTemplateName, newTemplatePath, newTemplateName );
482
483 sourceDir.Traverse( traverser );
484
485 if( !traverser.GetErrors().empty() )
486 {
487 DisplayErrorMessage( m_dialog, traverser.GetErrors() );
488 return;
489 }
490
491 wxFileName metaHtmlFile( newTemplatePath, "info.html" );
492 metaHtmlFile.AppendDir( "meta" );
493
494 if( metaHtmlFile.FileExists() )
495 {
496 wxTextFile htmlFile( metaHtmlFile.GetFullPath() );
497
498 if( htmlFile.Open() )
499 {
500 bool modified = false;
501
502 for( size_t i = 0; i < htmlFile.GetLineCount(); i++ )
503 {
504 wxString line = htmlFile.GetLine( i );
505
506 if( line.Contains( wxT( "<title>" ) ) && line.Contains( wxT( "</title>" ) ) )
507 {
508 int titleStart = line.Find( wxT( "<title>" ) );
509 int titleEnd = line.Find( wxT( "</title>" ) );
510
511 if( titleStart != wxNOT_FOUND && titleEnd != wxNOT_FOUND && titleEnd > titleStart )
512 {
513 wxString before = line.Left( titleStart + 7 );
514 wxString after = line.Mid( titleEnd );
515 line = before + newTemplateName + after;
516 htmlFile[i] = line;
517 modified = true;
518 }
519 }
520 }
521
522 if( modified )
523 htmlFile.Write();
524
525 htmlFile.Close();
526 }
527 }
528
529 // The file copy triggers OnFileSystemEvent which starts a refresh timer. If we show a
530 // modal info dialog here, the timer fires during the modal event loop and destroys this
531 // TEMPLATE_WIDGET while we're still on its call stack. Defer both the message and the
532 // refresh to run after the current event handler returns.
534
535 dlg->CallAfter(
536 [dlg, newTemplatePath]()
537 {
538 DisplayInfoMessage( dlg, wxString::Format( _( "Template duplicated successfully to '%s'." ),
539 newTemplatePath ) );
540 dlg->RefreshTemplateList();
541 } );
542}
543
544
545DIALOG_TEMPLATE_SELECTOR::DIALOG_TEMPLATE_SELECTOR( wxWindow* aParent, const wxPoint& aPos,
546 const wxSize& aSize, const wxString& aUserTemplatesPath,
547 const wxString& aSystemTemplatesPath,
548 const wxString& aDefaultTemplatesPath,
549 const std::vector<wxString>& aRecentTemplates,
550 const wxString& aBrowsedTemplatesPath ) :
551 DIALOG_TEMPLATE_SELECTOR_BASE( aParent, wxID_ANY, _( "Project Template Selector" ), aPos, aSize ),
553 m_selectedWidget( nullptr ),
554 m_selectedTemplate( nullptr ),
555 m_userTemplatesPath( aUserTemplatesPath ),
556 m_systemTemplatesPath( aSystemTemplatesPath ),
557 m_defaultTemplatesPath( aDefaultTemplatesPath ),
558 m_browsedTemplatesPath( aBrowsedTemplatesPath ),
559 m_recentTemplates( aRecentTemplates ),
560 m_searchTimer( this ),
561 m_refreshTimer( this ),
563 m_refreshPending( false ),
564 m_watcher( nullptr ),
565 m_webviewPanel( nullptr ),
566 m_loadingExternalHtml( false ),
568{
569 // Validate the persisted browsed path: drop it silently if the directory
570 // no longer exists so the dialog never points at a stale location.
571 if( !m_browsedTemplatesPath.IsEmpty() && !wxDirExists( m_browsedTemplatesPath ) )
573 // The base class now provides the UI structure via wxFormBuilder.
574 // Configure the scrolled windows.
575 m_scrolledMRU->SetScrollRate( 0, 25 );
576 m_scrolledTemplates->SetScrollRate( 0, 25 );
577 m_scrolledTemplates->SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE ) );
578
579 m_scrolledTemplates->SetMinSize( FromDIP( wxSize( 200, 200 ) ) );
580
581 // Configure the search control
582 m_searchCtrl->ShowSearchButton( true );
583 m_searchCtrl->ShowCancelButton( true );
584
585 // The browsed-path label shrinks below its text width and ellipsizes, using the smaller
586 // info font; neither is expressible in the form so they are applied to the base widget here.
587 m_browsedPathLabel->SetFont( KIUI::GetInfoFont( this ) );
588 m_browsedPathLabel->SetMinSize( wxSize( 0, -1 ) );
589
590 Bind( wxEVT_TIMER, &DIALOG_TEMPLATE_SELECTOR::OnSearchTimer, this, m_searchTimer.GetId() );
591 Bind( wxEVT_TIMER, &DIALOG_TEMPLATE_SELECTOR::OnRefreshTimer, this, m_refreshTimer.GetId() );
592 Bind( wxEVT_FSWATCHER, &DIALOG_TEMPLATE_SELECTOR::OnFileSystemEvent, this );
593 Bind( wxEVT_SYS_COLOUR_CHANGED, &DIALOG_TEMPLATE_SELECTOR::OnSysColourChanged, this );
595
596 // Set initial filter based on saved setting
598
599 if( settings )
600 {
601 // Pins of deleted or moved templates would otherwise linger in the settings forever
602 for( const wxString& path : settings->m_PinnedTemplates )
603 {
604 if( wxDirExists( path ) && !alg::contains( m_pinnedTemplates, path ) )
605 m_pinnedTemplates.push_back( path );
606 }
607
609
610 int filterChoice = settings->m_TemplateFilterChoice;
611
612 if( filterChoice >= 0 && filterChoice < static_cast<int>( m_filterChoice->GetCount() ) )
613 m_filterChoice->SetSelection( filterChoice );
614 else
615 m_filterChoice->SetSelection( 0 );
616 }
617 else
618 {
619 m_filterChoice->SetSelection( 0 );
620 }
621
622 // If the persisted browsed path was discarded (directory missing) avoid landing on the
623 // now-empty "Other Templates" filter.
624 if( m_browsedTemplatesPath.IsEmpty() && m_filterChoice->GetSelection() == 3 )
625 m_filterChoice->SetSelection( 0 );
626
628 BuildMRUList();
631
632 // Auto-select the most recently used template if available
633 if( !m_recentTemplates.empty() )
635
637
638 m_sdbSizerOK->SetDefault();
639
641}
642
643
645{
646 m_searchTimer.Stop();
647 m_refreshTimer.Stop();
648
649 if( m_watcher )
650 {
651 m_watcher->RemoveAll();
652 m_watcher->SetOwner( nullptr );
653 delete m_watcher;
654 m_watcher = nullptr;
655 }
656}
657
658
660{
661 if( m_splitter->IsSplit() )
662 return;
663
664 int sashPos = m_previewSashPos;
665
666 // Fall back to a third of the available width the first time the preview is shown
667 if( sashPos <= 0 )
668 {
669 int width = m_splitter->GetClientSize().GetWidth();
670 sashPos = width > 0 ? width / 3 : FromDIP( 300 );
671 }
672
673 m_splitter->SplitVertically( m_panelTemplates, m_panelPreview, sashPos );
674}
675
676
678{
679 m_state = aState;
680
681 switch( aState )
682 {
684 m_panelMRU->Show();
685 m_btnBack->Enable( false );
686
687 if( m_splitter->IsSplit() )
688 {
689 // Remember the sash so reselecting a template restores the user's layout
690 m_previewSashPos = m_splitter->GetSashPosition();
691 m_splitter->Unsplit( m_panelPreview );
692 }
693
694 break;
695
697 m_panelMRU->Hide();
698 m_btnBack->Enable( true );
700 break;
701
703 m_panelMRU->Show();
704 m_btnBack->Enable( true );
706 break;
707 }
708
709 Layout();
710}
711
712
714{
715 // Clear existing MRU widgets
716 for( TEMPLATE_MRU_WIDGET* widget : m_mruWidgets )
717 {
718 m_sizerMRU->Detach( widget );
719 widget->Destroy();
720 }
721
722 m_mruWidgets.clear();
723
724 for( const wxString& path : m_recentTemplates )
725 {
726 wxFileName templateDir;
727 templateDir.AssignDir( path );
728
729 if( !templateDir.DirExists() )
730 continue;
731
732 PROJECT_TEMPLATE templ( path );
733
734 wxString* title = templ.GetTitle();
735 wxBitmap* icon = templ.GetIcon();
736
737 wxBitmap scaledIcon;
738
739 if( icon && icon->IsOk() )
740 {
741 wxImage img = icon->ConvertToImage();
742 img.Rescale( 16, 16, wxIMAGE_QUALITY_HIGH );
743 scaledIcon = wxBitmap( img );
744 }
745 else
746 {
747 scaledIcon = KiBitmap( BITMAPS::icon_kicad );
748 wxImage img = scaledIcon.ConvertToImage();
749 img.Rescale( 16, 16, wxIMAGE_QUALITY_HIGH );
750 scaledIcon = wxBitmap( img );
751 }
752
753 wxString displayTitle = title ? *title : templateDir.GetDirs().Last();
754
755 TEMPLATE_MRU_WIDGET* mruWidget = new TEMPLATE_MRU_WIDGET( m_scrolledMRU, this, path, displayTitle,
756 scaledIcon );
757 m_sizerMRU->Add( mruWidget, 0, wxEXPAND | wxBOTTOM, 2 );
758 m_mruWidgets.push_back( mruWidget );
759 }
760
761 m_scrolledMRU->FitInside();
762 m_scrolledMRU->Layout();
763 m_panelMRU->Layout();
764}
765
766
768{
769 wxLogTrace( traceTemplateSelector, "BuildTemplateList() called" );
770
771 // Clear existing template widgets
772 for( TEMPLATE_WIDGET* widget : m_templateWidgets )
773 {
774 m_sizerTemplateList->Detach( widget );
775 widget->Destroy();
776 }
777
778 m_templateWidgets.clear();
779 m_templates.clear();
780
781 auto scanDirectory =
782 [this]( const wxString& aPath, TEMPLATE_WIDGET::CATEGORY aCategory )
783 {
784 if( aPath.IsEmpty() )
785 return;
786
787 wxDir dir;
788
789 if( !dir.Open( aPath ) )
790 return;
791
792 wxLogTrace( traceTemplateSelector, "Scanning directory: %s (category=%d)", aPath,
793 static_cast<int>( aCategory ) );
794
795 if( dir.HasSubDirs( "meta" ) )
796 {
797 auto templ = std::make_unique<PROJECT_TEMPLATE>( aPath );
798 wxFileName htmlFile = templ->GetHtmlFile();
799 wxString description = ExtractDescription( htmlFile );
800
802 widget->SetTemplate( templ.get() );
803 widget->SetDescription( description );
804 widget->SetCategory( aCategory );
805
806 m_templates.push_back( std::move( templ ) );
807 m_templateWidgets.push_back( widget );
808 }
809 else
810 {
811 wxString subName;
812 bool cont = dir.GetFirst( &subName, wxEmptyString, wxDIR_DIRS );
813
814 while( cont )
815 {
816 wxString subFull = aPath + wxFileName::GetPathSeparator() + subName;
817
818 // Only treat subdirectories that contain a meta directory as templates.
819 // Directories without meta (e.g. regular project directories the user
820 // placed in the template path) are silently skipped.
821 wxFileName metaTest;
822 metaTest.AssignDir( subFull );
823 metaTest.AppendDir( METADIR );
824
825 if( metaTest.DirExists() )
826 {
827 auto templ = std::make_unique<PROJECT_TEMPLATE>( subFull );
828 wxFileName htmlFile = templ->GetHtmlFile();
829 wxString description = templ->GetError().IsEmpty() ? ExtractDescription( htmlFile ) : templ->GetError();
830
831 TEMPLATE_WIDGET* widget =
833 widget->SetTemplate( templ.get() );
834 widget->SetDescription( description );
835 widget->SetCategory( aCategory );
836
837 m_templates.push_back( std::move( templ ) );
838 m_templateWidgets.push_back( widget );
839 }
840
841 cont = dir.GetNext( &subName );
842 }
843 }
844 };
845
846 scanDirectory( m_userTemplatesPath, TEMPLATE_WIDGET::CATEGORY::USER );
847 scanDirectory( m_systemTemplatesPath, TEMPLATE_WIDGET::CATEGORY::SYSTEM );
848
850 scanDirectory( m_browsedTemplatesPath, TEMPLATE_WIDGET::CATEGORY::BROWSED );
851
852 // The built-in "default" template lives in the stable default user templates path. It is
853 // always scanned so that the default remains available even when KICAD_USER_TEMPLATE_DIR
854 // points at a custom location. Treated as a built-in, not a user template.
855 scanDirectory( m_defaultTemplatesPath, TEMPLATE_WIDGET::CATEGORY::SYSTEM );
856
857 for( TEMPLATE_WIDGET* widget : m_templateWidgets )
858 widget->SetPinned( IsTemplatePinned( widget->GetTemplatePath() ) );
859
861
862 // Force initial sizing of widgets after layout
863 CallAfter(
864 [this]()
865 {
866 wxSizeEvent evt( m_scrolledTemplates->GetSize() );
868 } );
869
870 wxLogTrace( traceTemplateSelector, "BuildTemplateList() found %zu templates", m_templateWidgets.size() );
871}
872
873
875{
876 std::sort( m_templateWidgets.begin(), m_templateWidgets.end(),
878 {
879 return TemplateListLess( *a->GetTemplate()->GetTitle(), a->IsPinned(),
880 *b->GetTemplate()->GetTitle(), b->IsPinned() );
881 } );
882
883 m_sizerTemplateList->Clear( false );
884
885 for( TEMPLATE_WIDGET* widget : m_templateWidgets )
886 m_sizerTemplateList->Add( widget, 0, wxEXPAND | wxBOTTOM, 8 );
887
888 ApplyFilter();
889}
890
891
892bool DIALOG_TEMPLATE_SELECTOR::IsTemplatePinned( const wxString& aPath ) const
893{
894 return alg::contains( m_pinnedTemplates, aPath );
895}
896
897
898void DIALOG_TEMPLATE_SELECTOR::SetTemplatePinned( const wxString& aPath, bool aPinned )
899{
900 if( aPath.IsEmpty() || aPinned == IsTemplatePinned( aPath ) )
901 return;
902
903 if( aPinned )
904 m_pinnedTemplates.push_back( aPath );
905 else
906 m_pinnedTemplates.erase( std::remove( m_pinnedTemplates.begin(), m_pinnedTemplates.end(), aPath ),
907 m_pinnedTemplates.end() );
908
909 if( KICAD_SETTINGS* settings = Pgm().GetSettingsManager().GetAppSettings<KICAD_SETTINGS>( "kicad" ) )
910 settings->m_PinnedTemplates = m_pinnedTemplates;
911
912 // A browsed directory can list the same template a second time
913 for( TEMPLATE_WIDGET* widget : m_templateWidgets )
914 {
915 if( widget->GetTemplatePath() == aPath )
916 widget->SetPinned( aPinned );
917 }
918
920}
921
922
924{
925 int filterChoice = m_filterChoice->GetSelection();
926 wxString searchText = m_searchCtrl->GetValue().Lower();
927
928 for( TEMPLATE_WIDGET* widget : m_templateWidgets )
929 {
930 bool matchesFilter = true;
931 TEMPLATE_WIDGET::CATEGORY cat = widget->GetCategory();
932
933 // 0 = All, 1 = User, 2 = System, 3 = Browsed / Other
934 if( filterChoice == 1 && cat != TEMPLATE_WIDGET::CATEGORY::USER )
935 matchesFilter = false;
936 else if( filterChoice == 2 && cat != TEMPLATE_WIDGET::CATEGORY::SYSTEM )
937 matchesFilter = false;
938 else if( filterChoice == 3 && cat != TEMPLATE_WIDGET::CATEGORY::BROWSED )
939 matchesFilter = false;
940
941 bool matchesSearch = true;
942
943 if( !searchText.IsEmpty() )
944 {
945 wxString title = widget->GetTemplate()->GetTitle()->Lower();
946 wxString description = widget->GetDescription().Lower();
947
948 matchesSearch = title.Contains( searchText ) || description.Contains( searchText );
949 }
950
951 widget->Show( matchesFilter && matchesSearch );
952 }
953
954 m_scrolledTemplates->FitInside();
955 m_scrolledTemplates->Layout();
956 Layout();
957}
958
959
960void DIALOG_TEMPLATE_SELECTOR::OnSearchCtrl( wxCommandEvent& event )
961{
962 m_searchTimer.Stop();
963 m_searchTimer.StartOnce( 200 );
964}
965
966
968{
969 m_searchCtrl->Clear();
970 ApplyFilter();
971}
972
973
974void DIALOG_TEMPLATE_SELECTOR::OnFilterChanged( wxCommandEvent& event )
975{
977
978 if( settings )
979 settings->m_TemplateFilterChoice = m_filterChoice->GetSelection();
980
981 ApplyFilter();
982}
983
984
986{
987 ApplyFilter();
988}
989
990
992{
993 if( m_refreshPauseCount > 0 )
994 {
995 m_refreshPending = true;
996 return;
997 }
998
1000}
1001
1002
1003void DIALOG_TEMPLATE_SELECTOR::OnBackClicked( wxCommandEvent& event )
1004{
1005 if( m_selectedWidget )
1006 m_selectedWidget->Unselect();
1007
1008 m_selectedWidget = nullptr;
1009 m_selectedTemplate = nullptr;
1010
1013}
1014
1015
1017{
1018 if( m_selectedWidget != nullptr && m_selectedWidget != aWidget )
1019 m_selectedWidget->Unselect();
1020
1021 m_selectedWidget = aWidget;
1022 m_selectedTemplate = aWidget ? aWidget->GetTemplate() : nullptr;
1023
1025
1026 if( m_selectedTemplate )
1028}
1029
1030
1032{
1033 SelectTemplateByPath( aPath, false );
1034}
1035
1036
1037void DIALOG_TEMPLATE_SELECTOR::SelectTemplateByPath( const wxString& aPath, bool aKeepMRUVisible )
1038{
1039 for( TEMPLATE_WIDGET* widget : m_templateWidgets )
1040 {
1041 if( widget->GetTemplate() )
1042 {
1043 wxFileName htmlFile = widget->GetTemplate()->GetHtmlFile();
1044 htmlFile.RemoveLastDir();
1045
1046 if( htmlFile.GetPath() == aPath )
1047 {
1048 if( aKeepMRUVisible )
1049 {
1050 // Select the widget but keep MRU visible, don't show preview
1051 if( m_selectedWidget != nullptr && m_selectedWidget != widget )
1052 m_selectedWidget->Unselect();
1053
1054 m_selectedWidget = widget;
1055 m_selectedTemplate = widget->GetTemplate();
1056
1057 widget->SelectWithoutStateChange();
1058
1059 // Scroll the widget into view
1060 int y = 0;
1061 int scrollRate = 0;
1062 widget->GetPosition( nullptr, &y );
1063 m_scrolledTemplates->GetScrollPixelsPerUnit( nullptr, &scrollRate );
1064
1065 if( scrollRate > 0 )
1066 m_scrolledTemplates->Scroll( -1, y / scrollRate );
1067 }
1068 else
1069 {
1070 widget->Select();
1071 }
1072
1073 return;
1074 }
1075 }
1076 }
1077
1078 wxLogTrace( traceTemplateSelector, "SelectTemplateByPath: template not found at %s", aPath );
1079}
1080
1081
1083{
1084 if( m_webviewPanel )
1085 return;
1086
1087 // Create the WEBVIEW_PANEL lazily to avoid WebKit JavaScript VM initialization issues
1088 // when the dialog is opened from a coroutine context.
1089 m_webviewPanel = new WEBVIEW_PANEL( m_webviewPlaceholder, wxID_ANY, wxDefaultPosition, wxDefaultSize,
1090 wxTAB_TRAVERSAL );
1091
1092 wxBoxSizer* sizer = new wxBoxSizer( wxVERTICAL );
1093 sizer->Add( m_webviewPanel, 1, wxEXPAND );
1094 m_webviewPlaceholder->SetSizer( sizer );
1095 m_webviewPlaceholder->Layout();
1096
1097 m_webviewPanel->BindLoadedEvent();
1098
1099 if( m_webviewPanel->GetWebView() )
1100 {
1101 Bind( wxEVT_WEBVIEW_LOADED, &DIALOG_TEMPLATE_SELECTOR::OnWebViewLoaded, this,
1102 m_webviewPanel->GetWebView()->GetId() );
1103 }
1104}
1105
1106
1108{
1109 if( !aTemplate )
1110 return;
1111
1113
1114 wxFileName htmlFile = aTemplate->GetHtmlFile();
1115
1116 if( htmlFile.FileExists() && htmlFile.IsFileReadable() )
1117 {
1118 m_loadingExternalHtml = true;
1119 wxString url = wxFileName::FileNameToURL( htmlFile );
1120 m_webviewPanel->LoadURL( url );
1121 }
1122 else
1123 {
1124 m_loadingExternalHtml = false;
1125 wxString html = GetTemplateInfoHtml( *aTemplate->GetTitle(), KIPLATFORM::UI::IsDarkTheme() );
1126 m_webviewPanel->SetPage( html );
1127 }
1128}
1129
1130
1137
1138
1140{
1141 if( m_watcher )
1142 {
1143 m_watcher->RemoveAll();
1144 delete m_watcher;
1145 m_watcher = nullptr;
1146 }
1147
1149 m_watcher->SetOwner( this );
1150
1151 wxLogNull logNo;
1152
1153 auto watchDir =
1154 [this]( const wxString& aPath, const char* aLabel )
1155 {
1156 if( aPath.IsEmpty() )
1157 return;
1158
1159 wxFileName dir;
1160 dir.AssignDir( aPath );
1161
1162 // wxMSW frees a watch before SMB completes its pending read, which then corrupts the heap
1163 if( KIPLATFORM::ENV::IsNetworkPath( dir.GetPath() ) )
1164 {
1165 wxLogTrace( traceTemplateSelector, "Network path, not watching %s templates: %s", aLabel,
1166 aPath );
1167 return;
1168 }
1169
1170 if( dir.DirExists() )
1171 {
1172 m_watcher->Add( dir );
1173 wxLogTrace( traceTemplateSelector, "Watching %s templates: %s", aLabel, aPath );
1174 }
1175 };
1176
1177 watchDir( m_userTemplatesPath, "user" );
1178 watchDir( m_systemTemplatesPath, "system" );
1179 watchDir( m_defaultTemplatesPath, "default" );
1180
1181 if( !browsedPathIsDuplicate() )
1182 watchDir( m_browsedTemplatesPath, "browsed" );
1183}
1184
1185
1187{
1188 if( m_browsedTemplatesPath.IsEmpty() )
1189 return true;
1190
1191 auto sameDir =
1192 []( const wxString& a, const wxString& b )
1193 {
1194 if( a.IsEmpty() || b.IsEmpty() )
1195 return false;
1196
1197 wxFileName lhs;
1198 lhs.AssignDir( a );
1199 lhs.Normalize( FN_NORMALIZE_FLAGS | wxPATH_NORM_ENV_VARS );
1200
1201 wxFileName rhs;
1202 rhs.AssignDir( b );
1203 rhs.Normalize( FN_NORMALIZE_FLAGS | wxPATH_NORM_ENV_VARS );
1204
1205 return lhs.SameAs( rhs );
1206 };
1207
1210}
1211
1212
1213void DIALOG_TEMPLATE_SELECTOR::OnFileSystemEvent( wxFileSystemWatcherEvent& event )
1214{
1215 if( !m_watcher )
1216 return;
1217
1218 wxLogTrace( traceTemplateSelector, "File system event detected" );
1219
1220 // wxFileSystemWatcher may fire events from a worker thread on some platforms.
1221 // Use CallAfter to marshal timer operations to the main thread.
1222 CallAfter(
1223 [this]()
1224 {
1225 if( m_refreshPauseCount > 0 )
1226 {
1227 m_refreshPending = true;
1228 return;
1229 }
1230
1231 m_refreshTimer.Stop();
1232 m_refreshTimer.StartOnce( 500 );
1233 } );
1234}
1235
1236
1237void DIALOG_TEMPLATE_SELECTOR::OnSysColourChanged( wxSysColourChangedEvent& event )
1238{
1239 event.Skip();
1240
1241 // Update background colors for the templates panel
1242 m_scrolledTemplates->SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE ) );
1243
1244 // Update all template widgets
1245 for( TEMPLATE_WIDGET* widget : m_templateWidgets )
1246 {
1247 if( widget->IsSelected() )
1248 widget->SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_HIGHLIGHT ) );
1249 else
1250 widget->SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE ) );
1251
1252 widget->Refresh();
1253 }
1254
1255 // Update all MRU widgets
1256 for( TEMPLATE_MRU_WIDGET* widget : m_mruWidgets )
1257 {
1258 widget->SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE ) );
1259 widget->Refresh();
1260 }
1261
1262 m_scrolledTemplates->Refresh();
1263 m_scrolledMRU->Refresh();
1264}
1265
1266
1268{
1269 event.Skip();
1270
1271 // Get the client width of the scrolled window
1272 int clientWidth = m_scrolledTemplates->GetClientSize().GetWidth();
1273
1274 if( clientWidth <= 0 )
1275 return;
1276
1277 // Force each widget to rewrap its text at the new width
1278 for( TEMPLATE_WIDGET* widget : m_templateWidgets )
1279 {
1280 wxSizeEvent sizeEvt( wxSize( clientWidth, -1 ) );
1281 widget->GetEventHandler()->ProcessEvent( sizeEvt );
1282 }
1283
1284 m_scrolledTemplates->FitInside();
1285}
1286
1287
1289{
1290 event.Skip();
1291
1292 // Safety check - ensure webview panel is valid
1293 if( !m_webviewPanel || !m_webviewPanel->GetWebView() )
1294 return;
1295
1296 // Add style to external documets
1298 {
1299 wxString script = wxString::Format( wxS( R"(
1300( function()
1301{
1302 var style = document.createElement( 'style' );
1303 style.textContent = `
1304%s
1305 `;
1306 document.head.appendChild( style );
1307} )();
1308 )" ), GetCommonStyles() );
1309
1310#if !defined( __MINGW32__ ) // RunScriptAsync() is not supported on MINGW build
1311 if( m_webviewPanel->GetBackend() != wxWebViewBackendIE )
1312 m_webviewPanel->RunScriptAsync( script );
1313#endif
1314 }
1315}
1316
1317
1319{
1320 wxString selectedPath;
1321
1322 if( m_selectedWidget && m_selectedWidget->GetTemplate() )
1323 {
1324 wxFileName htmlFile = m_selectedWidget->GetTemplate()->GetHtmlFile();
1325 htmlFile.RemoveLastDir();
1326 selectedPath = htmlFile.GetPath();
1327 }
1328
1329 // Clear pointers before destroying widgets to avoid dangling pointers
1330 m_selectedWidget = nullptr;
1331 m_selectedTemplate = nullptr;
1332
1334
1335 if( !selectedPath.IsEmpty() )
1336 SelectTemplateByPath( selectedPath );
1337}
1338
1339
1340wxString DIALOG_TEMPLATE_SELECTOR::ExtractDescription( const wxFileName& aHtmlFile )
1341{
1342 if( !aHtmlFile.FileExists() || !aHtmlFile.IsFileReadable() )
1343 return wxEmptyString;
1344
1345 wxTextFile file( aHtmlFile.GetFullPath() );
1346
1347 if( !file.Open() )
1348 return wxEmptyString;
1349
1350 wxString content;
1351
1352 for( wxString line = file.GetFirstLine(); !file.Eof(); line = file.GetNextLine() )
1353 {
1354 content += line + wxT( " " );
1355 }
1356
1357 file.Close();
1358
1359 // Try to extract text from the meta description tag
1360 wxRegEx reMetaDesc( wxT( "<meta[^>]*name=[\"']description[\"'][^>]*content=[\"']([^\"']*)[\"']" ),
1361 wxRE_ICASE );
1362
1363 if( reMetaDesc.Matches( content ) )
1364 return reMetaDesc.GetMatch( content, 1 );
1365
1366 // Fallback to first paragraph tag (allowing nested HTML tags)
1367 wxRegEx reParagraph( wxT( "<p[^>]*>(.*?)</p>" ), wxRE_ICASE );
1368
1369 if( reParagraph.Matches( content ) )
1370 {
1371 wxString desc = reParagraph.GetMatch( content, 1 );
1372
1373 // Strip nested HTML tags
1374 wxRegEx reTags( wxT( "<[^>]*>" ) );
1375 reTags.ReplaceAll( &desc, wxT( " " ) );
1376
1377 // Decode common HTML entities
1378 desc.Replace( wxT( "&nbsp;" ), wxT( " " ) );
1379 desc.Replace( wxT( "&amp;" ), wxT( "&" ) );
1380 desc.Replace( wxT( "&lt;" ), wxT( "<" ) );
1381 desc.Replace( wxT( "&gt;" ), wxT( ">" ) );
1382 desc.Replace( wxT( "&quot;" ), wxT( "\"" ) );
1383
1384 // Normalize whitespace
1385 wxRegEx reWhitespace( wxT( "\\s+" ) );
1386 reWhitespace.ReplaceAll( &desc, wxT( " " ) );
1387
1388 desc = desc.Trim().Trim( false );
1389
1390 if( !desc.IsEmpty() )
1391 return desc;
1392 }
1393
1394 // Final fallback: extract text content from body, stripping all HTML tags
1395 wxRegEx reBody( wxT( "<body[^>]*>(.*)</body>" ), wxRE_ICASE );
1396
1397 if( reBody.Matches( content ) )
1398 {
1399 wxString body = reBody.GetMatch( content, 1 );
1400
1401 // Strip all HTML tags
1402 wxRegEx reTags( wxT( "<[^>]*>" ) );
1403 reTags.ReplaceAll( &body, wxT( " " ) );
1404
1405 // Decode common HTML entities
1406 body.Replace( wxT( "&nbsp;" ), wxT( " " ) );
1407 body.Replace( wxT( "&amp;" ), wxT( "&" ) );
1408 body.Replace( wxT( "&lt;" ), wxT( "<" ) );
1409 body.Replace( wxT( "&gt;" ), wxT( ">" ) );
1410 body.Replace( wxT( "&quot;" ), wxT( "\"" ) );
1411
1412 // Normalize whitespace
1413 wxRegEx reWhitespace( wxT( "\\s+" ) );
1414 reWhitespace.ReplaceAll( &body, wxT( " " ) );
1415
1416 body = body.Trim().Trim( false );
1417
1418 // Return up to 250 characters
1419 if( body.Length() > 250 )
1420 return body.Left( 250 ) + wxS( "..." );
1421
1422 return body;
1423 }
1424
1425 return wxEmptyString;
1426}
1427
1428
1433
1434
1435void DIALOG_TEMPLATE_SELECTOR::onBrowseClicked( wxCommandEvent& aEvent )
1436{
1437 wxString startPath = m_browsedTemplatesPath;
1438
1439 if( startPath.IsEmpty() )
1440 startPath = m_userTemplatesPath;
1441
1442 wxDirDialog dirDialog( this, _( "Select Templates Directory" ), startPath,
1443 wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST );
1444
1445 if( dirDialog.ShowModal() != wxID_OK )
1446 return;
1447
1448 wxFileName dirName = wxFileName::DirName( dirDialog.GetPath() );
1449 dirName.Normalize( FN_NORMALIZE_FLAGS | wxPATH_NORM_ENV_VARS );
1450 m_browsedTemplatesPath = dirName.GetFullPath();
1451
1453
1454 // Make sure the user can actually see the templates that just got pulled in by
1455 // jumping to the Other Templates category whenever the filter is currently set
1456 // to something that would hide them.
1457 int filterChoice = m_filterChoice->GetSelection();
1458
1459 if( filterChoice != 0 && filterChoice != 3 )
1460 m_filterChoice->SetSelection( 3 );
1461
1464}
1465
1466
1468{
1469 if( m_browsedTemplatesPath.IsEmpty() )
1470 return;
1471
1472 m_browsedTemplatesPath.clear();
1474
1475 // If we were filtered to Other Templates, drop back to All so the list isn't empty.
1476 if( m_filterChoice->GetSelection() == 3 )
1477 m_filterChoice->SetSelection( 0 );
1478
1481}
1482
1483
1485{
1486 if( !m_browsedPathLabel )
1487 return;
1488
1489 if( m_browsedTemplatesPath.IsEmpty() )
1490 m_browsedPathLabel->SetLabel( _( "(no other directory)" ) );
1491 else
1493
1495 m_clearBrowseButton->Enable( !m_browsedTemplatesPath.IsEmpty() );
1496
1497 if( wxSizer* parentSizer = m_browsedPathLabel->GetContainingSizer() )
1498 parentSizer->Layout();
1499}
wxBitmapBundle KiBitmapBundleDef(BITMAPS aBitmap, int aDefHeight)
Construct and return a bitmap bundle for the given icon ID, with the default bitmap size being aDefHe...
Definition bitmap.cpp:112
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
void finishDialogSettings()
In all dialogs, we must call the same functions to fix minimal dlg size, the default position and per...
REFRESH_GUARD(DIALOG_TEMPLATE_SELECTOR *aDialog)
DIALOG_TEMPLATE_SELECTOR_BASE(wxWindow *parent, wxWindowID id=wxID_ANY, const wxString &title=_("Project Template Selector"), const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxSize(900, 600), long style=wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER)
wxString ExtractDescription(const wxFileName &aHtmlFile)
void SetState(DialogState aState)
void SelectTemplateByPath(const wxString &aPath)
void OnBackClicked(wxCommandEvent &event) override
void LoadTemplatePreview(PROJECT_TEMPLATE *aTemplate)
void OnSearchCtrl(wxCommandEvent &event) override
bool IsTemplatePinned(const wxString &aPath) const
void OnFileSystemEvent(wxFileSystemWatcherEvent &event)
void onClearBrowsedClicked(wxCommandEvent &aEvent) override
bool browsedPathIsDuplicate() const
Returns true if the browsed path is empty or duplicates one of the standard template directories (aft...
void OnSearchCtrlCancel(wxCommandEvent &event) override
void OnWebViewLoaded(wxWebViewEvent &event)
void OnFilterChanged(wxCommandEvent &event) override
void onBrowseClicked(wxCommandEvent &aEvent) override
void SetTemplatePinned(const wxString &aPath, bool aPinned)
std::vector< TEMPLATE_WIDGET * > m_templateWidgets
void OnRefreshTimer(wxTimerEvent &event)
void OnScrolledTemplatesSize(wxSizeEvent &event)
void SetWidget(TEMPLATE_WIDGET *aWidget)
std::vector< TEMPLATE_MRU_WIDGET * > m_mruWidgets
void OnSysColourChanged(wxSysColourChangedEvent &event)
void OnSearchTimer(wxTimerEvent &event)
DIALOG_TEMPLATE_SELECTOR(wxWindow *aParent, const wxPoint &aPos, const wxSize &aSize, const wxString &aUserTemplatesPath, const wxString &aSystemTemplatesPath, const wxString &aDefaultTemplatesPath, const std::vector< wxString > &aRecentTemplates, const wxString &aBrowsedTemplatesPath=wxEmptyString)
std::vector< wxString > m_pinnedTemplates
std::vector< std::unique_ptr< PROJECT_TEMPLATE > > m_templates
std::vector< wxString > m_recentTemplates
std::vector< wxString > m_PinnedTemplates
static const wxString GetPinningSymbol()
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:124
A class which provides project template functionality.
wxBitmap * GetIcon()
Get the 64px^2 icon for the project template.
wxFileName GetHtmlFile()
Get the full Html filename for the project template.
wxString * GetTitle()
Get the title of the project (extracted from the html title tag)
Traverser class to duplicate/copy project or template files with proper renaming.
T * GetAppSettings(const char *aFilename)
Return a handle to the a given settings by type.
A widget displaying a recently used template with a small icon and title.
DIALOG_TEMPLATE_SELECTOR * m_dialog
void OnEnter(wxMouseEvent &event)
TEMPLATE_MRU_WIDGET(wxWindow *aParent, DIALOG_TEMPLATE_SELECTOR *aDialog, const wxString &aPath, const wxString &aTitle, const wxBitmap &aIcon)
void OnLeave(wxMouseEvent &event)
void OnClick(wxMouseEvent &event)
void OnDoubleClick(wxMouseEvent &event)
TEMPLATE_WIDGET_BASE(wxWindow *parent, wxWindowID id=wxID_ANY, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxSize(-1,-1), long style=wxBORDER_THEME|wxTAB_TRAVERSAL, const wxString &name=wxEmptyString)
PROJECT_TEMPLATE * GetTemplate()
void OnMouse(wxMouseEvent &event)
void onOpenFolder(wxCommandEvent &event)
void SetCategory(CATEGORY aCategory)
void SetPinned(bool aPinned)
void SetTemplate(PROJECT_TEMPLATE *aTemplate)
Set the project template for this widget, which will determine the icon and title associated with thi...
void onTogglePinned(wxCommandEvent &event)
DIALOG_TEMPLATE_SELECTOR * m_dialog
void SetDescription(const wxString &aDescription)
void OnSize(wxSizeEvent &event)
void onEditTemplate(wxCommandEvent &event)
void OnDoubleClick(wxMouseEvent &event)
void onDuplicateTemplate(wxCommandEvent &event)
void onRightClick(wxMouseEvent &event)
wxString GetTemplatePath() const
The template directory, the identity used for recent and pinned templates.
TEMPLATE_WIDGET(wxWindow *aParent, DIALOG_TEMPLATE_SELECTOR *aDialog)
PROJECT_TEMPLATE * m_currTemplate
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
void DisplayError(wxWindow *aParent, const wxString &aText)
Display an error or warning message box with aMessage.
Definition confirm.cpp:192
This file is part of the common library.
static const wxChar * traceTemplateSelector
static constexpr int ID_TOGGLE_PINNED
#define _(s)
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 IsDarkTheme()
Determine if the desktop interface is currently using a dark theme or a light theme.
Definition wxgtk/ui.cpp:57
KICOMMON_API wxFont GetInfoFont(wxWindow *aWindow)
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:96
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
#define METADIR
A directory which contains information about the project template and does not get copied.
#define wxFileSystemWatcher
T * GetAppSettings(const char *aFilename)
const int scale
wxString GetWelcomeHtml(bool aDarkMode)
wxString GetTemplateInfoHtml(const wxString &aTemplateName, bool aDarkMode)
std::string path
Functions to provide common constants and other functions to assist in making a consistent UI.
#define FN_NORMALIZE_FLAGS
Default flags to pass to wxFileName::Normalize().
Definition wx_filename.h:35