Exemple #1
0
class TimedProgressBar(QProgressBar):
    """A QProgressBar showing a certain time elapse."""
    hideOnTimeout = True

    def __init__(self, parent=None):
        super(TimedProgressBar, self).__init__(parent, minimum=0, maximum=100)
        self._timeline = QTimeLine(updateInterval=100,
                                   frameChanged=self.setValue)
        self._timeline.setFrameRange(0, 100)
        self._hideTimer = QTimer(timeout=self._done,
                                 singleShot=True,
                                 interval=3000)

    def start(self, total, elapsed=0.0):
        """Starts showing progress.
        
        total is the number of seconds (maybe float) the timeline will last,
        elapsed (defaulting to 0) is the value to start with.
        
        """
        self._hideTimer.stop()
        self._timeline.stop()
        self._timeline.setDuration(total * 1000)
        self._timeline.setCurrentTime(elapsed * 1000)
        self.setValue(self._timeline.currentFrame())
        self._timeline.resume()
        if self.hideOnTimeout:
            self.show()

    def stop(self, showFinished=True):
        """Ends the progress display.
        
        If showFinished is True (the default), 100% is shown for a few
        seconds and then the progress is reset.
        The progressbar is hidden if the hideOnTimeout attribute is True.
        
        """
        self._hideTimer.stop()
        self._timeline.stop()
        if showFinished:
            self.setValue(100)
            self._hideTimer.start()
        else:
            self._done()

    def _done(self):
        if self.hideOnTimeout:
            self.hide()
        self.reset()
Exemple #2
0
class RotatingIcon(QLabel):
    def __init__(self, resource, parent=None, steps=20, width=15, height=15):
        QLabel.__init__(self, parent)
        self._resource = resource
        self._steps = steps
        self._width = width
        self._height = height
        self._progressTimeLine = QTimeLine(1000, self)
        self._progressTimeLine.setFrameRange(0, self._steps)
        self._progressTimeLine.setLoopCount(0)
        self.connect(self._progressTimeLine, SIGNAL("frameChanged(int)"),
                     self.setProgress)
        self._renderPixmaps()
        self.setProgress(0)

    def _renderPixmaps(self):
        self._pixmaps = []
        for i in range(self._steps + 1):
            angle = int(i * 360.0 / self._steps)
            pixmap = QPixmap(self._resource)
            # if problem with loading png
            if pixmap.size().width() == 0:
                self._pixmaps = None
                return
            rotate_matrix = QMatrix()
            rotate_matrix.rotate(angle)
            pixmap_rotated = pixmap.transformed(rotate_matrix)
            pixmap_moved = QPixmap(pixmap.size())
            pixmap_moved.fill(Qt.transparent)
            painter = QPainter()
            painter.begin(pixmap_moved)
            painter.drawPixmap(
                (pixmap_moved.width() - pixmap_rotated.width()) / 2.0,
                (pixmap_moved.height() - pixmap_rotated.height()) / 2.0,
                pixmap_rotated)
            painter.end()
            self._pixmaps += [pixmap_moved.scaled(self._width, self._height)]

    def setProgress(self, progress):
        if self._pixmaps != None:
            self.setPixmap(self._pixmaps[progress])

    def start(self):
        self.setProgress(0)
        self._progressTimeLine.start()

    def stop(self):
        self._progressTimeLine.stop()
class Animation:
    def __init__(self, duration, component):
        self.tl = QTimeLine(duration)
        self.tl.setFrameRange(0, duration)
        self.component = component
        self.t = QGraphicsItemAnimation()
        self.t.setItem(self.component.item)
        self.t.setTimeLine(self.tl)
        self.tl.connect(self.tl, SIGNAL('frameChanged(int)'), self.update)
        self.tl.connect(self.tl, SIGNAL('finished()'), self.finished)
    def start(self):
        self.tl.stop()
        self.tl.start()
    def update(self):
        pass
    def finished(self):
        pass
class TimedProgressBar(QProgressBar):
    """A QProgressBar showing a certain time elapse."""
    hideOnTimeout = True
    def __init__(self, parent=None):
        super(TimedProgressBar, self).__init__(parent, minimum=0, maximum=100)
        self._timeline = QTimeLine(updateInterval=100, frameChanged=self.setValue)
        self._timeline.setFrameRange(0, 100)
        self._hideTimer = QTimer(timeout=self._done, singleShot=True, interval=3000)
    
    def start(self, total, elapsed=0.0):
        """Starts showing progress.
        
        total is the number of seconds (maybe float) the timeline will last,
        elapsed (defaulting to 0) is the value to start with.
        
        """
        self._hideTimer.stop()
        self._timeline.stop()
        self._timeline.setDuration(total * 1000)
        self._timeline.setCurrentTime(elapsed * 1000)
        self.setValue(self._timeline.currentFrame())
        self._timeline.resume()
        if self.hideOnTimeout:
            self.show()
        
    def stop(self, showFinished=True):
        """Ends the progress display.
        
        If showFinished is True (the default), 100% is shown for a few
        seconds and then the progress is reset.
        The progressbar is hidden if the hideOnTimeout attribute is True.
        
        """
        self._hideTimer.stop()
        self._timeline.stop()
        if showFinished:
            self.setValue(100)
            self._hideTimer.start()
        else:
            self._done()

    def _done(self):
        if self.hideOnTimeout:
            self.hide()
        self.reset()
