def __init__(self, methodName): """Run once on class initialization.""" unittest.TestCase.__init__(self, methodName) self.mapSettings = QgsMapSettings() # create composition self.mComposition = QgsComposition(self.mapSettings) self.mComposition.setPaperSize(297, 210) # create polygon = QPolygonF() polygon.append(QPointF(0.0, 0.0)) polygon.append(QPointF(100.0, 0.0)) polygon.append(QPointF(200.0, 100.0)) polygon.append(QPointF(100.0, 200.0)) self.mComposerPolyline = QgsComposerPolyline(polygon, self.mComposition) self.mComposition.addComposerPolyline(self.mComposerPolyline) # style props = {} props["color"] = "0,0,0,255" props["width"] = "10.0" props["capstyle"] = "square" style = QgsLineSymbolV2.createSimple(props) self.mComposerPolyline.setPolylineStyleSymbol(style)
def __init__(self, methodName): """Run once on class initialization.""" unittest.TestCase.__init__(self, methodName) self.mapSettings = QgsMapSettings() # create composition self.mComposition = QgsComposition(self.mapSettings) self.mComposition.setPaperSize(297, 210) # create polygon = QPolygonF() polygon.append(QPointF(0.0, 0.0)) polygon.append(QPointF(100.0, 0.0)) polygon.append(QPointF(200.0, 100.0)) polygon.append(QPointF(100.0, 200.0)) self.mComposerPolygon = QgsComposerPolygon(polygon, self.mComposition) self.mComposition.addComposerPolygon(self.mComposerPolygon) # style props = {} props["color"] = "green" props["style"] = "solid" props["style_border"] = "solid" props["color_border"] = "black" props["width_border"] = "10.0" props["joinstyle"] = "miter" style = QgsFillSymbolV2.createSimple(props) self.mComposerPolygon.setPolygonStyleSymbol(style)
def paint(self, painter, option, widget=None): rect = QRectF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2.0, -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2.0, ModelerGraphicItem.BOX_WIDTH + 2, ModelerGraphicItem.BOX_HEIGHT + 2) painter.setPen(QPen(Qt.gray, 1)) color = QColor(125, 232, 232) if isinstance(self.element, ModelerParameter): color = QColor(179, 179, 255) elif isinstance(self.element, Algorithm): color = Qt.white painter.setBrush(QBrush(color, Qt.SolidPattern)) painter.drawRect(rect) font = QFont('Verdana', 8) painter.setFont(font) painter.setPen(QPen(Qt.black)) text = self.getAdjustedText(self.text) if isinstance(self.element, Algorithm) and not self.element.active: painter.setPen(QPen(Qt.gray)) text = text + "\n(deactivated)" elif self.isSelected(): painter.setPen(QPen(Qt.blue)) fm = QFontMetricsF(font) text = self.getAdjustedText(self.text) h = fm.height() pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, h / 2.0) painter.drawText(pt, text) painter.setPen(QPen(Qt.black)) if isinstance(self.element, Algorithm): h = -(fm.height() * 1.2) h = h - ModelerGraphicItem.BOX_HEIGHT / 2.0 + 5 pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, h) painter.drawText(pt, 'In') i = 1 if not self.element.paramsFolded: for param in self.element.algorithm.parameters: if not param.hidden: text = self.getAdjustedText(param.description) h = -(fm.height() * 1.2) * (i + 1) h = h - ModelerGraphicItem.BOX_HEIGHT / 2.0 + 5 pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 33, h) painter.drawText(pt, text) i += 1 h = fm.height() * 1.2 h = h + ModelerGraphicItem.BOX_HEIGHT / 2.0 pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, h) painter.drawText(pt, 'Out') if not self.element.outputsFolded: for i, out in enumerate(self.element.algorithm.outputs): text = self.getAdjustedText(out.description) h = fm.height() * 1.2 * (i + 2) h = h + ModelerGraphicItem.BOX_HEIGHT / 2.0 pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 33, h) painter.drawText(pt, text) if self.pixmap: painter.drawPixmap(-(ModelerGraphicItem.BOX_WIDTH / 2.0) + 3, -8, self.pixmap)
def foldInput(self, folded): self.element.paramsFolded = folded self.prepareGeometryChange() if self.element.algorithm.outputs: pt = self.getLinkPointForOutput(-1) pt = QPointF(0, pt.y()) self.outButton.position = pt for arrow in self.arrows: arrow.updatePath() self.update()
def __init__(self, element, model): super(ModelerGraphicItem, self).__init__(None, None) self.model = model self.element = element if isinstance(element, ModelerParameter): icon = QIcon(os.path.join(pluginPath, 'images', 'input.png')) self.pixmap = icon.pixmap(20, 20, state=QIcon.On) self.text = element.param.description elif isinstance(element, ModelerOutput): # Output name icon = QIcon(os.path.join(pluginPath, 'images', 'output.png')) self.pixmap = icon.pixmap(20, 20, state=QIcon.On) self.text = element.description else: self.text = element.description self.pixmap = element.algorithm.getIcon().pixmap(15, 15) self.arrows = [] self.setFlag(QGraphicsItem.ItemIsMovable, True) self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) self.setZValue(1000) if not isinstance(element, ModelerOutput): icon = QIcon(os.path.join(pluginPath, 'images', 'edit.png')) pt = QPointF( ModelerGraphicItem.BOX_WIDTH / 2 - FlatButtonGraphicItem.WIDTH / 2, ModelerGraphicItem.BOX_HEIGHT / 2 - FlatButtonGraphicItem.HEIGHT / 2 + 1) self.editButton = FlatButtonGraphicItem(icon, pt, self.editElement) self.editButton.setParentItem(self) icon = QIcon(os.path.join(pluginPath, 'images', 'delete.png')) pt = QPointF( ModelerGraphicItem.BOX_WIDTH / 2 - FlatButtonGraphicItem.WIDTH / 2, -ModelerGraphicItem.BOX_HEIGHT / 2 + FlatButtonGraphicItem.HEIGHT / 2 + 1) self.deleteButton = FlatButtonGraphicItem(icon, pt, self.removeElement) self.deleteButton.setParentItem(self) if isinstance(element, Algorithm): alg = element.algorithm if alg.parameters: pt = self.getLinkPointForParameter(-1) pt = QPointF(0, pt.y() + 2) self.inButton = FoldButtonGraphicItem( pt, self.foldInput, self.element.paramsFolded) self.inButton.setParentItem(self) if alg.outputs: pt = self.getLinkPointForOutput(-1) pt = QPointF(0, pt.y() + 2) self.outButton = FoldButtonGraphicItem( pt, self.foldOutput, self.element.outputsFolded) self.outButton.setParentItem(self)
def testAddNode(self): """Test addNode method""" # default searching radius is 10 self.assertEqual(self.mComposerPolygon.nodesSize(), 4) rc = self.mComposerPolygon.addNode(QPointF(50.0, 10.0)) self.assertEqual(rc, False) # default searching radius is 10 self.assertEqual(self.mComposerPolygon.nodesSize(), 4) rc = self.mComposerPolygon.addNode(QPointF(50.0, 9.99)) self.assertEqual(rc, True) self.assertEqual(self.mComposerPolygon.nodesSize(), 5)
def testAddNodeCustomRadius(self): """Test addNode with custom radius""" # default searching radius is 10 self.assertEqual(self.mComposerPolygon.nodesSize(), 4) rc = self.mComposerPolygon.addNode(QPointF(50.0, 8.1), True, 8.0) self.assertEqual(rc, False) self.assertEqual(self.mComposerPolygon.nodesSize(), 4) # default searching radius is 10 rc = self.mComposerPolygon.addNode(QPointF(50.0, 7.9), True, 8.0) self.assertEqual(rc, True) self.assertEqual(self.mComposerPolygon.nodesSize(), 5)
def paint(self, painter, option, widget=None): pt = QPointF(-self.WIDTH / 2, -self.HEIGHT / 2) + self.position rect = QRectF(pt.x(), pt.y(), self.WIDTH, self.HEIGHT) if self.isIn: painter.setPen(QPen(Qt.transparent, 1)) painter.setBrush(QBrush(Qt.lightGray, Qt.SolidPattern)) else: painter.setPen(QPen(Qt.transparent, 1)) painter.setBrush(QBrush(Qt.transparent, Qt.SolidPattern)) painter.drawRect(rect) painter.drawPixmap(pt.x(), pt.y(), self.pixmap)
def testMoveNode(self): """Test moveNode method""" rc = self.mComposerPolygon.moveNode(30, QPointF(100.0, 300.0)) self.assertEqual(rc, False) rc = self.mComposerPolygon.moveNode(3, QPointF(100.0, 150.0)) self.assertEqual(rc, True) checker = QgsCompositionChecker('composerpolygon_movenode', self.mComposition) checker.setControlPathPrefix("composer_polygon") myTestResult, myMessage = checker.testComposition() assert myTestResult, myMessage
def testNodeAtPosition(self): """Test nodeAtPosition method""" # default searching radius is 10 rc = self.mComposerPolygon.nodeAtPosition(QPointF(100.0, 210.0)) self.assertEqual(rc, -1) # default searching radius is 10 rc = self.mComposerPolygon.nodeAtPosition(QPointF(100.0, 210.0), False) self.assertEqual(rc, 3) # default searching radius is 10 rc = self.mComposerPolygon.nodeAtPosition(QPointF(100.0, 210.0), True, 10.1) self.assertEqual(rc, 3)
def fromdict(d): try: fullClassName = d["class"] tokens = fullClassName.split(".") className = tokens[-1] moduleName = ".".join(tokens[:-1]) values = d["values"] if className == "point": return QPointF(values["x"], values["y"]) def _import(name): __import__(name) return sys.modules[name] if moduleName.startswith("processing.parameters"): moduleName = "processing.core.parameters" module = _import(moduleName) clazz = getattr(module, className) instance = clazz() for k, v in values.iteritems(): instance.__dict__[k] = v return instance except KeyError: return d except Exception as e: raise e
def getLinkPointForOutput(self, outputIndex): if isinstance(self.element, Algorithm) and self.element.algorithm.outputs: outputIndex = (outputIndex if not self.element.outputsFolded else -1) text = self.getAdjustedText( self.element.algorithm.outputs[outputIndex].description) font = QFont('Verdana', 8) fm = QFontMetricsF(font) w = fm.width(text) h = fm.height() * 1.2 * (outputIndex + 1) + fm.height() / 2.0 y = h + ModelerGraphicItem.BOX_HEIGHT / 2.0 + 5 x = (-ModelerGraphicItem.BOX_WIDTH / 2 + 33 + w + 5 if not self.element.outputsFolded else 10) return QPointF(x, y) else: return QPointF(0, 0)
def polygon(self): font = QFont('Verdana', 8) fm = QFontMetricsF(font) hUp = fm.height() * 1.2 * (len(self.element.parameters) + 2) hDown = fm.height() * 1.2 * (len(self.element.outputs) + 2) pol = QPolygonF([ QPointF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2, -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2 - hUp), QPointF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2, (ModelerGraphicItem.BOX_HEIGHT + 2) / 2 + hDown), QPointF((ModelerGraphicItem.BOX_WIDTH + 2) / 2, (ModelerGraphicItem.BOX_HEIGHT + 2) / 2 + hDown), QPointF((ModelerGraphicItem.BOX_WIDTH + 2) / 2, -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2 - hUp), QPointF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2, -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2 - hUp) ]) return pol
def getPositionForParameterItem(self): MARGIN = 20 BOX_WIDTH = 200 BOX_HEIGHT = 80 if self.alg.inputs: maxX = max([i.pos.x() for i in self.alg.inputs.values()]) newX = min(MARGIN + BOX_WIDTH + maxX, self.CANVAS_SIZE - BOX_WIDTH) else: newX = MARGIN + BOX_WIDTH / 2 return QPointF(newX, MARGIN + BOX_HEIGHT / 2)
def _addAlgorithm(self, alg, pos=None): dlg = alg.getCustomModelerParametersDialog(self.alg) if not dlg: dlg = ModelerParametersDialog(alg, self.alg) dlg.exec_() if dlg.alg is not None: if pos is None: dlg.alg.pos = self.getPositionForAlgorithmItem() else: dlg.alg.pos = pos if isinstance(dlg.alg.pos, QPoint): dlg.alg.pos = QPointF(pos) from processing.modeler.ModelerGraphicItem import ModelerGraphicItem for i, out in enumerate(dlg.alg.outputs): dlg.alg.outputs[out].pos = dlg.alg.pos + QPointF( ModelerGraphicItem.BOX_WIDTH, (i + 1.5) * ModelerGraphicItem.BOX_HEIGHT) self.alg.addAlgorithm(dlg.alg) self.repaintModel() self.hasChanged = True
def testAddNodeWithoutCheckingArea(self): """Test addNode without checking the maximum distance allowed""" # default searching radius is 10 self.assertEqual(self.mComposerPolygon.nodesSize(), 4) rc = self.mComposerPolygon.addNode(QPointF(50.0, 20.0)) self.assertEqual(rc, False) self.assertEqual(self.mComposerPolygon.nodesSize(), 4) # default searching radius is 10 self.assertEqual(self.mComposerPolygon.nodesSize(), 4) rc = self.mComposerPolygon.addNode(QPointF(50.0, 20.0), False) self.assertEqual(rc, True) self.assertEqual(self.mComposerPolygon.nodesSize(), 5) checker = QgsCompositionChecker('composerpolygon_addnode', self.mComposition) checker.setControlPathPrefix("composer_polygon") myTestResult, myMessage = checker.testComposition() assert myTestResult, myMessage
def updateAlgorithm(self, alg): alg.pos = self.algs[alg.name].pos alg.paramsFolded = self.algs[alg.name].paramsFolded alg.outputsFolded = self.algs[alg.name].outputsFolded self.algs[alg.name] = alg from processing.modeler.ModelerGraphicItem import ModelerGraphicItem for i, out in enumerate(alg.outputs): alg.outputs[out].pos = ( alg.outputs[out].pos or alg.pos + QPointF(ModelerGraphicItem.BOX_WIDTH, (i + 1.5) * ModelerGraphicItem.BOX_HEIGHT))
def getLinkPointForParameter(self, paramIndex): offsetX = 25 if isinstance(self.element, Algorithm) and self.element.paramsFolded: paramIndex = -1 offsetX = 17 font = QFont('Verdana', 8) fm = QFontMetricsF(font) if isinstance(self.element, Algorithm): h = -(fm.height() * 1.2) * (paramIndex + 2) - fm.height() / 2.0 + 8 h = h - ModelerGraphicItem.BOX_HEIGHT / 2.0 else: h = 0 return QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + offsetX, h)
def addInputOfType(self, paramType, pos=None): if paramType in ModelerParameterDefinitionDialog.paramTypes: dlg = ModelerParameterDefinitionDialog(self.alg, paramType) dlg.exec_() if dlg.param is not None: if pos is None: pos = self.getPositionForParameterItem() if isinstance(pos, QPoint): pos = QPointF(pos) self.alg.addParameter(ModelerParameter(dlg.param, pos)) self.repaintModel() #self.view.ensureVisible(self.scene.getLastParameterItem()) self.hasChanged = True
def test_background_svg_w_offset(self): # Label SVG background self.lyr.fontSizeInMapUnits = True font = QFont(self._TestFont) font.setPointSizeF(460) self.lyr.textFont = font self.lyr.shapeDraw = True self.lyr.shapeType = QgsPalLayerSettings.ShapeSVG svg = os.path.join(svgSymbolsPath(), 'backgrounds', 'background_square.svg') self.lyr.shapeSVGFile = svg self.lyr.shapeSizeUnits = QgsPalLayerSettings.MapUnits self.lyr.shapeSizeType = QgsPalLayerSettings.SizeBuffer self.lyr.shapeSize = QPointF(100.0, 0.0) self.lyr.shapeOffsetUnits = QgsPalLayerSettings.MapUnits self.lyr.shapeOffset = QPointF(-2850.0, 500.0) self._Mismatches['TestComposerPdfVsComposerPoint'] = 760 self._Mismatches['TestCanvasPoint'] = 776 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest()
def getPositionForAlgorithmItem(self): MARGIN = 20 BOX_WIDTH = 200 BOX_HEIGHT = 80 if self.alg.algs: maxX = max([alg.pos.x() for alg in self.alg.algs.values()]) maxY = max([alg.pos.y() for alg in self.alg.algs.values()]) newX = min(MARGIN + BOX_WIDTH + maxX, self.CANVAS_SIZE - BOX_WIDTH) newY = min(MARGIN + BOX_HEIGHT + maxY, self.CANVAS_SIZE - BOX_HEIGHT) else: newX = MARGIN + BOX_WIDTH / 2 newY = MARGIN * 2 + BOX_HEIGHT + BOX_HEIGHT / 2 return QPointF(newX, newY)
def __init__(self, element, model): super(ModelerGraphicItem, self).__init__(None, None) self.model = model self.element = element if isinstance(element, ModelerParameter): icon = QIcon(os.path.join(pluginPath, 'images', 'input.png')) self.pixmap = icon.pixmap(20, 20, state=QIcon.On) self.text = element.param.description elif isinstance(element, ModelerOutput): # Output name icon = QIcon(os.path.join(pluginPath, 'images', 'output.png')) self.pixmap = icon.pixmap(20, 20, state=QIcon.On) self.text = element.description else: self.text = element.description self.pixmap = element.algorithm.getIcon().pixmap(15, 15) self.arrows = [] self.setFlag(QGraphicsItem.ItemIsMovable, True) self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) self.setZValue(1000) if not isinstance(element, ModelerOutput): icon = QIcon(os.path.join(pluginPath, 'images', 'edit.png')) pt = QPointF(ModelerGraphicItem.BOX_WIDTH / 2 - FlatButtonGraphicItem.WIDTH / 2, ModelerGraphicItem.BOX_HEIGHT / 2 - FlatButtonGraphicItem.HEIGHT / 2 + 1) self.editButton = FlatButtonGraphicItem(icon, pt, self.editElement) self.editButton.setParentItem(self) icon = QIcon(os.path.join(pluginPath, 'images', 'delete.png')) pt = QPointF(ModelerGraphicItem.BOX_WIDTH / 2 - FlatButtonGraphicItem.WIDTH / 2, - ModelerGraphicItem.BOX_HEIGHT / 2 + FlatButtonGraphicItem.HEIGHT / 2 + 1) self.deleteButton = FlatButtonGraphicItem(icon, pt, self.removeElement) self.deleteButton.setParentItem(self) if isinstance(element, Algorithm): alg = element.algorithm if alg.parameters: pt = self.getLinkPointForParameter(-1) pt = QPointF(0, pt.y() + 2) self.inButton = FoldButtonGraphicItem(pt, self.foldInput, self.element.paramsFolded) self.inButton.setParentItem(self) if alg.outputs: pt = self.getLinkPointForOutput(-1) pt = QPointF(0, pt.y() + 2) self.outButton = FoldButtonGraphicItem(pt, self.foldOutput, self.element.outputsFolded) self.outButton.setParentItem(self)
def test_background_rect_w_offset(self): # Label rectangular background self._Mismatches['TestComposerImageVsCanvasPoint'] = 800 self._Mismatches['TestComposerImagePoint'] = 800 # verify fix for issues # http://hub.qgis.org/issues/9057 # http://gis.stackexchange.com/questions/86900 self.lyr.fontSizeInMapUnits = True font = QFont(self._TestFont) font.setPointSizeF(460) self.lyr.textFont = font self.lyr.shapeDraw = True self.lyr.shapeOffsetUnits = QgsPalLayerSettings.MapUnits self.lyr.shapeOffset = QPointF(-2900.0, -450.0) self._Mismatches['TestCanvasPoint'] = 774 self._ColorTols['TestComposerPdfPoint'] = 2 self.checkTest()
def testQgsGradientFillSymbolLayerV2(self): """Test setting and getting QgsGradientFillSymbolLayerV2 properties. """ mGradientLayer = QgsGradientFillSymbolLayerV2() mExpectedValue = type(QgsGradientFillSymbolLayerV2()) mValue = type(mGradientLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QgsGradientFillSymbolLayerV2.Radial mGradientLayer.setGradientType(mExpectedValue) mValue = mGradientLayer.gradientType() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QgsGradientFillSymbolLayerV2.ColorRamp mGradientLayer.setGradientColorType(mExpectedValue) mValue = mGradientLayer.gradientColorType() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QColor('#55aaff') mGradientLayer.setColor2(mExpectedValue) mValue = mGradientLayer.color2() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QgsGradientFillSymbolLayerV2.Viewport mGradientLayer.setCoordinateMode(mExpectedValue) mValue = mGradientLayer.coordinateMode() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QgsGradientFillSymbolLayerV2.Reflect mGradientLayer.setGradientSpread(mExpectedValue) mValue = mGradientLayer.gradientSpread() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QPointF(0.5, 0.8) mGradientLayer.setReferencePoint1(mExpectedValue) mValue = mGradientLayer.referencePoint1() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = True mGradientLayer.setReferencePoint1IsCentroid(mExpectedValue) mValue = mGradientLayer.referencePoint1IsCentroid() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QPointF(0.2, 0.4) mGradientLayer.setReferencePoint2(mExpectedValue) mValue = mGradientLayer.referencePoint2() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = True mGradientLayer.setReferencePoint2IsCentroid(mExpectedValue) mValue = mGradientLayer.referencePoint2IsCentroid() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 90 mGradientLayer.setAngle(mExpectedValue) mValue = mGradientLayer.angle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QPointF(10, 20) mGradientLayer.setOffset(mExpectedValue) mValue = mGradientLayer.offset() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QgsSymbolV2.MapUnit mGradientLayer.setOffsetUnit(mExpectedValue) mValue = mGradientLayer.offsetUnit() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def updatePath(self): self.endPoints = [] controlPoints = [] endPt = self.endItem.getLinkPointForParameter(self.endIndex) startPt = self.startItem.getLinkPointForOutput(self.startIndex) if isinstance(self.startItem.element, Algorithm): if self.startIndex != -1: controlPoints.append(self.startItem.pos() + startPt) controlPoints.append(self.startItem.pos() + startPt + QPointF(ModelerGraphicItem.BOX_WIDTH / 3, 0)) controlPoints.append(self.endItem.pos() + endPt - QPointF(ModelerGraphicItem.BOX_WIDTH / 3, 0)) controlPoints.append(self.endItem.pos() + endPt) pt = QPointF(self.startItem.pos() + startPt + QPointF(-3, -3)) self.endPoints.append(pt) pt = QPointF(self.endItem.pos() + endPt + QPointF(-3, -3)) self.endPoints.append(pt) else: # Case where there is a dependency on an algorithm not # on an output controlPoints.append(self.startItem.pos() + startPt) controlPoints.append(self.startItem.pos() + startPt + QPointF(ModelerGraphicItem.BOX_WIDTH / 3, 0)) controlPoints.append(self.endItem.pos() + endPt - QPointF(ModelerGraphicItem.BOX_WIDTH / 3, 0)) controlPoints.append(self.endItem.pos() + endPt) else: controlPoints.append(self.startItem.pos()) controlPoints.append(self.startItem.pos() + QPointF(ModelerGraphicItem.BOX_WIDTH / 3, 0)) controlPoints.append(self.endItem.pos() + endPt - QPointF(ModelerGraphicItem.BOX_WIDTH / 3, 0)) controlPoints.append(self.endItem.pos() + endPt) pt = QPointF(self.endItem.pos() + endPt + QPointF(-3, -3)) self.endPoints.append(pt) path = QPainterPath() path.moveTo(controlPoints[0]) path.cubicTo(*controlPoints[1:]) self.setPath(path)
def paintModel(self, model): self.model = model # Inputs for inp in model.inputs.values(): item = ModelerGraphicItem(inp, model) item.setFlag(QGraphicsItem.ItemIsMovable, True) item.setFlag(QGraphicsItem.ItemIsSelectable, True) self.addItem(item) item.setPos(inp.pos.x(), inp.pos.y()) self.paramItems[inp.param.name] = item # We add the algs for alg in model.algs.values(): item = ModelerGraphicItem(alg, model) item.setFlag(QGraphicsItem.ItemIsMovable, True) item.setFlag(QGraphicsItem.ItemIsSelectable, True) self.addItem(item) item.setPos(alg.pos.x(), alg.pos.y()) self.algItems[alg.name] = item # And then the arrows for alg in model.algs.values(): idx = 0 for parameter in alg.algorithm.parameters: if not parameter.hidden: if parameter.name in alg.params: value = alg.params[parameter.name] else: value = None sourceItems = self.getItemsFromParamValue(value) for sourceItem, sourceIdx in sourceItems: arrow = ModelerArrowItem(sourceItem, sourceIdx, self.algItems[alg.name], idx) sourceItem.addArrow(arrow) self.algItems[alg.name].addArrow(arrow) arrow.updatePath() self.addItem(arrow) idx += 1 for depend in alg.dependencies: arrow = ModelerArrowItem(self.algItems[depend], -1, self.algItems[alg.name], -1) self.algItems[depend].addArrow(arrow) self.algItems[alg.name].addArrow(arrow) arrow.updatePath() self.addItem(arrow) # And finally the outputs for alg in model.algs.values(): outputs = alg.outputs outputItems = {} idx = 0 for key in outputs: out = outputs[key] if out is not None: item = ModelerGraphicItem(out, model) item.setFlag(QGraphicsItem.ItemIsMovable, True) item.setFlag(QGraphicsItem.ItemIsSelectable, True) self.addItem(item) pos = alg.outputs[key].pos if pos is None: pos = ( alg.pos + QPointF(ModelerGraphicItem.BOX_WIDTH, 0) + self.algItems[alg.name].getLinkPointForOutput(idx)) item.setPos(pos) outputItems[key] = item arrow = ModelerArrowItem(self.algItems[alg.name], idx, item, -1) self.algItems[alg.name].addArrow(arrow) item.addArrow(arrow) arrow.updatePath() self.addItem(arrow) idx += 1 else: outputItems[key] = None self.outputItems[alg.name] = outputItems
def fromOldFormatFile(filename): def _tr(s): return QCoreApplication.translate('ModelerAlgorithm', s) hardcodedValues = {} modelParameters = [] modelAlgs = [] model = ModelerAlgorithm() model.descriptionFile = filename lines = codecs.open(filename, 'r', encoding='utf-8') line = lines.readline().strip('\n').strip('\r') try: while line != '': if line.startswith('PARAMETER:'): paramLine = line[len('PARAMETER:'):] param = getParameterFromString(paramLine) if param: pass else: raise WrongModelException( _tr('Error in parameter line: %s', 'ModelerAlgorithm') % line) line = lines.readline().strip('\n') tokens = line.split(',') model.addParameter( ModelerParameter( param, QPointF(float(tokens[0]), float(tokens[1])))) modelParameters.append(param.name) elif line.startswith('VALUE:'): valueLine = line[len('VALUE:'):] tokens = valueLine.split('===') name = tokens[0] value = tokens[1].replace( ModelerAlgorithm.LINE_BREAK_STRING, '\n') hardcodedValues[name] = value elif line.startswith('NAME:'): model.name = line[len('NAME:'):] elif line.startswith('GROUP:'): model.group = line[len('GROUP:'):] elif line.startswith('ALGORITHM:'): algLine = line[len('ALGORITHM:'):] alg = ModelerUtils.getAlgorithm(algLine) if alg is not None: modelAlg = Algorithm(alg.commandLineName()) modelAlg.description = alg.name posline = lines.readline().strip('\n').strip('\r') tokens = posline.split(',') modelAlg.pos = QPointF(float(tokens[0]), float(tokens[1])) # dependenceline = lines.readline().strip('\n').strip('\r') for param in alg.parameters: if not param.hidden: line = lines.readline().strip('\n').strip('\r') if line == unicode(None): modelAlg.params[param.name] = None else: tokens = line.split('|') try: algIdx = int(tokens[0]) except: raise WrongModelException( _tr('Number of parameters in the ' '{} algorithm does not match ' 'current Processing ' 'implementation'.format( alg.name))) if algIdx == -1: if tokens[1] in modelParameters: modelAlg.params[ param.name] = ValueFromInput( tokens[1]) else: modelAlg.params[ param.name] = hardcodedValues[ tokens[1]] else: modelAlg.params[ param.name] = ValueFromOutput( algIdx, tokens[1]) for out in alg.outputs: if not out.hidden: line = lines.readline().strip('\n').strip('\r') if unicode(None) != line: if '|' in line: tokens = line.split('|') name = tokens[0] tokens = tokens[1].split(',') pos = QPointF(float(tokens[0]), float(tokens[1])) else: name = line pos = None modelerOutput = ModelerOutput(name) modelerOutput.pos = pos modelAlg.outputs[out.name] = modelerOutput model.addAlgorithm(modelAlg) modelAlgs.append(modelAlg.name) else: raise WrongModelException( _tr('Error in algorithm name: %s', ) % algLine) line = lines.readline().strip('\n').strip('\r') for modelAlg in model.algs.values(): for name, value in modelAlg.params.iteritems(): if isinstance(value, ValueFromOutput): value.alg = modelAlgs[value.alg] return model except Exception as e: if isinstance(e, WrongModelException): raise e else: raise WrongModelException( _tr('Error in model definition line: ') + '%s\n%s' % (line.strip(), traceback.format_exc()))