Пример #1
0
    def thumbnailIcon(self):
        """
        Return the thumbnail icon.

        :rtype: QtGui.QIcon
        """
        thumbnailPath = self.thumbnailPath()

        if not os.path.exists(thumbnailPath):
            color = self.textColor()
            thumbnailPath = studiolibrary.resource().icon("thumbnail",
                                                          color=color)

        if not self._thumbnailIcon:
            if self.ENABLE_THUMBNAIL_THREAD and not self._workerStarted:
                self._workerStarted = True
                self._worker.setPath(thumbnailPath)

                self.ThreadPool.start(self._worker)

                color = self.textColor()
                self._thumbnailIcon = studiolibrary.resource().icon(
                    "thumbnail", color=color)
            else:
                self._thumbnailIcon = QtGui.QIcon(thumbnailPath)

        return self._thumbnailIcon
Пример #2
0
    def newMenu(self):
        """
        Return the new menu for adding new folders and records.
        
        :rtype: QtGui.QMenu
        """
        color = self.iconColor()
        icon = studiolibrary.resource().icon('add', color=color)
        menu = QtGui.QMenu(self)
        menu.setIcon(icon)
        menu.setTitle('New')
        icon = studiolibrary.resource().icon('folder', color=color)
        action = QtGui.QAction(icon, 'Folder', menu)
        action.triggered.connect(self.showCreateFolderDialog)
        menu.addAction(action)
        icon = studiolibrary.resource().icon('add_library', color=color)
        action = QtGui.QAction(icon, 'Library', menu)
        action.triggered.connect(self.showNewLibraryDialog)
        menu.addAction(action)
        separator = QtGui.QAction('', menu)
        separator.setSeparator(True)
        menu.addAction(separator)
        for name in self.library().plugins():
            plugin = self.plugin(name)
            action = plugin.newAction(parent=menu)
            if action:
                callback = partial(self.showCreateWidget, plugin=plugin)
                action.triggered.connect(callback)
                menu.addAction(action)

        return menu
    def newMenu(self):
        """
        Return the new menu for adding new folders and records.
        
        :rtype: QtGui.QMenu
        """
        color = self.iconColor()
        icon = studiolibrary.resource().icon('add', color=color)
        menu = QtGui.QMenu(self)
        menu.setIcon(icon)
        menu.setTitle('New')
        icon = studiolibrary.resource().icon('folder', color=color)
        action = QtGui.QAction(icon, 'Folder', menu)
        action.triggered.connect(self.showCreateFolderDialog)
        menu.addAction(action)
        icon = studiolibrary.resource().icon('add_library', color=color)
        action = QtGui.QAction(icon, 'Library', menu)
        action.triggered.connect(self.showNewLibraryDialog)
        menu.addAction(action)
        separator = QtGui.QAction('', menu)
        separator.setSeparator(True)
        menu.addAction(separator)
        for name in self.library().plugins():
            plugin = self.plugin(name)
            action = plugin.newAction(parent=menu)
            if action:
                callback = partial(self.showCreateWidget, plugin=plugin)
                action.triggered.connect(callback)
                menu.addAction(action)

        return menu
Пример #4
0
    def createActions(self):
        """
        Crate the actions to be shown in the menu.
        
        :rtype: None 
        """
        # Create the menu actions for setting the accent color
        action = SeparatorAction("Accent", self)
        self.addAction(action)

        themes = self._themes

        if not themes:
            themes = themePresets()

        for theme in themes:
            if theme.accentColor():
                action = ThemeAction(theme, self)
                self.addAction(action)

        if self.ENABLE_CUSTOM_ACTION:
            action = QtWidgets.QAction("Custom", self)
            action.triggered.connect(self.theme().browseAccentColor)
            color = self.theme().accentColor().toString()
            icon = studiolibrary.resource().icon(ThemesMenu.THEME_ICON,
                                                 color=color)
            action.setIcon(icon)
            self.addAction(action)

        # Create the menu actions for setting the background color
        action = SeparatorAction("Background", self)
        self.addAction(action)

        for theme in themes:
            if not theme.accentColor() and theme.backgroundColor():
                action = ThemeAction(theme, self)
                self.addAction(action)

        if self.ENABLE_CUSTOM_ACTION:
            action = QtWidgets.QAction("Custom", self)
            action.triggered.connect(self._theme.browseBackgroundColor)
            color = self._theme.backgroundColor().toString()
            icon = studiolibrary.resource().icon(ThemesMenu.THEME_ICON,
                                                 color=color)
            action.setIcon(icon)
            self.addAction(action)

        self.triggered.connect(self._triggered)
Пример #5
0
    def __init__(self, parent=None):
        """
        :type parent: QtWidgets.QWidget
        :type library: studiolibrary.Library
        """
        QtWidgets.QDialog.__init__(self, parent)
        studioqt.loadUi(self)

        self._validator = None
        self._accentColor = self.DEFAULT_ACCENT_COLOR
        self._backgroundColor = self.DEFAULT_BACKGROUND_COLOR

        resource = studiolibrary.resource()
        self.setWindowIcon(resource.icon("icon_black"))

        windowTitle = "Studio Library - {version}"
        windowTitle = windowTitle.format(version=studiolibrary.version())
        self.setWindowTitle(windowTitle)

        self.createAccentColorBar()
        self.createBackgroundColorBar()

        self.ui.acceptButton.clicked.connect(self.accept)
        self.ui.rejectButton.clicked.connect(self.close)
        self.ui.browsePathButton.clicked.connect(self.browsePath)

        self.updateStyleSheet()
        self.center()
 def createWidget(self, parent):
     """
     :type parent: QtGui.QMenu
     """
     height = 25
     spacing = 1
     actionWidget = QtGui.QFrame(parent)
     actionWidget.setObjectName('actionWidget')
     styleSheet = studioqt.StyleSheet.fromText(LibraryAction.STYLE_SHEET, options=self.library().theme())
     actionWidget.setStyleSheet(styleSheet.data())
     actionLabel = QtGui.QLabel(self.library().name(), actionWidget)
     actionLabel.setObjectName('actionLabel')
     actionLabel.setFixedHeight(height)
     iconColor = QtGui.QColor(255, 255, 255, 220)
     icon = studiolibrary.resource().icon('delete', color=iconColor)
     actionOption = QtGui.QPushButton('', actionWidget)
     actionOption.setObjectName('actionOption')
     actionOption.setIcon(icon)
     actionOption.setFixedHeight(height + spacing)
     actionOption.setFixedWidth(height)
     actionOption.clicked.connect(self.deleteLibrary)
     actionIcon = QtGui.QLabel('', actionWidget)
     actionIcon.setObjectName('actionIcon')
     actionIcon.setFixedWidth(10)
     actionIcon.setFixedHeight(height)
     actionLayout = QtGui.QHBoxLayout(actionWidget)
     actionLayout.setSpacing(0)
     actionLayout.setContentsMargins(0, 0, 0, 0)
     actionLayout.addWidget(actionIcon, stretch=1)
     actionLayout.addWidget(actionLabel, stretch=1)
     actionLayout.addWidget(actionOption, stretch=1)
     return actionWidget
