Ejemplo n.º 1
0
Archivo: utils.py Proyecto: dVoCex/ts2
    def yieldValue(self):
        """Returns a random value in the bounds and probabilities given by
        this DurationProba instance.

        This is done in two steps:
        - First we take a random number to determine the segment (tuple) in
          which we should be according to our _probaList.
        - Then we take a second random number to get our value inside the
          selected segment (with even probability).
        """
        try:
            probas = list(cumsum([t[2] for t in self._probaList]))
            probas.insert(0, 0)
        except TypeError:
            # We have a value instead of a list
            return self._probaList
        except Exception as err:
            QtCore.qDebug(str(err))
            return None

        # First determine our segment
        r0 = 100 * random.random()
        seg = 0
        for i in range(len(probas) - 1):
            if probas[i] < r0 < probas[i+1]:
                break
            seg += 1
        else:
            # Out of range: returns max value
            return self._probaList[-1][1]

        # Then pick up a number inside our segment
        r1 = random.random()
        low, high, prob = self._probaList[seg]
        return r1 * (high - low) + low
Ejemplo n.º 2
0
Archivo: editor.py Proyecto: dVoCex/ts2
 def setupTrainsFromServices(self):
     """Removes all trains instances and creates a train for each relevant
     service, that is each service which is not following another one (i.e
     a service which is not the nextService of another service)."""
     self._trains = []
     serviceList = list(self.services.keys())
     for s in self.services.values():
         if s.nextServiceCode is not None and \
            s.nextServiceCode != "":
             try:
                 serviceList.remove(s.nextServiceCode)
             except ValueError:
                 QtCore.qDebug("nextServiceCode: %s does not exist" %
                               s.nextServiceCode)
     for sc in serviceList:
         train = self.addNewTrain()
         train.serviceCode = sc
         service = self.service(sc)
         placeCode, trackCode = service.getEntryPlaceData()
         entryLineItem = self.getLineItem(placeCode, trackCode)
         if entryLineItem is not None:
             if isinstance(entryLineItem.nextItem, enditem.EndItem):
                 previousTI = entryLineItem.nextItem
             else:
                 previousTI = entryLineItem.previousItem
             pos = position.Position(entryLineItem, previousTI,
                                     max(0, entryLineItem.realLength - 1))
             initialSpeed = entryLineItem.maxSpeed
         else:
             pos = self.getValidPosition()
             initialSpeed = 0
         train.trainHead = pos
         train.initialSpeed = initialSpeed
         train.trainTypeCode = service.plannedTrainType
         if service.lines[0].scheduledArrivalTimeStr != "":
             train.appearTimeStr = service.lines[0].scheduledArrivalTimeStr
         else:
             train.appearTimeStr = "00:00:00"
Ejemplo n.º 3
0
Archivo: route.py Proyecto: dVoCex/ts2
 def createPositionsList(self):
     """ Populates the _positions list.
     If the route is invalid, it leaves the _positions list empty.
     Also completes the _directions map, with obvious directions."""
     cur = self._positions[0].next()
     it = 1
     while not cur.isOut():
         if cur == self._positions[-1]:
             return True
         self._positions.insert(it, cur)
         it += 1
         if isinstance(cur.trackItem, pointsitem.PointsItem):
             if cur.previousTI == cur.trackItem.normalItem:
                 self._directions[cur.trackItem.tiId] = 0
             elif cur.previousTI == cur.trackItem.reverseItem:
                 self._directions[cur.trackItem.tiId] = 1
             elif cur.previousTI == cur.trackItem.commonItem \
                     and cur.trackItem.tiId not in self._directions:
                 self._directions[cur.trackItem.tiId] = 0
         cur = cur.next(0, self._directions.get(cur.trackItem.tiId, -1))
     QtCore.qCritical(self.tr("Invalid route %i. Impossible to link "
                              "beginSignal with endSignal" % self.routeNum))
     return False
Ejemplo n.º 4
0
def Main(args=None):
    """Start the ts2 application and present :class:`~ts2.mainwindow.MainWindow`

    :param object args: Command line args from argparse
    """
    app = QtWidgets.QApplication(sys.argv)
    app.setApplicationName(__APP_SHORT__)
    app.setApplicationName(__VERSION__)
    app.setWindowIcon(QtGui.QIcon(QtGui.QPixmap(":/ts2.png")))
    qtTranslator = QtCore.QTranslator()
    qtTranslator.load("qt_" + QtCore.QLocale.system().name(),
                      QtCore.QLibraryInfo.location(
                                      QtCore.QLibraryInfo.TranslationsPath))
    app.installTranslator(qtTranslator)
    ts2Translator = QtCore.QTranslator()
    ts2Translator.load(QtCore.QLocale.system(), "ts2", "_", "i18n", ".qm")
    app.installTranslator(ts2Translator)
    QtCore.qDebug(QtCore.QLocale.system().name())
    # TODO: Uncomment in production
    # try:
    mw = mainwindow.MainWindow(args=args)
    mw.show()
    return app.exec_()
