Beispiel #1
0
class CometManagerProxy(QObject):
    def __init__(self, parent=None):
        super(CometManagerProxy, self).__init__(parent)
        dm = manager()
        dm.termTopicConnectionCountChanged.connect(
            self.termTopicConnectionCountChanged)

    termTopicConnectionCountChanged = Signal(int)
    termTopicConnectionCount = Property(
        int,
        lambda self: manager().termTopicConnectionCount(),
        notify=termTopicConnectionCountChanged)
Beispiel #2
0
class ClickFrame(QFrame):
    """Frame that sends a signal on click."""

    clicked = Signal()

    def __init__(self, parent=None, flags=0):
        """Create ClickFrame widget."""
        super(ClickFrame, self).__init__(parent, flags)

    def mousePressEvent(self, event):
        """Emits the clicked signal."""
        self.clicked.emit()
Beispiel #3
0
class PostInputManagerBean(QObject):
    def __init__(self, parent=None, manager=None):
        super(PostInputManagerBean, self).__init__(parent)
        self.manager = manager or PostInputManager(self)
        self.manager.postReceived.connect(self.postReceived)

    postReceived = Signal(unicode, unicode)  # json post, json image

    @Slot(long, str)
    def newPost(self, topicId, postType):
        self.manager.newPost(topicId=topicId, type=postType)

    @Slot(long, long)
    def replyPost(self, topicId, postId):
        self.manager.newPost(topicId=topicId, replyId=postId, type='reply')

    imageEnabledChanged = Signal(bool)
    imageEnabled = Property(bool,
                            lambda self: self.manager.isImageEnabled(),
                            lambda self, t: self.manager.setImageEnabled(t),
                            notify=imageEnabledChanged)
Beispiel #4
0
class TopicEditorManagerBean(QObject):
  def __init__(self, parent=None, manager=None):
    super(TopicEditorManagerBean, self).__init__(parent)
    self.manager = manager or TopicEditorManager(self)
    self.manager.topicChanged.connect(self.topicChanged)

  topicChanged = Signal(unicode, unicode, unicode) # json topic, json image, json tickets

  imageEnabledChanged = Signal(bool)
  imageEnabled = Property(bool,
      lambda self: self.manager.isImageEnabled(),
      lambda self, t: self.manager.setImageEnabled(t),
      notify=imageEnabledChanged)

  @Slot(unicode)
  def editTopic(self, data): # json ->
    try:
      topic = json.loads(data)
      topic['id'] = long(topic['id'])
      self.manager.editTopic(**topic)
    except Exception, e: dwarn(e)
Beispiel #5
0
class WbAddressEdit(QtWidgets.QComboBox):
    def __init__(self, parent=None):
        super(WbAddressEdit, self).__init__(parent)
        self.__d = _WbAddressEdit(self)
        self.setInsertPolicy(QtWidgets.QComboBox.InsertAtTop)
        self.setEditable(True)

        #self.currentIndexChanged.connect(self.enter) # recursion
        #self.lineEdit().returnPressed.connect(self.enter)

        self.maxCount = config.ADDRESS_HISTORY_SIZE

        self.setToolTip("Ctrl+L, Alt+D")

        completer = self.completer()
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        completer.setCompletionMode(
            QtWidgets.QCompleter.UnfilteredPopupCompletion)
        completer.setModelSorting(
            QtWidgets.QCompleter.CaseInsensitivelySortedModel)

    textEntered = Signal(unicode)

    #def enter(self):
    #  t = self.currentText().strip()
    #  if t:
    #    self.setText(t)
    #    self.textEntered.emit(t)

    def focus(self):
        self.setFocus()
        self.lineEdit().selectAll()

    def setText(self, text):  # unicode ->
        self.addText(text)
        #self.setEditText(text)
        self.setCurrentIndex(0)

    def addText(self, text):  # unicode ->
        index = self.findText(text)
        if index >= 0:
            self.removeItem(index)

        icon = rc.url_icon(text)
        self.insertItem(0, icon, text)  # Note: This will change current item!
        if self.count() > self.maxCount:
            self.removeItem(self.maxCount)

    def setProgress(self, v):  # int [0,100]
        d = self.__d
        if d.progress != v:
            d.progress = v
            d.refreshPallete()
