def OnKeyPressed(self, event): """Key pressed capture special treatment for tabulator to show help""" pos = self.GetCurrentPos() if 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: 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_RETURN, wx.WXK_NUMPAD_ENTER) and not self.AutoCompActive() ): # run command on line when <return> is pressed self._runCmd(self.GetCurLine()[0].strip()) 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: # without strip causes problem on windows txt = self.cmdbuffer[self.cmdindex].strip() except KeyError: txt = "" # clear current line and insert command history self.DelLineLeft() self.DelLineRight() pos = self.GetCurrentPos() self.InsertText(pos, txt) self.LineEnd() self.ShowStatusText("") else: event.Skip()
def OnKeyPressed(self, event): """Key pressed capture special treatment for tabulator to show help""" pos = self.GetCurrentPos() if 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: 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_RETURN, wx.WXK_NUMPAD_ENTER) and \ not self.AutoCompActive(): # run command on line when <return> is pressed self._runCmd(self.GetCurLine()[0].strip()) 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: # without strip causes problem on windows txt = self.cmdbuffer[self.cmdindex].strip() except KeyError: txt = '' # clear current line and insert command history self.DelLineLeft() self.DelLineRight() pos = self.GetCurrentPos() self.InsertText(pos, txt) self.LineEnd() self.ShowStatusText('') else: event.Skip()
def get_title(self, module): """ create title of main window :param module: called module :return: new title of the window with parameters """ self.title = [p for p in gtask.command_info(module)['keywords']] self.title = re.sub("'", "", module + " " + str(self.title)) return self.title
def get_command_description(command): pd.options.mode.chained_assignment = None b = command.encode('utf-8') commandspecs = gtask.command_info(b) flags = [] for i, v in enumerate(commandspecs['flags']): flags.append(pd.DataFrame.from_dict({0: v}, orient='index')) flags = pd.concat(flags).reset_index() flags.drop('index', 1, inplace=True) flags['guisection'].loc[(flags['guisection'] == '')] = 'Optional' params = [] for i, v in enumerate(commandspecs['params']): params.append(pd.DataFrame.from_dict({0: v}, orient='index')) params = pd.concat(params).reset_index() params.drop('index', 1, inplace=True) params['guisection'].loc[ (params['guisection'] == '') & (params['required'] == False) ] = 'Optional' params['guisection'].loc[ (params['guisection'] == '') | (params['required'] == True) ] = 'Required' guisection = list(params['guisection'].unique()) + \ list(flags['guisection'].unique()) guisection = set(guisection) command_description = {} pr = {} fl = {} for i in guisection: pr[i] = params.loc[(params['guisection'] == i)].reset_index() fl[i] = flags.loc[(flags['guisection'] == i)].reset_index() del pr[i]['index'] del fl[i]['index'] command_description['description'] = commandspecs['description'] command_description['keywords'] = commandspecs['keywords'] command_description['usage'] = commandspecs['usage'] command_description['parameters'] = pr command_description['flags'] = fl command_description['model'] = get_model() return command_description
def get_description(self, module): """ creates description with logo :param module: called module :return: label with module description """ logo = QtGui.QLabel() logo.setPixmap(QtGui.QPixmap(os.path.join(IMGDIR, 'grass_form.png'))) logo.setFixedWidth(logo.sizeHint().width()) text = QtGui.QLabel(gtask.command_info(module)['description']) text.setWordWrap(True) layout = QtGui.QHBoxLayout() layout.addWidget(logo) layout.addWidget(text) layout.setContentsMargins(0, 0, 0, 0) description = QtGui.QWidget() description.setLayout(layout) description.setFixedHeight(description.sizeHint().height()) return description
def module_has_parameter(module, parameter): from grass.script import task as gtask task = gtask.command_info(module) return parameter in [each['name'] for each in task['params']]
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()
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 get_tabs(self, module): """ parse individual widgets, create tabs and put widgets into those tabs :param module: called module :return: tabs, code_string (widget with code string that user can see) """ tabs = QtGui.QTabWidget() page_required = QtGui.QWidget() box_required = QtGui.QVBoxLayout() boxs = {} page_optional = QtGui.QWidget() box_optional = QtGui.QVBoxLayout() pages = {} page_section = {} boxs_section = {} self.codeDict = {} self.flagList = [] code_string = QtGui.QTextEdit(module) code_string.setLineWrapMode(QtGui.QTextEdit.NoWrap) code_string.setReadOnly(True) code_string.setFixedHeight(QtGui.QLineEdit().sizeHint().height()*2) fact = Factory() # tabs for params for task in gtask.command_info(module)['params']: widget = newWidget(task, module, self.codeDict, self.flagList, code_string, fact).new_widget() if task['guisection']: try: page_section[task['guisection']] except: page = QtGui.QWidget() box = QtGui.QVBoxLayout() page_section.update({task['guisection']: page}) boxs_section.update({task['guisection']: box}) pages.update({task['guisection']: page_section[task['guisection']]}) boxs.update({task['guisection']: boxs_section[task['guisection']]}) boxs[task['guisection']].addWidget(widget) elif task['required'] is True: try: pages.update({'Required': page_required}) boxs.update({'Required': box_required}) except: pass boxs['Required'].addWidget(widget) else: try: pages.update({'Optional': page_optional}) boxs.update({'Optional': box_optional}) except: pass boxs['Optional'].addWidget(widget) # tabs for flags for task in gtask.command_info(module)['flags']: widget = newWidget(task, module, self.codeDict, self.flagList, code_string, fact).new_widget() if task['guisection']: try: page_section[task['guisection']] except: page = QtGui.QWidget() box = QtGui.QVBoxLayout() page_section.update({task['guisection']: page}) boxs_section.update({task['guisection']: box}) pages.update({task['guisection']: page_section[task['guisection']]}) boxs.update({task['guisection']: boxs_section[task['guisection']]}) boxs[task['guisection']].addWidget(widget) else: try: pages.update({'Optional': page_optional}) boxs.update({'Optional': box_optional}) except: pass if not task['name'] == 'help': boxs['Optional'].addWidget(widget) # we don't have to see help everywhere for i in pages: boxs[i].addStretch() layout = boxs[i] layout.setSpacing(0) widget = QtGui.QWidget() widget.setLayout(layout) a = QtGui.QScrollArea() palette = a.palette() palette.setColor( a.backgroundRole(), QtGui.QLineEdit().palette().color(QtGui.QLineEdit(). backgroundRole())) a.setPalette(palette) a.setWidget(widget) a.setWidgetResizable(True) a.setFrameShape(QtGui.QFrame.NoFrame) a.setAutoFillBackground(True) a.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) a.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) new_layout = QtGui.QVBoxLayout() new_layout.addWidget(a) new_layout.setContentsMargins(1, 1, 1, 1) pages[i].setLayout(new_layout) if box_required: tabs.addTab(page_required, 'Required') for i in page_section: tabs.addTab(pages[i], i) tabs.addTab(page_optional, 'Optional') return tabs, code_string
# add grass environment before run this from grass.script import task as gtask module = 'g.list' commandspecs = gtask.command_info(module) ''' command keys: dict_keys(['description', 'keywords', 'flags', 'params', 'usage']) param: dict_keys(['name', 'type', 'required', 'multiple', 'label', 'description', 'gisprompt', 'age', 'element', 'prompt', 'guisection', 'guidependency', 'default', 'values', 'values_desc', 'value', 'key_desc', 'hidden']) flags: dict_keys(['name', 'label', 'description', 'guisection', 'suppress_required', 'value', 'hidden']) '''
def module_has_parameter(module, parameter): task = gtask.command_info(module) return parameter in [each["name"] for each in task["params"]]
def init(self): self.w = MainGui() # self.prompts = [] self.datasurcesprompts = [] self.filesprompts = [] self.gflags = [] self.goptionsstring = [] self.goptionsmultistring = [] self.goptionsnum = [] self.goptionstext = [] # self.parameters = [] self.datasurceprompt = [] self.fileprompt = [] self.flags = [] self.stringoption = [] self.multistringoption = [] self.numoption = [] self.textoption = [] # self.commandname = 'r.in.gdal' # self.message = '' gsec = gcommand(self.commandname) commandspecs = gtask.command_info(self.commandname) self.w.commanddescription.setText(commandspecs['description']) self.w.commanddescription.setWordWrap(True) keywords = ', '.join(gsec['keywords']) title = str(self.commandname) + " [" + keywords + ']' #title = str(self.commandname)+" "+str(gsec['keywords']) self.w.setWindowTitle(title) for i in gsec['parameters'].keys(): tab = QtWidgets.QScrollArea() tab.setWidget(QtWidgets.QWidget()) fl = QtWidgets.QVBoxLayout(tab.widget()) tab.setWidgetResizable(True) tab.setObjectName(i) self.w.commandtab.addTab(tab, i) for j in gsec['flags'][i].index.values: flag = gsec['flags'][i].iloc[j] gflag = GisOptionFlag(fl, self.flags, flag) self.gflags.append(gflag) for j in gsec['parameters'][i].index.values: command = gsec['parameters'][i].iloc[j] if command['gisprompt']: # and command['age'] == 'old': if command['prompt'] in [ 'raster', 'raster_3d', 'vector', 'label', 'region', 'group', 'all' ]: print(command['prompt']) fileopen = GisOptionPrompt(fl, self.parameters, command) fileopen.setObjectName("fileopen_%s" % i) self.prompts.append(fileopen) # TODO: handle here the datasource prompt # # if command['gisprompt'] and command['prompt'] == 'datasource': # fileopen = GisOptionDataSourcePrompt(fl, self.datasurceprompt, command) # fileopen.setObjectName("fileopen_%s" % i) # self.datasurcesprompts.append(fileopen) # TODO: handle here the file prompt # if command['gisprompt'] and command['prompt'] == 'file': fileopen = GisOptionFilePrompt(fl, self.fileprompt, command) fileopen.setObjectName("fileopen_%s" % i) self.filesprompts.append(fileopen) #for j in gsec['parameters'][i].index.values: # command = gsec['parameters'][i].iloc[j] if command['type'] == 'string' and command[ 'values'] != [] and not command['multiple']: opt = GisOptionString(fl, self.stringoption, command) opt.setObjectName("opt_%s" % i) self.goptionsstring.append(opt) # TODO: handle multicheckbox here if command['type'] == 'string' and command[ 'values'] != [] and command['multiple']: opt = GisOptionMultiString(fl, self.multistringoption, command) opt.setObjectName("opt_%s" % i) self.goptionsmultistring.append(opt) #for j in gsec['parameters'][i].index.values: # command = gsec['parameters'][i].iloc[j] if command['type'] == 'integer' or command[ 'type'] == 'float' and not command['multiple']: opt = GisOptionNum(fl, self.numoption, command) opt.setObjectName("opt_%s" % i) self.goptionsnum.append(opt) if command['type'] == 'integer' or command[ 'type'] == 'float' and command['multiple']: opt = GisOptionText(fl, self.textoption, command) opt.setObjectName("opt_%s" % i) self.goptionstext.append(opt) spacerItem4 = QtWidgets.QSpacerItem( 20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) fl.addItem(spacerItem4) doclink = os.path.join(GISBASE, 'docs/html', self.commandname) self.w.manualpage.load(QUrl('file://%s.html' % doclink)) #self.w.runcommand.clicked.connect(self.getParam) self.w.copycommand.clicked.connect(self.messagecopy) self.w.closecommand.clicked.connect(self.w.close) for i in self.gflags: i.valueUpdated.connect(self.handleValueUpdated) for i in self.goptionsstring: i.valueUpdated.connect(self.handleValueUpdated) for i in self.goptionsmultistring: i.valueUpdated.connect(self.handleValueUpdated) for i in self.goptionstext: i.valueUpdated.connect(self.handleValueUpdated) for i in self.goptionsnum: i.valueUpdated.connect(self.handleValueUpdated) for i in self.prompts: i.valueUpdated.connect(self.handleValueUpdated) for i in self.filesprompts: i.valueUpdated.connect(self.handleValueUpdated) self.status = {} self.status['flags'] = [] for i in range(self.w.commandtab.count()): #print(i, self.w.commandtab.widget(i).objectName()) if self.w.commandtab.widget(i).objectName() == 'Required': self.w.commandtab.tabBar().moveTab(i, 0) if self.w.commandtab.widget(i).objectName() == 'CommandOutput': self.w.commandtab.tabBar().moveTab( i, self.w.commandtab.count() - 2) if self.w.commandtab.widget(i).objectName() == 'Manual': self.w.commandtab.tabBar().moveTab( i, self.w.commandtab.count() - 1) print(self.w.commandtab.count()) self.w.commandtab.setCurrentIndex(0) self.w.show()