Ejemplo n.º 5
0
    def __init__(self, parent=None):
        """
		Args:
			flow: What part of setup is the user entering into?
		"""
        super(CreateStructureWorkflow, self).__init__(parent)

        self.logger = logging.getLogger('menu.' + self.__class__.__name__)
        self.logger.info('Workplace creation starting...')
        self.setObjectName('launcher_{0}'.format(self.__class__.__name__))

        self.parent = parent
        self.armada_root_path = definitions.ROOT_PATH

        # self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.installEventFilter(self)
        self.setStyleSheet(resource.style_sheet('setup'))
        self.sizeHint()

        # GUI ----------------------------------
        self.btn_back = QtWidgets.QPushButton()
        self.btn_back.setIcon(resource.color_svg('arrow_left', 128, '#9E9E9E'))
        self.btn_back.setIconSize(QtCore.QSize(30, 30))
        self.btn_back.setFixedHeight(30)
        self.btn_back.setStyleSheet(resource.style_sheet('push_button_w_icon'))

        self.tb_welcome = QtWidgets.QLabel()
        self.tb_welcome.setText("""
			<p style="font-size:30px;font-weight: normal;">How should we organize this project?</p>"""
                                )
        self.tb_welcome.setWordWrap(True)

        self.tb_description = QtWidgets.QLabel()
        self.tb_description.setStyleSheet("""
			background-color: transparent;
			font: 12px;
			font-weight: normal""")
        self.tb_description.setText("""
			<p>Each project utilizes a set of rules called a <b>structure</b> to enforce folder/file locations and naming conventions.
			<p>Once configured a structure automatically makes sure everyone adheres to the ruleset so you can focus on what you do best: Makin art!</p>"""
                                    )
        self.tb_description.setWordWrap(True)

        # Input
        self.lbl_structure_workflow = QtWidgets.QLabel(
            "Choose a structure workflow")

        self.lw_items = QtWidgets.QListWidget()
        self.lw_items.setViewMode(QtWidgets.QListView.IconMode)
        # self.lw_items.setMaximumHeight(50)
        # self.lw_items.setResizeMode(QtWidgets.QListView.Fixed)
        self.lw_items.setUniformItemSizes(True)
        self.lw_items.setSizeAdjustPolicy(QtWidgets.QListWidget.AdjustIgnored)
        self.lw_items.setMovement(self.lw_items.Static)
        self.lw_items.setSizeAdjustPolicy(
            QtWidgets.QAbstractScrollArea.AdjustToContents)
        self.lw_items.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                    QtWidgets.QSizePolicy.Expanding)
        self.lw_items.setFlow(QtWidgets.QListView.LeftToRight)
        # self.lw_items.setSpacing(5)
        self.lw_items.setMinimumHeight(100)
        self.lw_items.setStyleSheet("""
				QListView{
					show-decoration-selected: 0;
					background: #262626;
					color:rgb(218,218,218) ;
					font:12px "Roboto-Thin";
					border: none;
					height: 200px;
					outline: 0;
					padding-left: 10;
					padding-right: 10;
				}
				""")

        # Structure workflow options
        builtin_icon = resource.color_svg('folder_folder', 1024, '#F9D085')
        lw_item = QtWidgets.QListWidgetItem(builtin_icon, 'Built In Structure')
        lw_item.setSizeHint(self.lw_items.sizeHint())
        self.lw_items.addItem(lw_item)

        custom_icon = resource.color_svg('structure_create', 1024, '#7D7D7D')
        lw_item = QtWidgets.QListWidgetItem(custom_icon, 'Custom Structure')
        lw_item.setSizeHint(self.lw_items.sizeHint())
        # lw_item.setFlags(QtCore.Qt.ItemIsSelectable)  # TODO: enable when custom structures workflow is figured out
        self.lw_items.addItem(lw_item)

        self.lbl_structure_description = QtWidgets.QLabel()
        self.lbl_structure_description.setWordWrap(True)
        self.lbl_structure_description.setStyleSheet("""
			background-color: transparent;
			font: 12px;
			font-weight: normal""")

        self.hline_username = QtWidgets.QFrame()
        self.hline_username.setFixedHeight(1)
        self.hline_username.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                          QtWidgets.QSizePolicy.Fixed)
        self.hline_username.setStyleSheet("background-color: #636363;")

        self.btn_next = QtWidgets.QPushButton('Next')
        self.btn_next.setFixedWidth(100)
        self.btn_next.setStyleSheet('''
			QPushButton{
				Background:#2e7a78;
				height: 30px;
				font: 12px "Roboto-Thin"
			}
			QPushButton:hover{
				Background: #369593;
			}
			QPushButton:hover:pressed{
				Background: #2e7a78;
			}
			QPushButton:pressed{
				Background:  #2a615f;
			}
			QPushButton:disabled{
				Background: #3b3b3b;
			}''')
        self.btn_next.setFixedSize(100, 40)
        self.btn_next.setEnabled(False)

        # self.lbl_disclaimer = QtWidgets.QTextBrowser()
        # self.lbl_disclaimer.setReadOnly(True)
        # self.lbl_disclaimer.setText('Armada Pipeline does not store passwords or account data at this time. Your acocunt is stored locally and only used to add another degree of flexibility project')
        # self.lbl_disclaimer.setMinimumSize(100, 50)

        # Layout --------------------------------------------
        btn_back_layout = QtWidgets.QVBoxLayout()
        btn_back_layout.addWidget(self.btn_back)
        btn_back_layout.setAlignment(QtCore.Qt.AlignTop)
        btn_back_layout.setContentsMargins(0, 0, 0, 0)
        btn_back_layout.setSpacing(0)

        description_layout = QtWidgets.QVBoxLayout()
        description_layout.addWidget(self.tb_welcome)
        description_layout.addWidget(self.tb_description)
        description_layout.setAlignment(QtCore.Qt.AlignTop)
        description_layout.setContentsMargins(0, 0, 0, 0)
        description_layout.setSpacing(30)

        input_layout = QtWidgets.QVBoxLayout()
        input_layout.addWidget(self.lbl_structure_workflow)
        input_layout.addWidget(self.lw_items)
        input_layout.addWidget(self.lbl_structure_description)
        input_layout.setAlignment(QtCore.Qt.AlignTop)
        input_layout.setContentsMargins(0, 0, 0, 0)
        input_layout.setSpacing(10)

        btn_layout = QtWidgets.QVBoxLayout()
        btn_layout.addWidget(self.btn_next)
        btn_layout.setAlignment(QtCore.Qt.AlignTop)
        btn_layout.setContentsMargins(0, 0, 0, 0)
        btn_layout.setSpacing(0)

        contents_layout = QtWidgets.QVBoxLayout()
        contents_layout.addLayout(description_layout)
        contents_layout.addLayout(input_layout)
        contents_layout.addLayout(btn_layout)
        contents_layout.addStretch()
        contents_layout.setAlignment(QtCore.Qt.AlignTop)
        contents_layout.setContentsMargins(0, 0, 0, 0)
        contents_layout.setSpacing(50)

        self.main_layout = QtWidgets.QHBoxLayout()
        self.main_layout.addLayout(btn_back_layout)
        self.main_layout.addLayout(contents_layout)
        self.main_layout.setContentsMargins(20, 20, 60, 20)
        self.main_layout.setSpacing(10)

        self.setLayout(self.main_layout)

        # Connections -----------------------------------
        # self.btn_next.clicked.connect(self._on_next)
        self.lw_items.itemClicked.connect(self._lw_sel_changed)
Ejemplo n.º 6
0
class FtrackEventsThread(QtCore.QThread):
    # Senders
    signal_timer_started = QtCore.Signal(object)
    signal_timer_stopped = QtCore.Signal()

    def __init__(self, parent):
        super(FtrackEventsThread, self).__init__()
        cred = credentials._get_credentials()
        self.username = cred['username']
        self.user = None
        self.last_task = None

    def run(self):
        self.timer_session = ftrack_api.Session(auto_connect_event_hub=True)
        self.timer_session.event_hub.subscribe(
            'topic=ftrack.update and source.user.username={}'.format(
                self.username), self.event_handler)

        user_query = 'User where username is "{}"'.format(self.username)
        self.user = self.timer_session.query(user_query).one()

        timer_query = 'Timer where user.username is "{}"'.format(self.username)
        timer = self.timer_session.query(timer_query).first()
        if timer is not None:
            self.last_task = timer['context']
            self.signal_timer_started.emit(
                self.get_data_from_task(self.last_task))

        self.timer_session.event_hub.wait()

    def get_data_from_task(self, task_entity):
        data = {}
        data['task_name'] = task_entity['name']
        data['task_type'] = task_entity['type']['name']
        data['project_name'] = task_entity['project']['full_name']
        data['hierarchy'] = self.get_parents(task_entity['parent'])

        return data

    def get_parents(self, entity):
        output = []
        if entity.entity_type.lower() == 'project':
            return output
        output.extend(self.get_parents(entity['parent']))
        output.append(entity['name'])

        return output

    def event_handler(self, event):
        try:
            if event['data']['entities'][0]['objectTypeId'] != 'timer':
                return
        except Exception:
            return

        new = event['data']['entities'][0]['changes']['start']['new']
        old = event['data']['entities'][0]['changes']['start']['old']

        if old is None and new is None:
            return

        timer_query = 'Timer where user.username is "{}"'.format(self.username)
        timer = self.timer_session.query(timer_query).first()
        if timer is not None:
            self.last_task = timer['context']

        if old is None:
            self.signal_timer_started.emit(
                self.get_data_from_task(self.last_task))
        elif new is None:
            self.signal_timer_stopped.emit()

    def ftrack_stop_timer(self):
        actual_timer = self.timer_session.query(
            'Timer where user_id = "{0}"'.format(self.user['id'])).first()

        if actual_timer is not None:
            self.user.stop_timer()
            self.timer_session.commit()
            self.signal_timer_stopped.emit()

    def ftrack_start_timer(self, input_data):
        if self.user is None:
            return

        actual_timer = self.timer_session.query(
            'Timer where user_id = "{0}"'.format(self.user['id'])).first()
        if (actual_timer is not None
                and input_data['task_name'] == self.last_task['name']
                and input_data['hierarchy'][-1]
                == self.last_task['parent']['name']):
            return

        input_data['entity_name'] = input_data['hierarchy'][-1]

        task_query = ('Task where name is "{task_name}"'
                      ' and parent.name is "{entity_name}"'
                      ' and project.full_name is "{project_name}"').format(
                          **input_data)

        task = self.timer_session.query(task_query).one()
        self.last_task = task
        self.user.start_timer(task)
        self.timer_session.commit()
        self.signal_timer_started.emit(self.get_data_from_task(self.last_task))