Пример #7
0
 def __init__(self, parent, library):
     """
     :type parent: QtWidgets.QWidget
     :type library: studiolibrary.Library
     """
     QtWidgets.QDialog.__init__(self, parent)
     studioqt.loadUi(self)
     resource = studiolibrary.resource()
     self.setWindowIcon(resource.icon('icon_black'))
     windowTitle = 'Studio Library - {version}'
     windowTitle = windowTitle.format(version=studiolibrary.version())
     self.setWindowTitle(windowTitle)
     self.ui.acceptButton.clicked.connect(self.accept)
     self.ui.rejectButton.clicked.connect(self.close)
     self.ui.browseColorButton.clicked.connect(self.browseColor)
     self.ui.browseLocationButton.clicked.connect(self.browseLocation)
     self.ui.browseBackgroundColorButton.clicked.connect(self.browseBackgroundColor)
     self.ui.theme1Button.clicked.connect(self.setTheme1)
     self.ui.theme2Button.clicked.connect(self.setTheme2)
     self.ui.theme3Button.clicked.connect(self.setTheme3)
     self.ui.theme4Button.clicked.connect(self.setTheme4)
     self.ui.theme5Button.clicked.connect(self.setTheme5)
     self.ui.theme6Button.clicked.connect(self.setTheme6)
     self.ui.theme7Button.clicked.connect(self.setTheme7)
     self.ui.background1Button.clicked.connect(self.setBackground1)
     self.ui.background2Button.clicked.connect(self.setBackground2)
     self.ui.background3Button.clicked.connect(self.setBackground3)
     self.ui.background4Button.clicked.connect(self.setBackground4)
     self._library = library
     self.updateStyleSheet()
     self.center()
