Exemple #1
0
class FaderWidget(QWidget):
    def __init__(self, old_widget, new_widget):
        QWidget.__init__(self, new_widget)

        self.old_pixmap = QPixmap(new_widget.size())
        old_widget.render(self.old_pixmap)
        self.pixmap_opacity = 1.0

        self.timeline = QTimeLine()
        self.timeline.valueChanged.connect(self.animate)
        self.timeline.finished.connect(self.close)
        self.timeline.setDuration(555)
        self.timeline.start()

        self.resize(new_widget.size())
        self.show()

    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        painter.setOpacity(self.pixmap_opacity)
        painter.drawPixmap(0, 0, self.old_pixmap)
        painter.end()

    def animate(self, value):
        self.pixmap_opacity = 1.0 - value
        self.repaint()
Exemple #2
0
class FaderWidget(QWidget):

    def __init__(self, old_widget, new_widget):
        QWidget.__init__(self, new_widget)

        self.old_pixmap = QPixmap(new_widget.size())
        old_widget.render(self.old_pixmap)
        self.pixmap_opacity = 1.0

        self.timeline = QTimeLine()
        self.timeline.valueChanged.connect(self.animate)
        self.timeline.finished.connect(self.close)
        self.timeline.setDuration(500)
        self.timeline.start()

        self.resize(new_widget.size())
        self.show()

    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        painter.setOpacity(self.pixmap_opacity)
        painter.drawPixmap(0, 0, self.old_pixmap)
        painter.end()

    def animate(self, value):
        self.pixmap_opacity = 1.0 - value
        self.repaint()
class Meterbar(Button):
    def __init__(self, max=255, filename=None, width=None, height=None, x=0, y=0, pixmap=None, group=None, pos=None, size=None, padding=None):
        Button.__init__(self, filename, width, height, x, y, pixmap, group, pos, size, padding)
        self.max = max
        self.outer = QGraphicsRectItem(x,y,width,max + 2)
        self.outer.setPen(QPen(QColor(Qt.black), 1, Qt.SolidLine))
        self.outer.setBrush(Qt.green)
#         self.outer.hide()
        self.inner = QGraphicsRectItem(x + 1,y + 1,width - 2,max)
        self.inner.setPen(QPen(QColor(Qt.green), 1, Qt.SolidLine))
        self.inner.setBrush(Qt.blue)
        self.items = [self.outer, self.inner]
        self.current = 255
        self.effect = QGraphicsDropShadowEffect()
        self.effect.setOffset(0, 0)
        self.effect.setBlurRadius(0)
        self.effect.setColor(Qt.green)
        self.item = self.outer
        self.addEffect('shadow', self.effect, True)
        self.addAnimation('glow', Glow(15, 300, self, maxRadius=80, minRadius=5))
#         self.test(10)
    
    def test(self, x):
        self.tl = QTimeLine(10000)
        self.tl.setFrameRange(0, 10000)
        self.a = QGraphicsItemAnimation()
        self.a.setItem(self.inner)
        self.a.setTimeLine(self.tl)
#         self.a.setPosAt(0, QPointF(self.getX(), self.current))
#         self.a.setTranslationAt(1, self.getX(), self.getY() + self.max - x + 1)
        self.a.setScaleAt(0, 1, 1)
        self.a.setScaleAt(1, 1, 0.1)
        self.current = x
        self.tl.start()
        
    def update(self, x):
        x2 = 1 - (float(x) * 1.0 / float(self.max))
#         print x
#         return
        self.tl = QTimeLine(10)
        self.tl.setFrameRange(0, 10)
        self.a = QGraphicsItemAnimation()
        self.a.setItem(self.inner)
        self.a.setTimeLine(self.tl)
#         self.a.setPosAt(0, QPointF(self.getX(), self.current))
#         self.a.setTranslationAt(1, self.getX(), self.getY() + self.max - x + 1)
        self.a.setScaleAt(0, 1, self.current)
        self.a.setScaleAt(1, 1, x2)
        self.current = x
        self.tl.start()
        if x > 3 :
            self.play('glow')
        
    def setScene(self, scene):
        self.scene = scene
        for item in self.items :
            self.scene.addItem(item)
class FaceButtonsView(QGraphicsView):

    def __init__(self, *args):
        QGraphicsView.__init__(self, *args)
        self.move(170, 90)
        self.btnSize = 40
        self.padding = 5
        self.setMaximumHeight(self.btnSize * 4)
        self.setMaximumWidth(self.btnSize * 4)
        self.setMinimumHeight(self.btnSize * 4)
        self.setMinimumWidth(self.btnSize * 4)
        self.adjustSize()
        self.setStyleSheet('background-color:transparent; border-width: 0px; border: 0px;')
        self.scene = QGraphicsScene(self)
        self.psButtons = QPixmap(os.getcwd() + '/../icons/PS3_Buttons.png')
        self.triangle = self.psButtons.copy(0, 0, 220, 225)
        self.triangle = self.triangle.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.square = self.psButtons.copy(220, 0, 220, 225)
        self.square = self.square.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.circle = self.psButtons.copy(440, 0, 220, 225)
        self.circle = self.circle.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.cross = self.psButtons.copy(660, 0, 220, 225)
        self.cross = self.cross.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.triangleItem = QGraphicsPixmapItem(self.triangle)
        self.triangleItem.setOffset(QPointF(self.btnSize + self.padding, 0))
        self.scene.addItem(self.triangleItem)
        self.squareItem = QGraphicsPixmapItem(self.square)
        self.squareItem.setOffset(QPointF(0, self.btnSize + self.padding))
        self.scene.addItem(self.squareItem)
        self.circleItem = QGraphicsPixmapItem(self.circle)
        self.circleItem.setOffset(QPointF(self.btnSize * 2 + self.padding * 2, self.btnSize + self.padding))
        self.scene.addItem(self.circleItem)
        self.crossItem = QGraphicsPixmapItem(self.cross)
        self.crossItem.setOffset(QPointF(self.btnSize + self.padding, self.btnSize * 2 + self.padding * 2))
        self.scene.addItem(self.crossItem)
        self.effect = QGraphicsDropShadowEffect()
        self.effect.setOffset(0, 0)
        self.effect.setBlurRadius(20)
        self.effect.setColor(Qt.green)
        self.triangleItem.setGraphicsEffect(self.effect)
        self.setScene(self.scene)
        self.tl2 = QTimeLine(10000)
        self.tl2.setFrameRange(0, 10000)
        self.t = QGraphicsItemAnimation()
        self.t.setItem(self.triangleItem)
        self.t.setTimeLine(self.tl2)
        self.tl2.connect(self.tl2, SIGNAL('frameChanged(int)'), self.updateEffect)
        self.effectd = 3
        self.tl2.start()

    def updateEffect(self):
        if self.effect.blurRadius() > 50:
            self.effectd = -3
        elif self.effect.blurRadius() < 5:
            self.effectd = 3
        self.effect.setBlurRadius(self.effect.blurRadius() + self.effectd)
class DpadView(QGraphicsView):

    def __init__(self, *args):
        QGraphicsView.__init__(self, *args)
        self.move(2, 90)
        self.btnSize = 75
        self.padding = -35
        self.setMaximumHeight(self.btnSize * 2 + 20)
        self.setMaximumWidth(self.btnSize * 2 + 20)
        self.setMinimumHeight(self.btnSize * 2 + 20)
        self.setMinimumWidth(self.btnSize * 2 + 20)
        self.adjustSize()
        self.setStyleSheet('background-color:transparent; border-width: 0px; border: 0px;')
        self.scene = QGraphicsScene(self)
        self.left = QPixmap(os.getcwd() + '/../icons/left.png')
        self.left = self.left.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.right = QPixmap(os.getcwd() + '/../icons/right.png')
        self.right = self.right.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.up = QPixmap(os.getcwd() + '/../icons/up.png')
        self.up = self.up.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.down = QPixmap(os.getcwd() + '/../icons/down.png')
        self.down = self.down.scaled(self.btnSize, self.btnSize, Qt.KeepAspectRatio)
        self.leftItem = QGraphicsPixmapItem(self.left)
        self.leftItem.setOffset(QPointF(0, self.btnSize + self.padding))
        self.scene.addItem(self.leftItem)
        self.rightItem = QGraphicsPixmapItem(self.right)
        self.rightItem.setOffset(QPointF(self.btnSize * 2 + self.padding * 2, self.btnSize + self.padding))
        self.scene.addItem(self.rightItem)
        self.upItem = QGraphicsPixmapItem(self.up)
        self.upItem.setOffset(QPointF(self.btnSize + self.padding, 0))
        self.scene.addItem(self.upItem)
        self.downItem = QGraphicsPixmapItem(self.down)
        self.downItem.setOffset(QPointF(self.btnSize + self.padding, self.btnSize * 2 + self.padding * 2))
        self.scene.addItem(self.downItem)
        self.effect = QGraphicsDropShadowEffect()
        self.effect.setOffset(0, 0)
        self.effect.setBlurRadius(20)
        self.effect.setColor(Qt.green)
        self.downItem.setGraphicsEffect(self.effect)
        self.setScene(self.scene)
        self.tl2 = QTimeLine(10000)
        self.tl2.setFrameRange(0, 10000)
        self.t = QGraphicsItemAnimation()
        self.t.setItem(self.downItem)
        self.t.setTimeLine(self.tl2)
        self.tl2.connect(self.tl2, SIGNAL('frameChanged(int)'), self.updateEffect)
        self.effectd = 3
        self.tl2.start()

    def updateEffect(self):
        if self.effect.blurRadius() > 50:
            self.effectd = -3
        elif self.effect.blurRadius() < 5:
            self.effectd = 3
        self.effect.setBlurRadius(self.effect.blurRadius() + self.effectd)
class Joystick(Button):
    def __init__(self, outer, inner, filename=None, width=None, height=None, x=0, y=0, pixmap=None, group=None, pos=None, size=None, padding=None):
        Button.__init__(self, filename, width, height, x, y, pixmap, group, pos, size, padding)
        self.outer = outer
        self.inner = inner
        self.innerRange = 48
        self.inputRange = 256
        self.thresh = 5
        self.outerCircle = QGraphicsEllipseItem(self.getX(), self.getY(), self.outer, self.outer)
        self.outerCircle.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
        self.outerCircle.setBrush(Qt.gray)
        self.innerCircle = QGraphicsEllipseItem(self.getX() + self.outer / 2 - self.inner / 2, self.getY() + self.outer / 2 - self.inner / 2, self.inner, self.inner)
        self.innerCircle.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
        self.innerCircle.setBrush(Qt.lightGray)
        self.currentX = 0
        self.currentY = 0
        self.items = [self.outerCircle, self.innerCircle]
    def getItems(self):
        return self.items
    def setScene(self, scene):
        self.scene = scene
        for item in self.items :
            self.scene.addItem(item)
    def update(self,x,y,z):
#         y = y - sqrt(x + y) if x > 0 else y
#         x = x - sqrt(x + y) if y > 0 else x
        x2 = x * self.innerRange / self.inputRange - self.innerRange / 2
        y2 = y * self.innerRange / self.inputRange - self.innerRange / 2
        x2 = x2 - sqrt(abs(y2)) if x2 >= 0 else x2 + sqrt(abs(y2))
        y2 = y2 - sqrt(abs(x2)) if y2 >= 0 else y2 + sqrt(abs(x2)) 
        if self.inputRange / 2 - self.thresh <= x <= self.inputRange / 2 + self.thresh:
            x2 = 0
        if self.inputRange / 2 - self.thresh <= y <= self.inputRange / 2 + self.thresh:
            y2 = 0
        self.tl = QTimeLine(10)
        self.tl.setFrameRange(0, 10)
        self.a = QGraphicsItemAnimation()
        self.a.setItem(self.innerCircle)
        self.a.setTimeLine(self.tl)
        self.a.setPosAt(0, QPointF(self.currentX, self.currentY))
        self.a.setTranslationAt(1, x2, y2)
        if z:
            self.innerCircle.setPen(QPen(QColor(Qt.white), 1, Qt.SolidLine))
            self.innerCircle.setBrush(QColor(200, 225, 3))
        else:
            self.innerCircle.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
            self.innerCircle.setBrush(Qt.lightGray)
        self.currentX = x2
        self.currentY = y2
        self.tl.start()
class SingleJoystickView(QGraphicsView):

    def __init__(self, *args):
        QGraphicsView.__init__(self, *args)
        self.outerD = 125
        self.innerD = 25
        self.innerRange = 50
        self.inputRange = 256
        self.thresh = 3
        self.worker = JoystickThread()
        self.worker.valueUpdated.connect(self.moveJoystick)
        self.worker.start()
        self.move(30, 100)
        self.setContentsMargins(0, 0, 0, 0)
        self.setMaximumHeight(140)
        self.setMaximumWidth(140)
        self.adjustSize()
        self.scene = QGraphicsScene(self)
        self.outerCircle = QGraphicsEllipseItem(0, 0, self.outerD, self.outerD)
        self.outerCircle.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
        self.outerCircle.setBrush(Qt.gray)
        self.innerCircle = QGraphicsEllipseItem(self.outerD / 2 - self.innerD / 2, self.outerD / 2 - self.innerD / 2, self.innerD, self.innerD)
        self.innerCircle.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
        self.innerCircle.setBrush(Qt.lightGray)
        self.scene.addItem(self.outerCircle)
        self.scene.addItem(self.innerCircle)
        self.setScene(self.scene)
        self.setStyleSheet('background-color:transparent;color:red')
        self.currentX = 0
        self.currentY = 0

    def moveJoystick(self, x, y):
        x2 = x * self.innerRange / self.inputRange - self.innerRange / 2
        y2 = y * self.innerRange / self.inputRange - self.innerRange / 2
        if -self.thresh <= x2 <= self.thresh:
            x2 = 0
        if -self.thresh <= y2 <= self.thresh:
            y2 = 0
        self.tl = QTimeLine(10)
        self.tl.setFrameRange(0, 10)
        self.a = QGraphicsItemAnimation()
        self.a.setItem(self.innerCircle)
        self.a.setTimeLine(self.tl)
        self.a.setPosAt(0, QPointF(self.currentX, self.currentY))
        self.a.setTranslationAt(1, x2, y2)
        self.currentX = x2
        self.currentY = y2
        self.tl.start()
        print 'x:%d y:%d' % (x2, y2)
Exemple #8
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
Exemple #10
0
class AnimatedGraphicsSvgItem(QGraphicsSvgItem):
    def __init__(self, file, parent = None):
        QGraphicsSvgItem.__init__(self, file, parent)
        self.animation = QGraphicsItemAnimation()
        self.animation.setItem(self)
        self.timeline = QTimeLine(300)
        self.animation.setTimeLine(self.timeline)
    def setMatrix(self, matrix):
        self.matrix = matrix
        QGraphicsSvgItem.setMatrix(self, matrix)
    def show(self):
        self.scale(0.0, 0.0)
        self.animation.setPosAt(0.0, QPointF(self.matrix.dx()+self.boundingRect().width()/8, self.matrix.dy()+self.boundingRect().height()/8))
        self.animation.setPosAt(1.0, QPointF(self.matrix.dx(), self.matrix.dy()))
        self.animation.setScaleAt(0.0, 0.25, 0.25)
        self.animation.setScaleAt(1.0, 0.5, 0.5)
        self.timeline.start()
        QGraphicsSvgItem.show(self)