Ejemplo n.º 7
0
class VersionSelector(QtWidgets.QWidget, ui_versionSelector.Ui_Form):
    signalSetTagStart = QtCore.Signal()
    signalSetTag = QtCore.Signal(str, str)
    signalSetTagEnd = QtCore.Signal()

    def __init__(self,
                 parent,
                 withFileFormatFilter=True,
                 fileFormatFilterTagName=None,
                 fileFormatFilterNodeType=None,
                 pathFormat=None):
        super(VersionSelector, self).__init__()
        self.setupUi(self)
        self.parent = parent
        self.font = uiUtils.getFont('monospace')
        self._data = {}
        self._path = ''
        self.__internalRemap = {}

        self._pathFormat = pathFormat
        if pathFormat is None:
            self._pathFormat = '/projects/{project}/{sequence}/{shot}/{department}/{task}/{name}_{major}.{minor}.{ext}'

        # File Format Filter
        self.fileFormatModel = None
        self._fileFormatFilterTagName = None
        self._fileFormatFilterNodeType = None
        if withFileFormatFilter is True:
            filterData = self.__getFileFormatNames()
            self.fileFormatModel = QtCore.QStringListModel(filterData)
            self.fileFormatComboBox.setModel(self.fileFormatModel)
            if fileFormatFilterTagName is not None:
                if isinstance(fileFormatFilterTagName, str):
                    self._fileFormatFilterTagName = fileFormatFilterTagName
                else:
                    raise ValueError
            if fileFormatFilterNodeType is not None:
                if isinstance(fileFormatFilterNodeType, str):
                    self._fileFormatFilterNodeType = fileFormatFilterNodeType
                else:
                    raise ValueError
        else:
            self.fileFormatLabel.hide()
            self.fileFormatComboBox.hide()

        rootNode = nodes.Node('root', data=self._path)
        self.versionModel = VersionModel(rootNode, font=self.font)

        self.versionFilterModel = qtLearn.uiModels.SortFilterProxyModel()
        self.versionFilterModel.setSourceModel(self.versionModel)
        self.versionFilterModel.setDynamicSortFilter(True)
        self.versionFilterModel.setFilterCaseSensitivity(
            QtCore.Qt.CaseInsensitive)
        self.versionFilterModel.setFilterTagName(self._fileFormatFilterTagName)
        self.versionFilterModel.setFilterTagNodeType(
            self._fileFormatFilterNodeType)

        self.treeView.setModel(self.versionFilterModel)
        self.treeView.setSortingEnabled(True)
        self.treeView.sortByColumn(0, QtCore.Qt.DescendingOrder)
        self.treeView.expandAll()

        self.selectionModel = self.treeView.selectionModel()
        self.selectionModel.currentChanged.connect(self.slotCurrentChanged)

        self.fileFormatComboBox.currentIndexChanged.connect(
            self.slotFileFormatFilterChanged)
        # self.fileFormatComboBox.currentIndexChanged.connect(self.slotSetFilterTagValue)

    ############################################################################

    def __getFileFormatNames(self):
        data = self.getFileFormatsData()
        names = map(lambda x: x[1], data)
        # names = list(names)
        # print('getFileFormatNames:', names)
        return names

    def __getFileFormatExtensions(self):
        data = self.getFileFormatsData()
        exts = map(lambda x: x[0], data)
        # exts = list(exts)
        # print('getFileFormatExtensions:', exts)
        return exts

    def data(self):
        if self._data is None:
            return {}
        return self._data.copy()

    def setData(self, value):
        self._data = value

    def getDataValue(self, key, default=None):
        return self._data.get(key, default)

    def setDataValue(self, key, value):
        self._data[key] = value

    def getFileFormatFilterTagName(self):
        return self._fileFormatFilterTagName

    def getFileFormatFilterTagNodeType(self):
        return self._fileFormatFilterNodeType

    ############################################################################

    def getFileFormatsData(self):
        return [
            # (None, '<all file formats>'),
            # ('.ma', 'Maya ASCII (*.ma)'),
            # ('.mb', 'Maya Binary (*.mb)')
            (None, '<all file formats>'),
            ('.ma', 'ma'),
            ('.mb', 'mb')
        ]

    def getVersionNodes(self):
        # TODO: Use 'path' to look up versions rather than hard-coding test data.
        tags = self.data()
        pth = paths.Path(tags, format=self._pathFormat)
        path = pth.getPath()
        # print('VersionSelector getVersionNodes path:', path)
        rootNode = self.__internalRemap.get(path)
        if rootNode is not None:
            return rootNode

        exts = ['mb', 'ma']

        versions_1 = [
            ('v001.001', 'john', 'description', random.choice(exts)),
            ('v002.001', 'davidc', 'description', random.choice(exts)),
            ('v002.002', 'davidc', 'description', random.choice(exts)),
            ('v002.003', 'davidc', 'description', random.choice(exts)),
            ('v002.004', 'john', 'description', random.choice(exts)),
            ('v003.001', 'bob', 'description', random.choice(exts)),
        ]
        versions_2 = [
            ('v001.001', 'davidc', 'description', random.choice(exts)),
        ]
        versions_3 = [
            ('v001.001', 'davidc', 'description', random.choice(exts)),
            ('v002.001', 'davidc', 'description', random.choice(exts)),
            ('v003.001', 'davidc', 'description', random.choice(exts)),
            ('v004.001', 'davidc', 'description', random.choice(exts)),
            ('v005.001', 'davidc', 'description', random.choice(exts)),
            ('v006.001', 'davidc', 'description', random.choice(exts)),
            ('v007.001', 'davidc', 'description', random.choice(exts)),
            ('v008.001', 'davidc', 'description', random.choice(exts)),
            ('v009.001', 'davidc', 'description', random.choice(exts)),
            ('v010.001', 'davidc', 'description', random.choice(exts)),
            ('v011.001', 'davidc', 'description', random.choice(exts)),
            ('v012.001', 'john', 'description', random.choice(exts)),
        ]
        versions_4 = [
            ('v001.001', 'bob', 'description', random.choice(exts)),
            ('v001.002', 'bob', 'description', random.choice(exts)),
            ('v001.003', 'bob', 'description', random.choice(exts)),
            ('v001.004', 'bob', 'description', random.choice(exts)),
            ('v001.005', 'bob', 'description', random.choice(exts)),
            ('v001.006', 'bob', 'description', random.choice(exts)),
            ('v001.007', 'bob', 'description', random.choice(exts)),
            ('v001.008', 'bob', 'description', random.choice(exts)),
            ('v001.009', 'bob', 'description', random.choice(exts)),
            ('v001.010', 'bob', 'description', random.choice(exts)),
            ('v002.001', 'davidc', 'description', random.choice(exts)),
            ('v002.002', 'davidc', 'description', random.choice(exts)),
            ('v002.003', 'davidc', 'description', random.choice(exts)),
            ('v002.004', 'davidc', 'description', random.choice(exts)),
            ('v002.005', 'davidc', 'description', random.choice(exts)),
            ('v002.006', 'davidc', 'description', random.choice(exts)),
            ('v002.007', 'davidc', 'description', random.choice(exts)),
            ('v002.008', 'davidc', 'description', random.choice(exts)),
            ('v002.009', 'davidc', 'description', random.choice(exts)),
            ('v002.010', 'davidc', 'description', random.choice(exts)),
            ('v002.011', 'davidc', 'description', random.choice(exts)),
            ('v002.012', 'davidc', 'description', random.choice(exts)),
        ]
        versions = [versions_1, versions_2, versions_3, versions_4]
        versions = random.choice(versions)

        major_versions = {}
        minor_versions = {}
        rootNode = nodes.Node('ROOT')
        for version in versions:
            ver = version[0]
            split = str(ver).split('.')
            major_ver = split[0]
            minor_ver = split[1]
            user = version[1]
            desc = version[2]
            file_ext = version[3]
            data = {
                'major': major_ver,
                'minor': minor_ver,
                'version': ver,
                'user': user,
                'description': desc,
                'ext': file_ext,
            }

            # Create Major Version
            if major_ver in major_versions:
                majorNode = major_versions[major_ver]
            else:
                majorNode = MajorVersionNode(major_ver,
                                             parent=rootNode,
                                             data=data)

            # Create Minor Version
            if ver in minor_versions:
                minorNode = minor_versions[major_ver]
            else:
                minorNode = MinorVersionNode(minor_ver,
                                             user,
                                             desc,
                                             parent=majorNode,
                                             data=data)

            major_versions[major_ver] = majorNode
            minor_versions[ver] = minorNode

        self.__internalRemap[path] = rootNode
        return rootNode

    ############################################################################

    @QtCore.Slot(int)
    def slotFileFormatFilterChanged(self, index):
        text = self.fileFormatComboBox.currentText()
        text = text.lower()
        if not text.isalpha():
            text = None
        # print('VersionSelector slotFileFormatFilterChanged', text)
        self.versionFilterModel.setFilterTagValue(text)
        self.treeView.expandAll()

    @QtCore.Slot(str)
    def slotSetUserFilterValue(self, value):
        # print('VersionSelector slotSetFilterTagValue', value)
        self.versionFilterModel.setFilterTagValue(value)
        self.treeView.expandAll()

    @QtCore.Slot(dict)
    def slotSetPathData(self, tags):
        # print('VersionSelector slotSetPathData tags:', tags)
        if not isinstance(tags, dict):
            return
        allowedTagKeys = [
            'project', 'sequence', 'shot', 'name', 'task', 'department'
        ]
        for key in tags.keys():
            if key in allowedTagKeys:
                self._data[key] = tags.get(key)
            else:
                if key in self._data:
                    self._data.pop(key)
        # print('VersionSelector slotSetPathData changed:', self._data)
        rootNode = self.getVersionNodes()
        self.versionModel.setRootNode(rootNode)
        self.treeView.expandAll()
        return

    @QtCore.Slot(QtCore.QModelIndex, QtCore.QModelIndex)
    def slotCurrentChanged(self, index, prevIndex):
        # print('VersionSelector currentChanged START')

        if not index.isValid():
            return
        index_map = self.versionFilterModel.mapToSource(index)
        node = index_map.internalPointer()
        if node is None:
            return
        nodeData = node.data()
        if nodeData is None:
            return

        # Emit tag signals
        self.signalSetTagStart.emit()
        # print('VersionSelector currentChanged keys', nodeData.keys())
        for key in nodeData.keys():
            value = nodeData.get(key)
            # print('VersionSelector currentChanged value', key, newValue)
            self.setDataValue(key, nodeData[key])
            self.signalSetTag.emit(key, value)
        self.signalSetTagEnd.emit()

        # print('VersionSelector currentChanged END', repr(nodeData))
        return
