File: eda_base_frame.cpp

package info (click to toggle)
kicad 9.0.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 770,320 kB
  • sloc: cpp: 961,692; ansic: 121,001; xml: 66,428; python: 18,387; sh: 1,010; awk: 301; asm: 292; makefile: 227; javascript: 167; perl: 10
file content (1650 lines) | stat: -rw-r--r-- 49,964 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
/*
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 2017 Jean-Pierre Charras, jp.charras at wanadoo.fr
 * Copyright (C) 2013 Wayne Stambaugh <stambaughw@gmail.com>
 * Copyright (C) 2023 CERN (www.cern.ch)
 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

#include "kicad_manager_frame.h"
#include <eda_base_frame.h>

#include <advanced_config.h>
#include <bitmaps.h>
#include <bitmap_store.h>
#include <dialog_shim.h>
#include <dialogs/git/panel_git_repos.h>
#include <dialogs/panel_common_settings.h>
#include <dialogs/panel_mouse_settings.h>
#include <dialogs/panel_data_collection.h>
#include <dialogs/panel_plugin_settings.h>
#include <eda_dde.h>
#include <file_history.h>
#include <id.h>
#include <kiface_base.h>
#include <hotkeys_basic.h>
#include <panel_hotkeys_editor.h>
#include <paths.h>
#include <confirm.h>
#include <panel_packages_and_updates.h>
#include <pgm_base.h>
#include <settings/app_settings.h>
#include <settings/common_settings.h>
#include <settings/settings_manager.h>
#include <project/project_local_settings.h>
#include <tool/action_manager.h>
#include <tool/action_menu.h>
#include <tool/action_toolbar.h>
#include <tool/actions.h>
#include <tool/common_control.h>
#include <tool/tool_manager.h>
#include <tool/tool_dispatcher.h>
#include <trace_helpers.h>
#include <widgets/paged_dialog.h>
#include <widgets/wx_busy_indicator.h>
#include <widgets/wx_infobar.h>
#include <widgets/wx_aui_art_providers.h>
#include <widgets/wx_grid.h>
#include <widgets/wx_treebook.h>
#include <wx/app.h>
#include <wx/config.h>
#include <wx/display.h>
#include <wx/stdpaths.h>
#include <wx/string.h>
#include <wx/msgdlg.h>
#include <kiplatform/app.h>
#include <kiplatform/io.h>
#include <kiplatform/ui.h>

#include <functional>
#include <kiface_ids.h>

#ifdef KICAD_IPC_API
#include <api/api_server.h>
#endif


// Minimum window size
static const wxSize minSizeLookup( FRAME_T aFrameType, wxWindow* aWindow )
{
    switch( aFrameType )
    {
    case KICAD_MAIN_FRAME_T:
        return wxWindow::FromDIP( wxSize( 406, 354 ), aWindow );

    default:
        return wxWindow::FromDIP( wxSize( 500, 400 ), aWindow );
    }
}


static const wxSize defaultSize( FRAME_T aFrameType, wxWindow* aWindow )
{
    switch( aFrameType )
    {
    case KICAD_MAIN_FRAME_T:
        return wxWindow::FromDIP( wxSize( 850, 540 ), aWindow );

    default:
        return wxWindow::FromDIP( wxSize( 1280, 720 ), aWindow );
    }
}


BEGIN_EVENT_TABLE( EDA_BASE_FRAME, wxFrame )
    // These event table entries are needed to handle events from the mac application menu
    EVT_MENU( wxID_ABOUT, EDA_BASE_FRAME::OnKicadAbout )
    EVT_MENU( wxID_PREFERENCES, EDA_BASE_FRAME::OnPreferences )

    EVT_CHAR_HOOK( EDA_BASE_FRAME::OnCharHook )
    EVT_MENU_OPEN( EDA_BASE_FRAME::OnMenuEvent )
    EVT_MENU_CLOSE( EDA_BASE_FRAME::OnMenuEvent )
    EVT_MENU_HIGHLIGHT_ALL( EDA_BASE_FRAME::OnMenuEvent )
    EVT_MOVE( EDA_BASE_FRAME::OnMove )
    EVT_SIZE( EDA_BASE_FRAME::OnSize )
    EVT_MAXIMIZE( EDA_BASE_FRAME::OnMaximize )

    EVT_SYS_COLOUR_CHANGED( EDA_BASE_FRAME::onSystemColorChange )
    EVT_ICONIZE( EDA_BASE_FRAME::onIconize )
END_EVENT_TABLE()


void EDA_BASE_FRAME::commonInit( FRAME_T aFrameType )
{
    m_ident             = aFrameType;
    m_maximizeByDefault = false;
    m_infoBar           = nullptr;
    m_settingsManager   = nullptr;
    m_fileHistory       = nullptr;
    m_supportsAutoSave  = false;
    m_autoSavePending   = false;
    m_undoRedoCountMax  = DEFAULT_MAX_UNDO_ITEMS;
    m_isClosing         = false;
    m_isNonUserClose    = false;
    m_autoSaveTimer     = new wxTimer( this, ID_AUTO_SAVE_TIMER );
    m_autoSaveRequired  = false;
    m_mruPath           = PATHS::GetDefaultUserProjectsPath();
    m_frameSize         = defaultSize( aFrameType, this );
    m_displayIndex      = -1;

    m_auimgr.SetArtProvider( new WX_AUI_DOCK_ART() );

    m_settingsManager = &Pgm().GetSettingsManager();

    // Set a reasonable minimal size for the frame
    wxSize minSize = minSizeLookup( aFrameType, this );
    SetSizeHints( minSize.x, minSize.y, -1, -1, -1, -1 );

    // Store dimensions of the user area of the main window.
    GetClientSize( &m_frameSize.x, &m_frameSize.y );

    Connect( ID_AUTO_SAVE_TIMER, wxEVT_TIMER,
             wxTimerEventHandler( EDA_BASE_FRAME::onAutoSaveTimer ) );

    // hook wxEVT_CLOSE_WINDOW so we can call SaveSettings().  This function seems
    // to be called before any other hook for wxCloseEvent, which is necessary.
    Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( EDA_BASE_FRAME::windowClosing ) );

    initExitKey();
}


EDA_BASE_FRAME::EDA_BASE_FRAME( wxWindow* aParent, FRAME_T aFrameType, const wxString& aTitle,
                                const wxPoint& aPos, const wxSize& aSize, long aStyle,
                                const wxString& aFrameName, KIWAY* aKiway,
                                const EDA_IU_SCALE& aIuScale ) :
        wxFrame( aParent, wxID_ANY, aTitle, aPos, aSize, aStyle, aFrameName ),
        TOOLS_HOLDER(),
        KIWAY_HOLDER( aKiway, KIWAY_HOLDER::FRAME ),
        UNITS_PROVIDER( aIuScale, EDA_UNITS::MM )
{
    commonInit( aFrameType );
}


wxWindow* findQuasiModalDialog( wxWindow* aParent )
{
    for( wxWindow* child : aParent->GetChildren() )
    {
        if( DIALOG_SHIM* dlg = dynamic_cast<DIALOG_SHIM*>( child ) )
        {
            if( dlg->IsQuasiModal() )
                return dlg;

            if( wxWindow* nestedDlg = findQuasiModalDialog( child ) )
                return nestedDlg;
        }
    }

    return nullptr;
}


wxWindow* EDA_BASE_FRAME::findQuasiModalDialog()
{
    if( wxWindow* dlg = ::findQuasiModalDialog( this ) )
        return dlg;

    // FIXME: CvPcb is currently implemented on top of KIWAY_PLAYER rather than DIALOG_SHIM,
    // so we have to look for it separately.
    if( m_ident == FRAME_SCH )
    {
        wxWindow* cvpcb = wxWindow::FindWindowByName( wxS( "CvpcbFrame" ) );

        if( cvpcb )
            return cvpcb;
    }

    return nullptr;
}


void EDA_BASE_FRAME::windowClosing( wxCloseEvent& event )
{
    // Don't allow closing when a quasi-modal is open.
    wxWindow* quasiModal = findQuasiModalDialog();

    if( quasiModal )
    {
        // Raise and notify; don't give the user a warning regarding "quasi-modal dialogs"
        // when they have no idea what those are.
        quasiModal->Raise();
        wxBell();

        if( event.CanVeto() )
            event.Veto();

        return;
    }


    if( event.GetId() == wxEVT_QUERY_END_SESSION
        || event.GetId() == wxEVT_END_SESSION )
    {
        // End session means the OS is going to terminate us
        m_isNonUserClose = true;
    }

    if( canCloseWindow( event ) )
    {
        m_isClosing = true;

        if( m_infoBar )
            m_infoBar->Dismiss();

        APP_SETTINGS_BASE* cfg = config();

        if( cfg )
            SaveSettings( cfg );    // virtual, wxFrame specific

        doCloseWindow();

        // Destroy (safe delete frame) this frame only in non modal mode.
        // In modal mode, the caller will call Destroy().
        if( !IsModal() )
            Destroy();
    }
    else
    {
        if( event.CanVeto() )
            event.Veto();
    }
}


EDA_BASE_FRAME::~EDA_BASE_FRAME()
{
    Disconnect( ID_AUTO_SAVE_TIMER, wxEVT_TIMER,
                wxTimerEventHandler( EDA_BASE_FRAME::onAutoSaveTimer ) );
    Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( EDA_BASE_FRAME::windowClosing ) );

    delete m_autoSaveTimer;
    delete m_fileHistory;

    ClearUndoRedoList();

    SocketCleanup();

    KIPLATFORM::APP::RemoveShutdownBlockReason( this );
}


bool EDA_BASE_FRAME::ProcessEvent( wxEvent& aEvent )
{
#ifdef  __WXMAC__
    // Apple in its infinite wisdom will raise a disabled window before even passing
    // us the event, so we have no way to stop it.  Instead, we have to catch an
    // improperly ordered disabled window and quasi-modal dialog here and reorder
    // them.
    if( !IsEnabled() && IsActive() )
    {
        wxWindow* dlg = findQuasiModalDialog();

        if( dlg )
            dlg->Raise();
    }
#endif

    if( !wxFrame::ProcessEvent( aEvent ) )
        return false;

    if( Pgm().m_Quitting )
        return true;

    if( !m_isClosing && m_supportsAutoSave && IsShownOnScreen() && IsActive()
            && m_autoSavePending != isAutoSaveRequired()
            && GetAutoSaveInterval() > 0 )
    {
        if( !m_autoSavePending )
        {
            wxLogTrace( traceAutoSave, wxT( "Starting auto save timer." ) );
            m_autoSaveTimer->Start( GetAutoSaveInterval() * 1000, wxTIMER_ONE_SHOT );
            m_autoSavePending = true;
        }
        else if( m_autoSaveTimer->IsRunning() )
        {
            wxLogTrace( traceAutoSave, wxT( "Stopping auto save timer." ) );
            m_autoSaveTimer->Stop();
            m_autoSavePending = false;
        }
    }

    return true;
}


int EDA_BASE_FRAME::GetAutoSaveInterval() const
{
    return Pgm().GetCommonSettings()->m_System.autosave_interval;
}


void EDA_BASE_FRAME::onAutoSaveTimer( wxTimerEvent& aEvent )
{
    // Don't stomp on someone else's timer event.
    if( aEvent.GetId() != ID_AUTO_SAVE_TIMER )
    {
        aEvent.Skip();
        return;
    }

    if( !doAutoSave() )
        m_autoSaveTimer->Start( GetAutoSaveInterval() * 1000, wxTIMER_ONE_SHOT );
}


bool EDA_BASE_FRAME::doAutoSave()
{
    wxCHECK_MSG( false, true, wxT( "Auto save timer function not overridden.  Bad programmer!" ) );
}


void EDA_BASE_FRAME::OnCharHook( wxKeyEvent& aKeyEvent )
{
    wxLogTrace( kicadTraceKeyEvent, wxS( "EDA_BASE_FRAME::OnCharHook %s" ), dump( aKeyEvent ) );

    // Key events can be filtered here.
    // Currently no filtering is made.
    aKeyEvent.Skip();
}


void EDA_BASE_FRAME::OnMenuEvent( wxMenuEvent& aEvent )
{
    if( !m_toolDispatcher )
        aEvent.Skip();
    else
        m_toolDispatcher->DispatchWxEvent( aEvent );
}


void EDA_BASE_FRAME::RegisterUIUpdateHandler( int aID, const ACTION_CONDITIONS& aConditions )
{
    UIUpdateHandler evtFunc = std::bind( &EDA_BASE_FRAME::HandleUpdateUIEvent,
                                         std::placeholders::_1,
                                         this,
                                         aConditions );

    m_uiUpdateMap[aID] = evtFunc;

    Bind( wxEVT_UPDATE_UI, evtFunc, aID );
}


void EDA_BASE_FRAME::UnregisterUIUpdateHandler( int aID )
{
    const auto it = m_uiUpdateMap.find( aID );

    if( it == m_uiUpdateMap.end() )
        return;

    Unbind( wxEVT_UPDATE_UI, it->second, aID );
}


void EDA_BASE_FRAME::HandleUpdateUIEvent( wxUpdateUIEvent& aEvent, EDA_BASE_FRAME* aFrame,
                                          ACTION_CONDITIONS aCond )
{
    bool       checkRes  = false;
    bool       enableRes = true;
    bool       showRes   = true;
    bool       isCut     = aEvent.GetId() == ACTIONS::cut.GetUIId();
    bool       isCopy    = aEvent.GetId() == ACTIONS::copy.GetUIId();
    bool       isPaste   = aEvent.GetId() == ACTIONS::paste.GetUIId();
    SELECTION& selection = aFrame->GetCurrentSelection();

    try
    {
        checkRes  = aCond.checkCondition( selection );
        enableRes = aCond.enableCondition( selection );
        showRes   = aCond.showCondition( selection );
    }
    catch( std::exception& )
    {
        // Something broke with the conditions, just skip the event.
        aEvent.Skip();
        return;
    }

    if( showRes && aEvent.GetId() == ACTIONS::undo.GetUIId() )
    {
        wxString msg = _( "Undo" );

        if( enableRes )
            msg += wxS( " " ) + aFrame->GetUndoActionDescription();

        aEvent.SetText( msg );
    }
    else if( showRes && aEvent.GetId() == ACTIONS::redo.GetUIId() )
    {
        wxString msg = _( "Redo" );

        if( enableRes )
            msg += wxS( " " ) + aFrame->GetRedoActionDescription();

        aEvent.SetText( msg );
    }

    if( isCut || isCopy || isPaste )
    {
        wxWindow*    focus = wxWindow::FindFocus();
        wxTextEntry* textEntry = dynamic_cast<wxTextEntry*>( focus );

        if( textEntry && isCut && textEntry->CanCut() )
            enableRes = true;
        else if( textEntry && isCopy && textEntry->CanCopy() )
            enableRes = true;
        else if( textEntry && isPaste && textEntry->CanPaste() )
            enableRes = true;
        else if( dynamic_cast<WX_GRID*>( focus ) )
            enableRes = false;  // Must disable menu in order to get command as CharHook event
    }

    aEvent.Enable( enableRes );
    aEvent.Show( showRes );

    if( aEvent.IsCheckable() )
        aEvent.Check( checkRes );
}


void EDA_BASE_FRAME::setupUIConditions()
{
    // Setup the conditions to check a language menu item
    auto isCurrentLang =
            [] ( const SELECTION& aSel, int aLangIdentifier )
            {
                return Pgm().GetSelectedLanguageIdentifier() == aLangIdentifier;
            };

    for( unsigned ii = 0;  LanguagesList[ii].m_KI_Lang_Identifier != 0; ii++ )
    {
        ACTION_CONDITIONS cond;
        cond.Check( std::bind( isCurrentLang, std::placeholders::_1,
                               LanguagesList[ii].m_WX_Lang_Identifier ) );

        RegisterUIUpdateHandler( LanguagesList[ii].m_KI_Lang_Identifier, cond );
    }
}


void EDA_BASE_FRAME::ReCreateMenuBar()
{
    /**
     * As of wxWidgets 3.2, recreating the menubar from within an event handler of that menubar
     * will result in memory corruption on macOS.  In order to minimize the chance of programmer
     * error causing regressions here, we always wrap calls to ReCreateMenuBar in a CallAfter to
     * ensure that they do not occur within the same event handling call stack.
     */

    CallAfter( [this]()
               {
                   if( !m_isClosing )
                       doReCreateMenuBar();
               } );
}


