File: browser.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 (491 lines) | stat: -rw-r--r-- 16,186 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
"""
@package history.browser

@brief History browser

Classes:
 - browser::HistoryInfoPanel
 - browser::HistoryBrowser

(C) 2023-2024 by Linda Karlovska, and 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 Linda Karlovska (Kladivova) linda.karlovska@seznam.cz
@author Anna Petrasova (kratochanna gmail com)
@author Tomas Zigo
"""

from datetime import datetime

import wx
import wx.lib.scrolledpanel as SP

from gui_core.wrap import SearchCtrl, StaticText, StaticBox, Button
from history.tree import HistoryBrowserTree
from icons.icon import MetaIcon

import grass.script as gs

from grass.grassdb import history

from grass.pydispatch.signal import Signal

from core.gcmd import GError


TRANSLATION_KEYS = {
    "timestamp": _("Timestamp:"),
    "runtime": _("Runtime duration:"),
    "status": _("Status:"),
    "mask2d": _("Mask 2D:"),
    "mask3d": _("Mask 3D:"),
    "n": _("North:"),
    "s": _("South:"),
    "w": _("West:"),
    "e": _("East:"),
    "nsres": _("North-south resolution:"),
    "ewres": _("East-west resolution:"),
    "rows": _("Number of rows:"),
    "cols": _("Number of columns:"),
    "cells": _("Number of cells:"),
}


def get_translated_value(key, value):
    """Function for mapping command info values to the structure used in GUI."""
    if key == "timestamp":
        exec_datetime = datetime.fromisoformat(value)
        return exec_datetime.strftime("%Y-%m-%d %H:%M:%S")
    elif key == "runtime":
        return _("{} sec".format(value))
    elif key == "status":
        return _(value.capitalize())
    elif key in ("mask2d", "mask3d"):
        return _(str(value))


def make_label(key):
    return TRANSLATION_KEYS.get(key, "")