Ejemplo n.º 8
0
Archivo: model.py Proyecto: 3dzayn/pype
class InstanceModel(QtGui.QStandardItemModel):

    group_created = QtCore.Signal(QtCore.QModelIndex)

    def __init__(self, controller, *args, **kwargs):
        super(InstanceModel, self).__init__(*args, **kwargs)

        self.controller = controller
        self.checkstates = {}
        self.group_items = {}
        self.instance_items = {}

    def reset(self):
        self.group_items = {}
        self.instance_items = {}
        self.clear()

    def append(self, instance):
        new_item = InstanceItem(instance)
        if new_item.is_context:
            self.appendRow(new_item)
        else:
            families = new_item.data(Roles.FamiliesRole)
            group_item = self.group_items.get(families[0])
            if not group_item:
                group_item = GroupItem(families[0])
                self.appendRow(group_item)
                self.group_items[families[0]] = group_item
                self.group_created.emit(group_item.index())

            group_item.appendRow(new_item)
        instance_id = instance.id
        self.instance_items[instance_id] = new_item

    def remove(self, instance_id):
        instance_item = self.instance_items.pop(instance_id)
        parent_item = instance_item.parent()
        parent_item.removeRow(instance_item.row())
        if parent_item.rowCount():
            return

        self.group_items.pop(parent_item.data(QtCore.Qt.DisplayRole))
        self.removeRow(parent_item.row())

    def store_checkstates(self):
        self.checkstates.clear()

        for instance_item in self.instance_items.values():
            if not instance_item.instance.optional:
                continue

            uid = instance_item.data(Roles.ObjectUIdRole)
            self.checkstates[uid] = instance_item.data(
                QtCore.Qt.CheckStateRole)

    def restore_checkstates(self):
        for instance_item in self.instance_items.values():
            if not instance_item.instance.optional:
                continue

            uid = instance_item.data(Roles.ObjectUIdRole)
            state = self.checkstates.get(uid)
            if state is not None:
                instance_item.setData(state, QtCore.Qt.CheckStateRole)

    def update_with_result(self, result):
        instance = result["instance"]
        if instance is None:
            instance_id = self.controller.context.id
        else:
            instance_id = instance.id

        item = self.instance_items.get(instance_id)
        if not item:
            return

        new_flag_states = {InstanceStates.InProgress: False}

        publish_states = item.data(Roles.PublishFlagsRole)
        has_warning = publish_states & InstanceStates.HasWarning
        new_records = result.get("records") or []
        if not has_warning:
            for record in new_records:
                level_no = record.get("levelno")
                if level_no and level_no >= 30:
                    new_flag_states[InstanceStates.HasWarning] = True
                    break

        if (not publish_states & InstanceStates.HasError
                and not result["success"]):
            new_flag_states[InstanceStates.HasError] = True

        item.setData(new_flag_states, Roles.PublishFlagsRole)

        records = item.data(Roles.LogRecordsRole) or []
        records.extend(new_records)

        item.setData(records, Roles.LogRecordsRole)

        return item

    def update_compatibility(self, context, instances):
        families = util.collect_families_from_instances(context, True)
        for plugin_item in self.plugin_items.values():
            publish_states = plugin_item.data(Roles.PublishFlagsRole)
            if (publish_states & PluginStates.WasProcessed
                    or publish_states & PluginStates.WasSkipped):
                continue

            is_compatible = False
            # A plugin should always show if it has processed.
            if plugin_item.plugin.__instanceEnabled__:
                compatibleInstances = pyblish.logic.instances_by_plugin(
                    context, plugin_item.plugin)
                for instance in instances:
                    if not instance.data.get("publish"):
                        continue

                    if instance in compatibleInstances:
                        is_compatible = True
                        break
            else:
                plugins = pyblish.logic.plugins_by_families(
                    [plugin_item.plugin], families)
                if plugins:
                    is_compatible = True

            current_is_compatible = publish_states & PluginStates.IsCompatible
            if ((is_compatible and not current_is_compatible)
                    or (not is_compatible and current_is_compatible)):
                plugin_item.setData({PluginStates.IsCompatible: is_compatible},
                                    Roles.PublishFlagsRole)
Ejemplo n.º 9
0
 def index(self, row, column, parent=QtCore.QModelIndex()):
     return self.createIndex(row, column, QtCore.QModelIndex())
Ejemplo n.º 10
0
 def columnCount(self, parent=QtCore.QModelIndex()):
     # This is not right for global proxy, but in this case it is enough
     return self.sourceModel().columnCount()
Ejemplo n.º 11
0
 def _set_dayu_size(self):
     self.setFixedSize(QtCore.QSize(self._dayu_size, self._dayu_size))
     self._set_dayu_image()
Ejemplo n.º 12
0
 def dataChangedEmit(self):
     self.dataChanged.emit(QtCore.QModelIndex(), QtCore.QModelIndex())
Ejemplo n.º 13
0
 def mouseMoveEvent(self, event):
     """
     """
     _parent = self.parent()
     _parent_rect = self.parent().rect()
     if self._is_press:
         if event.buttons() == QtCore.Qt.LeftButton:
             _mouse_fix = event.globalPos() - self._drag_position
             _glo_mouse_point = self.parent().mapToParent(event.pos())
             if self._area == "left":
                 _rect = QtCore.QRect(
                     self._glo_parent_point_top_left.x() + _mouse_fix.x(),
                     self._glo_parent_point_top_left.y(),
                     abs(self._glo_parent_point_top_left.x() +
                         _mouse_fix.x() -
                         self._glo_parent_point_bottom_right.x()),
                     _parent_rect.height())
             elif self._area == "top":
                 _rect = QtCore.QRect(
                     self._glo_parent_point_top_left.x(),
                     self._glo_parent_point_top_left.y() + _mouse_fix.y(),
                     _parent_rect.width(),
                     abs(self._glo_parent_point_top_left.y() +
                         _mouse_fix.y() -
                         self._glo_parent_point_bottom_right.y()))
             elif self._area == "right":
                 _rect = QtCore.QRect(self._glo_parent_point_top_left.x(),
                                      self._glo_parent_point_top_left.y(),
                                      _mouse_fix.x() + self.width(),
                                      _parent_rect.height())
             elif self._area == "bottom":
                 _rect = QtCore.QRect(self._glo_parent_point_top_left.x(),
                                      self._glo_parent_point_top_left.y(),
                                      _parent_rect.width(),
                                      _mouse_fix.y() + self.height())
             elif self._area == "top_left":
                 _rect = QtCore.QRect(
                     self._glo_parent_point_top_left.x() + _mouse_fix.x(),
                     self._glo_parent_point_top_left.y() + _mouse_fix.y(),
                     abs(self._glo_parent_point_top_left.x() +
                         _mouse_fix.x() -
                         self._glo_parent_point_bottom_right.x()),
                     abs(self._glo_parent_point_top_left.y() +
                         _mouse_fix.y() -
                         self._glo_parent_point_bottom_right.y()))
             elif self._area == "top_right":
                 _rect = QtCore.QRect(
                     self._glo_parent_point_top_left.x(),
                     self._glo_parent_point_top_left.y() + _mouse_fix.y(),
                     _mouse_fix.x() + self.width(),
                     abs(self._glo_parent_point_top_left.y() +
                         _mouse_fix.y() -
                         self._glo_parent_point_bottom_right.y()))
             elif self._area == "bottom_left":
                 _rect = QtCore.QRect(
                     self._glo_parent_point_bottom_left.x() +
                     _mouse_fix.x(), self._glo_parent_point_top_left.y(),
                     abs(self._glo_parent_point_bottom_left.x() +
                         _mouse_fix.x() -
                         self._glo_parent_point_bottom_right.x()),
                     _mouse_fix.y() + self.height())
             elif self._area == "bottom_right":
                 _rect = QtCore.QRect(self._glo_parent_point_top_left.x(),
                                      self._glo_parent_point_top_left.y(),
                                      _mouse_fix.x() + self.width(),
                                      _mouse_fix.y() + self.height())
             # self.geometry.emit(bottom_rect )
             self.parent().setGeometry(_rect)
     else:
         self._glo_parent_point_top_left = _parent.mapToParent(
             _parent_rect.topLeft())
         self._glo_parent_point_top_right = _parent.mapToParent(
             _parent_rect.topRight())
         self._glo_parent_point_bottom_left = _parent.mapToParent(
             _parent_rect.bottomLeft())
         self._glo_parent_point_bottom_right = _parent.mapToParent(
             _parent_rect.bottomRight())
