Skip to content

Commit

Permalink
Move algorithm id (previously commandLineName) to QgsProcessingAlgorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
nyalldawson committed Apr 7, 2017
1 parent 950ed68 commit 2a1a715
Show file tree
Hide file tree
Showing 22 changed files with 66 additions and 70 deletions.
8 changes: 8 additions & 0 deletions python/core/processing/qgsprocessingalgorithm.sip
Expand Up @@ -51,6 +51,14 @@ class QgsProcessingAlgorithm
\see tags()
%End

QString id() const;
%Docstring
Returns the unique ID for the algorithm, which is a combination of the algorithm
provider's ID and the algorithms unique name (e.g. "qgis:mergelayers" ).
\see name()
\see provider()
%End

virtual QString displayName() const = 0;
%Docstring
Returns the translated algorithm name, which should be used for any user-visible display
Expand Down
5 changes: 1 addition & 4 deletions python/plugins/processing/algs/gdal/GridAverage.py
Expand Up @@ -57,17 +57,14 @@ class GridAverage(GdalAlgorithm):
TYPE = ['Byte', 'Int16', 'UInt16', 'UInt32', 'Int32', 'Float32', 'Float64']

def name(self):
return 'gridmovingaverage'
return 'gridaverage'

def displayName(self):
return self.tr('Grid (Moving average)')

def icon(self):
return QIcon(os.path.join(pluginPath, 'images', 'gdaltools', 'grid.png'))

def commandLineName(self):
return "gdal:gridaverage"

def group(self):
return self.tr('Raster analysis')

Expand Down
3 changes: 0 additions & 3 deletions python/plugins/processing/algs/gdal/GridDataMetrics.py
Expand Up @@ -70,9 +70,6 @@ def displayName(self):
def icon(self):
return QIcon(os.path.join(pluginPath, 'images', 'gdaltools', 'grid.png'))

def commandLineName(self):
return "gdal:griddatametrics"

def group(self):
return self.tr('Raster analysis')

Expand Down
5 changes: 1 addition & 4 deletions python/plugins/processing/algs/grass7/Grass7Algorithm.py
Expand Up @@ -90,7 +90,7 @@ def __init__(self, descriptionfile):
self.uniqueSuffix = str(uuid.uuid4()).replace('-', '')

# Use the ext mechanism
name = self.commandLineName().replace('.', '_')[len('grass7:'):]
name = self.name().replace('.', '_')
try:
self.module = importlib.import_module('processing.algs.grass7.ext.' + name)
except ImportError:
Expand Down Expand Up @@ -574,9 +574,6 @@ def exportRasterLayer(self, layer):
def getTempFilename(self):
return system.getTempFilename()

def commandLineName(self):
return 'grass7:' + self.name()

def checkBeforeOpeningParametersDialog(self):
return Grass7Utils.checkGrass7IsInstalled()

Expand Down
17 changes: 2 additions & 15 deletions python/plugins/processing/algs/saga/SagaAlgorithm.py
Expand Up @@ -108,10 +108,6 @@ def defineCharacteristicsFromFile(self):
else:
self.cmdname = self._name
self._display_name = QCoreApplication.translate("SAGAAlgorithm", str(self._name))
# _commandLineName is the name used in processing to call the algorithm
# Most of the time will be equal to the cmdname, but in same cases, several processing algorithms
# call the same SAGA one
self._commandLineName = self.createCommandLineName(self._name)
self._name = decoratedAlgorithmName(self._name)
self._display_name = QCoreApplication.translate("SAGAAlgorithm", str(self._name))

Expand Down Expand Up @@ -289,7 +285,7 @@ def processAlgorithm(self, feedback):
f.write(self.crs.toWkt())

def preProcessInputs(self):
name = self.commandLineName().replace('.', '_')[len('saga:'):]
name = self.name().replace('.', '_')
try:
module = importlib.import_module('processing.algs.saga.ext.' + name)
except ImportError:
Expand All @@ -299,9 +295,8 @@ def preProcessInputs(self):
func(self)

def editCommands(self, commands):
name = self.commandLineName()[len('saga:'):]
try:
module = importlib.import_module('processing.algs.saga.ext.' + name)
module = importlib.import_module('processing.algs.saga.ext.' + self.name())
except ImportError:
return commands
if hasattr(module, 'editCommands'):
Expand Down Expand Up @@ -373,11 +368,3 @@ def checkParameterValuesBeforeExecuting(self):
extent2 = (layer.extent(), layer.height(), layer.width())
if extent != extent2:
return self.tr("Input layers do not have the same grid extent.")

def createCommandLineName(self, name):
validChars = \
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:'
return 'saga:' + ''.join(c for c in name if c in validChars).lower()

