Skip to content

Commit

Permalink
wxGUI: add recent_files param to print a list of wxGUI component rece…
Browse files Browse the repository at this point in the history
…nt files

Main wxGUI component:

```
GRASS nc_basic_spm_grass7/PERMANENT:~ > g.gui recent_files=main
/tmp/w2.gxw
/tmp/w1.gxw
```

Simple Python Editor wxGUI component:

```
GRASS nc_basic_spm_grass7/PERMANENT:~ > g.gui recent_files=pyedit
/tmp/test.py
```
  • Loading branch information
tmszi committed Sep 15, 2022
1 parent 1fe95b8 commit f5ac94a
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 23 deletions.
5 changes: 5 additions & 0 deletions gui/wxpython/core/globalvar.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,3 +255,8 @@ def UpdateGRASSAddOnCommands(eList=None):

"""@Add GUIDIR/scripts into path"""
os.environ["PATH"] = os.path.join(GUIDIR, "scripts") + os.pathsep + os.environ["PATH"]

RECENT_FILES_WXGUI_APP_NAMES = {
"main": {"name": "main", "pos": 0},
"pyedit": {"name": "pyedit", "pos": 1}
}
56 changes: 45 additions & 11 deletions gui/wxpython/gui_core/menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
Classes:
- menu::Menu
- menu::SearchModuleWindow
- menu::RecentFilesConfig
- menu::RecentFilesMenu
(C) 2010-2013 by the GRASS Development Team
Expand All @@ -18,7 +19,7 @@
@author Milena Nowotarska (menu customization)
@author Robert Szczepanek (menu customization)
@author Vaclav Petras <wenzeslaus gmail.com> (menu customization)
@author Tomas Zigo <tomas.zigo slovanet.sk> RecentFilesMenu
@author Tomas Zigo <tomas.zigo slovanet.sk> RecentFilesConfig, RecentFilesMenu
"""
import re
import os
Expand Down Expand Up @@ -305,6 +306,48 @@ def OnItemSelected(self, node):
self.showNotification.emit(message=label)


class RecentFilesConfig(wx.FileConfig):
"""Storing and retrieving recent files using plain text files"""

def __init__(
self,
appName,
style=wx.CONFIG_USE_LOCAL_FILE,
localFilename=None,
*args,
**kwargs,
):
if not localFilename:
localFilename = os.path.join(
utils.GetSettingsPath(),
".recent_files",
)

super().__init__(
appName,
style=style,
localFilename=localFilename,
*args,
**kwargs,
)
self.SetPath(strPath=appName)

def GetRecentFiles(self):
"""Get recent files
:return list: list of recent files
"""
recent_files = []
num_of_entries = self.GetNumberOfEntries()
for i in range(0, num_of_entries):
entry = self.GetNextEntry(index=i)
if entry[0]:
file_path = self.Read(key=entry[1])
if file_path and os.path.exists(file_path):
recent_files.append(file_path)
return recent_files


class RecentFilesMenu:
"""Add recent files history menu
Expand All @@ -326,8 +369,6 @@ class RecentFilesMenu:
into the .recent_files file to app name group
"""

recent_files = ".recent_files"

def __init__(self, app_name, parent_menu, pos, history_len=10):
self._history_len = history_len
self._parent_menu = parent_menu
Expand All @@ -338,14 +379,7 @@ def __init__(self, app_name, parent_menu, pos, history_len=10):
self._filehistory = wx.FileHistory(maxFiles=history_len)
# Recent files path stored in GRASS GIS config dir in the
# .recent_files file in the group by application name
self._config = wx.FileConfig(
style=wx.CONFIG_USE_LOCAL_FILE,
localFilename=os.path.join(
utils.GetSettingsPath(),
self.recent_files,
),
)
self._config.SetPath(strPath=app_name)
self._config = RecentFilesConfig(appName=app_name)
self._filehistory.Load(self._config)
self.RemoveNonExistentFiles()

Expand Down
5 changes: 3 additions & 2 deletions gui/wxpython/gui_core/pyedit.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,10 +287,11 @@ def __init__(self, panel, guiparent, giface):

# Get first (File) menu
menu = guiparent.menubar.GetMenu(0)
recent_files_conf = globalvar.RECENT_FILES_WXGUI_APP_NAMES["pyedit"]
self.recent_files = RecentFilesMenu(
app_name="pyedit",
app_name=recent_files_conf["name"],
parent_menu=menu,
pos=1,
pos=recent_files_conf["pos"],
) # pos=1 recent files menu position (index) in the parent (File) menu

self.recent_files.file_requested.connect(self.OpenRecentFile)
Expand Down
6 changes: 4 additions & 2 deletions gui/wxpython/lmgr/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

from core.settings import UserSettings
from core.gcmd import RunCommand, GError, GMessage
from core.globalvar import RECENT_FILES_WXGUI_APP_NAMES
from core.workspace import ProcessWorkspaceFile, WriteWorkspaceFile
from core.debug import Debug
from gui_core.menu import RecentFilesMenu
Expand Down Expand Up @@ -510,10 +511,11 @@ def CreateRecentFilesMenu(self, menu=None):
workspace_item = file_menu.FindItem(
id=file_menu.FindItem(itemString=_("Workspace")),
)[0]
recent_files_conf = RECENT_FILES_WXGUI_APP_NAMES["main"]
self._recent_files = RecentFilesMenu(
app_name="main",
app_name=recent_files_conf["name"],
parent_menu=workspace_item.GetSubMenu(),
pos=0,
pos=recent_files_conf["pos"],
)
self._recent_files.file_requested.connect(self.OpenRecentFile)

Expand Down
68 changes: 60 additions & 8 deletions gui/wxpython/wxgui.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,29 +106,74 @@ def OnExit(self):
return super().OnExit()


def get_wxgui_components_app_names():
"""Get wxGUI components app names
:return list: wxGUI components app names
"""
return list(
map(
lambda x: x["name"],
globalvar.RECENT_FILES_WXGUI_APP_NAMES.values(),
)
)


def printHelp():
"""Print program help"""
print("Usage:", file=sys.stderr)
print(" python wxgui.py [options]", file=sys.stderr)
print("%sOptions:" % os.linesep, file=sys.stderr)
print(" -w\t--workspace file\tWorkspace file to load", file=sys.stderr)
print(
" -r\t--recent_files wxGUI component name"
f" ({'|'.join(get_wxgui_components_app_names())})"
" Print wxGUI component recent files",
file=sys.stderr,
)
sys.exit(1)


def process_opt(opts, args):
"""Process command-line arguments"""
workspaceFile = None
"""Process command-line arguments
:param opts list: list of (option, value) pairs
:param args list: list of trailing slice of args
:return dict parsed_args: parsed command-line args
"""
parsed_args = {}
for o, a in opts:
if o in ("-h", "--help"):
printHelp()

elif o in ("-w", "--workspace"):
if a != "":
workspaceFile = str(a)
parsed_args.update({"w": str(a)})
else:
parsed_args.update({"w": args.pop(0)})
elif o in ("-r", "--recent_files"):
if a != "":
parsed_args.update({"r": str(a)})
else:
workspaceFile = args.pop(0)
parsed_args.update({"r": args.pop(0)})
return parsed_args

return workspaceFile

def print_wxgui_component_recent_files(args):
"""Print wxGUI component recent files
:param args dict: parsed command-line args
"""
recent_files_app_name = args.get("r")
if recent_files_app_name:
from gui_core.menu import RecentFilesConfig

app = wx.App()
config = RecentFilesConfig(appName=recent_files_app_name)
for i in config.GetRecentFiles():
print(i, file=sys.stderr)
sys.exit(1)


def main(argv=None):
Expand All @@ -137,16 +182,23 @@ def main(argv=None):
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "hw:", ["help", "workspace"])
opts, args = getopt.getopt(
argv[1:],
"hwr:",
["help", "workspace", "recent_files"],
)
except getopt.error as msg:
raise Usage(msg)
except Usage as err:
print(err.msg, file=sys.stderr)
print(sys.stderr, "for help use --help", file=sys.stderr)
printHelp()

workspaceFile = process_opt(opts, args)
app = GMApp(workspaceFile)
parsed_args = process_opt(opts, args)

print_wxgui_component_recent_files(args=parsed_args)

app = GMApp(workspace=parsed_args.get("w"))

# suppress wxPython logs
q = wx.LogNull()
Expand Down

0 comments on commit f5ac94a

Please sign in to comment.