Ejemplo n.º 14
0
class edge_frame(QtWidgets.QFrame):
    geometry = QtCore.Signal(QtCore.QRect)

    def __init__(self, parent=None, area="top"):
        super(edge_frame, self).__init__(parent)
        self.setMouseTracking(True)

        self._fix_area = 4

        self._is_press = False
        self._drag_position = QtCore.QPoint(0, 0)

        self._area = area

    def enterEvent(self, event):
        """
        """
        if self._is_press:
            return
        if self._area == "top":
            self.setCursor(QtGui.QCursor(QtCore.Qt.SizeVerCursor))
        elif self._area == "top_left":
            self.setCursor(QtGui.QCursor(QtCore.Qt.SizeFDiagCursor))
        elif self._area == "bottom_right":
            self.setCursor(QtGui.QCursor(QtCore.Qt.SizeFDiagCursor))
        elif self._area == "bottom_left":
            self.setCursor(QtGui.QCursor(QtCore.Qt.SizeBDiagCursor))
        elif self._area == "top_right":
            self.setCursor(QtGui.QCursor(QtCore.Qt.SizeBDiagCursor))
        elif self._area == "left":
            self.setCursor(QtGui.QCursor(QtCore.Qt.SizeHorCursor))
        elif self._area == "right":
            self.setCursor(QtGui.QCursor(QtCore.Qt.SizeHorCursor))
        elif self._area == "bottom":
            self.setCursor(QtGui.QCursor(QtCore.Qt.SizeVerCursor))

    def mousePressEvent(self, event):
        super(edge_frame, self).mousePressEvent(event)
        self._is_press = True
        if event.button() == QtCore.Qt.LeftButton:
            self._drag_position = event.globalPos() - self.pos()

    def mouseReleaseEvent(self, event):
        super(edge_frame, self).mouseReleaseEvent(event)
        self._is_press = False
        # self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))

    def mouseMoveEvent(self, event):
        """
        """
        _parent = self.parent()
        _parent_rect = self.parent().rect()
        if self._is_press:
            if event.buttons() == QtCore.Qt.LeftButton:
                _mouse_fix = event.globalPos() - self._drag_position
                _glo_mouse_point = self.parent().mapToParent(event.pos())
                if self._area == "left":
                    _rect = QtCore.QRect(
                        self._glo_parent_point_top_left.x() + _mouse_fix.x(),
                        self._glo_parent_point_top_left.y(),
                        abs(self._glo_parent_point_top_left.x() +
                            _mouse_fix.x() -
                            self._glo_parent_point_bottom_right.x()),
                        _parent_rect.height())
                elif self._area == "top":
                    _rect = QtCore.QRect(
                        self._glo_parent_point_top_left.x(),
                        self._glo_parent_point_top_left.y() + _mouse_fix.y(),
                        _parent_rect.width(),
                        abs(self._glo_parent_point_top_left.y() +
                            _mouse_fix.y() -
                            self._glo_parent_point_bottom_right.y()))
                elif self._area == "right":
                    _rect = QtCore.QRect(self._glo_parent_point_top_left.x(),
                                         self._glo_parent_point_top_left.y(),
                                         _mouse_fix.x() + self.width(),
                                         _parent_rect.height())
                elif self._area == "bottom":
                    _rect = QtCore.QRect(self._glo_parent_point_top_left.x(),
                                         self._glo_parent_point_top_left.y(),
                                         _parent_rect.width(),
                                         _mouse_fix.y() + self.height())
                elif self._area == "top_left":
                    _rect = QtCore.QRect(
                        self._glo_parent_point_top_left.x() + _mouse_fix.x(),
                        self._glo_parent_point_top_left.y() + _mouse_fix.y(),
                        abs(self._glo_parent_point_top_left.x() +
                            _mouse_fix.x() -
                            self._glo_parent_point_bottom_right.x()),
                        abs(self._glo_parent_point_top_left.y() +
                            _mouse_fix.y() -
                            self._glo_parent_point_bottom_right.y()))
                elif self._area == "top_right":
                    _rect = QtCore.QRect(
                        self._glo_parent_point_top_left.x(),
                        self._glo_parent_point_top_left.y() + _mouse_fix.y(),
                        _mouse_fix.x() + self.width(),
                        abs(self._glo_parent_point_top_left.y() +
                            _mouse_fix.y() -
                            self._glo_parent_point_bottom_right.y()))
                elif self._area == "bottom_left":
                    _rect = QtCore.QRect(
                        self._glo_parent_point_bottom_left.x() +
                        _mouse_fix.x(), self._glo_parent_point_top_left.y(),
                        abs(self._glo_parent_point_bottom_left.x() +
                            _mouse_fix.x() -
                            self._glo_parent_point_bottom_right.x()),
                        _mouse_fix.y() + self.height())
                elif self._area == "bottom_right":
                    _rect = QtCore.QRect(self._glo_parent_point_top_left.x(),
                                         self._glo_parent_point_top_left.y(),
                                         _mouse_fix.x() + self.width(),
                                         _mouse_fix.y() + self.height())
                # self.geometry.emit(bottom_rect )
                self.parent().setGeometry(_rect)
        else:
            self._glo_parent_point_top_left = _parent.mapToParent(
                _parent_rect.topLeft())
            self._glo_parent_point_top_right = _parent.mapToParent(
                _parent_rect.topRight())
            self._glo_parent_point_bottom_left = _parent.mapToParent(
                _parent_rect.bottomLeft())
            self._glo_parent_point_bottom_right = _parent.mapToParent(
                _parent_rect.bottomRight())