class HistoryInfoPanel(SP.ScrolledPanel):
    def __init__(self, parent, giface, title=("Command Info"), style=wx.TAB_TRAVERSAL):
        super().__init__(parent=parent, id=wx.ID_ANY, style=style)

        self.parent = parent
        self.giface = giface
        self.title = title

        self.region_settings = None

        self._initImages()

        self._createGeneralInfoBox()
        self._createRegionSettingsBox()

        self._layout()

    def _layout(self):
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        mainSizer.Add(
            self.general_info_box_sizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5
        )
        mainSizer.Add(
            self.sizer_region_settings,
            proportion=0,
            flag=wx.EXPAND | wx.ALL,
            border=5,
        )
        self.SetSizer(mainSizer)
        self.SetMinSize(self.GetBestSize())

        self.Layout()

    def _initImages(self):
        bmpsize = (16, 16)
        self.icons = {
            "check": MetaIcon(img="success").GetBitmap(bmpsize),
            "cross": MetaIcon(img="cross").GetBitmap(bmpsize),
        }

    def _createGeneralInfoBox(self):
        """Create static box for general info about the command"""
        self.general_info_box = StaticBox(
            parent=self, id=wx.ID_ANY, label=_("General info")
        )
        self.general_info_box_sizer = wx.StaticBoxSizer(
            self.general_info_box, wx.VERTICAL
        )

        self.sizer_general_info = wx.GridBagSizer(hgap=0, vgap=0)
        self.sizer_general_info.SetCols(2)
        self.sizer_general_info.SetRows(5)

        self.general_info_box_sizer.Add(
            self.sizer_general_info, proportion=1, flag=wx.ALL | wx.EXPAND, border=5
        )
        self.sizer_general_info.AddGrowableCol(1)
        self.general_info_box.Hide()

    def _createRegionSettingsBox(self):
        """Create a static box for displaying region settings of the command"""
        self.region_settings_box = StaticBox(
            parent=self,
            id=wx.ID_ANY,
            label=_("Computational region during command execution"),
        )
        self.sizer_region_settings = wx.StaticBoxSizer(
            self.region_settings_box, wx.VERTICAL
        )

        self.sizer_region_settings_match = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer_region_settings.Add(
            self.sizer_region_settings_match,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=5,
        )

        self.sizer_region_settings_grid = wx.GridBagSizer(hgap=0, vgap=0)
        self.sizer_region_settings_grid.SetCols(2)
        self.sizer_region_settings_grid.SetRows(9)

        self.sizer_region_settings.Add(
            self.sizer_region_settings_grid,
            proportion=1,
            flag=wx.ALL | wx.EXPAND,
            border=5,
        )

        self.sizer_region_settings_grid.AddGrowableCol(1)
        self.region_settings_box.Hide()

    def _general_info_filter(self, key, value):
        filter_keys = ["timestamp", "runtime", "status"]
        return key in filter_keys or (
            (key == "mask2d" or key == "mask3d") and value is True
        )

    def _region_settings_filter(self, key):
        return (key != "projection") and (key != "zone") and (key != "cells")

    def _updateGeneralInfoBox(self, command_info):
        """Update a static box for displaying general info about the command.

        :param dict command_info: command info entry for update
        """
        self.sizer_general_info.Clear(True)

        idx = 0
        for key, value in command_info.items():
            if self._general_info_filter(key, value):
                self.sizer_general_info.Add(
                    StaticText(
                        parent=self.general_info_box,
                        id=wx.ID_ANY,
                        label=make_label(key),
                        style=wx.ALIGN_LEFT,
                    ),
                    flag=wx.ALIGN_LEFT | wx.ALL,
                    border=5,
                    pos=(idx, 0),
                )
                self.sizer_general_info.Add(
                    StaticText(
                        parent=self.general_info_box,
                        id=wx.ID_ANY,
                        label=get_translated_value(key, value),
                        style=wx.ALIGN_LEFT,
                    ),
                    flag=wx.ALIGN_LEFT | wx.ALL,
                    border=5,
                    pos=(idx, 1),
                )
                idx += 1

        self.general_info_box.Layout()
        self.general_info_box.Show()

    def _updateRegionSettingsGrid(self, command_info):
        """Update a grid that displays numerical values
        for the regional settings of the executed command.

        :param dict command_info: command info entry for update
        """
        self.sizer_region_settings_grid.Clear(True)

        self.region_settings = command_info["region"]
        idx = 0
        for key, value in self.region_settings.items():
            if self._region_settings_filter(key):
                self.sizer_region_settings_grid.Add(
                    StaticText(
                        parent=self.region_settings_box,
                        id=wx.ID_ANY,
                        label=make_label(key),
                        style=wx.ALIGN_LEFT,
                    ),
                    flag=wx.ALIGN_LEFT | wx.ALL,
                    border=5,
                    pos=(idx, 0),
                )
                self.sizer_region_settings_grid.Add(
                    StaticText(
                        parent=self.region_settings_box,
                        id=wx.ID_ANY,
                        label=str(value),
                        style=wx.ALIGN_LEFT,
                    ),
                    flag=wx.ALIGN_LEFT | wx.ALL,
                    border=5,
                    pos=(idx, 1),
                )
                idx += 1

        self.region_settings_box.Show()

    def _updateRegionSettingsMatch(self):
        """Update text, icon and button dealing with region update"""
        self.sizer_region_settings_match.Clear(True)

        # Region condition
        history_region = self.region_settings
        current_region = self._get_current_region()
        region_matches = history_region == current_region

        # Icon and button according to the condition
        if region_matches:
            icon = self.icons["check"]
            button_label = None
        else:
            icon = self.icons["cross"]
            button_label = _("Update current region")

        # Static text
        textRegionMatch = StaticText(
            parent=self.region_settings_box,
            id=wx.ID_ANY,
            label=_("Region match"),
        )
        self.sizer_region_settings_match.Add(
            textRegionMatch,
            proportion=0,
            flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
            border=10,
        )

        # Static bitmap for icon
        iconRegionMatch = wx.StaticBitmap(self.region_settings_box, bitmap=icon)
        self.sizer_region_settings_match.Add(
            iconRegionMatch,
            proportion=0,
            flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
            border=10,
        )

        if button_label:
            # Button for region update
            buttonUpdateRegion = Button(self.region_settings_box, id=wx.ID_ANY)
            buttonUpdateRegion.SetLabel(_("Update current region"))
            buttonUpdateRegion.SetToolTip(
                _("Set current computational region to the region of executed command")
            )
            buttonUpdateRegion.Bind(wx.EVT_BUTTON, self.OnUpdateRegion)
            self.sizer_region_settings_match.Add(
                buttonUpdateRegion,
                proportion=1,
                flag=wx.ALIGN_CENTER_VERTICAL,
                border=10,
            )

        self.region_settings_box.Show()

    def showCommandInfo(self, command_info):
        """Show command info input.

        :param dict command_info: command info entry for update
        """
        if command_info:
            self._updateGeneralInfoBox(command_info)
            self._updateRegionSettingsGrid(command_info)
            self._updateRegionSettingsMatch()
        else:
            self.hideCommandInfo()
        self.SetupScrolling(scroll_x=False, scroll_y=True)
        self.Layout()

    def hideCommandInfo(self):
        """Hide command info input."""
        self.general_info_box.Hide()
        self.region_settings_box.Hide()

    def _get_current_region(self):
        """Get current computational region settings."""
        return gs.region()

    def _get_history_region(self):
        """Get computational region settings of executed command."""
        history_region = {}
        for key, value in self.region_settings.items():
            if self._region_settings_filter(key):
                history_region[key] = value
        return history_region

    def OnUpdateRegion(self, event):
        """Set current region to the region of executed command."""
        history_region = self._get_history_region()
        gs.run_command("g.region", **history_region)
        self.giface.updateMap.emit(render=False, renderVector=False)
        self._updateRegionSettingsMatch()
        self.Layout()


