File: frame.py

package info (click to toggle)
grass 8.4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 277,040 kB
  • sloc: ansic: 460,798; python: 227,732; cpp: 42,026; sh: 11,262; makefile: 7,007; xml: 3,637; sql: 968; lex: 520; javascript: 484; yacc: 450; asm: 387; perl: 157; sed: 25; objc: 6; ruby: 4
file content (2466 lines) | stat: -rw-r--r-- 86,782 bytes parent folder | download | duplicates (2)
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
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
"""
@package main_window::frame

@brief Single Window layout - main menu, main toolbars, dockable
panes for display management and access to command console.

Classes:
 - frame::GMFrame
 - frame::SingleWindowAuiManager

(C) 2006-2021 by the GRASS Development Team

This program is free software under the GNU General Public License
(>=v2). Read the file COPYING that comes with GRASS for details.

@author Michael Barton (Arizona State University)
@author Jachym Cepicky (Mendel University of Agriculture)
@author Martin Landa <landa.martin gmail.com>
@author Vaclav Petras <wenzeslaus gmail.com> (menu customization)
"""

import sys
import os
import stat
import platform
import re

from core import globalvar

try:
    from agw import aui
except ImportError:
    import wx.lib.agw.aui as aui

import wx

try:
    import wx.lib.agw.flatnotebook as FN
except ImportError:
    import wx.lib.flatnotebook as FN

if os.path.join(globalvar.ETCDIR, "python") not in sys.path:
    sys.path.append(os.path.join(globalvar.ETCDIR, "python"))

from grass.script import core as grass
from grass.script.utils import decode

from core.gcmd import RunCommand, GError, GMessage
from core.settings import UserSettings, GetDisplayVectSettings
from core.utils import SetAddOnPath, GetLayerNameFromCmd, command2ltype, get_shell_pid
from core.watchdog import (
    EVT_UPDATE_MAPSET,
    EVT_CURRENT_MAPSET_CHANGED,
    MapsetWatchdog,
)
from gui_core.preferences import MapsetAccess, PreferencesDialog
from lmgr.layertree import LayerTree, LMIcons
from lmgr.menudata import LayerManagerMenuData, LayerManagerModuleTree
from main_window.notebook import MainNotebook
from gui_core.widgets import GNotebook
from core.gconsole import GConsole, EVT_IGNORED_CMD_RUN
from core.giface import Notification
from gui_core.goutput import GConsoleWindow, GC_PROMPT
from gui_core.dialogs import (
    LocationDialog,
    MapsetDialog,
    CreateNewVector,
    GroupDialog,
    MapLayersDialog,
    QuitDialog,
)
from gui_core.menu import SearchModuleWindow, Menu as GMenu
from core.debug import Debug
from lmgr.toolbars import LMWorkspaceToolbar, LMToolsToolbar
from lmgr.toolbars import LMMiscToolbar, LMNvizToolbar, DisplayPanelToolbar
from lmgr.statusbar import SbMain
from lmgr.workspace import WorkspaceManager
from lmgr.pyshell import PyShellWindow
from lmgr.giface import LayerManagerGrassInterface
from mapdisp.frame import MapPanel
from datacatalog.catalog import DataCatalog
from history.browser import HistoryBrowser
from gui_core.forms import GUI
from gui_core.wrap import Menu, TextEntryDialog, SimpleTabArt
from startup.guiutils import (
    can_switch_mapset_interactive,
    switch_mapset_interactively,
    create_mapset_interactively,
    create_location_interactively,
)
from grass.grassdb.checks import is_first_time_user
from grass.grassdb.history import Status


class SingleWindowAuiManager(aui.AuiManager):
    """Custom AuiManager class which override OnClose window
    close event handler method to prevent prematurely uninitialize
    manager

    https://github.com/wxWidgets/Phoenix/pull/2460
    """

    def OnClose(self, event):
        event.Skip()


