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 (1630 lines) | stat: -rw-r--r-- 51,866 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
"""
@package iclass.frame

@brief wxIClass frame with toolbar for digitizing training areas and
for spectral signature analysis.

Classes:
 - frame::IClassMapPanel
 - frame::IClassMapDisplay
 - frame::MapManager

(C) 2006-2013 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 Vaclav Petras <wenzeslaus gmail.com>
@author Anna Kratochvilova <kratochanna gmail.com>
"""

import os
import copy
import tempfile

import wx

from ctypes import *

try:
    from grass.lib.imagery import *
    from grass.lib.vector import *

    haveIClass = True
    errMsg = ""
except ImportError as e:
    haveIClass = False
    errMsg = _("Loading imagery lib failed.\n%s") % e

import grass.script as grass

from mapdisp import statusbar as sb
from mapdisp.main import StandaloneMapDisplayGrassInterface
from mapwin.buffered import BufferedMapWindow
from vdigit.toolbars import VDigitToolbar
from gui_core.mapdisp import DoubleMapPanel, FrameMixin
from core import globalvar
from core.render import Map
from core.gcmd import RunCommand, GMessage, GError
from gui_core.dialogs import SetOpacityDialog
from gui_core.wrap import Menu
from dbmgr.vinfo import VectorDBInfo

from iclass.digit import IClassVDigitWindow, IClassVDigit
from iclass.toolbars import (
    IClassMapToolbar,
    IClassMiscToolbar,
    IClassToolbar,
    IClassMapManagerToolbar,
)
from iclass.statistics import StatisticsData
from iclass.dialogs import (
    IClassCategoryManagerDialog,
    IClassGroupDialog,
    IClassSignatureFileDialog,
    IClassExportAreasDialog,
    IClassMapDialog,
)
from iclass.plots import PlotPanel

from grass.pydispatch.signal import Signal