void EDA_BASE_FRAME::AddStandardHelpMenu( wxMenuBar* aMenuBar )
{
    COMMON_CONTROL* commonControl = m_toolManager->GetTool<COMMON_CONTROL>();
    ACTION_MENU*    helpMenu = new ACTION_MENU( false, commonControl );

    helpMenu->Add( ACTIONS::help );
    helpMenu->Add( ACTIONS::gettingStarted );
    helpMenu->Add( ACTIONS::listHotKeys );
    helpMenu->Add( ACTIONS::getInvolved );
    helpMenu->Add( ACTIONS::donate );
    helpMenu->Add( ACTIONS::reportBug );

    helpMenu->AppendSeparator();
    helpMenu->Add( ACTIONS::about );

    aMenuBar->Append( helpMenu, _( "&Help" ) );
}


void EDA_BASE_FRAME::ShowChangedLanguage()
{
    TOOLS_HOLDER::ShowChangedLanguage();

    if( GetMenuBar() )
    {
        ReCreateMenuBar();
        GetMenuBar()->Refresh();
    }
}


void EDA_BASE_FRAME::CommonSettingsChanged( int aFlags )
{
    TOOLS_HOLDER::CommonSettingsChanged( aFlags );

    COMMON_SETTINGS* settings = Pgm().GetCommonSettings();

#ifdef KICAD_IPC_API
    bool running = Pgm().GetApiServer().Running();

    if( running && !settings->m_Api.enable_server )
        Pgm().GetApiServer().Stop();
    else if( !running && settings->m_Api.enable_server )
        Pgm().GetApiServer().Start();
#endif

    if( m_fileHistory )
    {
        int historySize = settings->m_System.file_history_size;
        m_fileHistory->SetMaxFiles( (unsigned) std::max( 0, historySize ) );
    }

    GetBitmapStore()->ThemeChanged();
    ThemeChanged();

    if( GetMenuBar() )
    {
        // For icons in menus, icon scaling & hotkeys
        ReCreateMenuBar();
        GetMenuBar()->Refresh();
    }
}