Exemple #5
0
class RotatingIcon(QLabel):
    def __init__(self,resource,parent=None,steps=20,width=15,height=15):
        QLabel.__init__(self,parent)
        self._resource=resource
        self._steps=steps
        self._width=width
        self._height=height
        self._progressTimeLine = QTimeLine(1000, self)
        self._progressTimeLine.setFrameRange(0, self._steps)
        self._progressTimeLine.setLoopCount(0)
        self.connect(self._progressTimeLine, SIGNAL("frameChanged(int)"), self.setProgress)
        self._renderPixmaps()
        self.setProgress(0)

    def _renderPixmaps(self):
        self._pixmaps=[]
        for i in range(self._steps+1):
            angle = int(i * 360.0 / self._steps)
            pixmap = QPixmap(self._resource)
            # if problem with loading png
            if pixmap.size().width()==0:
                self._pixmaps=None
                return
            rotate_matrix = QMatrix()
            rotate_matrix.rotate(angle)
            pixmap_rotated = pixmap.transformed(rotate_matrix)
            pixmap_moved = QPixmap(pixmap.size())
            pixmap_moved.fill(Qt.transparent)
            painter = QPainter()
            painter.begin(pixmap_moved)
            painter.drawPixmap((pixmap_moved.width() - pixmap_rotated.width()) / 2.0, (pixmap_moved.height() - pixmap_rotated.height()) / 2.0, pixmap_rotated)
            painter.end()
            self._pixmaps+=[pixmap_moved.scaled(self._width, self._height)]
        
    def setProgress(self, progress):
        if self._pixmaps!=None:
            self.setPixmap(self._pixmaps[progress])
        
    def start(self):
        self.setProgress(0)
        self._progressTimeLine.start()
        
    def stop(self):
        self._progressTimeLine.stop()
Exemple #6
0
class TransitionWidget(QWidget):
    """
    This class implements a transition effect between two pixmaps.

    Starts the transition with the method `start` and emit the signal finished()
    when the transition is done.
    """

    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self._timeline = QTimeLine(400, self)
        self._blending_factor = 0.0
        self.connect(self._timeline, SIGNAL("valueChanged(qreal)"),
                     self._triggerRepaint)
        self.connect(self._timeline, SIGNAL("finished()"), SIGNAL("finished()"))

    def start(self, prev_pixmap, next_pixmap):
        self._prev_pixmap = prev_pixmap
        self._next_pixmap = next_pixmap
        self._timeline.start()

    def stop(self):
        self._timeline.stop()

    def _triggerRepaint(self, value):
        self._blending_factor = value
        self.update()

    def paintEvent(self, event):
        QWidget.paintEvent(self, event)
        if self._timeline.state() == QTimeLine.NotRunning:  # nothing to do
            return
        p = QPainter(self)
        p.setRenderHint(QPainter.SmoothPixmapTransform, True)
        p.drawPixmap(QPoint(0, 0), self._prev_pixmap)
        p.setOpacity(self._blending_factor)
        p.drawPixmap(QPoint(0, 0), self._next_pixmap)