Beispiel #6
0
class HubOpenFile(QObject):
    def __init__(self):
        super(HubOpenFile, self).__init__()

    @Slot(str)
    def connect(self, config):

        txtFileName = QFileDialog.getOpenFileNames(None, "Open")[0]
        txtFileName = str(txtFileName).replace("[u'", '').replace("']", '')
        print(txtFileName)

        text = open(txtFileName).read()
        self.on_file_open_event.emit(text)

    @Slot(str)
    def disconnect(self, config):
        print(config)

    on_file_open_event = Signal(str)
    on_connect = Signal(str)
    on_disconnect = Signal(str)
Beispiel #7
0
class PunchingBag(QObject):
    ''' Represents a punching bag; when you punch it, it
        emits a signal that indicates that it was punched. '''
    punched = Signal()

    def __init__(self):
        # Initialize the PunchingBag as a QObject
        QObject.__init__(self)

    def punch(self):
        ''' Punch the bag '''
        self.punched.emit()
Beispiel #8
0
    class SkTaskBarObject(SkWindowObject):
        def __init__(self, parent=None):
            super(SkTaskBarObject, self).__init__(parent)

        def setAutoHide(self, t):
            pass

        autoHideChanged = Signal(bool)
        autoHide = Property(bool,
                            lambda self: False,
                            setAutoHide,
                            notify=autoHideChanged)
class QtReduceFontSizeComboBoxFs(QtReduceComboBox):
    currentFontSizeChangedFs = Signal(StringType)

    def __init__(self,parent=None):
        super(QtReduceFontSizeComboBoxFs,self).__init__()
        self.currentIndexChanged.connect(self.currentIndexChangedHandler)

    def currentFontSize(self):
        return self.findText(currentSize)

    def currentIndexChangedHandler(self,index):
        return self.currentFontSizeChangedFs.emit(self.currentText())
Beispiel #10
0
class StarEditor(QWidget):
    """ The custome editor for editing StarRatings. """

    # A signal to tell the delegate when we've finished editing.
    editingFinished = Signal()

    def __init__(self, parent=None):
        """ Initialize the editor object, making sure we can watch mouse
            events.
        """
        super(StarEditor, self).__init__(parent)

        self.setMouseTracking(True)
        self.setAutoFillBackground(True)

    def sizeHint(self):
        """ Tell the caller how big we are. """
        return self.starRating.sizeHint()

    def paintEvent(self, event):
        """ Paint the editor, offloading the work to the StarRating class. """
        painter = QPainter(self)
        self.starRating.paint(painter,
                              self.rect(),
                              self.palette(),
                              isEditable=True)

    def mouseMoveEvent(self, event):
        """ As the mouse moves inside the editor, track the position and 
            update the editor to display as many stars as necessary. 
        """
        star = self.starAtPosition(event.x())

        if (star != self.starRating.starCount) and (star != -1):
            self.starRating.starCount = star
            self.update()

    def mouseReleaseEvent(self, event):
        """ Once the user has clicked his/her chosen star rating, tell the
            delegate we're done editing.
        """
        self.editingFinished.emit()

    def starAtPosition(self, x):
        """ Calculate which star the user's mouse cursor is currently 
            hovering over.
        """
        star = (x / (self.starRating.sizeHint().width() /
                     self.starRating.maxStarCount)) + 1
        if (star <= 0) or (star > self.starRating.maxStarCount):
            return -1

        return star
Beispiel #11
0
class View(QDeclarativeView):
    def __init__(self):
        QDeclarativeView.__init__(self)
        self.setSource(
            QUrl.fromLocalFile(adjust_filename('bug_847.qml', __file__)))
        self.rootObject().setProperty('pythonObject', self)

    @Slot(int, int)
    def blubb(self, x, y):
        self.called.emit(x, y)

    called = Signal(int, int)
Beispiel #12
0
class ClickLabel(QLabel):
    """Label that sends a signal on click."""

    clicked = Signal()

    def __init__(self, parent=None, flags=0):
        """Create a ClickLabel widget."""
        super(ClickLabel, self).__init__(parent, flags)

    def mousePressEvent(self, event):
        """Emits the clicked signal."""
        self.clicked.emit()