void EDA_BASE_FRAME::ThemeChanged()
{
    ClearScaledBitmapCache();

    // Update all the toolbars to have new icons
    wxAuiPaneInfoArray panes = m_auimgr.GetAllPanes();

    for( size_t i = 0; i < panes.GetCount(); ++i )
    {
        if( ACTION_TOOLBAR* toolbar = dynamic_cast<ACTION_TOOLBAR*>( panes[i].window ) )
            toolbar->RefreshBitmaps();
    }
}


void EDA_BASE_FRAME::OnSize( wxSizeEvent& aEvent )
{
#ifdef __WXMAC__
    int currentDisplay = wxDisplay::GetFromWindow( this );

    if( m_displayIndex >= 0 && currentDisplay >= 0 && currentDisplay != m_displayIndex )
    {
        wxLogTrace( traceDisplayLocation, wxS( "OnSize: current display changed %d to %d" ),
                    m_displayIndex, currentDisplay );
        m_displayIndex = currentDisplay;
        ensureWindowIsOnScreen();
    }
#endif

    aEvent.Skip();
}


void EDA_BASE_FRAME::LoadWindowState( const wxString& aFileName )
{
    if( !Pgm().GetCommonSettings()->m_Session.remember_open_files )
        return;

    const PROJECT_FILE_STATE* state = Prj().GetLocalSettings().GetFileState( aFileName );

    if( state != nullptr )
    {
        LoadWindowState( state->window );
    }
}