class HistoryBrowser(wx.SplitterWindow):
    """History browser window for executing the commands from history log
    and showing history info.

    Signal:
        showNotification - attribute 'message'
    """

    def __init__(
        self,
        parent,
        giface,
        id=wx.ID_ANY,
        title=_("History browser"),
        style=wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE,
        name="history",
        **kwargs,
    ):
        super().__init__(parent=parent, id=wx.ID_ANY, style=style, **kwargs)
        self.SetName("HistoryBrowser")

        self.parent = parent
        self._giface = giface

        self.showNotification = Signal("HistoryBrowser.showNotification")
        self.runIgnoredCmdPattern = Signal("HistoryBrowser.runIgnoredCmdPattern")

        self.panelBrowser = wx.Panel(parent=self)
        self.panelInfo = wx.Panel(parent=self)

        # info panel
        self.infoPanel = HistoryInfoPanel(parent=self.panelInfo, giface=giface)

        # tree with layers
        self.tree = HistoryBrowserTree(
            parent=self.panelBrowser, giface=giface, infoPanel=self.infoPanel
        )
        self.tree.SetToolTip(_("Double-click to run selected tool"))
        self.tree.showNotification.connect(self.showNotification)
        self.tree.runIgnoredCmdPattern.connect(self.runIgnoredCmdPattern)

        # search box
        self.search = SearchCtrl(parent=self.panelBrowser)
        self.search.SetDescriptiveText(_("Search"))
        self.search.ShowCancelButton(True)
        self.search.Bind(wx.EVT_TEXT, lambda evt: self.tree.Filter(evt.GetString()))
        self.search.Bind(wx.EVT_SEARCHCTRL_CANCEL_BTN, lambda evt: self.tree.Filter(""))

        # buttons
        self.btnCmdExportHistory = Button(parent=self.panelInfo, id=wx.ID_ANY)
        self.btnCmdExportHistory.SetLabel(_("&Export history"))
        self.btnCmdExportHistory.SetToolTip(
            _("Export history of executed commands to a file")
        )
        self.btnCmdExportHistory.Bind(wx.EVT_BUTTON, self.OnCmdExportHistory)

        self._layout()

    def _layout(self):
        """Dialog layout"""
        self.browserSizer = wx.BoxSizer(wx.VERTICAL)
        self.infoSizer = wx.BoxSizer(wx.VERTICAL)

        self.browserSizer.Add(
            self.search,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=5,
        )
        self.browserSizer.Add(
            self.tree, proportion=1, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5
        )

        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer.AddStretchSpacer()
        btnSizer.Add(
            self.btnCmdExportHistory,
            proportion=0,
            flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
            border=5,
        )
        self.infoSizer.Add(
            self.infoPanel,
            proportion=1,
            flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP,
            border=5,
        )
        self.infoSizer.Add(
            btnSizer,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=5,
        )

        self.browserSizer.Fit(self)
        self.browserSizer.SetSizeHints(self)
        self.panelBrowser.SetSizer(self.browserSizer)
        self.browserSizer.FitInside(self.panelBrowser)

        self.infoSizer.Fit(self)
        self.infoSizer.SetSizeHints(self)
        self.panelInfo.SetSizer(self.infoSizer)
        self.infoSizer.FitInside(self.panelInfo)

        # split window
        self.SplitHorizontally(self.panelBrowser, self.panelInfo, 0)
        self.SetMinimumPaneSize(self.btnCmdExportHistory.GetSize()[1] + 100)
        self.SetSashPosition(self.GetSize().y - 500)
        self.SetSashGravity(1.0)

        # layout
        self.SetAutoLayout(True)
        self.Layout()

    def OnCmdExportHistory(self, event):
        """Export the history of executed commands to a selected file."""
        history_path = history.get_current_mapset_gui_history_path()
        if history.get_history_file_extension(history_path) == ".json":
            defaultFile = "grass_cmd_log.json"
            wildcard = _("{json} (*.json)|*.txt|{files} (*)|*").format(
                json=_("JSON files"), files=_("Files")
            )
        else:
            defaultFile = "grass_cmd_log.txt"
            wildcard = _("{txt} (*.txt)|*.txt|{files} (*)|*").format(
                txt=_("Text files"), files=_("Files")
            )
        dlg = wx.FileDialog(
            self,
            message=_("Save file as..."),
            defaultFile=defaultFile,
            wildcard=wildcard,
            style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
        )
        if dlg.ShowModal() == wx.ID_OK:
            target_path = dlg.GetPath()
            try:
                history.copy(history_path, target_path)
                self.showNotification.emit(
                    message=_("Command history saved to '{}'".format(target_path))
                )
            except OSError as e:
                GError(str(e))

        dlg.Destroy()
        event.Skip()