File: mapdisp.py

package info (click to toggle)
grass 7.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 135,976 kB
  • ctags: 44,148
  • sloc: ansic: 410,300; python: 166,939; cpp: 34,819; sh: 9,358; makefile: 6,618; xml: 3,551; sql: 769; lex: 519; yacc: 450; asm: 387; perl: 282; sed: 17; objc: 7
file content (694 lines) | stat: -rw-r--r-- 22,177 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
"""
@package gui_core.mapdisp

@brief Base classes for Map display window

Classes:
 - mapdisp::MapFrameBase
 - mapdisp::SingleMapFrame
 - mapdisp::DoubleMapFrame

(C) 2009-2014 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 Martin Landa <landa.martin gmail.com>
@author Michael Barton <michael.barton@asu.edu>
@author Vaclav Petras <wenzeslaus gmail.com>
@author Anna Kratochvilova <kratochanna gmail.com>
"""

import os
import sys

import wx

from core import globalvar
from core.debug import Debug
from core.utils import _
from gui_core.toolbars import ToolSwitcher

from grass.script import core as grass


class MapFrameBase(wx.Frame):
    """Base class for map display window

    Derived class must use (create and initialize) \c statusbarManager
    or override
    GetProperty(), SetProperty() and HasProperty() methods.

    Several methods has to be overriden or
    \c NotImplementedError("MethodName") will be raised.

    If derived class enables and disables auto-rendering,
    it should override IsAutoRendered method.

    It is expected that derived class will call _setUpMapWindow().

    Derived class can has one or more map windows (and map renderes)
    but implementation of MapFrameBase expects that one window and
    one map will be current.
    Current instances of map window and map renderer should be returned
    by methods GetWindow() and GetMap() respectively.

    AUI manager is stored in \c self._mgr.
    """

    def __init__(self, parent=None, id=wx.ID_ANY, title='',
                 style=wx.DEFAULT_FRAME_STYLE,
                 auimgr=None, name='', **kwargs):
        """

        .. warning::
            Use \a auimgr parameter only if you know what you are doing.

        :param parent: gui parent
        :param id: wx id
        :param title: window title
        :param style: \c wx.Frame style
        :param toolbars: array of activated toolbars, e.g. ['map', 'digit']
        :param auimgr: AUI manager (if \c None, wx.aui.AuiManager is used)
        :param name: frame name
        :param kwargs: arguments passed to \c wx.Frame
        """

        self.parent = parent

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

        #
        # set the size & system icon
        #
        self.SetClientSize(self.GetSize())
        self.iconsize = (16, 16)

        self.SetIcon(
            wx.Icon(
                os.path.join(
                    globalvar.ICONDIR,
                    'grass_map.ico'),
                wx.BITMAP_TYPE_ICO))

        # toolbars
        self.toolbars = {}

        #
        # Fancy gui
        #
        if auimgr is None:
            from wx.aui import AuiManager
            self._mgr = AuiManager(self)
        else:
            self._mgr = auimgr

        # handles switching between tools in different toolbars
        self._toolSwitcher = ToolSwitcher()
        self._toolSwitcher.toggleToolChanged.connect(self._onToggleTool)

        # set accelerator table (fullscreen, close window)
        accelTable = []
        for wxId, handler, entry, kdb in (
            (wx.NewId(),
             self.OnFullScreen, wx.ACCEL_NORMAL, wx.WXK_F11),
            (wx.NewId(),
             self.OnCloseWindow, wx.ACCEL_CTRL, ord('W'))):
            self.Bind(wx.EVT_MENU, handler, id=wxId)
            accelTable.append((entry, kdb, wxId))

        self.SetAcceleratorTable(wx.AcceleratorTable(accelTable))

    def _initMap(self, Map):
        """Initialize map display, set dimensions and map region
        """
        if not grass.find_program('g.region', '--help'):
            sys.exit(_("GRASS module '%s' not found. Unable to start map "
                       "display window.") % 'g.region')

        Debug.msg(2, "MapFrame._initMap():")
        Map.ChangeMapSize(self.GetClientSize())
        Map.region = Map.GetRegion()  # g.region -upgc
        # self.Map.SetRegion() # adjust region to match display window

    def _resize(self):
        Debug.msg(1, "MapFrame._resize():")
        wm, hw = self.MapWindow.GetClientSize()
        wf, hf = self.GetSize()
        dw = wf - wm
        dh = hf - hw
        self.SetSize((wf + dw, hf + dh))

    def _onToggleTool(self, id):
        if self._toolSwitcher.IsToolInGroup(id, 'mouseUse'):
            self.GetWindow().UnregisterAllHandlers()

    def OnSize(self, event):
        """Adjust statusbar on changing size"""
        # reposition checkbox in statusbar
        self.StatusbarReposition()

        # update statusbar
        self.StatusbarUpdate()

    def OnFullScreen(self, event):
        """!Switch fullscreen mode, hides also toolbars"""
        for toolbar in self.toolbars.keys():
            self._mgr.GetPane(self.toolbars[toolbar]).Show(self.IsFullScreen())
        self._mgr.Update()
        self.ShowFullScreen(not self.IsFullScreen())
        event.Skip()

    def OnCloseWindow(self, event):
        self.Destroy()

    def GetToolSwitcher(self):
        return self._toolSwitcher

    def SetProperty(self, name, value):
        """Sets property"""
        self.statusbarManager.SetProperty(name, value)

    def GetProperty(self, name):
        """Returns property"""
        return self.statusbarManager.GetProperty(name)

    def HasProperty(self, name):
        """Checks whether object has property"""
        return self.statusbarManager.HasProperty(name)

    def GetPPM(self):
        """Get pixel per meter

        .. todo::
            now computed every time, is it necessary?

        .. todo::
            enable user to specify ppm (and store it in UserSettings)
        """
        # TODO: need to be fixed...
        # screen X region problem
        # user should specify ppm
        dc = wx.ScreenDC()
        dpSizePx = wx.DisplaySize()   # display size in pixels
        dpSizeMM = wx.DisplaySizeMM()  # display size in mm (system)
        dpSizeIn = (dpSizeMM[0] / 25.4, dpSizeMM[1] / 25.4)  # inches
        sysPpi = dc.GetPPI()
        comPpi = (dpSizePx[0] / dpSizeIn[0],
                  dpSizePx[1] / dpSizeIn[1])

        ppi = comPpi                  # pixel per inch
        ppm = ((ppi[0] / 2.54) * 100,  # pixel per meter
               (ppi[1] / 2.54) * 100)

        Debug.msg(4, "MapFrameBase.GetPPM(): size: px=%d,%d mm=%f,%f "
                  "in=%f,%f ppi: sys=%d,%d com=%d,%d; ppm=%f,%f" %
                  (dpSizePx[0], dpSizePx[1], dpSizeMM[0], dpSizeMM[1],
                   dpSizeIn[0], dpSizeIn[1],
                   sysPpi[0], sysPpi[1], comPpi[0], comPpi[1],
                   ppm[0], ppm[1]))

        return ppm

    def SetMapScale(self, value, map=None):
        """Set current map scale

        :param value: scale value (n if scale is 1:n)
        :param map: Map instance (if none self.Map is used)
        """
        if not map:
            map = self.Map

        region = self.Map.region
        dEW = value * (region['cols'] / self.GetPPM()[0])
        dNS = value * (region['rows'] / self.GetPPM()[1])
        region['n'] = region['center_northing'] + dNS / 2.
        region['s'] = region['center_northing'] - dNS / 2.
        region['w'] = region['center_easting'] - dEW / 2.
        region['e'] = region['center_easting'] + dEW / 2.

        # add to zoom history
        self.GetWindow().ZoomHistory(region['n'], region['s'],
                                     region['e'], region['w'])

    def GetMapScale(self, map=None):
        """Get current map scale

        :param map: Map instance (if none self.Map is used)
        """
        if not map:
            map = self.GetMap()

        region = map.region
        ppm = self.GetPPM()

        heightCm = region['rows'] / ppm[1] * 100
        widthCm = region['cols'] / ppm[0] * 100

        Debug.msg(4, "MapFrame.GetMapScale(): width_cm=%f, height_cm=%f" %
                  (widthCm, heightCm))

        xscale = (region['e'] - region['w']) / (region['cols'] / ppm[0])
        yscale = (region['n'] - region['s']) / (region['rows'] / ppm[1])
        scale = (xscale + yscale) / 2.

        Debug.msg(
            3, "MapFrame.GetMapScale(): xscale=%f, yscale=%f -> scale=%f" %
            (xscale, yscale, scale))

        return scale

    def GetProgressBar(self):
        """Returns progress bar

        Progress bar can be used by other classes.
        """
        return self.statusbarManager.GetProgressBar()

    def GetMap(self):
        """Returns current map (renderer) instance"""
        raise NotImplementedError("GetMap")

    def GetWindow(self):
        """Returns current map window"""
        raise NotImplementedError("GetWindow")

    def GetWindows(self):
        """Returns list of map windows"""
        raise NotImplementedError("GetWindows")

    def GetMapToolbar(self):
        """Returns toolbar with zooming tools"""
        raise NotImplementedError("GetMapToolbar")

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

        return None

    def StatusbarUpdate(self):
        """Update statusbar content"""
        if self.statusbarManager:
            Debug.msg(5, "MapFrameBase.StatusbarUpdate()")
            self.statusbarManager.Update()

    def IsAutoRendered(self):
        """Check if auto-rendering is enabled"""
        # TODO: this is now not the right place to access this attribute
        # TODO: add mapWindowProperties to init parameters
        # and pass the right object in the init of derived class?
        # or do not use this method at all, let mapwindow decide
        return self.mapWindowProperties.autoRender

    def CoordinatesChanged(self):
        """Shows current coordinates on statusbar.
        """
        # assuming that the first mode is coordinates
        # probably shold not be here but good solution is not available now
        if self.statusbarManager:
            if self.statusbarManager.GetMode() == 0:
                self.statusbarManager.ShowItem('coordinates')

    def StatusbarReposition(self):
        """Reposition items in statusbar"""
        if self.statusbarManager:
            self.statusbarManager.Reposition()

    def StatusbarEnableLongHelp(self, enable=True):
        """Enable/disable toolbars long help"""
        for toolbar in self.toolbars.itervalues():
            toolbar.EnableLongHelp(enable)

    def IsStandalone(self):
        """Check if map frame is standalone"""
        raise NotImplementedError("IsStandalone")

    def OnRender(self, event):
        """Re-render map composition (each map layer)
        """
        raise NotImplementedError("OnRender")

    def OnDraw(self, event):
        """Re-display current map composition
        """
        self.MapWindow.UpdateMap(render=False)

    def OnErase(self, event):
        """Erase the canvas
        """
        self.MapWindow.EraseMap()

    def OnZoomIn(self, event):
        """Zoom in the map."""
        self.MapWindow.SetModeZoomIn()

    def OnZoomOut(self, event):
        """Zoom out the map."""
        self.MapWindow.SetModeZoomOut()

    def _setUpMapWindow(self, mapWindow):
        """Binds map windows' zoom history signals to map toolbar."""
        # enable or disable zoom history tool
        if self.GetMapToolbar():
            mapWindow.zoomHistoryAvailable.connect(
                lambda:
                self.GetMapToolbar().Enable('zoomBack', enable=True))
            mapWindow.zoomHistoryUnavailable.connect(
                lambda:
                self.GetMapToolbar().Enable('zoomBack', enable=False))
        mapWindow.mouseMoving.connect(self.CoordinatesChanged)

    def OnPointer(self, event):
        """Sets mouse mode to pointer."""
        self.MapWindow.SetModePointer()

    def OnPan(self, event):
        """Panning, set mouse to drag
        """
        self.MapWindow.SetModePan()

    def OnZoomBack(self, event):
        """Zoom last (previously stored position)
        """
        self.MapWindow.ZoomBack()

    def OnZoomToMap(self, event):
        """
        Set display extents to match selected raster (including NULLs)
        or vector map.
        """
        self.MapWindow.ZoomToMap(layers=self.Map.GetListOfLayers())

    def OnZoomToWind(self, event):
        """Set display geometry to match computational region
        settings (set with g.region)
        """
        self.MapWindow.ZoomToWind()

    def OnZoomToDefault(self, event):
        """Set display geometry to match default region settings
        """
        self.MapWindow.ZoomToDefault()