void EDA_BASE_FRAME::LoadWindowState( const WINDOW_STATE& aState )
{
    bool wasDefault = false;

    m_framePos.x  = aState.pos_x;
    m_framePos.y  = aState.pos_y;
    m_frameSize.x = aState.size_x;
    m_frameSize.y = aState.size_y;

    wxLogTrace( traceDisplayLocation, wxS( "Config position (%d, %d) with size (%d, %d)" ),
                m_framePos.x, m_framePos.y, m_frameSize.x, m_frameSize.y );

    // Ensure minimum size is set if the stored config was zero-initialized
    wxSize minSize = minSizeLookup( m_ident, this );

    if( m_frameSize.x < minSize.x || m_frameSize.y < minSize.y )
    {
        m_frameSize = defaultSize( m_ident, this );
        wasDefault  = true;

        wxLogTrace( traceDisplayLocation, wxS( "Using minimum size (%d, %d)" ),
                    m_frameSize.x, m_frameSize.y );
    }

    wxLogTrace( traceDisplayLocation, wxS( "Number of displays: %d" ), wxDisplay::GetCount() );

    if( aState.display >= wxDisplay::GetCount() )
    {
        wxLogTrace( traceDisplayLocation, wxS( "Previous display not found" ) );

        // If it isn't attached, use the first display
        // Warning wxDisplay has 2 ctor variants. the parameter needs a type:
        const unsigned int index = 0;
        wxDisplay display( index );
        wxRect    clientSize = display.GetGeometry();

        m_framePos = wxDefaultPosition;

        // Ensure the window fits on the display, since the other one could have been larger
        if( m_frameSize.x > clientSize.width )
            m_frameSize.x = clientSize.width;

        if( m_frameSize.y > clientSize.height )
            m_frameSize.y = clientSize.height;
    }
    else
    {
        wxPoint upperRight( m_framePos.x + m_frameSize.x, m_framePos.y );
        wxPoint upperLeft( m_framePos.x, m_framePos.y );

        wxDisplay display( aState.display );
        wxRect clientSize = display.GetClientArea();

        int yLimTop   = clientSize.y;
        int yLimBottom = clientSize.y + clientSize.height;
        int xLimLeft  = clientSize.x;
        int xLimRight = clientSize.x + clientSize.width;

        if( upperLeft.x  > xLimRight ||  // Upper left corner too close to right edge of screen
            upperRight.x < xLimLeft  ||  // Upper right corner too close to left edge of screen
            upperLeft.y < yLimTop ||   // Upper corner too close to the bottom of the screen
            upperLeft.y > yLimBottom )
        {
            m_framePos = wxDefaultPosition;
            wxLogTrace( traceDisplayLocation, wxS( "Resetting to default position" ) );
        }
    }

    wxLogTrace( traceDisplayLocation, wxS( "Final window position (%d, %d) with size (%d, %d)" ),
                m_framePos.x, m_framePos.y, m_frameSize.x, m_frameSize.y );

    SetSize( m_framePos.x, m_framePos.y, m_frameSize.x, m_frameSize.y );

    // Center the window if we reset to default
    if( m_framePos.x == -1 )
    {
        wxLogTrace( traceDisplayLocation, wxS( "Centering window" ) );
        Center();
        m_framePos = GetPosition();
    }

    // Record the frame sizes in an un-maximized state
    m_normalFrameSize = m_frameSize;
    m_normalFramePos  = m_framePos;

    // Maximize if we were maximized before
    if( aState.maximized || ( wasDefault && m_maximizeByDefault ) )
    {
        wxLogTrace( traceDisplayLocation, wxS( "Maximizing window" ) );
        Maximize();
    }

    m_displayIndex = wxDisplay::GetFromWindow( this );
}


void EDA_BASE_FRAME::ensureWindowIsOnScreen()
{
    wxDisplay display( wxDisplay::GetFromWindow( this ) );
    wxRect    clientSize = display.GetClientArea();
    wxPoint   pos        = GetPosition();
    wxSize    size       = GetWindowSize();

    wxLogTrace( traceDisplayLocation,
                wxS( "ensureWindowIsOnScreen: clientArea (%d, %d) w %d h %d" ),
                clientSize.x, clientSize.y,
                clientSize.width, clientSize.height );

    if( pos.y < clientSize.y )
    {
        wxLogTrace( traceDisplayLocation,
                    wxS( "ensureWindowIsOnScreen: y pos %d below minimum, setting to %d" ), pos.y,
                    clientSize.y );
        pos.y = clientSize.y;
    }

    if( pos.x < clientSize.x )
    {
        wxLogTrace( traceDisplayLocation,
                    wxS( "ensureWindowIsOnScreen: x pos %d is off the client rect, setting to %d" ),
                    pos.x, clientSize.x );
        pos.x = clientSize.x;
    }

    if( pos.x + size.x - clientSize.x > clientSize.width )
    {
        int newWidth = clientSize.width - ( pos.x - clientSize.x );
        wxLogTrace( traceDisplayLocation,
                    wxS( "ensureWindowIsOnScreen: effective width %d above available %d, setting "
                         "to %d" ), pos.x + size.x, clientSize.width, newWidth );
        size.x = newWidth;
    }

    if( pos.y + size.y - clientSize.y > clientSize.height )
    {
        int newHeight = clientSize.height - ( pos.y - clientSize.y );
        wxLogTrace( traceDisplayLocation,
                    wxS( "ensureWindowIsOnScreen: effective height %d above available %d, setting "
                         "to %d" ), pos.y + size.y, clientSize.height, newHeight );
        size.y = newHeight;
    }

    wxLogTrace( traceDisplayLocation, wxS( "Updating window position (%d, %d) with size (%d, %d)" ),
                pos.x, pos.y, size.x, size.y );

    SetSize( pos.x, pos.y, size.x, size.y );
}


void EDA_BASE_FRAME::LoadWindowSettings( const WINDOW_SETTINGS* aCfg )
{
    LoadWindowState( aCfg->state );

    m_perspective = aCfg->perspective;
    m_mruPath = aCfg->mru_path;

    TOOLS_HOLDER::CommonSettingsChanged();
}


void EDA_BASE_FRAME::SaveWindowSettings( WINDOW_SETTINGS* aCfg )
{
    if( IsIconized() )
        return;

    // If the window is maximized, we use the saved window size from before it was maximized
    if( IsMaximized() )
    {
        m_framePos  = m_normalFramePos;
        m_frameSize = m_normalFrameSize;
    }
    else
    {
        m_frameSize = GetWindowSize();
        m_framePos  = GetPosition();
    }

    aCfg->state.pos_x     = m_framePos.x;
    aCfg->state.pos_y     = m_framePos.y;
    aCfg->state.size_x    = m_frameSize.x;
    aCfg->state.size_y    = m_frameSize.y;
    aCfg->state.maximized = IsMaximized();
    aCfg->state.display   = wxDisplay::GetFromWindow( this );

    wxLogTrace( traceDisplayLocation, wxS( "Saving window maximized: %s" ),
                IsMaximized() ? wxS( "true" ) : wxS( "false" ) );
    wxLogTrace( traceDisplayLocation, wxS( "Saving config position (%d, %d) with size (%d, %d)" ),
                m_framePos.x, m_framePos.y, m_frameSize.x, m_frameSize.y );

    // Once this is fully implemented, wxAuiManager will be used to maintain
    // the persistence of the main frame and all it's managed windows and
    // all of the legacy frame persistence position code can be removed.
    aCfg->perspective = m_auimgr.SavePerspective().ToStdString();

    aCfg->mru_path = m_mruPath;
}