Exemple #11
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 #12
0
class StackFader(QWidget):
    """
    A widget that creates smooth transitions in a QStackedWidget.
    """
    def __init__(self, stackedWidget):
        QWidget.__init__(self, stackedWidget)
        self.curIndex = None
        self.timeline = QTimeLine()
        self.timeline.setDuration(333)
        self.timeline.finished.connect(self.hide)
        self.timeline.valueChanged.connect(self.animate)
        stackedWidget.currentChanged.connect(self.start)
        self.hide()
    
    def start(self, index):
        if self.curIndex is not None:
            stack = self.parent()
            old, new = stack.widget(self.curIndex), stack.widget(index)
            if old and new:
                self.old_pixmap = QPixmap(new.size())
                old.render(self.old_pixmap)
                self.pixmap_opacity = 1.0
                self.resize(new.size())
                self.timeline.start()
                self.raise_()
                self.show()
        self.curIndex = index
        
    def paintEvent(self, ev):
        painter = QPainter()
        painter.begin(self)
        painter.setOpacity(self.pixmap_opacity)
        painter.drawPixmap(0, 0, self.old_pixmap)
        painter.end()
        
    def animate(self, value):
        self.pixmap_opacity = 1.0 - value
        self.repaint()
Exemple #13
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)
class AnimatedGraphicsSvgItem(QGraphicsSvgItem):
    def __init__(self, file, parent=None):
        QGraphicsSvgItem.__init__(self, file, parent)
        self.animation = QGraphicsItemAnimation()
        self.animation.setItem(self)
        self.timeline = QTimeLine(300)
        self.animation.setTimeLine(self.timeline)

    def setMatrix(self, matrix):
        self.matrix = matrix
        QGraphicsSvgItem.setMatrix(self, matrix)

    def show(self):
        self.scale(0.0, 0.0)
        self.animation.setPosAt(
            0.0,
            QPointF(self.matrix.dx() + self.boundingRect().width() / 8,
                    self.matrix.dy() + self.boundingRect().height() / 8))
        self.animation.setPosAt(1.0, QPointF(self.matrix.dx(),
                                             self.matrix.dy()))
        self.animation.setScaleAt(0.0, 0.25, 0.25)
        self.animation.setScaleAt(1.0, 0.5, 0.5)
        self.timeline.start()
        QGraphicsSvgItem.show(self)
class ViewMain(QMainWindow):
    """This Class Provides the Graphical Interface for Game"""

    # Use Constants To Avoid Magic Numbers
    
    # Declare stack widget names
    MAIN_PAGE = 0
    SETTINGS_PAGE = 1
    GAME_PAGE = 2
    INSTRUCTIONS_PAGE = 3
    CREDITS_PAGE = 4
    STORY_PAGE = 5
    
    def __init__(self, parent=None):
        """Initialize the abstracted class instance"""
        super(ViewMain, self).__init__(parent)

        # Init Data Members
        self.gui  = Gui(self)
        self.game = None
        self.connectGui()
        self.messageFade = None

        # Dictionary of Graphics Objects
        self.graphicsObjects = {}
        
        # Overlays
        self.overlays = {}
        
        self.currStackIndex = self.MAIN_PAGE
        self.gui.soundManager.playCurrMusic()
        self.gui.soundManager.setVolume(0)
        
        self.popupTimelineStart = QTimeLine(200)
        self.popupTimelineStart.setFrameRange(0,100)
        self.popupTimelineEnd = QTimeLine(200)
        self.popupTimelineEnd.setFrameRange(0,100)
        self.popupTimelineWait = QTimeLine()
        self.popupTimelineWait.setFrameRange(0,100)
        self.popupClue = False
        
        self.toMain = False
        #self.gui.personView.centerOn(0,0)
        #self.gui.mapView.centerOn(0,0)
        
########################################
### Signals and slots connected here ###
########################################

        self.popupTimelineStart.frameChanged.connect(self.drawPopup)
        self.popupTimelineStart.finished.connect(self.popupWait)
        self.popupTimelineEnd.frameChanged.connect(self.erasePopup)   
        self.popupTimelineWait.finished.connect(self.enableErasePopup) 
    
    def connectGui(self):
        """Connect signals for Gui"""
        self.gui.actionQuit.triggered.connect(self.close)
        self.gui.quitButton.released.connect(self.close)
        self.gui.settingsButton.released.connect(self.setSettings)
        self.gui.actionSettings.triggered.connect(self.setSettings)
        self.gui.loadButton.released.connect(self.loadFileDialog)
        self.gui.actionSave_Game.triggered.connect(self.saveFileDialog)
        self.gui.doneButton.released.connect(self.goBack)
        self.gui.startButton.released.connect(self.newGame)
        self.gui.actionMain_Menu.triggered.connect(self.setMain)
        self.gui.actionHelp.triggered.connect(self.setInstructions)
        self.gui.instrButton.released.connect(self.setInstructions)
        self.gui.doneButton2.released.connect(self.goBack)
        self.gui.doneButton3.released.connect(self.goBack)
        self.gui.actionCredits.triggered.connect(self.setCredits)
        self.gui.latLongCheck.stateChanged.connect(self.latLong)
        self.gui.colorCheck.stateChanged.connect(self.colorize)
        self.gui.legendCheck.stateChanged.connect(self.legend)
        self.gui.searchButton.released.connect(self.doSearch)
        self.gui.nextButton.released.connect(self.storyButton)
        self.gui.volumeSlider.sliderMoved.connect(self.setVol)
        
    def connectGame(self):
        # character (emits when updates) , emits newpos
        # places (emits when loc added), emits loc and signal
        # - viewMain connects that signal between the location obj and 
        # - the graphics obj
        # story (emits when working on a clue for too long), emits nothing
        # story (emits signal updating search progress), emits 0-1
        # story (emits signal for message fade), emits 1-0
        self.game.places.passLoc.connect(self.addGraphicsObject)
        self.game.story.searchTime.connect(self.enableErasePopup)
        self.game.story.clueResult.connect(self.handleClueResult)
        self.game.frameTimer.timeout.connect(self.frameUpdate)