Beispiel #13
0
class SignalHandler(QObject):

    clearSignal = Signal()
    newUser = Signal(str)
    stopSignal = Signal()
    refreshSignal = Signal()
    stopCon = Signal(int)
    newmsg = Signal(str)

    def __init__(self):
        QObject.__init__(self)

    def clear(self):
        self.clearSignal.emit()

    def new_User(self, name):
        self.newUser.emit(name)

    def stop(self):
        self.stopSignal.emit()

    def refresh(self):
        self.refreshSignal.emit()

    def stopConnection(self, i):
        self.stopCon.emit(i)

    def msg(self, text):
        self.newmsg.emit(text)
Beispiel #14
0
class ViewModelSignals(QObject):
    updateProduction = Signal(str)
    updateDepartment = Signal(str)
    updateBody = Signal(str)
    updateCheckedOutBodies = Signal(dict)
    updateOverviewBodies = Signal(tuple, dict)
    changePage = Signal(int, list)
Beispiel #15
0
class RpcServer(QObject):
    def __init__(self, parent=None):
        super(RpcServer, self).__init__(parent)
        self.__d = _RpcServer(self)

    activated = Signal()

    def stop(self):
        self.__d.server.stop()

    def start(self):
        """@return  bool"""
        return self.__d.server.start()

    def isActive(self):
        """@return  bool"""
        return self.__d.server.isActive()

    activated = Signal()

    # Agent

    agentConnected = Signal(long)  # pid
    agentDisconnected = Signal(long)  # pid
    windowTextsReceived = Signal(dict)  # {long hash:unicode text}
    engineReceived = Signal(str)  # name
    engineTextReceived = Signal(unicode, str, long, int,
                                bool)  # text, hash, role, needsTranslation

    def isAgentConnected(self):
        return bool(self.__d.agentSocket)

    def closeAgent(self):
        self.__d.closeAgentSocket()

    #def enableAgent(self): self.__d.callAgent('enable')
    def disableAgent(self):
        self.__d.callAgent('disable')

    #def detachAgent(self): self.__d.callAgent('detach')

    def agentProcessId(self):
        return self.__d.agentPid

    def setAgentSettings(self, data):
        """
    @param  data  {k:v}
    """
        try:
            data = json.dumps(
                data
            )  #, ensure_ascii=False) # the json parser in vnragent don't enforce ascii
            self.__d.callAgent('settings', data)
        except TypeError, e:
            dwarn("failed to encode json: %s" % e)
Beispiel #16
0
class EthClient(QObject):
    def __init__(self, privkey):
        super(EthClient, self).__init__()
        self.privkey = privkey
        self.api = APIClient(DEFAULT_HOST, DEFAULT_PORT)

    @Slot(str)
    def getbalance(self, data):
        print "balance", data
        address = privtoaddr(self.privkey)
        balance = self.api.getbalance(address)
        res = dict(address=address, balance=str(balance))
        print 'response:', res
        self.on_getbalance_cb.emit(json.dumps(res))

    @Slot(str)
    def transact(self, data):
        data = json.loads(data)
        print "transact", data
        res = self.api.quicktx(DEFAULT_GASPRICE,
                               DEFAULT_STARTGAS, data['txto'],
                               int(data['txvalue']), '', self.privkey)
        print 'response:', res
        self.on_transact_cb.emit(json.dumps(res))

    on_getbalance = Signal(str)
    on_getbalance_cb = Signal(str)
    on_transact = Signal(str)
    on_transact_cb = Signal(str)

    on_client_event = Signal(str)
    on_actor_event = Signal(str)
Beispiel #17
0
class ToggleObject(QObject):

    toggled = Signal()
    activated = Signal()
    deactivated = Signal()

    toggleRequested = Signal()
    activationRequested = Signal()
    deactivationRequested = Signal()

    def __init__(self, initialState=False):
        QObject.__init__(self)
        self._toggled = initialState
        self.isToggled = partial(getattr, self, '_toggled')

    def toggle(self):
        state = not self._toggled
        self._toggled = state
        self.toggled.emit()
        getattr(self, 'activated' if state else 'deactivated').emit()

    def requestToggle(self):
        self.toggleRequested.emit()
        getattr(
            self, 'deactivationRequested'
            if self.isToggled() else 'activationRequested').emit()