class SingleMapFrame(MapFrameBase):
    """Frame with one map window.

    It is base class for frames which needs only one map.

    Derived class should have \c self.MapWindow or
    it has to override GetWindow() methods.

    @note To access maps use getters only
    (when using class or when writing class itself).
    """

    def __init__(self, parent=None, giface=None, id=wx.ID_ANY, title='',
                 style=wx.DEFAULT_FRAME_STYLE,
                 Map=None,
                 auimgr=None, name='', **kwargs):
        """

        :param parent: gui parent
        :param id: wx id
        :param title: window title
        :param style: \c wx.Frame style
        :param map: instance of render.Map
        :param name: frame name
        :param kwargs: arguments passed to MapFrameBase
        """

        MapFrameBase.__init__(self, parent=parent, id=id, title=title,
                              style=style,
                              auimgr=auimgr, name=name, **kwargs)

        self.Map = Map       # instance of render.Map

        #
        # initialize region values
        #
        if self.Map:
            self._initMap(Map=self.Map)

    def GetMap(self):
        """Returns map (renderer) instance"""
        return self.Map

    def GetWindow(self):
        """Returns map window"""
        return self.MapWindow

    def GetWindows(self):
        """Returns list of map windows"""
        return [self.MapWindow]

    def OnRender(self, event):
        """Re-render map composition (each map layer)
        """
        self.GetWindow().UpdateMap(render=True, renderVector=True)

        # update statusbar
        self.StatusbarUpdate()