def commandLineName(self):
return self._commandLineName
7 changes: 2 additions & 5 deletions python/plugins/processing/core/GeoAlgorithm.py
Expand Up @@ -93,7 +93,7 @@ def help(self):
return False, None

def shortHelp(self):
text = shortHelp.get(self.commandLineName(), None)
text = shortHelp.get(self.id(), None)
if text is not None:
text = self._formatHelp(text)
return text
Expand Down Expand Up @@ -461,9 +461,6 @@ def __str__(self):
s += '\n'
return s

def commandLineName(self):
return self.provider().id().lower() + ':' + self.name()

def removeOutputFromName(self, name):
for out in self.outputs:
if out.name == name:
Expand Down Expand Up @@ -499,7 +496,7 @@ def getAsCommand(self):
console.
"""

s = 'processing.run("' + self.commandLineName() + '",'
s = 'processing.run("' + self.id() + '",'
for param in self.parameters:
s += param.getValueAsCommandLineParameter() + ','
for out in self.outputs:
Expand Down
4 changes: 2 additions & 2 deletions python/plugins/processing/core/alglist.py
Expand Up @@ -47,13 +47,13 @@ def reloadProvider(self, provider_id):
for p in QgsApplication.processingRegistry().providers():
if p.id() == provider_id:
p.refreshAlgorithms()
self.algs[p.id()] = {a.commandLineName(): a for a in p.algorithms()}
self.algs[p.id()] = {a.id(): a for a in p.algorithms()}
self.providerUpdated.emit(p.id())
break

def addProvider(self, provider):
if QgsApplication.processingRegistry().addProvider(provider):
self.algs[provider.id()] = {a.commandLineName(): a for a in provider.algorithms()}
self.algs[provider.id()] = {a.id(): a for a in provider.algorithms()}

def getAlgorithm(self, name):
for provider in list(self.algs.values()):
Expand Down
10 changes: 5 additions & 5 deletions python/plugins/processing/gui/ConfigDialog.py
Expand Up @@ -236,9 +236,9 @@ def fillTreeUsingProviders(self):
algItem.setIcon(icon)
algItem.setEditable(False)
try:
settingMenu = ProcessingConfig.settings["MENU_" + alg.commandLineName()]
settingButton = ProcessingConfig.settings["BUTTON_" + alg.commandLineName()]
settingIcon = ProcessingConfig.settings["ICON_" + alg.commandLineName()]
settingMenu = ProcessingConfig.settings["MENU_" + alg.id()]
settingButton = ProcessingConfig.settings["BUTTON_" + alg.id()]
settingIcon = ProcessingConfig.settings["ICON_" + alg.id()]
except:
continue
self.items[settingMenu] = SettingItem(settingMenu)
Expand Down Expand Up @@ -269,8 +269,8 @@ def resetMenusToDefaults(self):
providers = Processing.providers
for provider in providers:
for alg in provider.algorithms():
d = defaultMenuEntries.get(alg.commandLineName(), "")
setting = ProcessingConfig.settings["MENU_" + alg.commandLineName()]
d = defaultMenuEntries.get(alg.id(), "")
setting = ProcessingConfig.settings["MENU_" + alg.id()]
item = self.items[setting]
item.setData(d, Qt.EditRole)
self.saveMenus = True
Expand Down
4 changes: 2 additions & 2 deletions python/plugins/processing/gui/EditRenderingStylesDialog.py
Expand Up @@ -75,7 +75,7 @@ def setTableContent(self):
self.tblStyles.setItem(i, 0, item)
item = RenderingStyleFilePanel()
style = \
RenderingStyles.getStyle(self.alg.commandLineName(),
RenderingStyles.getStyle(self.alg.id(),
output.name)
if style:
item.setText(str(style))
Expand All @@ -88,7 +88,7 @@ def accept(self):
styles = {}
for key in list(self.valueItems.keys()):
styles[key] = str(self.valueItems[key].getValue())
RenderingStyles.addAlgStylesAndSave(self.alg.commandLineName(), styles)
RenderingStyles.addAlgStylesAndSave(self.alg.id(), styles)

QDialog.accept(self)

Expand Down
2 changes: 1 addition & 1 deletion python/plugins/processing/gui/Postprocessing.py
Expand Up @@ -70,7 +70,7 @@ def handleAlgorithmResults(alg, feedback=None, showResults=True):
else:
name = out.description
dataobjects.load(out.value, name, alg.crs,
RenderingStyles.getStyle(alg.commandLineName(),
RenderingStyles.getStyle(alg.id(),
out.name))
except Exception:
ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
Expand Down
8 changes: 4 additions & 4 deletions python/plugins/processing/gui/ProcessingToolbox.py
Expand Up @@ -141,7 +141,7 @@ def _filterItem(self, item, text):
# hide if every part of text is not contained somewhere in either the item text or item user role
item_text = [item.text(0).lower(), item.data(0, Qt.UserRole).lower()]
if isinstance(item, TreeAlgorithmItem):
item_text.append(item.alg.commandLineName())
item_text.append(item.alg.id())
item_text.extend(item.data(0, Qt.UserRole + 1))

hide = bool(text) and not all(
Expand Down Expand Up @@ -227,14 +227,14 @@ def showPopupMenu(self, point):
def editRenderingStyles(self):
item = self.algorithmTree.currentItem()
if isinstance(item, TreeAlgorithmItem):
alg = Processing.getAlgorithm(item.alg.commandLineName())
alg = Processing.getAlgorithm(item.alg.id())
dlg = EditRenderingStylesDialog(alg)
dlg.exec_()

def executeAlgorithmAsBatchProcess(self):
item = self.algorithmTree.currentItem()
if isinstance(item, TreeAlgorithmItem):
alg = Processing.getAlgorithm(item.alg.commandLineName())
alg = Processing.getAlgorithm(item.alg.id())
alg = alg.getCopy()
dlg = BatchAlgorithmDialog(alg)
dlg.show()
Expand All @@ -243,7 +243,7 @@ def executeAlgorithmAsBatchProcess(self):
def executeAlgorithm(self):
item = self.algorithmTree.currentItem()
if isinstance(item, TreeAlgorithmItem):
alg = Processing.getAlgorithm(item.alg.commandLineName())
alg = Processing.getAlgorithm(item.alg.id())
message = alg.checkBeforeOpeningParametersDialog()
if message:
dlg = MessageDialog()
Expand Down
18 changes: 9 additions & 9 deletions python/plugins/processing/gui/menus.py
Expand Up @@ -114,14 +114,14 @@
def initializeMenus():
for provider in QgsApplication.processingRegistry().providers():
for alg in provider.algorithms():
d = defaultMenuEntries.get(alg.commandLineName(), "")
setting = Setting(menusSettingsGroup, "MENU_" + alg.commandLineName(),
d = defaultMenuEntries.get(alg.id(), "")
setting = Setting(menusSettingsGroup, "MENU_" + alg.id(),
"Menu path", d)
ProcessingConfig.addSetting(setting)
setting = Setting(menusSettingsGroup, "BUTTON_" + alg.commandLineName(),
setting = Setting(menusSettingsGroup, "BUTTON_" + alg.id(),
"Add button", False)
ProcessingConfig.addSetting(setting)
setting = Setting(menusSettingsGroup, "ICON_" + alg.commandLineName(),
setting = Setting(menusSettingsGroup, "ICON_" + alg.id(),
"Icon", "", valuetype=Setting.FILE)
ProcessingConfig.addSetting(setting)

Expand All @@ -137,9 +137,9 @@ def updateMenus():
def createMenus():
for provider in list(algList.algs.values()):
for alg in list(provider.values()):
menuPath = ProcessingConfig.getSetting("MENU_" + alg.commandLineName())
addButton = ProcessingConfig.getSetting("BUTTON_" + alg.commandLineName())
icon = ProcessingConfig.getSetting("ICON_" + alg.commandLineName())
menuPath = ProcessingConfig.getSetting("MENU_" + alg.id())
addButton = ProcessingConfig.getSetting("BUTTON_" + alg.id())
icon = ProcessingConfig.getSetting("ICON_" + alg.id())
if icon and os.path.exists(icon):
icon = QIcon(icon)
else:
Expand All @@ -152,7 +152,7 @@ def createMenus():
def removeMenus():
for provider in list(algList.algs.values()):
for alg in list(provider.values()):
menuPath = ProcessingConfig.getSetting("MENU_" + alg.commandLineName())
menuPath = ProcessingConfig.getSetting("MENU_" + alg.id())
if menuPath:
paths = menuPath.split("/")
removeAlgorithmEntry(alg, paths[0], paths[-1])
Expand All @@ -161,7 +161,7 @@ def removeMenus():
def addAlgorithmEntry(alg, menuName, submenuName, actionText=None, icon=None, addButton=False):
action = QAction(icon or alg.icon(), actionText or alg.displayName(), iface.mainWindow())
action.triggered.connect(lambda: _executeAlgorithm(alg))
action.setObjectName("mProcessingUserMenu_%s" % alg.commandLineName())
action.setObjectName("mProcessingUserMenu_%s" % alg.id())

if menuName:
menu = getMenu(menuName, iface.mainWindow().menuBar())
Expand Down
6 changes: 0 additions & 6 deletions python/plugins/processing/modeler/ModelerAlgorithm.py
Expand Up @@ -541,12 +541,6 @@ def getAsCommand(self):
else:
return None

def commandLineName(self):
if self.descriptionFile is None:
return ''
else:
return 'modeler:' + os.path.basename(self.descriptionFile)[:-6].lower()

def checkBeforeOpeningParametersDialog(self):
for alg in list(self.algs.values()):
algInstance = algList.getAlgorithm(alg.consoleName)
Expand Down
6 changes: 3 additions & 3 deletions python/plugins/processing/modeler/ModelerDialog.py
Expand Up @@ -186,7 +186,7 @@ def _mimeDataAlgorithm(items):
item = items[0]
if isinstance(item, TreeAlgorithmItem):
mimeData = QMimeData()
mimeData.setText(item.alg.commandLineName())
mimeData.setText(item.alg.id())
return mimeData

self.algorithmTree.mimeData = _mimeDataAlgorithm
Expand Down Expand Up @@ -549,7 +549,7 @@ def fillInputsTree(self):
def addAlgorithm(self):
item = self.algorithmTree.currentItem()
if isinstance(item, TreeAlgorithmItem):
alg = algList.getAlgorithm(item.alg.commandLineName())
alg = algList.getAlgorithm(item.alg.id())
self._addAlgorithm(alg.getCopy())

def _addAlgorithm(self, alg, pos=None):
Expand Down Expand Up @@ -611,7 +611,7 @@ def fillAlgorithmTreeUsingProviders(self):
for alg in algs:
if alg.flags() & QgsProcessingAlgorithm.FlagHideFromModeler:
continue
if alg.commandLineName() == self.alg.commandLineName():
if alg.id() == self.alg.id():
continue

item_text = [alg.displayName().lower()]
Expand Down
Expand Up @@ -321,7 +321,7 @@ def setPreviousValues(self):
self.dependenciesPanel.setSelectedItems(selected)

def createAlgorithm(self):
alg = Algorithm(self._alg.commandLineName())
alg = Algorithm(self._alg.id())
alg.setName(self.model)
alg.description = self.descriptionBox.text()
params = self._alg.parameters
Expand Down
Expand Up @@ -63,7 +63,7 @@ def getCopy(self):
return newone

def defineCharacteristics(self):
self.name = self.description["name"]
self._name = self.description["name"]
self._group = self.description["group"]

def execute(self, feedback):
Expand Down
Expand Up @@ -35,4 +35,4 @@ def algAsDict(alg):
outputs = {}
for out in alg.outputs:
outputs[out.name] = out.value
return {"parameters": params, "outputs": outputs, "algname": alg.commandLineName()}
return {"parameters": params, "outputs": outputs, "algname": alg.id()}
4 changes: 2 additions & 2 deletions python/plugins/processing/tools/general.py
Expand Up @@ -51,7 +51,7 @@ def algorithmsList(text=None):
sortedlist = sorted(list(provider.values()), key=lambda alg: alg.name())
for alg in sortedlist:
if text is None or text.lower() in alg.name().lower():
lst.append(alg.commandLineName())
lst.append(alg.id())
return lst


Expand All @@ -66,7 +66,7 @@ def printAlgorithms(text=None):
sortedlist = sorted(list(provider.values()), key=lambda alg: alg.name())
for alg in sortedlist:
if text is None or text.lower() in alg.name().lower():
s += '{}--->{}\n'.format(alg.name().ljust(50, '-'), alg.commandLineName())
s += '{}--->{}\n'.format(alg.name().ljust(50, '-'), alg.id())
print(s)


Expand Down
4 changes: 2 additions & 2 deletions python/plugins/processing/tools/help.py
Expand Up @@ -38,7 +38,7 @@ def baseHelpForAlgorithm(alg, folder):
groupName = alg.group().lower()
groupName = groupName.replace('[', '').replace(']', '').replace(' - ', '_')
groupName = groupName.replace(' ', '_')
cmdLineName = alg.commandLineName()
cmdLineName = alg.id()
algName = cmdLineName[cmdLineName.find(':') + 1:].lower()
validChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'
safeGroupName = ''.join(c for c in groupName if c in validChars)
Expand Down Expand Up @@ -89,7 +89,7 @@ def baseHelpForAlgorithm(alg, folder):
f.write('Console usage\n')
f.write('-------------\n')
f.write('\n::\n\n')
cmd = " processing.run('{}', ".format(alg.commandLineName())
cmd = " processing.run('{}', ".format(alg.id())
for p in alg.parameters:
cmd += '{}, '.format(p.name.lower().strip())

Expand Down

0 comments on commit 2a1a715

Please sign in to comment.