Ejemplo n.º 15
0
    def calculate_attribute_draw_details(self):
        """Calculate position of all known attr names. Details stored in
        self._attribute_draw_details. Public interface to get details is split
        into two functions, get_attr_in_pos and get_attr_out_pos.
        """
        self._attribute_draw_details = OrderedDict()
        index = -1
        comp_layer = self.model.comp_layer
        for attr_name in self.user_attr_names:
            index += 1
            draw_details = {}
            # sizes
            rect_y = self.title_rect_height + index * self.attr_rect_height
            rect_midpoint = rect_y + (self.attr_rect_height / 2)
            draw_details['text_height'] = rect_y
            draw_details['bg_rect'] = QtCore.QRectF(0, rect_y, self.max_width,
                                                    self.attr_rect_height)
            # positions
            draw_details['in_pos'] = QtCore.QPointF(self.attr_plug_side_margin,
                                                    rect_midpoint)
            out_x = self.max_width - self.attr_plug_side_margin
            draw_details['out_pos'] = QtCore.QPointF(out_x, rect_midpoint)
            # background color
            color = self.model.get_node_attr_color(self.node_path, attr_name,
                                                   comp_layer)
            bg_color = QtGui.QColor(color).darker(150).darker(self.dim_factor)
            bg_color.setAlphaF(self.attr_rect_opacity)
            draw_details['bg_color'] = bg_color
            # plug color
            type_ = self.model.get_node_attr_type(self.node_path, attr_name,
                                                  comp_layer)
            draw_details['plug_color'] = colors.ATTR_COLORS.get(type_,
                                                                QtCore.Qt.gray)
            # title color
            attr_is_instance = self.model.node_attr_is_instance(self.node_path,
                                                                attr_name,
                                                                comp_layer)
            dim_title = 150 if attr_is_instance else self.dim_factor
            white = QtGui.QColor(QtCore.Qt.white)
            draw_details['title_color'] = white.darker(dim_title)
            # font
            font = QtGui.QFont(self.attr_font.family(),
                               self.attr_font.pointSize(),
                               italic=attr_is_instance)
            draw_details['title_font'] = font

            self._attribute_draw_details[attr_name] = draw_details
        # Internal Attrs
        # Exec
        draw_details = {}
        in_pos = QtCore.QPointF(0, self.title_bounding_rect.height()*0.5)
        draw_details['in_pos'] = in_pos
        out_pos = QtCore.QPointF(self.max_width,
                                 self.title_bounding_rect.height()*0.5)
        draw_details['out_pos'] = out_pos
        draw_details['plug_color'] = QtGui.QColor(QtCore.Qt.white)
        exec_attr = nxt_node.INTERNAL_ATTRS.EXECUTE_IN
        self._attribute_draw_details[exec_attr] = draw_details
        # Inst
        draw_details = {}
        in_pos = QtCore.QPointF(0, (self.title_bounding_rect.height()/3) * 2)
        draw_details['in_pos'] = in_pos
        out_pos = QtCore.QPointF(self.max_width,
                                 (self.title_bounding_rect.height()/3) * 2)
        draw_details['out_pos'] = out_pos
        draw_details['plug_color'] = QtGui.QColor(QtCore.Qt.gray)
        inst_attr = nxt_node.INTERNAL_ATTRS.INSTANCE_PATH
        self._attribute_draw_details[inst_attr] = draw_details
Ejemplo n.º 16
0
    def __init__(self, model, node_path, view):
        super(NodeGraphicsItem, self).__init__()
        self.count = 0
        self.dim_factor = 100
        self.colors = [QtGui.QColor(QtCore.Qt.darkGray)]
        self.color_alpha = 1.0
        # graph settings
        self.node_path = node_path
        self.model = model
        self.view = view

        # item settings
        self.setCacheMode(QtWidgets.QGraphicsItem.DeviceCoordinateCache)

        self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable |
                      QtWidgets.QGraphicsItem.ItemIsFocusable |
                      QtWidgets.QGraphicsItem.ItemIsSelectable |
                      QtWidgets.QGraphicsItem.ItemSendsScenePositionChanges |
                      QtWidgets.QGraphicsItem.ItemNegativeZStacksBehindParent)
        self.setAcceptHoverEvents(True)

        # draw settings
        self.title_font = QtGui.QFont("Roboto Mono", 14)
        self.attr_font = QtGui.QFont("Roboto Mono", 9)
        self.title_rect_height = 39
        self.attr_rect_height = 26
        self.attr_rect_opacity = 0.9
        self.attr_plug_side_margin = 0
        self.plug_selection_range_mult = 1.1
        self.max_width = 260
        self.stack_offset = 20
        self.is_break = False
        self.is_start = False
        self.start_color = colors.ERROR
        self.is_proxy = False
        self.locked = False
        self.is_real = True
        self.attr_dots = [False, False, False]
        self.error_list = []
        self.error_item = None
        self.is_build_focus = False

        # local attributes
        self.user_attr_names = []
        self._attribute_draw_details = OrderedDict()
        self._attr_plug_graphics = {}
        self.exec_out_plug = NodeExecutionPlug(self.model, self.node_path, is_input=False, parent=self)
        self.exec_in_plug = NodeExecutionPlug(self.model, self.node_path, is_input=True, parent=self)
        self.is_hovered = False
        self.collapse_state = False
        self.collapse_arrows = []
        self.node_enabled = None
        self.node_instance = None

        self.model.build_idx_changed.connect(self.update_build_focus)
        self.model.executing_changed.connect(self.update_build_focus)
        # draw node
        self.update_from_model()

        # Setup groups
        # In
        self.in_anim_group = QtCore.QParallelAnimationGroup()
        self.in_anim_group.finished.connect(self.finished_anim)
        # Out
        self.out_anim_group = QtCore.QParallelAnimationGroup()
        self.out_anim_group.finished.connect(self.finished_anim)
Ejemplo n.º 17
0
    def draw_title(self, painter, lod=1.):
        """Draw title of the node. Called exclusively in paint.

        :param painter: painter from paint.
        :type painter: QtGui.QPainter
        """
        # draw bg
        painter.setPen(QtCore.Qt.NoPen)
        bg = painter.background()
        bgm = painter.backgroundMode()
        if self.error_item:
            self.scene().removeItem(self.error_item)
            self.error_item.deleteLater()
        self.error_item = None
        if self.is_real and not self.locked:
            painter.setBackgroundMode(QtCore.Qt.OpaqueMode)
        else:
            painter.setBackgroundMode(QtCore.Qt.TransparentMode)
            [c.setAlphaF(self.color_alpha) for c in self.colors]
        color_count = len(self.colors)
        color_band_width = 10
        for i in range(color_count):
            color = self.colors[i]
            if self.is_proxy:
                painter.setBackground(color.darker(self.dim_factor))
                brush = QtGui.QBrush(color.darker(self.dim_factor*2),
                                     QtCore.Qt.FDiagPattern)
            else:
                brush = QtGui.QBrush(color.darker(self.dim_factor))
            if self.locked:
                c = color.darker(self.dim_factor)
                c.setAlphaF(.5)
                painter.setBackground(c)
                brush = QtGui.QBrush(c.darker(self.dim_factor * 2),
                                     QtCore.Qt.Dense1Pattern)
            painter.setBrush(brush)
            # Top Opinion
            if i+1 == color_count:
                remaining_width = self.max_width - (i*color_band_width)
                rect = QtCore.QRectF(0, 0, remaining_width,
                                     self.title_rect_height)
            # Lower Opinions
            else:
                x_pos = self.max_width - (i+1)*color_band_width
                rect = QtCore.QRectF(x_pos, 0, color_band_width,
                                     self.title_rect_height)
            painter.drawRoundedRect(rect, self.ROUND_X, self.ROUND_Y)
        painter.setBackground(bg)
        painter.setBackgroundMode(bgm)
        # draw exec plugs
        exec_attr = nxt_node.INTERNAL_ATTRS.EXECUTE_IN
        exec_in_pos = self.get_attr_in_pos(exec_attr, scene=False)
        out_pos = self.get_attr_out_pos(exec_attr, scene=False)
        self.exec_out_plug.setPos(out_pos)
        self.exec_in_plug.setPos(exec_in_pos)
        if lod > MIN_LOD:
            # draw attr dots
            offset = -6
            for fill in self.attr_dots:
                painter.setBrush(QtCore.Qt.white)
                if fill:
                    painter.setBrush(QtCore.Qt.white)
                else:
                    painter.setBrush(QtCore.Qt.NoBrush)
                dots_color = QtGui.QColor(QtCore.Qt.white).darker(self.dim_factor)
                painter.setPen(QtGui.QPen(dots_color, 0.5))
                dot_x = self.max_width - 15
                dot_y = (self.title_rect_height / 2) + offset
                painter.drawEllipse(QtCore.QPointF(dot_x, dot_y), 2, 2)
                offset += 6

        # draw title

        painter.setFont(self.title_font)
        title_str = nxt_path.node_name_from_node_path(self.node_path)
        font_metrics = QtGui.QFontMetrics(self.title_font)
        width = self.max_width - 40
        if self.error_list:
            width -= 20
        if lod > MIN_LOD:
            painter.setPen(
                QtGui.QColor(QtCore.Qt.white).darker(self.dim_factor))
            if not self.node_enabled:
                painter.setPen(QtGui.QColor(QtCore.Qt.white).darker(150))
            title = font_metrics.elidedText(title_str,
                                            QtCore.Qt.ElideRight, width)
            painter.drawText(15, 0, self.max_width - 15, self.title_rect_height,
                             QtCore.Qt.AlignVCenter, title)
        else:
            painter.setBrush(QtGui.QColor(QtCore.Qt.white).darker(self.dim_factor))
            if not self.node_enabled:
                painter.setBrush(QtGui.QColor(QtCore.Qt.white).darker(150))
            proxy_rect = font_metrics.boundingRect(title_str)
            r_width = proxy_rect.width() * .8
            height = proxy_rect.height()
            painter.drawRect(15, height * .8,
                             min(r_width, width), height * .2)

        if lod > MIN_LOD:
            # draw error
            if self.error_list:
                pos = QtCore.QPointF(self.max_width-45, self.title_rect_height/4)
                error_item = ErrorItem(font=QtGui.QFont('Roboto', 16, 75),
                                       pos=pos, text='!')
                error_item.setParentItem(self)
                error_item.setZValue(50)
                self.error_item = error_item

        # draw collapse state arrow
        for arrow in self.collapse_arrows:
            self.scene().removeItem(arrow)
        if lod > MIN_LOD:
            self.collapse_arrows = []
            # TODO calculation needed arrows should be done outside drawing

            if self.collapse_state:
                des_colors = self.model.get_descendant_colors(self.node_path)
                filled = self.model.has_children(self.node_path)
                if not filled:
                    des_colors = [QtCore.Qt.white]
                elif not des_colors:
                    disp = self.model.comp_layer
                    des_colors = [self.model.get_node_color(self.node_path, disp)]
                i = 0
                num = len(des_colors)
                for c in des_colors:
                    arrow = CollapseArrow(self, filled=filled, color=c)
                    arrow_width = arrow.width * 1.1
                    center_offset = (arrow_width * (num * .5) - arrow_width * .5)
                    cur_offset = (i * arrow_width)
                    pos = ((self.max_width * .5) + center_offset - cur_offset)
                    arrow.setPos(pos, self.boundingRect().height())
                    self.collapse_arrows += [arrow]
                    i += 1