Пример #8
0
    def __init__(self, *args):
        QtWidgets.QWidget.__init__(self, *args)

        layout = QtWidgets.QHBoxLayout(self)
        self.setLayout(layout)

        layout.setContentsMargins(0,0,0,0)
        layout.setSpacing(0)

        self._dataset = None
        self._iconPadding = 6
        self._iconButton = QtWidgets.QPushButton(self)
        self._iconButton.clicked.connect(self._onClicked)
        layout.addWidget(self._iconButton)

        icon = studiolibrary.resource().icon("pokeball")
        self._iconButton.setIcon(icon)

        self._comboBox = QtWidgets.QComboBox(self)
        layout.addWidget(self._comboBox, 1)

        self._comboBox.addItem("Select a character", "")
        self._comboBox.installEventFilter(self)
        self._comboBox.activated.connect(self._onActivated)

        self._comboBox.setSizePolicy( QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
        self.setSizePolicy( QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)

        self.update()
Пример #9
0
 def __init__(self, parent, library):
     """
     :type parent: QtWidgets.QWidget
     :type library: studiolibrary.Library
     """
     QtWidgets.QDialog.__init__(self, parent)
     studioqt.loadUi(self)
     resource = studiolibrary.resource()
     self.setWindowIcon(resource.icon('icon_black'))
     windowTitle = 'Studio Library - {version}'
     windowTitle = windowTitle.format(version=studiolibrary.version())
     self.setWindowTitle(windowTitle)
     self.ui.acceptButton.clicked.connect(self.accept)
     self.ui.rejectButton.clicked.connect(self.close)
     self.ui.browseColorButton.clicked.connect(self.browseColor)
     self.ui.browseLocationButton.clicked.connect(self.browseLocation)
     self.ui.browseBackgroundColorButton.clicked.connect(
         self.browseBackgroundColor)
     self.ui.theme1Button.clicked.connect(self.setTheme1)
     self.ui.theme2Button.clicked.connect(self.setTheme2)
     self.ui.theme3Button.clicked.connect(self.setTheme3)
     self.ui.theme4Button.clicked.connect(self.setTheme4)
     self.ui.theme5Button.clicked.connect(self.setTheme5)
     self.ui.theme6Button.clicked.connect(self.setTheme6)
     self.ui.theme7Button.clicked.connect(self.setTheme7)
     self.ui.background1Button.clicked.connect(self.setBackground1)
     self.ui.background2Button.clicked.connect(self.setBackground2)
     self.ui.background3Button.clicked.connect(self.setBackground3)
     self.ui.background4Button.clicked.connect(self.setBackground4)
     self._library = library
     self.updateStyleSheet()
     self.center()
Пример #10
0
    def setIcon(self, column, icon, color=None):
        """
        Set the icon to be displayed in the given column.

        :type column: int or str
        :type icon: QtGui.QIcon
        :type color: QtGui.QColor or None
        :rtype: None
        """
        # Safe guard for when the class is being used without the gui.
        isAppRunning = bool(QtWidgets.QApplication.instance())
        if not isAppRunning:
            return

        if isinstance(icon, basestring):
            if not os.path.exists(icon):
                color = color or studioqt.Color(255, 255, 255, 20)
                icon = studiolibrary.resource().icon("image", color=color)
            else:
                icon = QtGui.QIcon(icon)

        if isinstance(column, basestring):
            self._icon[column] = icon
        else:
            self._pixmap[column] = None
            QtWidgets.QTreeWidgetItem.setIcon(self, column, icon)

        self.updateIcon()
Пример #11
0
    def setIcon(self, column, icon, color=None):
        """
        Set the icon to be displayed in the given column.

        :type column: int or str
        :type icon: QtGui.QIcon
        :type color: QtGui.QColor or None
        :rtype: None
        """
        # Safe guard for when the class is being used without the gui.
        isAppRunning = bool(QtWidgets.QApplication.instance())
        if not isAppRunning:
            return

        if isinstance(icon, basestring):
            if not os.path.exists(icon):
                color = color or studioqt.Color(255, 255, 255, 20)
                icon = studiolibrary.resource().icon("image", color=color)
            else:
                icon = QtGui.QIcon(icon)

        if isinstance(column, basestring):
            self._icon[column] = icon
        else:
            self._pixmap[column] = None
            QtWidgets.QTreeWidgetItem.setIcon(self, column, icon)

        self.updateIcon()
Пример #12
0
 def expandedIconPath(self):
     """
     Return the icon path to be shown when expanded.
     
     :rtype: str 
     """
     return self._expandedIconPath or studiolibrary.resource().get(
         "icons", "folder_open")
Пример #13
0
    def collapsedIconPath(self):
        """
        Return the icon path to be shown when collapsed.

        :rtype: str 
        """
        return self._collapsedIconPath or studiolibrary.resource().get(
            "icons", "folder_48")
Пример #14
0
    def createActions(self):
        """
        Crate the actions to be shown in the menu.
        
        :rtype: None 
        """
        # Create the menu actions for setting the accent color
        action = SeparatorAction("Accent", self)
        self.addAction(action)

        themes = self._themes

        if not themes:
            themes = themePresets()

        for theme in themes:
            if theme.accentColor():
                action = ThemeAction(theme, self)
                self.addAction(action)

        if self.ENABLE_CUSTOM_ACTION:
            action = QtWidgets.QAction("Custom", self)
            action.triggered.connect(self.theme().browseAccentColor)
            color = self.theme().accentColor().toString()
            icon = studiolibrary.resource().icon(ThemesMenu.THEME_ICON, color=color)
            action.setIcon(icon)
            self.addAction(action)

        # Create the menu actions for setting the background color
        action = SeparatorAction("Background", self)
        self.addAction(action)

        for theme in themes:
            if not theme.accentColor() and theme.backgroundColor():
                action = ThemeAction(theme, self)
                self.addAction(action)

        if self.ENABLE_CUSTOM_ACTION:
            action = QtWidgets.QAction("Custom", self)
            action.triggered.connect(self._theme.browseBackgroundColor)
            color = self._theme.backgroundColor().toString()
            icon = studiolibrary.resource().icon(ThemesMenu.THEME_ICON, color=color)
            action.setIcon(icon)
            self.addAction(action)

        self.triggered.connect(self._triggered)
Пример #15
0
    def styleSheet(self):
        """
        Return the style sheet for this theme.

        :rtype: str
        """
        options = self.options()
        path = studiolibrary.resource().get("css", "default.css")
        styleSheet = studioqt.StyleSheet.fromPath(path, options=options, dpi=self.dpi())
        return styleSheet.data()
Пример #16
0
    def iconPath(self):
        """
        :rtype: str
        """
        iconPath = self.metaFile().get("icon", None)  # Legacy
        iconPath = self.metaFile().get("iconPath", iconPath)

        if not iconPath:
            iconPath = studiolibrary.resource().get("icons", "folder")

        return iconPath
Пример #17
0
    def iconPath(self):
        """
        :rtype: str
        """
        iconPath = self.metaFile().get("icon", None)  # Legacy
        iconPath = self.metaFile().get("iconPath", iconPath)

        if not iconPath:
            iconPath = studiolibrary.resource().get("icons", "folder")

        return iconPath
Пример #18
0
    def showErrorMessage(self, message, msecs=None):
        """
        Set an error to be displayed in the status widget.

        :type message: str
        :type msecs: int
        
        :rtype: None 
        """
        icon = studiolibrary.resource().icon("error")
        self.setStyleSheet(self.ERROR_CSS)
        self.showMessage(message, icon, msecs, blocking=True)
Пример #19
0
 def pixmap(self):
     """
     :rtype: QtGui.QPixmap
     """
     if not self.isIconVisible():
         return studiolibrary.resource().pixmap('')
     color = self.color()
     iconPath = self.iconPath()
     self._pixmap = studioqt.Pixmap(iconPath)
     if color:
         self._pixmap.setColor(color)
     return self._pixmap
Пример #20
0
    def showErrorMessage(self, message, msecs=None):
        """
        Set an error to be displayed in the status widget.

        :type message: str
        :type msecs: int
        
        :rtype: None 
        """
        icon = studiolibrary.resource().icon("error")
        self.setStyleSheet(self.ERROR_CSS)
        self.showMessage(message, icon, msecs, blocking=True)
Пример #21
0
 def pixmap(self):
     """
     :rtype: QtGui.QPixmap
     """
     if not self.isIconVisible():
         return studiolibrary.resource().pixmap('')
     color = self.color()
     iconPath = self.iconPath()
     self._pixmap = studioqt.Pixmap(iconPath)
     if color:
         self._pixmap.setColor(color)
     return self._pixmap
Пример #22
0
    def options(self):
        """
        Return the variables used to customise the style sheet.

        :rtype: dict
        """
        accentColor = self.accentColor()
        accentForegroundColor = self.accentForgroundColor()

        foregroundColor = self.forgroundColor()
        backgroundColor = self.backgroundColor()

        itemBackgroundColor = self.itemBackgroundColor()
        itemBackgroundHoverColor = self.itemBackgroundHoverColor()

        if self.isDark():
            darkness = "white"
        else:
            darkness = "black"

        resourceDirname = studiolibrary.resource().dirname()
        resourceDirname = resourceDirname.replace("\\", "/")

        options = {
            "DARKNESS": darkness,
            "RESOURCE_DIRNAME": resourceDirname,

            "ACCENT_COLOR": accentColor.toString(),
            "ACCENT_COLOR_R": str(accentColor.red()),
            "ACCENT_COLOR_G": str(accentColor.green()),
            "ACCENT_COLOR_B": str(accentColor.blue()),

            "ACCENT_FOREGROUND_COLOR": accentForegroundColor.toString(),

            "FOREGROUND_COLOR": foregroundColor.toString(),
            "FOREGROUND_COLOR_R": str(foregroundColor.red()),
            "FOREGROUND_COLOR_G": str(foregroundColor.green()),
            "FOREGROUND_COLOR_B": str(foregroundColor.blue()),

            "BACKGROUND_COLOR": backgroundColor.toString(),
            "BACKGROUND_COLOR_R": str(backgroundColor.red()),
            "BACKGROUND_COLOR_G": str(backgroundColor.green()),
            "BACKGROUND_COLOR_B": str(backgroundColor.blue()),

            "ITEM_TEXT_COLOR": foregroundColor.toString(),
            "ITEM_TEXT_SELECTED_COLOR": accentForegroundColor.toString(),

            "ITEM_BACKGROUND_COLOR": itemBackgroundColor.toString(),
            "ITEM_BACKGROUND_HOVER_COLOR": itemBackgroundHoverColor.toString(),
            "ITEM_BACKGROUND_SELECTED_COLOR": accentColor.toString(),
        }

        return options
Пример #23
0
 def reset(self):
     """
     Called when the current animation has finished.
     
     :rtype: None 
     """
     self._timer.stop()
     self._button.hide()
     self._label.setText("")
     icon = studiolibrary.resource().icon("blank")
     self._button.setIcon(icon)
     self.setStyleSheet("")
     self._blocking = False
Пример #24
0
 def reset(self):
     """
     Called when the current animation has finished.
     
     :rtype: None 
     """
     self._timer.stop()
     self._button.hide()
     self._label.setText("")
     icon = studiolibrary.resource().icon("blank")
     self._button.setIcon(icon)
     self.setStyleSheet("")
     self._blocking = False
Пример #25
0
    def showErrorMessage(self, message, msecs=None):
        """
        Set an error to be displayed in the status widget.

        :type message: str
        :type msecs: int
        
        :rtype: None 
        """
        self.setProperty("status", "error")

        icon = studiolibrary.resource().icon("error")
        self.showMessage(message, icon, msecs, blocking=True)
Пример #26
0
    def showWarningMessage(self, message, msecs=None):
        """
        Set a warning to be displayed in the status widget.
        
        :type message: str
        :type msecs: int
        
        :rtype: None 
        """
        if self.isBlocking():
            return

        icon = studiolibrary.resource().icon("warning")
        self.setStyleSheet(self.WARNING_CSS)
        self.showMessage(message, icon, msecs)
Пример #27
0
    def __init__(self, *args):
        QtWidgets.QLineEdit.__init__(self, *args)

        self._dataset = None
        self._spaceOperator = "and"
        self._iconPadding = 6
        self._iconButton = QtWidgets.QPushButton(self)
        self._iconButton.clicked.connect(self._iconClicked)

        icon = studiolibrary.resource().icon("search")
        self.setIcon(icon)

        self._clearButton = QtWidgets.QPushButton(self)
        self._clearButton.setCursor(QtCore.Qt.ArrowCursor)
        icon = studiolibrary.resource().icon("cross")
        self._clearButton.setIcon(icon)
        self._clearButton.setToolTip("Clear all search text")
        self._clearButton.clicked.connect(self._clearClicked)
        self._clearButton.setStyleSheet("background-color: transparent;")

        self.setPlaceholderText(self.PLACEHOLDER_TEXT)
        self.textChanged.connect(self._textChanged)

        self.update()
Пример #28
0
    def showInfoMessage(self, message, msecs=None):
        """
        Set an info message to be displayed in the status widget.
        
        :type message: str
        :type msecs: int
        
        :rtype: None 
        """
        if self.isBlocking():
            return

        icon = studiolibrary.resource().icon("info")
        self.setStyleSheet(self.INFO_CSS)
        self.showMessage(message, icon, msecs)
Пример #29
0
    def showInfoMessage(self, message, msecs=None):
        """
        Set an info message to be displayed in the status widget.
        
        :type message: str
        :type msecs: int
        
        :rtype: None 
        """
        if self.isBlocking():
            return

        icon = studiolibrary.resource().icon("info")
        self.setStyleSheet(self.INFO_CSS)
        self.showMessage(message, icon, msecs)
Пример #30
0
    def showWarningMessage(self, message, msecs=None):
        """
        Set a warning to be displayed in the status widget.
        
        :type message: str
        :type msecs: int
        
        :rtype: None 
        """
        if self.isBlocking():
            return

        icon = studiolibrary.resource().icon("warning")
        self.setStyleSheet(self.WARNING_CSS)
        self.showMessage(message, icon, msecs)
Пример #31
0
 def contextMenu(self, menu):
     """
     :type menu: QtGui.QMenu
     :rtype: None
     """
     folders = self.selectedFolders()
     if not folders:
         return
     separator = QtGui.QAction('Separator1', menu)
     separator.setSeparator(True)
     menu.addAction(separator)
     icon = studiolibrary.resource().icon('settings14')
     settingsMenu = QtGui.QMenu(self)
     settingsMenu.setIcon(icon)
     settingsMenu.setTitle('Settings')
     action = QtGui.QAction('Refresh', settingsMenu)
     action.triggered.connect(self.clearCache)
     settingsMenu.addAction(action)
     separator = QtGui.QAction('Separator2', settingsMenu)
     separator.setSeparator(True)
     settingsMenu.addAction(separator)
     action = QtGui.QAction('Show icon', settingsMenu)
     action.setCheckable(True)
     action.setChecked(self.isFolderIconVisible())
     action.triggered[bool].connect(self.setFolderIconVisible)
     settingsMenu.addAction(action)
     action = QtGui.QAction('Show bold', settingsMenu)
     action.setCheckable(True)
     action.setChecked(self.isFolderBold())
     action.triggered[bool].connect(self.setFolderBold)
     settingsMenu.addAction(action)
     separator = QtGui.QAction('Separator2', settingsMenu)
     separator.setSeparator(True)
     settingsMenu.addAction(separator)
     action = QtGui.QAction('Change icon', settingsMenu)
     action.triggered.connect(self.browseFolderIcon)
     settingsMenu.addAction(action)
     action = QtGui.QAction('Change color', settingsMenu)
     action.triggered.connect(self.browseFolderColor)
     settingsMenu.addAction(action)
     separator = QtGui.QAction('Separator3', settingsMenu)
     separator.setSeparator(True)
     settingsMenu.addAction(separator)
     action = QtGui.QAction('Reset settings', settingsMenu)
     action.triggered.connect(self.resetFolderSettings)
     settingsMenu.addAction(action)
     menu.addMenu(settingsMenu)
Пример #32
0
    def __init__(self, theme, *args):
        """
        :type theme: Theme
        :type menu: QtWidgets.QMenu
        :rtype: QtWidgets.QAction
        """
        QtWidgets.QAction.__init__(self, theme.name(), *args)
        self._theme = theme

        if theme.accentColor():
            color = theme.accentColor()
        elif theme.backgroundColor():
            color = theme.backgroundColor()
        else:
            color = "rgb(255,255,255)"

        icon = studiolibrary.resource().icon(ThemesMenu.THEME_ICON, color=color)
        self.setIcon(icon)
Пример #33
0
def showExample():
    """
    Run a simple example of the widget.

    :rtype: QtWidgets.QWidget
    """

    with studioqt.app():

        menuBarWidget = MenuBarWidget(None)

        def setIconColor():
            menuBarWidget.setIconColor(QtGui.QColor(255, 255, 0))

        def collapse():
            menuBarWidget.collapse()

        menuBarWidget.show()

        action = menuBarWidget.addAction("Collapse")
        action.triggered.connect(collapse)

        w = QtWidgets.QLineEdit()
        menuBarWidget.addWidget(w)

        icon = studiolibrary.resource().icon("add")
        menuBarWidget.addAction(icon, "Plus")
        menuBarWidget.setStyleSheet("""
background-color: rgb(0,200,100);
spacing:5px;
        """)

        menuBarWidget.setChildrenHeight(50)

        action = QtWidgets.QAction("Yellow", None)
        action.triggered.connect(setIconColor)
        menuBarWidget.insertAction("Plus", action)
        menuBarWidget.setGeometry(400, 400, 400, 100)

        menuBarWidget.expand()
Пример #34
0
def showExample():
    """
    Run a simple example of the widget.

    :rtype: QtWidgets.QWidget
    """

    with studioqt.app():

        menuBarWidget = MenuBarWidget(None)

        def setIconColor():
            menuBarWidget.setIconColor(QtGui.QColor(255, 255, 0))

        def collapse():
            menuBarWidget.collapse()

        menuBarWidget.show()

        action = menuBarWidget.addAction("Collapse")
        action.triggered.connect(collapse)

        w = QtWidgets.QLineEdit()
        menuBarWidget.addWidget(w)

        icon = studiolibrary.resource().icon("add")
        menuBarWidget.addAction(icon, "Plus")
        menuBarWidget.setStyleSheet("""
background-color: rgb(0,200,100);
spacing:5px;
        """)

        menuBarWidget.setChildrenHeight(50)

        action = QtWidgets.QAction("Yellow", None)
        action.triggered.connect(setIconColor)
        menuBarWidget.insertAction("Plus", action)
        menuBarWidget.setGeometry(400, 400, 400, 100)

        menuBarWidget.expand()
Пример #35
0
    def thumbnailIcon(self):
        """
        Return the thumbnail icon.

        :rtype: QtGui.QIcon
        """
        thumbnailPath = self.thumbnailPath()

        if not os.path.exists(thumbnailPath):
            color = self.textColor()
            thumbnailPath = studiolibrary.resource().icon("thumbnail",
                                                          color=color)

        if not self._thumbnailIcon:

            if self.ENABLE_THUMBNAIL_THREAD and not self._thread:
                self._thread = IconThread(thumbnailPath)
                self._thread.triggered.connect(self._thumbnailFromImage)
                self._thread.start()
            else:
                self._thumbnailIcon = QtGui.QIcon(thumbnailPath)

        return self._thumbnailIcon
Пример #36
0
def example():
    """
    import studiolibrary
    studiolibrary.reload()
    
    import studiolibrary
    studiolibrary.widgets.formwidget.example()
    """
    import studiolibrary
    image = studiolibrary.resource().get("icons", "icon.png")

    schema = [
        {
            "name": "name",
            "value": "Face.anim",
            "type": "string",
        },
        {
            "name": "objects",
            "value": "125 objects",
            "type": "label",
        },
        {
            "name": "sep1",
            "type": "separator",
        },
        {
            "name": "color",
            "type": "color",
        },
        {
            "name": "blend",
            "type": "slider",
        },
        {
            "name": "Bake",
            "type": "bool",
        },
        {
            "name": "image",
            "type": "image",
            "value": image
        },
        {
            "name": "frameRange",
            "type": "range"
        },
        {
            "name": "option",
            "type": "enum",
            "items": ["Test1", "Test2", "Test4"]
        },
        {
            "name": "comment",
            "value": "this is a comment",
            "type": "text",
            "layout": "vertical"
        },
    ]

    def validator(**fields):
        print(fields)

    w = FormWidget()
    w.setValidator(validator)
    w.setSchema(schema)
    w.setStyleSheet(STYLE)
    w.show()

    return w
Пример #37
0
class FolderLibraryItem(studiolibrary.LibraryItem):

    EnabledOnlyInLibrary = False

    RegisterOrder = 95
    EnableNestedItems = True

    MenuName = "Library"
    MenuOrder = 1
    MenuIconPath = studiolibrary.resource().get("icons/library.png")
    PreviewWidgetClass = studiolibrary.widgets.PreviewWidget
    DefaultThumbnailPath = studiolibrary.resource().get(
        "icons/library_item.png")

    @classmethod
    def match(cls, path):
        """
        Return True if the given path is supported by the item.

        :type path: str 
        :rtype: bool 
        """
        if path.endswith(".lib"):
            return True
        return False

    def info(self):
        """
        Get the info to display to user.
        
        :rtype: list[dict]
        """

        return [{
            "name": "name",
            "value": self.name()[:-4]
        }, {
            "name": "path",
            "value": self.path()
        }, {
            "name": "library id",
            "value": self.itemData()['lib_id']
        }]

    def libraryId(self):
        """
        get the library id
        """
        return self.itemData()['lib_id']

    @classmethod
    def showCreateWidget(cls, libraryWindow):
        """
        Show the dialog for creating a new folder.

        :rtype: None
        """
        path = libraryWindow.selectedFolderPath() or libraryWindow.path()

        #we can only create a library inside a user,
        #so let's make sure we are inside one
        if '.user' not in path:
            studiolibrary.widgets.MessageBox.warning(
                libraryWindow,
                "Missing User",
                "You need to be inside a user to create a library",
                buttons=QtWidgets.QDialogButtonBox.Ok)

        else:

            loaded_rigs = libraryWindow.library().findRigsInScene()

            if len(loaded_rigs) <= 0:
                studiolibrary.widgets.MessageBox.warning(
                    libraryWindow,
                    "Missing rigs",
                    "No entity found in the scene",
                    buttons=QtWidgets.QDialogButtonBox.Ok)

            else:

                custom = FolderLibraryCreateCustomWidget(loaded_rigs)

                button = studiolibrary.widgets.MessageBox.customInput(
                    libraryWindow, "Create library", "Create a library for:",
                    custom)

                name = custom.text()

                if name and button == QtWidgets.QDialogButtonBox.Ok:
                    path = path.split('.user')[0] + '.user'
                    for p in name.split('/'):
                        path = os.path.join(path, p)
                    path += '.lib'

                    os.makedirs(path)

                    if libraryWindow:
                        libraryWindow.sync()

    def createItemData(self):
        """Overriding this method to force the item type to library"""
        itemData = super(FolderLibraryItem, self).createItemData()
        itemData['type'] = "Library"
        itemData['lib_id'] = itemData['path'].split('.user/')[-1].split(
            '.lib')[0]
        return itemData

    def doubleClicked(self):
        """Overriding this method to show the items contained in the folder."""
        self.libraryWindow().selectFolderPath(self.path())

    def write(self, *args, **kwargs):
        """Adding this method to avoid NotImpementedError."""
        pass

    def contextMenu(self, menu, items=None):
        """
        Called when the user right clicks on the item.

        :type menu: QtWidgets.QMenu
        :type items: list[LibraryItem]
        :rtype: None
        """
        callback = partial(
            self._filterLibraries,
            [item for item in items if isinstance(item, FolderLibraryItem)])

        action = QtWidgets.QAction("Display only selected libraries", menu)
        action.triggered.connect(callback)
        menu.addAction(action)

        super(FolderLibraryItem, self).contextMenu(menu, items)

    def _filterLibraries(self, items):
        """callback when filtering with the menu
        
        Arguments:
            items {list of items} -- list of FolderLibraryItems
        """
        self.libraryWindow().setFolderFilterLibraryText(" ".join(
            [item.name()[:-4] for item in items]))

    def isDeleteEnabled(self):
        """Check if we can delete this element
        """
        return True

    def FolderLibraryItem(self):
        """
        returns the containing folder library item
        """
        return self
Пример #38
0
class FolderItem(studiolibrary.LibraryItem):

    RegisterOrder = 100
    EnableNestedItems = True
    DisplayInSidebar = True

    MenuName = "Folder"
    MenuOrder = 1
    MenuIconPath = studiolibrary.resource().get("icons/folder.png")
    ThumbnailPath = studiolibrary.resource().get("icons/folder_item.png")

    @classmethod
    def match(cls, path):
        """
        Return True if the given path is supported by the item.

        :type path: str 
        :rtype: bool 
        """
        if os.path.isdir(path):
            return True

    @classmethod
    def showCreateWidget(cls, libraryWidget):
        """
        Show the dialog for creating a new folder.

        :rtype: None
        """
        path = libraryWidget.selectedFolderPath() or libraryWidget.path()

        name, button = studioqt.MessageBox.input(
            libraryWidget,
            "Create folder",
            "Create a new folder with the name:",
        )

        name = name.strip()

        if name and button == QtWidgets.QDialogButtonBox.Ok:
            path = os.path.join(path, name)

            item = cls(path, libraryWidget=libraryWidget)
            item.save()

    def updatePathData(self):
        """Overriding this method to force the item type to Folder"""
        super(FolderItem, self).updatePathData()
        self.setText("type", "Folder")

    def doubleClicked(self):
        """Overriding this method to show the items contained in the folder."""
        self.libraryWidget().selectFolderPath(self.path())

    def save(self, *args, **kwargs):
        """
        Create a new folder on disc at the given path.

        :rtype: str
        """
        super(FolderItem, self).save(*args, **kwargs)

        if self.libraryWidget():
            self.libraryWidget().selectFolderPath(self.path())
Пример #39
0
 def clear(self):
     self._timer.stop()
     self.ui.message.setText('')
     self.ui.message.setStyleSheet('')
     icon = studiolibrary.resource().icon('blank')
     self.ui.button.setIcon(icon)
Пример #40
0
def example():
    """
    import studiolibrary
    studiolibrary.reload()
    
    import studiolibrary
    studiolibrary.widgets.formwidget.example()
    """
    import studiolibrary
    image = studiolibrary.resource().get("icons", "icon.png")

    schema = [
        {
            "name": "name",
            "value": "Face.anim",
            "type": "string",
        },
        {
            "name": "objects",
            "value": "125 objects",
            "type": "label",
        },
        {
            "name": "sep1",
            "type": "separator",
        },
        {
            "name": "color",
            "type": "color",
        },
        {
            "name": "blend",
            "type": "slider",
        },
        {
            "name": "Bake",
            "type": "bool",
        },
        {
            "name": "image",
            "type": "image",
            "value": image
        },
        {
            "name": "frameRange",
            "type": "range"
        },
        {
            "name": "option",
            "type": "enum",
            "items": ["Test1", "Test2", "Test4"]
        },
        {
            "name": "comment",
            "value": "this is a comment",
            "type": "text",
            "layout": "vertical"
        },
    ]

    def validator(**fields):
        print(fields)

    w = FormWidget()
    w.setValidator(validator)
    w.setSchema(schema)
    w.setStyleSheet(STYLE)
    w.show()

    return w
Пример #41
0
 def setInfo(self, text, msec = DISPLAY_TIME):
     icon = studiolibrary.resource().icon('info')
     self.ui.button.setIcon(icon)
     self.ui.message.setStyleSheet('')
     self.setText(text, msec)
Пример #42
0
class FolderItem(studiolibrary.LibraryItem):

    RegisterOrder = 100
    EnableNestedItems = True
    DisplayInSidebar = True

    MenuName = "Folder"
    MenuOrder = 1
    MenuIconPath = studiolibrary.resource().get("icons/folder.png")
    ThumbnailPath = studiolibrary.resource().get("icons/folder_item.png")
    PreviewWidgetClass = studiolibrary.widgets.PreviewWidget

    @classmethod
    def match(cls, path):
        """
        Return True if the given path is supported by the item.

        :type path: str 
        :rtype: bool 
        """
        if os.path.isdir(path):
            return True

    def options(self):

        created = os.stat(self.path()).st_ctime
        created = datetime.fromtimestamp(created).strftime("%Y-%m-%d %H:%M %p")

        modified = os.stat(self.path()).st_mtime
        modified = datetime.fromtimestamp(modified).strftime(
            "%Y-%m-%d %H:%M %p")

        return [{
            "name": "name",
            "value": self.name()
        }, {
            "name": "path",
            "value": self.path()
        }, {
            "name": "created",
            "value": created,
        }, {
            "name": "modified",
            "value": modified,
        }]

    @classmethod
    def showCreateWidget(cls, libraryWindow):
        """
        Show the dialog for creating a new folder.

        :rtype: None
        """
        path = libraryWindow.selectedFolderPath() or libraryWindow.path()

        name, button = studiolibrary.widgets.MessageBox.input(
            libraryWindow,
            "Create folder",
            "Create a new folder with the name:",
        )

        name = name.strip()

        if name and button == QtWidgets.QDialogButtonBox.Ok:
            path = os.path.join(path, name)

            item = cls(path, libraryWindow=libraryWindow)
            item.save()

    def createItemData(self):
        """Overriding this method to force the item type to Folder"""
        itemData = super(FolderItem, self).createItemData()

        itemData['type'] = "Folder"

        return itemData

    def doubleClicked(self):
        """Overriding this method to show the items contained in the folder."""
        self.libraryWindow().selectFolderPath(self.path())

    def save(self, *args, **kwargs):
        """
        Create a new folder on disc at the given path.

        :rtype: str
        """
        super(FolderItem, self).save(*args, **kwargs)

        if self.libraryWindow():
            self.libraryWindow().selectFolderPath(self.path())
Пример #43
0
class LibraryItem(studiolibrary.widgets.Item):

    EnableDelete = False
    EnableNestedItems = False

    Extension = ""
    Extensions = []

    MenuName = ""
    MenuOrder = 10
    MenuIconPath = ""
    DefaultThumbnailPath = studiolibrary.resource().get(
        "icons", "thumbnail.png")

    RegisterOrder = 10
    TypeIconPath = ""
    DisplayInSidebar = False
    CreateWidgetClass = None
    PreviewWidgetClass = None

    _libraryItemSignals = LibraryItemSignals()

    saved = _libraryItemSignals.saved
    saving = _libraryItemSignals.saving
    loaded = _libraryItemSignals.loaded
    copied = _libraryItemSignals.renamed
    renamed = _libraryItemSignals.renamed
    deleted = _libraryItemSignals.deleted

    @classmethod
    def createAction(cls, menu, libraryWindow):
        """
        Return the action to be displayed when the user 
        ks the "plus" icon.

        :type menu: QtWidgets.QMenu
        :type libraryWindow: studiolibrary.LibraryWindow
        :rtype: QtCore.QAction
        """
        if cls.MenuName:

            icon = QtGui.QIcon(cls.MenuIconPath)
            callback = partial(cls.showCreateWidget, libraryWindow)

            action = QtWidgets.QAction(icon, cls.MenuName, menu)
            action.triggered.connect(callback)

            return action

    @classmethod
    def showCreateWidget(cls, libraryWindow):
        """
        Show the create widget for creating a new item.

        :type libraryWindow: studiolibrary.LibraryWindow
        """
        widget = cls.CreateWidgetClass()
        libraryWindow.setCreateWidget(widget)

    @classmethod
    def isValidPath(cls, path):
        """
        This method has been deprecated. 
        
        Please use LibraryItem.match(cls, path)
        
        :type path: str
        :rtype: bool 
        """
        return cls.match(path)

    @classmethod
    def match(cls, path):
        """
        Return True if the given path location is supported by the item.

        :type path: str
        :rtype: bool 
        """
        for ext in cls.Extensions:
            if path.endswith(ext):
                return True
        return False

    def __init__(
        self,
        path="",
        library=None,
        libraryWindow=None,
    ):
        """
        The LibraryItem class provides an item for use with the LibraryWindow.

        :type path: str
        :type library: studiolibrary.Library or None 
        :type libraryWindow: studiolibrary.LibraryWindow or None
        """
        super(LibraryItem, self).__init__()

        self._path = ""
        self._modal = None
        self._library = None
        self._metadata = None
        self._iconPath = None
        self._typePixmap = None
        self._libraryWindow = None

        if libraryWindow:
            self.setLibraryWindow(libraryWindow)

        if library:
            self.setLibrary(library)

        if path:
            self.setPath(path)

    def info(self):
        """
        Get the info to display to user.
        
        :rtype: list[dict]
        """
        return []

    def loadSchema(self):
        """
        Get the options used to load the item.
        
        :rtype: list[dict]
        """
        return []

    def loadValidator(self, **options):
        """
        Validate the current load options.
        
        :type options: dict
        :rtype: list[dict]
        """
        return []

    def id(self):
        """
        Return the unique id for the item.
    
        :rtype: str 
        """
        return self.path()

    def showToastMessage(self, text):
        """
        A convenience method for showing the toast widget with the given text.

        :type text: str
        :rtype: None
        """
        if self.libraryWindow():
            self.libraryWindow().showToastMessage(text)

    def showErrorDialog(self, title, text):
        """
        Convenience method for showing an error dialog to the user.
        
        :type title: str
        :type text: str
        :rtype: QMessageBox.StandardButton or None
        """
        if self.libraryWindow():
            self.libraryWindow().showErrorMessage(text)

        button = None

        if not self._modal:
            self._modal = True

            try:
                button = studiolibrary.widgets.MessageBox.critical(
                    self.libraryWindow(), title, text)
            finally:
                self._modal = False

        return button

    def showExceptionDialog(self, title, error):
        """
        Convenience method for showing a question dialog to the user.

        :type title: str
        :type error: Exception
        :rtype: QMessageBox.StandardButton
        """
        logger.exception(error)
        return self.showErrorDialog(title, error)

    def showQuestionDialog(self, title, text):
        """
        Convenience method for showing a question dialog to the user.

        :type title: str
        :type text: str
        :rtype: QMessageBox.StandardButton
        """
        return studiolibrary.widgets.MessageBox.question(
            self.libraryWindow(), title, text)

    def typeIconPath(self):
        """
        Return the type icon path on disc.

        :rtype: path or None
        """
        return self.TypeIconPath

    def thumbnailPath(self):
        """
        Return the thumbnail location on disc for this item.

        :rtype: str
        """
        thumbnailPath = self.path() + "/thumbnail.jpg"
        if os.path.exists(thumbnailPath):
            return thumbnailPath

        thumbnailPath = thumbnailPath.replace(".jpg", ".png")
        if os.path.exists(thumbnailPath):
            return thumbnailPath

        return self.DefaultThumbnailPath

    def showPreviewWidget(self, libraryWindow):
        """
        Show the preview Widget for the item instance.

        :type libraryWindow: studiolibrary.LibraryWindow
        """
        widget = self.previewWidget(libraryWindow)
        libraryWindow.setPreviewWidget(widget)

    def previewWidget(self, libraryWindow):
        """
        Return the widget to be shown when the user clicks on the item.

        :type libraryWindow: studiolibrary.LibraryWindow
        :rtype: QtWidgets.QWidget or None
        """
        widget = None

        if self.PreviewWidgetClass:
            widget = self.PreviewWidgetClass(item=self)

        return widget

    def contextEditMenu(self, menu, items=None):
        """
        Called when the user would like to edit the item from the menu.

        The given menu is shown as a submenu of the main context menu.

        :type menu: QtWidgets.QMenu
        :type items: list[LibraryItem]
        :rtype: None
        """
        if self.EnableDelete:
            action = QtWidgets.QAction("Delete", menu)
            action.triggered.connect(self.showDeleteDialog)
            menu.addAction(action)
            menu.addSeparator()

        action = QtWidgets.QAction("Rename", menu)
        action.triggered.connect(self.showRenameDialog)
        menu.addAction(action)

        action = QtWidgets.QAction("Move to", menu)
        action.triggered.connect(self.showMoveDialog)
        menu.addAction(action)

        action = QtWidgets.QAction("Show in Folder", menu)
        action.triggered.connect(self.showInFolder)
        menu.addAction(action)

        if self.libraryWindow():
            action = QtWidgets.QAction("Select Folder", menu)
            action.triggered.connect(self.selectFolder)
            menu.addAction(action)

    def contextMenu(self, menu, items=None):
        """
        Called when the user right clicks on the item.

        :type menu: QtWidgets.QMenu
        :type items: list[LibraryItem]
        :rtype: None
        """
        pass

    def showInFolder(self):
        """Open the file explorer at the given path location."""
        path = self.path()
        studiolibrary.showInFolder(path)

    def selectFolder(self):
        """select the folder in the library widget"""
        if self.libraryWindow():
            path = '/'.join(
                studiolibrary.normPath(self.path()).split('/')[:-1])
            self.libraryWindow().selectFolderPath(path)

    def url(self):
        """Used by the mime data when dragging/dropping the item."""
        return QtCore.QUrl("file:///" + self.path())

    def dirname(self):
        """
        :rtype: str
        """
        return os.path.dirname(self.path())

    def extension(self):
        """
        :rtype: str
        """
        _, extension = os.path.splitext(self.path())
        return extension

    def exists(self):
        """
        :rtype: bool
        """
        return os.path.exists(self.path())

    def mtime(self):
        """
        :rtype: float
        """
        return os.path.getmtime(self.path())

    def ctime(self):
        """
        Return when the item was created.

        :rtype: str
        """
        path = self.path()

        if os.path.exists(path):
            return int(os.path.getctime(path))

        return None

    def setLibraryWindow(self, libraryWindow):
        """
        Set the library widget containing the item.
        
        :rtype: studiolibrary.LibraryWindow or None
        """
        self._libraryWindow = libraryWindow

    def libraryWindow(self):
        """
        Return the library widget containing the item.
        
        :rtype: studiolibrary.LibraryWindow or None
        """
        return self._libraryWindow

    def setLibrary(self, library):
        """
        Set the library model for the item.

        :type library: studiolibrary.Library
        """
        self._library = library

    def library(self):
        """
        Return the library model for the item.

        :rtype: studiolibrary.Library or None
        """
        if not self._library and self.libraryWindow():
            return self.libraryWindow().library()

        return self._library

    def setIconPath(self, path):
        """
        Set the icon path for the current item.

        :type path: str
        :rtype: None
        """
        self._iconPath = path

    def iconPath(self):
        """
        Return the icon path for the current item.

        :rtype: None
        """
        return self._iconPath

    def mimeText(self):
        """
        :rtype: str
        """
        return self.path()

    def path(self):
        """
        Return the path for the item.

        :rtype: str
        """
        return self._path

    def setPath(self, path):
        """
        Set the path location on disc for the item.

        :type path: str
        :rtype: None
        """
        if not path:
            raise ItemError('Cannot set an empty item path.')

        self.resetImageSequence()

        path = studiolibrary.normPath(path)

        self._path = path

        self.updateItemData()

    def setMetadata(self, metadata):
        """
        Set the given metadata for the item.
        
        :type metadata: dict
        """
        self._metadata = metadata

    def metadata(self):
        """
        Get the metadata for the item from disc.
        
        :rtype: dict
        """
        return self._metadata

    def updateMetadata(self, metadata):
        """
        Update the current metadata from disc with the given metadata.
        
        :type metadata: dict
        """
        metadata_ = self.readMetadata()
        metadata_.update(metadata)
        self.saveMetadata(metadata_)

    def saveMetadata(self, metadata):
        """
        Save the given metadata to disc.
        
        :type metadata: dict
        """
        formatString = studiolibrary.config().get('metadataPath')
        path = studiolibrary.formatPath(formatString, self.path())
        studiolibrary.saveJson(path, metadata)
        self.setMetadata(metadata)

    def readMetadata(self):
        """
        Read the metadata for the item from disc.
        
        :rtype: dict
        """
        formatString = studiolibrary.config().get('metadataPath')
        path = studiolibrary.formatPath(formatString, self.path())
        metadata = studiolibrary.readJson(path)
        return metadata

    def updateItemData(self):
        itemData = self.createItemData()
        self.setItemData(itemData)

    def createItemData(self):

        path = self.path()

        dirname, basename, extension = studiolibrary.splitPath(path)

        name = os.path.basename(path)
        category = os.path.basename(dirname)
        # modified = ""
        # timeAgo = ""

        # if os.path.exists(path):
        #     modified = os.path.getmtime(path)
        #     timeAgo = studiolibrary.timeAgo(modified)

        itemData = {
            "name": name,
            "path": path,
            "type": extension,
            "folder": dirname,
            "category": category,
            # "modified": modified
        }

        return itemData

    def saveItemData(self):
        """Sync the item data to the database """
        self.updateItemData()
        self.library().updateItem(self)

    def load(self, *args, **kwargs):
        """Reimplement this method for loading any item data."""
        logger.debug(u'Loading "{0}"'.format(self.name()))
        logger.debug(u'Loading kwargs {0}'.format(kwargs))
        LibraryItem.loaded.emit(self)

    def saveSchema(self):
        """
        Get the schema used for saving the item.
        
        :rtype: list[dict]
        """
        return []

    def saveValidator(self, **fields):
        """
        Validate the given save fields.
        
        :type fields: dict
        :rtype: list[dict]
        """
        return []

    @studioqt.showWaitCursor
    def save(self, path, *args, **kwargs):
        """
        Submit the item for saving.

        :type path: str
        """
        path = path or self.path()

        if path and not path.endswith(self.Extension):
            path += self.Extension

        self.setPath(path)
        path = self.path()

        logger.debug(u'Item Saving: {0}'.format(path))
        self.saving.emit(self)

        if os.path.exists(path):
            self.showAlreadyExistsDialog()

        tempPath = studiolibrary.createTempPath(self.__class__.__name__)

        self.write(tempPath, *args, **kwargs)

        shutil.move(tempPath, path)

        self.saveItemData()

        if self.libraryWindow():
            self.libraryWindow().selectItems([self])

        self.saved.emit(self)
        logger.debug(u'Item Saved: {0}'.format(self.path()))

    def write(self, path, *args, **kwargs):
        """
        Write the item io data to the given path.

        :type path: str
        """
        raise NotImplementedError("The write method has not been implemented!")

    # -----------------------------------------------------------------
    # Support for copy and rename
    # -----------------------------------------------------------------

    def delete(self):
        """
        Delete the item from disc and the library model.

        :rtype: None
        """
        studiolibrary.removePath(self.path())

        if self.library():
            self.library().removePath(self.path())

        self.deleted.emit(self)

    def copy(self, dst):
        """
        Make a copy/duplicate the current item to the given destination.

        :type dst: str
        :rtype: None
        """
        src = self.path()
        dst = studiolibrary.copyPath(src, dst)

        if self.library():
            self.library().copyPath(src, dst)

        self.copied.emit(self, src, dst)

        if self.libraryWindow():
            self.libraryWindow().refresh()

    def move(self, dst):
        """
        Move the current item to the given destination.

        :type dst: str
        :rtype: None
        """
        self.rename(dst)

    def rename(self, dst, extension=None):
        """
        Rename the current path to the given destination path.

        :type dst: str
        :type extension: bool or None
        :rtype: None
        """
        extension = extension or self.extension()
        if dst and extension not in dst:
            dst += extension

        src = self.path()

        # Rename the path on the filesystem
        dst = studiolibrary.renamePath(src, dst)

        # Rename the path inside the library database
        if self.library():
            self.library().renamePath(src, dst)

        # Update the data for the item
        self.setPath(dst)
        self.saveItemData()

        self.renamed.emit(self, src, dst)

    def showRenameDialog(self, parent=None):
        """
        Show the rename dialog.

        :type parent: QtWidgets.QWidget
        """
        select = False

        if self.libraryWindow():
            parent = parent or self.libraryWindow()
            select = self.libraryWindow().selectedFolderPath() == self.path()

        name, button = studiolibrary.widgets.MessageBox.input(
            parent,
            "Rename item",
            "Rename the current item to:",
            inputText=self.name())

        if button == QtWidgets.QDialogButtonBox.Ok:
            try:
                self.rename(name)

                if select:
                    self.libraryWindow().selectFolderPath(self.path())

            except Exception as error:
                self.showExceptionDialog("Rename Error", error)
                raise

        return button

    def showMoveDialog(self, parent=None):
        """
        Show the move to browser dialog.

        :type parent: QtWidgets.QWidget
        """
        title = "Move To..."
        path = os.path.dirname(self.dirname())

        dst = QtWidgets.QFileDialog.getExistingDirectory(parent, title, path)

        if dst:
            try:
                self.move(dst)
            except Exception as error:
                self.showExceptionDialog("Move Error", error)
                raise

    def showDeleteDialog(self):
        """
        Show the delete item dialog.

        :rtype: None
        """

        text = 'Are you sure you want to delete this item?'

        button = self.showQuestionDialog("Delete Item", text)

        if button == QtWidgets.QDialogButtonBox.Yes:
            try:
                self.delete()
            except Exception as error:
                self.showExceptionDialog("Delete Error", error)
                raise

    def showAlreadyExistsDialog(self):
        """
        Show a warning dialog if the item already exists on save.
        
        :rtype: None
        """
        if not self.libraryWindow():
            raise ItemSaveError("Item already exists!")

        path = self.path()

        title = "Item already exists"
        text = 'Would you like to move the existing item "{}" to the trash?'
        text = text.format(self.name())

        buttons = QtWidgets.QMessageBox.Yes | \
                  QtWidgets.QMessageBox.Cancel

        try:
            QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.ArrowCursor)
            button = self.libraryWindow().showQuestionDialog(
                title, text, buttons)
        finally:
            QtWidgets.QApplication.restoreOverrideCursor()

        if button == QtWidgets.QMessageBox.Yes:
            library = self.library()
            item = studiolibrary.LibraryItem(path, library=library)
            self.libraryWindow().moveItemsToTrash([item])
            self.setPath(path)
        else:
            raise ItemSaveError("You cannot save over an existing item.")

        return button

    # -----------------------------------------------------------------
    # Support for painting the type icon
    # -----------------------------------------------------------------

    def typePixmap(self):
        """
        Return the type pixmap for the plugin.

        :rtype: QtWidgets.QPixmap
        """
        if not self._typePixmap:
            iconPath = self.typeIconPath()
            if iconPath and os.path.exists(iconPath):
                self._typePixmap = QtGui.QPixmap(iconPath)
        return self._typePixmap

    def typeIconRect(self, option):
        """
        Return the type icon rect.

        :rtype: QtGui.QRect
        """
        padding = 2 * self.dpi()
        r = self.iconRect(option)

        x = r.x() + padding
        y = r.y() + padding
        rect = QtCore.QRect(x, y, 13 * self.dpi(), 13 * self.dpi())

        return rect

    def paintTypeIcon(self, painter, option):
        """
        Draw the item type icon at the top left.

        :type painter: QtWidgets.QPainter
        :type option: QtWidgets.QStyleOptionViewItem
        :rtype: None
        """
        rect = self.typeIconRect(option)
        typePixmap = self.typePixmap()
        if typePixmap:
            painter.setOpacity(0.5)
            painter.drawPixmap(rect, typePixmap)
            painter.setOpacity(1)

    def paint(self, painter, option, index):
        """
        Overriding the paint method to draw the tag icon and type icon.

        :type painter: QtWidgets.QPainter
        :type option: QtWidgets.QStyleOptionViewItem
        :rtype: None
        """
        super(LibraryItem, self).paint(painter, option, index)

        painter.save()
        try:
            if index.column() == 0:
                self.paintTypeIcon(painter, option)
        finally:
            painter.restore()