########################################
###### Custom slots defined here #######
########################################

    def setSettings(self):
        self.setStackWidgetIndex(self.SETTINGS_PAGE)
        
    def setInstructions(self):
        self.setStackWidgetIndex(self.INSTRUCTIONS_PAGE)

    def setCredits(self):
        self.setStackWidgetIndex(self.CREDITS_PAGE)
        
    def goBack(self):
        self.setStackWidgetIndex(self.gui.stackIndex)
        if self.gui.stackIndex == self.GAME_PAGE:
            self.gui.background.setPixmap(self.gui.backgroundPixmapSettings)
        else:
            self.gui.background.setPixmap(self.gui.backgroundPixmapMenu)
            #Should be something here later
    
    def loadFileDialog(self):
        
        fd = QFileDialog()
        filename = fd.getOpenFileName(None, "Load Saved Game",
                                      "saves", "MapMaster Save files (*.save)")
        
        if isfile(filename):
            self.setStackWidgetIndex(self.GAME_PAGE)
            self.game = Game() 
            self.connectGame()
            self.game.load(filename)
            debug("Initializing the saved game...")
            
            
            self.overlays['latLongOverlay'] = self.addOverlay(
                        normpath("images/latOverlay.png"))
            self.overlays['colorOverlay'] = self.addOverlay(
                        normpath("images/colorOverlay.png"))
            self.overlays['legendOverlay'] = self.addOverlay(
                        normpath("images/legendOverlay.png"))

            self.gui.scoreBox.setText((str)(self.game.story.score))
            self.gui.clueView.setText(self.game.story.currClue['text'])
            self.gui.stackIndex = self.GAME_PAGE

    def saveFileDialog(self,toMain = False):
        filename = QFileDialog.getSaveFileName(None, "Save Game", "saves", 
                                               "MapMaster Save files (*.save)")
        if filename == "":
            return False
        else:
            if ".save" not in filename:
                debug(".save is not in the file, add one..")
                filename = filename + ".save"
            debug("correctly save data to file...",filename)
            self.game.save(filename)    
               
                        
    def newGame(self):
        self.gui.background.setPixmap(self.gui.backgroundPixmapSettings)
        self.setStackWidgetIndex(self.STORY_PAGE)
        self.gui.stackIndex = self.GAME_PAGE
        
        # Create game instance and start the game
        self.game = Game()
        debug("Initialized a new game")
        self.connectGame()
        self.game.new()
        debug("Starting a new game")
        
        self.overlays['latLongOverlay'] = self.addOverlay(
                        normpath("images/latOverlay.png"))
        self.overlays['colorOverlay'] = self.addOverlay(
                        normpath("images/colorOverlay.png"))
        self.overlays['legendOverlay'] = self.addOverlay(
                        normpath("images/legendOverlay.png"))
        self.gui.clueView.setText(self.game.story.currClue['text'])
        
    def storyButton(self):
        self.setStackWidgetIndex(self.GAME_PAGE)
        
    def setMain(self):
        if (self.saveFileDialog() == False):
            pass
        else:
            self.gui.background.setPixmap(self.gui.backgroundPixmapMenu)
            self.setStackWidgetIndex(self.MAIN_PAGE)
            self.gui.stackIndex = self.MAIN_PAGE
        
    def setStackWidgetIndex(self, index):
        if index == self.MAIN_PAGE:
            self.gui.background.setPixmap(self.gui.backgroundPixmapMenu)
        else:
            self.gui.background.setPixmap(self.gui.backgroundPixmapSettings)
    
        self.gui.stackedWidget.setCurrentIndex(index)
        self.currStackIndex = index
        self.gui.soundManager.switchSongs(index)
    
    def latLong(self):
        if self.gui.latLongCheck.isChecked():
            debug("Lat/long overlay on")
        else:
            debug("Lat/long overlay off")
        self.overlays['latLongOverlay'].setVisible(
                                        self.gui.latLongCheck.isChecked())
    
    def colorize(self):
        if self.gui.colorCheck.isChecked():
            debug("Color overlay on")
        else:
            debug("Color overlay off")
        self.overlays['colorOverlay'].setVisible(
                                        self.gui.colorCheck.isChecked())
                                        
    def legend(self):
        if self.gui.legendCheck.isChecked():
            debug("Legend overlay on")
        else:
            debug("Legend overlay off")
        self.overlays['legendOverlay'].setVisible(
                                        self.gui.legendCheck.isChecked())

    def setVol(self):
        self.gui.soundManager.setVolume(self.gui.volumeSlider.sliderPosition())
        
    def doSearch(self):
        self.game.story.searchForClue(self.game.character.getCenter())
        self.popupClue = True
        self.gui.popupText.setPlainText("Searching...")
        self.popupTimelineStart.start()
        
        
    def drawPopup(self, value):
        debug("Called drawPopup")
        self.gui.popupImage.setOpacity(value/100.0)
        self.gui.popupText.setOpacity(value/100.0)
        
    def enableErasePopup(self):
        debug("Enabled erase popup")
        self.popupClue = False
        self.popupTimelineEnd.start()
        
    def erasePopup(self, value):
        debug("Called erase popup")
        self.gui.popupImage.setOpacity(1-(value/100.0))
        self.gui.popupText.setOpacity(1-(value/100.0))
        
    def popupWait(self):
        debug("Entered popupWait")
        if not self.popupClue:
            self.popupTimelineWait.start()
        
    # FIXME This needs time actions
    def handleClueResult(self, action, text):
        if action == 'ClueFound':
            #self.popupMessage("You found a clue!", 2000)
            self.gui.clueView.setText(text)
            self.gui.scoreBox.setText(`self.game.story.score`)
        elif action == 'GameOver':
            self.gui.clueView.setText(text)
        else:
            None
    
    def popupMessage(self, text, time):
        self.gui.popupText.setPlainText(text)
        self.popupTimelineWait.setDuration(time)
        self.popupTimelineStart.start()
        
    def keyPressEvent(self, event):
        """Get keyboard events no matter what widget has focus"""
        if self.game:
            self.game.keyPress(event)
    
    def keyReleaseEvent(self, event):
        """Get keyboard events no matter what widget has focus"""
        if self.game:
            key = event.key()
            if key == Qt.Key_Space or key == Qt.Key_Enter or key == Qt.Key_Return:
                self.doSearch()
            else:
                self.game.keyRelease(event)
    
    def closeEvent(self, event):
        """Remapping the close event to a message box"""
        quit_msg = "Are you sure you want to quit?"
        reply = QMessageBox()
        reply.setWindowTitle("Quit Game")
        reply.setText(quit_msg)
        reply.setStandardButtons(
            QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
        reply.setDefaultButton(QMessageBox.Save)
        ret = reply.exec_()
        
        if ret == QMessageBox.Discard:
            print "Accepting close event"
            event.accept()
        elif ret == QMessageBox.Cancel:
            event.ignore()
        else:
            if (self.saveFileDialog() == False):
                debug("Not quit yet, go back to game...")
                event.ignore()
            else:
                print "Accepting close event"
                event.accept()

    def addGraphicsObject(self, name, xval, yval, objType):
        """Add graphics object to the person veiw and map view properly and
        leave a graphics object in ViewMain to handle it. """
        debug("Receiving passLoc")
        graphic = Graphic(xval, yval, str(name), str(objType))
        graphic.createInitial(self.gui.personView, self.gui.mapView)
        self.graphicsObjects[name] = graphic
        self.game.places.locList[str(name)].changePos.connect(
                                        self.updateGraphicsObject)
        debug("Connecting Loc to Graphic for " + name)
        
        self.game.places.locList[str(name)].emitter()
        
        #self.graphicsObjects.append(graphic)
    def updateGraphicsObject(self, xpos, ypos, name):
        #debug("Updating the graphics object")
        self.graphicsObjects[name].update(xpos, ypos)
        
    def addOverlay(self, filename):
        obj = self.gui.mapView.scene.addPixmap(QPixmap(filename))
        obj.setX(-195)
        obj.setY(-250)
        obj.setVisible(False)
        return obj
        
    def frameUpdate(self):
        #debug('Frame update sent to character')
        self.game.character.frameUpdate(self.game.FRAME_RATE)
Exemple #16
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 #17
0
class MainManager(QtGui.QWidget):
    def __init__(self, parent, standAlone=True, app=None):
        QtGui.QWidget.__init__(self, parent)

        # Create the ui
        self.ui = Ui_mainManager()
        self.app = app
        self.lastEditedPackage = None
        self.lastEditedData = None
        self.lastEditedInfo = None

        # Network Manager can run as KControl Module or Standalone
        if standAlone:
            self.ui.setupUi(self)
            self.baseWidget = self
        else:
            self.ui.setupUi(parent)
            self.baseWidget = parent

        # Set visibility of indicators
        self.ui.workingLabel.hide()
        self.ui.refreshButton.hide()

        # Call Comar
        self.iface = NetworkIface()
        self.widgets = {}

        # Populate Packages
        self.packages = {}
        for package in self.iface.packages():
            self.packages[package] = self.iface.linkInfo(package)

        # Naruto
        self.animator = QTimeLine(ANIMATION_TIME, self)

        # List of functions to call after animation is finished
        self.animatorFinishHook = []

        # Let look what we can do
        self.refreshBrowser()

        # Security dialog
        self.securityDialog = SecurityDialog(parent)
        self.securityFields = []
        self.securityValues = {}

        # Nameserver dialog
        self.nameserverDialog = NameServerDialog(parent)

        # Preparing for animation
        self.ui.editBox.setMaximumHeight(TARGET_HEIGHT)
        self.lastAnimation = SHOW

        # Animator connections, Naruto loves Sakura-chan
        self.connect(self.animator, SIGNAL("frameChanged(int)"), self.animate)
        self.connect(self.animator, SIGNAL("finished()"), self.animateFinished)

        # Hide editBox when clicked Cancel*
        self.connect(self.ui.buttonCancel, SIGNAL("clicked()"), self.hideEditBox)
        self.connect(self.ui.buttonCancelMini, SIGNAL("clicked()"), self.hideEditBox)

        # Save changes when clicked Apply
        self.connect(self.ui.buttonApply, SIGNAL("clicked()"), self.applyChanges)

        # Show NameServer Settings Dialog
        self.connect(self.ui.buttonNameServer, SIGNAL("clicked()"), self.slotNameServerDialog)

        # Filter
        self.connect(self.ui.filterBox, SIGNAL("currentIndexChanged(int)"), self.filterList)

        # Refresh button for scanning remote again..
        self.connect(self.ui.refreshButton, SIGNAL("leftClickedUrl()"), self.filterESSID)

        # Security details button
        self.connect(self.ui.pushSecurity, SIGNAL("clicked()"), self.openSecurityDialog)

        # Security types
        self.connect(self.ui.comboSecurityTypes, SIGNAL("currentIndexChanged(int)"), self.slotSecurityChanged)

        # Update service status and follow Comar for sate changes
        self.getConnectionStates()

    def slotNameServerDialog(self):
        self.nameserverDialog.setHostname(self.iface.getHostname())
        self.nameserverDialog.setNameservers(self.iface.getNameservers())
        if self.nameserverDialog.exec_():
            self.iface.setHostname(self.nameserverDialog.getHostname())
            self.iface.setNameservers(self.nameserverDialog.getNameservers())

    def openSecurityDialog(self):
        self.securityDialog.setValues(self.securityValues)
        if self.securityDialog.exec_():
            self.securityValues = self.securityDialog.getValues()

    def slotSecurityChanged(self, index):
        method = str(self.ui.comboSecurityTypes.itemData(index).toString())
        if method == "none":
            # Hide security widgets
            self.ui.pushSecurity.hide()
            self.ui.lineKey.hide()
            self.ui.labelKey.hide()
            self.ui.checkShowPassword.hide()
            # Erase all security data
            self.securityValues = {}
        else:
            parameters = self.iface.authParameters(self.lastEditedPackage, method)
            if len(parameters) == 1 and parameters[0][2] in ["text", "pass"]:
                # Single text or password field, don't use dialog
                self.ui.pushSecurity.hide()
                # Show other fields
                self.ui.lineKey.show()
                self.ui.labelKey.show()
                self.ui.checkShowPassword.show()
                self.ui.labelKey.setText(parameters[0][1])
            else:
                # Too many fields, dialog required
                self.ui.pushSecurity.show()
                self.ui.lineKey.hide()
                self.ui.labelKey.hide()
                self.ui.checkShowPassword.hide()
                self.securityDialog.setFields(parameters)

    def refreshBrowser(self):
        if self.animator.state() != 0:
            # Refreshing browser when animator is active causes blindness
            if not self.refreshBrowser in self.animatorFinishHook:
                self.animatorFinishHook.append(self.refreshBrowser)
            return
        aa = time.time()
        self.ui.filterBox.clear()
        self.probedDevices = []
        menu = QtGui.QMenu(self)
        for package in self.packages:
            info = self.packages[package]
            devices = self.iface.devices(package)
            # Add filter menu entry
            if len(devices):
                self.ui.filterBox.addItem(info["name"], QVariant(package))
                if info["type"] == "wifi":
                    self.ui.filterBox.addItem(i18n("Available Profiles"), QVariant("essid"))
                    wifiScanner = WifiPopup(self)
                    self.ui.buttonScan.setMenu(wifiScanner)
            # Create devices menu entry
            if len(devices) > 0:
                # Create profile menu with current devices
                for device in devices.keys():
                    if self.packages[package]['type'] in ('net', 'wifi'):
                        menuItem = QtGui.QAction("%s - %s" % (self.packages[package]['name'], findInterface(device).name), self)
                        menuItem.setData(QVariant("%s::%s" % (package,device)))
                        self.connect(menuItem, SIGNAL("triggered()"), self.createConnection)
                        # Store a list of probed devices
                        if device not in self.probedDevices:
                            self.probedDevices.append(device)
                        menu.addAction(menuItem)
                menu.addSeparator()
            if self.packages[package]['type'] == 'dialup':
                pppMenu = QtGui.QMenu(self.packages[package]['name'], self)
                devices = self.iface.devices(package)
                for device in devices.keys():
                    menuItem = QtGui.QAction(device, self)
                    menuItem.setData(QVariant("%s::%s" % (package,device)))
                    self.connect(menuItem, SIGNAL("triggered()"), self.createConnection)
                    pppMenu.addAction(menuItem)
                menu.addMenu(pppMenu)
                menu.addSeparator()

        if len(self.packages) > 0:
            self.ui.buttonCreate.setMenu(menu)
            self.ui.filterBox.insertItem(0, i18n("All Profiles"), QVariant("all"))
        else:
            self.ui.buttonCreate.setText(i18n("No Device Found"))
            self.ui.buttonCreate.setEnabled(False)
            self.ui.filterBox.insertItem(0, i18n("No Device Found"))
            self.ui.filterBox.setEnabled(False)
        self.ui.filterBox.setCurrentIndex(0)

        # Fill the list
        self.fillProfileList()

    def filterESSID(self):
        self.filterList("essid")

    def filterList(self, id=None):
        if not id:
            filter = ""
        elif id == "essid":
            filter = "essid"
        else:
            filter = str(self.ui.filterBox.itemData(id).toString())

        def filterByScan(*args):
            # We have finished the scanning let set widgets to old states
            self.ui.profileList.setEnabled(True)
            self.ui.refreshButton.show()
            self.ui.workingLabel.hide()
            self.setCursor(Qt.ArrowCursor)

            # Update the GUI
            if self.app:
                self.app.processEvents()

            # Update List with found remote networks
            availableNetworks = {}
            for result in args[2][0]:
                availableNetworks[unicode(result['remote'])] = int(result['quality'])
            for widget in self.widgets.values():
                if widget.item.isHidden():
                    continue
                if "remote" in widget.data and unicode(widget.data["remote"]) in availableNetworks.keys():
                    widget.setSignalStrength(availableNetworks[unicode(widget.data["remote"])])
                    widget.item.setHidden(False)
                else:
                    widget.hideSignalStrength()
                    widget.item.setHidden(True)

        def setHidden(package=None, hidden=False, attr="package"):
            for widget in self.widgets.values():
                widget.hideSignalStrength()
                if not package:
                    widget.item.setHidden(False)
                    continue
                if attr == "essid" and not widget.package == 'wireless_tools':
                    widget.item.setHidden(True)
                    continue
                elif attr == "essid" and widget.package == 'wireless_tools':
                    if not widget.data.has_key("remote"):
                        widget.item.setHidden(True)
                    continue
                if getattr(widget, attr) == package:
                    widget.item.setHidden(hidden)
                else:
                    widget.item.setHidden(not hidden)

        # Set visibility of indicators
        self.ui.workingLabel.hide()
        self.ui.refreshButton.hide()
        # All profiles
        if filter == "all":
            setHidden()
        # Avaliable profiles
        elif filter == "essid":
            # We need to show user, we are working :)
            self.ui.profileList.setEnabled(False)
            self.ui.refreshButton.hide()
            self.ui.workingLabel.show()
            self.setCursor(Qt.WaitCursor)

            # Show all profiles
            setHidden()

            # Hide not usable ones
            setHidden("wireless_tools", False, "essid")

            # Update the GUI
            if self.app:
                self.app.processEvents()

            # Scan for availableNetworks
            devices = self.iface.devices("wireless_tools")
            for device in devices.keys():
                if self.app:
                    self.app.processEvents()
                self.iface.scanRemote(device, "wireless_tools", filterByScan)
        else:
            # Filter by given package
            setHidden(filter, False)

    def fillProfileList(self, ignore = None):
        # Clear the entire list
        # FIXME Sip makes crash in here sometimes, I know this is not the right way of it.
        # self.ui.profileList.clear()
        for i in range(self.ui.profileList.count()):
            it = self.ui.profileList.takeItem(0)
            it.setHidden(True)
        self.widgets = {}

        # Fill the list with current connections
        for package in self.packages:
            # Fill profile list
            self.connections = self.iface.connections(package)
            self.connections.sort()
            for connection in self.connections:
                if ignore:
                    if package == ignore[0] and connection == ignore[1]:
                        continue
                info = self.iface.info(package, connection)
                state = str(info["state"])
                item = QtGui.QListWidgetItem(self.ui.profileList)
                item.setFlags(Qt.NoItemFlags | Qt.ItemIsEnabled)
                item.setSizeHint(QSize(48,48))
                key = "%s-%s" % (package, connection)
                self.widgets[key] = ConnectionItemWidget(package, connection, info, self, item)
                if (info["device_id"] not in self.probedDevices) and not state.startswith("inaccessible"):
                    state = "unplugged"
                self.widgets[key].updateData(state)
                self.ui.profileList.setItemWidget(item, self.widgets[key])
                del item

        # Filter list with selected filter method
        self.filterList(self.ui.filterBox.currentIndex())

    # Anime Naruto depends on GUI
    def animate(self, height):
        self.ui.editBox.setMaximumHeight(height)
        self.ui.profileList.setMaximumHeight(self.baseWidget.height()-height)
        self.update()

    def animateFinished(self):
        if self.lastAnimation == SHOW:
            self.ui.lineConnectionName.setFocus()
            self.ui.editBox.setMaximumHeight(DEFAULT_HEIGHT)
            self.ui.profileList.setMaximumHeight(TARGET_HEIGHT)
            self.ui.editBox.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
            self.ui.buttonCreate.setEnabled(False)
            self.ui.filterBox.setEnabled(False)
        elif self.lastAnimation == HIDE:
            self.ui.profileList.setFocus()
            self.ui.profileList.setMaximumHeight(DEFAULT_HEIGHT)
            self.ui.editBox.setMaximumHeight(TARGET_HEIGHT)
            self.ui.profileList.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
            self.ui.buttonCreate.setEnabled(True)
            self.ui.filterBox.setEnabled(True)
            QTimer.singleShot(100, self.runFinishHook)

    def runFinishHook(self):
        # Call waiting functions
        for func in self.animatorFinishHook:
            func()
        self.animatorFinishHook = []

    def hideEditBox(self):
        if self.lastAnimation == SHOW:
            self.lastAnimation = HIDE
            self.hideScrollBars()
            self.animator.setFrameRange(self.ui.editBox.height(), TARGET_HEIGHT)
            self.animator.start()
            self.resetForm()

    def showEditBox(self, package, profile=None, device=None):
        sender = self.sender().parent()
        self.lastAnimation = SHOW
        self.hideScrollBars()

        # Fill package name and package capabilities
        self.lastEditedPackage = package
        self.lastEditedInfo = info = self.iface.capabilities(package)

        # Hide all settings first
        self.ui.groupRemote.hide()
        self.ui.groupNetwork.hide()
        self.ui.groupNameServer.hide()

        modes = info["modes"].split(",")

        if "auth" in modes:
            self.ui.comboSecurityTypes.clear()
            self.ui.comboSecurityTypes.addItem(i18n("No Authentication"), QVariant("none"))
            for name, desc in self.iface.authMethods(package):
                self.ui.comboSecurityTypes.addItem(desc, QVariant(name))

        # Then show them by giving package
        if "net" in modes:
            self.ui.groupNetwork.show()
            self.ui.groupNameServer.show()
        if "remote" in modes:
            remote_name = self.iface.remoteName(package)
            self.ui.labelRemote.setText("%s :" % remote_name)
            if "remote_scan" in modes:
                wifiScanner = WifiPopup(self)
                self.ui.buttonScan.setMenu(wifiScanner)
                self.ui.buttonScan.show()
            else:
                self.ui.buttonScan.hide()
            self.ui.groupRemote.show()
        if "device" in modes:
            self.fillDeviceList(package, device)

        if profile:
            self.buildEditBoxFor(sender.package, sender.profile)

        self.animator.setFrameRange(TARGET_HEIGHT, self.baseWidget.height() - TARGET_HEIGHT)
        self.animator.start()

    def hideScrollBars(self):
        self.ui.editBox.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.ui.profileList.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

    def fillDeviceList(self, package, selected_device=None):
        ui = self.ui
        devices = self.iface.devices(package)
        for device in devices:
            ui.deviceList.addItem(device)
        if selected_device:
            ui.deviceList.setCurrentIndex(ui.deviceList.findText(selected_device))
        if len(devices) == 1:
            ui.deviceList.hide()
            ui.labelDeviceDescription.show()
            ui.labelDeviceDescription.setText(cropText(devices[device]))
        else:
            ui.deviceList.show()
            ui.labelDeviceDescription.hide()

    # Comar operations calls gui
    def buildEditBoxFor(self, package, profile):
        ui = self.ui
        self.lastEditedData = data = self.iface.info(package, profile)

        ui.lineConnectionName.setText(data["name"])

        if "device_name" in data:
            ui.labelDeviceDescription.setText(cropText(data["device_name"]))
        if "device_id" in data:
            index = ui.deviceList.findText(data["device_id"])
            if index != -1:
                ui.deviceList.setCurrentIndex(index)
            else:
                ui.deviceList.addItem(data["device_id"])
                ui.deviceList.setCurrentIndex(ui.deviceList.count() - 1)
                ui.deviceList.show()
                ui.labelDeviceDescription.hide()

        if "remote" in data:
            ui.lineRemote.setText(data["remote"])

        modes = self.lastEditedInfo["modes"].split(",")

        if "auth" in modes:
            authType = self.iface.authType(package, profile)
            authInfo = self.iface.authInfo(package, profile)
            authParams = self.iface.authParameters(package, authType)
            ui.comboSecurityTypes.setCurrentIndex(ui.comboSecurityTypes.findData(QVariant(authType)))

            if len(authParams) == 1:
                if len(authInfo.values()):
                    password = authInfo.values()[0]
                else:
                    password = ""
                ui.lineKey.setText(password)
            elif len(authParams) > 1:
                self.securityValues = authInfo
                self.securityDialog.setValues(authInfo)

        if data.has_key("net_mode"):
            if data["net_mode"] == "auto":
                ui.useDHCP.setChecked(True)
                if data.get("net_address", "") != "":
                    ui.useCustomAddress.setChecked(True)
                if data.get("net_gateway", "") != "":
                    ui.useCustomDNS.setChecked(True)
            else:
                ui.useManual.setChecked(True)

        if data.has_key("net_address"):
            ui.lineAddress.setText(data["net_address"])
        if data.has_key("net_mask"):
            ui.lineNetworkMask.lineEdit().setText(data["net_mask"])
        if data.has_key("net_gateway"):
            ui.lineGateway.setText(data["net_gateway"])

        if data.has_key("name_mode"):
            if data["name_mode"] == "default":
                ui.useDefault.setChecked(True)
            if data["name_mode"] == "auto":
                ui.useAutomatic.setChecked(True)
            if data["name_mode"] == "custom":
                ui.useCustom.setChecked(True)
                ui.lineCustomDNS.setText(data["name_server"])

    def resetForm(self):
        ui = self.ui
        ui.lineConnectionName.setText("")
        ui.deviceList.clear()
        ui.labelDeviceDescription.setText("")
        ui.useDHCP.setChecked(True)
        ui.useCustomAddress.setChecked(False)
        ui.useCustomDNS.setChecked(False)
        ui.useManual.setChecked(False)
        ui.lineAddress.setText("")
        ui.lineNetworkMask.lineEdit().setText("")
        ui.lineGateway.setText("")
        ui.lineRemote.setText("")
        ui.useDefault.setChecked(True)
        ui.useAutomatic.setChecked(False)
        ui.useCustom.setChecked(False)
        ui.lineCustomDNS.setText("")
        ui.lineKey.setText("")
        ui.comboSecurityTypes.setCurrentIndex(0)
        self.lastEditedData = None
        self.lastEditedPackage = None
        self.lastEditedInfo = None

    def applyChanges(self):
        ui = self.ui
        connectionName = unicode(ui.lineConnectionName.text())

        try:
            self.iface.updateConnection(self.lastEditedPackage, connectionName, self.collectDataFromUI())
        except Exception, e:
            KMessageBox.error(self.baseWidget, unicode(e))
            return

        if self.lastEditedData:
            # Profile name has been changed, delete old profile
            if not self.lastEditedData["name"] == connectionName:
                self.iface.deleteConnection(self.lastEditedPackage, self.lastEditedData["name"])
            # Profile state was up
            if self.lastEditedData.has_key("state"):
                if self.lastEditedData["state"].startswith("up"):
                    self.iface.connect(self.lastEditedPackage, connectionName)
        self.hideEditBox()
Exemple #18
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)
    
    '''
class ParallaxSlide(QGraphicsView):
    def __init__(self):

        QGraphicsView.__init__(self)
        self.ofs = 0
        self.factor = 1
        self.scene = QGraphicsScene()
        self.background = None
        self.icons = []
        self.iconTimeLine = QTimeLine()
        self.backgroundTimeLine = QTimeLine()

        self.setScene(self.scene)

        self.background = self.scene.addPixmap(QPixmap(":/background.jpg"))
        self.background.setZValue(0.0)
        self.background.setPos(0, 0)

        for i in range(7):
            str = QString(":/icon%1.png").arg(i + 1)
            icon = self.scene.addPixmap(QPixmap(str))
            icon.setPos(320 + i * 64, 400)
            icon.setZValue(1.0)
            self.icons.append(icon)

        self.setFixedSize(320, 480)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        self.connect(self.iconTimeLine, SIGNAL("frameChanged(int)"), self,
                     SLOT("moveIcons(int)"))
        self.iconTimeLine.setCurveShape(QTimeLine.EaseInOutCurve)

        self.connect(self.backgroundTimeLine, SIGNAL("frameChanged(int)"),
                     self, SLOT("moveBackground(int)"))
        self.connect(self.backgroundTimeLine, SIGNAL("finished()"), self,
                     SLOT("adjustParameters()"))
        self.backgroundTimeLine.setCurveShape(QTimeLine.EaseInOutCurve)

        self.controls = Ui_ControlsForm()

        toolWidget = QWidget(self)
        toolWidget.setWindowFlags(Qt.Tool | Qt.WindowTitleHint)
        self.controls.setupUi(toolWidget)
        toolWidget.show()

        self.connect(self.controls.speedSlider, SIGNAL("valueChanged(int)"),
                     self, SLOT("adjustParameters()"))
        self.connect(self.controls.normalButton, SIGNAL("clicked()"), self,
                     SLOT("adjustParameters()"))
        self.connect(self.controls.parallaxButton, SIGNAL("clicked()"), self,
                     SLOT("adjustParameters()"))
        self.connect(self.controls.leftButton, SIGNAL("clicked()"), self,
                     SLOT("slideLeft()"))
        self.connect(self.controls.rightButton, SIGNAL("clicked()"), self,
                     SLOT("slideRight()"))

        self.slideBy(-320)
        self.adjustParameters()

    @pyqtSignature("")
    def slideLeft(self):

        if self.iconTimeLine.state() != QTimeLine.NotRunning:
            return

        if self.ofs > -640:
            self.slideBy(-320)

    @pyqtSignature("")
    def slideRight(self):

        if self.iconTimeLine.state() != QTimeLine.NotRunning:
            return

        if self.ofs < 0:
            self.slideBy(320)

    @pyqtSignature("int")
    def slideBy(self, dx):

        iconStart = self.ofs
        iconEnd = self.ofs + dx
        self.iconTimeLine.setFrameRange(iconStart, iconEnd)
        self.iconTimeLine.start()

        backgroundStart = -320 - int((-320 - iconStart) / self.factor)
        backgroundEnd = -320 - int((-320 - iconEnd) / self.factor)
        self.backgroundTimeLine.setFrameRange(backgroundStart, backgroundEnd)
        self.backgroundTimeLine.start()

        self.ofs = iconEnd

    @pyqtSignature("bool")
    def setParallaxEnabled(self, p):

        if p:
            self.factor = 2
            self.setWindowTitle("Sliding - Parallax mode")
        else:
            self.factor = 1
            self.setWindowTitle("Sliding - Normal mode")

    def keyPressEvent(self, event):

        if event.key() == Qt.Key_Left:
            self.slideLeft()

        if event.key() == Qt.Key_Right:
            self.slideRight()

    @pyqtSignature("int")
    def moveIcons(self, x):

        i = 0
        for icon in self.icons:
            icon.setPos(320 + x + i * 64, icon.pos().y())
            i += 1

    @pyqtSignature("int")
    def moveBackground(self, x):

        self.background.setPos(x, self.background.pos().y())

    @pyqtSignature("")
    def adjustParameters(self):

        speed = self.controls.speedSlider.value()
        self.iconTimeLine.setDuration(1200 - speed * 10)
        self.backgroundTimeLine.setDuration(1200 - speed * 10)
        self.setParallaxEnabled(self.controls.parallaxButton.isChecked())
        self.controls.leftButton.setEnabled(self.ofs > -640)
        self.controls.rightButton.setEnabled(self.ofs < 0)
Exemple #20
0
class MainManager(QtGui.QWidget):
    def __init__(self, parent, standAlone=True, app=None):
        QtGui.QWidget.__init__(self, parent)

        # Create the ui
        self.ui = Ui_mainManager()
        self.app = app
        self.lastEditedPackage = None
        self.lastEditedData = None
        self.lastEditedInfo = None
        self.isEditBox = None

        # Network Manager can run as KControl Module or Standalone
        if standAlone:
            self.ui.setupUi(self)
            self.baseWidget = self
        else:
            self.ui.setupUi(parent)
            self.baseWidget = parent

        # Workaround for Pyuic Problem
        self.ui.buttonCancelMini.setText('')

        # Set visibility of indicators
        self.ui.workingLabel.hide()
        self.ui.refreshButton.hide()

        # Call Comar
        self.iface = NetworkIface()
        self.widgets = {}

        # Populate Packages
        self.packages = {}
        for package in self.iface.packages():
            self.packages[package] = self.iface.linkInfo(package)

        # Naruto
        self.animator = QTimeLine(ANIMATION_TIME, self)

        # List of functions to call after animation is finished
        self.animatorFinishHook = []

        # Let look what we can do
        self.refreshBrowser()

        # Security dialog
        self.securityDialog = SecurityDialog(parent)
        self.securityFields = []
        self.securityValues = {}

        # Nameserver dialog
        self.nameserverDialog = NameServerDialog(parent)

        # Preparing for animation
        self.ui.editBox.setMaximumHeight(TARGET_HEIGHT)
        self.lastAnimation = SHOW

        # Animator connections, Naruto loves Sakura-chan
        self.connect(self.animator, SIGNAL("frameChanged(int)"), self.animate)
        self.connect(self.animator, SIGNAL("finished()"), self.animateFinished)

        # Hide editBox when clicked mini cancel
        self.connect(self.ui.buttonCancelMini, SIGNAL("clicked()"),
                     self.hideEditBox)

        # Save changes when clicked Apply, Reject changes when clicked Cancel
        self.connect(self.ui.buttonBox, SIGNAL("rejected()"), self.hideEditBox)
        self.connect(self.ui.buttonBox, SIGNAL("accepted()"),
                     self.applyChanges)

        # Show NameServer Settings Dialog
        self.ui.buttonNameServer.setIcon(KIcon("configure"))
        self.connect(self.ui.buttonNameServer, SIGNAL("clicked()"),
                     self.slotNameServerDialog)

        # Filter
        self.connect(self.ui.filterBox, SIGNAL("currentIndexChanged(int)"),
                     self.filterList)

        # Refresh button for scanning remote again..
        self.connect(self.ui.refreshButton, SIGNAL("leftClickedUrl()"),
                     self.filterESSID)

        # Security details button
        self.connect(self.ui.pushSecurity, SIGNAL("clicked()"),
                     self.openSecurityDialog)

        # Security types
        self.connect(self.ui.comboSecurityTypes,
                     SIGNAL("currentIndexChanged(int)"),
                     self.slotSecurityChanged)

        # Update service status and follow Comar for sate changes
        self.getConnectionStates()

    def slotNameServerDialog(self):
        self.nameserverDialog.setHostname(self.iface.getHostname())
        self.nameserverDialog.setNameservers(self.iface.getNameservers())
        if self.nameserverDialog.exec_():
            self.iface.setHostname(self.nameserverDialog.getHostname())
            self.iface.setNameservers(self.nameserverDialog.getNameservers())

    def openSecurityDialog(self):
        self.securityDialog.setValues(self.securityValues)
        if self.securityDialog.exec_():
            self.securityValues = self.securityDialog.getValues()

    def slotSecurityChanged(self, index):
        method = str(self.ui.comboSecurityTypes.itemData(index).toString())
        if method == "none":
            # Hide security widgets
            self.ui.pushSecurity.hide()
            self.ui.lineKey.hide()
            self.ui.labelKey.hide()
            self.ui.checkShowPassword.hide()
            # Erase all security data
            self.securityValues = {}
        else:
            parameters = self.iface.authParameters(self.lastEditedPackage,
                                                   method)
            if len(parameters) == 1 and parameters[0][2] in ["text", "pass"]:
                # Single text or password field, don't use dialog
                self.ui.pushSecurity.hide()
                # Show other fields
                self.ui.lineKey.show()
                self.ui.labelKey.show()
                self.ui.checkShowPassword.show()
                self.ui.labelKey.setText(parameters[0][1])
            else:
                # Too many fields, dialog required
                self.ui.pushSecurity.show()
                self.ui.lineKey.hide()
                self.ui.labelKey.hide()
                self.ui.checkShowPassword.hide()
                self.securityDialog.setFields(parameters)

    def refreshBrowser(self):
        if self.animator.state() != 0:
            # Refreshing browser when animator is active causes blindness
            if not self.refreshBrowser in self.animatorFinishHook:
                self.animatorFinishHook.append(self.refreshBrowser)
            return

        aa = time.time()
        self.ui.filterBox.clear()
        self.probedDevices = []
        menu = KMenu(self)

        for package in self.packages:
            info = self.packages[package]
            devices = self.iface.devices(package)

            if len(devices) > 0:
                # Add package container and set icon
                menuPackageContainer = KMenu(self.packages[package]['name'],
                                             menu)
                menuPackageContainer.setIcon(KIcon(getIconForPackage(package)))
                menu.addMenu(menuPackageContainer)

                # Add filter menu entry
                self.ui.filterBox.addItem(info["name"], QVariant(package))

                if "remote_scan" in info["modes"]:
                    self.ui.filterBox.addItem(i18n("Available Profiles"),
                                              QVariant("essid"))
                    APScanner = APPopup(self, package)
                    self.ui.buttonScan.setMenu(APScanner)

                # Create profile menu with current devices
                for device in devices.keys():

                    print device, devices[device]
                    menuItem = QtGui.QAction(devices[device],
                                             menuPackageContainer)
                    menuItem.setData(
                        QVariant("%s::%s::%s" %
                                 (package, device, devices[device])))

                    self.connect(menuItem, SIGNAL("triggered()"),
                                 self.createConnection)

                    # Store a list of probed devices
                    if device not in self.probedDevices:
                        self.probedDevices.append(device)

                    menuPackageContainer.addAction(menuItem)

        if len(self.packages) > 0:
            self.ui.buttonCreate.setIcon(KIcon("list-add"))
            self.ui.buttonCreate.setMenu(menu)
            self.ui.filterBox.insertItem(0, i18n("All Profiles"),
                                         QVariant("all"))
        else:
            self.ui.buttonCreate.setText(i18n("No Device Found"))
            self.ui.buttonCreate.setEnabled(False)
            self.ui.filterBox.insertItem(0, i18n("No Device Found"))
            self.ui.filterBox.setEnabled(False)
        self.ui.filterBox.setCurrentIndex(0)

        # Fill the list
        self.fillProfileList()

    def filterESSID(self):
        self.filterList("essid")

    def filterList(self, id=None):
        if not id:
            filter = ""
        elif id == "essid":
            filter = "essid"
        else:
            filter = str(self.ui.filterBox.itemData(id).toString())

        def filterByScan(*args):
            # We have finished the scanning let set widgets to old states
            self.ui.profileList.setEnabled(True)
            self.ui.refreshButton.show()
            self.ui.workingLabel.hide()
            self.setCursor(Qt.ArrowCursor)

            # Update the GUI
            if self.app:
                self.app.processEvents()

            # Update List with found remote networks
            availableNetworks = {}
            for result in args[2][0]:
                availableNetworks[unicode(result['remote'])] = int(
                    result['quality'])
            for widget in self.widgets.values():
                if widget.item.isHidden():
                    continue
                if "remote" in widget.data and unicode(
                        widget.data["remote"]) in availableNetworks.keys():
                    widget.setSignalStrength(availableNetworks[unicode(
                        widget.data["remote"])])
                    widget.item.setHidden(False)
                else:
                    widget.hideSignalStrength()
                    widget.item.setHidden(True)

        def setHidden(package=None, hidden=False, attr="package"):
            for widget in self.widgets.values():
                widget.hideSignalStrength()
                if not package:
                    widget.item.setHidden(False)
                    continue
                if attr == "essid" and not widget.package == 'wireless_tools':
                    widget.item.setHidden(True)
                    continue
                elif attr == "essid" and widget.package == 'wireless_tools':
                    if not widget.data.has_key("remote"):
                        widget.item.setHidden(True)
                    continue
                if getattr(widget, attr) == package:
                    widget.item.setHidden(hidden)
                else:
                    widget.item.setHidden(not hidden)

        # Set visibility of indicators
        self.ui.workingLabel.hide()
        self.ui.refreshButton.hide()
        # All profiles
        if filter == "all":
            setHidden()
        # Avaliable profiles
        elif filter == "essid":
            # We need to show user, we are working :)
            self.ui.profileList.setEnabled(False)
            self.ui.refreshButton.hide()
            self.ui.workingLabel.show()
            self.setCursor(Qt.WaitCursor)

            # Show all profiles
            setHidden()

            # Hide not usable ones
            setHidden("wireless_tools", False, "essid")

            # Update the GUI
            if self.app:
                self.app.processEvents()

            # Scan for availableNetworks
            devices = self.iface.devices("wireless_tools")
            for device in devices.keys():
                if self.app:
                    self.app.processEvents()
                self.iface.scanRemote(device, "wireless_tools", filterByScan)
        else:
            # Filter by given package
            setHidden(filter, False)

    def fillProfileList(self, ignore=None):
        # Clear the entire list
        # FIXME Sip makes crash in here sometimes, I know this is not the right way of it.
        # self.ui.profileList.clear()
        for i in range(self.ui.profileList.count()):
            it = self.ui.profileList.takeItem(0)
            it.setHidden(True)
        self.widgets = {}

        # Fill the list with current connections
        for package in self.packages:
            # Fill profile list
            self.connections = self.iface.connections(package)
            self.connections.sort()
            for connection in self.connections:
                if ignore:
                    if package == ignore[0] and connection == ignore[1]:
                        continue
                info = self.iface.info(package, connection)
                state = str(info["state"])
                item = QtGui.QListWidgetItem(self.ui.profileList)
                item.setFlags(Qt.NoItemFlags | Qt.ItemIsEnabled)
                item.setSizeHint(QSize(48, 48))
                key = "%s-%s" % (package, connection)
                self.widgets[key] = ConnectionItemWidget(
                    package, connection, info, self, item)
                if (info["device_id"] not in self.probedDevices
                    ) and not state.startswith("inaccessible"):
                    state = "unplugged"
                self.widgets[key].updateData(state)
                self.ui.profileList.setItemWidget(item, self.widgets[key])
                del item

        # Filter list with selected filter method
        self.filterList(self.ui.filterBox.currentIndex())

    # Anime Naruto depends on GUI
    def animate(self, height):
        self.ui.editBox.setMaximumHeight(height)
        self.ui.profileList.setMaximumHeight(self.baseWidget.height() - height)
        self.update()

    def animateFinished(self):
        if self.lastAnimation == SHOW:
            self.ui.lineProfileName.setFocus()
            self.ui.editBox.setMaximumHeight(DEFAULT_HEIGHT)
            self.ui.profileList.setMaximumHeight(TARGET_HEIGHT)
            self.ui.editBox.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
            self.ui.buttonCreate.setEnabled(False)
            self.ui.filterBox.setEnabled(False)
        elif self.lastAnimation == HIDE:
            self.ui.profileList.setFocus()
            self.ui.profileList.setMaximumHeight(DEFAULT_HEIGHT)
            self.ui.editBox.setMaximumHeight(TARGET_HEIGHT)
            self.ui.profileList.setVerticalScrollBarPolicy(
                Qt.ScrollBarAsNeeded)
            self.ui.buttonCreate.setEnabled(True)
            self.ui.filterBox.setEnabled(True)
            QTimer.singleShot(100, self.runFinishHook)

    def runFinishHook(self):
        # Call waiting functions
        for func in self.animatorFinishHook:
            func()
        self.animatorFinishHook = []

    def hideEditBox(self):
        if self.lastAnimation == SHOW:
            self.lastAnimation = HIDE
            self.hideScrollBars()
            self.animator.setFrameRange(self.ui.editBox.height(),
                                        TARGET_HEIGHT)
            self.animator.start()
            self.resetForm()

    def showEditBox(self, package, profile=None, device=None):
        sender = self.sender().parent()
        self.lastAnimation = SHOW
        self.hideScrollBars()

        # Fill package name and package capabilities
        self.lastEditedPackage = package
        self.lastEditedInfo = info = self.iface.capabilities(package)

        # Hide all settings first
        self.ui.groupRemote.hide()
        self.ui.groupNetwork.hide()
        self.ui.groupNameServer.hide()

        modes = info["modes"].split(",")

        if "auth" in modes:
            self.ui.comboSecurityTypes.clear()
            self.ui.comboSecurityTypes.addItem(i18n("No Authentication"),
                                               QVariant(u'none'))
            for name, desc in self.iface.authMethods(package):
                self.ui.comboSecurityTypes.addItem(desc,
                                                   QVariant(unicode(name)))

        # Then show them by giving package
        if "net" in modes:
            self.ui.groupNetwork.show()
            self.ui.groupNameServer.show()
        if "remote" in modes:
            remote_name = self.iface.remoteName(package)
            self.ui.labelRemote.setText("%s :" % remote_name)
            if "remote_scan" in modes:
                APScanner = APPopup(self, package)
                self.ui.buttonScan.setMenu(APScanner)
                self.ui.buttonScan.show()
            else:
                self.ui.buttonScan.hide()
            self.ui.groupRemote.show()
        if "device" in modes:
            self.fillDeviceList(package, device)

        if profile:
            self.buildEditBoxFor(sender.package, sender.profile)
            self.isEditBox = 1

        self.animator.setFrameRange(TARGET_HEIGHT,
                                    self.baseWidget.height() - TARGET_HEIGHT)
        self.animator.start()

    def hideScrollBars(self):
        self.ui.editBox.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.ui.profileList.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

    def fillDeviceList(self, package, selected_device=None):
        ui = self.ui
        devices = self.iface.devices(package)
        for device in devices:
            ui.deviceList.addItem(device)
        if selected_device:
            ui.deviceList.setCurrentIndex(
                ui.deviceList.findText(selected_device))
        if len(devices) == 1:
            ui.deviceList.hide()
            ui.labelDeviceDescription.show()
            ui.labelDeviceDescription.setText(cropText(devices[device]))
        else:
            ui.deviceList.show()
            ui.labelDeviceDescription.hide()

    # Comar operations calls gui
    def buildEditBoxFor(self, package, profile):
        ui = self.ui
        self.lastEditedData = data = self.iface.info(package, profile)

        ui.lineProfileName.setText(data["name"])

        if "device_name" in data:
            ui.labelDeviceDescription.setText(cropText(data["device_name"]))
        if "device_id" in data:
            index = ui.deviceList.findText(data["device_id"])
            if index != -1:
                ui.deviceList.setCurrentIndex(index)
            else:
                ui.deviceList.addItem(data["device_id"])
                ui.deviceList.setCurrentIndex(ui.deviceList.count() - 1)
                ui.deviceList.show()
                ui.labelDeviceDescription.hide()

        if "remote" in data:
            ui.lineRemote.setText(data["remote"])

        modes = self.lastEditedInfo["modes"].split(",")

        if "auth" in modes:
            authType = self.iface.authType(package, profile)
            authInfo = self.iface.authInfo(package, profile)
            authParams = self.iface.authParameters(package, authType)
            ui.comboSecurityTypes.setCurrentIndex(
                ui.comboSecurityTypes.findData(QVariant(unicode(authType))))

            if len(authParams) == 1:
                if len(authInfo.values()):
                    password = authInfo.values()[0]
                else:
                    password = ""
                ui.lineKey.setText(password)
            elif len(authParams) > 1:
                self.securityValues = authInfo
                self.securityDialog.setValues(authInfo)

        if data.has_key("net_mode"):
            if data["net_mode"] == "auto":
                ui.useDHCP.setChecked(True)
                if data.get("net_address", "") != "":
                    ui.useCustomAddress.setChecked(True)
                if data.get("net_gateway", "") != "":
                    ui.useCustomDNS.setChecked(True)
            else:
                ui.useManual.setChecked(True)

        if data.has_key("net_address"):
            ui.lineAddress.setText(data["net_address"])
        if data.has_key("net_mask"):
            ui.lineNetworkMask.lineEdit().setText(data["net_mask"])
        if data.has_key("net_gateway"):
            ui.lineGateway.setText(data["net_gateway"])

        if data.has_key("name_mode"):
            if data["name_mode"] == "default":
                ui.useDefault.setChecked(True)
            if data["name_mode"] == "auto":
                ui.useAutomatic.setChecked(True)
            if data["name_mode"] == "custom":
                ui.useCustom.setChecked(True)
                ui.lineCustomDNS.setText(data["name_server"])

    def resetForm(self):
        ui = self.ui
        ui.lineProfileName.setText("")
        ui.deviceList.clear()
        ui.labelDeviceDescription.setText("")
        ui.useDHCP.setChecked(True)
        ui.useCustomAddress.setChecked(False)
        ui.useCustomDNS.setChecked(False)
        ui.useManual.setChecked(False)
        ui.lineAddress.setText("")
        ui.lineNetworkMask.lineEdit().setText("")
        ui.lineGateway.setText("")
        ui.lineRemote.setText("")
        ui.useDefault.setChecked(True)
        ui.useAutomatic.setChecked(False)
        ui.useCustom.setChecked(False)
        ui.lineCustomDNS.setText("")
        ui.lineKey.setText("")
        ui.comboSecurityTypes.setCurrentIndex(0)
        self.lastEditedData = None
        self.lastEditedPackage = None
        self.lastEditedInfo = None

    def applyChanges(self):
        ui = self.ui
        connectionName = unicode(ui.lineProfileName.text())
        connections = self.iface.connections(self.lastEditedPackage)

        if (self.isEditBox) or (not connectionName in connections):
            try:
                self.iface.updateConnection(self.lastEditedPackage,
                                            connectionName,
                                            self.collectDataFromUI())
            except Exception, e:
                KMessageBox.error(self.baseWidget, unicode(e))
                ui.lineProfileName.setFocus()
                return
        else:
Exemple #21
0
class QPageWidget(QScrollArea):
    """ The QPageWidget provides a stack widget with animated page transitions. """

    def __init__(self, parent = None, direction = "ltr", rtf = False):
        """ Creates a new QPageWidget on given parent object. 

        parent: QWidget parent
        direction: "ltr" -> Left To Right
                   "ttb" -> Top To Bottom
        rtf: Return to first, if its True it flips to the first page 
             when next page requested at the last page
        """
        # First initialize, QPageWidget is based on QScrollArea
        QScrollArea.__init__(self, parent)

        # Properties for QScrollArea
        self.setFrameShape(QFrame.NoFrame)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidgetResizable(True)

        # Main widget, which stores all Pages in it
        self.widget = QWidget(self)

        # Layout based on QBoxLayout which supports Vertical or Horizontal layout
        if direction == "ltr":
            self.layout = QBoxLayout(QBoxLayout.LeftToRight, self.widget)
            self.__scrollBar = self.horizontalScrollBar()
            self.__base_value = self.width
        else:
            self.layout = QBoxLayout(QBoxLayout.TopToBottom, self.widget)
            self.__scrollBar = self.verticalScrollBar()
            self.__base_value = self.height
        self.layout.setSpacing(0)
        self.layout.setMargin(0)

        # Return to first
        self.__return_to_first = rtf

        # TMP_PAGE, its using as last page in stack
        # A workaround for a QScrollArea bug
        self.__tmp_page = Page(QWidget(self.widget))
        self.__pages = [self.__tmp_page]
        self.__current = 0
        self.__last = 0

        # Set main widget
        self.setWidget(self.widget)

        # Animation TimeLine
        self.__timeline = QTimeLine()
        self.__timeline.setUpdateInterval(2)

        # Updates scrollbar position when frame changed
        self.__timeline.frameChanged.connect(lambda x: self.__scrollBar.setValue(x))

        # End of the animation
        self.__timeline.finished.connect(self._animateFinished)

        # Initialize animation
        self.setAnimation()
        self.setDuration()

    def _animateFinished(self):
        """ Its called by TimeLine when animation finished.

        It first runs the outMethod of last Page and then the inMethod of current Page
        Finally tt gives the focus to the current page and fixes the scrollBar
        """

        # Disable other widgets
        for page in self.__pages:
            if not page == self.__pages[self.__current]:
                page.widget.setEnabled(False)

        # Run last page's outMethod if exists
        if self.__pages[self.__last].outMethod:
            self.__pages[self.__last].outMethod()

        # Run new page's inMethod if exists
        if self.__pages[self.__current].inMethod:
            self.__pages[self.__current].inMethod()

        # Give focus to the current Page
        self.__pages[self.__current].widget.setFocus()

        # Update scrollbar position for current page
        self.__scrollBar.setValue(self.__current * self.__base_value())

        # Emit currentChanged SIGNAL
        self.emit(SIGNAL("currentChanged()"))

    def event(self, event):
        """ Overrides the main event handler to catch resize events """
        # Catch Resize event
        if event.type() == QEvent.Resize:
            # Update each page size limits to mainwidget's new size
            for page in self.__pages:
                page.widget.setMinimumSize(self.size())
                page.widget.setMaximumSize(self.size())

            # Update viewport size limits to mainwidget's new size
            # It's a workaround for QScrollArea updateGeometry bug
            self.viewport().setMinimumSize(self.size())
            self.viewport().setMaximumSize(self.size())

            # Update scrollbar position for current page
            self.__scrollBar.setValue(self.__current * self.__base_value())

        # Return the Event
        return QScrollArea.event(self, event)

    def keyPressEvent(self, event):
        """ Overrides the keyPressEvent to ignore them """
        pass

    def wheelEvent(self, event):
        """ Overrides the wheelEvent to ignore them """
        pass

    def createPage(self, widget, inMethod = None, outMethod = None):
        """ Creates and adds new Page for given widget with given in/out methods.

        widget: A QWidget which is the mainwidget for this Page
        inMethod: (optional) QPageWidget triggers this method when the Page appear
        outMethod: (optional) QPageWidget triggers this method when the Page disappear
        """
        self.addPage(Page(widget, inMethod, outMethod))

    def addPage(self, page):
        """ Adds the given Page to the stack.

        page: A Page object
        """
        # First remove the last page; its __tmp_page
        self.__pages.pop()

        # Add new page
        self.__pages.append(page)
        self.layout.addWidget(page.widget)

        # Add __tmp_page to end
        self.__pages.append(self.__tmp_page)
        self.layout.addWidget(self.__tmp_page.widget)

        # Create connections for page navigation signals from new page
        self.connect(page.widget, SIGNAL("pageNext()"), self.next)
        self.connect(page.widget, SIGNAL("pagePrevious()"), self.prev)
        self.connect(page.widget, SIGNAL("setCurrent(int)"), self.setCurrent)

    def __setCurrent(self, pageNumber):
        """ Internal method to set current page index. """
        self.__last = self.__current
        self.__current = min(max(0, pageNumber), len(self.__pages) - 2)
        if pageNumber == len(self.__pages) - 1 and self.__return_to_first:
            self.__current = 0

    def setCurrent(self, pageNumber = 0):
        """ Set and flip the page with given pageNumber.

        pageNumber: index number of Page (default is 0)
        """
        self.__setCurrent(pageNumber)
        self.flipPage()

    def getCurrent(self):
        """ Returns current page index. """
        return self.__current

    def getCurrentWidget(self):
        """ Returns current page widget. """
        return self.getWidget(self.getCurrent())

    def getWidget(self, pageNumber):
        """ Returns widget for given page index 

        pageNumber: index number of Page
        """
        try:
            return self.__pages[pageNumber].widget
        except:
            return None

    def count(self):
        """ Returns number of pages. """
        return len(self.__pages) - 1

    def setAnimation(self, animation = 35):
        """ Set the transition animation with the given animation.

        animation: the number represents predefined QEasingCurves
                   List of predefined QEasingCurves can be found from:
                   http://doc.qt.nokia.com/4/qeasingcurve.html#Type-enum

                   Default is QEasingCurve::InOutBack (35)
        """
        self.__animation = animation
        self.__timeline.setEasingCurve(QEasingCurve(self.__animation))

    def setDuration(self, duration = 400):
        """ Set the transition duration.

        duration: duration time in ms
        """
        self.__duration = duration
        self.__timeline.setDuration(self.__duration)

    def flipPage(self, direction=0):
        """ Flip the page with given direction.

        direction: can be -1, 0 or +1
                   -1: previous page (if exists)
                    0: just flip to current page
                   +1: next page (if exists)
        """
        # Enable all widgets
        for page in self.__pages:
            page.widget.setEnabled(True)

        # Check given direction
        direction = direction if direction == 0 else max(min(1, direction), -1)

        # If direction is equal to zero no need to re-set current
        if not direction == 0:
            self.__setCurrent(self.__current + direction)

        # If last page is different from new page, flip it !
        if not self.__last == self.__current:
            self.__timeline.setFrameRange(self.__scrollBar.value(), self.__current * self.__base_value())
            self.__timeline.start()

    def next(self):
        """ Helper method to flip next page. """
        self.flipPage(1)

    def prev(self):
        """ Helper method to flip previous page. """
        self.flipPage(-1)
class DualJoystickView(QGraphicsView):

    def __init__(self, *args):
        QGraphicsView.__init__(self, *args)
        self.outerD = 125
        self.innerD = 35
        self.innerRange = 48
        self.inputRange = 256
        self.thresh = 3
        self.padding = 40
        self.worker = QSixAxisThread()
        self.worker.valueUpdated.connect(self.moveJoysticks)
        self.worker.start()
        self.move(2, 100)
        self.setContentsMargins(0, 0, 0, 0)
        self.setMaximumHeight(180)
        self.setMaximumWidth(420)
        self.setMinimumHeight(140)
        self.setMinimumWidth(300)
        self.adjustSize()
        self.scene = QGraphicsScene(self)
        self.outerCircle1 = QGraphicsEllipseItem(0, 0, self.outerD, self.outerD)
        self.outerCircle1.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
        self.outerCircle1.setBrush(Qt.gray)
        self.innerCircle1 = QGraphicsEllipseItem(self.outerD / 2 - self.innerD / 2, self.outerD / 2 - self.innerD / 2, self.innerD, self.innerD)
        self.innerCircle1.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
        self.innerCircle1.setBrush(Qt.lightGray)
        self.scene.addItem(self.outerCircle1)
        self.scene.addItem(self.innerCircle1)
        self.outerCircle2 = QGraphicsEllipseItem(self.outerD + self.padding, 0, self.outerD, self.outerD)
        self.outerCircle2.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
        self.outerCircle2.setBrush(Qt.gray)
        self.innerCircle2 = QGraphicsEllipseItem(self.outerD + self.padding + self.outerD / 2 - self.innerD / 2, self.outerD / 2 - self.innerD / 2, self.innerD, self.innerD)
        self.innerCircle2.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
        self.innerCircle2.setBrush(Qt.lightGray)
        self.scene.addItem(self.outerCircle2)
        self.scene.addItem(self.innerCircle2)
        self.setScene(self.scene)
        self.setStyleSheet('background-color:transparent;')
        self.currentX = 0
        self.currentY = 0
        self.currentA = 0
        self.currentZ = 0
        self.test = QGraphicsItem(self.outerCircle2)

    def moveJoysticks(self, x, y, a, z, l3, r3):
        x2 = x * self.innerRange / self.inputRange - self.innerRange / 2
        y2 = y * self.innerRange / self.inputRange - self.innerRange / 2
        a2 = a * self.innerRange / self.inputRange - self.innerRange / 2
        z2 = z * self.innerRange / self.inputRange - self.innerRange / 2
        if -self.thresh <= x2 <= self.thresh:
            x2 = 0
        if -self.thresh <= y2 <= self.thresh:
            y2 = 0
        if -self.thresh <= a2 <= self.thresh:
            a2 = 0
        if -self.thresh <= z2 <= self.thresh:
            z2 = 0
        self.tl = QTimeLine(10)
        self.tl.setFrameRange(0, 10)
        self.a = QGraphicsItemAnimation()
        self.a.setItem(self.innerCircle1)
        self.a.setTimeLine(self.tl)
        self.a.setPosAt(0, QPointF(self.currentX, self.currentY))
        self.a.setTranslationAt(1, x2, y2)
        if l3:
            self.innerCircle1.setPen(QPen(QColor(Qt.white), 1, Qt.SolidLine))
            self.innerCircle1.setBrush(QColor(200, 225, 3))
        else:
            self.innerCircle1.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
            self.innerCircle1.setBrush(Qt.lightGray)
        if r3:
            self.innerCircle2.setPen(QPen(QColor(Qt.white), 1, Qt.SolidLine))
            self.innerCircle2.setBrush(QColor(200, 225, 3))
        else:
            self.innerCircle2.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
            self.innerCircle2.setBrush(Qt.lightGray)
        self.b = QGraphicsItemAnimation()
        self.b.setItem(self.innerCircle2)
        self.b.setTimeLine(self.tl)
        self.b.setPosAt(0, QPointF(self.currentA, self.currentZ))
        self.b.setTranslationAt(1, a2, z2)
        self.currentX = x2
        self.currentY = y2
        self.currentA = a2
        self.currentZ = z2
        self.tl.start()
Exemple #23
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
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_()
class ParallaxSlide(QGraphicsView):

    def __init__(self):
    
        QGraphicsView.__init__(self)
        self.ofs = 0
        self.factor = 1
        self.scene = QGraphicsScene()
        self.background = None
        self.icons = []
        self.iconTimeLine = QTimeLine()
        self.backgroundTimeLine = QTimeLine()
        
        self.setScene(self.scene)
        
        self.background = self.scene.addPixmap(QPixmap(":/background.jpg"))
        self.background.setZValue(0.0)
        self.background.setPos(0, 0)
    
        for i in range(7):
            str = QString(":/icon%1.png").arg(i+1)
            icon = self.scene.addPixmap(QPixmap(str))
            icon.setPos(320+i*64, 400)
            icon.setZValue(1.0)
            self.icons.append(icon)
    
        self.setFixedSize(320, 480)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    
        self.connect(self.iconTimeLine, SIGNAL("frameChanged(int)"), self, SLOT("moveIcons(int)"))
        self.iconTimeLine.setCurveShape(QTimeLine.EaseInOutCurve)
    
        self.connect(self.backgroundTimeLine, SIGNAL("frameChanged(int)"), self, SLOT("moveBackground(int)"))
        self.connect(self.backgroundTimeLine, SIGNAL("finished()"), self, SLOT("adjustParameters()"))
        self.backgroundTimeLine.setCurveShape(QTimeLine.EaseInOutCurve)
        
        self.controls = Ui_ControlsForm()
        
        toolWidget = QWidget(self)
        toolWidget.setWindowFlags(Qt.Tool | Qt.WindowTitleHint)
        self.controls.setupUi(toolWidget)
        toolWidget.show()
    
        self.connect(self.controls.speedSlider, SIGNAL("valueChanged(int)"),
                     self, SLOT("adjustParameters()"))
        self.connect(self.controls.normalButton, SIGNAL("clicked()"),
                     self, SLOT("adjustParameters()"))
        self.connect(self.controls.parallaxButton, SIGNAL("clicked()"),
                     self, SLOT("adjustParameters()"))
        self.connect(self.controls.leftButton, SIGNAL("clicked()"),
                     self, SLOT("slideLeft()"))
        self.connect(self.controls.rightButton, SIGNAL("clicked()"),
                     self, SLOT("slideRight()"))
    
        self.slideBy(-320)
        self.adjustParameters()
    
    @pyqtSignature("")
    def slideLeft(self):
    
        if self.iconTimeLine.state() != QTimeLine.NotRunning:
            return
        
        if self.ofs > -640:
            self.slideBy(-320)
    
    @pyqtSignature("")
    def slideRight(self):
    
        if self.iconTimeLine.state() != QTimeLine.NotRunning:
            return
        
        if self.ofs < 0:
            self.slideBy(320)
    
    @pyqtSignature("int")
    def slideBy(self, dx):
    
        iconStart = self.ofs
        iconEnd = self.ofs + dx
        self.iconTimeLine.setFrameRange(iconStart, iconEnd)
        self.iconTimeLine.start()
        
        backgroundStart = -320 - int((-320 - iconStart)/self.factor)
        backgroundEnd = -320 - int((-320 - iconEnd)/self.factor)
        self.backgroundTimeLine.setFrameRange(backgroundStart, backgroundEnd)
        self.backgroundTimeLine.start()
        
        self.ofs = iconEnd
    
    @pyqtSignature("bool")
    def setParallaxEnabled(self, p):
    
        if p:
            self.factor = 2
            self.setWindowTitle("Sliding - Parallax mode")
        else:
            self.factor = 1
            self.setWindowTitle("Sliding - Normal mode")
    
    def keyPressEvent(self, event):
    
        if event.key() == Qt.Key_Left:
            self.slideLeft()

        if event.key() == Qt.Key_Right:
            self.slideRight()
    
    @pyqtSignature("int")
    def moveIcons(self, x):
    
        i = 0
        for icon in self.icons:
            icon.setPos(320 + x+i*64, icon.pos().y())
            i += 1
    
    @pyqtSignature("int")
    def moveBackground(self, x):
    
        self.background.setPos(x, self.background.pos().y())
    
    @pyqtSignature("")
    def adjustParameters(self):
    
        speed = self.controls.speedSlider.value()
        self.iconTimeLine.setDuration(1200 - speed*10)
        self.backgroundTimeLine.setDuration(1200 - speed*10)
        self.setParallaxEnabled(self.controls.parallaxButton.isChecked())
        self.controls.leftButton.setEnabled(self.ofs > -640)
        self.controls.rightButton.setEnabled(self.ofs < 0)
Exemple #26
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 SixAxisView(QGraphicsView):

    def __init__(self, *args):
        QGraphicsView.__init__(self, *args)
        self.move(20, 240)
        self.outerD = 125
        self.innerD = 35
        self.innerRange = 48
        self.inputRange = 256
        self.thresh = 3
        self.padding = 40
        self.marginTop = 10
        self.worker = QSixAxisThread()
        self.worker.valueUpdated.connect(self.moveJoysticks)
        self.worker.start()
        self.setContentsMargins(0, 0, 0, 0)
        self.setMaximumHeight(180)
        self.setMaximumWidth(420)
        self.setMinimumHeight(240)
        self.setMinimumWidth(300)
        self.adjustSize()
        self.scene = QGraphicsScene(self)
        self.outerCircle1 = QGraphicsEllipseItem(0, self.marginTop, self.outerD, self.outerD)
        self.outerCircle1.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
        self.outerCircle1.setBrush(Qt.gray)
        self.innerCircle1 = QGraphicsEllipseItem(self.outerD / 2 - self.innerD / 2, self.outerD / 2 - self.innerD / 2 + self.marginTop, self.innerD, self.innerD)
        self.innerCircle1.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
        self.innerCircle1.setBrush(Qt.lightGray)
        self.scene.addItem(self.outerCircle1)
        self.scene.addItem(self.innerCircle1)
        self.outerCircle2 = QGraphicsEllipseItem(self.outerD + self.padding, self.marginTop, self.outerD, self.outerD)
        self.outerCircle2.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
        self.outerCircle2.setBrush(Qt.gray)
        self.innerCircle2 = QGraphicsEllipseItem(self.outerD + self.padding + self.outerD / 2 - self.innerD / 2, self.outerD / 2 - self.innerD / 2 + self.marginTop, self.innerD, self.innerD)
        self.innerCircle2.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
        self.innerCircle2.setBrush(Qt.lightGray)
        self.scene.addItem(self.outerCircle2)
        self.scene.addItem(self.innerCircle2)
        self.setScene(self.scene)
        self.setStyleSheet('background-color:transparent; border-width: 0px; border: 0px;')
        self.currentX = 0
        self.currentY = 0
        self.currentA = 0
        self.currentZ = 0
        self.psBtn = QPixmap(os.getcwd() + '/../icons/bt_PS.png')
        self.psBtn = self.psBtn.scaled(50, 50, Qt.KeepAspectRatio)
        self.psItem = QGraphicsPixmapItem(self.psBtn)
        self.psItem.setOffset(QPointF(self.outerD - 4, 0))
        self.effect = QGraphicsDropShadowEffect()
        self.effect.setOffset(0, 0)
        self.effect.setBlurRadius(20)
        self.effect.setColor(Qt.green)
        self.psItem.setGraphicsEffect(self.effect)
        self.scene.addItem(self.psItem)
        self.tl2 = QTimeLine(10000)
        self.tl2.setFrameRange(0, 10000)
        self.c = QGraphicsItemAnimation()
        self.c.setItem(self.psItem)
        self.c.setTimeLine(self.tl2)
        self.tl2.connect(self.tl2, SIGNAL('frameChanged(int)'), self.updateEffect)
        self.effectd = 3
        self.tl2.start()

    def updateEffect(self):
        if self.effect.blurRadius() > 50:
            self.effectd = -3
        elif self.effect.blurRadius() < 5:
            self.effectd = 3
        self.effect.setBlurRadius(self.effect.blurRadius() + self.effectd)

    def update(self, *args, **kwargs):
        return QGraphicsView.update(self, *args, **kwargs)

    def moveJoysticks(self, x, y, a, z, l3, r3):
        x2 = x * self.innerRange / self.inputRange - self.innerRange / 2
        y2 = y * self.innerRange / self.inputRange - self.innerRange / 2
        a2 = a * self.innerRange / self.inputRange - self.innerRange / 2
        z2 = z * self.innerRange / self.inputRange - self.innerRange / 2
        if -self.thresh <= x2 <= self.thresh:
            x2 = 0
        if -self.thresh <= y2 <= self.thresh:
            y2 = 0
        if -self.thresh <= a2 <= self.thresh:
            a2 = 0
        if -self.thresh <= z2 <= self.thresh:
            z2 = 0
        self.tl = QTimeLine(10)
        self.tl.setFrameRange(0, 10)
        self.a = QGraphicsItemAnimation()
        self.a.setItem(self.innerCircle1)
        self.a.setTimeLine(self.tl)
        self.a.setPosAt(0, QPointF(self.currentX, self.currentY))
        self.a.setTranslationAt(1, x2, y2)
        if l3:
            self.innerCircle1.setPen(QPen(QColor(Qt.white), 1, Qt.SolidLine))
            self.innerCircle1.setBrush(QColor(200, 225, 3))
        else:
            self.innerCircle1.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
            self.innerCircle1.setBrush(Qt.lightGray)
        if r3:
            self.innerCircle2.setPen(QPen(QColor(Qt.white), 1, Qt.SolidLine))
            self.innerCircle2.setBrush(QColor(200, 225, 3))
        else:
            self.innerCircle2.setPen(QPen(QColor(Qt.darkGray), 1, Qt.SolidLine))
            self.innerCircle2.setBrush(Qt.lightGray)
        self.b = QGraphicsItemAnimation()
        self.b.setItem(self.innerCircle2)
        self.b.setTimeLine(self.tl)
        self.b.setPosAt(0, QPointF(self.currentA, self.currentZ))
        self.b.setTranslationAt(1, a2, z2)
        self.currentX = x2
        self.currentY = y2
        self.currentA = a2
        self.currentZ = z2
        self.tl.start()
Exemple #28
0
class QPageWidget(QScrollArea):
    """ The QPageWidget provides a stack widget with animated page transitions. """
    def __init__(self, parent=None, direction="ltr", rtf=False):
        """ Creates a new QPageWidget on given parent object. 

        parent: QWidget parent
        direction: "ltr" -> Left To Right
                   "ttb" -> Top To Bottom
        rtf: Return to first, if its True it flips to the first page 
             when next page requested at the last page
        """
        # First initialize, QPageWidget is based on QScrollArea
        QScrollArea.__init__(self, parent)

        # Properties for QScrollArea
        self.setFrameShape(QFrame.NoFrame)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidgetResizable(True)

        # Main widget, which stores all Pages in it
        self.widget = QWidget(self)

        # Layout based on QBoxLayout which supports Vertical or Horizontal layout
        if direction == "ltr":
            self.layout = QBoxLayout(QBoxLayout.LeftToRight, self.widget)
            self.__scrollBar = self.horizontalScrollBar()
            self.__base_value = self.width
        else:
            self.layout = QBoxLayout(QBoxLayout.TopToBottom, self.widget)
            self.__scrollBar = self.verticalScrollBar()
            self.__base_value = self.height
        self.layout.setSpacing(0)
        self.layout.setMargin(0)

        # Return to first
        self.__return_to_first = rtf

        # TMP_PAGE, its using as last page in stack
        # A workaround for a QScrollArea bug
        self.__tmp_page = Page(QWidget(self.widget))
        self.__pages = [self.__tmp_page]
        self.__current = 0
        self.__last = 0

        # Set main widget
        self.setWidget(self.widget)

        # Animation TimeLine
        self.__timeline = QTimeLine()
        self.__timeline.setUpdateInterval(2)

        # Updates scrollbar position when frame changed
        self.__timeline.frameChanged.connect(
            lambda x: self.__scrollBar.setValue(x))

        # End of the animation
        self.__timeline.finished.connect(self._animateFinished)

        # Initialize animation
        self.setAnimation()
        self.setDuration()

    def _animateFinished(self):
        """ Its called by TimeLine when animation finished.

        It first runs the outMethod of last Page and then the inMethod of current Page
        Finally tt gives the focus to the current page and fixes the scrollBar
        """

        # Disable other widgets
        for page in self.__pages:
            if not page == self.__pages[self.__current]:
                page.widget.setEnabled(False)

        # Run last page's outMethod if exists
        if self.__pages[self.__last].outMethod:
            self.__pages[self.__last].outMethod()

        # Run new page's inMethod if exists
        if self.__pages[self.__current].inMethod:
            self.__pages[self.__current].inMethod()

        # Give focus to the current Page
        self.__pages[self.__current].widget.setFocus()

        # Update scrollbar position for current page
        self.__scrollBar.setValue(self.__current * self.__base_value())

        # Emit currentChanged SIGNAL
        self.emit(SIGNAL("currentChanged()"))

    def event(self, event):
        """ Overrides the main event handler to catch resize events """
        # Catch Resize event
        if event.type() == QEvent.Resize:
            # Update each page size limits to mainwidget's new size
            for page in self.__pages:
                page.widget.setMinimumSize(self.size())
                page.widget.setMaximumSize(self.size())

            # Update viewport size limits to mainwidget's new size
            # It's a workaround for QScrollArea updateGeometry bug
            self.viewport().setMinimumSize(self.size())
            self.viewport().setMaximumSize(self.size())

            # Update scrollbar position for current page
            self.__scrollBar.setValue(self.__current * self.__base_value())

        # Return the Event
        return QScrollArea.event(self, event)

    def keyPressEvent(self, event):
        """ Overrides the keyPressEvent to ignore them """
        pass

    def wheelEvent(self, event):
        """ Overrides the wheelEvent to ignore them """
        pass

    def createPage(self, widget, inMethod=None, outMethod=None):
        """ Creates and adds new Page for given widget with given in/out methods.

        widget: A QWidget which is the mainwidget for this Page
        inMethod: (optional) QPageWidget triggers this method when the Page appear
        outMethod: (optional) QPageWidget triggers this method when the Page disappear
        """
        self.addPage(Page(widget, inMethod, outMethod))

    def addPage(self, page):
        """ Adds the given Page to the stack.

        page: A Page object
        """
        # First remove the last page; its __tmp_page
        self.__pages.pop()

        # Add new page
        self.__pages.append(page)
        self.layout.addWidget(page.widget)

        # Add __tmp_page to end
        self.__pages.append(self.__tmp_page)
        self.layout.addWidget(self.__tmp_page.widget)

        # Create connections for page navigation signals from new page
        self.connect(page.widget, SIGNAL("pageNext()"), self.next)
        self.connect(page.widget, SIGNAL("pagePrevious()"), self.prev)
        self.connect(page.widget, SIGNAL("setCurrent(int)"), self.setCurrent)

    def __setCurrent(self, pageNumber):
        """ Internal method to set current page index. """
        self.__last = self.__current
        self.__current = min(max(0, pageNumber), len(self.__pages) - 2)
        if pageNumber == len(self.__pages) - 1 and self.__return_to_first:
            self.__current = 0

    def setCurrent(self, pageNumber=0):
        """ Set and flip the page with given pageNumber.

        pageNumber: index number of Page (default is 0)
        """
        self.__setCurrent(pageNumber)
        self.flipPage()

    def getCurrent(self):
        """ Returns current page index. """
        return self.__current

    def getCurrentWidget(self):
        """ Returns current page widget. """
        return self.getWidget(self.getCurrent())

    def getWidget(self, pageNumber):
        """ Returns widget for given page index 

        pageNumber: index number of Page
        """
        try:
            return self.__pages[pageNumber].widget
        except:
            return None

    def count(self):
        """ Returns number of pages. """
        return len(self.__pages) - 1

    def setAnimation(self, animation=35):
        """ Set the transition animation with the given animation.

        animation: the number represents predefined QEasingCurves
                   List of predefined QEasingCurves can be found from:
                   http://doc.qt.nokia.com/4/qeasingcurve.html#Type-enum

                   Default is QEasingCurve::InOutBack (35)
        """
        self.__animation = animation
        self.__timeline.setEasingCurve(QEasingCurve(self.__animation))

    def setDuration(self, duration=400):
        """ Set the transition duration.

        duration: duration time in ms
        """
        self.__duration = duration
        self.__timeline.setDuration(self.__duration)

    def flipPage(self, direction=0):
        """ Flip the page with given direction.

        direction: can be -1, 0 or +1
                   -1: previous page (if exists)
                    0: just flip to current page
                   +1: next page (if exists)
        """
        # Enable all widgets
        for page in self.__pages:
            page.widget.setEnabled(True)

        # Check given direction
        direction = direction if direction == 0 else max(min(1, direction), -1)

        # If direction is equal to zero no need to re-set current
        if not direction == 0:
            self.__setCurrent(self.__current + direction)

        # If last page is different from new page, flip it !
        if not self.__last == self.__current:
            self.__timeline.setFrameRange(self.__scrollBar.value(),
                                          self.__current * self.__base_value())
            self.__timeline.start()

    def next(self):
        """ Helper method to flip next page. """
        self.flipPage(1)

    def prev(self):
        """ Helper method to flip previous page. """
        self.flipPage(-1)
class ViewMain(QMainWindow):
    """This Class Provides the Graphical Interface for Game"""

    # Use Constants To Avoid Magic Numbers
    
    # Declare stack widget names
    MAIN_PAGE = 0
    SETTINGS_PAGE = 1
    GAME_PAGE = 2
    INSTRUCTIONS_PAGE = 3
    CREDITS_PAGE = 4
    STORY_PAGE = 5
    SCORE_PAGE = 6

    finished = pyqtSignal()
    
    def __init__(self, parent=None):
        """Initialize the abstracted class instance"""
        super(ViewMain, self).__init__(parent)

        # Init Data Members
        self.gui  = Gui(self)
        self.game = None
        self.connectGui()

        self.gameWasLoaded = False
        self.useLoadWorkaround = True

        # Dictionary of Graphics Objects
        self.graphicsObjects = {}
        
        # Overlays
        self.overlays = {}
        
        self.currStackIndex = self.MAIN_PAGE
        self.gui.soundManager.playCurrMusic()
        #self.gui.soundManager.setVolume(0)
        
        # Timer initialization and setup for normal popups
        self.popupTimelineStart = QTimeLine(200)
        self.popupTimelineStart.setFrameRange(0,100)
        self.popupTimelineEnd = QTimeLine(200)
        self.popupTimelineEnd.setFrameRange(0,100)
        self.popupTimelineWait = QTimeLine()
        self.popupTimelineWait.setFrameRange(0,100)
        self.popupClue = False
        self.popupStory = False
        
        # Initialization and setup for animated popups
        self.popupAnimationOpen = QPropertyAnimation(self.gui.popup,"geometry")
        self.popupAnimationOpen.setDuration(200)
        self.popupAnimationOpen.setStartValue(QRect(0, 591, 0, 0))
        self.popupAnimationOpen.setEndValue(QRect(25, 25, 750, 450))
        self.popupAnimationClose = QPropertyAnimation(self.gui.popup,"geometry")
        self.popupAnimationClose.setDuration(200)
        self.popupAnimationClose.setStartValue(QRect(25, 25, 750, 450))
        self.popupAnimationClose.setEndValue(QRect(0, 591, 0, 0))
        self.popupAnimationWait = QTimeLine()
        
        self.toMain = False
        #self.gui.personView.centerOn(0,0)
        self.gui.mapView.centerOn(0,0)
        
########################################
### Signals and slots connected here ###
########################################

        # Connections for normal popups
        self.popupTimelineStart.frameChanged.connect(self.drawPopup)
        self.popupTimelineStart.finished.connect(self.popupWait)
        self.popupTimelineEnd.frameChanged.connect(self.erasePopup)   
        self.popupTimelineWait.finished.connect(self.enableErasePopup) 
        self.popupTimelineEnd.finished.connect(self.writeClue)
        
        # Connections for animated popups
        self.popupAnimationOpen.finished.connect(self.popupAnimationWait.start)
        self.popupAnimationWait.finished.connect(self.popupAnimationClose.start)
        self.popupAnimationClose.finished.connect(self.popupAnimationCleanup)
        self.finished.connect(self.writeStory)
    
    def connectGui(self):
        """Connect signals for Gui"""
        self.gui.actionQuit.triggered.connect(self.close)
        self.gui.quitButton.released.connect(self.close)
        self.gui.settingsButton.released.connect(self.setSettings)
        self.gui.actionSettings.triggered.connect(self.setSettings)
        self.gui.loadButton.released.connect(self.loadFileDialog)
        self.gui.actionSave_Game.triggered.connect(self.saveFileDialog)
        self.gui.doneButton.released.connect(self.goBack)
        self.gui.startButton.released.connect(self.enterName)
        self.gui.actionMain_Menu.triggered.connect(self.setMain)
        self.gui.actionHelp.triggered.connect(self.setInstructions)
        self.gui.instrButton.released.connect(self.setInstructions)
        self.gui.doneButton2.released.connect(self.goBack)
        self.gui.doneButton3.released.connect(self.goBack)
        self.gui.doneButtonScore.released.connect(self.scoreButton)
        self.gui.actionCredits.triggered.connect(self.setCredits)
        self.gui.latLongCheck.stateChanged.connect(self.latLong)
        self.gui.colorCheck.stateChanged.connect(self.colorize)
        self.gui.legendCheck.stateChanged.connect(self.legend)
        self.gui.searchButton.released.connect(self.doSearch)
        self.gui.nextButton.released.connect(self.storyButton)
        self.gui.volumeSlider.sliderMoved.connect(self.setVol)
        
    def connectGame(self):
        """Connect signals for Game"""
        self.game.places.passLoc.connect(self.addGraphicsObject)
        self.game.frameTimer.timeout.connect(self.frameUpdate)
        self.game.frameTimer.timeout.connect(self.game.story.frameTime)
        self.game.story.clueTrouble.connect(self.giveHint)

########################################
###### Custom slots defined here #######
########################################

    def setSettings(self):
        """Change to the settings page in the stack widget"""
        self.setStackWidgetIndex(self.SETTINGS_PAGE)
        
    def setInstructions(self):
        """Change to the instructions page in the stack widget"""
        self.setStackWidgetIndex(self.INSTRUCTIONS_PAGE)

    def setCredits(self):
        """Change to the credits page in the stack widget"""
        self.setStackWidgetIndex(self.CREDITS_PAGE)
        
    def goBack(self):
        """Return to the last primary page in the stack"""
        self.setStackWidgetIndex(self.gui.stackIndex)
        if self.gui.stackIndex == self.GAME_PAGE:
            self.gui.background.setPixmap(self.gui.backgroundPixmapSettings)
        else:
            self.gui.background.setPixmap(self.gui.backgroundPixmapMenu)
    
    def scoreButton(self):
        """Set widget to main menu after winning the game"""
        self.setStackWidgetIndex(self.MAIN_PAGE)
        self.gui.stackIndex = self.MAIN_PAGE
        
    def scoreWidget(self):
        """change to score widget"""
        self.game.loadScores()
        if self.game.topTen:
            text = "Congratulations "+ self.game.playerName+ \
                   ".\nYou make the Top Ten List !!"
        else:
            text = "Congratulations "+ self.game.playerName + \
                   ".\nYour score is "+ `self.game.story.score` + "!!"
        self.gui.scores.setText(text)
        self.displayHighScores()
        self.setStackWidgetIndex(self.SCORE_PAGE)
    
    def displayHighScores(self):
        """After player wins the game, we want to display
           the 10th high scores on screen
        """
        text = ""
        markCurr = 0 # Mark curr player if he made to the top ten list
        debug("len of scoreLIst is: ", len(self.game.scoreList))
        for prevPlayer in self.game.scoreList:
            prevName = prevPlayer[0]
            prevScore = prevPlayer[1]
            if (markCurr == 0 and prevName == self.game.playerName \
            and prevScore == self.game.story.score):
                markCurr = 1
                text = text + prevPlayer[0] + 40*"."  + `prevPlayer[1]` + "  *****" + "\n"
            else:
                text = text + prevPlayer[0] + 40*"."  + `prevPlayer[1]` + "\n"
        self.gui.topTenScores.setText(text)
        self.game.writeScoreToFile() 
 

    def enterName(self):
        """Name enter dialog"""
        playerName, ok = QInputDialog.getText(self, 'Enter Name Dialog', 
            'Please enter your name:')

        if ok and playerName!="":
            self.newGame()
            self.game.playerName = playerName
        else:
            pass
            
    def loadFileDialog(self):
        """pop up the loading dialog for players to choose saved file"""
        fd = QFileDialog()
        filename = fd.getOpenFileName(None, "Load Saved Game",
                                      "saves", "MapMaster Save files (*.save)")

        if isfile(filename):
            self.loadGame(filename)
        
            self.gameWasLoaded = True
            self.filename = filename
        else:
            debug("invalid file")

    def loadGame(self, filename):
        """pop up the loading dialog for players to choose saved file"""

        self.setStackWidgetIndex(self.GAME_PAGE)
        self.game = Game() 
        self.connectGame()
        self.game.load(filename)
        debug("Initializing the saved game...")
        
        
        self.overlays['latLongOverlay'] = self.addOverlay(
                    normpath("images/latOverlayNew.png"))
        self.overlays['colorOverlay'] = self.addOverlay(
                    normpath("images/colorOverlay.png"))
        self.overlays['legendOverlay'] = self.addOverlay(
                    normpath("images/legendOverlayNew.png"))

        self.gui.scoreBox.setText((str)(self.game.story.score))
        self.gui.clueView.setText(self.game.story.currClue['text'])
        self.gui.stackIndex = self.GAME_PAGE

    def saveFileDialog(self,toMain = False):
        """Dialog to save a game"""
        filename = QFileDialog.getSaveFileName(None, "Save Game", "saves", 
                                               "MapMaster Save files (*.save)")        
        if filename == "":
            return False
        else:
            if ".save" not in filename:
                debug(".save is not in the file, add one..")
                filename = filename + ".save"
            debug("correctly save data to file...",filename)
            self.game.save(filename)    
              
                        
    def newGame(self):
        """Start a new game"""
        self.gui.background.setPixmap(self.gui.backgroundPixmapSettings)
        self.setStackWidgetIndex(self.STORY_PAGE)
        self.gui.stackIndex = self.STORY_PAGE
        
        # Create game instance and start the game
        self.game = Game()
        self.connectGame()
        self.game.new()
        debug("Starting a new game")
        
        self.overlays['latLongOverlay'] = self.addOverlay(
                        normpath("images/latOverlayNew.png"))
        self.overlays['colorOverlay'] = self.addOverlay(
                        normpath("images/colorOverlay.png"))
        self.overlays['legendOverlay'] = self.addOverlay(
                        normpath("images/legendOverlayNew.png"))
        self.gui.clueView.setText(self.game.story.currClue['text'])
        self.gui.scoreBox.setText((str)(0))

        self.gameWasLoaded = False
        
    def storyButton(self):
        """Continue from the story page to the game page"""
        self.setStackWidgetIndex(self.GAME_PAGE)
        self.gui.stackIndex = self.GAME_PAGE

    def setMain(self):
        """Create a message box when player want to go back to main menu
           from the middle of the game. Make sure that player save the game.
        """
        quit_msg = "Go back to Main Menu will lose all the game, are you sure?"
        reply = QMessageBox()
        reply.setWindowTitle("Back to Main")
        reply.setText(quit_msg)
        reply.setStandardButtons(
             QMessageBox.Ok | QMessageBox.Save |  QMessageBox.Cancel)
        reply.setDefaultButton(QMessageBox.Save)
        ret = reply.exec_()
        
        if ret == QMessageBox.Ok:
            debug( "Go back to main menu" )
            self.gui.background.setPixmap(self.gui.backgroundPixmapMenu)
            self.setStackWidgetIndex(self.MAIN_PAGE)
            self.gui.stackIndex = self.MAIN_PAGE
        elif ret == QMessageBox.Cancel:
            debug("cancel back to main menu action...")
            pass
        else:
            if (self.saveFileDialog() == False):
                debug("Not save yet, go back to game...")
                pass
            else:
                debug("save and back to main menu...")
                self.gui.background.setPixmap(self.gui.backgroundPixmapMenu)
                self.setStackWidgetIndex(self.MAIN_PAGE)
                self.gui.stackIndex = self.MAIN_PAGE
        
    def setStackWidgetIndex(self, index):
        """Allow to switch between widgets."""
        if index == self.MAIN_PAGE:
            self.gui.background.setPixmap(self.gui.backgroundPixmapMenu)
        else:
            self.gui.background.setPixmap(self.gui.backgroundPixmapSettings)
    
        self.gui.stackedWidget.setCurrentIndex(index)
        self.currStackIndex = index
        self.gui.soundManager.switchSongs(index)
    
    def latLong(self):
        """Turn on/off latitude graphic overlays in the mapView"""
        if self.gui.latLongCheck.isChecked():
            debug("Lat/long overlay on")
        else:
            debug("Lat/long overlay off")
        self.overlays['latLongOverlay'].setVisible(
                                        self.gui.latLongCheck.isChecked())
    
    def colorize(self):
        """Turn on/off color coding graphic overlays in the mapView"""
        if self.gui.colorCheck.isChecked():
            debug("Color overlay on")
        else:
            debug("Color overlay off")
        self.overlays['colorOverlay'].setVisible(
                                        self.gui.colorCheck.isChecked())
                                        
    def legend(self):
        """Turn on/off legend graphic overlays in the mapView"""
        if self.gui.legendCheck.isChecked():
            debug("Legend overlay on")
        else:
            debug("Legend overlay off")
        self.overlays['legendOverlay'].setVisible(
                                        self.gui.legendCheck.isChecked())

    def setVol(self):
        """Set volumn level for the game"""
        self.gui.soundManager.setVolume(self.gui.volumeSlider.sliderPosition())
        
    def doSearch(self):
        """Begins searching for a clue"""
        self.popupClue = True
        self.popupMessage("Searching...", 2*ONE_SECOND)
    
    def writeClue(self):
        """Handles the result of searching for a clue"""
        self.popupStory = False
        if self.popupClue:
            clueResult = self.game.story.searchForClue(
                                        self.game.character.getCenter())
            self.handleClueResult(clueResult[0], clueResult[1])
            self.popupClue = False
            if clueResult[0] == 'ClueFound':
                self.popupMessageAnimated(
                        'You found a clue!\n' + clueResult[1], 4*ONE_SECOND)
                self.gui.soundManager.playSound("success")
            elif clueResult[0] == 'ClueFailed':
                self.popupMessage(clueResult[1], 2*ONE_SECOND)
                self.gui.soundManager.playSound("failure")
            elif clueResult[0] == 'GameOver':
                self.popupMessage(clueResult[1], 5*ONE_SECOND) 
                self.gui.soundManager.playSound("victory")
                QTimer.singleShot(4*ONE_SECOND, self.scoreWidget)
            else:
                None

    def writeStory(self):
        """Handles drawing story"""
        if self.game.story.currClue['story'] != 'none':
            self.popupStory = True
            self.popupMessage(self.game.story.currClue['story'], 5*ONE_SECOND)
           
    def drawPopup(self, value):
        """Draws the popup to the screen"""
        debug("Called drawPopup")
        if self.popupStory:
            self.gui.popupStoryImage.setOpacity(value/100.0)
        else:
            self.gui.popupImage.setOpacity(value/100.0)
        self.gui.popupText.setOpacity(value/100.0)
        
    def enableErasePopup(self):
        """Starts the timeline for erasePopup"""
        debug("Enabled erase popup")
        self.popupTimelineEnd.start()
        
    def erasePopup(self, value):
        """Erases the popup from the screen"""
        debug("Called erase popup")
        if self.popupStory:
            self.gui.popupStoryImage.setOpacity(1-(value/100.0))
        else:
            self.gui.popupImage.setOpacity(1-(value/100.0))
        self.gui.popupText.setOpacity(1-(value/100.0))
        
    def popupWait(self):
        """Keeps the popup on the screeen"""
        debug("Entered popupWait")
        self.popupTimelineWait.start()
        
    def popupMessageAnimated(self, text, time):
        """Uses an animated popup to display text for some time"""
        self.gui.popupText.setPlainText('')
        self.gui.popup.setGeometry(QRect(0, 591, 0, 0))
        self.gui.popupImage.setOpacity(1)
        self.popupAnimationWait.setDuration(time)
        self.popupAnimationOpen.start()
        self.gui.popupText.setPlainText(text)
        self.gui.popupText.setOpacity(1)
        
    def popupAnimationCleanup(self):
        """Returns the popup to its original state after it finishes"""
        self.gui.popupImage.setOpacity(0)
        self.gui.popupText.setOpacity(0)
        self.gui.popup.setGeometry(QRect(25, 25, 750, 450))
        self.finished.emit()
        
    def handleClueResult(self, action, text):
        """Performs the writing to gui after a clue was found"""
        if action == 'ClueFound':
            self.gui.clueView.setText(text)
            self.gui.scoreBox.setText(`self.game.story.score`)
        elif action == 'GameOver':
            self.gui.clueView.setText(text)
        else:
            None
            
    def giveHint(self):
        """If the player has been stuck on a clue, give a hint"""
        text = self.game.story.troubleFindingClue()
        self.popupMessage(text, 5*ONE_SECOND)
    
    def popupMessage(self, text, time):
        """Displays the given text for the given time in a popup"""
        self.gui.popupText.setPlainText(text)
        self.popupTimelineWait.setDuration(time)
        self.popupTimelineStart.start()
       
    def keyPressEvent(self, event):
        """Get keyboard events no matter what widget has focus"""
        if self.game and (self.gui.stackIndex == self.GAME_PAGE):
            self.game.keyPress(event)

        #Work around to make load work.
        if self.useLoadWorkaround and self.gameWasLoaded:
            self.game = Game() 
            self.connectGame()
            self.game.load(self.filename)
            
            debug("use work round")
            self.useLoadWorkaround = False

            self.overlays['latLongOverlay'] = self.addOverlay(
                    normpath("images/latOverlayNew.png"))
            self.overlays['colorOverlay'] = self.addOverlay(
                        normpath("images/colorOverlay.png"))
            self.overlays['legendOverlay'] = self.addOverlay(
                        normpath("images/legendOverlayNew.png"))
        
    
    def keyReleaseEvent(self, event):
        """Get keyboard events no matter what widget has focus"""
        if self.game and (self.gui.stackIndex == self.GAME_PAGE):
            key = event.key()
            if key==Qt.Key_Space or key==Qt.Key_Enter or key==Qt.Key_Return:
                self.doSearch()
            elif key==Qt.Key_L:
                debug('Character location is ' 
                        + `self.game.character.getCenter()`)
            else:
                self.game.keyRelease(event)
    
    def closeEvent(self, event):
        """Remapping the close event to a message box"""
        quit_msg = "Are you sure you want to quit?"
        reply = QMessageBox()
        reply.setWindowTitle("Quit Game")
        reply.setText(quit_msg)
        reply.setStandardButtons(
            QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
        reply.setDefaultButton(QMessageBox.Save)
        ret = reply.exec_()
        
        if ret == QMessageBox.Discard:
            debug("Accepting close event")
            event.accept()
        elif ret == QMessageBox.Cancel:
            event.ignore()
        else:
            if (self.saveFileDialog() == False):
                debug("Not quit yet, go back to game...")
                event.ignore()
            else:
                debug("Accepting close event")
                event.accept()

    def addGraphicsObject(self, name, xval, yval, objType):
        """Add graphics object to the person veiw and map view properly and
        leave a graphics object in ViewMain to handle it. """
        debug("Receiving passLoc")
        graphic = Graphic(xval, yval, str(name), str(objType))
        graphic.createInitial(self.gui.personView, self.gui.mapView)
        self.graphicsObjects[name] = graphic
        self.game.places.locList[str(name)].changePos.connect(
                                        self.updateGraphicsObject)
        debug("Connecting Loc to Graphic for " + name)
        
        self.game.places.locList[str(name)].emitter()
        
    def updateGraphicsObject(self, xpos, ypos, name):
        """Changes the position of the character on the screen"""
        self.graphicsObjects[name].update(xpos, ypos)
        
    def addOverlay(self, filename):
        """Adds an overlay to the map view"""
        obj = self.gui.mapView.scene.addPixmap(QPixmap(filename))
        obj.setX(-195)
        obj.setY(-250)
        obj.setVisible(False)
        return obj
        
    def frameUpdate(self):
        """One tick of the game clock sent to the character"""
        self.game.character.frameUpdate(self.game.FRAME_RATE)