void EDA_BASE_FRAME::LoadSettings( APP_SETTINGS_BASE* aCfg )
{
    LoadWindowSettings( GetWindowSettings( aCfg ) );

    // Get file history size from common settings
    int fileHistorySize = Pgm().GetCommonSettings()->m_System.file_history_size;

    // Load the recently used files into the history menu
    m_fileHistory = new FILE_HISTORY( (unsigned) std::max( 1, fileHistorySize ),
                                      ID_FILE1, ID_FILE_LIST_CLEAR );
    m_fileHistory->Load( *aCfg );
}


void EDA_BASE_FRAME::SaveSettings( APP_SETTINGS_BASE* aCfg )
{
    wxCHECK( config(), /* void */ );

    SaveWindowSettings( GetWindowSettings( aCfg ) );

    bool fileOpen = m_isClosing && m_isNonUserClose;

    wxString currentlyOpenedFile = GetCurrentFileName();

    if( Pgm().GetCommonSettings()->m_Session.remember_open_files && !currentlyOpenedFile.IsEmpty() )
    {
        wxFileName rfn( currentlyOpenedFile );
        rfn.MakeRelativeTo( Prj().GetProjectPath() );
        Prj().GetLocalSettings().SaveFileState( rfn.GetFullPath(), &aCfg->m_Window, fileOpen );
    }

    // Save the recently used files list
    if( m_fileHistory )
    {
        // Save the currently opened file in the file history
        if( !currentlyOpenedFile.IsEmpty() )
            UpdateFileHistory( currentlyOpenedFile );

        m_fileHistory->Save( *aCfg );
    }
}


WINDOW_SETTINGS* EDA_BASE_FRAME::GetWindowSettings( APP_SETTINGS_BASE* aCfg )
{
    return &aCfg->m_Window;
}


APP_SETTINGS_BASE* EDA_BASE_FRAME::config() const
{
    // KICAD_MANAGER_FRAME overrides this
    return Kiface().KifaceSettings();
}


const SEARCH_STACK& EDA_BASE_FRAME::sys_search()
{
    return Kiface().KifaceSearch();
}


wxString EDA_BASE_FRAME::help_name()
{
    return Kiface().GetHelpFileName();
}


void EDA_BASE_FRAME::PrintMsg( const wxString& text )
{
    SetStatusText( text );
}


void EDA_BASE_FRAME::CreateInfoBar()
{
#if defined( __WXOSX_MAC__ )
    m_infoBar = new WX_INFOBAR( GetToolCanvas() );
#else
    m_infoBar = new WX_INFOBAR( this, &m_auimgr );

    m_auimgr.AddPane( m_infoBar, EDA_PANE().InfoBar().Name( wxS( "InfoBar" ) ).Top().Layer(1) );
#endif
}


void EDA_BASE_FRAME::FinishAUIInitialization()
{
#if defined( __WXOSX_MAC__ )
    m_auimgr.Update();
#else
    // Call Update() to fix all pane default sizes, especially the "InfoBar" pane before
    // hiding it.
    m_auimgr.Update();

    // We don't want the infobar displayed right away
    m_auimgr.GetPane( wxS( "InfoBar" ) ).Hide();
    m_auimgr.Update();
#endif
}


void EDA_BASE_FRAME::ShowInfoBarError( const wxString& aErrorMsg, bool aShowCloseButton,
                                       WX_INFOBAR::MESSAGE_TYPE aType )
{
    m_infoBar->RemoveAllButtons();

    if( aShowCloseButton )
        m_infoBar->AddCloseButton();

    GetInfoBar()->ShowMessageFor( aErrorMsg, 8000, wxICON_ERROR, aType );
}


void EDA_BASE_FRAME::ShowInfoBarError( const wxString& aErrorMsg, bool aShowCloseButton,
                                       std::function<void(void)> aCallback )
{
    m_infoBar->RemoveAllButtons();

    if( aShowCloseButton )
        m_infoBar->AddCloseButton();

    if( aCallback )
        m_infoBar->SetCallback( aCallback );

    GetInfoBar()->ShowMessageFor( aErrorMsg, 6000, wxICON_ERROR );
}


void EDA_BASE_FRAME::ShowInfoBarWarning( const wxString& aWarningMsg, bool aShowCloseButton )
{
    m_infoBar->RemoveAllButtons();

    if( aShowCloseButton )
        m_infoBar->AddCloseButton();

    GetInfoBar()->ShowMessageFor( aWarningMsg, 6000, wxICON_WARNING );
}


void EDA_BASE_FRAME::ShowInfoBarMsg( const wxString& aMsg, bool aShowCloseButton )
{
    m_infoBar->RemoveAllButtons();

    if( aShowCloseButton )
        m_infoBar->AddCloseButton();

    GetInfoBar()->ShowMessageFor( aMsg, 8000, wxICON_INFORMATION );
}


void EDA_BASE_FRAME::UpdateFileHistory( const wxString& FullFileName, FILE_HISTORY* aFileHistory )
{
    if( !aFileHistory )
        aFileHistory = m_fileHistory;

    wxASSERT( aFileHistory );

    aFileHistory->AddFileToHistory( FullFileName );

    // Update the menubar to update the file history menu
    if( !m_isClosing && GetMenuBar() )
    {
        ReCreateMenuBar();
        GetMenuBar()->Refresh();
    }
}


wxString EDA_BASE_FRAME::GetFileFromHistory( int cmdId, const wxString& type,
                                             FILE_HISTORY* aFileHistory )
{
    if( !aFileHistory )
        aFileHistory = m_fileHistory;

    wxASSERT( aFileHistory );

    int baseId = aFileHistory->GetBaseId();

    wxASSERT( cmdId >= baseId && cmdId < baseId + (int) aFileHistory->GetCount() );

    unsigned i = cmdId - baseId;

    if( i < aFileHistory->GetCount() )
    {
        wxString fn = aFileHistory->GetHistoryFile( i );

        if( wxFileName::FileExists( fn ) )
        {
            return fn;
        }
        else
        {
            DisplayErrorMessage( this, wxString::Format( _( "File '%s' was not found." ), fn ) );
            aFileHistory->RemoveFileFromHistory( i );
        }
    }

    // Update the menubar to update the file history menu
    if( GetMenuBar() )
    {
        ReCreateMenuBar();
        GetMenuBar()->Refresh();
    }

    return wxEmptyString;
}


void EDA_BASE_FRAME::ClearFileHistory( FILE_HISTORY* aFileHistory )
{
    if( !aFileHistory )
        aFileHistory = m_fileHistory;

    wxASSERT( aFileHistory );

    aFileHistory->ClearFileHistory();

    // Update the menubar to update the file history menu
    if( GetMenuBar() )
    {
        ReCreateMenuBar();
        GetMenuBar()->Refresh();
    }
}