Ejemplo n.º 18
0
	def plugAt( self, position ) :

		index = self._qtWidget().indexAt( QtCore.QPoint( position.x, position.y ) )
		return self._qtWidget().model().plugForIndex( index )
Ejemplo n.º 19
0
 def closest_grid_point(self, position):
     snapped_pos = self.model.snap_pos_to_grid((position.x(), position.y()))
     return QtCore.QPointF(*snapped_pos)
Ejemplo n.º 20
0
        "formatter": icon_formatter
    },
    QtCore.Qt.ToolTipRole: {
        "config": "tooltip",
        "formatter": display_formatter
    },
    QtCore.Qt.InitialSortOrderRole: {
        "config": "order",
        "formatter": {
            "asc": QtCore.Qt.AscendingOrder,
            "des": QtCore.Qt.DescendingOrder,
        },
    },
    QtCore.Qt.SizeHintRole: {
        "config": "size",
        "formatter": lambda args: QtCore.QSize(*args),
    },
    QtCore.Qt.UserRole: {
        "config": "data"
    },  # anything
}


class MTableModel(QtCore.QAbstractItemModel):
    def __init__(self, parent=None):
        super(MTableModel, self).__init__(parent)
        self.origin_count = 0
        self.root_item = {"name": "root", "children": []}
        self.data_generator = None
        self.header_list = []
        self.timer = QtCore.QTimer(self)
Ejemplo n.º 21
0
 def parent(self, index): # pylint:disable=W0613,R0201
     """ Return the parent model index """
     return QtCore.QModelIndex()
Ejemplo n.º 22
0
 def remove(self, data_dict):
     row = self.root_item["children"].index(data_dict)
     self.beginRemoveRows(QtCore.QModelIndex(), row, row)
     self.root_item["children"].remove(data_dict)
     self.endRemoveRows()
Ejemplo n.º 23
0
 def rowCount(self, parent=QtCore.QModelIndex()):
     if parent.isValid():
         return 0
     return len(self.mapping_to)
Ejemplo n.º 24
0
	def index( self, row, column, parent = QtCore.QModelIndex() ) :

		if parent.isValid() :
			return QtCore.QModelIndex()

		return self.createIndex( row, column )
Ejemplo n.º 25
0
 def parent(self, index=None):
     return QtCore.QModelIndex()
