File: test_mapdisp.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 (367 lines) | stat: -rwxr-xr-x 12,327 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
#!/usr/bin/env python3

############################################################################
#
# MODULE:    Map window and mapdisplay test module
# AUTHOR(S): Vaclav Petras
# PURPOSE:   Test functionality using small GUI applications.
# COPYRIGHT: (C) 2013 by Vaclav Petras, and the GRASS Development Team
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
############################################################################

# %module
# % description: Tests map display and map window widgets
# % keyword: general
# % keyword: GUI
# % keyword: test
# %end
# %option
# % key: test
# % description: Test to run
# % options: mapwindow,mapdisplay,apitest,distance,profile
# % descriptions: mapwindow;Opens map window ;mapdisplay;Opens map display; apitest;Open an application to test API of map window; distance;Starts map window with distance measurement activated; profile;Starts map window with profile tool activated
# % required: yes
# %end
# %option G_OPT_R_INPUT
# % key: raster
# % multiple: yes
# % required: no
# %end
# %option G_OPT_V_INPUT
# % key: vector
# % multiple: yes
# % required: no
# %end

"""
Module to run test map window (BufferedWidnow) and map display (MapFrame).

@author Vaclav Petras  <wenzeslaus gmail.com>
"""

import os
import sys
import wx

import grass.script as grass

from grass.script.setup import set_gui_path

set_gui_path()

# GUI imports require path to GUI code to be set.
from core.settings import UserSettings  # noqa: E402
from core.giface import StandaloneGrassInterface  # noqa: E402
from mapwin.base import MapWindowProperties  # noqa: E402
from mapwin.buffered import BufferedMapWindow  # noqa: E402
from core.render import Map  # noqa: E402
from rlisetup.sampling_frame import RLiSetupMapPanel  # noqa: E402
from mapdisp.main import LayerList  # noqa: E402
from gui_core.wrap import StaticText  # noqa: E402


class MapdispGrassInterface(StandaloneGrassInterface):
    """@implements GrassInterface"""

    def __init__(self, map_):
        StandaloneGrassInterface.__init__(self)
        self._map = map_
        self.mapWindow = None

    def GetLayerList(self):
        return LayerList(self._map, giface=self)

    def GetMapWindow(self):
        return self.mapWindow