void EDA_BASE_FRAME::OnKicadAbout( wxCommandEvent& event )
{
    void ShowAboutDialog( EDA_BASE_FRAME * aParent ); // See AboutDialog_main.cpp
    ShowAboutDialog( this );
}


void EDA_BASE_FRAME::OnPreferences( wxCommandEvent& event )
{
    ShowPreferences( wxEmptyString, wxEmptyString );
}


void EDA_BASE_FRAME::ShowPreferences( wxString aStartPage, wxString aStartParentPage )
{
    PAGED_DIALOG dlg( this, _( "Preferences" ), true, true, wxEmptyString,
                      wxWindow::FromDIP( wxSize( 980, 560 ), NULL ) );

    dlg.SetEvtHandlerEnabled( false );

    {
        WX_BUSY_INDICATOR busy_cursor;

        WX_TREEBOOK*            book = dlg.GetTreebook();
        PANEL_HOTKEYS_EDITOR*   hotkeysPanel = new PANEL_HOTKEYS_EDITOR( this, book, false );
        KIFACE*                 kiface = nullptr;
        std::vector<int>        expand;

        wxWindow* kicadMgr_window = wxWindow::FindWindowByName( KICAD_MANAGER_FRAME_NAME );

        if( KICAD_MANAGER_FRAME* kicadMgr = static_cast<KICAD_MANAGER_FRAME*>( kicadMgr_window ) )
        {
            ACTION_MANAGER* actionMgr = kicadMgr->GetToolManager()->GetActionManager();

            for( const auto& [name, action] : actionMgr->GetActions() )
                hotkeysPanel->ActionsList().push_back( action );
        }

        book->AddLazyPage(
                []( wxWindow* aParent ) -> wxWindow*
                {
                    return new PANEL_COMMON_SETTINGS( aParent );
                },
                _( "Common" ) );

        book->AddLazyPage(
                []( wxWindow* aParent ) -> wxWindow*
                {
                    return new PANEL_MOUSE_SETTINGS( aParent );
                }, _( "Mouse and Touchpad" ) );

        book->AddPage( hotkeysPanel, _( "Hotkeys" ) );

        book->AddLazyPage(
                []( wxWindow* aParent ) -> wxWindow*
                {
                    return new PANEL_GIT_REPOS( aParent );
                }, _( "Version Control" ) );

#ifdef KICAD_USE_SENTRY
        book->AddLazyPage(
                []( wxWindow* aParent ) -> wxWindow*
                {
                    return new PANEL_DATA_COLLECTION( aParent );
                }, _( "Data Collection" ) );
#endif

#define LAZY_CTOR( key )                                                \
        [this, kiface]( wxWindow* aParent )                             \
        {                                                               \
            return kiface->CreateKiWindow( aParent, key, &Kiway() );    \
        }

        // If a dll is not loaded, the loader will show an error message.

        try
        {
            kiface = Kiway().KiFACE( KIWAY::FACE_SCH );

            if( !kiface )
                return;

            kiface->GetActions( hotkeysPanel->ActionsList() );

            if( GetFrameType() == FRAME_SCH_SYMBOL_EDITOR )
                expand.push_back( (int) book->GetPageCount() );

            book->AddPage( new wxPanel( book ), _( "Symbol Editor" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_SYM_DISP_OPTIONS ), _( "Display Options" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_SYM_EDIT_GRIDS ), _( "Grids" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_SYM_EDIT_OPTIONS ), _( "Editing Options" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_SYM_COLORS ), _( "Colors" ) );

            if( GetFrameType() == FRAME_SCH )
                expand.push_back( (int) book->GetPageCount() );

            book->AddPage( new wxPanel( book ), _( "Schematic Editor" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_SCH_DISP_OPTIONS ), _( "Display Options" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_SCH_GRIDS ), _( "Grids" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_SCH_EDIT_OPTIONS ), _( "Editing Options" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_SCH_ANNO_OPTIONS ), _( "Annotation Options" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_SCH_COLORS ), _( "Colors" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_SCH_FIELD_NAME_TEMPLATES ),
                                  _( "Field Name Templates" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_SCH_SIMULATOR ), _( "Simulator" ) );
        }
        catch( ... )
        {
        }

        try
        {
            kiface = Kiway().KiFACE( KIWAY::FACE_PCB );

            if( !kiface )
                return;

            kiface->GetActions( hotkeysPanel->ActionsList() );

            if( GetFrameType() == FRAME_FOOTPRINT_EDITOR )
                expand.push_back( (int) book->GetPageCount() );

            book->AddPage( new wxPanel( book ), _( "Footprint Editor" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_FP_DISPLAY_OPTIONS ), _( "Display Options" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_FP_GRIDS ), _( "Grids" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_FP_ORIGINS_AXES ), _( "Origins & Axes" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_FP_EDIT_OPTIONS ), _( "Editing Options" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_FP_COLORS ), _( "Colors" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_FP_DEFAULT_FIELDS ), _( "Footprint Defaults" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_FP_DEFAULT_GRAPHICS_VALUES ),
                                  _( "Graphics Defaults" ) );

            if( GetFrameType() ==  FRAME_PCB_EDITOR )
                expand.push_back( (int) book->GetPageCount() );

            book->AddPage( new wxPanel( book ), _( "PCB Editor" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_PCB_DISPLAY_OPTS ), _( "Display Options" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_PCB_GRIDS ), _( "Grids" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_PCB_ORIGINS_AXES ), _( "Origins & Axes" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_PCB_EDIT_OPTIONS ), _( "Editing Options" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_PCB_COLORS ), _( "Colors" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_PCB_ACTION_PLUGINS ), _( "Plugins" ) );

            if( GetFrameType() == FRAME_PCB_DISPLAY3D )
                expand.push_back( (int) book->GetPageCount() );

            book->AddPage( new wxPanel( book ), _( "3D Viewer" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_3DV_DISPLAY_OPTIONS ), _( "General" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_3DV_OPENGL ), _( "Realtime Renderer" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_3DV_RAYTRACING ), _( "Raytracing Renderer" ) );
        }
        catch( ... )
        {
        }

        try
        {
            kiface = Kiway().KiFACE( KIWAY::FACE_GERBVIEW );

            if( !kiface )
                return;

            kiface->GetActions( hotkeysPanel->ActionsList() );

            if( GetFrameType() == FRAME_GERBER )
                expand.push_back( (int) book->GetPageCount() );

            book->AddPage( new wxPanel( book ), _( "Gerber Viewer" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_GBR_DISPLAY_OPTIONS ), _( "Display Options" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_GBR_COLORS ), _( "Colors" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_GBR_GRIDS ), _( "Grids" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_GBR_EXCELLON_OPTIONS ),
                                  _( "Excellon Options" ) );
        }
        catch( ... )
        {
        }

        try
        {
            kiface = Kiway().KiFACE( KIWAY::FACE_PL_EDITOR );

            if( !kiface )
                return;

            kiface->GetActions( hotkeysPanel->ActionsList() );

            if( GetFrameType() == FRAME_PL_EDITOR )
                expand.push_back( (int) book->GetPageCount() );

            book->AddPage( new wxPanel( book ), _( "Drawing Sheet Editor" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_DS_DISPLAY_OPTIONS ), _( "Display Options" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_DS_GRIDS ), _( "Grids" ) );
            book->AddLazySubPage( LAZY_CTOR( PANEL_DS_COLORS ), _( "Colors" ) );

            book->AddLazyPage(
                    []( wxWindow* aParent ) -> wxWindow*
                    {
                        return new PANEL_PACKAGES_AND_UPDATES( aParent );
                    }, _( "Packages and Updates" ) );
        }
        catch( ... )
        {
        }

#ifdef KICAD_IPC_API
        book->AddPage( new PANEL_PLUGIN_SETTINGS( book ), _( "Plugins" ) );
#endif

        // Update all of the action hotkeys. The process of loading the actions through
        // the KiFACE will only get us the default hotkeys
        ReadHotKeyConfigIntoActions( wxEmptyString, hotkeysPanel->ActionsList() );

        for( size_t i = 0; i < book->GetPageCount(); ++i )
            book->GetPage( i )->Layout();

        for( int page : expand )
            book->ExpandNode( page );

        if( !aStartPage.IsEmpty() )
            dlg.SetInitialPage( aStartPage, aStartParentPage );

        dlg.SetEvtHandlerEnabled( true );
#undef LAZY_CTOR
    }

    if( dlg.ShowModal() == wxID_OK )
    {
        // Update our grids that are cached in the tool
        m_toolManager->ResetTools( TOOL_BASE::REDRAW );
        Pgm().GetSettingsManager().Save();
        dlg.Kiway().CommonSettingsChanged( HOTKEYS_CHANGED );
    }

}


