def __init__(self, parent, giface, inputGisdbase, inputLocation, inputMapset, inputLayer, outputGisdbase, outputLocation, outputMapset, etype, id=wx.ID_ANY, title=_("Reprojection"), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER): self.parent = parent # GMFrame self._giface = giface # used to add layers wx.Dialog.__init__(self, parent, id, title, style=style, name="ReprojectionDialog") self.panel = wx.Panel(parent=self, id=wx.ID_ANY) self.iGisdbase = inputGisdbase self.iLocation = inputLocation self.iMapset = inputMapset self.iLayer = inputLayer self.oGisdbase = outputGisdbase self.oLocation = outputLocation self.oMapset = outputMapset self.etype = etype self._blackList = { 'enabled': True, 'items': { 'r.proj': { 'params': ['location', 'mapset', 'input', 'dbase'], 'flags': ['l']}, 'v.proj': { 'params': ['location', 'mapset', 'input', 'dbase'], 'flags': ['l']}}} if self.etype == 'raster': grass_task = gtask.parse_interface('r.proj', blackList=self._blackList) elif self.etype == 'vector': grass_task = gtask.parse_interface('v.proj', blackList=self._blackList) self.settingsPanel = CmdPanel(parent=self, giface=self._giface, task=grass_task, frame=None) self.closeOnFinished = wx.CheckBox(self.panel, label=_("Close dialog on finish")) # # buttons # # cancel self.btn_close = wx.Button(parent=self.panel, id=wx.ID_CLOSE) self.btn_close.Bind(wx.EVT_BUTTON, lambda evt: self.Close()) # run self.btn_run = wx.Button( parent=self.panel, id=wx.ID_OK, label=_("Reproject")) if self.etype == 'raster': self.btn_run.SetToolTipString(_("Reproject raster")) elif self.etype == 'vector': self.btn_run.SetToolTipString(_("Reproject vector")) self.btn_run.SetDefault() self.btn_run.Bind(wx.EVT_BUTTON, self.OnReproject) self.doLayout()
def OnItemSelected(self, event): """Item selected from the list""" lastWord = self.GetWordLeft() # to insert selection correctly if selected word partly matches written text match = difflib.SequenceMatcher(None, event.GetText(), lastWord) matchTuple = match.find_longest_match(0, len(event.GetText()), 0, len(lastWord)) compl = event.GetText()[matchTuple[2]:] text = self.GetTextLeft() + compl # add space or '=' at the end end = '=' for char in ('.','-','='): if text.split(' ')[-1].find(char) >= 0: end = ' ' compl += end text += end self.AddText(compl) pos = len(text) self.SetCurrentPos(pos) cmd = text.strip().split(' ')[0] if not self.cmdDesc or cmd != self.cmdDesc.get_name(): try: self.cmdDesc = gtask.parse_interface(cmd) except IOError: self.cmdDesc = None
def parseModules(): """Parse modules' interface""" modules = dict() # list of modules to be ignored ignore = [ "g.mapsets_picker.py", "v.type_wrapper.py", "g.parser", "vcolors" ] count = len(grassCmd) i = 0 for module in grassCmd: i += 1 if i % 10 == 0: grass.info("* %d/%d" % (i, count)) if module in ignore: continue try: interface = gtask.parse_interface(module) except Exception as e: grass.error(module + ": " + str(e)) continue modules[interface.name] = { "label": interface.label, "desc": interface.description, "keywords": interface.keywords, } return modules
def parseModules(): """Parse modules' interface""" modules = dict() # list of modules to be ignored ignore = ['g.mapsets_picker.py', 'v.type_wrapper.py', 'g.parser', 'vcolors'] count = len(grassCmd) i = 0 for module in grassCmd: i += 1 if i % 10 == 0: grass.info('* %d/%d' % (i, count)) if module in ignore: continue try: interface = gtask.parse_interface(module) except Exception as e: grass.error(module + ': ' + str(e)) continue modules[interface.name] = {'label': interface.label, 'desc': interface.description, 'keywords': interface.keywords} return modules
def OnItemSelected(self, event): """!Item selected from the list""" lastWord = self.GetWordLeft() # to insert selection correctly if selected word partly matches written text match = difflib.SequenceMatcher(None, event.GetText(), lastWord) matchTuple = match.find_longest_match(0, len(event.GetText()), 0, len(lastWord)) compl = event.GetText()[matchTuple[2]:] text = self.GetTextLeft() + compl # add space or '=' at the end end = '=' for char in ('.','-','='): if text.split(' ')[-1].find(char) >= 0: end = ' ' compl += end text += end self.AddText(compl) pos = len(text) self.SetCurrentPos(pos) cmd = text.strip().split(' ')[0] if not self.cmdDesc or cmd != self.cmdDesc.get_name(): if cmd in ('r.mapcalc', 'r3.mapcalc'): self.parent.parent.OnMapCalculator(event = None, cmd = [cmd]) # add command to history & clean prompt self.UpdateCmdHistory([cmd]) self.OnCmdErase(None) else: try: self.cmdDesc = gtask.parse_interface(cmd) except IOError: self.cmdDesc = None
def _setModule(self, name): """!Set module's choices (flags, parameters)""" # get module's description if name in self._choicesCmd and not self._module: try: self._module = gtask.parse_interface(name) except IOError: self._module = None # set choices (flags) self._choicesMap['flag'] = self._module.get_list_flags() for idx in range(len(self._choicesMap['flag'])): item = self._choicesMap['flag'][idx] desc = self._module.get_flag(item)['label'] if not desc: desc = self._module.get_flag(item)['description'] self._choicesMap['flag'][idx] = '%s (%s)' % (item, desc) # set choices (parameters) self._choicesMap['param'] = self._module.get_list_params() for idx in range(len(self._choicesMap['param'])): item = self._choicesMap['param'][idx] desc = self._module.get_param(item)['label'] if not desc: desc = self._module.get_param(item)['description'] self._choicesMap['param'][idx] = '%s (%s)' % (item, desc)
def _loadMetadata(module): """Load metadata to modules. :param module: module name :return: (description, keywords as a list) """ try: task = gtask.parse_interface(module) except ScriptError as e: sys.stderr.write("%s: %s\n" % (module, e)) return "", "" return task.get_description(full=True), task.get_keywords()
def _loadMetadata(module): """Load metadata to modules. :param module: module name :return: (description, keywords as a list) """ try: task = gtask.parse_interface(module) except ScriptError: return '', '' return task.get_description(full=True), \ task.get_keywords()
def createSettingsPage(self): self._blackList = { 'enabled' : True, 'items' : {self._getCommand() : {'params' : self._getBlackListedParameters(), 'flags' : self._getBlackListedFlags()}}} grass_task = gtask.parse_interface(self._getCommand(), blackList=self._blackList) self.advancedPagePanel = CmdPanel(parent=self, giface=None, task=grass_task, frame=None) self.notebook.AddPage(page = self.advancedPagePanel, text=_('Import settings'), name = 'settings')
def _get_module_metadata(self, name): path = os.environ["PATH"] os.environ["PATH"] += (os.pathsep + os.path.join(self.build_path, name, "bin") + os.pathsep + os.path.join(self.build_path, name, "scripts")) try: task = gtask.parse_interface(name) except: task = None os.environ["PATH"] = path if not task: return "", "" return task.get_description(full=True), task.get_keywords()
def get_module_metadata(name): import grass.script.task as gtask path = os.environ['PATH'] os.environ['PATH'] += os.pathsep + os.path.join(sys.argv[1], name, 'bin') + os.pathsep + \ os.path.join(sys.argv[1], name, 'scripts') try: task = gtask.parse_interface(name) except: task = None os.environ['PATH'] = path if not task: return '', '' return task.get_description(full = True), \ task.get_keywords()
def get_module_metadata(name): """ >>> get_module_metadata('g.region') ('Manages the boundary definitions for the geographic region.', ['general', 'settings']) >>> get_module_metadata('m.proj') ('Converts coordinates from one projection to another (cs2cs frontend).', ['miscellaneous', 'projection']) """ try: task = gtask.parse_interface(name) except: sys.stderr.write("Cannot parse interface for module %s. Empty strings" " will be placed instead of description and keywords." "\n" % name) return '', '' return task.get_description(full=True), \ task.get_keywords()
def get_module_metadata(name): import grass.script.task as gtask path = os.environ["PATH"] os.environ["PATH"] += (os.pathsep + os.path.join(sys.argv[1], name, "bin") + os.pathsep + os.path.join(sys.argv[1], name, "scripts")) try: task = gtask.parse_interface(name) except: task = None os.environ["PATH"] = path if not task: return "", "" return task.get_description(full=True), task.get_keywords()
def createSettingsPage(self): self._blackList = { 'enabled': True, 'items': { self._getCommand(): { 'params': self._getBlackListedParameters(), 'flags': self._getBlackListedFlags()}}} grass_task = gtask.parse_interface(self._getCommand(), blackList=self._blackList) self.advancedPagePanel = CmdPanel( parent=self, giface=None, task=grass_task, frame=None) self.notebook.AddPage(page=self.advancedPagePanel, text=_('Import settings'), name='settings')
def OnItemSelected(self, event): """!Item selected from the list""" lastWord = self.GetWordLeft() # to insert selection correctly if selected word partly matches written text match = difflib.SequenceMatcher(None, event.GetText(), lastWord) matchTuple = match.find_longest_match(0, len(event.GetText()), 0, len(lastWord)) compl = event.GetText()[matchTuple[2]:] text = self.GetTextLeft() + compl # add space or '=' at the end end = '=' for char in ('.', '-', '='): if text.split(' ')[-1].find(char) >= 0: end = ' ' compl += end text += end self.AddText(compl) pos = len(text) self.SetCurrentPos(pos) cmd = text.strip().split(' ')[0] if not self.cmdDesc or cmd != self.cmdDesc.get_name(): if cmd in ('r.mapcalc', 'v.type'): cmd = cmd + '_wrapper' if cmd in ('r.mapcalc', 'r3.mapcalc') and \ self.parent.parent.GetName() == 'LayerManager': self.parent.parent.OnMapCalculator(event=None, cmd=[cmd]) # add command to history & clean prompt self.UpdateCmdHistory([cmd]) self.OnCmdErase(None) else: try: self.cmdDesc = gtask.parse_interface(GetRealCmd(cmd)) except IOError: self.cmdDesc = None
def createSettingsPage(self): self._blackList = { "enabled": True, "items": { self._getCommand(): { "params": self._getBlackListedParameters(), "flags": self._getBlackListedFlags(), } }, } grass_task = gtask.parse_interface(self._getCommand(), blackList=self._blackList) self.advancedPagePanel = CmdPanel(parent=self, giface=None, task=grass_task, frame=None) self.notebook.AddPage(page=self.advancedPagePanel, text=_("Import settings"), name="settings")
def CmdToTuple(cmd): """Convert command list to tuple for gcmd.RunCommand()""" if len(cmd) < 1: return None dcmd = {} for item in cmd[1:]: if '=' in item: # params key, value = item.split('=', 1) dcmd[str(key)] = str(value).replace('"', '') elif item[:2] == '--': # long flags flag = item[2:] if flag in ('help', 'verbose', 'quiet', 'overwrite'): dcmd[str(flag)] = True elif len(item) == 2 and item[0] == '-': # -> flags if 'flags' not in dcmd: dcmd['flags'] = '' dcmd['flags'] += item[1] else: # unnamed parameter module = gtask.parse_interface(cmd[0]) dcmd[module.define_first()] = item return (cmd[0], dcmd)
def CmdToTuple(cmd): """!Convert command list to tuple for gcmd.RunCommand()""" if len(cmd) < 1: return None dcmd = {} for item in cmd[1:]: if '=' in item: # params key, value = item.split('=', 1) dcmd[str(key)] = str(value) elif item[:2] == '--': # long flags flag = item[2:] if flag in ('verbose', 'quiet', 'overwrite'): dcmd[str(flag)] = True elif len(item) == 2 and item[0] == '-': # -> flags if 'flags' not in dcmd: dcmd['flags'] = '' dcmd['flags'] += item[1] else: # unnamed parameter module = gtask.parse_interface(cmd[0]) dcmd[module.define_first()] = item return (cmd[0], dcmd)
def RunCmd( self, command, compReg=True, env=None, skipInterface=False, onDone=None, onPrepare=None, userData=None, addLayer=None, notification=Notification.MAKE_VISIBLE, ): """Run command typed into console command prompt (GPrompt). .. todo:: Document the other event. .. todo:: Solve problem with the other event (now uses gOutputText event but there is no text, use onPrepare handler instead?) .. todo:: Skip interface is ignored and determined always automatically. Posts event EVT_IGNORED_CMD_RUN when command which should be ignored (according to ignoredCmdPattern) is run. For example, see layer manager which handles d.* on its own. :param command: command given as a list (produced e.g. by utils.split()) :param compReg: True use computation region :param notification: form of notification :param bool skipInterface: True to do not launch GRASS interface parser when command has no arguments given :param onDone: function to be called when command is finished :param onPrepare: function to be called before command is launched :param addLayer: to be passed in the mapCreated signal :param userData: data defined for the command """ if len(command) == 0: Debug.msg(2, "GPrompt:RunCmd(): empty command") return # update history file self.UpdateHistoryFile(" ".join(command)) if command[0] in globalvar.grassCmd: # send GRASS command without arguments to GUI command interface # except ignored commands (event is emitted) if ( self._ignoredCmdPattern and re.compile(self._ignoredCmdPattern).search(" ".join(command)) and "--help" not in command and "--ui" not in command ): event = gIgnoredCmdRun(cmd=command) wx.PostEvent(self, event) return else: # other GRASS commands (r|v|g|...) try: task = GUI(show=None).ParseCommand(command) except GException as e: GError(parent=self._guiparent, message=str(e), showTraceback=False) return hasParams = False if task: options = task.get_options() hasParams = options["params"] and options["flags"] # check for <input>=- for p in options["params"]: if ( p.get("prompt", "") == "input" and p.get("element", "") == "file" and p.get("age", "new") == "old" and p.get("value", "") == "-" ): GError( parent=self._guiparent, message=_( "Unable to run command:\n%(cmd)s\n\n" "Option <%(opt)s>: read from standard input is not " "supported by wxGUI" ) % {"cmd": " ".join(command), "opt": p.get("name", "")}, ) return if len(command) == 1: if command[0].startswith("g.gui."): import imp import inspect pyFile = command[0] if sys.platform == "win32": pyFile += ".py" pyPath = os.path.join(os.environ["GISBASE"], "scripts", pyFile) if not os.path.exists(pyPath): pyPath = os.path.join( os.environ["GRASS_ADDON_BASE"], "scripts", pyFile ) if not os.path.exists(pyPath): GError( parent=self._guiparent, message=_("Module <%s> not found.") % command[0], ) pymodule = imp.load_source(command[0].replace(".", "_"), pyPath) try: # PY3 pymain = inspect.getfullargspec(pymodule.main) except AttributeError: pymain = inspect.getargspec(pymodule.main) if pymain and "giface" in pymain.args: pymodule.main(self._giface) return # no arguments given if hasParams and not isinstance(self._guiparent, FormNotebook): # also parent must be checked, see #3135 for details try: GUI( parent=self._guiparent, giface=self._giface ).ParseCommand(command) except GException as e: print(e, file=sys.stderr) return if env: env = env.copy() else: env = os.environ.copy() # activate computational region (set with g.region) # for all non-display commands. if compReg and "GRASS_REGION" in env: del env["GRASS_REGION"] # process GRASS command with argument self.cmdThread.RunCmd( command, stdout=self.cmdStdOut, stderr=self.cmdStdErr, onDone=onDone, onPrepare=onPrepare, userData=userData, addLayer=addLayer, env=env, notification=notification, ) self.cmdOutputTimer.Start(50) # we don't need to change computational region settings # because we work on a copy else: # Send any other command to the shell. Send output to # console output window # # Check if the script has an interface (avoid double-launching # of the script) # check if we ignore the command (similar to grass commands part) if self._ignoredCmdPattern and re.compile(self._ignoredCmdPattern).search( " ".join(command) ): event = gIgnoredCmdRun(cmd=command) wx.PostEvent(self, event) return skipInterface = True if os.path.splitext(command[0])[1] in (".py", ".sh"): try: sfile = open(command[0], "r") for line in sfile.readlines(): if len(line) < 2: continue if line[0] == "#" and line[1] == "%": skipInterface = False break sfile.close() except IOError: pass if len(command) == 1 and not skipInterface: try: task = gtask.parse_interface(command[0]) except: task = None else: task = None if task: # process GRASS command without argument GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command) else: self.cmdThread.RunCmd( command, stdout=self.cmdStdOut, stderr=self.cmdStdErr, onDone=onDone, onPrepare=onPrepare, userData=userData, addLayer=addLayer, env=env, notification=notification, ) self.cmdOutputTimer.Start(50)
def GetLayerNameFromCmd(dcmd, fullyQualified=False, param=None, layerType=None): """!Get map name from GRASS command Parameter dcmd can be modified when first parameter is not defined. @param dcmd GRASS command (given as list) @param fullyQualified change map name to be fully qualified @param param params directory @param layerType check also layer type ('raster', 'vector', '3d-raster', ...) @return tuple (name, found) """ mapname = '' found = True if len(dcmd) < 1: return mapname, False if 'd.grid' == dcmd[0]: mapname = 'grid' elif 'd.geodesic' in dcmd[0]: mapname = 'geodesic' elif 'd.rhumbline' in dcmd[0]: mapname = 'rhumb' elif 'labels=' in dcmd[0]: mapname = dcmd[idx].split('=')[1] + ' labels' else: params = list() for idx in range(len(dcmd)): try: p, v = dcmd[idx].split('=', 1) except ValueError: continue if p == param: params = [(idx, p, v)] break if p in ('map', 'input', 'red', 'blue', 'green', 'h_map', 's_map', 'i_map', 'reliefmap', 'labels'): params.append((idx, p, v)) if len(params) < 1: if len(dcmd) > 1: i = 1 while i < len(dcmd): if '=' not in dcmd[i] and not dcmd[i].startswith('-'): task = gtask.parse_interface(dcmd[0]) # this expects the first parameter to be the right one p = task.get_options()['params'][0].get('name', '') params.append((i, p, dcmd[i])) break i += 1 else: return mapname, False if len(params) < 1: return mapname, False # need to add mapset for all maps mapsets = {} for i, p, v in params: mapname = v mapset = '' if fullyQualified and '@' not in mapname: if layerType in ('raster', 'vector', '3d-raster', 'rgb', 'his'): try: if layerType in ('raster', 'rgb', 'his'): findType = 'cell' else: findType = layerType mapset = grass.find_file(mapname, element=findType)['mapset'] except AttributeError, e: # not found return '', False if not mapset: found = False else: mapset = grass.gisenv()['MAPSET'] mapsets[i] = mapset # update dcmd for i, p, v in params: if p: dcmd[i] = p + '=' + v else: dcmd[i] = v if i in mapsets and mapsets[i]: dcmd[i] += '@' + mapsets[i] maps = list() for i, p, v in params: if not p: maps.append(v) else: maps.append(dcmd[i].split('=', 1)[1]) mapname = '\n'.join(maps)
def GetLayerNameFromCmd(dcmd, fullyQualified = False, param = None, layerType = None): """!Get map name from GRASS command Parameter dcmd can be modified when first parameter is not defined. @param dcmd GRASS command (given as list) @param fullyQualified change map name to be fully qualified @param param params directory @param layerType check also layer type ('raster', 'vector', '3d-raster', ...) @return tuple (name, found) """ mapname = '' found = True if len(dcmd) < 1: return mapname, False if 'd.grid' == dcmd[0]: mapname = 'grid' elif 'd.geodesic' in dcmd[0]: mapname = 'geodesic' elif 'd.rhumbline' in dcmd[0]: mapname = 'rhumb' elif 'labels=' in dcmd[0]: mapname = dcmd[idx].split('=')[1] + ' labels' else: params = list() for idx in range(len(dcmd)): try: p, v = dcmd[idx].split('=', 1) except ValueError: continue if p == param: params = [(idx, p, v)] break if p in ('map', 'input', 'red', 'blue', 'green', 'h_map', 's_map', 'i_map', 'reliefmap', 'labels'): params.append((idx, p, v)) if len(params) < 1: if len(dcmd) > 1: i = 1 while i < len(dcmd): if '=' not in dcmd[i] and not dcmd[i].startswith('-'): task = gtask.parse_interface(dcmd[0]) # this expects the first parameter to be the right one p = task.get_options()['params'][0].get('name', '') params.append((i, p, dcmd[i])) break i += 1 else: return mapname, False if len(params) < 1: return mapname, False # need to add mapset for all maps mapsets = {} for i, p, v in params: mapname = v mapset = '' if fullyQualified and '@' not in mapname: if layerType in ('raster', 'vector', '3d-raster', 'rgb', 'his'): try: if layerType in ('raster', 'rgb', 'his'): findType = 'cell' else: findType = layerType mapset = grass.find_file(mapname, element = findType)['mapset'] except AttributeError, e: # not found return '', False if not mapset: found = False else: mapset = grass.gisenv()['MAPSET'] mapsets[i] = mapset # update dcmd for i, p, v in params: if p: dcmd[i] = p + '=' + v else: dcmd[i] = v if i in mapsets and mapsets[i]: dcmd[i] += '@' + mapsets[i] maps = list() for i, p, v in params: if not p: maps.append(v) else: maps.append(dcmd[i].split('=', 1)[1]) mapname = '\n'.join(maps)
def GetLayerNameFromCmd(dcmd, fullyQualified = False, param = None, layerType = None): """!Get map name from GRASS command Parameter dcmd can be modified when first parameter is not defined. @param dcmd GRASS command (given as list) @param fullyQualified change map name to be fully qualified @param param params directory @param layerType check also layer type ('raster', 'vector', '3d-raster', ...) @return tuple (name, found) """ mapname = '' found = True if len(dcmd) < 1: return mapname, False if 'd.grid' == dcmd[0]: mapname = 'grid' elif 'd.geodesic' in dcmd[0]: mapname = 'geodesic' elif 'd.rhumbline' in dcmd[0]: mapname = 'rhumb' else: params = list() for idx in range(len(dcmd)): try: p, v = dcmd[idx].split('=', 1) except ValueError: continue if p == param: params = [(idx, p, v)] break if p in ('map', 'input', 'layer', 'red', 'blue', 'green', 'h_map', 's_map', 'i_map', 'reliefmap', 'labels'): params.append((idx, p, v)) if len(params) < 1: if len(dcmd) > 1 and '=' not in dcmd[1]: task = gtask.parse_interface(dcmd[0]) p = task.get_options()['params'][0].get('name', '') params.append((1, p, dcmd[1])) else: return mapname, False mapname = params[0][2] mapset = '' if fullyQualified and '@' not in mapname: if layerType in ('raster', 'vector', '3d-raster', 'rgb', 'his'): try: if layerType in ('raster', 'rgb', 'his'): findType = 'cell' else: findType = layerType mapset = grass.find_file(mapname, element = findType)['mapset'] except AttributeError, e: # not found return '', False if not mapset: found = False else: mapset = grass.gisenv()['MAPSET'] # update dcmd for i, p, v in params: if p == 'layer': continue dcmd[i] = p + '=' + v if mapset: dcmd[i] += '@' + mapset maps = list() ogr = False for i, p, v in params: if v.lower().rfind('@ogr') > -1: ogr = True if p == 'layer' and not ogr: continue maps.append(dcmd[i].split('=', 1)[1]) mapname = '\n'.join(maps)
def OnKeyPressed(self, event): """!Key press capture for autocompletion, calltips, and command history @todo event.ControlDown() for manual autocomplete """ # keycodes used: "." = 46, "=" = 61, "-" = 45 pos = self.GetCurrentPos() #complete command after pressing '.' if event.GetKeyCode() == 46 and not event.ShiftDown(): self.autoCompList = list() entry = self.GetTextLeft() self.InsertText(pos, '.') self.CharRight() self.toComplete = self.EntityToComplete() try: if self.toComplete['entity'] == 'command': self.autoCompList = self.moduleList[entry.strip()] except (KeyError, TypeError): return self.ShowList() # complete flags after pressing '-' elif event.GetKeyCode() == 45 and not event.ShiftDown(): self.autoCompList = list() entry = self.GetTextLeft() self.InsertText(pos, '-') self.CharRight() self.toComplete = self.EntityToComplete() if self.toComplete['entity'] == 'flags' and self.cmdDesc: if self.GetTextLeft()[-2:] == ' -': # complete e.g. --quite for flag in self.cmdDesc.get_options()['flags']: if len(flag['name']) == 1: self.autoCompList.append(flag['name']) else: for flag in self.cmdDesc.get_options()['flags']: if len(flag['name']) > 1: self.autoCompList.append(flag['name']) self.ShowList() # complete map or values after parameter elif event.GetKeyCode() == 61 and not event.ShiftDown(): self.autoCompList = list() self.InsertText(pos, '=') self.CharRight() self.toComplete = self.EntityToComplete() if self.toComplete: if self.toComplete['entity'] == 'raster map': self.autoCompList = self.mapList['raster'] elif self.toComplete['entity'] == 'vector map': self.autoCompList = self.mapList['vector'] elif self.toComplete['entity'] == 'param values': param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =') self.autoCompList = self.cmdDesc.get_param(param)['values'] self.ShowList() # complete after pressing CTRL + Space elif event.GetKeyCode() == wx.WXK_SPACE and event.ControlDown(): self.autoCompList = list() self.toComplete = self.EntityToComplete() if self.toComplete is None: return #complete command if self.toComplete['entity'] == 'command': for command in globalvar.grassCmd['all']: if command.find(self.toComplete['cmd']) == 0: dotNumber = list(self.toComplete['cmd']).count('.') self.autoCompList.append(command.split('.',dotNumber)[-1]) # complete flags in such situations (| is cursor): # r.colors -| ...w, q, l # r.colors -w| ...w, q, l elif self.toComplete['entity'] == 'flags' and self.cmdDesc: for flag in self.cmdDesc.get_options()['flags']: if len(flag['name']) == 1: self.autoCompList.append(flag['name']) # complete parameters in such situations (| is cursor): # r.colors -w | ...color, map, rast, rules # r.colors col| ...color elif self.toComplete['entity'] == 'params' and self.cmdDesc: for param in self.cmdDesc.get_options()['params']: if param['name'].find(self.GetWordLeft(withDelimiter=False)) == 0: self.autoCompList.append(param['name']) # complete flags or parameters in such situations (| is cursor): # r.colors | ...-w, -q, -l, color, map, rast, rules # r.colors color=grey | ...-w, -q, -l, color, map, rast, rules elif self.toComplete['entity'] == 'params+flags' and self.cmdDesc: self.autoCompList = list() for param in self.cmdDesc.get_options()['params']: self.autoCompList.append(param['name']) for flag in self.cmdDesc.get_options()['flags']: if len(flag['name']) == 1: self.autoCompList.append('-' + flag['name']) else: self.autoCompList.append('--' + flag['name']) self.ShowList() # complete map or values after parameter # r.buffer input=| ...list of raster maps # r.buffer units=| ... feet, kilometers, ... elif self.toComplete['entity'] == 'raster map': self.autoCompList = list() self.autoCompList = self.mapList['raster'] elif self.toComplete['entity'] == 'vector map': self.autoCompList = list() self.autoCompList = self.mapList['vector'] elif self.toComplete['entity'] == 'param values': self.autoCompList = list() param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =') self.autoCompList = self.cmdDesc.get_param(param)['values'] self.ShowList() elif event.GetKeyCode() == wx.WXK_TAB: # show GRASS command calltips (to hide press 'ESC') entry = self.GetTextLeft() try: cmd = entry.split()[0].strip() except IndexError: cmd = '' if cmd not in globalvar.grassCmd['all']: return info = gtask.command_info(cmd) self.CallTipSetBackground("#f4f4d1") self.CallTipSetForeground("BLACK") self.CallTipShow(pos, info['usage'] + '\n\n' + info['description']) elif event.GetKeyCode() in [wx.WXK_UP, wx.WXK_DOWN] and \ not self.AutoCompActive(): # Command history using up and down if len(self.cmdbuffer) < 1: return self.DocumentEnd() # move through command history list index values if event.GetKeyCode() == wx.WXK_UP: self.cmdindex = self.cmdindex - 1 if event.GetKeyCode() == wx.WXK_DOWN: self.cmdindex = self.cmdindex + 1 if self.cmdindex < 0: self.cmdindex = 0 if self.cmdindex > len(self.cmdbuffer) - 1: self.cmdindex = len(self.cmdbuffer) - 1 try: txt = self.cmdbuffer[self.cmdindex] except: txt = '' # clear current line and insert command history self.DelLineLeft() self.DelLineRight() pos = self.GetCurrentPos() self.InsertText(pos,txt) self.LineEnd() self.parent.parent.statusbar.SetStatusText('') elif event.GetKeyCode() == wx.WXK_RETURN and \ self.AutoCompActive() == False: # run command on line when <return> is pressed if self.parent.GetName() == "ModelerDialog": self.parent.OnOk(None) return # find the command to run line = self.GetCurLine()[0].strip() if len(line) == 0: return # parse command into list try: cmd = utils.split(str(line)) except UnicodeError: cmd = utils.split(utils.EncodeString((line))) cmd = map(utils.DecodeString, cmd) # send the command list to the processor if cmd[0] in ('r.mapcalc', 'r3.mapcalc') and len(cmd) == 1: self.parent.parent.OnMapCalculator(event = None, cmd = cmd) else: self.parent.RunCmd(cmd) # add command to history & clean prompt self.UpdateCmdHistory(cmd) self.OnCmdErase(None) self.parent.parent.statusbar.SetStatusText('') elif event.GetKeyCode() == wx.WXK_SPACE: items = self.GetTextLeft().split() if len(items) == 1: cmd = items[0].strip() if cmd in globalvar.grassCmd['all'] and \ cmd != 'r.mapcalc' and \ (not self.cmdDesc or cmd != self.cmdDesc.get_name()): try: self.cmdDesc = gtask.parse_interface(cmd) except IOError: self.cmdDesc = None event.Skip() else: event.Skip()
def RunCmd(self, command, compReg=True, skipInterface=False, onDone=None, onPrepare=None, userData=None, addLayer=None, notification=Notification.MAKE_VISIBLE): """Run command typed into console command prompt (GPrompt). .. todo:: Document the other event. .. todo:: Solve problem with the other event (now uses gOutputText event but there is no text, use onPrepare handler instead?) Posts event EVT_IGNORED_CMD_RUN when command which should be ignored (according to ignoredCmdPattern) is run. For example, see layer manager which handles d.* on its own. :param command: command given as a list (produced e.g. by utils.split()) :param compReg: True use computation region :param notification: form of notification :param bool skipInterface: True to do not launch GRASS interface parser when command has no arguments given :param onDone: function to be called when command is finished :param onPrepare: function to be called before command is launched :param addLayer: to be passed in the mapCreated signal :param userData: data defined for the command """ if len(command) == 0: Debug.msg(2, "GPrompt:RunCmd(): empty command") return # update history file self.UpdateHistoryFile(' '.join(command)) if command[0] in globalvar.grassCmd: # send GRASS command without arguments to GUI command interface # except ignored commands (event is emitted) if self._ignoredCmdPattern and \ re.compile(self._ignoredCmdPattern).search(' '.join(command)) and \ '--help' not in command and '--ui' not in command: event = gIgnoredCmdRun(cmd=command) wx.PostEvent(self, event) return else: # other GRASS commands (r|v|g|...) try: task = GUI(show=None).ParseCommand(command) except GException as e: GError(parent=self._guiparent, message=unicode(e), showTraceback=False) return hasParams = False if task: options = task.get_options() hasParams = options['params'] and options['flags'] # check for <input>=- for p in options['params']: if p.get('prompt', '') == 'input' and \ p.get('element', '') == 'file' and \ p.get('age', 'new') == 'old' and \ p.get('value', '') == '-': GError( parent=self._guiparent, message= _("Unable to run command:\n%(cmd)s\n\n" "Option <%(opt)s>: read from standard input is not " "supported by wxGUI") % { 'cmd': ' '.join(command), 'opt': p.get('name', '') }) return if len(command) == 1: if command[0].startswith('g.gui.'): import imp import inspect pyFile = command[0] if sys.platform == 'win32': pyFile += '.py' pyPath = os.path.join(os.environ['GISBASE'], 'scripts', pyFile) if not os.path.exists(pyPath): pyPath = os.path.join( os.environ['GRASS_ADDON_BASE'], 'scripts', pyFile) if not os.path.exists(pyPath): GError(parent=self._guiparent, message=_("Module <%s> not found.") % command[0]) pymodule = imp.load_source( command[0].replace('.', '_'), pyPath) pymain = inspect.getargspec(pymodule.main) if pymain and 'giface' in pymain.args: pymodule.main(self._giface) return if hasParams and command[0] != 'v.krige': # no arguments given try: GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command) except GException as e: print >> sys.stderr, e return # activate computational region (set with g.region) # for all non-display commands. if compReg: tmpreg = os.getenv("GRASS_REGION") if "GRASS_REGION" in os.environ: del os.environ["GRASS_REGION"] # process GRASS command with argument self.cmdThread.RunCmd(command, stdout=self.cmdStdOut, stderr=self.cmdStdErr, onDone=onDone, onPrepare=onPrepare, userData=userData, addLayer=addLayer, env=os.environ.copy(), notification=notification) self.cmdOutputTimer.Start(50) # deactivate computational region and return to display settings if compReg and tmpreg: os.environ["GRASS_REGION"] = tmpreg else: # Send any other command to the shell. Send output to # console output window # # Check if the script has an interface (avoid double-launching # of the script) # check if we ignore the command (similar to grass commands part) if self._ignoredCmdPattern and \ re.compile(self._ignoredCmdPattern).search(' '.join(command)): event = gIgnoredCmdRun(cmd=command) wx.PostEvent(self, event) return skipInterface = True if os.path.splitext(command[0])[1] in ('.py', '.sh'): try: sfile = open(command[0], "r") for line in sfile.readlines(): if len(line) < 2: continue if line[0] is '#' and line[1] is '%': skipInterface = False break sfile.close() except IOError: pass if len(command) == 1 and not skipInterface: try: task = gtask.parse_interface(command[0]) except: task = None else: task = None if task: # process GRASS command without argument GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command) else: self.cmdThread.RunCmd(command, stdout=self.cmdStdOut, stderr=self.cmdStdErr, onDone=onDone, onPrepare=onPrepare, userData=userData, addLayer=addLayer, notification=notification) self.cmdOutputTimer.Start(50)
def RunCmd(self, command, compReg=True, skipInterface=False, onDone=None, onPrepare=None, userData=None, notification=Notification.MAKE_VISIBLE): """Run command typed into console command prompt (GPrompt). .. todo:: Document the other event. .. todo:: Solve problem with the other event (now uses gOutputText event but there is no text, use onPrepare handler instead?) Posts event EVT_IGNORED_CMD_RUN when command which should be ignored (according to ignoredCmdPattern) is run. For example, see layer manager which handles d.* on its own. :param command: command given as a list (produced e.g. by utils.split()) :param compReg: True use computation region :param notification: form of notification :param bool skipInterface: True to do not launch GRASS interface parser when command has no arguments given :param onDone: function to be called when command is finished :param onPrepare: function to be called before command is launched :param userData: data defined for the command """ if len(command) == 0: Debug.msg(2, "GPrompt:RunCmd(): empty command") return # update history file self.UpdateHistoryFile(' '.join(command)) if command[0] in globalvar.grassCmd: # send GRASS command without arguments to GUI command interface # except ignored commands (event is emitted) if self._ignoredCmdPattern and \ re.compile(self._ignoredCmdPattern).search(' '.join(command)) and \ '--help' not in command and '--ui' not in command: event = gIgnoredCmdRun(cmd=command) wx.PostEvent(self, event) return else: # other GRASS commands (r|v|g|...) try: task = GUI(show=None).ParseCommand(command) except GException as e: GError(parent=self._guiparent, message=unicode(e), showTraceback=False) return hasParams = False if task: options = task.get_options() hasParams = options['params'] and options['flags'] # check for <input>=- for p in options['params']: if p.get('prompt', '') == 'input' and \ p.get('element', '') == 'file' and \ p.get('age', 'new') == 'old' and \ p.get('value', '') == '-': GError(parent=self._guiparent, message=_("Unable to run command:\n%(cmd)s\n\n" "Option <%(opt)s>: read from standard input is not " "supported by wxGUI") % {'cmd': ' '.join(command), 'opt': p.get('name', '')}) return if len(command) == 1 and hasParams and \ command[0] != 'v.krige': # no arguments given try: GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command) except GException as e: print >> sys.stderr, e return # activate computational region (set with g.region) # for all non-display commands. if compReg: tmpreg = os.getenv("GRASS_REGION") if "GRASS_REGION" in os.environ: del os.environ["GRASS_REGION"] # process GRASS command with argument self.cmdThread.RunCmd(command, stdout=self.cmdStdOut, stderr=self.cmdStdErr, onDone=onDone, onPrepare=onPrepare, userData=userData, env=os.environ.copy(), notification=notification) self.cmdOutputTimer.Start(50) # deactivate computational region and return to display settings if compReg and tmpreg: os.environ["GRASS_REGION"] = tmpreg else: # Send any other command to the shell. Send output to # console output window # # Check if the script has an interface (avoid double-launching # of the script) # check if we ignore the command (similar to grass commands part) if self._ignoredCmdPattern and \ re.compile(self._ignoredCmdPattern).search(' '.join(command)): event = gIgnoredCmdRun(cmd=command) wx.PostEvent(self, event) return skipInterface = True if os.path.splitext(command[0])[1] in ('.py', '.sh'): try: sfile = open(command[0], "r") for line in sfile.readlines(): if len(line) < 2: continue if line[0] is '#' and line[1] is '%': skipInterface = False break sfile.close() except IOError: pass if len(command) == 1 and not skipInterface: try: task = gtask.parse_interface(command[0]) except: task = None else: task = None if task: # process GRASS command without argument GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command) else: self.cmdThread.RunCmd(command, stdout=self.cmdStdOut, stderr=self.cmdStdErr, onDone=onDone, onPrepare=onPrepare, userData=userData, notification=notification) self.cmdOutputTimer.Start(50)
def __init__(self, parent, id = wx.ID_ANY, title = _("Fetch & install extension from GRASS Addons"), **kwargs): self.parent = parent self.options = dict() # list of options wx.Frame.__init__(self, parent = parent, id = id, title = title, **kwargs) self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO)) self.panel = wx.Panel(parent = self, id = wx.ID_ANY) self.repoBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY, label = " %s " % _("Repository")) self.treeBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY, label = " %s " % _("List of extensions")) self.repo = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY) self.fullDesc = wx.CheckBox(parent = self.panel, id = wx.ID_ANY, label = _("Fetch full info including description and keywords")) self.fullDesc.SetValue(True) self.search = SearchModuleWindow(parent = self.panel) self.search.SetSelection(0) self.tree = ExtensionTree(parent = self.panel, log = parent.GetLogWindow()) self.optionBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY, label = " %s " % _("Options")) task = gtask.parse_interface('g.extension.py') ignoreFlags = ['l', 'c', 'g', 'a', 'f', 'quiet', 'verbose'] if sys.platform == 'win32': ignoreFlags.append('d') ignoreFlags.append('i') for f in task.get_options()['flags']: name = f.get('name', '') desc = f.get('label', '') if not desc: desc = f.get('description', '') if not name and not desc: continue if name in ignoreFlags: continue self.options[name] = wx.CheckBox(parent = self.panel, id = wx.ID_ANY, label = desc) self.repo.SetValue(task.get_param(value = 'svnurl').get('default', 'http://svn.osgeo.org/grass/grass-addons')) self.statusbar = self.CreateStatusBar(number = 1) self.btnFetch = wx.Button(parent = self.panel, id = wx.ID_ANY, label = _("&Fetch")) self.btnFetch.SetToolTipString(_("Fetch list of available modules from GRASS Addons SVN repository")) self.btnClose = wx.Button(parent = self.panel, id = wx.ID_CLOSE) self.btnInstall = wx.Button(parent = self.panel, id = wx.ID_ANY, label = _("&Install")) self.btnInstall.SetToolTipString(_("Install selected add-ons GRASS module")) self.btnInstall.Enable(False) self.btnCmd = wx.Button(parent = self.panel, id = wx.ID_ANY, label = _("Command dialog")) self.btnCmd.SetToolTipString(_('Open %s dialog') % 'g.extension.py') self.btnClose.Bind(wx.EVT_BUTTON, self.OnCloseWindow) self.btnFetch.Bind(wx.EVT_BUTTON, self.OnFetch) self.btnInstall.Bind(wx.EVT_BUTTON, self.OnInstall) self.btnCmd.Bind(wx.EVT_BUTTON, self.OnCmdDialog) self.tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnItemActivated) self.tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnItemSelected) self.search.Bind(wx.EVT_TEXT_ENTER, self.OnShowItem) self.search.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar) self._layout()
def __init__(self, parent, giface, id=wx.ID_ANY, title=_("Fetch & install extension from GRASS Addons"), **kwargs): self.parent = parent self._giface = giface self.options = dict() # list of options wx.Frame.__init__(self, parent=parent, id=id, title=title, **kwargs) self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, "grass.ico"), wx.BITMAP_TYPE_ICO)) self.panel = wx.Panel(parent=self, id=wx.ID_ANY) self.repoBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY, label=" %s " % _("Repository")) self.treeBox = wx.StaticBox( parent=self.panel, id=wx.ID_ANY, label=" %s " % _("List of extensions - double-click to install") ) self.repo = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY) # modelBuilder loads data into tree model self.modelBuilder = ExtensionTreeModelBuilder() # tree view displays model data self.tree = CTreeView(parent=self.panel, model=self.modelBuilder.GetModel()) self.search = SearchModuleWidget(parent=self.panel, model=self.modelBuilder.GetModel(), showChoice=False) self.search.showSearchResult.connect(lambda result: self.tree.Select(result)) # show text in statusbar when notification appears self.search.showNotification.connect(lambda message: self.SetStatusText(message)) # load data in different thread self.thread = gThread() self.optionBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY, label=" %s " % _("Options")) task = gtask.parse_interface("g.extension") ignoreFlags = ["l", "c", "g", "a", "f", "t", "help", "quiet"] if sys.platform == "win32": ignoreFlags.append("d") ignoreFlags.append("i") for f in task.get_options()["flags"]: name = f.get("name", "") desc = f.get("label", "") if not desc: desc = f.get("description", "") if not name and not desc: continue if name in ignoreFlags: continue self.options[name] = wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=desc) defaultUrl = "http://svn.osgeo.org/grass/grass-addons/grass7" self.repo.SetValue(task.get_param(value="svnurl").get("default", defaultUrl)) self.statusbar = self.CreateStatusBar(number=1) self.btnFetch = wx.Button(parent=self.panel, id=wx.ID_ANY, label=_("&Fetch")) self.btnFetch.SetToolTipString(_("Fetch list of available modules " "from GRASS Addons SVN repository")) self.btnClose = wx.Button(parent=self.panel, id=wx.ID_CLOSE) self.btnInstall = wx.Button(parent=self.panel, id=wx.ID_ANY, label=_("&Install")) self.btnInstall.SetToolTipString(_("Install selected add-ons GRASS module")) self.btnInstall.Enable(False) self.btnHelp = wx.Button(parent=self.panel, id=wx.ID_HELP) self.btnHelp.SetToolTipString(_("Show g.extension manual page")) self.btnClose.Bind(wx.EVT_BUTTON, lambda evt: self.Close()) self.btnFetch.Bind(wx.EVT_BUTTON, self.OnFetch) self.btnInstall.Bind(wx.EVT_BUTTON, self.OnInstall) self.btnHelp.Bind(wx.EVT_BUTTON, self.OnHelp) self.tree.selectionChanged.connect(self.OnItemSelected) self.tree.itemActivated.connect(self.OnItemActivated) self.tree.contextMenu.connect(self.OnContextMenu) wx.CallAfter(self._fetch) self._layout()
gisdb = os.path.join(os.path.expanduser("~"), "Documents/grassdata") location = "nc_spm_08" mapset = "user1" rcfile = gsetup.init(gisbase, gisdb, location, mapset) from grass.script import core as gcore cmds = list(gcore.get_commands()[0]) cmds.sort() file_names = [cmd.replace('.', '_') for cmd in cmds] print len(cmds) with open(os.path.join("C:\Users", "radek", "Desktop", "generate_xml.bat"), 'w') as file: file.write('@ECHO ON\n') for name, file_name in zip(cmds, file_names): file.write( '{} --interface-description > C:\Users\\radek\Desktop\XML_grass\{}.xml\n' .format(name, file_name)) from grass.script import task as gtask gtask.command_info('r.info') # for name in cmds: print gtask.parse_interface( 'C:\\Program Files (x86)\\QGIS 3.0\\apps\\grass\\grass-7.4.0\\scripts\\r.grow.py' ) # r.univar --interface-description > C:\Users\radek\Desktop\r_univar.txt os.remove(rcfile)
def GetLayerNameFromCmd(dcmd, fullyQualified=False, param=None, layerType=None): """Get map name from GRASS command Parameter dcmd can be modified when first parameter is not defined. :param dcmd: GRASS command (given as list) :param fullyQualified: change map name to be fully qualified :param param: params directory :param str layerType: check also layer type ('raster', 'vector', 'raster_3d', ...) :return: tuple (name, found) """ mapname = '' found = True if len(dcmd) < 1: return mapname, False if 'd.grid' == dcmd[0]: mapname = 'grid' elif 'd.geodesic' in dcmd[0]: mapname = 'geodesic' elif 'd.rhumbline' in dcmd[0]: mapname = 'rhumb' elif 'd.graph' in dcmd[0]: mapname = 'graph' else: params = list() for idx in range(len(dcmd)): try: p, v = dcmd[idx].split('=', 1) except ValueError: continue if p == param: params = [(idx, p, v)] break # this does not use types, just some (incomplete subset of?) names if p in ('map', 'input', 'layer', 'red', 'blue', 'green', 'hue', 'saturation', 'intensity', 'shade', 'labels'): params.append((idx, p, v)) if len(params) < 1: if len(dcmd) > 1: i = 1 while i < len(dcmd): if '=' not in dcmd[i] and not dcmd[i].startswith('-'): task = gtask.parse_interface(dcmd[0]) # this expects the first parameter to be the right one p = task.get_options()['params'][0].get('name', '') params.append((i, p, dcmd[i])) break i += 1 else: return mapname, False if len(params) < 1: return mapname, False # need to add mapset for all maps mapsets = {} for i, p, v in params: if p == 'layer': continue mapname = v mapset = '' if fullyQualified and '@' not in mapname: if layerType in ('raster', 'vector', 'raster_3d', 'rgb', 'his'): try: if layerType in ('raster', 'rgb', 'his'): findType = 'cell' elif layerType == 'raster_3d': findType = 'grid3' else: findType = layerType mapset = grass.find_file(mapname, element=findType)['mapset'] except AttributeError: # not found return '', False if not mapset: found = False else: mapset = '' # grass.gisenv()['MAPSET'] mapsets[i] = mapset # update dcmd for i, p, v in params: if p == 'layer': continue dcmd[i] = p + '=' + v if i in mapsets and mapsets[i]: dcmd[i] += '@' + mapsets[i] maps = list() ogr = False for i, p, v in params: if v.lower().rfind('@ogr') > -1: ogr = True if p == 'layer' and not ogr: continue maps.append(dcmd[i].split('=', 1)[1]) mapname = '\n'.join(maps) return mapname, found
def GetLayerNameFromCmd(dcmd, fullyQualified=False, param=None, layerType=None): """Get map name from GRASS command Parameter dcmd can be modified when first parameter is not defined. :param dcmd: GRASS command (given as list) :param fullyQualified: change map name to be fully qualified :param param: params directory :param str layerType: check also layer type ('raster', 'vector', 'raster_3d', ...) :return: tuple (name, found) """ mapname = "" found = True if len(dcmd) < 1: return mapname, False if "d.grid" == dcmd[0]: mapname = "grid" elif "d.geodesic" in dcmd[0]: mapname = "geodesic" elif "d.rhumbline" in dcmd[0]: mapname = "rhumb" elif "d.graph" in dcmd[0]: mapname = "graph" else: params = list() for idx in range(len(dcmd)): try: p, v = dcmd[idx].split("=", 1) except ValueError: continue if p == param: params = [(idx, p, v)] break # this does not use types, just some (incomplete subset of?) names if p in ( "map", "input", "layer", "red", "blue", "green", "hue", "saturation", "intensity", "shade", "labels", ): params.append((idx, p, v)) if len(params) < 1: if len(dcmd) > 1: i = 1 while i < len(dcmd): if "=" not in dcmd[i] and not dcmd[i].startswith("-"): task = gtask.parse_interface(dcmd[0]) # this expects the first parameter to be the right one p = task.get_options()["params"][0].get("name", "") params.append((i, p, dcmd[i])) break i += 1 else: return mapname, False if len(params) < 1: return mapname, False # need to add mapset for all maps mapsets = {} for i, p, v in params: if p == "layer": continue mapname = v mapset = "" if fullyQualified and "@" not in mapname: if layerType in ("raster", "vector", "raster_3d", "rgb", "his"): try: if layerType in ("raster", "rgb", "his"): findType = "cell" elif layerType == "raster_3d": findType = "grid3" else: findType = layerType mapset = grass.find_file(mapname, element=findType)["mapset"] except AttributeError: # not found return "", False if not mapset: found = False else: mapset = "" # grass.gisenv()['MAPSET'] mapsets[i] = mapset # update dcmd for i, p, v in params: if p == "layer": continue dcmd[i] = p + "=" + v if i in mapsets and mapsets[i]: dcmd[i] += "@" + mapsets[i] maps = list() ogr = False for i, p, v in params: if v.lower().rfind("@ogr") > -1: ogr = True if p == "layer" and not ogr: continue maps.append(dcmd[i].split("=", 1)[1]) mapname = "\n".join(maps) return mapname, found
def __init__(self, parent, giface, id=wx.ID_ANY, title=_("Fetch & install extension from GRASS Addons"), **kwargs): self.parent = parent self._giface = giface self.options = dict() # list of options wx.Frame.__init__(self, parent=parent, id=id, title=title, **kwargs) self.SetIcon( wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO)) self.panel = wx.Panel(parent=self, id=wx.ID_ANY) self.repoBox = wx.StaticBox( parent=self.panel, id=wx.ID_ANY, label=" %s " % _("Repository (leave empty to use the official one)")) self.treeBox = wx.StaticBox( parent=self.panel, id=wx.ID_ANY, label=" %s " % _("List of extensions - double-click to install")) self.repo = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY) # modelBuilder loads data into tree model self.modelBuilder = ExtensionTreeModelBuilder() # tree view displays model data self.tree = CTreeView(parent=self.panel, model=self.modelBuilder.GetModel()) self.search = SearchModuleWidget(parent=self.panel, model=self.modelBuilder.GetModel(), showChoice=False) self.search.showSearchResult.connect( lambda result: self.tree.Select(result)) # show text in statusbar when notification appears self.search.showNotification.connect( lambda message: self.SetStatusText(message)) # load data in different thread self.thread = gThread() self.optionBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY, label=" %s " % _("Options")) task = gtask.parse_interface('g.extension') ignoreFlags = ['l', 'c', 'g', 'a', 'f', 't', 'help', 'quiet'] if sys.platform == 'win32': ignoreFlags.append('d') ignoreFlags.append('i') for f in task.get_options()['flags']: name = f.get('name', '') desc = f.get('label', '') if not desc: desc = f.get('description', '') if not name and not desc: continue if name in ignoreFlags: continue self.options[name] = wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=desc) defaultUrl = '' # default/official one will be used when option empty self.repo.SetValue( task.get_param(value='url').get('default', defaultUrl)) self.statusbar = self.CreateStatusBar(number=1) self.btnFetch = wx.Button(parent=self.panel, id=wx.ID_ANY, label=_("&Fetch")) self.btnFetch.SetToolTipString( _("Fetch list of available modules " "from GRASS Addons SVN repository")) self.btnClose = wx.Button(parent=self.panel, id=wx.ID_CLOSE) self.btnInstall = wx.Button(parent=self.panel, id=wx.ID_ANY, label=_("&Install")) self.btnInstall.SetToolTipString( _("Install selected add-ons GRASS module")) self.btnInstall.Enable(False) self.btnHelp = wx.Button(parent=self.panel, id=wx.ID_HELP) self.btnHelp.SetToolTipString(_("Show g.extension manual page")) self.btnClose.Bind(wx.EVT_BUTTON, lambda evt: self.Close()) self.btnFetch.Bind(wx.EVT_BUTTON, self.OnFetch) self.btnInstall.Bind(wx.EVT_BUTTON, self.OnInstall) self.btnHelp.Bind(wx.EVT_BUTTON, self.OnHelp) self.tree.selectionChanged.connect(self.OnItemSelected) self.tree.itemActivated.connect(self.OnItemActivated) self.tree.contextMenu.connect(self.OnContextMenu) wx.CallAfter(self._fetch) self._layout()
def GetLayerNameFromCmd(dcmd, fullyQualified=False, param=None, layerType=None): """Get map name from GRASS command Parameter dcmd can be modified when first parameter is not defined. :param dcmd: GRASS command (given as list) :param fullyQualified: change map name to be fully qualified :param param: params directory :param str layerType: check also layer type ('raster', 'vector', 'raster_3d', ...) :return: tuple (name, found) """ mapname = '' found = True if len(dcmd) < 1: return mapname, False if 'd.grid' == dcmd[0]: mapname = 'grid' elif 'd.geodesic' in dcmd[0]: mapname = 'geodesic' elif 'd.rhumbline' in dcmd[0]: mapname = 'rhumb' elif 'd.graph' in dcmd[0]: mapname = 'graph' else: params = list() for idx in range(len(dcmd)): try: p, v = dcmd[idx].split('=', 1) except ValueError: continue if p == param: params = [(idx, p, v)] break # this does not use types, just some (incomplete subset of?) names if p in ('map', 'input', 'layer', 'red', 'blue', 'green', 'hue', 'saturation', 'intensity', 'shade', 'labels'): params.append((idx, p, v)) if len(params) < 1: if len(dcmd) > 1: i = 1 while i < len(dcmd): if '=' not in dcmd[i] and not dcmd[i].startswith('-'): task = gtask.parse_interface(dcmd[0]) # this expects the first parameter to be the right one p = task.get_options()['params'][0].get('name', '') params.append((i, p, dcmd[i])) break i += 1 else: return mapname, False if len(params) < 1: return mapname, False # need to add mapset for all maps mapsets = {} for i, p, v in params: if p == 'layer': continue mapname = v mapset = '' if fullyQualified and '@' not in mapname: if layerType in ('raster', 'vector', 'raster_3d', 'rgb', 'his'): try: if layerType in ('raster', 'rgb', 'his'): findType = 'cell' elif layerType == 'raster_3d': findType = 'grid3' else: findType = layerType mapset = grass.find_file( mapname, element=findType)['mapset'] except AttributeError: # not found return '', False if not mapset: found = False else: mapset = '' # grass.gisenv()['MAPSET'] mapsets[i] = mapset # update dcmd for i, p, v in params: if p == 'layer': continue dcmd[i] = p + '=' + v if i in mapsets and mapsets[i]: dcmd[i] += '@' + mapsets[i] maps = list() ogr = False for i, p, v in params: if v.lower().rfind('@ogr') > -1: ogr = True if p == 'layer' and not ogr: continue maps.append(dcmd[i].split('=', 1)[1]) mapname = '\n'.join(maps) return mapname, found
def __init__( self, parent, giface, id=wx.ID_ANY, title=_("Fetch & install extension from GRASS Addons"), **kwargs, ): self.parent = parent self._giface = giface self.options = dict() # list of options wx.Frame.__init__(self, parent=parent, id=id, title=title, **kwargs) self.SetIcon( wx.Icon(os.path.join(globalvar.ICONDIR, "grass.ico"), wx.BITMAP_TYPE_ICO)) self.panel = wx.Panel(parent=self, id=wx.ID_ANY) # self.repoBox = StaticBox( # parent=self.panel, id=wx.ID_ANY, label=" %s " % # _("Repository (leave empty to use the official one)")) self.treeBox = StaticBox( parent=self.panel, id=wx.ID_ANY, label=" %s " % _("List of extensions - double-click to install"), ) # self.repo = TextCtrl(parent=self.panel, id=wx.ID_ANY) # modelBuilder loads data into tree model self.modelBuilder = ExtensionTreeModelBuilder() # tree view displays model data self.tree = CTreeView(parent=self.panel, model=self.modelBuilder.GetModel()) self.search = SearchCtrl(self.panel) self.search.SetDescriptiveText(_("Search")) self.search.ShowCancelButton(True) # load data in different thread self.thread = gThread() self.optionBox = StaticBox(parent=self.panel, id=wx.ID_ANY, label=" %s " % _("Options")) task = gtask.parse_interface("g.extension") ignoreFlags = ["l", "c", "g", "a", "f", "t", "help", "quiet"] if sys.platform == "win32": ignoreFlags.append("d") ignoreFlags.append("i") for f in task.get_options()["flags"]: name = f.get("name", "") desc = f.get("label", "") if not desc: desc = f.get("description", "") if not name and not desc: continue if name in ignoreFlags: continue self.options[name] = wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=desc) # defaultUrl = '' # default/official one will be used when option empty # self.repo.SetValue( # task.get_param( # value='url').get( # 'default', # defaultUrl)) self.statusbar = self.CreateStatusBar(number=1) # self.btnFetch = Button(parent=self.panel, id=wx.ID_ANY, # label=_("&Fetch")) # self.btnFetch.SetToolTip(_("Fetch list of available modules " # "from GRASS Addons repository")) self.btnClose = Button(parent=self.panel, id=wx.ID_CLOSE) self.btnInstall = Button(parent=self.panel, id=wx.ID_ANY, label=_("&Install")) self.btnInstall.SetToolTip(_("Install selected add-ons GRASS module")) self.btnInstall.Enable(False) self.btnHelp = Button(parent=self.panel, id=wx.ID_HELP) self.btnHelp.SetToolTip(_("Show g.extension manual page")) self.btnClose.Bind(wx.EVT_BUTTON, lambda evt: self.Close()) # self.btnFetch.Bind(wx.EVT_BUTTON, self.OnFetch) self.btnInstall.Bind(wx.EVT_BUTTON, self.OnInstall) self.btnHelp.Bind(wx.EVT_BUTTON, self.OnHelp) self.search.Bind(wx.EVT_TEXT, lambda evt: self.Filter(evt.GetString())) self.search.Bind(wx.EVT_SEARCHCTRL_CANCEL_BTN, lambda evt: self.Filter("")) self.tree.selectionChanged.connect(self.OnItemSelected) self.tree.itemActivated.connect(self.OnItemActivated) self.tree.contextMenu.connect(self.OnContextMenu) wx.CallAfter(self._fetch) self._layout()
def __init__(self, parent, giface, id=wx.ID_ANY, title=_( "Fetch & install extension from GRASS Addons"), **kwargs): self.parent = parent self._giface = giface self.options = dict() # list of options wx.Frame.__init__(self, parent=parent, id=id, title=title, **kwargs) self.SetIcon( wx.Icon( os.path.join( globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO)) self.panel = wx.Panel(parent=self, id=wx.ID_ANY) self.repoBox = wx.StaticBox( parent=self.panel, id=wx.ID_ANY, label=" %s " % _("Repository (leave empty to use the official one)")) self.treeBox = wx.StaticBox( parent=self.panel, id=wx.ID_ANY, label=" %s " % _("List of extensions - double-click to install")) self.repo = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY) # modelBuilder loads data into tree model self.modelBuilder = ExtensionTreeModelBuilder() # tree view displays model data self.tree = CTreeView( parent=self.panel, model=self.modelBuilder.GetModel()) self.search = SearchModuleWidget( parent=self.panel, model=self.modelBuilder.GetModel(), showChoice=False) self.search.showSearchResult.connect( lambda result: self.tree.Select(result)) # show text in statusbar when notification appears self.search.showNotification.connect( lambda message: self.SetStatusText(message)) # load data in different thread self.thread = gThread() self.optionBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY, label=" %s " % _("Options")) task = gtask.parse_interface('g.extension') ignoreFlags = ['l', 'c', 'g', 'a', 'f', 't', 'help', 'quiet'] if sys.platform == 'win32': ignoreFlags.append('d') ignoreFlags.append('i') for f in task.get_options()['flags']: name = f.get('name', '') desc = f.get('label', '') if not desc: desc = f.get('description', '') if not name and not desc: continue if name in ignoreFlags: continue self.options[name] = wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=desc) defaultUrl = '' # default/official one will be used when option empty self.repo.SetValue( task.get_param( value='url').get( 'default', defaultUrl)) self.statusbar = self.CreateStatusBar(number=1) self.btnFetch = wx.Button(parent=self.panel, id=wx.ID_ANY, label=_("&Fetch")) self.btnFetch.SetToolTipString(_("Fetch list of available modules " "from GRASS Addons SVN repository")) self.btnClose = wx.Button(parent=self.panel, id=wx.ID_CLOSE) self.btnInstall = wx.Button(parent=self.panel, id=wx.ID_ANY, label=_("&Install")) self.btnInstall.SetToolTipString( _("Install selected add-ons GRASS module")) self.btnInstall.Enable(False) self.btnHelp = wx.Button(parent=self.panel, id=wx.ID_HELP) self.btnHelp.SetToolTipString(_("Show g.extension manual page")) self.btnClose.Bind(wx.EVT_BUTTON, lambda evt: self.Close()) self.btnFetch.Bind(wx.EVT_BUTTON, self.OnFetch) self.btnInstall.Bind(wx.EVT_BUTTON, self.OnInstall) self.btnHelp.Bind(wx.EVT_BUTTON, self.OnHelp) self.tree.selectionChanged.connect(self.OnItemSelected) self.tree.itemActivated.connect(self.OnItemActivated) self.tree.contextMenu.connect(self.OnContextMenu) wx.CallAfter(self._fetch) self._layout()
def OnChar(self, event): """Key char capture for autocompletion, calltips, and command history .. todo:: event.ControlDown() for manual autocomplete """ # keycodes used: "." = 46, "=" = 61, "-" = 45 pos = self.GetCurrentPos() # complete command after pressing '.' if event.GetKeyCode() == 46: self.autoCompList = list() entry = self.GetTextLeft() self.InsertText(pos, '.') self.CharRight() self.toComplete = self.EntityToComplete() try: if self.toComplete['entity'] == 'command': for command in globalvar.grassCmd: try: if command.find(self.toComplete['cmd']) == 0: dotNumber = list(self.toComplete['cmd']).count('.') self.autoCompList.append(command.split('.',dotNumber)[-1]) except UnicodeDecodeError as e: # TODO: fix it sys.stderr.write(DecodeString(command) + ": " + unicode(e)) except (KeyError, TypeError): return self.ShowList() # complete flags after pressing '-' elif (event.GetKeyCode() == 45) \ or event.GetKeyCode() == wx.WXK_NUMPAD_SUBTRACT \ or event.GetKeyCode() == wx.WXK_SUBTRACT: self.autoCompList = list() entry = self.GetTextLeft() self.InsertText(pos, '-') self.CharRight() self.toComplete = self.EntityToComplete() if self.toComplete['entity'] == 'flags' and self.cmdDesc: if self.GetTextLeft()[-2:] == ' -': # complete e.g. --quite for flag in self.cmdDesc.get_options()['flags']: if len(flag['name']) == 1: self.autoCompList.append(flag['name']) else: for flag in self.cmdDesc.get_options()['flags']: if len(flag['name']) > 1: self.autoCompList.append(flag['name']) self.ShowList() # complete map or values after parameter elif event.GetKeyCode() == 61: self.autoCompList = list() self.InsertText(pos, '=') self.CharRight() self.toComplete = self.EntityToComplete() if self.toComplete['entity'] == 'raster map': self.autoCompList = self.mapList['raster'] elif self.toComplete['entity'] == 'vector map': self.autoCompList = self.mapList['vector'] elif self.toComplete['entity'] == 'param values': param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =') self.autoCompList = self.cmdDesc.get_param(param)['values'] self.ShowList() # complete mapset ('@') elif event.GetKeyCode() == 64: self.autoCompList = list() self.InsertText(pos, '@') self.CharRight() self.toComplete = self.EntityToComplete() if self.toComplete['entity'] == 'mapsets': self.autoCompList = self.mapsetList self.ShowList() # complete after pressing CTRL + Space elif event.GetKeyCode() == wx.WXK_SPACE and event.ControlDown(): self.autoCompList = list() self.toComplete = self.EntityToComplete() #complete command if self.toComplete['entity'] == 'command': for command in globalvar.grassCmd: if command.find(self.toComplete['cmd']) == 0: dotNumber = list(self.toComplete['cmd']).count('.') self.autoCompList.append(command.split('.',dotNumber)[-1]) # complete flags in such situations (| is cursor): # r.colors -| ...w, q, l # r.colors -w| ...w, q, l elif self.toComplete['entity'] == 'flags' and self.cmdDesc: for flag in self.cmdDesc.get_options()['flags']: if len(flag['name']) == 1: self.autoCompList.append(flag['name']) # complete parameters in such situations (| is cursor): # r.colors -w | ...color, map, rast, rules # r.colors col| ...color elif self.toComplete['entity'] == 'params' and self.cmdDesc: for param in self.cmdDesc.get_options()['params']: if param['name'].find(self.GetWordLeft(withDelimiter=False)) == 0: self.autoCompList.append(param['name']) # complete flags or parameters in such situations (| is cursor): # r.colors | ...-w, -q, -l, color, map, rast, rules # r.colors color=grey | ...-w, -q, -l, color, map, rast, rules elif self.toComplete['entity'] == 'params+flags' and self.cmdDesc: self.autoCompList = list() for param in self.cmdDesc.get_options()['params']: self.autoCompList.append(param['name']) for flag in self.cmdDesc.get_options()['flags']: if len(flag['name']) == 1: self.autoCompList.append('-' + flag['name']) else: self.autoCompList.append('--' + flag['name']) self.ShowList() # complete map or values after parameter # r.buffer input=| ...list of raster maps # r.buffer units=| ... feet, kilometers, ... elif self.toComplete['entity'] == 'raster map': self.autoCompList = list() self.autoCompList = self.mapList['raster'] elif self.toComplete['entity'] == 'vector map': self.autoCompList = list() self.autoCompList = self.mapList['vector'] elif self.toComplete['entity'] == 'param values': self.autoCompList = list() param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =') self.autoCompList = self.cmdDesc.get_param(param)['values'] self.ShowList() elif event.GetKeyCode() == wx.WXK_SPACE: items = self.GetTextLeft().split() if len(items) == 1: cmd = items[0].strip() if cmd in globalvar.grassCmd and \ (not self.cmdDesc or cmd != self.cmdDesc.get_name()): try: self.cmdDesc = gtask.parse_interface(cmd) except IOError: self.cmdDesc = None event.Skip() else: event.Skip()
def RunCmd(self, command, compReg=True, env=None, skipInterface=False, onDone=None, onPrepare=None, userData=None, addLayer=None, notification=Notification.MAKE_VISIBLE): """Run command typed into console command prompt (GPrompt). .. todo:: Document the other event. .. todo:: Solve problem with the other event (now uses gOutputText event but there is no text, use onPrepare handler instead?) .. todo:: Skip interface is ignored and determined always automatically. Posts event EVT_IGNORED_CMD_RUN when command which should be ignored (according to ignoredCmdPattern) is run. For example, see layer manager which handles d.* on its own. :param command: command given as a list (produced e.g. by utils.split()) :param compReg: True use computation region :param notification: form of notification :param bool skipInterface: True to do not launch GRASS interface parser when command has no arguments given :param onDone: function to be called when command is finished :param onPrepare: function to be called before command is launched :param addLayer: to be passed in the mapCreated signal :param userData: data defined for the command """ if len(command) == 0: Debug.msg(2, "GPrompt:RunCmd(): empty command") return # update history file self.UpdateHistoryFile(' '.join(command)) if command[0] in globalvar.grassCmd: # send GRASS command without arguments to GUI command interface # except ignored commands (event is emitted) if self._ignoredCmdPattern and \ re.compile(self._ignoredCmdPattern).search(' '.join(command)) and \ '--help' not in command and '--ui' not in command: event = gIgnoredCmdRun(cmd=command) wx.PostEvent(self, event) return else: # other GRASS commands (r|v|g|...) try: task = GUI(show=None).ParseCommand(command) except GException as e: GError(parent=self._guiparent, message=unicode(e), showTraceback=False) return hasParams = False if task: options = task.get_options() hasParams = options['params'] and options['flags'] # check for <input>=- for p in options['params']: if p.get('prompt', '') == 'input' and \ p.get('element', '') == 'file' and \ p.get('age', 'new') == 'old' and \ p.get('value', '') == '-': GError( parent=self._guiparent, message=_( "Unable to run command:\n%(cmd)s\n\n" "Option <%(opt)s>: read from standard input is not " "supported by wxGUI") % { 'cmd': ' '.join(command), 'opt': p.get( 'name', '')}) return if len(command) == 1: if command[0].startswith('g.gui.'): import imp import inspect pyFile = command[0] if sys.platform == 'win32': pyFile += '.py' pyPath = os.path.join( os.environ['GISBASE'], 'scripts', pyFile) if not os.path.exists(pyPath): pyPath = os.path.join( os.environ['GRASS_ADDON_BASE'], 'scripts', pyFile) if not os.path.exists(pyPath): GError( parent=self._guiparent, message=_("Module <%s> not found.") % command[0]) pymodule = imp.load_source( command[0].replace('.', '_'), pyPath) pymain = inspect.getargspec(pymodule.main) if pymain and 'giface' in pymain.args: pymodule.main(self._giface) return # no arguments given if hasParams and \ not isinstance(self._guiparent, FormNotebook): # also parent must be checked, see #3135 for details try: GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command) except GException as e: print >> sys.stderr, e return if env: env = env.copy() else: env = os.environ.copy() # activate computational region (set with g.region) # for all non-display commands. if compReg and "GRASS_REGION" in env: del env["GRASS_REGION"] # process GRASS command with argument self.cmdThread.RunCmd(command, stdout=self.cmdStdOut, stderr=self.cmdStdErr, onDone=onDone, onPrepare=onPrepare, userData=userData, addLayer=addLayer, env=env, notification=notification) self.cmdOutputTimer.Start(50) # we don't need to change computational region settings # because we work on a copy else: # Send any other command to the shell. Send output to # console output window # # Check if the script has an interface (avoid double-launching # of the script) # check if we ignore the command (similar to grass commands part) if self._ignoredCmdPattern and \ re.compile(self._ignoredCmdPattern).search(' '.join(command)): event = gIgnoredCmdRun(cmd=command) wx.PostEvent(self, event) return skipInterface = True if os.path.splitext(command[0])[1] in ('.py', '.sh'): try: sfile = open(command[0], "r") for line in sfile.readlines(): if len(line) < 2: continue if line[0] is '#' and line[1] is '%': skipInterface = False break sfile.close() except IOError: pass if len(command) == 1 and not skipInterface: try: task = gtask.parse_interface(command[0]) except: task = None else: task = None if task: # process GRASS command without argument GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command) else: self.cmdThread.RunCmd(command, stdout=self.cmdStdOut, stderr=self.cmdStdErr, onDone=onDone, onPrepare=onPrepare, userData=userData, addLayer=addLayer, env=env, notification=notification) self.cmdOutputTimer.Start(50)