# this is a copy of method from some frame class
def copyOfInitMap(map_, width, height):
    """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"
        )
    map_.ChangeMapSize((width, height))
    map_.region = map_.GetRegion()  # g.region -upgc
    # self.Map.SetRegion() # adjust region to match display window


class TextShower:
    def __init__(self, parent, title):
        self._cf = wx.Frame(parent=parent, title=title)
        self._cp = wx.Panel(parent=self._cf, id=wx.ID_ANY)
        self._cs = wx.BoxSizer(wx.VERTICAL)
        self._cl = StaticText(parent=self._cp, id=wx.ID_ANY, label="No text set yet")
        self._cs.Add(self._cl, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
        self._cp.SetSizer(self._cs)
        self._cp.Layout()
        self._cf.Show()

    def SetLabel(self, text):
        self._cl.SetLabel(text)


class Tester:
    def _listenToAllMapWindowSignals(self, window):
        output = sys.stderr
        # will make bad thigs after it is closed but who cares
        coordinatesShower = TextShower(window, "Coordinates")

        window.zoomChanged.connect(lambda: output.write("zoomChanged\n"))
        window.zoomHistoryUnavailable.connect(
            lambda: output.write("zoomHistoryUnavailable\n")
        )
        window.zoomHistoryAvailable.connect(
            lambda: output.write("zoomHistoryAvailable\n")
        )

        window.mapQueried.connect(lambda: output.write("mapQueried\n"))
        window.mouseEntered.connect(lambda: output.write("mouseEntered\n"))
        window.mouseLeftUpPointer.connect(lambda: output.write("mouseLeftUpPointer\n"))
        window.mouseLeftUp.connect(lambda: output.write("mouseLeftUp\n"))
        window.mouseMoving.connect(
            lambda x, y: coordinatesShower.SetLabel("%s , %s" % (x, y))
        )
        window.mouseHandlerRegistered.connect(
            lambda: output.write("mouseHandlerRegistered\n")
        )
        window.mouseHandlerUnregistered.connect(
            lambda: output.write("mouseHandlerUnregistered\n")
        )

    def testMapWindow(self, giface, map_):
        self.frame = wx.Frame(parent=None, title=_("Map window test frame"))
        panel = wx.Panel(parent=self.frame, id=wx.ID_ANY)
        sizer = wx.BoxSizer(wx.VERTICAL)
        mapWindowProperties = MapWindowProperties()
        mapWindowProperties.setValuesFromUserSettings()
        width, height = self.frame.GetClientSize()
        copyOfInitMap(map_, width, height)
        window = BufferedMapWindow(
            parent=panel, giface=giface, Map=map_, properties=mapWindowProperties
        )
        sizer.Add(window, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
        panel.SetSizer(sizer)
        panel.Layout()
        self.frame.Show()

    def testMapDisplay(self, giface, map_):
        from mapdisp.frame import MapFrame

        # known issues (should be similar with d.mon):
        # * opening map in digitizer ends with: vdigit/toolbars.py:723: 'selection'
        #   referenced before assignment
        # * nviz start fails (closes window? segfaults?) after mapdisp/frame.py:306:
        #   'NoneType' object has no attribute 'GetLayerNotebook'
        frame = MapFrame(
            parent=None, title=_("Map display test"), giface=giface, Map=map_
        )
        # this is questionable: how complete the giface when creating objects
        # which are in giface
        giface.mapWindow = frame.GetMapWindow()
        frame.GetMapWindow().ZoomToMap()
        frame.Show()

    def testMapWindowApi(self, giface, map_):
        self.frame = wx.Frame(parent=None, title=_("Map window API test frame"))
        panel = wx.Panel(parent=self.frame, id=wx.ID_ANY)
        sizer = wx.BoxSizer(wx.VERTICAL)

        mapWindowProperties = MapWindowProperties()
        mapWindowProperties.setValuesFromUserSettings()
        mapWindowProperties.showRegion = True

        width, height = self.frame.GetClientSize()
        copyOfInitMap(map_, width, height)
        window = BufferedMapWindow(
            parent=panel, giface=giface, Map=map_, properties=mapWindowProperties
        )

        giface.mapWindow = window

        sizer.Add(window, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
        panel.SetSizer(sizer)
        panel.Layout()

        window.ZoomToWind()

        self.frame.Show()

    def testMapWindowDistance(self, giface, map_):
        self.frame = wx.Frame(
            parent=None, title=_("Map window distance measurement test frame")
        )
        panel = wx.Panel(parent=self.frame, id=wx.ID_ANY)
        sizer = wx.BoxSizer(wx.VERTICAL)

        mapWindowProperties = MapWindowProperties()
        mapWindowProperties.setValuesFromUserSettings()
        mapWindowProperties.showRegion = True

        width, height = self.frame.GetClientSize()
        copyOfInitMap(map_, width, height)
        window = BufferedMapWindow(
            parent=panel, giface=giface, Map=map_, properties=mapWindowProperties
        )

        giface.mapWindow = window

        sizer.Add(window, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
        panel.SetSizer(sizer)
        panel.Layout()

        window.ZoomToWind()

        self._listenToAllMapWindowSignals(window)

        self.frame.Show()

        from mapwin.analysis import MeasureDistanceController

        self.controller = MeasureDistanceController(giface, window)
        self.controller.Start()

    def testMapWindowProfile(self, giface, map_):
        self.frame = wx.Frame(
            parent=None, title=_("Map window profile tool test frame")
        )
        panel = wx.Panel(parent=self.frame, id=wx.ID_ANY)
        sizer = wx.BoxSizer(wx.VERTICAL)

        mapWindowProperties = MapWindowProperties()
        mapWindowProperties.setValuesFromUserSettings()
        mapWindowProperties.showRegion = True

        width, height = self.frame.GetClientSize()
        copyOfInitMap(map_, width, height)
        window = BufferedMapWindow(
            parent=panel, giface=giface, Map=map_, properties=mapWindowProperties
        )

        giface.mapWindow = window

        sizer.Add(window, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
        panel.SetSizer(sizer)
        panel.Layout()

        window.ZoomToWind()

        self._listenToAllMapWindowSignals(window)

        self.frame.Show()

        from mapwin.analysis import ProfileController

        self.controller = ProfileController(giface, window)
        self.controller.Start()

        rasters = []
        for layer in giface.GetLayerList().GetSelectedLayers():
            if layer.maplayer.GetType() == "raster":
                rasters.append(layer.maplayer.GetName())

        from wxplot.profile import ProfileFrame

        profileWindow = ProfileFrame(
            parent=self.frame,
            giface=giface,
            controller=self.controller,
            units=map_.projinfo["units"],
            rasterList=rasters,
        )
        profileWindow.CentreOnParent()
        profileWindow.Show()
        # Open raster select dialog to make sure that a raster (and
        # the desired raster) is selected to be profiled
        profileWindow.OnSelectRaster(None)

    def testMapWindowRlisetup(self, map_):
        self.frame = wx.Frame(parent=None, title=_("Map window rlisetup test frame"))

        RLiSetupMapPanel(parent=self.frame, map_=map_)
        self.frame.Show()


def main():
    """Sets the GRASS display driver"""
    driver = UserSettings.Get(group="display", key="driver", subkey="type")
    if driver == "png":
        os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
    else:
        os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo"

    # TODO: message format should not be GUI
    # TODO: should messages here be translatable?
    # (for test its great, for translator not)

    options, flags = grass.parser()
    test = options["test"]

    app = wx.App()
    map_ = Map()

    if options["raster"]:
        names = options["raster"]
        for name in names.split(","):
            cmdlist = ["d.rast", "map=%s" % name]
            map_.AddLayer(
                ltype="raster",
                command=cmdlist,
                active=True,
                name=name,
                hidden=False,
                opacity=1.0,
                render=True,
            )
    if options["vector"]:
        names = options["vector"]
        for name in names.split(","):
            cmdlist = ["d.vect", "map=%s" % name]
            map_.AddLayer(
                ltype="vector",
                command=cmdlist,
                active=True,
                name=name,
                hidden=False,
                opacity=1.0,
                render=True,
            )

    giface = MapdispGrassInterface(map_=map_)
    tester = Tester()

    if test == "mapwindow":
        tester.testMapWindow(giface, map_)
    elif test == "mapdisplay":
        tester.testMapDisplay(giface, map_)
    elif test == "apitest":
        tester.testMapWindowApi(giface, map_)
    elif test == "distance":
        tester.testMapWindowDistance(giface, map_)
    elif test == "profile":
        tester.testMapWindowProfile(giface, map_)
    elif test == "rlisetup":
        tester.testMapWindowRlisetup(map_)
    else:
        # TODO: this should not happen but happens
        import grass.script as sgrass

        sgrass.fatal(_("Unknown value %s of test parameter." % test))

    app.MainLoop()


if __name__ == "__main__":
    main()