Beispiel #18
0
class AddEffectMenuView(QMenu):
	Initialize = Signal(object, object)

	def __init__(self, presenter, parent=None, item_color="rgb(51, 51, 51)", background_color="rgb(245, 245, 245)"):
		super(AddEffectMenuView, self).__init__(parent)

		self.item_color = item_color
		self.background_color = background_color

		style_string = "QMenu {{ \
							font: 'Roboto Light'; \
							font-size: 14px; \
							padding: 0px, 0px, 0px, 0px; \
							background-color: {}; \
						}} \
						 \
						QMenu::icon {{ \
							position: absolute; \
							right: 1px; \
							left: 9px; \
						}} \
						QMenu::item {{ \
							color: {}; \
							padding-top: 3px; \
							padding-bottom: 3px; \
							padding-right: 27px; \
							padding-left: 27px; \
						}} \
						 \
						QMenu::separator {{ \
							height: 1px; \
							background: rgb(230, 230, 230); \
							margin-left: 2px; \
							margin-right: 2px; \
						}} \
						QMenu::item:selected {{ \
							background-color: rgb(37, 191, 161); \
							color: rgb(246, 246, 246); \
						}}".format(self.background_color, self.item_color)

		self.setAttribute(Qt.WA_StyledBackground)
		self.setStyleSheet(style_string)
		self.presenter = presenter
		self.setAttribute(Qt.WA_StyledBackground)

		self.Initialize.connect(self._initialize)

	def _initialize(self, effects_names_and_callback, pos):
		for effect_name_and_callback in effects_names_and_callback:
			self.addAction(*effect_name_and_callback)
		self.move(pos)
		self.show()
Beispiel #19
0
class ScriptDummyWithQtSignal(Script, QThread):
    # NOTE THAT THE ORDER OF Script and QThread IS IMPORTANT!!
    _DEFAULT_SETTINGS = Parameter([
        Parameter('count', 10, int),
        Parameter('name', 'this is a counter'),
        Parameter('wait_time', 0.1, float)
    ])

    _INSTRUMENTS = {}
    _SCRIPTS = {}

    #This is the signal that will be emitted during the processing.
    #By including int as an argument, it lets the signal know to expect
    #an integer argument when emitting.
    updateProgress = Signal(int)

    def __init__(self, name=None, settings=None, log_output=None):
        """
        Example of a script that emits a QT signal for the gui
        Args:
            name (optional): name of script, if empty same as class name
            settings (optional): settings for this script, if empty same as default settings
        """
        Script.__init__(self, name, settings, log_output=log_output)
        # QtCore.QThread.__init__(self)
        QThread.__init__(self)

    def _function(self):
        """
        This is the actual function that will be executed. It uses only information that is provided in the settings property
        will be overwritten in the __init__
        """

        # some generic function
        import time
        import random

        count = self.settings['count']
        name = self.settings['name']
        wait_time = self.settings['wait_time']

        self.log('I am a test function counting to {:d}...'.format(count))

        data = []
        for i in range(count):
            time.sleep(wait_time)
            progress = int(100 * (i + 1) / count)
            self.updateProgress.emit(progress)

            data.append(random.random())

        self.data = {'random data': data}
Beispiel #20
0
class TopicInputManager(QObject):
    def __init__(self, parent=None):
        super(TopicInputManager, self).__init__(parent)
        self.__d = _TopicInputManager()

        from PySide.QtCore import QCoreApplication
        qApp = QCoreApplication.instance()
        qApp.aboutToQuit.connect(self.hide)

        import dataman
        dataman.manager().loginChanged.connect(
            lambda name: name or name == 'guest' or self.hide())

        #import netman
        #netman.manager().onlineChanged.connect(lambda t: t or self.hide())

    topicReceived = Signal(unicode, unicode,
                           unicode)  # json topic, json image, json tickets

    #def clear(self): self.hide()

    def isVisible(self):
        if self.__d.dialogs:
            for w in self.__d.dialogs:
                if w.isVisible():
                    return True
        return False

    def hide(self):
        if self.__d.dialogs:
            for w in self.__d.dialogs:
                if w.isVisible():
                    w.hide()

    def newTopic(self, type='chat', subjectId=0, subjectType='', imagePath=''):
        """
    @param* type  str  topic type
    @param* subjectId  long
    @param* subjectType  str
    @param* imagePath  unicode
    """
        w = self.__d.getDialog(self)
        w.setSubject(subjectId, subjectType)
        w.setType(type)
        w.setImagePath(imagePath)
        w.show()

    def isImageEnabled(self):
        return self.__d.imageEnabled

    def setImageEnabled(self, t):
        self.__d.imageEnabled = t