void EDA_BASE_FRAME::OnDropFiles( wxDropFilesEvent& aEvent )
{
    wxString* files = aEvent.GetFiles();

    for( int nb = 0; nb < aEvent.GetNumberOfFiles(); nb++ )
    {
        const wxFileName fn = wxFileName( files[nb] );
        wxString         ext = fn.GetExt();

        // Alias all gerber files as GerberFileExtension
        if( FILEEXT::IsGerberFileExtension( ext ) )
            ext = FILEEXT::GerberFileExtension;

        if( m_acceptedExts.find( ext.ToStdString() ) != m_acceptedExts.end() )
            m_AcceptedFiles.emplace_back( fn );
    }

    DoWithAcceptedFiles();
    m_AcceptedFiles.clear();
}


void EDA_BASE_FRAME::DoWithAcceptedFiles()
{
    for( const wxFileName& file : m_AcceptedFiles )
    {
        wxString fn = file.GetFullPath();
        m_toolManager->RunAction<wxString*>( *m_acceptedExts.at( file.GetExt() ), &fn );
    }
}


bool EDA_BASE_FRAME::IsWritable( const wxFileName& aFileName, bool aVerbose )
{
    wxString msg;
    wxFileName fn = aFileName;

    // Check for absence of a file path with a file name.  Unfortunately KiCad
    // uses paths relative to the current project path without the ./ part which
    // confuses wxFileName. Making the file name path absolute may be less than
    // elegant but it solves the problem.
    if( fn.GetPath().IsEmpty() && fn.HasName() )
        fn.MakeAbsolute();

    wxCHECK_MSG( fn.IsOk(), false,
                 wxT( "File name object is invalid.  Bad programmer!" ) );
    wxCHECK_MSG( !fn.GetPath().IsEmpty(), false,
                 wxT( "File name object path <" ) + fn.GetFullPath() +
                 wxT( "> is not set.  Bad programmer!" ) );

    if( fn.IsDir() && !fn.IsDirWritable() )
    {
        msg.Printf( _( "Insufficient permissions to folder '%s'." ), fn.GetPath() );
    }
    else if( !fn.FileExists() && !fn.IsDirWritable() )
    {
        msg.Printf( _( "Insufficient permissions to save file '%s'." ), fn.GetFullPath() );
    }
    else if( fn.FileExists() && !fn.IsFileWritable() )
    {
        msg.Printf( _( "Insufficient permissions to save file '%s'." ), fn.GetFullPath() );
    }

    if( !msg.IsEmpty() )
    {
        if( aVerbose )
            DisplayErrorMessage( this, msg );

        return false;
    }

    return true;
}


void EDA_BASE_FRAME::CheckForAutoSaveFile( const wxFileName& aFileName )
{
    if( !Pgm().IsGUI() )
        return;

    wxCHECK_RET( aFileName.IsOk(), wxT( "Invalid file name!" ) );

    wxFileName autoSaveFileName = aFileName;

    // Check for auto save file.
    autoSaveFileName.SetName( FILEEXT::AutoSaveFilePrefix + aFileName.GetName() );

    wxLogTrace( traceAutoSave,
                wxT( "Checking for auto save file " ) + autoSaveFileName.GetFullPath() );

    if( !autoSaveFileName.FileExists() )
        return;

    wxString msg = wxString::Format( _( "Well this is potentially embarrassing!\n"
                                        "It appears that the last time you were editing\n"
                                        "%s\n"
                                        "KiCad exited before saving.\n"
                                        "\n"
                                        "Do you wish to open the auto-saved file instead?" ),
                                        aFileName.GetFullName() );

    int response = wxMessageBox( msg, Pgm().App().GetAppDisplayName(), wxYES_NO | wxICON_QUESTION,
                                 this );

    // Make a backup of the current file, delete the file, and rename the auto save file to
    // the file name.
    if( response == wxYES )
    {
        // Preserve the permissions of the current file
        KIPLATFORM::IO::DuplicatePermissions( aFileName.GetFullPath(),
                                              autoSaveFileName.GetFullPath() );

        if( !wxRenameFile( autoSaveFileName.GetFullPath(), aFileName.GetFullPath() ) )
        {
            wxMessageBox( _( "The auto save file could not be renamed to the board file name." ),
                          Pgm().App().GetAppDisplayName(), wxOK | wxICON_EXCLAMATION, this );
        }
    }
    else
    {
        DeleteAutoSaveFile( aFileName );
    }
}


void EDA_BASE_FRAME::DeleteAutoSaveFile( const wxFileName& aFileName )
{
    if( !Pgm().IsGUI() )
        return;

    wxCHECK_RET( aFileName.IsOk(), wxT( "Invalid file name!" ) );

    wxFileName autoSaveFn = aFileName;
    autoSaveFn.SetName( FILEEXT::AutoSaveFilePrefix + aFileName.GetName() );

    if( autoSaveFn.FileExists() )
    {
        wxLogTrace( traceAutoSave, wxT( "Removing auto save file " ) + autoSaveFn.GetFullPath() );
        wxRemoveFile( autoSaveFn.GetFullPath() );
    }
}