Exemple #7
0
class ProgressDialog(Ui_ProgressDialog, DialogBase):
    def __init__(self, publisher, plugin, parentWidget=None):
        DialogBase.__init__(self, parentWidget)
        self.setupUi(self)
        self.setObjectName("ProgressDialog")
        self.viewButton_.setEnabled(False)

        self._publisher = publisher
        self._plugin = plugin
	self._parent = parentWidget
        self._cancelled = False
        self._timeline = QTimeLine(1000*60, self)
        self._timeline.setFrameRange(0, 2*60)
        self._timeline.setLoopCount(0)
        self.progressBar_.setRange(0, 60)
        self.connect(self._timeline, QtCore.SIGNAL("frameChanged(int)"),
                     self.updateProgressBar)

        self.outputGroupBox_ = QGroupBox("Script output", None)

        self.outputTextEdit_ = QTextEdit()
        self.outputTextEdit_.setTextInteractionFlags(Qt.TextSelectableByKeyboard
                                                     | Qt.TextSelectableByMouse)
        self.outputTextEdit_.setReadOnly(True)
        self.outputTextEdit_.setTabChangesFocus(True)
        self.outputTextEdit_.setAcceptRichText(False)

        groupBoxLayout = QVBoxLayout()
        groupBoxLayout.setObjectName("groupBoxLayout")
        groupBoxLayout.setMargin(0)
        groupBoxLayout.addWidget(self.outputTextEdit_)
        self.outputGroupBox_.setLayout(groupBoxLayout)

        gridLayout = QGridLayout()
        gridLayout.setSizeConstraint(gridLayout.SetFixedSize)
        gridLayout.addWidget(self.progressLabel_, 0, 0, 1, 4)
        gridLayout.addWidget(self.progressBar_, 1, 0, 1, 4)
        gridLayout.addWidget(self.detailsCheckBox_, 2, 0)
        hSpacer = QSpacerItem(250, 10, QSizePolicy.Expanding)
        gridLayout.addItem(hSpacer, 2, 1)

        gridLayout.addWidget(self.viewButton_, 2, 2)
        gridLayout.addWidget(self.cancelButton_, 2, 3)
        gridLayout.addWidget(self.outputGroupBox_, 3, 0, 1, 4)

        self.setLayout(gridLayout)

        self.outputGroupBox_.setVisible(False)

    def updateProgressBar(self, frame):
        self.progressBar_.setValue(self.progressBar_.value() + 1)

    def on_detailsCheckBox__stateChanged(self, state):
        self.outputGroupBox_.setVisible(Qt.Checked == state)
        gridLayout = self.layout()
        if Qt.Checked == state:
            gridLayout.setSizeConstraint(gridLayout.SetMaximumSize)
            self.setSizeGripEnabled(True)
        else:
            gridLayout.setSizeConstraint(gridLayout.SetFixedSize)
            self.setSizeGripEnabled(False)

    def on_cancelButton__clicked(self, released=True):
        if not released:
            return

        if self._cancelled:
            self.reject()
            return

        self.cancelButton_.setEnabled(False)
        self.progressLabel_.setText("Cancelling...")
        self._publisher.cancel()
        self._cancelled = True
        QTimer.singleShot(5*1000, self, QtCore.SLOT("_kill()"))

    @QtCore.pyqtSignature("_kill()")
    def _cancel(self):
        self._parent.update()
        self._publisher.cancel(True)
        self.reject()

    def updatePublisherOutput(self, data):
        self.outputTextEdit_.append(data)

    def publishComplete(self, exitCode, exitStatus):
        self.progressBar_.setValue(self.progressBar_.maximum())
        self._timeline.stop()
        if self._cancelled:
            self.reject()
        self._cancelled = True
        publishSuccess = (0 == exitCode and QProcess.NormalExit == exitStatus)
        output_exists = self.__findOutput()
        self.viewButton_.setEnabled(publishSuccess and \
                                    output_exists)
        if not publishSuccess:
            self.progressLabel_.setText("Publishing failed, see script output"
                                        " for more details")
        else:
            self.progressLabel_.setText("Publishing completed")

    def __findOutput(self):
        output_exists = os.path.exists(unicode(self._outFile))
        if not output_exists:
            output_exists = self.__findInSubdir()
        if not(output_exists) and ('Dita' in self._publisher.__str__()) :
            output_exists = self.__findInLog()
        if not(output_exists) and ('Docbook' in self._publisher.__str__()) :
            output_exists = self.__findInPI()
        return output_exists

    def __findInLog(self):
        log = self.outputTextEdit_.toPlainText()
        src_filename = os.path.basename(self._publisher.attrs()['srcUri'])
        dst_filename = src_filename.split('.')[0] + "." + self._publisher.attrs()['extension']
        re_str = '\[xslt\] Processing.*?' + src_filename  + ' to (?P<outputFilename>.*?' + dst_filename + ')'
        output_re = re.compile(re_str)
        output_filename = ''
        if None != output_re.search(log):
            output_filename = output_re.search(log).group("outputFilename")
        if not output_filename:
            return False
        real_dst_dir = os.path.dirname(unicode(output_filename))
        dst_filename = os.path.join(real_dst_dir, os.path.basename(self._outFile))
        os.rename(output_filename, dst_filename)
        output_exists = os.path.exists(dst_filename)
        if output_exists:
            self._outFile = dst_filename
            self._parent.setOutputFilePath(self._outFile)
            return True
        return False

    def __findInPI(self):
        src_uri = self._publisher.attrs()['srcUri']
        grove = Grove.buildGroveFromFile(src_uri)
        xpath_value = XpathExpr("//self::processing-instruction('dbhtml')").eval(grove.document())
        dbhtml_pi = xpath_value.getNodeSet().firstNode()
        str_ = unicode(dbhtml_pi.asGrovePi().data())
        filename_re = re.compile('filename="(?P<filename>.*?\n?.*?)"')
        dir_re = re.compile('dir="(?P<dir>.*?\n?.*?)"')
        if None != filename_re.search(str_):
            filename_ = filename_re.search(str_).group("filename")
        if None != dir_re.search(str_):
            dir_ = dir_re.search(str_).group("dir")
        out_dir = os.path.dirname(self._outFile)
        combined_output_filename = os.path.join(out_dir, dir_, filename_)
        output_exists = os.path.exists(combined_output_filename)
        if output_exists:
            self._outFile = combined_output_filename
            self._parent.setOutputFilePath(self._outFile)
            return True
        return False

    def __findInSubdir(self):
        output_filename = unicode(self._outFile)
	filename_ = os.path.basename(output_filename)
        dir_ = os.path.dirname(output_filename)
	folder_name = os.path.basename(dir_)
	output_filename = os.path.join(dir_, folder_name, filename_)
	output_exists = os.path.exists(output_filename)
	if output_exists:
	    self._outFile = output_filename
            self._parent.setOutputFilePath(self._outFile)
            return True
        return False

    def on_viewButton__clicked(self, released=True):
        if not released:
            return
        self._plugin.launchViewer(os.path.abspath(self._outFile))

    def publish(self, dsi, outFile):
        if not self._publisher:
            self.updatePublisherOutput("Script is not found")
            self.publishComplete(1, QProcess.Crashed)
            return self.exec_()
        self._outFile = outFile
        self.show()
        try:
            self.progressBar_.setValue(self.progressBar_.minimum() + 1)
            self._publisher.publish(self, dsi, outFile)
            self._timeline.start()
        except PublishException, pe:
            self.updatePublisherOutput(pe.getErrorString())
        return self.exec_()