Beispiel #21
0
class QmlReferenceInput(QObject):
    def __init__(self, parent=None):
        super(QmlReferenceInput, self).__init__(parent)
        self.__d = _QmlRefrenceInput(self)

    referenceSelected = Signal(QObject)

    #@Slot()
    #def show(self):
    #  d = self.__d
    #  d.showWindow(d.dialog)

    @staticmethod
    def _getGameIcon(gameId):
        import dataman
        return dataman.manager().queryGameIcon(id=gameId)

    @staticmethod
    def _getGameName(gameId):
        import dataman
        dm = dataman.manager()
        for it in dm.queryReferenceData(gameId=gameId, online=False):
            if it.title:
                return it.title
        return dm.queryGameName(id=gameId)

    @Slot(int)
    def showGame(self, gameId):
        if not gameId:
            growl.notify(
                my.tr("Unknown game. Please try updating the database."))
            return
        d = self.__d
        d.gameId = gameId

        import dataman
        dm = dataman.manager()

        name = self._getGameName(gameId)

        title = my.tr("Please select the game title")
        if name:
            title += " - " + name

        w = d.dialog
        w.setWindowTitle(title)

        icon = self._getGameIcon(gameId)
        w.setWindowIcon(icon or rc.icon('window-refinput'))
        if name:
            w.setDefaultText(name)
        d.showWindow(w)
class HyperdeckState(QObject):

    transportChange = Signal(dict)
    clipsListChange = Signal(dict)

    def __init__(self, hyperdeck):
        super(HyperdeckState, self).__init__()
        self.deck = hyperdeck
        self.clip_listing = {}

        self.transport = {"status": TransportState.STOPPED}

        if self.deck:
            self.transport = self.deck.getTransportState()

    def handleMessage(self, msgType, data):
        if msgType == HyperDeckMessageTypes.TRANSPORT_STATE_CHANGED:
            self.transport = data
            self.transportChange.emit(data)
        if msgType == HyperDeckMessageTypes.CLIP_LISTING:
            self.clip_listing = data
            self.clipsListChange.emit(data)
Beispiel #23
0
class DeclarativeView(QDeclarativeView):
    def __init__(self):
        QDeclarativeView.__init__(self)
        self.setAttribute(Qt.WA_OpaquePaintEvent)
        self.setAttribute(Qt.WA_NoSystemBackground)
        self.viewport().setAttribute(Qt.WA_OpaquePaintEvent)
        self.viewport().setAttribute(Qt.WA_NoSystemBackground)

    closing = Signal()

    def closeEvent(self, event):
        self.closing.emit()
        event.ignore()
Beispiel #24
0
class SkClipboardProxy(QObject):
  def __init__(self, parent=None):
    super(SkClipboardProxy, self).__init__(parent)
    self.__d = _SkClipboardProxy(self)

    QApplication.clipboard().dataChanged.connect(lambda:
        self.textChanged.emit(self.text))

  textChanged = Signal(unicode)
  text = Property(unicode,
      lambda _: QApplication.clipboard().text(),
      lambda _, v: QApplication.clipboard().setText(v),
      notify=textChanged)
