1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
|
# -*- coding: utf-8 -*-
"""
***************************************************************************
EditScriptDialog.py
---------------------
Date : December 2012
Copyright : (C) 2012 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Alexander Bruy'
__date__ = 'December 2012'
__copyright__ = '(C) 2012, Alexander Bruy'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import codecs
import sys
import json
import os
from qgis.PyQt import uic
from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtGui import QIcon, QCursor
from qgis.PyQt.QtWidgets import QMenu, QAction, QMessageBox, QFileDialog, QApplication
from qgis.core import QgsApplication
from qgis.utils import iface
from processing.core.alglist import algList
from processing.gui.AlgorithmDialog import AlgorithmDialog
from processing.gui.HelpEditionDialog import HelpEditionDialog
from processing.algs.r.RAlgorithm import RAlgorithm
from processing.algs.r.RUtils import RUtils
from processing.script.ScriptAlgorithm import ScriptAlgorithm
from processing.script.ScriptUtils import ScriptUtils
pluginPath = os.path.split(os.path.dirname(__file__))[0]
WIDGET, BASE = uic.loadUiType(
os.path.join(pluginPath, 'ui', 'DlgScriptEditor.ui'))
class ScriptEditorDialog(BASE, WIDGET):
SCRIPT_PYTHON = 0
SCRIPT_R = 1
hasChanged = False
def __init__(self, algType, alg):
super(ScriptEditorDialog, self).__init__(None)
self.setupUi(self)
self.searchWidget.setVisible(False)
self.setWindowFlags(Qt.WindowMinimizeButtonHint |
Qt.WindowMaximizeButtonHint |
Qt.WindowCloseButtonHint)
# Set icons
self.btnOpen.setIcon(
QgsApplication.getThemeIcon('/mActionFileOpen.svg'))
self.btnSave.setIcon(
QgsApplication.getThemeIcon('/mActionFileSave.svg'))
self.btnSaveAs.setIcon(
QgsApplication.getThemeIcon('/mActionFileSaveAs.svg'))
self.btnEditHelp.setIcon(
QIcon(os.path.join(pluginPath, 'images', 'edithelp.png')))
self.btnRun.setIcon(
QIcon(os.path.join(pluginPath, 'images', 'runalgorithm.png')))
self.btnSearch.setIcon(
QIcon(os.path.join(pluginPath, 'images', 'search.png')))
self.btnCut.setIcon(QgsApplication.getThemeIcon('/mActionEditCut.svg'))
self.btnCopy.setIcon(
QgsApplication.getThemeIcon('/mActionEditCopy.svg'))
self.btnPaste.setIcon(
QgsApplication.getThemeIcon('/mActionEditPaste.svg'))
self.btnUndo.setIcon(QgsApplication.getThemeIcon('/mActionUndo.svg'))
self.btnRedo.setIcon(QgsApplication.getThemeIcon('/mActionRedo.svg'))
self.btnSnippets.setIcon(QgsApplication.getThemeIcon('/mActionHelpAPI.png'))
# Connect signals and slots
self.btnOpen.clicked.connect(self.openScript)
self.btnSave.clicked.connect(self.save)
self.btnSaveAs.clicked.connect(self.saveAs)
self.btnEditHelp.clicked.connect(self.editHelp)
self.btnRun.clicked.connect(self.runAlgorithm)
self.btnSnippets.clicked.connect(self.showSnippets)
self.btnCut.clicked.connect(self.editor.cut)
self.btnCopy.clicked.connect(self.editor.copy)
self.btnPaste.clicked.connect(self.editor.paste)
self.btnUndo.clicked.connect(self.editor.undo)
self.btnRedo.clicked.connect(self.editor.redo)
self.btnSearch.clicked.connect(self.toggleSearchBox)
self.btnIncreaseFont.clicked.connect(self.editor.zoomIn)
self.btnDecreaseFont.clicked.connect(self.editor.zoomOut)
self.btnFind.clicked.connect(self.find)
self.btnReplace.clicked.connect(self.replace)
self.editor.textChanged.connect(lambda: self.setHasChanged(True))
self.lastSearch = None
self.alg = alg
self.algType = algType
self.snippets = {}
if self.algType == self.SCRIPT_PYTHON:
path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "script", "snippets.py")
with open(path) as f:
lines = f.readlines()
snippetlines = []
name = None
for line in lines:
if line.startswith("##"):
if snippetlines:
self.snippets[name] = "".join(snippetlines)
name = line[2:]
snippetlines = []
else:
snippetlines.append(line)
if snippetlines:
self.snippets[name] = "".join(snippetlines)
if not self.snippets:
self.btnSnippets.setVisible(False)
if self.alg is not None:
self.filename = self.alg.descriptionFile
self.editor.setText(self.alg.script)
else:
self.filename = None
self.update = False
self.help = None
self.setHasChanged(False)
self.editor.setLexerType(self.algType)
def find(self):
txt = self.findBox.text()
cs = self.chkCaseSensitive.isChecked()
wo = self.chkWholeWord.isChecked()
if self.lastSearch is None or txt != self.lastSearch:
self.editor.findFirst(txt, False, cs, wo, True)
else:
self.editor.findNext()
def replace(self):
txt = self.replaceBox.text()
self.editor.replaceSelectedText(txt)
def toggleSearchBox(self):
self.searchWidget.setVisible(not self.searchWidget.isVisible())
def showSnippets(self, evt):
popupmenu = QMenu()
for name, snippet in self.snippets.iteritems():
action = QAction(self.tr(name), self.btnSnippets)
action.triggered[()].connect(lambda snippet=snippet: self.editor.insert(snippet))
popupmenu.addAction(action)
popupmenu.exec_(QCursor.pos())
def closeEvent(self, evt):
if self.hasChanged:
ret = QMessageBox.question(self, self.tr('Unsaved changes'),
self.tr('There are unsaved changes in script. Continue?'),
QMessageBox.Yes | QMessageBox.No, QMessageBox.No
)
if ret == QMessageBox.Yes:
evt.accept()
else:
evt.ignore()
else:
evt.accept()
def editHelp(self):
if self.alg is None:
if self.algType == self.SCRIPT_PYTHON:
alg = ScriptAlgorithm(None, unicode(self.editor.text()))
elif self.algType == self.SCRIPT_R:
alg = RAlgorithm(None, unicode(self.editor.text()))
else:
alg = self.alg
dlg = HelpEditionDialog(alg)
dlg.exec_()
if dlg.descriptions:
self.help = dlg.descriptions
self.setHasChanged(True)
def openScript(self):
if self.hasChanged:
ret = QMessageBox.warning(self, self.tr('Unsaved changes'),
self.tr('There are unsaved changes in script. Continue?'),
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if ret == QMessageBox.No:
return
if self.algType == self.SCRIPT_PYTHON:
scriptDir = ScriptUtils.scriptsFolders()[0]
filterName = self.tr('Python scripts (*.py)')
elif self.algType == self.SCRIPT_R:
scriptDir = RUtils.RScriptsFolders()[0]
filterName = self.tr('Processing R script (*.rsx)')
self.filename = QFileDialog.getOpenFileName(
self, self.tr('Open script'), scriptDir, filterName)
if self.filename == '':
return
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
with codecs.open(self.filename, 'r', encoding='utf-8') as f:
txt = f.read()
self.editor.setText(txt)
self.hasChanged = False
self.editor.setModified(False)
self.editor.recolor()
QApplication.restoreOverrideCursor()
def save(self):
self.saveScript(False)
def saveAs(self):
self.saveScript(True)
def saveScript(self, saveAs):
if self.filename is None or saveAs:
if self.algType == self.SCRIPT_PYTHON:
scriptDir = ScriptUtils.scriptsFolders()[0]
filterName = self.tr('Python scripts (*.py)')
elif self.algType == self.SCRIPT_R:
scriptDir = RUtils.RScriptsFolders()[0]
filterName = self.tr('Processing R script (*.rsx)')
self.filename = unicode(QFileDialog.getSaveFileName(self,
self.tr('Save script'), scriptDir,
filterName))
if self.filename:
if self.algType == self.SCRIPT_PYTHON and \
not self.filename.lower().endswith('.py'):
self.filename += '.py'
if self.algType == self.SCRIPT_R and \
not self.filename.lower().endswith('.rsx'):
self.filename += '.rsx'
text = unicode(self.editor.text())
if self.alg is not None:
self.alg.script = text
try:
with codecs.open(self.filename, 'w', encoding='utf-8') as fout:
fout.write(text)
except IOError:
QMessageBox.warning(self, self.tr('I/O error'),
self.tr('Unable to save edits. Reason:\n %s')
% unicode(sys.exc_info()[1])
)
return
self.update = True
# If help strings were defined before saving the script for
# the first time, we do it here
if self.help:
with open(self.filename + '.help', 'w') as f:
json.dump(self.help, f)
self.help = None
self.setHasChanged(False)
else:
self.filename = None
def setHasChanged(self, hasChanged):
self.hasChanged = hasChanged
self.btnSave.setEnabled(hasChanged)
def runAlgorithm(self):
if self.algType == self.SCRIPT_PYTHON:
alg = ScriptAlgorithm(None, unicode(self.editor.text()))
alg.provider = algList.getProviderFromName('script')
if self.algType == self.SCRIPT_R:
alg = RAlgorithm(None, unicode(self.editor.text()))
alg.provider = algList.getProviderFromName('r')
dlg = alg.getCustomParametersDialog()
if not dlg:
dlg = AlgorithmDialog(alg)
canvas = iface.mapCanvas()
prevMapTool = canvas.mapTool()
dlg.show()
dlg.exec_()
if canvas.mapTool() != prevMapTool:
try:
canvas.mapTool().reset()
except:
pass
canvas.setMapTool(prevMapTool)
|