File: statusbar.py

package info (click to toggle)
grass 6.4.4-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 104,028 kB
  • ctags: 40,409
  • sloc: ansic: 419,980; python: 63,559; tcl: 46,692; cpp: 29,791; sh: 18,564; makefile: 7,000; xml: 3,505; yacc: 561; perl: 559; lex: 480; sed: 70; objc: 7
file content (1068 lines) | stat: -rw-r--r-- 42,387 bytes parent folder | download
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
"""!
@package mapdisp.statusbar

@brief Classes for statusbar management

Classes:
 - statusbar::SbException
 - statusbar::SbManager
 - statusbar::SbItem
 - statusbar::SbRender
 - statusbar::SbShowRegion
 - statusbar::SbAlignExtent
 - statusbar::SbResolution
 - statusbar::SbMapScale
 - statusbar::SbGoTo
 - statusbar::SbProjection
 - statusbar::SbMask
 - statusbar::SbTextItem
 - statusbar::SbDisplayGeometry
 - statusbar::SbCoordinates
 - statusbar::SbRegionExtent
 - statusbar::SbCompRegionExtent
 - statusbar::SbProgress

(C) 2006-2011 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 wx

from core          import utils
from core.gcmd     import GMessage, RunCommand
from core.settings import UserSettings

from grass.script  import core as grass

class SbException:
    """! Exception class used in SbManager and SbItems"""
    def __init__(self, message):
        self.message = message
    def __str__(self):
        return self.message


class SbManager:
    """!Statusbar manager for wx.Statusbar and SbItems.
    
    Statusbar manager manages items added by AddStatusbarItem method.
    Provides progress bar (SbProgress) and choice (wx.Choice).
    Items with position 0 are shown according to choice selection.
    Only one item of the same class is supposed to be in statusbar.
    Manager user have to create statusbar on his own, add items to manager
    and call Update method to show particular widgets.
    User settings (group = 'display', key = 'statusbarMode', subkey = 'selection')
    are taken into account.
    
    @todo generalize access to UserSettings (specify group, etc.) 
    @todo add GetMode method using name instead of index
    """
    def __init__(self, mapframe, statusbar):
        """!Connects manager to statusbar
        
        Creates choice and progress bar.
        """
        self.mapFrame = mapframe
        self.statusbar = statusbar
        
        self.choice = wx.Choice(self.statusbar, wx.ID_ANY)
        
        self.choice.Bind(wx.EVT_CHOICE, self.OnToggleStatus)
        
        self.statusbarItems = dict()
        
        self._postInitialized = False
        
        self.progressbar = SbProgress(self.mapFrame, self.statusbar)
        
        self._hiddenItems = {}
    
    def SetProperty(self, name, value):
        """!Sets property represented by one of contained SbItems
            
        @param name name of SbItem (from name attribute)
        @param value value to be set
        """
        self.statusbarItems[name].SetValue(value)
        
    def GetProperty(self, name):
        """!Returns property represented by one of contained SbItems
        
        @param name name of SbItem (from name attribute)
        """
        return self.statusbarItems[name].GetValue()
        
    def HasProperty(self, name):
        """!Checks whether property is represented by one of contained SbItems
        
        @param name name of SbItem (from name attribute)
        
        @returns True if particular SbItem is contained, False otherwise
        """
        if name in self.statusbarItems:
            return True
        return False
    
    def AddStatusbarItem(self, item):
        """!Adds item to statusbar
        
        If item position is 0, item is managed by choice.
        
        @see AddStatusbarItemsByClass
        """
        self.statusbarItems[item.name] = item
        if item.GetPosition() == 0:
            self.choice.Append(item.label, clientData = item) #attrError?
            
    def AddStatusbarItemsByClass(self, itemClasses, **kwargs):
        """!Adds items to statusbar

        @param itemClasses list of classes of items to be add
        @param kwargs SbItem constructor parameters
        
        @see AddStatusbarItem
        """
        for Item in itemClasses:
            item = Item(**kwargs)
            self.AddStatusbarItem(item)
                      
    def HideStatusbarChoiceItemsByClass(self, itemClasses):
        """!Hides items showed in choice
        
        Hides items with position 0 (items showed in choice) by removing
        them from choice.
        
        @param itemClasses list of classes of items to be hided
        
        @see ShowStatusbarChoiceItemsByClass
        @todo consider adding similar function which would take item names
        """
        index = []
        for itemClass in itemClasses:
            for i in range(0, self.choice.GetCount() - 1):
                item = self.choice.GetClientData(i)
                if item.__class__ == itemClass:
                    index.append(i)
                    self._hiddenItems[i] = item
        # must be sorted in reverse order to be removed correctly
        for i in sorted(index, reverse = True):
            self.choice.Delete(i)
        
    def ShowStatusbarChoiceItemsByClass(self, itemClasses):
        """!Shows items showed in choice
        
        Shows items with position 0 (items showed in choice) by adding
        them to choice.
        Items are restored in their old positions.
        
        @param itemClasses list of classes of items to be showed
        
        @see HideStatusbarChoiceItemsByClass
        """
        # must be sorted to be inserted correctly
        for pos in sorted(self._hiddenItems.keys()):
            item = self._hiddenItems[pos]
            if item.__class__ in itemClasses:
                self.choice.Insert(item.label, pos, item)
        
    def ShowItem(self, itemName):
        """!Invokes showing of particular item
        
        @see Update
        """
        self.statusbarItems[itemName].Show()
        
    def _postInit(self):
        """!Post-initialization method
        
        It sets internal user settings,
        set choice's selection (from user settings) and does reposition.
        It needs choice filled by items.
        it is called automatically.
        """
        UserSettings.Set(group = 'display',
                         key = 'statusbarMode',
                         subkey = 'choices',
                         value = self.choice.GetItems(),
                         internal = True)
        
        self.choice.SetSelection(UserSettings.Get(group = 'display',
                                                  key = 'statusbarMode',
                                                  subkey = 'selection')) 
        self.Reposition()
        
        self._postInitialized = True
        
    def Update(self):
        """!Updates statusbar

        It always updates mask.
        """
        if not self._postInitialized:
            self._postInit()
        
        for item in self.statusbarItems.values():
            if item.GetPosition() == 0:
                item.Hide()
            else:
                item.Update() # mask, render
        
        if self.choice.GetCount() > 0:
            item = self.choice.GetClientData(self.choice.GetSelection())
            item.Update()
        
    def Reposition(self):
        """!Reposition items in statusbar
        
        Set positions to all items managed by statusbar manager.
        It should not be necessary to call it manually.
        """
        
        widgets = []
        for item in self.statusbarItems.values():
            widgets.append((item.GetPosition(), item.GetWidget()))
            
        widgets.append((1, self.choice))
        widgets.append((0, self.progressbar.GetWidget()))
                
        for idx, win in widgets:
            if not win:
                continue
            rect = self.statusbar.GetFieldRect(idx)
            if idx == 0: # show region / mapscale / process bar
                # -> size
                wWin, hWin = win.GetBestSize()
                if win == self.progressbar.GetWidget():
                    wWin = rect.width - 6
                # -> position
                # if win == self.statusbarWin['region']:
                # x, y = rect.x + rect.width - wWin, rect.y - 1
                # align left
                # else:
                x, y = rect.x + 3, rect.y - 1
                w, h = wWin, rect.height + 2
            else: # choice || auto-rendering
                x, y = rect.x, rect.y - 1
                w, h = rect.width, rect.height + 2
                if idx == 2: # mask
                    x += 5
                    y += 4
                elif idx == 3: # render
                    x += 5
            win.SetPosition((x, y))
            win.SetSize((w, h))
        
    def GetProgressBar(self):
        """!Returns progress bar"""
        return self.progressbar
    
    def OnToggleStatus(self, event):
        """!Toggle status text
        """
        self.Update()
        
    def SetMode(self, modeIndex):
        """!Sets current mode
        
        Mode is usually driven by user through choice.
        """
        self.choice.SetSelection(modeIndex)
    
    def GetMode(self):
        """!Returns current mode"""
        return self.choice.GetSelection()

class SbItem:
    """!Base class for statusbar items.
    
    Each item represents functionality (or action) controlled by statusbar
    and related to MapFrame.
    One item is usually connected with one widget but it is not necessary.
    Item can represent property (depends on manager).
    Items are not widgets but can provide interface to them.
    Items usually has requirements to MapFrame instance
    (specified as MapFrame.methodname or MapWindow.methodname).
    
    @todo consider externalizing position (see SbProgress use in SbManager)
    """
    def __init__(self, mapframe, statusbar, position = 0):
        """!
        
        @param mapframe instance of class with MapFrame interface
        @param statusbar statusbar instance (wx.Statusbar)
        @param position item position in statusbar
        
        @todo rewrite Update also in derived classes to take in account item position
        """
        self.mapFrame = mapframe
        self.statusbar = statusbar
        self.position = position
    
    def Show(self):
        """!Invokes showing of underlying widget.
        
        In derived classes it can do what is appropriate for it,
        e.g. showing text on statusbar (only).
        """
        self.widget.Show()
        
    def Hide(self):
        self.widget.Hide()
        
    def SetValue(self, value):
        self.widget.SetValue(value)
    
    def GetValue(self):
        return self.widget.GetValue()
        
    def GetPosition(self):
        return self.position
    
    def GetWidget(self):
        """!Returns underlaying winget.
        
        @return widget or None if doesn't exist
        """
        return self.widget
    
    def _update(self, longHelp):
        """!Default implementation for Update method.
        
        @param longHelp True to enable long help (help from toolbars)
        """
        self.statusbar.SetStatusText("", 0)
        self.Show()
        self.mapFrame.StatusbarEnableLongHelp(longHelp)
        
    def Update(self):
        """!Called when statusbar action is activated (e.g. through wx.Choice).
        """
        self._update(longHelp = False)

class SbRender(SbItem):
    """!Checkbox to enable and disable auto-rendering.
    
    Requires MapFrame.OnRender method.
    """
    def __init__(self, mapframe, statusbar, position = 0):
        SbItem.__init__(self, mapframe, statusbar, position)
        self.name = 'render'
        
        self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
                                  label = _("Render"))
        
        self.widget.SetValue(UserSettings.Get(group = 'display',
                                              key = 'autoRendering',
                                              subkey = 'enabled'))
        self.widget.Hide()
        self.widget.SetToolTip(wx.ToolTip (_("Enable/disable auto-rendering")))
                                            
        self.widget.Bind(wx.EVT_CHECKBOX, self.OnToggleRender)
        
    def OnToggleRender(self, event):
        # (other items should call self.mapFrame.IsAutoRendered())
        if self.GetValue():
            self.mapFrame.OnRender(None)

    def Update(self):
        self.Show()
        
class SbShowRegion(SbItem):
    """!Checkbox to enable and disable showing of computational region.
    
    Requires MapFrame.OnRender, MapFrame.IsAutoRendered, MapFrame.GetWindow.
    Expects that instance returned by MapFrame.GetWindow will handle
    regionCoords attribute. 
    """
    def __init__(self, mapframe, statusbar, position = 0):
        SbItem.__init__(self, mapframe, statusbar, position)
        self.name = 'region'
        self.label = _("Show comp. extent")
        
        self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
                                  label = _("Show computational extent"))
        
        self.widget.SetValue(False)
        self.widget.Hide()
        self.widget.SetToolTip(wx.ToolTip (_("Show/hide computational "
                                             "region extent (set with g.region). "
                                             "Display region drawn as a blue box inside the "
                                             "computational region, "
                                             "computational region inside a display region "
                                             "as a red box).")))
                                            
        self.widget.Bind(wx.EVT_CHECKBOX, self.OnToggleShowRegion)
    
    def OnToggleShowRegion(self, event):
        """!Shows/Hides extent (comp. region) in map canvas.
        
        Shows or hides according to checkbox value.
        """
        if self.widget.GetValue():
            # show extent
            self.mapFrame.GetWindow().regionCoords = []
        elif hasattr(self.mapFrame.GetWindow(), 'regionCoords'):
            del self.mapFrame.GetWindow().regionCoords

        # redraw map if auto-rendering is enabled
        if self.mapFrame.IsAutoRendered():
            self.mapFrame.OnRender(None)

    def SetValue(self, value):
        SbItem.SetValue(self, value)
        if value:
            self.mapFrame.GetWindow().regionCoords = []
        elif hasattr(self.mapFrame.GetWindow(), 'regionCoords'):
            del self.mapFrame.GetWindow().regionCoords
            
class SbAlignExtent(SbItem):
    """!Checkbox to select zoom behavior.
    
    Used by BufferedWindow (through MapFrame property).
    See tooltip for explanation.
    """
    def __init__(self, mapframe, statusbar, position = 0):
        SbItem.__init__(self, mapframe, statusbar, position)
        self.name = 'alignExtent'
        self.label = _("Display mode")
        
        self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
                                  label = _("Align region extent based on display size"))
        
        self.widget.SetValue(UserSettings.Get(group = 'display', key = 'alignExtent', subkey = 'enabled'))
        self.widget.Hide()
        self.widget.SetToolTip(wx.ToolTip (_("Align region extent based on display "
                                             "size from center point. "
                                             "Default value for new map displays can "
                                             "be set up in 'User GUI settings' dialog.")))      
        
class SbResolution(SbItem):
    """!Checkbox to select used display resolution.
    
    Requires MapFrame.OnRender method. 
    """
    def __init__(self, mapframe, statusbar, position = 0):
        SbItem.__init__(self, mapframe, statusbar, position)
        self.name = 'resolution'
        self.label = _("Display resolution")
        
        self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
                                  label = _("Constrain display resolution to computational settings"))
        
        self.widget.SetValue(UserSettings.Get(group = 'display', key = 'compResolution', subkey = 'enabled'))
        self.widget.Hide()
        self.widget.SetToolTip(wx.ToolTip (_("Constrain display resolution "
                                             "to computational region settings. "
                                             "Default value for new map displays can "
                                             "be set up in 'User GUI settings' dialog.")))
                                            
        self.widget.Bind(wx.EVT_CHECKBOX, self.OnToggleUpdateMap)
        
    def OnToggleUpdateMap(self, event):
        """!Update display when toggle display mode
        """
        # redraw map if auto-rendering is enabled
        if self.mapFrame.IsAutoRendered():
            self.mapFrame.OnRender(None)


class SbMapScale(SbItem):
    """!Editable combobox to get/set current map scale.
    
    Requires MapFrame.GetMapScale, MapFrame.SetMapScale
    and MapFrame.GetWindow (and GetWindow().UpdateMap()).
    """
    def __init__(self, mapframe, statusbar, position = 0):
        SbItem.__init__(self, mapframe, statusbar, position)
        self.name = 'mapscale'
        self.label = _("Map scale")
        
        self.widget = wx.ComboBox(parent = self.statusbar, id = wx.ID_ANY,
                                                    style = wx.TE_PROCESS_ENTER,
                                                    size = (150, -1))
        
        self.widget.SetItems(['1:1000',
                              '1:5000',
                              '1:10000',
                              '1:25000',
                              '1:50000',
                              '1:100000',
                              '1:1000000'])
        self.widget.Hide()
        self.widget.SetToolTip(wx.ToolTip (_("As everyone's monitors and resolutions "
                                            "are set differently these values are not "
                                            "true map scales, but should get you into "
                                            "the right neighborhood.")))
                                            
        self.widget.Bind(wx.EVT_TEXT_ENTER, self.OnChangeMapScale)
        self.widget.Bind(wx.EVT_COMBOBOX, self.OnChangeMapScale)
        
        self.lastMapScale = None

    def Update(self):
        scale = self.mapFrame.GetMapScale()
        self.statusbar.SetStatusText("")
        try:
            self.SetValue("1:%ld" % (scale + 0.5))
        except TypeError:
            pass # FIXME, why this should happen?
        
        self.lastMapScale = scale
        self.Show()

        # disable long help
        self.mapFrame.StatusbarEnableLongHelp(False)

    def OnChangeMapScale(self, event):
        """!Map scale changed by user
        """
        scale = event.GetString()

        try:
            if scale[:2] != '1:':
                raise ValueError
            value = int(scale[2:])
        except ValueError:
            self.SetValue('1:%ld' % int(self.lastMapScale))
            return
        
        self.mapFrame.SetMapScale(value)
        
        # redraw a map
        self.mapFrame.GetWindow().UpdateMap()
        self.GetWidget().SetFocus()
        
        
class SbGoTo(SbItem):
    """!Textctrl to set coordinates which to focus on.
    
    Requires MapFrame.GetWindow, MapWindow.GoTo method.
    """
    
    def __init__(self, mapframe, statusbar, position = 0):
        SbItem.__init__(self, mapframe, statusbar, position)
        self.name = 'goto'
        self.label = _("Go to")
        
        self.widget = wx.TextCtrl(parent = self.statusbar, id = wx.ID_ANY,
                                                value = "", style = wx.TE_PROCESS_ENTER,
                                                size = (300, -1))
        
        self.widget.Hide()
        
        self.widget.Bind(wx.EVT_TEXT_ENTER, self.OnGoTo)
    
    def ReprojectENToMap(self, e, n, useDefinedProjection):
        """!Reproject east, north from user defined projection
        
        @param e,n coordinate (for DMS string, else float or string)
        @param useDefinedProjection projection defined by user in settings dialog
        
        @throws SbException if useDefinedProjection is True and projection is not defined in UserSettings
        """
        if useDefinedProjection:
            settings = UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'proj4')
            if not settings:
                raise SbException(_("Projection not defined (check the settings)"))
            else:
                # reproject values
                projIn = settings
                projOut = RunCommand('g.proj',
                                     flags = 'jf',
                                     read = True)
                proj = projIn.split(' ')[0].split('=')[1]
                if proj in ('ll', 'latlong', 'longlat'):
                    e, n = utils.DMS2Deg(e, n)
                    proj, coord1 = utils.ReprojectCoordinates(coord = (e, n),
                                                              projIn = projIn,
                                                              projOut = projOut, flags = 'd')
                    e, n = coord1
                else:
                    e, n = float(e), float(n)
                    proj, coord1 = utils.ReprojectCoordinates(coord = (e, n),
                                                              projIn = projIn,
                                                              projOut = projOut, flags = 'd')
                    e, n = coord1
        elif self.mapFrame.GetMap().projinfo['proj'] == 'll':
            e, n = utils.DMS2Deg(e, n)
        else: 
            e, n = float(e), float(n)
        return e, n

    def OnGoTo(self, event):
        """!Go to position
        """
        try:
            e, n = self.GetValue().split(';')
            e, n = self.ReprojectENToMap(e, n, self.mapFrame.GetProperty('projection'))
            self.mapFrame.GetWindow().GoTo(e, n)
            self.widget.SetFocus()
        except ValueError:
            # FIXME: move this code to MapWindow/BufferedWindow/MapFrame
            region = self.mapFrame.GetMap().GetCurrentRegion()
            precision = int(UserSettings.Get(group = 'projection', key = 'format',
                                             subkey = 'precision'))
            format = UserSettings.Get(group = 'projection', key = 'format',
                                      subkey = 'll')
            if self.mapFrame.GetMap().projinfo['proj'] == 'll' and format == 'DMS':
                    self.SetValue("%s" % utils.Deg2DMS(region['center_easting'], 
                                                                            region['center_northing'],
                                                                            precision = precision))
            else:
                self.SetValue("%.*f; %.*f" % \
                               (precision, region['center_easting'],
                                precision, region['center_northing']))
        except SbException, e:
            # FIXME: this may be useless since statusbar update checks user defined projection and this exception raises when user def proj does not exists
            self.statusbar.SetStatusText(str(e), 0)

    def GetCenterString(self, map):
        """!Get current map center in appropriate format"""
        region = map.GetCurrentRegion()
        precision = int(UserSettings.Get(group = 'projection', key = 'format',
                                         subkey = 'precision'))
        format = UserSettings.Get(group = 'projection', key = 'format',
                                  subkey = 'll')
        projection = UserSettings.Get(group='projection', key='statusbar', subkey='proj4')
        
        if self.mapFrame.GetProperty('projection'):
            if not projection:
                raise SbException(_("Projection not defined (check the settings)"))
            else:
                proj, coord  = utils.ReprojectCoordinates(coord = (region['center_easting'],
                                                                   region['center_northing']),
                                                          projOut = projection,
                                                          flags = 'd')
                if coord:
                    if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
                        return "%s" % utils.Deg2DMS(coord[0],
                                                                                coord[1],
                                                                                precision = precision)
                    else:
                        return "%.*f; %.*f" % (precision, coord[0], precision, coord[1])
                else:
                    raise SbException(_("Error in projection (check the settings)"))
        else:
            if self.mapFrame.GetMap().projinfo['proj'] == 'll' and format == 'DMS':
                return "%s" % utils.Deg2DMS(region['center_easting'], region['center_northing'],
                                                                      precision = precision)
            else:
                return "%.*f; %.*f" % (precision, region['center_easting'], precision, region['center_northing'])


    def SetCenter(self):
        """!Set current map center as item value"""
        center = self.GetCenterString(self.mapFrame.GetMap())
        self.SetValue(center)
        
    def Update(self):
        self.statusbar.SetStatusText("")
        
        try:
            self.SetCenter()
            self.Show()
        except SbException, e:
            self.statusbar.SetStatusText(str(e), 0)
                        
        # disable long help
        self.mapFrame.StatusbarEnableLongHelp(False)
        

class SbProjection(SbItem):
    """!Checkbox to enable user defined projection (can be set in settings)"""
    def __init__(self, mapframe, statusbar, position = 0):
        SbItem.__init__(self, mapframe, statusbar, position)
        self.name = 'projection'
        self.label = _("Projection")
        
        self.defaultLabel = _("Use defined projection")
        
        self.widget = wx.CheckBox(parent = self.statusbar, id = wx.ID_ANY,
                                  label = self.defaultLabel)
        
        self.widget.SetValue(False)
        
        # necessary?
        size = self.widget.GetSize()
        self.widget.SetMinSize((size[0] + 150, size[1]))
        
        self.widget.Hide()
        self.widget.SetToolTip(wx.ToolTip (_("Reproject coordinates displayed "
                                             "in the statusbar. Projection can be "
                                             "defined in GUI preferences dialog "
                                             "(tab 'Projection')")))
                                            
    def Update(self):
        self.statusbar.SetStatusText("")
        epsg = UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'epsg')
        if epsg:
            label = '%s (EPSG: %s)' % (self.defaultLabel, epsg)
            self.widget.SetLabel(label)
        else:
            self.widget.SetLabel(self.defaultLabel)
        self.Show()
        
        # disable long help
        self.mapFrame.StatusbarEnableLongHelp(False)
        

class SbMask(SbItem):
    """!StaticText to show whether mask is activated."""
    def __init__(self, mapframe, statusbar, position = 0):
        SbItem.__init__(self, mapframe, statusbar, position)
        self.name = 'mask'
        
        self.widget = wx.StaticText(parent = self.statusbar, id = wx.ID_ANY, label = _('MASK'))
        self.widget.SetForegroundColour(wx.Colour(255, 0, 0))
        self.widget.Hide()
        
    def Update(self):
        if grass.find_file(name = 'MASK', element = 'cell',
                           mapset = grass.gisenv()['MAPSET'])['name']:
            self.Show()
        else:
            self.Hide()
        
class SbTextItem(SbItem):
    """!Base class for items without widgets.
    
    Only sets statusbar text.
    """
    def __init__(self, mapframe, statusbar, position = 0):
        SbItem.__init__(self, mapframe, statusbar, position)
        
        self.text = None
        
    def Show(self):
        self.statusbar.SetStatusText(self.GetValue(), self.position)
        
    def Hide(self):
        self.statusbar.SetStatusText("", self.position)
        
    def SetValue(self, value):
        self.text = value
    
    def GetValue(self):
        return self.text
            
    def GetWidget(self):
        return None
    
    def Update(self):
        self._update(longHelp = True)

class SbDisplayGeometry(SbTextItem):
    """!Show current display resolution."""
    def __init__(self, mapframe, statusbar, position = 0):
        SbTextItem.__init__(self, mapframe, statusbar, position)
        self.name = 'displayGeometry'
        self.label = _("Display geometry")
        
    def Show(self):
        region = self.mapFrame.GetMap().GetCurrentRegion()
        self.SetValue("rows=%d; cols=%d; nsres=%.2f; ewres=%.2f" %
                     (region["rows"], region["cols"],
                      region["nsres"], region["ewres"]))
        SbTextItem.Show(self)

class SbCoordinates(SbTextItem):
    """!Show map coordinates when mouse moves.
    
    Requires MapWindow.GetLastEN method."""
    def __init__(self, mapframe, statusbar, position = 0):
        SbTextItem.__init__(self, mapframe, statusbar, position)
        self.name = 'coordinates'
        self.label = _("Coordinates")
        
    def Show(self):
        precision = int(UserSettings.Get(group = 'projection', key = 'format',
                             subkey = 'precision'))
        format = UserSettings.Get(group = 'projection', key = 'format',
                                       subkey = 'll')
        projection = self.mapFrame.GetProperty('projection')
        try:
            e, n = self.mapFrame.GetWindow().GetLastEN()
            self.SetValue(self.ReprojectENFromMap(e, n, projection, precision, format))
        except SbException, e:
            self.SetValue(e)
        except TypeError, e:
            self.SetValue("")
        except AttributeError:
            self.SetValue("") # during initialization MapFrame has no MapWindow
        SbTextItem.Show(self)
        
    def ReprojectENFromMap(self, e, n, useDefinedProjection, precision, format):
        """!Reproject east, north to user defined projection.
        
        @param e,n coordinate
        
        @throws SbException if useDefinedProjection is True and projection is not defined in UserSettings
        """
        if useDefinedProjection:
            settings = UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'proj4')
            if not settings:
                raise SbException(_("Projection not defined (check the settings)"))
            else:
                # reproject values
                proj, coord  = utils.ReprojectCoordinates(coord = (e, n),
                                                          projOut = settings,
                                                          flags = 'd')
                if coord:
                    e, n = coord
                    if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
                        return utils.Deg2DMS(e, n, precision = precision)
                    else:
                        return "%.*f; %.*f" % (precision, e, precision, n)
                else:
                    raise SbException(_("Error in projection (check the settings)"))
        else:
            if self.mapFrame.GetMap().projinfo['proj'] == 'll' and format == 'DMS':
                return utils.Deg2DMS(e, n, precision = precision)
            else:
                return "%.*f; %.*f" % (precision, e, precision, n)
        
class SbRegionExtent(SbTextItem):
    """!Shows current display region"""
    def __init__(self, mapframe, statusbar, position = 0):
        SbTextItem.__init__(self, mapframe, statusbar, position)
        self.name = 'displayRegion'
        self.label = _("Extent")
        
    def Show(self):
        precision = int(UserSettings.Get(group = 'projection', key = 'format',
                             subkey = 'precision'))
        format = UserSettings.Get(group = 'projection', key = 'format',
                                       subkey = 'll')
        projection = self.mapFrame.GetProperty('projection')        
        region = self._getRegion()
        try:
            regionReprojected = self.ReprojectRegionFromMap(region, projection, precision, format)
            self.SetValue(regionReprojected)
        except SbException, e:
            self.SetValue(e)
        SbTextItem.Show(self)
    
    def _getRegion(self):
        """!Get current display region"""
        return self.mapFrame.GetMap().GetCurrentRegion() # display region
        
    def _formatRegion(self, w, e, s, n, nsres, ewres, precision = None):
        """!Format display region string for statusbar

        @param nsres,ewres unused
        """
        if precision is not None:
            return "%.*f - %.*f, %.*f - %.*f" % (precision, w, precision, e,
                                                 precision, s, precision, n)
        else:
            return "%s - %s, %s - %s" % (w, e, s, n)
         
           
    def ReprojectRegionFromMap(self, region, useDefinedProjection, precision, format):
        """!Reproject region values
        
        @todo reorganize this method to remove code useful only for derived class SbCompRegionExtent
        """
        if useDefinedProjection:
            settings = UserSettings.Get(group = 'projection', key = 'statusbar', subkey = 'proj4')
            
            if not settings:
                raise SbException(_("Projection not defined (check the settings)"))
            else:
                projOut = settings
                proj, coord1 = utils.ReprojectCoordinates(coord = (region["w"], region["s"]),
                                                          projOut = projOut, flags = 'd')
                proj, coord2 = utils.ReprojectCoordinates(coord = (region["e"], region["n"]),
                                                          projOut = projOut, flags = 'd')
                # useless, used in derived class
                proj, coord3 = utils.ReprojectCoordinates(coord = (0.0, 0.0),
                                                          projOut = projOut, flags = 'd')
                proj, coord4 = utils.ReprojectCoordinates(coord = (region["ewres"], region["nsres"]),
                                                          projOut = projOut, flags = 'd')
                if coord1 and coord2:
                    if proj in ('ll', 'latlong', 'longlat') and format == 'DMS':
                        w, s = utils.Deg2DMS(coord1[0], coord1[1], string = False,
                                             precision = precision)
                        e, n = utils.Deg2DMS(coord2[0], coord2[1], string = False,
                                             precision = precision)
                        ewres, nsres = utils.Deg2DMS(abs(coord3[0]) - abs(coord4[0]),
                                                         abs(coord3[1]) - abs(coord4[1]),
                                                         string = False, hemisphere = False,
                                                         precision = precision)
                        return self._formatRegion(w = w, s = s, e = e, n = n, ewres = ewres, nsres = nsres)
                    else:
                        w, s = coord1
                        e, n = coord2
                        ewres, nsres = coord3
                        return self._formatRegion(w = w, s = s, e = e, n = n, ewres = ewres,
                                                  nsres = nsres, precision = precision)
                else:
                    raise SbException(_("Error in projection (check the settings)"))
                
        else:
            if self.mapFrame.GetMap().projinfo['proj'] == 'll' and format == 'DMS':
                w, s = utils.Deg2DMS(region["w"], region["s"],
                                     string = False, precision = precision)
                e, n = utils.Deg2DMS(region["e"], region["n"],
                                     string = False, precision = precision)
                ewres, nsres = utils.Deg2DMS(region['ewres'], region['nsres'],
                                             string = False, precision = precision)
                return self._formatRegion(w = w, s = s, e = e, n = n, ewres = ewres, nsres = nsres)
            else:
                w, s = region["w"], region["s"]
                e, n = region["e"], region["n"]
                ewres, nsres = region['ewres'], region['nsres']
                return self._formatRegion(w = w, s = s, e = e, n = n, ewres = ewres,
                                          nsres = nsres, precision = precision)
                                
                                
class SbCompRegionExtent(SbRegionExtent):
    """!Shows computational region."""
    def __init__(self, mapframe, statusbar, position = 0):
        SbRegionExtent.__init__(self, mapframe, statusbar, position)
        self.name = 'computationalRegion'
        self.label = _("Comp. region")
        
    def _formatRegion(self, w, e, s, n, ewres, nsres, precision = None):
        """!Format computational region string for statusbar"""
        if precision is not None:
            return "%.*f - %.*f, %.*f - %.*f (%.*f, %.*f)" % (precision, w, precision, e,
                                                              precision, s, precision, n,
                                                              precision, ewres, precision, nsres)
        else:
            return "%s - %s, %s - %s (%s, %s)" % (w, e, s, n, ewres, nsres)
        
    def _getRegion(self):
        """!Returns computational region."""
        return self.mapFrame.GetMap().GetRegion() # computational region
        
        
class SbProgress(SbItem):
    """!General progress bar to show progress.
    
    Underlaying widget is wx.Gauge.
    """
    def __init__(self, mapframe, statusbar, position = 0):
        SbItem.__init__(self, mapframe, statusbar, position)
        self.name = 'progress'

        # on-render gauge
        self.widget = wx.Gauge(parent = self.statusbar, id = wx.ID_ANY,
                                      range = 0, style = wx.GA_HORIZONTAL)
        self.widget.Hide()
        
    def GetRange(self):
        """!Returns progress range."""
        return self.widget.GetRange()
    
    def SetRange(self, range):
        """!Sets progress range."""
        self.widget.SetRange(range)
        
    def SetValue(self, value):
        if value >= value:
            self.widget.SetValue(self.GetRange())
        else:
            self.widget.SetValue(value)
    

class SbGoToGCP(SbItem):
    """!SpinCtrl to select GCP to focus on
    
    Requires MapFrame.GetSrcWindow, MapFrame.GetTgtWindow, MapFrame.GetListCtrl,
    MapFrame.GetMapCoordList.
    """
    
    def __init__(self, mapframe, statusbar, position = 0):
        SbItem.__init__(self, mapframe, statusbar, position)
        self.name = 'gotoGCP'
        self.label = _("Go to GCP No.")

        self.widget = wx.SpinCtrl(parent = self.statusbar, id = wx.ID_ANY,
                                                value = "", min = 0)
        self.widget.Hide()
        
        self.widget.Bind(wx.EVT_TEXT_ENTER, self.OnGoToGCP)
        self.widget.Bind(wx.EVT_SPINCTRL, self.OnGoToGCP)
    
    def OnGoToGCP(self, event):
        """!Zooms to given GCP."""
        GCPNo = self.GetValue()
        mapCoords = self.mapFrame.GetMapCoordList()
        
        if GCPNo < 0 or GCPNo > len(mapCoords): # always false, spin checks it
            GMessage(parent = self,
                     message = "%s 1 - %s." % (_("Valid Range:"),
                                               len(mapCoords)))
            return

        if GCPNo == 0:
            return
            
        listCtrl = self.mapFrame.GetListCtrl()
        
        listCtrl.selectedkey = GCPNo
        listCtrl.selected = listCtrl.FindItemData(-1, GCPNo)
        listCtrl.render = False
        listCtrl.SetItemState(listCtrl.selected,
                          wx.LIST_STATE_SELECTED,
                          wx.LIST_STATE_SELECTED)
        listCtrl.render = True
        
        listCtrl.EnsureVisible(listCtrl.selected)

        srcWin = self.mapFrame.GetSrcWindow()
        tgtWin = self.mapFrame.GetTgtWindow()
        
        # Source MapWindow:
        begin = (mapCoords[GCPNo][1], mapCoords[GCPNo][2])
        begin = srcWin.Cell2Pixel(begin)
        end = begin
        srcWin.Zoom(begin, end, 0)

        # redraw map
        srcWin.UpdateMap()

        if self.mapFrame.GetShowTarget():
            # Target MapWindow:
            begin = (mapCoords[GCPNo][3], mapCoords[GCPNo][4])
            begin = tgtWin.Cell2Pixel(begin)
            end = begin
            tgtWin.Zoom(begin, end, 0)

            # redraw map
            tgtWin.UpdateMap()

        self.GetWidget().SetFocus()
    
    def Update(self):
        self.statusbar.SetStatusText("")
        max = self.mapFrame.GetListCtrl().GetItemCount()
        if max < 1:
            max = 1
        self.widget.SetRange(0, max)
        self.Show()
                        
        # disable long help
        self.mapFrame.StatusbarEnableLongHelp(False)
        
class SbRMSError(SbTextItem):
    """!Shows RMS error.
    
    Requires MapFrame.GetFwdError, MapFrame.GetBkwError.
    """
    def __init__(self, mapframe, statusbar, position = 0):
        SbTextItem.__init__(self, mapframe, statusbar, position)
        self.name = 'RMSError'
        self.label = _("RMS error")
        
    def Show(self):
        self.SetValue(_("Forward: %(forw)s, Backward: %(back)s") %
                                   { 'forw' : self.mapFrame.GetFwdError(),
                                     'back' : self.mapFrame.GetBkwError() })
        SbTextItem.Show(self)