Beispiel #25
0
class ResizeDialog(QDialog, fr.Ui_Dialog):
    resized = Signal(float)

    def __init__(self, accept=None, reject=None, low=True, parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        self.buttonBox.rejected.connect(self.close)
        self.buttonBox.accepted.connect(self._resize)

    def _resize(self):
        self.resized.emit(self.doubleSpinBox.value())
        self.close()
Beispiel #26
0
class PerFrameSeekerFilter(QObject):
    """
    Event filter for filtering mouse btn release events
    """

    LMouseRelease = Signal()
    LMousePress = Signal()

    def eventFilter(self, obj, event):
        """
        :type obj: PySide.QtGui.QSlider
        :type event: PySide.QtCore.QEvent
        """
        if event.type() is QEvent.MouseButtonPress and event.button(
        ) is Qt.LeftButton:
            self.LMousePress.emit()

        if event.type() is QEvent.MouseButtonRelease and event.button(
        ) is Qt.LeftButton:
            self.LMouseRelease.emit()

        return super(PerFrameSeekerFilter, self).eventFilter(obj, event)
Beispiel #27
0
class PostEditorManagerBean(QObject):
    def __init__(self, parent=None, manager=None):
        super(PostEditorManagerBean, self).__init__(parent)
        self.manager = manager or PostEditorManager(self)
        self.manager.postChanged.connect(self.postChanged)

    postChanged = Signal(unicode, unicode)  # json post, json image

    imageEnabledChanged = Signal(bool)
    imageEnabled = Property(bool,
                            lambda self: self.manager.isImageEnabled(),
                            lambda self, t: self.manager.setImageEnabled(t),
                            notify=imageEnabledChanged)

    @Slot(unicode)
    def editPost(self, data):  # json ->
        try:
            post = json.loads(data)
            post['id'] = long(post['id'])
            self.manager.editPost(**post)
        except Exception, e:
            dwarn(e)
Beispiel #28
0
class DataSource(QObject):
    def __init__(self, parent=None):
        super(DataSource, self).__init__(parent)
        self.spectrum = Spectrum([])

    updated = Signal(object)

    def getSpectrum(self):
        return self.spectrum

    @Slot()
    def refresh(self):
        self.updated.emit(self.getSpectrum())
Beispiel #29
0
class FilterLineEdit(QLineEdit):

    key_down = Signal()

    def __init__(self):
        super(FilterLineEdit,self).__init__()

    def keyPressEvent(self,event):
        if event.key() == Qt.Key_Down:
            event.ignore()
            self.key_down.emit()

        return super(FilterLineEdit,self).keyPressEvent(event)
Beispiel #30
0
class Handbrake(QObject):
    return_signal = Signal(str)

    def __init__(self, emoji=None):
        """
        This class allows you to add() video files and convert them to gifs.
        Output files are going to be in the same folder as the input files.
        """
        super(Handbrake, self).__init__()
        self.tp = TasksPool()
        self.tp.return_signal.connect(lambda x: self.return_signal.emit(x))

        # If we supply Emoji object, then
        if isinstance(emoji, Emoji):
            video_file = abspath(join(emoji.folder, emoji.name + Config()()['name_delimiter'] + emoji.version + '.mov'))
            if not exists(video_file):
                video_file = abspath(join(emoji.folder, emoji.name + '-' + emoji.version + '.mov'))
            if exists(video_file):
                self.add(video_file)
                self.run()
            else:
                error_msg = 'Failed to locate {}, based on {}.'.format(video_file, emoji.name_no_ext)
                self.return_signal.emit(__name__ + error_msg)
                logger.warning(error_msg)
                error_box = QMessageBox()
                error_box.setStyleSheet(stylesheet.houdini)
                error_box.setWindowTitle('Handbrake mov to mp4 conversion: File error')
                error_box.setText(error_msg)
                error_box.exec_()
        elif isinstance(emoji, str):
            video_file = emoji
            if exists(video_file):
                self.add(video_file)
                self.run()

    def add(self, input_file):
        """
        :param input_file: Source video file
        :return: String with resulting gif's path
        """
        output_file = splitext(input_file)[0]+'.mp4'
        cmd = 'bin\\HandBrakeCLI.exe -i "{}" -o "{}"'.format(input_file, output_file)
        self.tp.add_task(cmd)
        logger.debug(cmd + ' added')

    def run(self):
        """
        Launches FFmpeg conversion process queue filled with add() method
        """
        self.tp.launch_list()
        self.tp = None