Exemple #8
0
class CanvasProps (QGraphicsItem):


    def __init__(self, parent=None, scene=None):
        
        QGraphicsItem.__init__ (self)
        
        self.parent = parent
        self.helper = self.parent.getHelper()
        
        #self.setFlags (QGraphicsItem.ItemIsSelectable)
        self.setAcceptsHoverEvents (True)
        
        self.pen_color = QPen (Qt.black, 2)
        
        self.color = QColor (Qt.white).dark (150)
        
        # init Canvas Animation Tweening
        self.timeline = QTimeLine (200)
        self.timeline.setFrameRange (0, 100)
        self.anim = QGraphicsItemAnimation ()
        self.anim.setItem (self)
        self.anim.setTimeLine (self.timeline)
        self.helper.connect (self.timeline, SIGNAL("finished()"), self.moveFurtherUp)
        self.anim_active = False
        
        #self._nodename = QGraphicsTextItem ('text '+str(self.node_id), self)
        self._nodename = QGraphicsTextItem ('', self)
        self._nodename.setPos (QPointF (18, 20))
        self._nodename.setDefaultTextColor (QColor (Qt.white).light (255))
        self._nodename.setFont (QFont ("Helvetica", 11, QFont.Bold, False))
        self._nodename.setTextWidth(120)
        self._nodename.setToolTip (self._nodename.toPlainText ())
        #self._nodename.setHtml("<h2 align=\"center\">hello</h2><h2 align=\"center\">world 1234345345</h2>123");
        
        self.props_list = []
        self.props_textItem_value_list = []
        
        self.FACTOR = 4.0
        
        self._canvas_height = 0
    
    def boundingRect (self): return QRectF (0, 0, 122, 150)
    
    def shape (self):
        
        path = QPainterPath ()
        path.addRect (0, 0, 122, 20)
        return path
    
    def paint (self, painter, option, unused_widget):
        
        if option.state & QStyle.State_Selected:
            fillColor = self.color.dark (100)
        else:
            fillColor = self.color
        
        if option.state & QStyle.State_MouseOver:
            fillColor = fillColor.light (120)
        
        if option.levelOfDetail < 0.2:
            
            if option.levelOfDetail < 0.125:
                painter.fillRect (QRectF (0, 0, 110, 70), fillColor)
                return
            
            painter.setPen   (QPen (Qt.black, 0))
            painter.setBrush (fillColor)
            painter.drawRect (0, 0, 120, 20)
            return
        
        oldPen = painter.pen ()
        pen = oldPen
        width = 0
        
        if option.state & QStyle.State_Selected:
            width += 2
        
        pen.setWidth (width)
        if option.state & QStyle.State_Sunken:
            level = 120
        else:
            level = 100
        
        painter.setBrush (QBrush (fillColor.dark (level)))
        #painter.drawRoundRect (QRect (0, 0, 80, 34+self.height), 20)
        painter.drawRect (QRect (0, 20, 120, 30+9*self._canvas_height))
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    def addProp (self, prop_name, prop_value):
        
        i = len (self.props_list)
        self.props_list.append  (QGraphicsTextItem (prop_name + ' : ', self))
        self.props_textItem_value_list.append (CustomFloatingText (prop_value, self))
        
        # (1) adding the prop's name.
        self.props_list[i].setPos (QPointF (7, 35+i*10))
        self.props_list[i].setDefaultTextColor (QColor (Qt.white).light (255))
        self.props_list[i].setFont (QFont ("Helvetica", 9, QFont.StyleItalic, False))
        self.props_list[i].setTextWidth (55)
        self.props_list[i].setToolTip (self.props_list[i].toPlainText ())
        
        # (2) adding the prop's value.
        self.props_textItem_value_list[i].setTextInteractionFlags (Qt.TextEditable)
        self.props_textItem_value_list[i].setPos (QPointF (55, 35+i*10))
        self.props_textItem_value_list[i].setDefaultTextColor (QColor (Qt.white).light (255))
        self.props_textItem_value_list[i].setFont (QFont ("Helvetica", 9, QFont.StyleNormal, False))
        self.props_textItem_value_list[i].setTextWidth (55)
        
        receiver = lambda value: self.parent.listenToChangedPropsValues (prop_name, value)
        self.helper.connect (self.props_textItem_value_list[i], SIGNAL ("textChanged(QString)"), receiver)
    
    def getProps (self):
        
        tmp_list = []
        
        l = len (self.props_list)
        for i in range (0, l):
            tmp_list[i] = [self.props_list[i].toPlainText(), self.props_textItem_value_list[i].toPlainText()]
        
        return tmp_list
    
    def setTitle (self, title): self._nodename.setPlainText (title)
    
    def setCanvasHeightInUnits (self, ch): self._canvas_height = ch
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    def moveDown (self, canvas_height_in_units):
        
        self.anim_active  = True
        self.upwards_flag = False
        
        self.canvas_height = canvas_height_in_units
        
        self.timeline.stop ()
        
        self.anim.setPosAt (0, QPointF(0, 1+(self.canvas_height+1)*self.FACTOR))
        self.anim.setPosAt (1, QPointF(0, 1+(self.canvas_height+2)*self.FACTOR))
        
        self.timeline.start ()
        self.update ()
    
    def moveUp (self, canvas_height_in_units):
        
        if self.anim_active == False:
            
            self.anim_active  = True
            self.upwards_flag = True
            
            self.canvas_height = canvas_height_in_units
            
            self.timeline.stop ()
            
            self.anim.setPosAt (0, QPointF(0, 1+(self.canvas_height+1)*self.FACTOR))
            self.anim.setPosAt (1, QPointF(0, 1+(self.canvas_height)  *self.FACTOR))
            
            self.timeline.start ()
            self.update ()
    
    # this method double-checks whether the canvas needs to be further up as a
    # result of receiving other asynchronous "delete link" SIGNALs while moving up.
    def moveFurtherUp (self):
        
        self.anim_active = False
        
        if self.upwards_flag==True:
            
            if self.parent.getMaxLen() < self.canvas_height:
                self.moveUp (self.canvas_height-1)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    def hoverEnterEvent (self, e):
        
        self._nodename.setToolTip (self._nodename.toPlainText ())
        QGraphicsItem.hoverEnterEvent (self, e)
    
    '''
Exemple #9
0
class ItemMovel(QGraphicsWidget):
    rectChanged = pyqtSignal()

    def __init__(self, moveX=True, moveY=True, rect=QRectF(0, 0, 30, 30), parent=None):
        super().__init__(parent)

        self._movel = Movel(moveX, moveY, self)
        self.installEventFilter(self._movel)

        self._newPos = QPointF()
        self._oldPos = QPointF()

        self._rect = QRectF()
        self._newRect = QRectF()
        self._oldRect = QRectF()

        self._timePos = QTimeLine(1000)
        self._timePos.setCurveShape(QTimeLine.EaseInOutCurve)
        self._timePos.valueChanged.connect(self._atualizaPos)

        self._timeRect = QTimeLine(1000)
        self._timeRect.valueChanged.connect(self._atualizaRect)

        self.setTamanho(rect)

    def setMoveXY(self, x, y):
        self._movel.setMoveXY(x, y)

    def getRect(self):
        return self._rect

    def setRect(self, rect):
        self._rect = rect
        self._atualizaGeometria()

    def boundingRect(self):
        return self._rect.adjusted(-1, -1, 1, 1)

    def altura(self):
        return self._newRect.height()

    def _atualizaPos(self, t):
        # Funcao da curva que parametriza um segmento AB
        # C(t) = A + (B - A)*t
        pos = self._oldPos + (self._newPos - self._oldPos) * t

        self.setPos(pos)
        self._atualizaGeometria()

    def _atualizaRect(self, t):
        oldP1 = self._oldRect.topLeft()
        oldP2 = self._oldRect.bottomRight()

        newP1 = self._newRect.topLeft()
        newP2 = self._newRect.bottomRight()

        p1 = oldP1 + (newP1 - oldP1) * t
        p2 = oldP2 + (newP2 - oldP2) * t

        self.setRect(QRectF(p1, p2))

    def _atualizaGeometria(self):
        self.setGeometry(QRectF(self.pos(), self.pos() + self._rect.bottomRight()))

    def goto(self, pos):
        if self.pos() == pos:
            return

        if self._timePos.state() == QTimeLine.Running:
            self._timePos.stop()

        self._oldPos = self.pos()
        self._newPos = pos
        self._timePos.start()

    def setTamanho(self, tam):
        if self._rect == tam:
            return

        if self._timeRect.state() == QTimeLine.Running:
            self._timeRect.stop()

        self._oldRect = self._rect
        self._newRect = tam
        self._timeRect.start()
        self.rectChanged.emit()

    def resize(self, size):
        if isinstance(size, QRect):
            size = size.size()

        self.setTamanho(QRectF(0, 0, size.width() - 3, self._newRect.height()))

    def paint(self, painter, widget, option):
        if self._timePos.state() == QTimeLine.Running:
            currentValue = self._timePos.currentValue()
            nextValue = self._timePos.valueForTime(self._timePos.currentTime() + 100)
            painter.setBrush(QColor(255, 0, 0, (nextValue - currentValue) * 150))

        painter.drawRoundedRect(self._rect, 7, 5)
class ProgressDialog(Ui_ProgressDialog, DialogBase):
    def __init__(self, publisher, plugin, parentWidget=None):
        DialogBase.__init__(self, parentWidget)
        self.setupUi(self)
        self.setObjectName("ProgressDialog")
        self.viewButton_.setEnabled(False)

        self._publisher = publisher
        self._plugin = plugin
        self._parent = parentWidget
        self._cancelled = False
        self._timeline = QTimeLine(1000 * 60, self)
        self._timeline.setFrameRange(0, 2 * 60)
        self._timeline.setLoopCount(0)
        self.progressBar_.setRange(0, 60)
        self.connect(self._timeline, QtCore.SIGNAL("frameChanged(int)"),
                     self.updateProgressBar)

        self.outputGroupBox_ = QGroupBox("Script output", None)

        self.outputTextEdit_ = QTextEdit()
        self.outputTextEdit_.setTextInteractionFlags(
            Qt.TextSelectableByKeyboard
            | Qt.TextSelectableByMouse)
        self.outputTextEdit_.setReadOnly(True)
        self.outputTextEdit_.setTabChangesFocus(True)
        self.outputTextEdit_.setAcceptRichText(False)

        groupBoxLayout = QVBoxLayout()
        groupBoxLayout.setObjectName("groupBoxLayout")
        groupBoxLayout.setMargin(0)
        groupBoxLayout.addWidget(self.outputTextEdit_)
        self.outputGroupBox_.setLayout(groupBoxLayout)

        gridLayout = QGridLayout()
        gridLayout.setSizeConstraint(gridLayout.SetFixedSize)
        gridLayout.addWidget(self.progressLabel_, 0, 0, 1, 4)
        gridLayout.addWidget(self.progressBar_, 1, 0, 1, 4)
        gridLayout.addWidget(self.detailsCheckBox_, 2, 0)
        hSpacer = QSpacerItem(250, 10, QSizePolicy.Expanding)
        gridLayout.addItem(hSpacer, 2, 1)

        gridLayout.addWidget(self.viewButton_, 2, 2)
        gridLayout.addWidget(self.cancelButton_, 2, 3)
        gridLayout.addWidget(self.outputGroupBox_, 3, 0, 1, 4)

        self.setLayout(gridLayout)

        self.outputGroupBox_.setVisible(False)

    def updateProgressBar(self, frame):
        self.progressBar_.setValue(self.progressBar_.value() + 1)

    def on_detailsCheckBox__stateChanged(self, state):
        self.outputGroupBox_.setVisible(Qt.Checked == state)
        gridLayout = self.layout()
        if Qt.Checked == state:
            gridLayout.setSizeConstraint(gridLayout.SetMaximumSize)
            self.setSizeGripEnabled(True)
        else:
            gridLayout.setSizeConstraint(gridLayout.SetFixedSize)
            self.setSizeGripEnabled(False)

    def on_cancelButton__clicked(self, released=True):
        if not released:
            return

        if self._cancelled:
            self.reject()
            return

        self.cancelButton_.setEnabled(False)
        self.progressLabel_.setText("Cancelling...")
        self._publisher.cancel()
        self._cancelled = True
        QTimer.singleShot(5 * 1000, self, QtCore.SLOT("_kill()"))

    @QtCore.pyqtSignature("_kill()")
    def _cancel(self):
        self._parent.update()
        self._publisher.cancel(True)
        self.reject()

    def updatePublisherOutput(self, data):
        self.outputTextEdit_.append(data)

    def publishComplete(self, exitCode, exitStatus):
        self.progressBar_.setValue(self.progressBar_.maximum())
        self._timeline.stop()
        if self._cancelled:
            self.reject()
        self._cancelled = True
        publishSuccess = (0 == exitCode and QProcess.NormalExit == exitStatus)
        output_exists = self.__findOutput()
        self.viewButton_.setEnabled(publishSuccess and \
                                    output_exists)
        if not publishSuccess:
            self.progressLabel_.setText("Publishing failed, see script output"
                                        " for more details")
        else:
            self.progressLabel_.setText("Publishing completed")

    def __findOutput(self):
        output_exists = os.path.exists(unicode(self._outFile))
        if not output_exists:
            output_exists = self.__findInSubdir()
        if not (output_exists) and ('Dita' in self._publisher.__str__()):
            output_exists = self.__findInLog()
        if not (output_exists) and ('Docbook' in self._publisher.__str__()):
            output_exists = self.__findInPI()
        return output_exists

    def __findInLog(self):
        log = self.outputTextEdit_.toPlainText()
        src_filename = os.path.basename(self._publisher.attrs()['srcUri'])
        dst_filename = src_filename.split(
            '.')[0] + "." + self._publisher.attrs()['extension']
        re_str = '\[xslt\] Processing.*?' + src_filename + ' to (?P<outputFilename>.*?' + dst_filename + ')'
        output_re = re.compile(re_str)
        output_filename = ''
        if None != output_re.search(log):
            output_filename = output_re.search(log).group("outputFilename")
        if not output_filename:
            return False
        real_dst_dir = os.path.dirname(unicode(output_filename))
        dst_filename = os.path.join(real_dst_dir,
                                    os.path.basename(self._outFile))
        os.rename(output_filename, dst_filename)
        output_exists = os.path.exists(dst_filename)
        if output_exists:
            self._outFile = dst_filename
            self._parent.setOutputFilePath(self._outFile)
            return True
        return False

    def __findInPI(self):
        src_uri = self._publisher.attrs()['srcUri']
        grove = Grove.buildGroveFromFile(src_uri)
        xpath_value = XpathExpr(
            "//self::processing-instruction('dbhtml')").eval(grove.document())
        dbhtml_pi = xpath_value.getNodeSet().firstNode()
        str_ = unicode(dbhtml_pi.asGrovePi().data())
        filename_re = re.compile('filename="(?P<filename>.*?\n?.*?)"')
        dir_re = re.compile('dir="(?P<dir>.*?\n?.*?)"')
        if None != filename_re.search(str_):
            filename_ = filename_re.search(str_).group("filename")
        if None != dir_re.search(str_):
            dir_ = dir_re.search(str_).group("dir")
        out_dir = os.path.dirname(self._outFile)
        combined_output_filename = os.path.join(out_dir, dir_, filename_)
        output_exists = os.path.exists(combined_output_filename)
        if output_exists:
            self._outFile = combined_output_filename
            self._parent.setOutputFilePath(self._outFile)
            return True
        return False

    def __findInSubdir(self):
        output_filename = unicode(self._outFile)
        filename_ = os.path.basename(output_filename)
        dir_ = os.path.dirname(output_filename)
        folder_name = os.path.basename(dir_)
        output_filename = os.path.join(dir_, folder_name, filename_)
        output_exists = os.path.exists(output_filename)
        if output_exists:
            self._outFile = output_filename
            self._parent.setOutputFilePath(self._outFile)
            return True
        return False

    def on_viewButton__clicked(self, released=True):
        if not released:
            return
        self._plugin.launchViewer(os.path.abspath(self._outFile))

    def publish(self, dsi, outFile):
        if not self._publisher:
            self.updatePublisherOutput("Script is not found")
            self.publishComplete(1, QProcess.Crashed)
            return self.exec_()
        self._outFile = outFile
        self.show()
        try:
            self.progressBar_.setValue(self.progressBar_.minimum() + 1)
            self._publisher.publish(self, dsi, outFile)
            self._timeline.start()
        except PublishException, pe:
            self.updatePublisherOutput(pe.getErrorString())
        return self.exec_()
Exemple #11
0
class HookBox0 (QGraphicsItem):


    def __init__(self, parent=None, scene=None):
        
        QGraphicsItem.__init__ (self)
        
        self.helper = None
        self.parent = parent
        
        self.setFlags (QGraphicsItem.ItemIsSelectable)
        self.setAcceptsHoverEvents (True)
        
        self.pen_color = QPen (Qt.black, 2)
        
        self.socket_id = None
        self.hookType  = None
        self.hookName  = ''
        
        # init Hook Animation Tweening
        self.timeline = QTimeLine (200)
        self.timeline.setFrameRange (0, 100)
        self.anim = QGraphicsItemAnimation ()
        self.anim.setItem (self)
        self.anim.setTimeLine (self.timeline)
        self.parent.helper.connect (self.timeline, SIGNAL("finished()"), self.moveFurtherUp)
        self.anim_active = False
    
    def setTextfield (self):
        
        tx = 8
        
        self._text_item = GText (self.hookName, self)
        self._text_item.setDefaultTextColor (Qt.black)
        self._text_item.setEnabled (False)
        
        if self.hookType=='out' :
            tx=-50
            tmp0 = QTextBlockFormat ()
            tmp0.setAlignment (Qt.AlignRight)
            tmp = QTextCursor ()
            tmp.setBlockFormat (tmp0)
            self._text_item.setTextCursor (tmp)
        
        self._text_item.setPos (QPointF (tx, -5))
        self._text_item.setFont (QFont ("Geneva", 8, QFont.AllLowercase, False))
        self._text_item.setTextWidth (65)
    
    def boundingRect (self): return QRectF (0, 0, 12, 12)
    
    def shape (self):
        
        path = QPainterPath ()
        path.addRect (2, 2, 10, 10)
        return path
    
    def paint (self, painter, option, unused_widget):
        
        painter.setBrush (QBrush (Qt.white))
        painter.setPen   (self.pen_color)
        
        painter.drawEllipse (1, 1, 8 ,8)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    def moveDown (self):
        
        self.anim_active = True
        self.up_flag=False
        
        self.timeline.stop ()
        self.hook_height = (self.pos_in_list-2)*10
        self.anim.setPosAt (0, QPointF (self.x(), self.hook_height))
        self.hook_height += 10
        self.anim.setPosAt (1, QPointF (self.x(), self.hook_height))
        self.timeline.start ()
        self.update ()
    
    def moveUp (self):
        
        if self.anim_active == False:
            
            if (self.parent.getHookPos(self)+1) < self.pos_in_list: # this check is to prevent the hooks with unchanged position from moving up.
            
                self.anim_active = True
                self.up_flag=True
                
                self.timeline.stop ()
                self.pos_in_list -= 1
                self.hook_height = float(self.y())
                self.anim.setPosAt (0, QPointF (self.x(), self.hook_height))
                self.hook_height -= 10
                self.anim.setPosAt (1, QPointF (self.x(), self.hook_height))
                self.timeline.start ()
                self.update ()
    
    # this method double-checks whether the hook needs to move up again as a result
    # of receiving other asynchronous "delete link" SIGNALs while moving up.
    def moveFurtherUp (self):
        
        self.anim_active = False
        
        if self.up_flag==True and self.parent.getHookPos(self)!=None: # it can happen to be None in the case the Hook gets only switched off instead of properly erased.
                        
            if (self.parent.getHookPos(self)+1) < self.pos_in_list:
                self.moveUp ()
    
    def switchOffHook (self, node_id, socket_id):
        
        if self.socket_id==socket_id:
                        
            self.parent.scrollRestOfHooksUp (self.hookType)
            self.setVisible (False)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    def hoverEnterEvent (self, e):
        
        self.pen_color = QPen (Qt.red, 2)
        self._text_item.setDefaultTextColor (Qt.red)
                
        # records the node_id in the helper's attribute.
        self.comm.setHoveredSocketId (self.socket_id)
        
        # deal with the harpoon.
        if not self.helper.isTimerEnded():
            self.setSelected (True)
            self.helper.getGraphView().addLinkAndWirePressBtnListener ()
        
        #self._text_item.setToolTip (self._text_item.toPlainText ())
        QGraphicsItem.hoverEnterEvent (self, e)
    
    def hoverLeaveEvent (self, e):
        
        self.pen_color = QPen (Qt.black, 2)
        self._text_item.setDefaultTextColor (Qt.black)
        
        # records the node_id in the helper's attribute.
        self.comm.setHoveredSocketId (None)
        
        QGraphicsItem.hoverLeaveEvent (self, e)
    
    def mousePressEvent (self, e):
        
        self.harpoon.setInitPos (self.pos()+self.parent.pos())
        self.harpoon.setVisible (True)
        
        self.harpoon.update ()
        QGraphicsItem.mousePressEvent (self, e)
    
    def mouseMoveEvent (self, e):
        
        self.harpoon.setEndPos (self.pos()+e.pos()+self.parent.pos())
        
        self.harpoon.update ()
        QGraphicsItem.mouseMoveEvent (self, e)
    
    def mouseReleaseEvent (self, e):
        
        self.harpoon.setVisible (False)
                
        self.helper.initAndStartTimer ()
        
        QGraphicsItem.mouseReleaseEvent (self, e)
    
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    def getAbsPos (self): return self.pos()+self.parent.pos()
    
    def setSocketId (self, socket_id) : self.socket_id = socket_id
    def getSocketId (self): return self.socket_id
    
    def getHookType (self): return self.hookType
    def setHookType (self, htype): self.hookType = htype
    
    def setHelper (self, helper):
        
        self.helper  = helper
        self.comm    = self.helper.getGraph().getComm()
        self.harpoon = self.helper.getHarpoon()
    
    def setHookName (self, name0):
        
        self.hookName = name0
        self.setTextfield()
    
    def setPosInList (self, pos):
        
        self.pos_in_list=pos