class IClassMapPanel(DoubleMapPanel):
    """wxIClass main frame

    It has two map windows one for digitizing training areas and one for
    result preview.
    It generates histograms, raster maps and signature files using
    @c I_iclass_* functions from C imagery library.

    It is wxGUI counterpart of old i.class module.
    """

    def __init__(
        self,
        parent=None,
        giface=None,
        title=_("Supervised Classification Tool"),
        toolbars=["iClassMisc", "iClassMap", "vdigit", "iClass"],
        size=(875, 600),
        name="IClassWindow",
        **kwargs,
    ):
        """
        :param parent: (no parent is expected)
        :param title: window title
        :param toolbars: dictionary of active toolbars (default value represents all
                         toolbars)
        :param size: default size
        """
        DoubleMapPanel.__init__(
            self,
            parent=parent,
            title=title,
            name=name,
            firstMap=Map(),
            secondMap=Map(),
            **kwargs,
        )
        if giface:
            self.giface = giface
        else:
            self.giface = StandaloneMapDisplayGrassInterface(self)
        self.tree = None

        # show computation region by default
        self.mapWindowProperties.showRegion = True

        self.firstMapWindow = IClassVDigitWindow(
            parent=self,
            giface=self.giface,
            properties=self.mapWindowProperties,
            map=self.firstMap,
        )
        self.secondMapWindow = BufferedMapWindow(
            parent=self,
            giface=self.giface,
            properties=self.mapWindowProperties,
            Map=self.secondMap,
        )
        self.MapWindow = self.firstMapWindow  # current by default

        self._bindWindowsActivation()
        self._setUpMapWindow(self.firstMapWindow)
        self._setUpMapWindow(self.secondMapWindow)
        self.firstMapWindow.InitZoomHistory()
        self.secondMapWindow.InitZoomHistory()
        # TODO: for vdigit: it does nothing here because areas do not produce
        # this info
        self.firstMapWindow.digitizingInfo.connect(
            lambda text: self.statusbarManager.statusbarItems[
                "coordinates"
            ].SetAdditionalInfo(text)
        )
        self.firstMapWindow.digitizingInfoUnavailable.connect(
            lambda: self.statusbarManager.statusbarItems[
                "coordinates"
            ].SetAdditionalInfo(None)
        )
        self.SetSize(size)

        #
        # Signals
        #

        self.groupSet = Signal("IClassMapPanel.groupSet")
        self.categoryChanged = Signal("IClassMapPanel.categoryChanged")

        self.InitStatistics()

        #
        # Add toolbars
        #
        for toolb in toolbars:
            self.AddToolbar(toolb)
        self.firstMapWindow.SetToolbar(self.toolbars["vdigit"])

        self.GetMapToolbar().GetActiveMapTool().Bind(wx.EVT_CHOICE, self.OnUpdateActive)

        self.trainingMapManager = MapManager(
            self, mapWindow=self.GetFirstWindow(), Map=self.GetFirstMap()
        )
        self.previewMapManager = MapManager(
            self, mapWindow=self.GetSecondWindow(), Map=self.GetSecondMap()
        )

        self.changes = False
        self.exportVector = None

        # dialogs
        self.dialogs = dict()
        self.dialogs["classManager"] = None
        self.dialogs["scatt_plot"] = None
        # just to make digitizer happy
        self.dialogs["attributes"] = None
        self.dialogs["category"] = None

        # PyPlot init
        self.plotPanel = PlotPanel(self, giface=self.giface, stats_data=self.stats_data)

        # statusbar items
        statusbarItems = [
            sb.SbCoordinates,
            sb.SbRegionExtent,
            sb.SbCompRegionExtent,
            sb.SbDisplayGeometry,
            sb.SbMapScale,
            sb.SbGoTo,
        ]
        self.statusbar = self.CreateStatusbar(statusbarItems)
        self._addPanes()
        self._mgr.Update()

        self.trainingMapManager.SetToolbar(self.toolbars["iClassTrainingMapManager"])
        self.previewMapManager.SetToolbar(self.toolbars["iClassPreviewMapManager"])

        # default action
        self.GetMapToolbar().SelectDefault()

        wx.CallAfter(self.AddTrainingAreaMap)

        self.Bind(wx.EVT_SIZE, self.OnSize)

        self.SendSizeEvent()

    def OnCloseWindow(self, event):
        self.GetFirstWindow().GetDigit().CloseMap()
        self.plotPanel.CloseWindow()
        self._cleanup()
        self._mgr.UnInit()
        self.Destroy()

    def _cleanup(self):
        """Frees C structs and removes vector map and all raster maps."""
        I_free_signatures(self.signatures)
        I_free_group_ref(self.refer)
        for st in self.cStatisticsDict.values():
            I_iclass_free_statistics(st)

        self.RemoveTempVector()
        for i in self.stats_data.GetCategories():
            self.RemoveTempRaster(self.stats_data.GetStatistics(i).rasterName)

    def OnHelp(self, event):
        """Show help page"""
        self.giface.Help(entry="wxGUI.iclass")

    def _getTempVectorName(self):
        """Return new name for temporary vector map (training areas)"""
        vectorPath = grass.tempfile(create=False)

        return "trAreas" + os.path.basename(vectorPath).replace(".", "")

    def SetGroup(self, group, subgroup):
        """Set group and subgroup manually"""
        self.g = {"group": group, "subgroup": subgroup}

    def CreateTempVector(self):
        """Create temporary vector map for training areas"""
        vectorName = self._getTempVectorName()

        env = os.environ.copy()
        env["GRASS_VECTOR_TEMPORARY"] = "1"  # create temporary map
        cmd = ("v.edit", {"tool": "create", "map": vectorName})

        ret = RunCommand(prog=cmd[0], parent=self, env=env, **cmd[1])

        if ret != 0:
            return False

        return vectorName

    def RemoveTempVector(self):
        """Removes temporary vector map with training areas"""
        ret = RunCommand(
            prog="g.remove",
            parent=self,
            flags="f",
            type="vector",
            name=self.trainingAreaVector,
        )
        if ret != 0:
            return False
        return True

    def RemoveTempRaster(self, raster):
        """Removes temporary raster maps"""
        self.GetFirstMap().Clean()
        self.GetSecondMap().Clean()
        ret = RunCommand(
            prog="g.remove", parent=self, flags="f", type="raster", name=raster
        )
        if ret != 0:
            return False
        return True

    def AddToolbar(self, name):
        """Add defined toolbar to the window

        Currently known toolbars are:
         - 'iClassMap'          - basic map toolbar
         - 'iClass'             - iclass tools
         - 'iClassMisc'         - miscellaneous (help)
         - 'vdigit'             - digitizer toolbar (areas)

         Toolbars 'iClassPreviewMapManager' are added in _addPanes().
        """
        if name == "iClassMap":
            if "iClassMap" not in self.toolbars:
                self.toolbars[name] = IClassMapToolbar(self, self._toolSwitcher)

            self._mgr.AddPane(
                self.toolbars[name],
                wx.aui.AuiPaneInfo()
                .Name(name)
                .Caption(_("Map Toolbar"))
                .ToolbarPane()
                .Top()
                .LeftDockable(False)
                .RightDockable(False)
                .BottomDockable(False)
                .TopDockable(True)
                .CloseButton(False)
                .Layer(2)
                .Row(1)
                .Position(0)
                .BestSize(self.toolbars[name].GetBestSize()),
            )

        if name == "iClass":
            if "iClass" not in self.toolbars:
                self.toolbars[name] = IClassToolbar(self, stats_data=self.stats_data)

            self._mgr.AddPane(
                self.toolbars[name],
                wx.aui.AuiPaneInfo()
                .Name(name)
                .Caption(_("IClass Toolbar"))
                .ToolbarPane()
                .Top()
                .LeftDockable(False)
                .RightDockable(False)
                .BottomDockable(False)
                .TopDockable(True)
                .CloseButton(False)
                .Layer(2)
                .Row(2)
                .Position(0)
                .BestSize(self.toolbars[name].GetBestSize()),
            )

        if name == "iClassMisc":
            if "iClassMisc" not in self.toolbars:
                self.toolbars[name] = IClassMiscToolbar(self)

            self._mgr.AddPane(
                self.toolbars[name],
                wx.aui.AuiPaneInfo()
                .Name(name)
                .Caption(_("IClass Misc Toolbar"))
                .ToolbarPane()
                .Top()
                .LeftDockable(False)
                .RightDockable(False)
                .BottomDockable(False)
                .TopDockable(True)
                .CloseButton(False)
                .Layer(2)
                .Row(1)
                .Position(1)
                .BestSize(self.toolbars[name].GetBestSize()),
            )

        if name == "vdigit":
            if "vdigit" not in self.toolbars:
                self.toolbars[name] = VDigitToolbar(
                    parent=self,
                    toolSwitcher=self._toolSwitcher,
                    MapWindow=self.GetFirstWindow(),
                    digitClass=IClassVDigit,
                    giface=self.giface,
                    tools=[
                        "addArea",
                        "moveVertex",
                        "addVertex",
                        "removeVertex",
                        "editLine",
                        "moveLine",
                        "deleteArea",
                        "undo",
                        "redo",
                        "settings",
                    ],
                )

            self._mgr.AddPane(
                self.toolbars[name],
                wx.aui.AuiPaneInfo()
                .Name(name)
                .Caption(_("Digitization Toolbar"))
                .ToolbarPane()
                .Top()
                .LeftDockable(False)
                .RightDockable(False)
                .BottomDockable(False)
                .TopDockable(True)
                .CloseButton(False)
                .Layer(2)
                .Row(2)
                .Position(1)
                .BestSize(self.toolbars[name].GetBestSize()),
            )

        self._mgr.Update()

    def _addPanes(self):
        """Add mapwindows, toolbars and statusbar to aui manager"""
        self._addPaneMapWindow(name="training", position=0)
        self._addPaneToolbar(name="iClassTrainingMapManager", position=1)
        self._addPaneMapWindow(name="preview", position=2)
        self._addPaneToolbar(name="iClassPreviewMapManager", position=3)

        # otherwise best size was ignored
        self._mgr.SetDockSizeConstraint(0.5, 0.5)

        self._mgr.AddPane(
            self.plotPanel,
            wx.aui.AuiPaneInfo()
            .Name("plots")
            .Caption(_("Plots"))
            .Dockable(False)
            .Floatable(False)
            .CloseButton(False)
            .Left()
            .Layer(1)
            .BestSize((335, -1)),
        )

        # statusbar
        self.AddStatusbarPane()

    def _addPaneToolbar(self, name, position):
        if name == "iClassPreviewMapManager":
            parent = self.previewMapManager
        else:
            parent = self.trainingMapManager

        self.toolbars[name] = IClassMapManagerToolbar(self, parent)
        self._mgr.AddPane(
            self.toolbars[name],
            wx.aui.AuiPaneInfo()
            .ToolbarPane()
            .Movable()
            .Name(name)
            .CloseButton(False)
            .Center()
            .Layer(0)
            .Position(position)
            .BestSize(self.toolbars[name].GetBestSize()),
        )

    def _addPaneMapWindow(self, name, position):
        if name == "preview":
            window = self.GetSecondWindow()
            caption = _("Preview Display")
        else:
            window = self.GetFirstWindow()
            caption = _("Training Areas Display")

        self._mgr.AddPane(
            window,
            wx.aui.AuiPaneInfo()
            .Name(name)
            .Caption(caption)
            .Dockable(False)
            .Floatable(False)
            .CloseButton(False)
            .Center()
            .Layer(0)
            .Position(position),
        )

    def OnUpdateActive(self, event):
        """
        .. todo::
            move to DoubleMapPanel?
        """
        if self.GetMapToolbar().GetActiveMap() == 0:
            self.MapWindow = self.firstMapWindow
            self.Map = self.firstMap
        else:
            self.MapWindow = self.secondMapWindow
            self.Map = self.secondMap

        self.UpdateActive(self.MapWindow)
        # for wingrass
        if os.name == "nt":
            self.MapWindow.SetFocus()

    def UpdateActive(self, win):
        """
        .. todo::
            move to DoubleMapPanel?
        """
        mapTb = self.GetMapToolbar()
        # optionally disable tool zoomback tool
        mapTb.Enable("zoomBack", enable=(len(self.MapWindow.zoomhistory) > 1))

        if mapTb.GetActiveMap() != (win == self.secondMapWindow):
            mapTb.SetActiveMap(win == self.secondMapWindow)
        self.StatusbarUpdate()

    def ActivateFirstMap(self, event=None):
        DoubleMapPanel.ActivateFirstMap(self, event)
        self.GetMapToolbar().Enable(
            "zoomBack", enable=(len(self.MapWindow.zoomhistory) > 1)
        )

    def ActivateSecondMap(self, event=None):
        DoubleMapPanel.ActivateSecondMap(self, event)
        self.GetMapToolbar().Enable(
            "zoomBack", enable=(len(self.MapWindow.zoomhistory) > 1)
        )

    def GetMapToolbar(self):
        """Returns toolbar with zooming tools"""
        return self.toolbars["iClassMap"] if "iClassMap" in self.toolbars else None

    def GetClassColor(self, cat):
        """Get class color as string

        :param cat: class category

        :return: 'R:G:B'
        """
        if cat in self.stats_data.GetCategories():
            return self.stats_data.GetStatistics(cat).color
        return "0:0:0"

    def OnZoomMenu(self, event):
        """Popup Zoom menu"""
        zoommenu = Menu()
        # Add items to the menu

        i = 0
        for label, handler in (
            (
                _("Adjust Training Area Display to Preview Display"),
                self.OnZoomToPreview,
            ),
            (
                _("Adjust Preview display to Training Area Display"),
                self.OnZoomToTraining,
            ),
            (_("Display synchronization ON"), lambda event: self.SetBindRegions(True)),
            (
                _("Display synchronization OFF"),
                lambda event: self.SetBindRegions(False),
            ),
        ):
            if label is None:
                zoommenu.AppendSeparator()
                continue

            item = wx.MenuItem(zoommenu, wx.ID_ANY, label)
            zoommenu.AppendItem(item)
            self.Bind(wx.EVT_MENU, handler, item)
            if i == 3:
                item.Enable(not self._bindRegions)
            elif i == 4:
                item.Enable(self._bindRegions)
            i += 1

        # Popup the menu. If an item is selected then its handler
        # will be called before PopupMenu returns.
        self.PopupMenu(zoommenu)
        zoommenu.Destroy()

    def OnZoomToTraining(self, event):
        """Set preview display to match extents of training display"""

        if not self.MapWindow == self.GetSecondWindow():
            self.MapWindow = self.GetSecondWindow()
            self.Map = self.GetSecondMap()
            self.UpdateActive(self.GetSecondWindow())

        newreg = self.firstMap.GetCurrentRegion()
        self.GetSecondMap().region = copy.copy(newreg)

        self.Render(self.GetSecondWindow())

    def OnZoomToPreview(self, event):
        """Set preview display to match extents of training display"""

        if not self.MapWindow == self.GetFirstWindow():
            self.MapWindow = self.GetFirstWindow()
            self.Map = self.GetFirstMap()
            self.UpdateActive(self.GetFirstWindow())

        newreg = self.GetSecondMap().GetCurrentRegion()
        self.GetFirstMap().region = copy.copy(newreg)

        self.Render(self.GetFirstWindow())

    def AddBands(self):
        """Add imagery group"""
        dlg = IClassGroupDialog(self, group=self.g["group"])

        while True:
            if dlg.ShowModal() == wx.ID_OK:
                if dlg.GetGroupBandsErr(parent=self):
                    g, s = dlg.GetData()
                    group = grass.find_file(name=g, element="group")
                    self.g["group"] = group["name"]
                    self.g["subgroup"] = s
                    self.groupSet.emit(
                        group=self.g["group"], subgroup=self.g["subgroup"]
                    )
                    break
            else:
                break

        dlg.Destroy()

    def OnImportAreas(self, event):
        """Import training areas"""
        # check if we have any changes
        if self.GetAreasCount() or self.stats_data.GetCategories():
            qdlg = wx.MessageDialog(
                parent=self,
                message=_("All changes will be lost. " "Do you want to continue?"),
                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE,
            )
            if qdlg.ShowModal() == wx.ID_NO:
                qdlg.Destroy()
                return
            qdlg.Destroy()

        dlg = IClassMapDialog(self, title=_("Import vector map"), element="vector")
        if dlg.ShowModal() == wx.ID_OK:
            vName = dlg.GetMap()

            self.ImportAreas(vName)

        dlg.Destroy()

    def _checkImportedTopo(self, vector):
        """Check if imported vector map has areas

        :param str vector: vector map name

        :return: warning message (empty if topology is ok)
        """
        topo = grass.vector_info_topo(map=vector)

        warning = ""
        if topo["areas"] == 0:
            warning = _("No areas in vector map <%s>.\n" % vector)
        if topo["points"] or topo["lines"]:
            warning += _(
                "Vector map <%s> contains points or lines, "
                "these features are ignored." % vector
            )

        return warning

    def ImportAreas(self, vector):
        """Import training areas.

        If table connected, try load certain columns to class manager

        :param str vector: vector map name
        """
        warning = self._checkImportedTopo(vector)
        if warning:
            GMessage(parent=self, message=warning)
            return

        wx.BeginBusyCursor()
        wx.GetApp().Yield()

        # close, build, copy and open again the temporary vector
        digitClass = self.GetFirstWindow().GetDigit()

        # open vector map to be imported
        if digitClass.OpenMap(vector, update=False) is None:
            GError(parent=self, message=_("Unable to open vector map <%s>") % vector)
            return

        # copy features to the temporary map
        vname = self._getTempVectorName()
        # avoid deleting temporary map
        os.environ["GRASS_VECTOR_TEMPORARY"] = "1"
        if digitClass.CopyMap(vname, tmp=True, update=True) == -1:
            GError(
                parent=self,
                message=_("Unable to copy vector features from <%s>") % vector,
            )
            return
        del os.environ["GRASS_VECTOR_TEMPORARY"]

        # close map
        digitClass.CloseMap()

        # open temporary map (copy of imported map)
        self.poMapInfo = digitClass.OpenMap(vname, tmp=True)
        if self.poMapInfo is None:
            GError(parent=self, message=_("Unable to open temporary vector map"))
            return

        # remove temporary rasters
        for cat in self.stats_data.GetCategories():
            self.RemoveTempRaster(self.stats_data.GetStatistics(cat).rasterName)

        # clear current statistics
        self.stats_data.DeleteAllStatistics()

        # reset plots
        self.plotPanel.Reset()

        self.GetFirstWindow().UpdateMap(render=False, renderVector=True)

        self.ImportClasses(vector)

        # should be saved in attribute table?
        self.toolbars["iClass"].UpdateStddev(1.5)

        wx.EndBusyCursor()

        return True

    def ImportClasses(self, vector):
        """If imported map has table, try to import certain columns to class manager"""
        # check connection
        dbInfo = VectorDBInfo(vector)
        connected = len(dbInfo.layers.keys()) > 0

        # remove attribute table of temporary vector, we don't need it
        if connected:
            RunCommand("v.db.droptable", flags="f", map=self.trainingAreaVector)

        # we use first layer with table, TODO: user should choose
        layer = None
        for key in dbInfo.layers.keys():
            if dbInfo.GetTable(key):
                layer = key

        # get columns to check if we can use them
        # TODO: let user choose which columns mean what
        if layer is not None:
            columns = dbInfo.GetColumns(table=dbInfo.GetTable(layer))
        else:
            columns = []

        # get class manager
        if self.dialogs["classManager"] is None:
            self.dialogs["classManager"] = IClassCategoryManagerDialog(self)

        listCtrl = self.dialogs["classManager"].GetListCtrl()

        # unable to load data (no connection, table, right columns)
        if (
            not connected
            or layer is None
            or "class" not in columns
            or "color" not in columns
        ):
            # no table connected
            cats = RunCommand(
                "v.category",
                input=vector,
                layer=1,  # set layer?
                # type = ['centroid', 'area'] ?
                option="print",
                read=True,
            )
            cats = map(int, cats.strip().split())
            cats = sorted(list(set(cats)))

            for cat in cats:
                listCtrl.AddCategory(cat=cat, name="class_%d" % cat, color="0:0:0")
        # connection, table and columns exists
        else:
            columns = ["cat", "class", "color"]
            ret = RunCommand(
                "v.db.select",
                quiet=True,
                parent=self,
                flags="c",
                map=vector,
                layer=1,
                columns=",".join(columns),
                read=True,
            )
            records = ret.strip().splitlines()
            for record in records:
                record = record.split("|")
                listCtrl.AddCategory(
                    cat=int(record[0]), name=record[1], color=record[2]
                )

    def OnExportAreas(self, event):
        """Export training areas"""
        if self.GetAreasCount() == 0:
            GMessage(parent=self, message=_("No training areas to export."))
            return

        dlg = IClassExportAreasDialog(self, vectorName=self.exportVector)

        if dlg.ShowModal() == wx.ID_OK:
            vName = dlg.GetVectorName()
            self.exportVector = vName
            withTable = dlg.WithTable()
            dlg.Destroy()

            if self.ExportAreas(vectorName=vName, withTable=withTable):
                GMessage(
                    _("%d training areas (%d classes) exported to vector map <%s>.")
                    % (
                        self.GetAreasCount(),
                        len(self.stats_data.GetCategories()),
                        self.exportVector,
                    ),
                    parent=self,
                )

    def ExportAreas(self, vectorName, withTable):
        """Export training areas to new vector map (with attribute table).

        :param str vectorName: name of exported vector map
        :param bool withTable: true if attribute table is required
        """
        wx.BeginBusyCursor()
        wx.GetApp().Yield()

        # close, build, copy and open again the temporary vector
        digitClass = self.GetFirstWindow().GetDigit()
        if "@" in vectorName:
            vectorName = vectorName.split("@")[0]
        if digitClass.CopyMap(vectorName) < 0:
            return False

        if not withTable:
            wx.EndBusyCursor()
            return False

        # add new table
        columns = [
            "class varchar(30)",
            "color varchar(11)",
            "n_cells integer",
        ]

        nbands = len(self.GetGroupLayers(self.g["group"], self.g["subgroup"]))
        for statistic, format in (
            ("min", "integer"),
            ("mean", "double precision"),
            ("max", "integer"),
        ):
            for i in range(nbands):
                # 10 characters limit?
                columns.append(
                    "band%(band)d_%(stat)s %(format)s"
                    % {"band": i + 1, "stat": statistic, "format": format}
                )

        if 0 != RunCommand(
            "v.db.addtable", map=vectorName, columns=columns, parent=self
        ):
            wx.EndBusyCursor()
            return False

        try:
            dbInfo = grass.vector_db(vectorName)[1]
        except KeyError:
            wx.EndBusyCursor()
            return False

        dbFile = tempfile.NamedTemporaryFile(mode="w", delete=False)
        if dbInfo["driver"] != "dbf":
            dbFile.write("BEGIN\n")
        # populate table
        for cat in self.stats_data.GetCategories():
            stat = self.stats_data.GetStatistics(cat)

            self._runDBUpdate(
                dbFile, table=dbInfo["table"], column="class", value=stat.name, cat=cat
            )
            self._runDBUpdate(
                dbFile, table=dbInfo["table"], column="color", value=stat.color, cat=cat
            )

            if not stat.IsReady():
                continue

            self._runDBUpdate(
                dbFile,
                table=dbInfo["table"],
                column="n_cells",
                value=stat.ncells,
                cat=cat,
            )

            for i in range(nbands):
                self._runDBUpdate(
                    dbFile,
                    table=dbInfo["table"],
                    column="band%d_min" % (i + 1),
                    value=stat.bands[i].min,
                    cat=cat,
                )
                self._runDBUpdate(
                    dbFile,
                    table=dbInfo["table"],
                    column="band%d_mean" % (i + 1),
                    value=stat.bands[i].mean,
                    cat=cat,
                )
                self._runDBUpdate(
                    dbFile,
                    table=dbInfo["table"],
                    column="band%d_max" % (i + 1),
                    value=stat.bands[i].max,
                    cat=cat,
                )

        if dbInfo["driver"] != "dbf":
            dbFile.write("COMMIT\n")
        dbFile.file.close()

        ret = RunCommand(
            "db.execute",
            input=dbFile.name,
            driver=dbInfo["driver"],
            database=dbInfo["database"],
        )
        wx.EndBusyCursor()
        os.remove(dbFile.name)
        if ret != 0:
            return False
        return True

    def _runDBUpdate(self, tmpFile, table, column, value, cat):
        """Helper function for UPDATE statement

        :param tmpFile: file where to write UPDATE statements
        :param table: table name
        :param column: name of updated column
        :param value: new value
        :param cat: which category to update
        """
        if isinstance(value, (int, float)):
            tmpFile.write(
                "UPDATE %s SET %s = %d WHERE cat = %d\n" % (table, column, value, cat)
            )
        else:
            tmpFile.write(
                "UPDATE %s SET %s = '%s' WHERE cat = %d\n" % (table, column, value, cat)
            )

    def OnCategoryManager(self, event):
        """Show category management dialog"""
        if self.dialogs["classManager"] is None:
            dlg = IClassCategoryManagerDialog(self)
            dlg.CenterOnParent()
            dlg.Show()
            self.dialogs["classManager"] = dlg
        else:
            if not self.dialogs["classManager"].IsShown():
                self.dialogs["classManager"].Show()

    def CategoryChanged(self, currentCat):
        """Updates everything which depends on current category.

        Updates number of stddev, histograms, layer in preview display.
        """
        if currentCat:
            stat = self.stats_data.GetStatistics(currentCat)
            nstd = stat.nstd
            self.toolbars["iClass"].UpdateStddev(nstd)

            self.plotPanel.UpdateCategory(currentCat)
            self.plotPanel.OnPlotTypeSelected(None)

            name = stat.rasterName
            name = self.previewMapManager.GetAlias(name)
            if name:
                self.previewMapManager.SelectLayer(name)

        self.categoryChanged.emit(cat=currentCat)

    def DeleteAreas(self, cats):
        """Removes all training areas of given categories

        :param cats: list of categories to be deleted
        """
        self.firstMapWindow.GetDigit().DeleteAreasByCat(cats)
        self.firstMapWindow.UpdateMap(render=False, renderVector=True)

    def HighlightCategory(self, cats):
        """Highlight araes given by category"""
        self.firstMapWindow.GetDigit().GetDisplay().SetSelected(cats, layer=1)
        self.firstMapWindow.UpdateMap(render=False, renderVector=True)

    def ZoomToAreasByCat(self, cat):
        """Zoom to areas given by category"""
        n, s, w, e = self.GetFirstWindow().GetDigit().GetDisplay().GetRegionSelected()
        self.GetFirstMap().GetRegion(n=n, s=s, w=w, e=e, update=True)
        self.GetFirstMap().AdjustRegion()
        self.GetFirstMap().AlignExtentFromDisplay()

        self.GetFirstWindow().UpdateMap(render=True, renderVector=True)

    def UpdateRasterName(self, newName, cat):
        """Update alias of raster map when category name is changed"""
        origName = self.stats_data.GetStatistics(cat).rasterName
        self.previewMapManager.SetAlias(origName, self._addSuffix(newName))

    def StddevChanged(self, cat, nstd):
        """Standard deviation multiplier changed, rerender map, histograms"""
        stat = self.stats_data.GetStatistics(cat)
        stat.SetStatistics({"nstd": nstd})

        if not stat.IsReady():
            return

        raster = stat.rasterName

        cstat = self.cStatisticsDict[cat]
        I_iclass_statistics_set_nstd(cstat, nstd)

        I_iclass_create_raster(cstat, self.refer, raster)
        self.Render(self.GetSecondWindow())

        stat.SetBandStatistics(cstat)
        self.plotPanel.StddevChanged()

    def UpdateChangeState(self, changes):
        """Informs if any important changes happened
        since last analysis computation.
        """
        self.changes = changes

    def AddRasterMap(self, name, firstMap=True, secondMap=True):
        """Add raster map to Map"""
        cmdlist = ["d.rast", "map=%s" % name]
        if firstMap:
            self.GetFirstMap().AddLayer(
                ltype="raster",
                command=cmdlist,
                active=True,
                name=name,
                hidden=False,
                opacity=1.0,
                render=False,
            )
            self.Render(self.GetFirstWindow())
        if secondMap:
            self.GetSecondMap().AddLayer(
                ltype="raster",
                command=cmdlist,
                active=True,
                name=name,
                hidden=False,
                opacity=1.0,
                render=False,
            )
            self.Render(self.GetSecondWindow())

    def AddTrainingAreaMap(self):
        """Add vector map with training areas to Map (training
        sub-display)"""
        vname = self.CreateTempVector()
        if vname:
            self.trainingAreaVector = vname
        else:
            GMessage(parent=self, message=_("Failed to create temporary vector map."))
            return

        # use 'hidden' for temporary maps (TODO: do it better)
        mapLayer = self.GetFirstMap().AddLayer(
            ltype="vector",
            command=["d.vect", "map=%s" % vname],
            name=vname,
            active=False,
            hidden=True,
        )

        self.toolbars["vdigit"].StartEditing(mapLayer)
        self.poMapInfo = self.GetFirstWindow().GetDigit().GetMapInfo()
        self.Render(self.GetFirstWindow())

    def OnRunAnalysis(self, event):
        """Run analysis and update plots"""
        if self.RunAnalysis():
            currentCat = self.GetCurrentCategoryIdx()
            self.plotPanel.UpdatePlots(
                group=self.g["group"],
                subgroup=self.g["subgroup"],
                currentCat=currentCat,
                stats_data=self.stats_data,
            )

    def RunAnalysis(self):
        """Run analysis

        Calls C functions to compute all statistics and creates raster maps.
        Signatures are created but signature file is not.
        """
        if not self.CheckInput(group=self.g["group"], vector=self.trainingAreaVector):
            return

        for statistic in self.cStatisticsDict.values():
            I_iclass_free_statistics(statistic)
        self.cStatisticsDict = {}

        # init Ref struct with the files in group */
        I_free_group_ref(self.refer)

        if not I_iclass_init_group(self.g["group"], self.g["subgroup"], self.refer):
            return False

        I_free_signatures(self.signatures)
        ret = I_iclass_init_signatures(self.signatures, self.refer)
        if not ret:
            GMessage(
                parent=self,
                message=_(
                    "There was an error initializing signatures. "
                    "Check GUI console for any error messages."
                ),
            )
            I_free_signatures(self.signatures)
            return False

        # why create copy
        # cats = self.statisticsList[:]

        cats = self.stats_data.GetCategories()
        for i in cats:
            stats = self.stats_data.GetStatistics(i)

            statistics_obj = IClass_statistics()
            statistics = pointer(statistics_obj)

            I_iclass_init_statistics(
                statistics, stats.category, stats.name, stats.color, stats.nstd
            )

            ret = I_iclass_analysis(
                statistics,
                self.refer,
                self.poMapInfo,
                "1",
                self.g["group"],
                stats.rasterName,
            )
            if ret > 0:
                # tests
                self.cStatisticsDict[i] = statistics

                stats.SetFromcStatistics(statistics)
                stats.SetReady()

                # stat is already part of stats_data?
                # self.statisticsDict[stats.category] = stats

                self.ConvertToNull(name=stats.rasterName)
                self.previewMapManager.AddLayer(
                    name=stats.rasterName,
                    alias=self._addSuffix(stats.name),
                    resultsLayer=True,
                )
                # write statistics
                I_iclass_add_signature(self.signatures, statistics)

            elif ret == 0:
                GMessage(
                    parent=self,
                    message=_("No area in category %s. Category skipped.")
                    % stats.category,
                )
                I_iclass_free_statistics(statistics)
            else:
                GMessage(parent=self, message=_("Analysis failed."))
                I_iclass_free_statistics(statistics)

        self.UpdateChangeState(changes=False)
        return True

    def _addSuffix(self, name):
        suffix = _("results")
        return "_".join((name, suffix))

    def OnSaveSigFile(self, event):
        """Asks for signature file name and saves it."""
        if not self.g["group"]:
            GMessage(parent=self, message=_("No imagery group selected."))
            return

        if self.changes:
            qdlg = wx.MessageDialog(
                parent=self,
                message=_(
                    "Due to recent changes in classes, "
                    "signatures can be outdated and should be recalculated. "
                    "Do you still want to continue?"
                ),
                caption=_("Outdated signatures"),
                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE,
            )
            if qdlg.ShowModal() == wx.ID_YES:
                qdlg.Destroy()
            else:
                qdlg.Destroy()
                return

        if not self.signatures.contents.nsigs:
            GMessage(
                parent=self,
                message=_(
                    "Signatures are not valid. Recalculate them and then try again."
                ),
            )
            return

        dlg = IClassSignatureFileDialog(self, file=self.sigFile)

        if dlg.ShowModal() == wx.ID_OK:
            if os.path.exists(dlg.GetFileName(fullPath=True)):
                qdlg = wx.MessageDialog(
                    parent=self,
                    message=_(
                        "A signature file named %s already exists.\n"
                        "Do you want to replace it?"
                    )
                    % dlg.GetFileName(),
                    caption=_("File already exists"),
                    style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE,
                )
                if qdlg.ShowModal() == wx.ID_YES:
                    qdlg.Destroy()
                else:
                    qdlg.Destroy()
                    return
            self.sigFile = dlg.GetFileName()
            self.WriteSignatures(self.signatures, self.sigFile)

        dlg.Destroy()

    def InitStatistics(self):
        """Initialize variables and c structures necessary for
        computing statistics.
        """
        self.g = {"group": None, "subgroup": None}
        self.sigFile = None

        self.stats_data = StatisticsData()

        self.cStatisticsDict = {}

        self.signatures_obj = Signature()
        self.signatures = pointer(self.signatures_obj)
        I_init_signatures(self.signatures, 0)  # must be freed on exit

        refer_obj = Ref()
        self.refer = pointer(refer_obj)
        I_init_group_ref(self.refer)  # must be freed on exit

    def WriteSignatures(self, signatures, filename):
        """Writes current signatures to signature file

        :param signatures: signature (c structure)
        :param filename: signature file name
        """
        I_iclass_write_signatures(signatures, filename)

    def CheckInput(self, group, vector):
        """Check if input is valid"""
        # check if group is ok
        # TODO check subgroup
        if not group:
            GMessage(
                parent=self,
                message=_("No imagery group selected. " "Operation canceled."),
            )
            return False

        groupLayers = self.GetGroupLayers(self.g["group"], self.g["subgroup"])

        nLayers = len(groupLayers)
        if nLayers <= 1:
            GMessage(
                parent=self,
                message=_(
                    "Group <%(group)s> does not have enough files "
                    "(it has %(files)d files). Operation canceled."
                )
                % {"group": group, "files": nLayers},
            )
            return False

        # check if vector has any areas
        if self.GetAreasCount() == 0:
            GMessage(parent=self, message=_("No areas given. " "Operation canceled."))
            return False

        # check if vector is inside raster
        regionBox = bound_box()
        Vect_get_map_box(self.poMapInfo, byref(regionBox))

        rasterInfo = grass.raster_info(groupLayers[0])

        if (
            regionBox.N > rasterInfo["north"]
            or regionBox.S < rasterInfo["south"]
            or regionBox.E > rasterInfo["east"]
            or regionBox.W < rasterInfo["west"]
        ):
            GMessage(
                parent=self,
                message=_(
                    "Vector features are outside raster layers. " "Operation canceled."
                ),
            )
            return False

        return True

    def GetAreasCount(self):
        """Returns number of not dead areas"""
        count = 0
        numAreas = Vect_get_num_areas(self.poMapInfo)
        for i in range(numAreas):
            if Vect_area_alive(self.poMapInfo, i + 1):
                count += 1
        return count

    def GetGroupLayers(self, group, subgroup=None):
        """Get layers in subgroup (expecting same name for group and subgroup)

        .. todo::
            consider moving this function to core module for convenient
        """
        kwargs = {}
        if subgroup:
            kwargs["subgroup"] = subgroup

        res = RunCommand("i.group", flags="g", group=group, read=True, **kwargs).strip()
        if res.splitlines()[0]:
            return sorted(res.splitlines())

        return []

    def ConvertToNull(self, name):
        """Sets value which represents null values for given raster map.

        :param name: raster map name
        """
        RunCommand("r.null", map=name, setnull=0)

    def GetCurrentCategoryIdx(self):
        """Returns current category number"""
        return self.toolbars["iClass"].GetSelectedCategoryIdx()

    def OnZoomIn(self, event):
        """Enable zooming for plots"""
        super().OnZoomIn(event)
        self.plotPanel.EnableZoom(type=1)

    def OnZoomOut(self, event):
        """Enable zooming for plots"""
        super().OnZoomOut(event)
        self.plotPanel.EnableZoom(type=-1)

    def OnPan(self, event):
        """Enable panning for plots"""
        super().OnPan(event)
        self.plotPanel.EnablePan()

    def OnPointer(self, event):
        """Set pointer mode.

        .. todo::
            pointers need refactoring
        """
        self.GetFirstWindow().SetModePointer()
        self.GetSecondWindow().SetModePointer()

    def GetMapManagers(self):
        """Get map managers of wxIClass

        :return: trainingMapManager, previewMapManager
        """
        return self.trainingMapManager, self.previewMapManager