bool EDA_BASE_FRAME::IsContentModified() const
{
    // This function should be overridden in child classes
    return false;
}


void EDA_BASE_FRAME::initExitKey()
{
    wxAcceleratorEntry entries[1];
    entries[0].Set( wxACCEL_CTRL, int( 'Q' ), wxID_EXIT );
    wxAcceleratorTable accel( 1, entries );
    SetAcceleratorTable( accel );
}


void EDA_BASE_FRAME::ClearUndoRedoList()
{
    ClearUndoORRedoList( UNDO_LIST );
    ClearUndoORRedoList( REDO_LIST );
}


void EDA_BASE_FRAME::PushCommandToUndoList( PICKED_ITEMS_LIST* aNewitem )
{
    m_undoList.PushCommand( aNewitem );

    // Delete the extra items, if count max reached
    if( m_undoRedoCountMax > 0 )
    {
        int extraitems = GetUndoCommandCount() - m_undoRedoCountMax;

        if( extraitems > 0 )
            ClearUndoORRedoList( UNDO_LIST, extraitems );
    }
}


void EDA_BASE_FRAME::PushCommandToRedoList( PICKED_ITEMS_LIST* aNewitem )
{
    m_redoList.PushCommand( aNewitem );

    // Delete the extra items, if count max reached
    if( m_undoRedoCountMax > 0 )
    {
        int extraitems = GetRedoCommandCount() - m_undoRedoCountMax;

        if( extraitems > 0 )
            ClearUndoORRedoList( REDO_LIST, extraitems );
    }
}


PICKED_ITEMS_LIST* EDA_BASE_FRAME::PopCommandFromUndoList( )
{
    return m_undoList.PopCommand();
}


PICKED_ITEMS_LIST* EDA_BASE_FRAME::PopCommandFromRedoList( )
{
    return m_redoList.PopCommand();
}


wxString EDA_BASE_FRAME::GetUndoActionDescription() const
{
    if( GetUndoCommandCount() > 0 )
        return m_undoList.m_CommandsList.back()->GetDescription();

    return wxEmptyString;
}


wxString EDA_BASE_FRAME::GetRedoActionDescription() const
{
    if( GetRedoCommandCount() > 0 )
        return m_redoList.m_CommandsList.back()->GetDescription();

    return wxEmptyString;
}


void EDA_BASE_FRAME::OnModify()
{
    m_autoSaveRequired = true;
}


void EDA_BASE_FRAME::ChangeUserUnits( EDA_UNITS aUnits )
{
    SetUserUnits( aUnits );
    unitsChangeRefresh();

    wxCommandEvent e( EDA_EVT_UNITS_CHANGED );
    e.SetInt( static_cast<int>( aUnits ) );
    e.SetClientData( this );
    ProcessEventLocally( e );
}


void EDA_BASE_FRAME::OnMaximize( wxMaximizeEvent& aEvent )
{
    // When we maximize the window, we want to save the old information
    // so that we can add it to the settings on next window load.
    // Contrary to the documentation, this event seems to be generated
    // when the window is also being unmaximized on OSX, so we only
    // capture the size information when we maximize the window when on OSX.
#ifdef __WXOSX__
    if( !IsMaximized() )
#endif
    {
        m_normalFrameSize = GetWindowSize();
        m_normalFramePos  = GetPosition();
        wxLogTrace( traceDisplayLocation,
                    "Maximizing window - Saving position (%d, %d) with size (%d, %d)",
                    m_normalFramePos.x, m_normalFramePos.y,
                    m_normalFrameSize.x, m_normalFrameSize.y );
    }

    // Skip event to actually maximize the window
    aEvent.Skip();
}


wxSize EDA_BASE_FRAME::GetWindowSize()
{
#ifdef __WXGTK__
    wxSize winSize = GetSize();

    // GTK includes the window decorations in the normal GetSize call,
    // so we have to use a GTK-specific sizing call that returns the
    // non-decorated window size.
    if( m_ident == KICAD_MAIN_FRAME_T )
    {
        int width  = 0;
        int height = 0;
        GTKDoGetSize( &width, &height );

        winSize.Set( width, height );
    }
#else
    wxSize winSize = GetSize();
#endif

    return winSize;
}


void EDA_BASE_FRAME::HandleSystemColorChange()
{
    // Update the icon theme when the system theme changes and update the toolbars
    GetBitmapStore()->ThemeChanged();
    ThemeChanged();

    // This isn't handled by ThemeChanged()
    if( GetMenuBar() )
    {
        // For icons in menus, icon scaling & hotkeys
        ReCreateMenuBar();
        GetMenuBar()->Refresh();
    }
}


void EDA_BASE_FRAME::onSystemColorChange( wxSysColourChangedEvent& aEvent )
{
    // Call the handler to update the colors used in the frame
    HandleSystemColorChange();

    // Skip the change event to ensure the rest of the window controls get it
    aEvent.Skip();
}


void EDA_BASE_FRAME::onIconize( wxIconizeEvent& aEvent )
{
    // Call the handler
    handleIconizeEvent( aEvent );

    // Skip the event.
    aEvent.Skip();
}


#ifdef __WXMSW__
WXLRESULT EDA_BASE_FRAME::MSWWindowProc( WXUINT message, WXWPARAM wParam, WXLPARAM lParam )
{
    // This will help avoid the menu keeping focus when the alt key is released
    // You can still trigger accelerators as long as you hold down alt
    if( message == WM_SYSCOMMAND )
    {
        if( wParam == SC_KEYMENU && ( lParam >> 16 ) <= 0 )
            return 0;
    }

    return wxFrame::MSWWindowProc( message, wParam, lParam );
}
#endif


void EDA_BASE_FRAME::AddMenuLanguageList( ACTION_MENU* aMasterMenu, TOOL_INTERACTIVE* aControlTool )
{
    ACTION_MENU* langsMenu = new ACTION_MENU( false, aControlTool );
    langsMenu->SetTitle( _( "Set Language" ) );
    langsMenu->SetIcon( BITMAPS::language );

    wxString tooltip;

    for( unsigned ii = 0; LanguagesList[ii].m_KI_Lang_Identifier != 0; ii++ )
    {
        wxString label;

        if( LanguagesList[ii].m_DoNotTranslate )
            label = LanguagesList[ii].m_Lang_Label;
        else
            label = wxGetTranslation( LanguagesList[ii].m_Lang_Label );

        wxMenuItem* item =
                new wxMenuItem( langsMenu,
                                LanguagesList[ii].m_KI_Lang_Identifier, // wxMenuItem wxID
                                label, tooltip, wxITEM_CHECK );

        langsMenu->Append( item );
    }

    // This must be done after the items are added
    aMasterMenu->Add( langsMenu );
}