Пример #44
0
class FolderUserItem(studiolibrary.LibraryItem):

    EnabledOnlyInLibrary = False

    RegisterOrder = 90
    EnableNestedItems = True

    MenuName = "User"
    MenuOrder = 1
    MenuIconPath = studiolibrary.resource().get("icons/user.png")
    PreviewWidgetClass = studiolibrary.widgets.PreviewWidget
    DefaultThumbnailPath = studiolibrary.resource().get("icons/user_item.png")

    @classmethod
    def match(cls, path):
        """
        Return True if the given path is supported by the item.

        :type path: str 
        :rtype: bool 
        """
        if path.endswith(".user"):
            return True
        return False

    def info(self):
        """
        Get the info to display to user.
        
        :rtype: list[dict]
        """

        return [{
            "name": "name",
            "value": self.name()[:-5]
        }, {
            "name": "path",
            "value": self.path()
        }]

    def user(self):
        """return the user name
        
        Returns:
            string -- user name
        """
        return self.name()[:-5]

    @classmethod
    def showCreateWidget(cls, libraryWindow):
        """
        Show the dialog for creating a new folder.

        :rtype: None
        """
        path = os.path.join(libraryWindow.library().path(), 'user')

        name, button = studiolibrary.widgets.MessageBox.input(
            libraryWindow, "Create User", "Create a new user:"******".user"

        if button == QtWidgets.QDialogButtonBox.Ok:
            path = os.path.join(path, name)

            if os.path.exists(path) == False:

                item = cls(path, libraryWindow=libraryWindow)
                item.save(path)

                if libraryWindow:
                    libraryWindow.refresh()
                    libraryWindow.selectFolderPath(path)

    def createItemData(self):
        """Overriding this method to force the item type to library"""
        itemData = super(FolderUserItem, self).createItemData()
        itemData['type'] = "User"
        return itemData

    def doubleClicked(self):
        """Overriding this method to show the items contained in the folder."""
        self.libraryWindow().selectFolderPath(self.path())

    def write(self, *args, **kwargs):
        """Adding this method to avoid NotImpementedError."""
        pass

    def contextMenu(self, menu, items=None):
        """
        Called when the user right clicks on the item.

        :type menu: QtWidgets.QMenu
        :type items: list[LibraryItem]
        :rtype: None
        """
        callback = partial(
            self._filterUsers,
            [item for item in items if isinstance(item, FolderUserItem)])

        action = QtWidgets.QAction("Display only selected users", menu)
        action.triggered.connect(callback)
        menu.addAction(action)

        super(FolderUserItem, self).contextMenu(menu, items)

    def _filterUsers(self, items):
        """callback when filtering with the menu
        
        Arguments:
            items {list of items} -- list of FolderLibraryItems
        """
        self.libraryWindow().setFolderFilterUserText(" ".join(
            [item.name()[:-5] for item in items]))

    def isDeleteEnabled(self):
        """Check if we can delete this element
        """
        return False

    def FolderUserItem(self):
        """
        returns the containing Folder user item
        """
        return self
Пример #45
0
 def setWarning(self, text, msec = DISPLAY_TIME):
     icon = studiolibrary.resource().icon('warning')
     self.ui.button.setIcon(icon)
     self.ui.message.setStyleSheet('color: rgb(222, 180, 0);')
     self.setText(text, msec)