Ejemplo n.º 26
0
	def __rowsAboutToBeInserted( self, parent, start, end ) :

		self.rowsAboutToBeInserted.emit( QtCore.QModelIndex(), start * 2, end * 2 + 1 )
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1084, 1168)
        MainWindow.setCursor(QtCore.Qt.ArrowCursor)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("images/tools.png"), QtGui.QIcon.Normal,
                       QtGui.QIcon.Off)
        MainWindow.setWindowIcon(icon)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QtCore.QRect(10, 220, 1071, 201))
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")
        self.horizontalLayoutWidget = QtWidgets.QWidget(self.tab)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(0, 10, 1051, 130))
        self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(
            self.horizontalLayoutWidget)
        self.horizontalLayout.setContentsMargins(0, -1, -1, -1)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.pushButton.sizePolicy().hasHeightForWidth())
        self.pushButton.setSizePolicy(sizePolicy)
        self.pushButton.setMinimumSize(QtCore.QSize(128, 128))
        self.pushButton.setMaximumSize(QtCore.QSize(128, 128))
        self.pushButton.setCursor(QtCore.Qt.PointingHandCursor)
        self.pushButton.setText("")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("images/spaceshuttle.png"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pushButton.setIcon(icon1)
        self.pushButton.setIconSize(QtCore.QSize(96, 96))
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.pushButton_2 = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.pushButton_2.sizePolicy().hasHeightForWidth())
        self.pushButton_2.setSizePolicy(sizePolicy)
        self.pushButton_2.setMinimumSize(QtCore.QSize(128, 128))
        self.pushButton_2.setMaximumSize(QtCore.QSize(128, 128))
        self.pushButton_2.setCursor(QtCore.Qt.PointingHandCursor)
        self.pushButton_2.setText("")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("images/tv.png"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.pushButton_2.setIcon(icon2)
        self.pushButton_2.setIconSize(QtCore.QSize(96, 96))
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout.addWidget(self.pushButton_2)
        spacerItem = QtWidgets.QSpacerItem(40, 20,
                                           QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")
        self.tabWidget.addTab(self.tab_2, "")
        self.tab_3 = QtWidgets.QWidget()
        self.tab_3.setObjectName("tab_3")
        self.tabWidget.addTab(self.tab_3, "")
        self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 1051, 201))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
        self.label.setObjectName("label")
        self.horizontalLayout_2.addWidget(self.label)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.textBrowser = QtWidgets.QTextBrowser(self.verticalLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.textBrowser.sizePolicy().hasHeightForWidth())
        self.textBrowser.setSizePolicy(sizePolicy)
        self.textBrowser.setAcceptDrops(False)
        self.textBrowser.setReadOnly(True)
        self.textBrowser.setObjectName("textBrowser")
        self.verticalLayout.addWidget(self.textBrowser)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1084, 36))
        self.menubar.setObjectName("menubar")
        self.menuMy_Main_Window = QtWidgets.QMenu(self.menubar)
        self.menuMy_Main_Window.setObjectName("menuMy_Main_Window")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionOpen = QtWidgets.QAction(MainWindow)
        self.actionOpen.setObjectName("actionOpen")
        self.actionSave = QtWidgets.QAction(MainWindow)
        self.actionSave.setObjectName("actionSave")
        self.actionSave_As = QtWidgets.QAction(MainWindow)
        self.actionSave_As.setObjectName("actionSave_As")
        self.menuMy_Main_Window.addAction(self.actionOpen)
        self.menuMy_Main_Window.addAction(self.actionSave)
        self.menuMy_Main_Window.addAction(self.actionSave_As)
        self.menubar.addAction(self.menuMy_Main_Window.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Ejemplo n.º 28
0
	def __rowsRemoved( self, parent, start, end ) :

		self.rowsRemoved.emit( QtCore.QModelIndex(), start * 2, end * 2 + 1 )
Ejemplo n.º 29
0
    def __init__(self,
                 parent,
                 withFileFormatFilter=True,
                 fileFormatFilterTagName=None,
                 fileFormatFilterNodeType=None,
                 pathFormat=None):
        super(VersionSelector, self).__init__()
        self.setupUi(self)
        self.parent = parent
        self.font = uiUtils.getFont('monospace')
        self._data = {}
        self._path = ''
        self.__internalRemap = {}

        self._pathFormat = pathFormat
        if pathFormat is None:
            self._pathFormat = '/projects/{project}/{sequence}/{shot}/{department}/{task}/{name}_{major}.{minor}.{ext}'

        # File Format Filter
        self.fileFormatModel = None
        self._fileFormatFilterTagName = None
        self._fileFormatFilterNodeType = None
        if withFileFormatFilter is True:
            filterData = self.__getFileFormatNames()
            self.fileFormatModel = QtCore.QStringListModel(filterData)
            self.fileFormatComboBox.setModel(self.fileFormatModel)
            if fileFormatFilterTagName is not None:
                if isinstance(fileFormatFilterTagName, str):
                    self._fileFormatFilterTagName = fileFormatFilterTagName
                else:
                    raise ValueError
            if fileFormatFilterNodeType is not None:
                if isinstance(fileFormatFilterNodeType, str):
                    self._fileFormatFilterNodeType = fileFormatFilterNodeType
                else:
                    raise ValueError
        else:
            self.fileFormatLabel.hide()
            self.fileFormatComboBox.hide()

        rootNode = nodes.Node('root', data=self._path)
        self.versionModel = VersionModel(rootNode, font=self.font)

        self.versionFilterModel = qtLearn.uiModels.SortFilterProxyModel()
        self.versionFilterModel.setSourceModel(self.versionModel)
        self.versionFilterModel.setDynamicSortFilter(True)
        self.versionFilterModel.setFilterCaseSensitivity(
            QtCore.Qt.CaseInsensitive)
        self.versionFilterModel.setFilterTagName(self._fileFormatFilterTagName)
        self.versionFilterModel.setFilterTagNodeType(
            self._fileFormatFilterNodeType)

        self.treeView.setModel(self.versionFilterModel)
        self.treeView.setSortingEnabled(True)
        self.treeView.sortByColumn(0, QtCore.Qt.DescendingOrder)
        self.treeView.expandAll()

        self.selectionModel = self.treeView.selectionModel()
        self.selectionModel.currentChanged.connect(self.slotCurrentChanged)

        self.fileFormatComboBox.currentIndexChanged.connect(
            self.slotFileFormatFilterChanged)
Ejemplo n.º 30
0
	def addMessage( self, message ) :

		nextIndex = self.rowCount()
		self.beginInsertRows( QtCore.QModelIndex(), nextIndex, nextIndex )
		self.__messages.add( message )
		self.endInsertRows()
Ejemplo n.º 31
0
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(271, 25)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout(Form)
        self.horizontalLayout_4.setSpacing(5)
        self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label = QtWidgets.QLabel(Form)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
        self.label.setSizePolicy(sizePolicy)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label)
        self.dsbX = QtWidgets.QDoubleSpinBox(Form)
        self.dsbX.setMinimumSize(QtCore.QSize(0, 0))
        self.dsbX.setMaximumSize(QtCore.QSize(80, 16777215))
        self.dsbX.setObjectName("dsbX")
        self.horizontalLayout.addWidget(self.dsbX)
        self.horizontalLayout_4.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label_2 = QtWidgets.QLabel(Form)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label_2.sizePolicy().hasHeightForWidth())
        self.label_2.setSizePolicy(sizePolicy)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout_2.addWidget(self.label_2)
        self.dsbY = QtWidgets.QDoubleSpinBox(Form)
        self.dsbY.setMinimumSize(QtCore.QSize(0, 0))
        self.dsbY.setMaximumSize(QtCore.QSize(80, 16777215))
        self.dsbY.setObjectName("dsbY")
        self.horizontalLayout_2.addWidget(self.dsbY)
        self.horizontalLayout_4.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_3 = QtWidgets.QLabel(Form)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label_3.sizePolicy().hasHeightForWidth())
        self.label_3.setSizePolicy(sizePolicy)
        self.label_3.setObjectName("label_3")
        self.horizontalLayout_3.addWidget(self.label_3)
        self.dsbZ = QtWidgets.QDoubleSpinBox(Form)
        self.dsbZ.setMaximumSize(QtCore.QSize(80, 16777215))
        self.dsbZ.setObjectName("dsbZ")
        self.horizontalLayout_3.addWidget(self.dsbZ)
        self.horizontalLayout_4.addLayout(self.horizontalLayout_3)
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_4.addItem(spacerItem)
        self.pbReset = QtWidgets.QPushButton(Form)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pbReset.sizePolicy().hasHeightForWidth())
        self.pbReset.setSizePolicy(sizePolicy)
        self.pbReset.setMaximumSize(QtCore.QSize(25, 25))
        self.pbReset.setText("")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/icons/resources/reset.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.pbReset.setIcon(icon)
        self.pbReset.setObjectName("pbReset")
        self.horizontalLayout_4.addWidget(self.pbReset)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)
Ejemplo n.º 32
0
def qInitResources():
    QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name,
                                 qt_resource_data)
Ejemplo n.º 33
0
    def _eventPosition(self, event):

        return self._qtWidget().cursorPositionAt(
            QtCore.QPoint(event.line.p0.x, event.line.p0.y))
Ejemplo n.º 34
0
class MAvatar(QtWidgets.QLabel):
    """
    Avatar component. It can be used to represent people or object.

    Property:
        image: avatar image, should be QPixmap.
        dayu_size: the size of image.
    """

    def __init__(self, parent=None, flags=QtCore.Qt.Widget):
        super(MAvatar, self).__init__(parent, flags)
        self._default_pix = MPixmap("user_fill.svg")
        self._pixmap = self._default_pix
        self._dayu_size = 0
        self.set_dayu_size(dayu_theme.default_size)

    def set_dayu_size(self, value):
        """
        Set the avatar size.
        :param value: integer
        :return: None
        """
        self._dayu_size = value
        self._set_dayu_size()

    def _set_dayu_size(self):
        self.setFixedSize(QtCore.QSize(self._dayu_size, self._dayu_size))
        self._set_dayu_image()

    def _set_dayu_image(self):
        self.setPixmap(
            self._pixmap.scaledToWidth(self.height(), QtCore.Qt.SmoothTransformation)
        )

    def set_dayu_image(self, value):
        """
        Set avatar image.
        :param value: QPixmap or None.
        :return: None
        """
        if value is None:
            self._pixmap = self._default_pix
        elif isinstance(value, QtGui.QPixmap):
            self._pixmap = self._default_pix if value.isNull() else value
        else:
            raise TypeError(
                "Input argument 'value' should be QPixmap or None, "
                "but get {}".format(type(value))
            )
        self._set_dayu_image()

    def get_dayu_image(self):
        """
        Get the avatar image.
        :return: QPixmap
        """
        return self._pixmap

    def get_dayu_size(self):
        """
        Get the avatar size
        :return: integer
        """
        return self._dayu_size

    dayu_image = QtCore.Property(QtGui.QPixmap, get_dayu_image, set_dayu_image)
    dayu_size = QtCore.Property(int, get_dayu_size, set_dayu_size)

    @classmethod
    def huge(cls, image=None):
        """Create a MAvatar with huge size"""
        inst = cls()
        inst.set_dayu_size(dayu_theme.huge)
        inst.set_dayu_image(image)
        return inst

    @classmethod
    def large(cls, image=None):
        """Create a MAvatar with large size"""
        inst = cls()
        inst.set_dayu_size(dayu_theme.large)
        inst.set_dayu_image(image)
        return inst

    @classmethod
    def medium(cls, image=None):
        """Create a MAvatar with medium size"""
        inst = cls()
        inst.set_dayu_size(dayu_theme.medium)
        inst.set_dayu_image(image)
        return inst

    @classmethod
    def small(cls, image=None):
        """Create a MAvatar with small size"""
        inst = cls()
        inst.set_dayu_size(dayu_theme.small)
        inst.set_dayu_image(image)
        return inst

    @classmethod
    def tiny(cls, image=None):
        """Create a MAvatar with tiny size"""
        inst = cls()
        inst.set_dayu_size(dayu_theme.tiny)
        inst.set_dayu_image(image)
        return inst
Ejemplo n.º 35
0
	def columnCount( self, parent = QtCore.QModelIndex() ) :

		if parent.isValid() :
			return 0

		return _MessageTableModel.ColumnCount
Ejemplo n.º 36
0
def qCleanupResources():
    QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name,
                                   qt_resource_data)