class GMFrame(wx.Frame):
    """Single Window Layout which will be parallelly developed next to the
    current Multi Window layout solution."""

    def __init__(
        self,
        parent,
        id=wx.ID_ANY,
        title=None,
        workspace=None,
        size=wx.GetClientDisplayRect().GetSize(),
        style=wx.DEFAULT_FRAME_STYLE,
        **kwargs,
    ):
        self.parent = parent
        if title:
            self.baseTitle = title
        else:
            self.baseTitle = _("GRASS GIS")

        self.iconsize = (16, 16)
        self.size = size

        self.displayIndex = 0  # index value for map displays and layer trees
        self.currentPage = None  # currently selected page for layer tree notebook
        self.currentPageNum = (
            None  # currently selected page number for layer tree notebook
        )
        self.cwdPath = None  # current working directory

        wx.Frame.__init__(self, parent=parent, id=id, size=size, style=style, **kwargs)

        self._giface = LayerManagerGrassInterface(self)

        # workspace manager
        self.workspace_manager = WorkspaceManager(lmgr=self, giface=self._giface)
        self._setTitle()
        self.SetName("LayerManager")

        self.SetIcon(
            wx.Icon(os.path.join(globalvar.ICONDIR, "grass.ico"), wx.BITMAP_TYPE_ICO)
        )

        menu_errors = []

        def add_menu_error(message):
            menu_errors.append(message)

        def show_menu_errors(messages):
            if messages:
                self._gconsole.WriteError(
                    _("There were some issues when loading menu" " or Tools:")
                )
                for message in messages:
                    self._gconsole.WriteError(message)

        # the main menu bar
        self._menuTreeBuilder = LayerManagerMenuData(message_handler=add_menu_error)
        # the search tree and command console
        self._moduleTreeBuilder = LayerManagerModuleTree(message_handler=add_menu_error)
        self._auimgr = SingleWindowAuiManager(self)

        # list of open dialogs
        self.dialogs = dict()
        self.dialogs["preferences"] = None
        self.dialogs["nvizPreferences"] = None
        self.dialogs["atm"] = list()

        # set pane sizes according to the full screen size of the primary monitor
        self.PANE_BEST_SIZE = tuple(t // 5 for t in self.size)
        self.PANE_MIN_SIZE = tuple(t // 8 for t in self.size)

        # create widgets and build panes
        self.CreateMenuBar()
        self.workspace_manager.CreateRecentFilesMenu(
            menu=self.menubar,
        )
        self.BuildPanes()
        self.BindEvents()

        self._giface.mapCreated.connect(self.OnMapCreated)
        self._giface.updateMap.connect(self._updateCurrentMap)
        self._giface.currentMapsetChanged.connect(self.OnMapsetChanged)

        # use default window layout ?
        if UserSettings.Get(group="general", key="defWindowPos", subkey="enabled"):
            single_window_dim = {
                "group": "general",
                "key": "defWindowPos",
                "subkey": "dimSingleWindow",
            }
            dim = UserSettings.Get(**single_window_dim)
            default_dim = UserSettings.Get(**single_window_dim, settings_type="default")

            if dim != default_dim:
                try:
                    x, y, w, h = map(int, dim.split(",")[:4])
                    client_disp = wx.ClientDisplayRect()
                    if x == 1:
                        # Get client display x offset (OS panel)
                        x = client_disp[0]
                    if y == 1:
                        # Get client display y offset (OS panel)
                        y = client_disp[1]
                    self.SetPosition((x, y))
                    self.SetSize((w, h))
                except Exception:
                    pass
            else:
                self.Maximize(True)
        else:
            self.Maximize(True)
        self.Show()

        # load workspace file if requested
        if workspace:
            if self.workspace_manager.Load(workspace):
                self._setTitle()
        else:
            # start default initial display
            self.NewDisplay(show=False)

        # show map display window
        # -> OnSize() -> UpdateMap()
        for mapdisp in self.GetMapDisplay(onlyCurrent=False):
            mapdisp.Show()

        # redirect stderr to log area
        self._gconsole.Redirect()

        #  mapset watchdog
        self._mapset_watchdog = MapsetWatchdog(
            elements_dirs=(("raster", "cell"),),
            evt_handler=self,
            giface=self._giface,
        )
        self._mapset_watchdog.ScheduleWatchCurrentMapset()
        self.Bind(
            EVT_UPDATE_MAPSET,
            lambda evt: self._onMapsetWatchdog(evt.src_path, evt.dest_path),
        )
        self.Bind(EVT_CURRENT_MAPSET_CHANGED, self._onMapsetChanged)
        # fix goutput's pane size (required for Mac OSX)`
        self.goutput.SetSashPosition(int(self.GetSize()[1] * 0.8))

        show_menu_errors(menu_errors)

        # start with layer manager on top
        if self.currentPage:
            self.GetMapDisplay().Raise()
        wx.CallAfter(self.Raise)

        self._show_demo_map()

    def _repaintLayersPaneMapDisplayToolbar(self):
        """Repaint Layers pane map display toolbar widget on the wxMac"""
        if sys.platform == "darwin":
            wx.CallLater(100, self.notebookLayers.Refresh)

    def _setTitle(self):
        """Set frame title"""
        gisenv = grass.gisenv()
        location = gisenv["LOCATION_NAME"]
        mapset = gisenv["MAPSET"]
        if self.workspace_manager.workspaceFile:
            filename = os.path.splitext(
                os.path.basename(self.workspace_manager.workspaceFile)
            )[0]
            self.SetTitle(
                "{workspace} - {location}/{mapset} - {program}".format(
                    location=location,
                    mapset=mapset,
                    workspace=filename,
                    program=self.baseTitle,
                )
            )
        else:
            self.SetTitle(
                "{location}/{mapset} - {program}".format(
                    location=location, mapset=mapset, program=self.baseTitle
                )
            )

    def CreateMenuBar(self):
        """Creates menu bar"""
        self.menubar = GMenu(
            parent=self, model=self._menuTreeBuilder.GetModel(separators=True)
        )
        self.SetMenuBar(self.menubar)
        self.menucmd = self.menubar.GetCmd()

    def _createTabMenu(self):
        """Creates context menu for display tabs.

        Used to rename display.
        """
        menu = Menu()
        item = wx.MenuItem(menu, id=wx.ID_ANY, text=_("Rename current Map Display"))
        menu.AppendItem(item)
        self.Bind(wx.EVT_MENU, self.OnRenameDisplay, item)

        return menu

    def _setCopyingOfSelectedText(self):
        copy = UserSettings.Get(
            group="manager", key="copySelectedTextToClipboard", subkey="enabled"
        )
        self.goutput.SetCopyingOfSelectedText(copy)

    def IsPaneShown(self, name):
        """Check if pane (toolbar, ...) of given name is currently shown"""
        if self._auimgr.GetPane(name).IsOk():
            return self._auimgr.GetPane(name).IsShown()
        return False

    def SetStatusText(self, *args):
        """Override SbMain statusbar method"""
        self.statusbar.SetStatusText(*args)

    def _createMainNotebook(self):
        """Create Map Display notebook"""
        # create the notebook off-window to avoid flicker
        self.mainnotebook = MainNotebook(parent=self)

    def _createDataCatalog(self, parent):
        """Initialize Data Catalog widget"""
        self.datacatalog = DataCatalog(parent=parent, giface=self._giface)
        self.datacatalog.showNotification.connect(
            lambda message: self.SetStatusText(message)
        )

    def _createDisplay(self, parent):
        """Initialize Display widget"""
        # create display notebook
        self.notebookLayers = GNotebook(parent=parent, style=globalvar.FNPageStyle)
        menu = self._createTabMenu()
        self.notebookLayers.SetRightClickMenu(menu)
        # bindings
        self.notebookLayers.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnCBPageChanged)
        self.notebookLayers.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnCBPageClosing)
        self.notebookLayers.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CLOSED, self.OnCBPageClosed)

    def _createSearchModule(self, parent):
        """Initialize Search module widget"""
        if not UserSettings.Get(group="manager", key="hideTabs", subkey="search"):
            self.search = SearchModuleWindow(
                parent=parent,
                handlerObj=self,
                giface=self._giface,
                model=self._moduleTreeBuilder.GetModel(),
            )
            self.search.showNotification.connect(
                lambda message: self.SetStatusText(message)
            )
        else:
            self.search = None

    def _createConsole(self, parent):
        """Initialize Console widget"""
        # create 'command output' text area
        self._gconsole = GConsole(
            guiparent=self,
            giface=self._giface,
            ignoredCmdPattern=globalvar.ignoredCmdPattern,
        )
        # create 'console' widget
        self.goutput = GConsoleWindow(
            parent=parent,
            giface=self._giface,
            gconsole=self._gconsole,
            menuModel=self._moduleTreeBuilder.GetModel(),
            gcstyle=GC_PROMPT,
        )
        self.goutput.showNotification.connect(
            lambda message: self.SetStatusText(message)
        )
        self.goutput.contentChanged.connect(
            lambda notification: self._focusPage(notification)
        )

        self._gconsole.mapCreated.connect(self.OnMapCreated)
        self._gconsole.Bind(
            EVT_IGNORED_CMD_RUN, lambda event: self.RunSpecialCmd(event.cmd)
        )

        self._setCopyingOfSelectedText()

    def _createHistoryBrowser(self, parent):
        """Initialize history browser widget"""
        if not UserSettings.Get(group="manager", key="hideTabs", subkey="history"):
            self.history = HistoryBrowser(parent=parent, giface=self._giface)
            self.history.showNotification.connect(
                lambda message: self.SetStatusText(message)
            )
            self.history.runIgnoredCmdPattern.connect(
                lambda cmd: self.RunSpecialCmd(command=cmd),
            )
        else:
            self.history = None

    def _createPythonShell(self, parent):
        """Initialize Python shell widget"""
        if not UserSettings.Get(group="manager", key="hideTabs", subkey="pyshell"):
            self.pyshell = PyShellWindow(
                parent=parent,
                giface=self._giface,
                simpleEditorHandler=self.OnSimpleEditor,
            )
        else:
            self.pyshell = None

    def OnNewDisplay(self, event=None):
        """Create new layer tree and map display window instance"""
        self.NewDisplay()

    def NewDisplay(self, name=None, show=True):
        """Create new layer tree structure and associated map display and
        add it to display notebook tab
        :param name: name of new map display window
        :param show: show map display window if True
        """
        Debug.msg(1, "GMFrame.NewDisplay(): idx=%d" % self.displayIndex)
        if not name:
            name = _("Map Display {number}").format(number=self.displayIndex + 1)

        # make a new page in the bookcontrol for the layer tree (on page 0 of
        # the notebook)
        self.pg_panel = wx.Panel(
            self.notebookLayers, id=wx.ID_ANY, style=wx.BORDER_NONE
        )
        # create display toolbar
        dmgrToolbar = DisplayPanelToolbar(guiparent=self.pg_panel, parent=self)

        self.notebookLayers.AddPage(page=self.pg_panel, text=name, select=True)
        self.currentPage = self.notebookLayers.GetCurrentPage()
        self.currentPageNum = self.notebookLayers.GetSelection()
        self.notebookLayers.EnsureVisible(self.currentPageNum)

        def CreateNewMapDisplay(giface, layertree):
            """Callback function which creates a new Map Display window
            :param giface: giface for map display
            :param layertree: layer tree object
            :return: reference to mapdisplay instance
            """

            # create Map Display
            mapdisplay = MapPanel(
                parent=self.mainnotebook,
                giface=giface,
                id=wx.ID_ANY,
                tree=layertree,
                lmgr=self,
                Map=layertree.Map,
                dockable=True,
                title=name,
                size=globalvar.MAP_WINDOW_SIZE,
            )
            # add map display panel to notebook and make it current
            self.mainnotebook.AddPage(mapdisplay, name)

            # set map display properties
            self._setUpMapDisplay(mapdisplay)

            return mapdisplay

        # create layer tree (tree control for managing GIS layers)  and put on
        # new notebook page and new map display frame
        self.currentPage.maptree = LayerTree(
            parent=self.currentPage,
            giface=self._giface,
            createNewMapDisplay=CreateNewMapDisplay,
            id=wx.ID_ANY,
            pos=wx.DefaultPosition,
            size=wx.DefaultSize,
            style=wx.TR_HAS_BUTTONS
            | wx.TR_LINES_AT_ROOT
            | wx.TR_HIDE_ROOT
            | wx.TR_DEFAULT_STYLE
            | wx.NO_BORDER
            | wx.FULL_REPAINT_ON_RESIZE,
            lmgr=self,
            notebook=self.notebookLayers,
            title=name,
        )

        # layout for controls
        cb_boxsizer = wx.BoxSizer(wx.VERTICAL)
        cb_boxsizer.Add(dmgrToolbar, proportion=0, flag=wx.EXPAND)
        cb_boxsizer.Add(self.GetLayerTree(), proportion=1, flag=wx.EXPAND, border=1)
        self.currentPage.SetSizer(cb_boxsizer)
        cb_boxsizer.Fit(self.GetLayerTree())
        self.currentPage.Layout()
        self.GetLayerTree().Layout()
        # Repaint Layers pane map display toolbar widget on the wxMac
        self._repaintLayersPaneMapDisplayToolbar()

        self.displayIndex += 1

        return self.GetMapDisplay()

    def _setUpMapDisplay(self, mapdisplay):
        """Set up Map Display properties"""
        page = self.currentPage

        def CanCloseDisplay(askIfSaveWorkspace):
            """Callback to check if user wants to close display. Map
            Display index can be different from index in Display tab.

            :return dict/None pgnum_dict/None: dict "layers" key represent
                                               map display notebook layers
                                               tree page index and
                                               "mainnotebook" key represent
                                               map display notebook page
                                               index (single window mode)
            """
            pgnum_dict = {}
            pgnum_dict["layers"] = self.notebookLayers.GetPageIndex(page)
            pgnum_dict["mainnotebook"] = self.mainnotebook.GetPageIndex(mapdisplay)
            name = self.notebookLayers.GetPageText(pgnum_dict["layers"])
            caption = _("Close Map Display {}").format(name)
            if not askIfSaveWorkspace or (
                askIfSaveWorkspace and self.workspace_manager.CanClosePage(caption)
            ):
                return pgnum_dict
            return None

        mapdisplay.SetUpPage(self, self.mainnotebook, CanCloseDisplay)

        # bind various events
        mapdisplay.onFocus.connect(
            lambda page=self.currentPage: self._onMapDisplayFocus(page),
        )

        mapdisplay.starting3dMode.connect(
            lambda firstTime, mapDisplayPage=self.currentPage: self._onStarting3dMode(
                mapDisplayPage
            )
        )
        mapdisplay.starting3dMode.connect(self.AddNvizTools)
        mapdisplay.ending3dMode.connect(self.RemoveNvizTools)

        # set default properties
        mapdisplay.SetProperties(
            render=UserSettings.Get(
                group="display", key="autoRendering", subkey="enabled"
            ),
            mode=UserSettings.Get(
                group="display", key="statusbarMode", subkey="selection"
            ),
            alignExtent=UserSettings.Get(
                group="display", key="alignExtent", subkey="enabled"
            ),
            constrainRes=UserSettings.Get(
                group="display", key="compResolution", subkey="enabled"
            ),
            showCompExtent=UserSettings.Get(
                group="display", key="showCompExtent", subkey="enabled"
            ),
        )

    def BuildPanes(self):
        """Build panes - toolbars as well as panels"""
        self._auimgr.SetAutoNotebookTabArt(SimpleTabArt())
        # initialize all main widgets
        self.statusbar = SbMain(parent=self, giface=self._giface)
        self._createMainNotebook()
        self._createDataCatalog(parent=self)
        self._createDisplay(parent=self)
        self._createSearchModule(parent=self)
        self._createConsole(parent=self)
        self._createHistoryBrowser(parent=self)
        self._createPythonShell(parent=self)
        self.toolbars = {
            "workspace": LMWorkspaceToolbar(parent=self),
            "tools": LMToolsToolbar(parent=self),
            "misc": LMMiscToolbar(parent=self),
            "nviz": LMNvizToolbar(parent=self),
        }
        self._toolbarsData = {
            "workspace": (
                "toolbarWorkspace",  # name
                _("Workspace Toolbar"),  # caption
                1,
                0,
            ),  # row, position
            "tools": ("toolbarTools", _("Tools Toolbar"), 1, 1),
            "misc": ("toolbarMisc", _("Misc Toolbar"), 1, 2),
            "nviz": ("toolbarNviz", _("3D view Toolbar"), 1, 3),
        }

        # add a bunch of panes
        toolbarsList = ("workspace", "tools", "misc", "nviz")
        for toolbar in toolbarsList:
            name, caption, row, position = self._toolbarsData[toolbar]
            self._auimgr.AddPane(
                self.toolbars[toolbar],
                aui.AuiPaneInfo()
                .Name(name)
                .Caption(caption)
                .ToolbarPane()
                .Top()
                .Row(row)
                .Position(position)
                .LeftDockable(False)
                .RightDockable(False)
                .BottomDockable(False)
                .TopDockable(True)
                .CloseButton(False)
                .Layer(2)
                .BestSize(self.toolbars[toolbar].GetBestSize()),
            )

        self._auimgr.AddPane(
            self.mainnotebook,
            aui.AuiPaneInfo().Name("map display content").CenterPane().PaneBorder(True),
        )

        self._auimgr.AddPane(
            self.statusbar.GetWidget(),
            aui.AuiPaneInfo()
            .Bottom()
            .MinSize(30, 30)
            .Fixed()
            .Name("statusbar")
            .CloseButton(False)
            .DestroyOnClose(True)
            .ToolbarPane()
            .Dockable(False)
            .PaneBorder(False)
            .Gripper(False),
        )

        self._auimgr.AddPane(
            self.datacatalog,
            aui.AuiPaneInfo()
            .Name("datacatalog")
            .Caption(_("Data"))
            .Left()
            .Layer(1)
            .Position(1)
            .BestSize(self.PANE_BEST_SIZE)
            .MinSize(self.PANE_MIN_SIZE)
            .CloseButton(False)
            .MinimizeButton(True)
            .MaximizeButton(True),
        )

        self._auimgr.AddPane(
            self.notebookLayers,
            aui.AuiPaneInfo()
            .Name("layers")
            .Caption(_("Layers"))
            .Left()
            .Layer(1)
            .Position(2)
            .BestSize(self.PANE_BEST_SIZE)
            .MinSize(self.PANE_MIN_SIZE)
            .CloseButton(False)
            .MinimizeButton(True)
            .MaximizeButton(True),
        )

        self._auimgr.AddPane(
            self.search,
            aui.AuiPaneInfo()
            .Name("tools")
            .Caption(_("Tools"))
            .Right()
            .Layer(1)
            .Position(1)
            .BestSize(self.PANE_BEST_SIZE)
            .MinSize(self.PANE_MIN_SIZE)
            .CloseButton(False)
            .MinimizeButton(True)
            .MaximizeButton(True),
        )

        self._auimgr.AddPane(
            self.goutput,
            aui.AuiPaneInfo()
            .Name("console")
            .Caption(_("Console"))
            .Right()
            .BestSize(self.PANE_BEST_SIZE)
            .MinSize(self.PANE_MIN_SIZE)
            .CloseButton(False)
            .MinimizeButton(True)
            .MaximizeButton(True),
            target=self._auimgr.GetPane("tools"),
        )

        self._auimgr.AddPane(
            self.history,
            aui.AuiPaneInfo()
            .Name("history")
            .Caption(_("History"))
            .Right()
            .BestSize(self.PANE_BEST_SIZE)
            .MinSize(self.PANE_MIN_SIZE)
            .CloseButton(False)
            .MinimizeButton(True)
            .MaximizeButton(True),
            target=self._auimgr.GetPane("tools"),
        )

        self._auimgr.AddPane(
            self.pyshell,
            aui.AuiPaneInfo()
            .Name("python")
            .Caption(_("Python"))
            .Right()
            .BestSize(self.PANE_BEST_SIZE)
            .MinSize(self.PANE_MIN_SIZE)
            .CloseButton(False)
            .MinimizeButton(True)
            .MaximizeButton(True),
            target=self._auimgr.GetPane("tools"),
        )

        self._auimgr.GetPane("toolbarNviz").Hide()

        # Set Tools as active tab
        notebooks = self._auimgr.GetNotebooks()
        if notebooks:
            notebook = notebooks[0]
            tools = self._auimgr.GetPane("tools")
            notebook.SetSelectionToPage(tools)

            # Set the size for automatic notebook
            pane = self._auimgr.GetPane(notebook)
            pane.BestSize(self.PANE_BEST_SIZE)
            pane.MinSize(self.PANE_MIN_SIZE)

        wx.CallAfter(self.datacatalog.LoadItems)

        single_win_panes_layout_pos_enabled = UserSettings.Get(
            group="general",
            key="singleWinPanesLayoutPos",
            subkey="enabled",
        )

        single_win_panes_layout_pos = UserSettings.Get(
            group="general",
            key="singleWinPanesLayoutPos",
            subkey="pos",
        )
        if single_win_panes_layout_pos_enabled and single_win_panes_layout_pos:
            self._auimgr.LoadPerspective(single_win_panes_layout_pos)

        self._auimgr.Update()

    def BindEvents(self):
        # bindings
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindowOrExit)

    def _show_demo_map(self):
        """If in demolocation, add demo map to map display

        This provides content for first-time user experience.
        """

        def show_demo():
            layer_name = "country_boundaries@PERMANENT"
            exists = grass.find_file(name=layer_name, element="vector")["name"]
            if not exists:
                # Do not fail nor report errors to the first-time user when not found.
                Debug.msg(
                    5, "GMFrame._show_demo_map(): {} does not exist".format(layer_name)
                )
                return
            self.GetLayerTree().AddLayer(
                ltype="vector",
                lname=layer_name,
                lchecked=True,
                lcmd=["d.vect", "map={}".format(layer_name)],
            )

        if is_first_time_user():
            # Show only after everything is initialized for proper map alignment.
            wx.CallLater(1000, show_demo)

    def AddNvizTools(self, firstTime):
        """Add nviz notebook page

        :param firstTime: if a mapdisplay is starting 3D mode for the
                          first time
        """
        Debug.msg(5, "GMFrame.AddNvizTools()")
        from nviz.main import haveNviz

        if not haveNviz:
            return

        from nviz.main import NvizToolWindow

        # show toolbar
        self._auimgr.GetPane("toolbarNviz").Show()
        # reorder other toolbars
        for pos, toolbar in enumerate(
            ("toolbarWorkspace", "toolbarTools", "toolbarMisc", "toolbarNviz")
        ):
            self._auimgr.GetPane(toolbar).Row(1).Position(pos)

        # create nviz tools tab
        self.nviz = NvizToolWindow(
            parent=self, tree=self.GetLayerTree(), display=self.GetMapDisplay()
        )
        self._auimgr.AddPane(
            self.nviz,
            aui.AuiPaneInfo()
            .Name("nviz")
            .Caption("3D view")
            .Left()
            .Layer(1)
            .Position(3)
            .BestSize(self.PANE_BEST_SIZE)
            .MinSize(self.PANE_MIN_SIZE)
            .CloseButton(False)
            .MinimizeButton(True)
            .MaximizeButton(True),
        )

        self._auimgr.GetPane("nviz").Show()
        self._auimgr.Update()

        # this is a bit strange here since a new window is created every time
        if not firstTime:
            for page in ("view", "light", "fringe", "constant", "cplane", "animation"):
                self.nviz.UpdatePage(page)

    def RemoveNvizTools(self):
        """Remove nviz notebook page"""
        # if more mapwindow3D were possible, check here if nb page should be
        # removed

        # hide toolbar
        self._auimgr.GetPane("toolbarNviz").Hide()
        for pos, toolbar in enumerate(
            ("toolbarWorkspace", "toolbarTools", "toolbarMisc")
        ):
            self._auimgr.GetPane(toolbar).Row(1).Position(pos)
        self._auimgr.DetachPane(self.nviz)
        self.nviz.Destroy()
        self._auimgr.Update()

    def OnLocationWizard(self, event):
        """Launch location wizard"""
        gisenv = grass.gisenv()
        grassdb, location, mapset = create_location_interactively(
            self, gisenv["GISDBASE"]
        )
        if location:
            self._giface.grassdbChanged.emit(
                grassdb=grassdb, location=location, action="new", element="location"
            )
            if grassdb == gisenv["GISDBASE"]:
                switch_grassdb = None
            else:
                switch_grassdb = grassdb
            if can_switch_mapset_interactive(self, grassdb, location, mapset):
                switch_mapset_interactively(
                    self,
                    self._giface,
                    switch_grassdb,
                    location,
                    mapset,
                    show_confirmation=True,
                )

    def OnSettingsChanged(self):
        """Here can be functions which have to be called
        after receiving settingsChanged signal.
        Now only set copying of selected text to clipboard (in goutput).
        """
        # self._createMenuBar() # bug when menu is re-created on the fly
        self._setCopyingOfSelectedText()

    def OnGCPManager(self, event=None, cmd=None):
        """Launch georectifier module. See OnIClass documentation"""
        from gcp.manager import GCPWizard

        GCPWizard(self, self._giface)

    def OnGModeler(self, event=None, cmd=None):
        """Launch Graphical Modeler. See OnIClass documentation"""
        from gmodeler.panels import ModelerPanel
        from gmodeler.menudata import ModelerMenuData

        gmodeler_panel = ModelerPanel(
            parent=self, giface=self._giface, statusbar=self.statusbar, dockable=True
        )
        gmodeler_panel.SetUpPage(
            self,
            self.mainnotebook,
            menuModel=ModelerMenuData().GetModel(separators=True),
            menuName="&Modeler",
        )

        # add map display panel to notebook and make it current
        self.mainnotebook.AddPage(gmodeler_panel, _("Graphical Modeler"))

    def OnPsMap(self, event=None, cmd=None):
        """Launch Cartographic Composer. See OnIClass documentation"""
        from psmap.frame import PsMapFrame

        win = PsMapFrame(parent=self)
        win.CentreOnScreen()
        win.Show()

    def OnMapSwipe(self, event=None, cmd=None):
        """Launch Map Swipe. See OnIClass documentation"""
        from mapswipe.frame import SwipeMapDisplay

        frame = wx.Frame(
            parent=None, size=globalvar.MAP_WINDOW_SIZE, title=_("Map Swipe Tool")
        )
        win = SwipeMapDisplay(
            parent=frame,
            giface=self._giface,
        )

        rasters = []
        tree = self.GetLayerTree()
        if tree:
            for layer in tree.GetSelections():
                if tree.GetLayerInfo(layer, key="maplayer").GetType() != "raster":
                    continue
                rasters.append(tree.GetLayerInfo(layer, key="maplayer").GetName())

        if len(rasters) >= 1:
            win.SetFirstRaster(rasters[0])
        if len(rasters) >= 2:
            win.SetSecondRaster(rasters[1])
            win.SetRasterNames()

        win.CentreOnScreen()
        win.Show()

    def OnRLiSetup(self, event=None, cmd=None):
        """Launch r.li setup. See OnIClass documentation"""
        from rlisetup.frame import RLiSetupFrame

        win = RLiSetupFrame(parent=self)
        win.CentreOnScreen()
        win.Show()

    def OnDataCatalog(self, event=None, cmd=None):
        """Launch Data Catalog"""
        from datacatalog.frame import DataCatalogFrame

        win = DataCatalogFrame(parent=self, giface=self._giface)
        win.CentreOnScreen()
        win.Show()

    def OnDone(self, event):
        """Command execution finished"""
        if hasattr(self, "model"):
            self.model.DeleteIntermediateData(log=self._gconsole)
            del self.model
        self.SetStatusText("")

    def OnRunModel(self, event):
        """Run model"""
        filename = ""
        dlg = wx.FileDialog(
            parent=self,
            message=_("Choose model to run"),
            defaultDir=os.getcwd(),
            wildcard=_("GRASS Model File (*.gxm)|*.gxm"),
        )
        if dlg.ShowModal() == wx.ID_OK:
            filename = dlg.GetPath()

        if not filename:
            dlg.Destroy()
            return

        from gmodeler.model import Model

        self.model = Model()
        self.model.LoadModel(filename)
        self.model.Run(log=self.GetLogWindow(), onDone=self.OnDone, parent=self)
        dlg.Destroy()

    def OnMapsets(self, event):
        """Launch mapset access dialog"""
        dlg = MapsetAccess(parent=self, id=wx.ID_ANY)
        dlg.CenterOnScreen()

        if dlg.ShowModal() == wx.ID_OK:
            ms = dlg.GetMapsets()
            RunCommand(
                "g.mapsets", parent=self, mapset="%s" % ",".join(ms), operation="set"
            )

    def OnCBPageChanged(self, event):
        """Page in notebook (display) changed.
        Also change active map notebook tab."""
        self.currentPage = self.notebookLayers.GetCurrentPage()
        self.currentPageNum = self.notebookLayers.GetSelection()

        if hasattr(self.currentPage, "maptree") and self.mainnotebook.GetCurrentPage():
            self.mainnotebook.SetSelectionToMainPage(self.GetMapDisplay())

        event.Skip()

    def OnCBPageClosed(self, event):
        """Page of notebook has been closed from the Layers pane via x
        button or via closing map display notebook page"""
        # Repaint Layers pane map display toolbar widget on the wxMac
        self._repaintLayersPaneMapDisplayToolbar()

    def OnCBPageClosing(self, event):
        """Page of notebook is being closed
        from Layer Manager (x button next to arrows)
        Also close associated map display (whether docked or undocked).
        """
        # save changes in the workspace
        name = self.notebookLayers.GetPageText(event.GetSelection())
        caption = _("Close Map Display {}").format(name)
        if not self.workspace_manager.CanClosePage(caption):
            event.Veto()
            return

        maptree = self.notebookLayers.GetPage(event.GetSelection()).maptree
        maptree.GetMapDisplay().CleanUp()
        self.mainnotebook.DeleteMainPage(self.GetMapDisplay())
        maptree.Close(True)

        self.currentPage = None

        event.Skip()

    def _renamePageNoEvent(self, pgnum_dict, is_docked, text):
        if is_docked:
            self.mainnotebook.SetMainPageText(
                self.mainnotebook.GetPage(pgnum_dict["mainnotebook"]), text
            )

    def _closePageNoEvent(self, pgnum_dict, is_docked):
        """If map display is docked, close page and destroy map display without
        generating layer notebook page closing event. If map display is undocked,
        close only layer notebook page, not map notebook page.

        :param dict pgnum_dict: dict "layers" key represent map display
                                notebook layers tree page index and
                                "mainnotebook" key represent map display
                                notebook page index (single window mode)
              boolean is_docked: "True" means that map display is docked in map
                               display notebook, "False" means that map display
                               is undocked to independent frame
        """
        self.notebookLayers.Unbind(FN.EVT_FLATNOTEBOOK_PAGE_CLOSING)
        if "layers" in pgnum_dict:
            self.notebookLayers.DeletePage(pgnum_dict["layers"])
        self.notebookLayers.Bind(
            FN.EVT_FLATNOTEBOOK_PAGE_CLOSING,
            self.OnCBPageClosing,
        )
        if is_docked:
            self.mainnotebook.DeletePage(pgnum_dict["mainnotebook"])

    def _focusPage(self, notification):
        """Focus the 'Console' notebook page according to event notification."""
        if (
            notification == Notification.HIGHLIGHT
            or notification == Notification.MAKE_VISIBLE
            or notification == Notification.RAISE_WINDOW
        ):
            self.FocusPage("Console")

    def FocusPage(self, page_text):
        """Focus the page if part of any of aui notebooks"""
        notebooks = self._auimgr.GetNotebooks()
        for notebook in notebooks:
            for i in range(notebook.GetPageCount()):
                if notebook.GetPageText(i) == page_text:
                    notebook.SetSelection(i)

    def RunSpecialCmd(self, command):
        """Run command from command line, check for GUI wrappers"""
        result = True
        if re.compile(r"^d\..*").search(command[0]):
            result = self.RunDisplayCmd(command)
        elif re.compile(r"r[3]?\.mapcalc").search(command[0]):
            self.OnMapCalculator(event=None, cmd=command)
        elif command[0] == "i.group":
            self.OnEditImageryGroups(event=None, cmd=command)
        elif command[0] == "r.import":
            self.OnImportGdalLayers(event=None, cmd=command)
        elif command[0] == "r.external":
            self.OnLinkGdalLayers(event=None, cmd=command)
        elif command[0] == "r.external.out":
            self.OnRasterOutputFormat(event=None)
        elif command[0] == "v.import":
            self.OnImportOgrLayers(event=None, cmd=command)
        elif command[0] == "v.external":
            self.OnLinkOgrLayers(event=None, cmd=command)
        elif command[0] == "v.external.out":
            self.OnVectorOutputFormat(event=None)
        elif command[0] == "cd":
            self.OnChangeCWD(event=None, cmd=command)
        else:
            result = False
            raise ValueError(
                "Layer Manager special command (%s)"
                " not supported." % " ".join(command)
            )
        if result:
            self._gconsole.UpdateHistory(status=Status.SUCCESS)
        else:
            self._gconsole.UpdateHistory(status=Status.FAILED)

    def RunDisplayCmd(self, command):
        """Handles display commands.

        :param command: command in a list
        :return int: False if failed, True if succcess
        """
        if not self.currentPage:
            self.NewDisplay(show=True)
        # here should be the d.* commands which are not layers
        if command[0] == "d.erase":
            # rest of d.erase is ignored
            self.GetLayerTree().DeleteAllLayers()
            return False
        try:
            # display GRASS commands
            layertype = command2ltype[command[0]]
        except KeyError:
            GMessage(
                parent=self,
                message=_(
                    "Command '%s' not yet implemented in the WxGUI. "
                    "Try adding it as a command layer instead."
                )
                % command[0],
            )
            return False

        if layertype == "barscale":
            if len(command) > 1:
                self.GetMapDisplay().AddBarscale(cmd=command)
            else:
                self.GetMapDisplay().AddBarscale()
        elif layertype == "rastleg":
            if len(command) > 1:
                self.GetMapDisplay().AddLegendRast(cmd=command)
            else:
                self.GetMapDisplay().AddLegendRast()
        elif layertype == "vectleg":
            if len(command) > 1:
                self.GetMapDisplay().AddLegendVect(cmd=command, showDialog=False)
            else:
                self.GetMapDisplay().AddLegendVect(showDialog=True)
        elif layertype == "northarrow":
            if len(command) > 1:
                self.GetMapDisplay().AddArrow(cmd=command)
            else:
                self.GetMapDisplay().AddArrow()
        elif layertype == "text":
            if len(command) > 1:
                self.GetMapDisplay().AddDtext(cmd=command)
            else:
                self.GetMapDisplay().AddDtext()
        elif layertype == "redraw":
            self.GetMapDisplay().OnRender(None)
        elif layertype == "export":
            GUI(parent=self, show=False).ParseCommand(
                command, completed=(self.GetMapDisplay().DOutFileOptData, "", "")
            )
        elif layertype == "torast":
            if len(command) <= 1:
                task = GUI(parent=self, show=True).ParseCommand(
                    command, completed=(self.GetMapDisplay().DToRastOptData, "", "")
                )
            else:
                task = GUI(parent=self, show=None).ParseCommand(
                    command, completed=(self.GetMapDisplay().DToRastOptData, "", "")
                )
                self.GetMapDisplay().DToRast(command=task.get_cmd())
        else:
            # add layer into layer tree
            lname, found = GetLayerNameFromCmd(
                command, fullyQualified=True, layerType=layertype
            )
            self.GetLayerTree().AddLayer(
                ltype=layertype,
                lchecked=True if lname else None,
                lname=lname,
                lcmd=command,
            )
        return True

    def GetAuiManager(self):
        """Get aui manager

        :return: aui manager instance
        """
        return self._auimgr

    def GetAuiNotebook(self):
        """Get aui notebook

        :return: aui notebook instance
        """
        return self.mainnotebook

    def GetLayerNotebook(self):
        """Get Layers Notebook"""
        return self.notebookLayers

    def GetLayerTree(self):
        """Get current layer tree

        :return: LayerTree instance
        :return: None no layer tree selected
        """
        if self.currentPage:
            return self.currentPage.maptree
        return None

    def GetMapDisplay(self, onlyCurrent=True):
        """Get current map display

        :param bool onlyCurrent: True to return only active mapdisplay
                                 False for list of all mapdisplays

        :return: MapPanel instance (or list)
        :return: None no mapdisplay selected
        """
        if onlyCurrent:
            if self.currentPage:
                return self.GetLayerTree().GetMapDisplay()
            else:
                return None
        else:  # -> return list of all mapdisplays
            mlist = list()
            for idx in range(0, self.notebookLayers.GetPageCount()):
                mlist.append(self.notebookLayers.GetPage(idx).maptree.GetMapDisplay())

            return mlist

    def GetAllMapDisplays(self):
        """Get all (open) map displays"""
        return self.GetMapDisplay(onlyCurrent=False)

    def GetLogWindow(self):
        """Gets console for command output and messages"""
        return self._gconsole

    def GetToolbar(self, name):
        """Returns toolbar if exists else None"""
        if name in self.toolbars:
            return self.toolbars[name]

        return None

    def GetMenuCmd(self, event):
        """Get GRASS command from menu item

        :return: command as a list"""
        layer = None
        if event:
            cmd = self.menucmd[event.GetId()]
        else:
            cmd = ""

        try:
            cmdlist = cmd.split(" ")
        except Exception:  # already list?
            cmdlist = cmd

        # check list of dummy commands for GUI modules that do not have GRASS
        # bin modules or scripts.
        if cmd in ["vcolors", "r.mapcalc", "r3.mapcalc"]:
            return cmdlist

        try:
            layer = self.GetLayerTree().layer_selected
            name = self.GetLayerTree().GetLayerInfo(layer, key="maplayer").name
            type = self.GetLayerTree().GetLayerInfo(layer, key="type")
        except Exception:
            layer = None

        if layer and len(cmdlist) == 1:  # only if no parameters given
            if (type == "raster" and cmdlist[0][0] == "r" and cmdlist[0][1] != "3") or (
                type == "vector" and cmdlist[0][0] == "v"
            ):
                input = GUI().GetCommandInputMapParamKey(cmdlist[0])
                if input:
                    cmdlist.append("%s=%s" % (input, name))

        return cmdlist

    def RunMenuCmd(self, event=None, cmd=[]):
        """Run command selected from menu"""
        if event:
            cmd = self.GetMenuCmd(event)
        self._gconsole.RunCmd(cmd)

    def OnMenuCmd(self, event=None, cmd=[]):
        """Parse command selected from menu"""
        if event:
            cmd = self.GetMenuCmd(event)
        GUI(parent=self, giface=self._giface).ParseCommand(cmd)

    def OnVNet(self, event):
        """Vector network analysis tool"""
        if self.GetMapDisplay():
            self.GetMapDisplay().OnVNet(event)
        else:
            self.NewDisplay(show=True).OnVNet(event)

    def OnVDigit(self, event):
        """Start vector digitizer"""
        if not self.currentPage:
            self.MsgNoLayerSelected()
            return

        tree = self.GetLayerTree()
        layer = tree.layer_selected
        # no map layer selected
        if not layer:
            self.MsgNoLayerSelected()
            return

        # available only for vector map layers
        try:
            mapLayer = tree.GetLayerInfo(layer, key="maplayer")
        except Exception:
            mapLayer = None

        if not mapLayer or mapLayer.GetType() != "vector":
            GMessage(parent=self, message=_("Selected map layer is not vector."))
            return

        if mapLayer.GetMapset() != grass.gisenv()["MAPSET"]:
            GMessage(
                parent=self,
                message=_(
                    "Editing is allowed only for vector maps from the "
                    "current mapset."
                ),
            )
            return

        if not tree.GetLayerInfo(layer):
            return
        dcmd = tree.GetLayerInfo(layer, key="cmd")
        if not dcmd:
            return

        digitToolbar = self.GetMapDisplay().GetToolbar("vdigit")
        if digitToolbar:
            stopOnly = False
            if mapLayer is digitToolbar.GetLayer():
                stopOnly = True
            tree.OnStopEditing(None)  # TODO: change to signal
            if stopOnly:
                return

        tree.OnStartEditing(None)  # TODO: change to signal

    def OnRunScript(self, event):
        """Run user-defined script"""
        # open dialog and choose script file
        dlg = wx.FileDialog(
            parent=self,
            message=_("Choose script file to run"),
            defaultDir=os.getcwd(),
            wildcard=_("Python script (*.py)|*.py|Bash script (*.sh)|*.sh"),
        )

        filename = None
        if dlg.ShowModal() == wx.ID_OK:
            filename = dlg.GetPath()

        if not filename:
            return False

        if not os.path.exists(filename):
            GError(
                parent=self,
                message=_("Script file '%s' doesn't exist. " "Operation canceled.")
                % filename,
            )
            return

        # check permission
        if not os.access(filename, os.X_OK):
            dlg = wx.MessageDialog(
                self,
                message=_(
                    "Script <%s> is not executable. "
                    "Do you want to set the permissions "
                    "that allows you to run this script "
                    "(note that you must be the owner of the file)?"
                    % os.path.basename(filename)
                ),
                caption=_("Set permission?"),
                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION,
            )
            if dlg.ShowModal() != wx.ID_YES:
                return
            dlg.Destroy()
            try:
                mode = stat.S_IMODE(os.lstat(filename)[stat.ST_MODE])
                os.chmod(filename, mode | stat.S_IXUSR)
            except OSError:
                GError(_("Unable to set permission. Operation canceled."), parent=self)
                return

        # check GRASS_ADDON_PATH
        addonPath = os.getenv("GRASS_ADDON_PATH", [])
        if addonPath:
            addonPath = addonPath.split(os.pathsep)
        dirName = os.path.dirname(filename)
        if dirName not in addonPath:
            addonPath.append(dirName)
            dlg = wx.MessageDialog(
                self,
                message=_(
                    "Directory '%s' is not defined in GRASS_ADDON_PATH. "
                    "Do you want add this directory to GRASS_ADDON_PATH?"
                )
                % dirName,
                caption=_("Update Addons path?"),
                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION,
            )
            if dlg.ShowModal() == wx.ID_YES:
                SetAddOnPath(os.pathsep.join(addonPath), key="PATH")
            dlg.Destroy()

        self._gconsole.WriteCmdLog(_("Launching script '%s'...") % filename)
        self._gconsole.RunCmd([filename])

    def OnChangeLocation(self, event):
        """Change current location"""
        dlg = LocationDialog(parent=self)
        gisenv = grass.gisenv()

        if dlg.ShowModal() == wx.ID_OK:
            location, mapset = dlg.GetValues()
            dlg.Destroy()

            if not location or not mapset:
                GError(
                    parent=self,
                    message=_("No project provided. Operation canceled."),
                )
                return  # this should not happen
            if can_switch_mapset_interactive(
                self, gisenv["GISDBASE"], location, mapset
            ):
                switch_mapset_interactively(self, self._giface, None, location, mapset)

    def OnCreateMapset(self, event):
        """Create new mapset"""
        gisenv = grass.gisenv()
        mapset = create_mapset_interactively(
            self, gisenv["GISDBASE"], gisenv["LOCATION_NAME"]
        )
        if mapset:
            self._giface.grassdbChanged.emit(
                grassdb=gisenv["GISDBASE"],
                location=gisenv["LOCATION_NAME"],
                mapset=mapset,
                action="new",
                element="mapset",
            )
            if can_switch_mapset_interactive(
                self, gisenv["GISDBASE"], gisenv["LOCATION_NAME"], mapset
            ):
                switch_mapset_interactively(
                    self, self._giface, None, None, mapset, show_confirmation=True
                )

    def OnChangeMapset(self, event):
        """Change current mapset"""
        dlg = MapsetDialog(parent=self)
        gisenv = grass.gisenv()

        if dlg.ShowModal() == wx.ID_OK:
            mapset = dlg.GetMapset()
            dlg.Destroy()

            if not mapset:
                GError(
                    parent=self, message=_("No mapset provided. Operation canceled.")
                )
                return
            if can_switch_mapset_interactive(
                self, gisenv["GISDBASE"], gisenv["LOCATION_NAME"], mapset
            ):
                switch_mapset_interactively(self, self._giface, None, None, mapset)

    def OnMapsetChanged(self, dbase, location, mapset):
        """Current mapset changed.
        If location is None, mapset changed within location.
        """
        if not location:
            self._setTitle()
        else:
            # close current workspace and create new one
            self.OnWorkspaceClose()
            self.OnWorkspaceNew()

    def OnChangeCWD(self, event=None, cmd=None):
        """Change current working directory

        :param event: to be able to serve as a handler of wx event
        :param cmd: command as a list (must start with 'cd')
        """

        # local functions
        def write_beginning(parameter=None, command=None):
            if parameter:
                self._giface.WriteCmdLog('cd "' + parameter + '"')
            else:
                # naive concat but will be enough most of the time
                self._giface.WriteCmdLog(" ".join(command))

        def write_changed():
            self._giface.WriteLog(
                _('Working directory changed to:\n"%s"') % os.getcwd()
            )

        def write_end():
            self._giface.WriteCmdLog(" ")

        def write_help():
            self._giface.WriteLog(
                _("Changes current working directory" " for this GUI.")
            )
            self._giface.WriteLog(_("Usage: cd [directory]"))
            self._giface.WriteLog(_("Without parameters it opens a dialog."))
            # TODO: the following is longer then 80 chars
            # but this should be solved by the function not caller
            # also because of translations
            self._giface.WriteLog(
                _(
                    "If ~ (tilde) is present as the first"
                    " directory on the path, it is replaced"
                    " by user's home directory."
                )
            )

        # check correctness of cmd
        if cmd and cmd[0] != "cd":
            # this is programmer's error
            # can be relaxed in future
            # but keep it strict unless needed otherwise
            raise ValueError(
                "OnChangeCWD cmd parameter must be list of"
                " length 1 or 2 and 'cd' as a first item"
            )
        if cmd and len(cmd) > 2:
            # this might be a user error
            write_beginning(command=cmd)
            self._giface.WriteError(_("More than one parameter provided."))
            write_help()
            write_end()
            return
        # use chdir or dialog
        if cmd and len(cmd) == 2:
            write_beginning(parameter=cmd[1])
            if cmd[1] in ["-h", "--h", "--help", "help"]:
                write_help()
                write_end()
                return
            try:
                path = os.path.expanduser(cmd[1])
                os.chdir(path)
                write_changed()
            except OSError as error:
                self._giface.WriteError(str(error))
            write_end()
        else:
            dlg = wx.DirDialog(
                parent=self,
                message=_("Choose a working directory"),
                defaultPath=os.getcwd(),
            )

            if dlg.ShowModal() == wx.ID_OK:
                self.cwdPath = dlg.GetPath()  # is saved in the workspace
                write_beginning(parameter=self.cwdPath)
                os.chdir(self.cwdPath)
                write_changed()
                write_end()

    def GetCwdPath(self):
        """Get current working directory or None"""
        return self.cwdPath

    def OnNewVector(self, event):
        """Create new vector map layer"""
        dlg = CreateNewVector(
            self, giface=self._giface, cmd=(("v.edit", {"tool": "create"}, "map"))
        )

        if not dlg:
            return

        name = dlg.GetName(full=True)
        if name and dlg.IsChecked("add"):
            # add layer to map layer tree
            self.GetLayerTree().AddLayer(
                ltype="vector",
                lname=name,
                lchecked=True,
                lcmd=["d.vect", "map=%s" % name],
            )
        dlg.Destroy()

    def OnSystemInfo(self, event):
        """Print system information"""
        vInfo = grass.version()
        if not vInfo:
            sys.stderr.write(_("Unable to get GRASS version\n"))

        # check also OSGeo4W on MS Windows
        if sys.platform == "win32" and not os.path.exists(
            os.path.join(os.getenv("GISBASE"), "WinGRASS-README.url")
        ):
            osgeo4w = " (OSGeo4W)"
        else:
            osgeo4w = ""

        self._gconsole.WriteCmdLog(_("System Info"))
        # platform decoding was added because of the Fedora 19 release
        # which has the name "Schrödinger’s cat" (umlaut and special ' character)
        # which appears in the platform.platform() string
        platform_ = decode(platform.platform())
        self._gconsole.WriteLog(
            "%s: %s\n" "%s: %s\n" "%s: %s\n" "%s: %s\n"
            # "%s: %s (%s)\n"
            "GDAL: %s\n"
            "PROJ: %s\n"
            "GEOS: %s\n"
            "SQLite: %s\n"
            "Python: %s\n"
            "wxPython: %s\n"
            "%s: %s%s\n"
            % (
                _("GRASS version"),
                vInfo.get("version", _("unknown version")),
                _("Code revision"),
                vInfo.get("revision", "?"),
                _("Build date"),
                vInfo.get("build_date", "?"),
                _("Build platform"),
                vInfo.get("build_platform", "?"),
                # _("GIS Library Revision"),
                # vInfo.get('libgis_revision'],
                # vInfo.get('libgis_date'].split('
                # ', 1)[0],
                vInfo.get("gdal", "?"),
                vInfo.get("proj", "?"),
                vInfo.get("geos", "?"),
                vInfo.get("sqlite", "?"),
                platform.python_version(),
                wx.__version__,
                _("Platform"),
                platform_,
                osgeo4w,
            ),
            notification=Notification.MAKE_VISIBLE,
        )
        self._gconsole.WriteCmdLog(" ")

    def OnAboutGRASS(self, event):
        """Display 'About GRASS' dialog"""
        from gui_core.ghelp import AboutWindow

        win = AboutWindow(self)
        win.CentreOnScreen()
        win.Show(True)

    def _popupMenu(self, data):
        """Create popup menu"""
        menu = Menu()

        for key, handler in data:
            if key is None:
                menu.AppendSeparator()
                continue
            item = wx.MenuItem(menu, wx.ID_ANY, LMIcons[key].GetLabel())
            item.SetBitmap(LMIcons[key].GetBitmap(self.iconsize))
            menu.AppendItem(item)
            self.Bind(wx.EVT_MENU, handler, item)

        # create menu
        self.PopupMenu(menu)
        menu.Destroy()

    def OnWorkspaceNew(self, event=None):
        """Create new workspace file"""
        self.workspace_manager.New()

    def OnWorkspaceOpen(self, event=None):
        """Open file with workspace definition"""
        self.workspace_manager.Open()

    def OnWorkspaceSave(self, event=None):
        """Save file with workspace definition"""
        self.workspace_manager.Save()

    def OnWorkspaceSaveAs(self, event=None):
        """Save workspace definition to selected file"""
        self.workspace_manager.SaveAs()

    def OnWorkspaceClose(self, event=None):
        """Close file with workspace definition"""
        self.workspace_manager.Close()

    def OnDisplayClose(self, event=None):
        """Close current map display window"""
        if self.currentPage and self.GetMapDisplay():
            self.GetMapDisplay().OnCloseWindow(event)

    def OnDisplayCloseAll(self, event):
        """Close all open map display windows (from menu)"""
        if not self.workspace_manager.CanClosePage(caption=_("Close all Map Displays")):
            return
        self.DisplayCloseAll()

    def DisplayCloseAll(self):
        """Close all open map display windows"""
        for display in self.GetMapDisplay(onlyCurrent=False):
            display.OnCloseWindow(event=None, askIfSaveWorkspace=False)

    def OnRenderAllMapDisplays(self, event=None):
        for display in self.GetAllMapDisplays():
            display.OnRender(None)

    def OnRenameDisplay(self, event):
        """Change Map Display name"""
        name = self.notebookLayers.GetPageText(self.currentPageNum)
        dlg = TextEntryDialog(
            self,
            message=_("Enter new name:"),
            caption=_("Rename Map Display"),
            value=name,
        )
        if dlg.ShowModal() == wx.ID_OK:
            name = dlg.GetValue()
            self.notebookLayers.SetPageText(page=self.currentPageNum, text=name)
            self.mainnotebook.SetMainPageText(page=self.GetMapDisplay(), text=name)
        dlg.Destroy()

    def OnRasterRules(self, event):
        """Launches dialog for raster color rules"""
        from modules.colorrules import RasterColorTable

        ctable = RasterColorTable(self, layerTree=self.GetLayerTree())
        ctable.Show()
        ctable.CentreOnScreen()

    def OnVectorRules(self, event):
        """Launches dialog for vector color rules"""
        from modules.colorrules import VectorColorTable

        ctable = VectorColorTable(
            self, layerTree=self.GetLayerTree(), attributeType="color"
        )
        ctable.Show()
        ctable.CentreOnScreen()

    def OnEditImageryGroups(self, event, cmd=None):
        """Show dialog for creating and editing groups."""
        dlg = GroupDialog(self)
        dlg.CentreOnScreen()
        dlg.Show()

    def OnInstallExtension(self, event):
        """Install extension from GRASS Addons repository"""
        from modules.extensions import InstallExtensionWindow

        win = InstallExtensionWindow(self, giface=self._giface, size=(650, 550))
        win.CentreOnScreen()
        win.Show()

    def OnManageExtension(self, event):
        """Manage or uninstall extensions"""
        from modules.extensions import ManageExtensionWindow

        win = ManageExtensionWindow(self, size=(650, 300))
        win.CentreOnScreen()
        win.Show()

    def OnPreferences(self, event):
        """General GUI preferences/settings"""
        if not self.dialogs["preferences"]:
            dlg = PreferencesDialog(parent=self, giface=self._giface)
            self.dialogs["preferences"] = dlg
            self.dialogs["preferences"].CenterOnParent()

            dlg.settingsChanged.connect(self.OnSettingsChanged)
            self.Bind(
                wx.EVT_CLOSE, lambda evt: self.dialogs.update(preferences=None), dlg
            )

        self.dialogs["preferences"].Show()

    def OnNvizPreferences(self, event):
        """Show nviz preferences"""
        if not self.dialogs["nvizPreferences"]:
            from nviz.preferences import NvizPreferencesDialog

            dlg = NvizPreferencesDialog(parent=self, giface=self._giface)
            self.dialogs["nvizPreferences"] = dlg
            self.dialogs["nvizPreferences"].CenterOnScreen()
        self.dialogs["nvizPreferences"].Show()

    def OnHelp(self, event):
        """Show help"""
        self._gconsole.RunCmd(["g.manual", "-i"])

    def OnIClass(self, event=None, cmd=None):
        """Start wxIClass tool

        The parameters of all handlers which are associated with module
        and contained in menu/toolboxes must be event and cmd.
        When called from menu event is always None and cmd is the
        associated command (list containing a module name and parameters).

        .. todo::
            This documentation is actually documentation of some
            component related to gui_core/menu.py file.
        """
        from iclass.frame import IClassMapDisplay, haveIClass, errMsg

        if not haveIClass:
            GError(
                _('Unable to launch "Supervised Classification Tool".\n\n' "Reason: %s")
                % errMsg
            )
            return

        frame = wx.Frame(
            parent=None,
            size=globalvar.MAP_WINDOW_SIZE,
            title=_("Supervised Classification Tool"),
        )
        win = IClassMapDisplay(parent=frame, giface=self._giface)
        win.CentreOnScreen()

        win.Show()

    def OnAnimationTool(self, event=None, cmd=None):
        """Launch Animation tool. See OnIClass documentation."""
        from animation.frame import AnimationFrame

        frame = AnimationFrame(parent=self, giface=self._giface)
        frame.CentreOnScreen()
        frame.Show()

        tree = self.GetLayerTree()
        if tree:
            rasters = []
            for layer in tree.GetSelectedLayers(checkedOnly=False):
                if tree.GetLayerInfo(layer, key="type") == "raster":
                    rasters.append(tree.GetLayerInfo(layer, key="maplayer").GetName())
            if len(rasters) >= 2:
                from core.layerlist import LayerList
                from animation.data import AnimLayer

                layerList = LayerList()
                layer = AnimLayer()
                layer.mapType = "raster"
                layer.name = ",".join(rasters)
                layer.cmd = ["d.rast", "map="]
                layerList.AddLayer(layer)
                frame.SetAnimations([layerList, None, None, None])

    def OnTimelineTool(self, event=None, cmd=None):
        """Launch Timeline Tool"""
        try:
            from timeline.frame import TimelineFrame
        except ImportError:
            GError(parent=self, message=_("Unable to start Timeline Tool."))
            return
        frame = TimelineFrame(None)
        frame.Show()

    def OnTplotTool(self, event=None, cmd=None):
        """Launch Temporal Plot Tool"""
        try:
            from tplot.frame import TplotFrame
        except ImportError:
            GError(parent=self, message=_("Unable to start Temporal Plot Tool."))
            return
        frame = TplotFrame(parent=self, giface=self._giface)
        frame.Show()

    def OnHistogram(self, event):
        """Init histogram display canvas and tools"""
        from modules.histogram import HistogramFrame

        win = HistogramFrame(self, giface=self._giface)

        win.CentreOnScreen()
        win.Show()
        win.Refresh()
        win.Update()

    def OnMapCalculator(self, event, cmd=""):
        """Init map calculator for interactive creation of mapcalc statements"""
        from modules.mcalc_builder import MapCalcFrame

        if event:
            try:
                cmd = self.GetMenuCmd(event)
            except KeyError:
                cmd = ["r.mapcalc"]
        win = MapCalcFrame(parent=self, giface=self._giface, cmd=cmd[0])
        win.CentreOnScreen()
        win.Show()

    def OnRasterOutputFormat(self, event):
        """Set raster output format handler"""
        self.OnMenuCmd(cmd=["r.external.out"])

    def OnVectorOutputFormat(self, event):
        """Set vector output format handler"""
        from modules.import_export import GdalOutputDialog

        dlg = GdalOutputDialog(parent=self, ogr=True)
        dlg.CentreOnScreen()
        dlg.Show()

    def OnImportDxfFile(self, event, cmd=None):
        """Convert multiple DXF layers to GRASS vector map layers"""
        from modules.import_export import DxfImportDialog

        dlg = DxfImportDialog(parent=self, giface=self._giface)
        dlg.CentreOnScreen()
        dlg.Show()

    def OnImportGdalLayers(self, event, cmd=None):
        """Convert multiple GDAL layers to GRASS raster map layers"""
        from modules.import_export import GdalImportDialog

        dlg = GdalImportDialog(parent=self, giface=self._giface)
        dlg.CentreOnScreen()
        dlg.Show()

    def OnLinkGdalLayers(self, event, cmd=None):
        """Link multiple GDAL layers to GRASS raster map layers"""
        from modules.import_export import GdalImportDialog

        dlg = GdalImportDialog(parent=self, giface=self._giface, link=True)
        dlg.CentreOnScreen()
        dlg.Show()

    def OnImportOgrLayers(self, event, cmd=None):
        """Convert multiple OGR layers to GRASS vector map layers"""
        from modules.import_export import OgrImportDialog

        dlg = OgrImportDialog(parent=self, giface=self._giface)
        dlg.CentreOnScreen()
        dlg.Show()

    def OnLinkOgrLayers(self, event, cmd=None):
        """Links multiple OGR layers to GRASS vector map layers"""
        from modules.import_export import OgrImportDialog

        dlg = OgrImportDialog(parent=self, giface=self._giface, link=True)
        dlg.CentreOnScreen()
        dlg.Show()

    def OnAddWS(self, event, cmd=None):
        """Add web services layer"""
        from web_services.dialogs import AddWSDialog

        dlg = AddWSDialog(parent=self, giface=self._giface)
        dlg.CentreOnScreen()
        x, y = dlg.GetPosition()
        dlg.SetPosition((x, y - 200))
        dlg.Show()

    def OnSimpleEditor(self, event):
        # import on demand
        from gui_core.pyedit import PyEditFrame

        # we don't keep track of them and we don't care about open files
        # there when closing the main GUI
        simpleEditor = PyEditFrame(parent=self, giface=self._giface)
        simpleEditor.SetSize(self.GetSize())
        simpleEditor.CenterOnScreen()
        simpleEditor.Show()

    def OnShowAttributeTable(self, event, selection=None):
        """Show attribute table of the given vector map layer"""
        if not self.currentPage:
            self.MsgNoLayerSelected()
            return

        tree = self.GetLayerTree()
        layer = tree.layer_selected
        # no map layer selected
        if not layer:
            self.MsgNoLayerSelected()
            return

        # available only for vector map layers
        try:
            maptype = tree.GetLayerInfo(layer, key="maplayer").type
        except Exception:
            maptype = None

        if not maptype or maptype != "vector":
            GMessage(parent=self, message=_("Selected map layer is not vector."))
            return

        if not tree.GetLayerInfo(layer):
            return
        dcmd = tree.GetLayerInfo(layer, key="cmd")
        if not dcmd:
            return

        from dbmgr.manager import AttributeManager

        dbmanager = AttributeManager(
            parent=self,
            id=wx.ID_ANY,
            size=wx.Size(500, 300),
            item=layer,
            log=self._gconsole,
            selection=selection,
        )
        # register ATM dialog
        self.dialogs["atm"].append(dbmanager)
        # show ATM window
        dbmanager.Show()

    def _onMapDisplayFocus(self, notebookLayerPage):
        """Changes bookcontrol page to page associated with display."""
        # moved from mapdisp/frame.py
        # TODO: why it is called 3 times when getting focus?
        # and one times when loosing focus?
        pgnum = self.notebookLayers.GetPageIndex(notebookLayerPage)
        if pgnum > -1:
            self.notebookLayers.SetSelection(pgnum)
            self.currentPage = self.notebookLayers.GetCurrentPage()

    def _onStarting3dMode(self, mapDisplayPage):
        """Disables 3D mode for all map displays except for @p mapDisplay"""
        # TODO: it should be disabled also for newly created map windows
        # moreover mapdisp.Disable3dMode() does not work properly
        for page in range(0, self.GetLayerNotebook().GetPageCount()):
            mapdisp = self.GetLayerNotebook().GetPage(page).maptree.GetMapDisplay()
            if self.GetLayerNotebook().GetPage(page) != mapDisplayPage:
                mapdisp.Disable3dMode()

    def OnAddMaps(self, event=None):
        """Add selected map layers into layer tree"""
        dialog = MapLayersDialog(
            parent=self, title=_("Add selected map layers into layer tree")
        )
        dialog.applyAddingMapLayers.connect(self.AddMaps)
        val = dialog.ShowModal()

        if val == wx.ID_OK:
            self.AddMaps(dialog.GetMapLayers(), dialog.GetLayerType(cmd=True))
        dialog.Destroy()

    def AddMaps(self, mapLayers, ltype, check=False):
        """Add map layers to layer tree.

        :param list mapLayers: list of map names
        :param str ltype: layer type ('raster', 'raster_3d', 'vector')
        :param bool check: True if new layers should be checked in
                           layer tree False otherwise
        """
        # start new map display if no display is available
        if not self.currentPage:
            self.NewDisplay()

        maptree = self.GetLayerTree()

        for layerName in mapLayers:
            if ltype == "raster":
                cmd = ["d.rast", "map=%s" % layerName]
            elif ltype == "raster_3d":
                cmd = ["d.rast3d", "map=%s" % layerName]
            elif ltype == "vector":
                cmd = ["d.vect", "map=%s" % layerName] + GetDisplayVectSettings()
            else:
                GError(
                    parent=self, message=_("Unsupported map layer type <%s>.") % ltype
                )
                return

            maptree.AddLayer(
                ltype=ltype,
                lname=layerName,
                lchecked=check,
                lopacity=1.0,
                lcmd=cmd,
                lgroup=None,
            )

    def _updateCurrentMap(self, **kwargs):
        """Updates map of the current map window."""
        if "delay" in kwargs:
            self.GetMapDisplay().GetWindow().UpdateMap(delay=kwargs["delay"])
        else:
            self.GetMapDisplay().GetWindow().UpdateMap()

    def OnMapCreated(self, name, ltype, add=None):
        """Decides whether the map should be added to layer tree."""
        if add is None:
            # add new map into layer if globally enabled
            if UserSettings.Get(group="cmd", key="addNewLayer", subkey="enabled"):
                self.AddOrUpdateMap(name, ltype)
        elif add:
            # add new map into layer tree
            self.AddOrUpdateMap(name, ltype)
        else:
            # update the map
            display = self.GetMapDisplay()
            display.GetWindow().UpdateMap(render=True)

    def AddOrUpdateMap(self, mapName, ltype):
        """Add map layer or update"""
        # start new map display if no display is available
        if ltype not in ["raster", "raster_3d", "vector"]:
            GError(parent=self, message=_("Unsupported map layer type <%s>.") % ltype)
            return

        if not self.currentPage:
            self.AddMaps([mapName], ltype, check=True)
        else:
            display = self.GetMapDisplay()
            mapLayers = map(
                lambda x: x.GetName(), display.GetMap().GetListOfLayers(ltype=ltype)
            )
            if mapName in mapLayers:
                display.GetWindow().UpdateMap(render=True)
            else:
                self.AddMaps([mapName], ltype, check=True)

    def OnAddRaster(self, event):
        """Add raster map layer"""
        # start new map display if no display is available
        if not self.currentPage:
            self.NewDisplay(show=True)

        self.GetLayerTree().AddLayer("raster")

    def OnAddRasterMisc(self, event):
        """Create misc raster popup-menu"""
        # start new map display if no display is available
        if not self.currentPage:
            self.NewDisplay(show=True)

        self._popupMenu(
            (
                ("layerRaster_3d", self.OnAddRaster3D),
                (None, None),
                ("layerRgb", self.OnAddRasterRGB),
                ("layerHis", self.OnAddRasterHIS),
                (None, None),
                ("layerShaded", self.OnAddRasterShaded),
                (None, None),
                ("layerRastarrow", self.OnAddRasterArrow),
                ("layerRastnum", self.OnAddRasterNum),
            )
        )

    def OnAddVector(self, event):
        """Add vector map to the current layer tree"""
        # start new map display if no display is available
        if not self.currentPage:
            self.NewDisplay(show=True)

        self.GetLayerTree().AddLayer("vector")

    def OnAddVectorMisc(self, event):
        """Create misc vector popup-menu"""
        # start new map display if no display is available
        if not self.currentPage:
            self.NewDisplay(show=True)

        self._popupMenu(
            (
                ("layerThememap", self.OnAddVectorTheme),
                ("layerThemechart", self.OnAddVectorChart),
            )
        )

    def OnAddVectorTheme(self, event):
        """Add thematic vector map to the current layer tree"""
        self.GetLayerTree().AddLayer("thememap")

    def OnAddVectorChart(self, event):
        """Add chart vector map to the current layer tree"""
        self.GetLayerTree().AddLayer("themechart")

    def OnAddOverlay(self, event):
        """Create decoration overlay menu"""
        # start new map display if no display is available
        if not self.currentPage:
            self.NewDisplay(show=True)

        self._popupMenu(
            (
                ("layerGrid", self.OnAddGrid),
                ("layerLabels", self.OnAddLabels),
                ("layerGeodesic", self.OnAddGeodesic),
                ("layerRhumb", self.OnAddRhumb),
                (None, None),
                ("layerCmd", self.OnAddCommand),
            )
        )

    def OnAddRaster3D(self, event):
        """Add 3D raster map to the current layer tree"""
        self.GetLayerTree().AddLayer("raster_3d")

    def OnAddRasterRGB(self, event):
        """Add RGB raster map to the current layer tree"""
        self.GetLayerTree().AddLayer("rgb")

    def OnAddRasterHIS(self, event):
        """Add HIS raster map to the current layer tree"""
        self.GetLayerTree().AddLayer("his")

    def OnAddRasterShaded(self, event):
        """Add shaded relief raster map to the current layer tree"""
        self.GetLayerTree().AddLayer("shaded")

    def OnAddRasterArrow(self, event):
        """Add flow arrows raster map to the current layer tree"""
        # here it seems that it should be retrieved from the mapwindow
        mapdisplay = self.GetMapDisplay()
        resolution = mapdisplay.mapWindowProperties.resolution
        if not resolution:
            dlg = self.MsgDisplayResolution()
            if dlg.ShowModal() == wx.ID_YES:
                mapdisplay.mapWindowProperties.resolution = True
            dlg.Destroy()

        self.GetLayerTree().AddLayer("rastarrow")

    def OnAddRasterNum(self, event):
        """Add cell number raster map to the current layer tree"""
        mapdisplay = self.GetMapDisplay()
        resolution = mapdisplay.mapWindowProperties.resolution
        if not resolution:
            limitText = _(
                "Note that cell values can only be displayed for "
                "regions of less than 10,000 cells."
            )
            dlg = self.MsgDisplayResolution(limitText)
            if dlg.ShowModal() == wx.ID_YES:
                mapdisplay.mapWindowProperties.resolution = True
            dlg.Destroy()

        # region = tree.GetMap().GetCurrentRegion()
        # if region['cells'] > 10000:
        #   GMessage(message = "Cell values can only be displayed
        #   for regions of < 10,000 cells.", parent = self)
        self.GetLayerTree().AddLayer("rastnum")

    def OnAddCommand(self, event):
        """Add command line map layer to the current layer tree"""
        # start new map display if no display is available
        if not self.currentPage:
            self.NewDisplay(show=True)

        self.GetLayerTree().AddLayer("command")

    def OnAddGroup(self, event):
        """Add layer group"""
        # start new map display if no display is available
        if not self.currentPage:
            self.NewDisplay(show=True)

        self.GetLayerTree().AddLayer("group")

    def OnAddGrid(self, event):
        """Add grid map layer to the current layer tree"""
        self.GetLayerTree().AddLayer("grid")

    def OnAddGeodesic(self, event):
        """Add geodesic line map layer to the current layer tree"""
        self.GetLayerTree().AddLayer("geodesic")

    def OnAddRhumb(self, event):
        """Add rhumb map layer to the current layer tree"""
        self.GetLayerTree().AddLayer("rhumb")

    def OnAddLabels(self, event):
        """Add vector labels map layer to the current layer tree"""
        # start new map display if no display is available
        if not self.currentPage:
            self.NewDisplay(show=True)

        self.GetLayerTree().AddLayer("labels")

    def OnShowRegionExtent(self, event):
        """Add vector labels map layer to the current layer tree"""
        # start new map display if no display is available
        if not self.currentPage:
            self.NewDisplay(show=True)
        # get current map display
        mapdisp = self.GetMapDisplay()
        # change the property
        mapdisp.mapWindowProperties.showRegion = True
        # show map display (user said show so make sure it is visible)
        mapdisp.Show()
        # redraw map if auto-rendering is enabled
        # seems little too low level for this place
        # no redraw when Render is unchecked
        if mapdisp.IsAutoRendered():
            mapdisp.GetMapWindow().UpdateMap(render=False)

    def OnDeleteLayer(self, event):
        """Remove selected map layer from the current layer Tree"""
        if not self.currentPage or not self.GetLayerTree().layer_selected:
            self.MsgNoLayerSelected()
            return

        if UserSettings.Get(group="manager", key="askOnRemoveLayer", subkey="enabled"):
            layerName = ""
            for item in self.GetLayerTree().GetSelections():
                name = self.GetLayerTree().GetItemText(item)
                idx = name.find("(" + _("opacity:"))
                if idx > -1:
                    layerName += "<" + name[:idx].strip(" ") + ">,\n"
                else:
                    layerName += "<" + name + ">,\n"
            layerName = layerName.rstrip(",\n")

            if len(layerName) > 2:  # <>
                message = (
                    _("Do you want to remove map layer(s)\n%s\n" "from layer tree?")
                    % layerName
                )
            else:
                message = _(
                    "Do you want to remove selected map layer(s) " "from layer tree?"
                )

            dlg = wx.MessageDialog(
                parent=self,
                message=message,
                caption=_("Remove map layer"),
                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION,
            )

            if dlg.ShowModal() != wx.ID_YES:
                dlg.Destroy()
                return

            dlg.Destroy()

        for layer in self.GetLayerTree().GetSelections():
            if self.GetLayerTree().GetLayerInfo(layer, key="type") == "group":
                self.GetLayerTree().DeleteChildren(layer)
            # nested children group layer in the parent group layer (both selected)
            try:
                self.GetLayerTree().Delete(layer)
            except ValueError:
                pass

    def OnCloseWindow(self, event):
        """Cleanup when wxGUI is quit"""
        self._closeWindow(event)

    def OnCloseWindowOrExit(self, event):
        """Cleanup when wxGUI is quit

        Ask user also to quit GRASS including terminal
        """
        dlg = QuitDialog(self)
        ret = dlg.ShowModal()
        dlg.Destroy()
        if ret != wx.ID_CANCEL:
            self._closeWindow(event)
            if ret == wx.ID_YES:
                self._quitGRASS()

    def _closeWindow(self, event):
        """Close wxGUI"""
        if not self.currentPage:
            self._auimgr.UnInit()
            self.Destroy()
            return
        if not self.workspace_manager.CanClosePage(caption=_("Quit GRASS GUI")):
            # when called from menu, it gets CommandEvent and not
            # CloseEvent
            if hasattr(event, "Veto"):
                event.Veto()
            return

        self.DisplayCloseAll()

        self._auimgr.UnInit()
        self.Destroy()

    def _quitGRASS(self):
        """Quit GRASS terminal"""
        shellPid = get_shell_pid()
        if shellPid is None:
            return
        Debug.msg(1, "Exiting shell with pid={0}".format(shellPid))
        import signal

        os.kill(shellPid, signal.SIGTERM)

    def MsgNoLayerSelected(self):
        """Show dialog message 'No layer selected'"""
        wx.MessageBox(
            parent=self,
            message=_("No map layer selected. Operation canceled."),
            caption=_("Message"),
            style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE,
        )

    def MsgDisplayResolution(self, limitText=None):
        """Returns dialog for d.rast.num, d.rast.arrow
            when display resolution is not constrained

        :param limitText: adds a note about cell limit
        """
        message = _(
            "Display resolution is currently not constrained to "
            "computational settings. "
            "It's suggested to constrain map to region geometry. "
            "Do you want to constrain "
            "the resolution?"
        )
        if limitText:
            message += "\n\n%s" % _(limitText)
        dlg = wx.MessageDialog(
            parent=self,
            message=message,
            caption=_("Constrain map to region geometry?"),
            style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE,
        )
        return dlg

    def _onMapsetWatchdog(self, map_path, map_dest):
        """Current mapset watchdog event handler

        :param str map_path: map path (map that is changed)
        :param str map_dest: new map path
        """
        self.statusbar.mask.dbChanged(
            map=os.path.basename(map_path) if map_path else map_path,
            newname=os.path.basename(map_dest) if map_dest else map_dest,
        )

    def _onMapsetChanged(self, event):
        self._mapset_watchdog.ScheduleWatchCurrentMapset()