class IClassMapDisplay(FrameMixin, IClassMapPanel):
    """Map display for wrapping map panel with frame methods"""

    def __init__(self, parent, giface, **kwargs):
        # init map panel
        IClassMapPanel.__init__(
            self,
            parent=parent,
            giface=giface,
            **kwargs,
        )
        # set system icon
        parent.SetIcon(
            wx.Icon(
                os.path.join(globalvar.ICONDIR, "grass_map.ico"), wx.BITMAP_TYPE_ICO
            )
        )

        # bindings
        parent.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        # extend shortcuts and create frame accelerator table
        self.shortcuts_table.append((self.OnFullScreen, wx.ACCEL_NORMAL, wx.WXK_F11))
        self._initShortcuts()

        # add Map Display panel to Map Display frame
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self, proportion=1, flag=wx.EXPAND)
        parent.SetSizer(sizer)
        parent.Layout()


class MapManager:
    """Class for managing map renderer.

    It is connected with iClassMapManagerToolbar.
    """

    def __init__(self, frame, mapWindow, Map):
        """

        It is expected that \a mapWindow is connected with \a Map.

        :param frame: application main window
        :param mapWindow: map window instance
        :param map: map renderer instance
        """
        self.map = Map
        self.frame = frame
        self.mapWindow = mapWindow
        self.toolbar = None

        self.layerName = {}

    def SetToolbar(self, toolbar):
        self.toolbar = toolbar

    def AddLayer(self, name, alias=None, resultsLayer=False):
        """Adds layer to Map and update toolbar

        :param str name: layer (raster) name
        :param str resultsLayer: True if layer is temp. raster showing the results of
                                 computation
        """
        if resultsLayer and name in [
            layer.GetName() for layer in self.map.GetListOfLayers(name=name)
        ]:
            self.frame.Render(self.mapWindow)
            return

        cmdlist = ["d.rast", "map=%s" % name]
        self.map.AddLayer(
            ltype="raster",
            command=cmdlist,
            active=True,
            name=name,
            hidden=False,
            opacity=1.0,
            render=True,
        )
        self.frame.Render(self.mapWindow)

        if alias is not None:
            self.layerName[alias] = name
            name = alias
        else:
            self.layerName[name] = name

        self.toolbar.choice.Insert(name, 0)
        self.toolbar.choice.SetSelection(0)

    def AddLayerRGB(self, cmd):
        """Adds RGB layer and update toolbar.

        :param cmd: d.rgb command as a list
        """
        name = []
        for param in cmd:
            if "=" in param:
                name.append(param.split("=")[1])
        name = ",".join(name)
        self.map.AddLayer(
            ltype="rgb",
            command=cmd,
            active=True,
            name=name,
            hidden=False,
            opacity=1.0,
            render=True,
        )
        self.frame.Render(self.mapWindow)
        self.layerName[name] = name
        self.toolbar.choice.Insert(name, 0)
        self.toolbar.choice.SetSelection(0)

    def RemoveTemporaryLayer(self, name):
        """Removes temporary layer (if exists) from Map and and updates toolbar.

        :param name: real name of layer
        """
        # check if layer is loaded
        layers = self.map.GetListOfLayers(ltype="raster")
        idx = None
        for i, layer in enumerate(layers):
            if name == layer.GetName():
                idx = i
                break
        if idx is None:
            return
        # remove it from Map
        self.map.RemoveLayer(name=name)

        # update inner list of layers
        alias = self.GetAlias(name)
        if alias not in self.layerName:
            return

        del self.layerName[alias]
        # update choice
        idx = self.toolbar.choice.FindString(alias)
        if idx != wx.NOT_FOUND:
            self.toolbar.choice.Delete(idx)
            if not self.toolbar.choice.IsEmpty():
                self.toolbar.choice.SetSelection(0)

        self.frame.Render(self.mapWindow)

    def Render(self):
        """
        .. todo::
            giface should be used instead of this method"""
        self.frame.Render(self.mapWindow)

    def RemoveLayer(self, name, idx):
        """Removes layer from Map and update toolbar"""
        name = self.layerName[name]
        self.map.RemoveLayer(name=name)
        del self.layerName[name]
        self.toolbar.choice.Delete(idx)
        if not self.toolbar.choice.IsEmpty():
            self.toolbar.choice.SetSelection(0)

        self.frame.Render(self.mapWindow)

    def SelectLayer(self, name):
        """Moves selected layer to top"""
        layers = self.map.GetListOfLayers(ltype="rgb") + self.map.GetListOfLayers(
            ltype="raster"
        )
        idx = None
        for i, layer in enumerate(layers):
            if self.layerName[name] == layer.GetName():
                idx = i
                break

        if idx is not None:  # should not happen
            layers.append(layers.pop(idx))

            choice = self.toolbar.choice
            idx = choice.FindString(name)
            choice.Delete(idx)
            choice.Insert(name, 0)
            choice.SetSelection(0)

            # layers.reverse()
            self.map.SetLayers(layers)
            self.frame.Render(self.mapWindow)

    def SetOpacity(self, name):
        """Sets opacity of layers."""
        name = self.layerName[name]
        layers = self.map.GetListOfLayers(name=name)
        if not layers:
            return

        # works for first layer only
        oldOpacity = layers[0].GetOpacity()
        dlg = SetOpacityDialog(self.frame, opacity=oldOpacity)
        dlg.applyOpacity.connect(
            lambda value: self._changeOpacity(layer=layers[0], opacity=value)
        )

        if dlg.ShowModal() == wx.ID_OK:
            self._changeOpacity(layer=layers[0], opacity=dlg.GetOpacity())

        dlg.Destroy()

    def _changeOpacity(self, layer, opacity):
        self.map.ChangeOpacity(layer=layer, opacity=opacity)
        self.frame.Render(self.mapWindow)

    def GetAlias(self, name):
        """Returns alias for layer"""
        name = [k for k, v in self.layerName.items() if v == name]
        if name:
            return name[0]
        return None

    def SetAlias(self, original, alias):
        name = self.GetAlias(original)
        if name:
            self.layerName[alias] = original
            del self.layerName[name]
            idx = self.toolbar.choice.FindString(name)
            if idx != wx.NOT_FOUND:
                self.toolbar.choice.SetString(idx, alias)


def test():
    app = wx.App()

    frame = wx.Frame(
        parent=None,
        size=globalvar.MAP_WINDOW_SIZE,
        title=_("Supervised Classification Tool"),
    )
    frame = IClassMapDisplay(parent=frame)
    frame.Show()
    app.MainLoop()


if __name__ == "__main__":
    test()