class DoubleMapFrame(MapFrameBase):
    """Frame with two map windows.

    It is base class for frames which needs two maps.
    There is no primary and secondary map. Both maps are equal.
    However, one map is current.

    It is expected that derived class will call _bindWindowsActivation()
    when both map windows will be initialized.

    Drived class should have method GetMapToolbar() returns toolbar
    which has methods SetActiveMap() and Enable().

    @note To access maps use getters only
    (when using class or when writing class itself).

    .. todo:
        Use it in GCP manager (probably changes to both DoubleMapFrame
        and GCP MapFrame will be neccessary).
    """

    def __init__(self, parent=None, id=wx.ID_ANY, title=None,
                 style=wx.DEFAULT_FRAME_STYLE,
                 firstMap=None, secondMap=None,
                 auimgr=None, name=None, **kwargs):
        """

        \a firstMap is set as active (by assign it to \c self.Map).
        Derived class should assging to \c self.MapWindow to make one
        map window current by dafault.

        :param parent: gui parent
        :param id: wx id
        :param title: window title
        :param style: \c wx.Frame style
        :param name: frame name
        :param kwargs: arguments passed to MapFrameBase
        """

        MapFrameBase.__init__(self, parent=parent, id=id, title=title,
                              style=style,
                              auimgr=auimgr, name=name, **kwargs)

        self.firstMap = firstMap
        self.secondMap = secondMap
        self.Map = firstMap

        #
        # initialize region values
        #
        self._initMap(Map=self.firstMap)
        self._initMap(Map=self.secondMap)
        self._bindRegions = False

    def _bindWindowsActivation(self):
        self.GetFirstWindow().Bind(wx.EVT_ENTER_WINDOW, self.ActivateFirstMap)
        self.GetSecondWindow().Bind(wx.EVT_ENTER_WINDOW, self.ActivateSecondMap)

    def _onToggleTool(self, id):
        if self._toolSwitcher.IsToolInGroup(id, 'mouseUse'):
            self.GetFirstWindow().UnregisterAllHandlers()
            self.GetSecondWindow().UnregisterAllHandlers()

    def GetFirstMap(self):
        """Returns first Map instance
        """
        return self.firstMap

    def GetSecondMap(self):
        """Returns second Map instance
        """
        return self.secondMap

    def GetFirstWindow(self):
        """Get first map window"""
        return self.firstMapWindow

    def GetSecondWindow(self):
        """Get second map window"""
        return self.secondMapWindow

    def GetMap(self):
        """Returns current map (renderer) instance

        @note Use this method to access current map renderer.
        (It is not guarented that current map will be stored in
        \c self.Map in future versions.)
        """
        return self.Map

    def GetWindow(self):
        """Returns current map window

        :func:`GetMap()`
        """
        return self.MapWindow

    def GetWindows(self):
        """Return list of all windows"""
        return [self.firstMapWindow, self.secondMapWindow]

    def ActivateFirstMap(self, event=None):
        """Make first Map and MapWindow active and (un)bind regions of the two Maps."""
        if self.MapWindow == self.firstMapWindow:
            return

        self.Map = self.firstMap
        self.MapWindow = self.firstMapWindow
        self.GetMapToolbar().SetActiveMap(0)

        # bind/unbind regions
        if self._bindRegions:
            self.firstMapWindow.zoomChanged.connect(self.OnZoomChangedFirstMap)
            self.secondMapWindow.zoomChanged.disconnect(
                self.OnZoomChangedSecondMap)

    def ActivateSecondMap(self, event=None):
        """Make second Map and MapWindow active and (un)bind regions of the two Maps."""
        if self.MapWindow == self.secondMapWindow:
            return

        self.Map = self.secondMap
        self.MapWindow = self.secondMapWindow
        self.GetMapToolbar().SetActiveMap(1)

        if self._bindRegions:
            self.secondMapWindow.zoomChanged.connect(
                self.OnZoomChangedSecondMap)
            self.firstMapWindow.zoomChanged.disconnect(
                self.OnZoomChangedFirstMap)

    def SetBindRegions(self, on):
        """Set or unset binding display regions."""
        self._bindRegions = on

        if on:
            if self.MapWindow == self.firstMapWindow:
                self.firstMapWindow.zoomChanged.connect(
                    self.OnZoomChangedFirstMap)
            else:
                self.secondMapWindow.zoomChanged.connect(
                    self.OnZoomChangedSecondMap)
        else:
            if self.MapWindow == self.firstMapWindow:
                self.firstMapWindow.zoomChanged.disconnect(
                    self.OnZoomChangedFirstMap)
            else:
                self.secondMapWindow.zoomChanged.disconnect(
                    self.OnZoomChangedSecondMap)

    def OnZoomChangedFirstMap(self):
        """Display region of the first window (Map) changed.

        Synchronize the region of the second map and re-render it.
        This is the default implementation which can be overridden.
        """
        region = self.GetFirstMap().GetCurrentRegion()
        self.GetSecondMap().region.update(region)
        self.Render(mapToRender=self.GetSecondWindow())

    def OnZoomChangedSecondMap(self):
        """Display region of the second window (Map) changed.

        Synchronize the region of the second map and re-render it.
        This is the default implementation which can be overridden.
        """
        region = self.GetSecondMap().GetCurrentRegion()
        self.GetFirstMap().region.update(region)
        self.Render(mapToRender=self.GetFirstWindow())

    def OnZoomIn(self, event):
        """Zoom in the map."""
        self.GetFirstWindow().SetModeZoomIn()
        self.GetSecondWindow().SetModeZoomIn()

    def OnZoomOut(self, event):
        """Zoom out the map."""
        self.GetFirstWindow().SetModeZoomOut()
        self.GetSecondWindow().SetModeZoomOut()

    def OnPan(self, event):
        """Panning, set mouse to pan"""
        self.GetFirstWindow().SetModePan()
        self.GetSecondWindow().SetModePan()

    def OnPointer(self, event):
        """Set pointer mode (dragging overlays)"""
        self.GetFirstWindow().SetModePointer()
        self.GetSecondWindow().SetModePointer()

    def OnQuery(self, event):
        """Set query mode"""
        self.GetFirstWindow().SetModeQuery()
        self.GetSecondWindow().SetModeQuery()

    def OnRender(self, event):
        """Re-render map composition (each map layer)
        """
        self.Render(mapToRender=self.GetFirstWindow())
        self.Render(mapToRender=self.GetSecondWindow())

    def Render(self, mapToRender):
        """Re-render map composition"""
        mapToRender.UpdateMap(
            render=True,
            renderVector=mapToRender == self.GetFirstWindow())

        # update statusbar
        self.StatusbarUpdate()

    def OnErase(self, event):
        """Erase the canvas
        """
        self.Erase(mapToErase=self.GetFirstWindow())
        self.Erase(mapToErase=self.GetSecondWindow())

    def Erase(self, mapToErase):
        """Erase the canvas
        """
        mapToErase.EraseMap()

    def OnDraw(self, event):
        """Re-display current map composition
        """
        self.Draw(mapToDraw=self.GetFirstWindow())
        self.Draw(mapToDraw=self.GetSecondWindow())

    def Draw(self, mapToDraw):
        """Re-display current map composition
        """
        mapToDraw.UpdateMap(render=False)