Пример #1
0
 def tabIcon(self):
     baseIcon = QtGui.QIcon()
     if self.filePath is not None:
         baseIcon = resources.getIcon(self.filePath)
     if self.isModified():
         baseIcon = resources.getIcon("document-save")
     if self.externalAction != None:
         importantIcon = resources.getIcon("emblem-important")
         baseIcon = combine_icons(baseIcon, importantIcon, 0.8)
     return baseIcon
Пример #2
0
 def tabIcon(self):
     baseIcon = QtGui.QIcon()
     if self.filePath is not None:
         baseIcon = resources.getIcon(self.filePath)
     if self.isModified():
         baseIcon = resources.getIcon("save")
     if self.externalAction != None:
         importantIcon = resources.getIcon("important")
         baseIcon = utils.combineIcons(baseIcon, importantIcon, 0.8)
     return baseIcon
Пример #3
0
 def tabIcon(self):
     baseIcon = QtGui.QIcon()
     if self.filePath is not None:
         baseIcon = resources.getIcon(self.filePath)
     if self.isModified():
         baseIcon = resources.getIcon("document-save")
     if self.externalAction != None:
         importantIcon = resources.getIcon("emblem-important")
         baseIcon = combine_icons(baseIcon, importantIcon, 0.8)
     return baseIcon
Пример #4
0
class ProjectSettingsWidget(QtGui.QWidget, SettingsTreeNode):
    TITLE = "Project"
    ICON = resources.getIcon("project-development")

    def __init__(self, settingGroup, parent=None):
        QtGui.QWidget.__init__(self, parent)
        SettingsTreeNode.__init__(self, "project", settingGroup)
Пример #5
0
    def __init__(self, name, area, parent):
        QtGui.QToolBar.__init__(self, parent)
        assert isinstance(parent, QtGui.QMainWindow)
        assert area in self.DOCK_AREA_TO_TB
        self._area = area
        self.setObjectName(text2objectname(name, prefix="ToolBar"))
        self.setWindowTitle(name)

        #Button Style
        #self.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)

        self.setFloatable(False)
        self.setMovable(False)
        self.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed,
                              QtGui.QSizePolicy.MinimumExpanding))
        self.setIconSize(QtCore.QSize(16, 16))

        #Restore action
        self.restoreAction = QtGui.QAction(self)
        self.restoreAction.setIcon(resources.getIcon("image-stack"))
        self.restoreAction.triggered.connect(self.hide)
        self.addAction(self.restoreAction)

        self.visibilityChanged.connect(self.on_visibilityChanged)
Пример #6
0
def create_toolbutton(parent, settings):
    """Create a QToolButton"""
    button = QtGui.QToolButton(parent)
    text = settings["text"] if settings.has_key("text") else "No name"
    button.setObjectName(text2objectname(text, prefix = "toolButton"))
    button.setText(text)
    
    # attrs
    if settings.has_key("icon"):
        icon = settings["icon"]
        if isinstance(icon, basestring):
            icon = resources.getIcon(icon)
        button.setIcon(icon)
    if settings.has_key("shortcut"):
        button.setShortcut(settings["shortcut"])
    if settings.has_key("tip"):
        button.setToolTip(settings["tip"])
    if settings.get("text_beside_icon", False):
        button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
    button.setAutoRaise(settings.get("autoraise", True))
    
    if settings.has_key("triggered") and callable(settings["triggered"]):
        parent.connect(button, QtCore.SIGNAL("clicked()"), settings["triggered"])
    if settings.has_key("clicked") and callable(settings["clicked"]):
        parent.connect(button, QtCore.SIGNAL("clicked()"), settings["clicked"])
    if settings.has_key("toggled") and callable(settings["toggled"]):
        parent.connect(button, QtCore.SIGNAL("toggled(bool)"), settings["toggled"])
        button.setCheckable(True)
        
    return button
Пример #7
0
class NetworkSettingsWidget(QtGui.QWidget, SettingsTreeNode, Ui_BrowserWidget):
    """Setup browser"""
    TITLE = "Browser"
    ICON = resources.getIcon("internet-web-browser")

    def __init__(self, settingGroup, parent=None):
        QtGui.QWidget.__init__(self, parent)
        SettingsTreeNode.__init__(self, "browser", settingGroup)
        self.setupUi(self)

    def filterString(self):
        return "proxyportnetwork" + SettingsTreeNode.filterString(self)

    def on_lineEditProxy_textEdited(self, text):
        self.settingGroup.setValue("proxy", text)

    def on_radioButtonNoProxy_toggled(self, checked):
        print "radioButtonNoProxy", checked

    def on_radioButtonSystemProxy_toggled(self, checked):
        print os.environ.get('http_proxy', '')
        print "radioButtonSystemProxy", checked

    def on_radioButtonManualProxy_toggled(self, checked):
        self.lineEditProxy.setEnabled(checked)
        self.settingGroup.setValue("proxy", "")
        self.lineEditProxy.clear()
Пример #8
0
def create_menu(parent,
                settings,
                useSeparatorName=False,
                connectActions=False):
    text = settings.get("text", "Menu")
    menu = QtGui.QMenu(text, parent)
    menu.setObjectName(text2objectname(text, prefix="menu"))

    # attrs
    if settings.has_key("icon"):
        icon = settings["icon"]
        if isinstance(icon, basestring):
            icon = resources.getIcon(icon)
        menu.setIcon(icon)

    # actions
    actions = extend_menu(menu, settings.get("items", []), useSeparatorName)
    if connectActions:
        for action in actions:
            if hasattr(action, 'callback'):
                if action.isCheckable():
                    parent.connect(action, QtCore.SIGNAL('triggered(bool)'),
                                   action.callback)
                else:
                    parent.connect(action, QtCore.SIGNAL('triggered()'),
                                   action.callback)
    return menu, actions
Пример #9
0
class PMXLoggerDock(QtGui.QDockWidget, Ui_LogWidget, PMXBaseDock):
    """Logging widget
    """
    SHORTCUT = "F12"
    ICON = resources.getIcon("utilities-log-viewer")
    PREFERED_AREA = QtCore.Qt.BottomDockWidgetArea

    def __init__(self, parent=None):
        QtGui.QDockWidget.__init__(self, parent)
        PMXBaseDock.__init__(self)
        self.setupUi(self)
        self.handler = QtLogHandler(self)
        self.handler.setLevel(logging.DEBUG)
        self.setup()

    def setup(self):
        logging.root.addHandler(self.handler)
        self.debug_levels_menu = QtGui.QMenu()
        self.debug_levels_action_group = QtGui.QActionGroup(self)
        for level, value in filter(lambda (key, value): type(key) == str,
                                   logging._levelNames.iteritems()):
            action = QtGui.QAction(level.title(), self)
            action.setData({'name': level, 'level': value})
            action.setCheckable(True)
            self.debug_levels_action_group.addAction(action)
            self.debug_levels_menu.addAction(action)

        self.debug_levels_menu.triggered.connect(self.debug_level_change)
        self.pushDebugLevel.setMenu(self.debug_levels_menu)
Пример #10
0
 def data(self, index, role = QtCore.Qt.DisplayRole):
     if not index.isValid():
         return None
     block = self.blocks[index.row()]
     if role in [ QtCore.Qt.DisplayRole, QtCore.Qt.ToolTipRole ]:
         return "%d - %s" % (block.blockNumber() + 1, block.text().strip())
     elif role == QtCore.Qt.DecorationRole:
         return resources.getIcon('bookmarkflag')
Пример #11
0
 def data(self, index, role=QtCore.Qt.DisplayRole):
     if not index.isValid():
         return None
     block = self.blocks[index.row()]
     if role in [QtCore.Qt.DisplayRole, QtCore.Qt.ToolTipRole]:
         return "%d - %s" % (block.blockNumber() + 1, block.text().strip())
     elif role == QtCore.Qt.DecorationRole:
         return resources.getIcon('bookmarkflag')
Пример #12
0
class PluginsSettingsWidget(QtGui.QWidget, SettingsTreeNode, Ui_Plugins):
    TITLE = "Plugins"
    ICON = resources.getIcon("preferences-plugin-script")

    def __init__(self, settingGroup, parent=None):
        QtGui.QWidget.__init__(self, parent)
        SettingsTreeNode.__init__(self, "plugins", settingGroup)
        self.setupUi(self)
Пример #13
0
class PMXSupportSettings(QtGui.QWidget, SettingsTreeNode, Ui_Support):
    ICON = resources.getIcon('gear')
    TITLE = "Support"

    def __init__(self, settingGroup, parent=None):
        QtGui.QWidget.__init__(self, parent)
        SettingsTreeNode.__init__(self, "support", settingGroup)
        self.setupUi(self)
Пример #14
0
 def configSelectTop(self):
     self.comboBoxItemFilter.addItem("Show all")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-syntax"), "Languages", "syntax")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-snippet"), "Snippets", "snippet")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-macro"), "Macros", "macro")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-command"), "Commands", "command")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-dragcommand"), "DragCommands", "dragcommand")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-preference"), "Preferences", "preference")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-template"), "Templates", "template templatefile")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-project"), "Projects", "project templatefile")
Пример #15
0
    class AddonsSettingsWidget(QtGui.QWidget, SettingsTreeNode, Ui_Addons):
        TITLE = "Addons"
        NAMESPACE = namespace
        ICON = resources.getIcon("preferences-plugin")

        def __init__(self, settingGroup, parent=None):
            QtGui.QWidget.__init__(self, parent)
            SettingsTreeNode.__init__(self, "addons", settingGroup)
            self.setupUi(self)
Пример #16
0
 def configSelectTop(self):
     self.comboBoxItemFilter.addItem("Show all")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-syntax"), "Languages", "syntax")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-snippet"), "Snippets", "snippet")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-macro"), "Macros", "macro")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-command"), "Commands", "command")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-dragcommand"), "DragCommands", "dragcommand")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-preference"), "Preferences", "preference")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-template"), "Templates", "template templatefile")
     self.comboBoxItemFilter.addItem(resources.getIcon("bundle-item-project"), "Projects", "project templatefile")
     self.comboBoxItemFilter.setInsertPolicy(QtGui.QComboBox.NoInsert)
     self.comboBoxItemFilter.lineEdit().returnPressed.connect(self.on_comboBoxItemFilter_returnPressed)
Пример #17
0
 def dictToStandardItem(a_dict):
     item = QtGui.QStandardItem()
     item.setText(a_dict.get('title', ''))
     image = a_dict.get('image')
     if image is not None:
         if isinstance(image, QtGui.QIcon):
             item.setIcon(image)
         else:
             image = resources.getIcon(image) or QtGui.QIcon()
         item.setIcon(image)
     return item
Пример #18
0
 def data(self, index, role = QtCore.Qt.DisplayRole):
     if not index.isValid() or not self.blocks:
         return None
     block = self.blocks[index.row()]
     userData = block.userData()
     #TODO: Ver donde es que pasa esto de que el userData sea None
     if userData is None:
         return None
     if role in [ QtCore.Qt.DisplayRole, QtCore.Qt.ToolTipRole]:
         return userData.symbol
     elif role == QtCore.Qt.DecorationRole:
         #userData.rootGroup(pos)
         return resources.getIcon("scope-root-entity")
Пример #19
0
 def data(self, index, role=QtCore.Qt.DisplayRole):
     if not index.isValid() or not self.blocks:
         return None
     block = self.blocks[index.row()]
     userData = block.userData()
     #TODO: Ver donde es que pasa esto de que el userData sea None
     if userData is None:
         return None
     if role in [QtCore.Qt.DisplayRole, QtCore.Qt.ToolTipRole]:
         return userData.symbol
     elif role == QtCore.Qt.DecorationRole:
         #userData.rootGroup(pos)
         return resources.getIcon("scope-root-entity")
Пример #20
0
 def data(self, index, role=QtCore.Qt.DisplayRole):
     if not index.isValid():
         return None
     suggestion = self.suggestions[index.row()]
     if role in (QtCore.Qt.DisplayRole, QtCore.Qt.EditRole):
         if isinstance(suggestion, dict) and index.column() == 0:
             if 'display' in suggestion:
                 return suggestion['display']
             elif 'title' in suggestion:
                 return suggestion['title']
         elif isinstance(suggestion, BundleItemTreeNode):
             #Es un bundle item
             if index.column() == 0:
                 return suggestion.tabTrigger
             elif index.column() == 1:
                 return suggestion.name
         elif isinstance(suggestion, tuple):
             return suggestion[index.column()]
         elif index.column() == 0:
             return suggestion
     elif role == QtCore.Qt.DecorationRole:
         if index.column() == 0:
             if isinstance(suggestion, dict) and 'image' in suggestion:
                 return resources.getIcon(suggestion['image'])
             elif isinstance(suggestion, BundleItemTreeNode):
                 return suggestion.icon
             else:
                 return resources.getIcon('inserttext')
     elif role == QtCore.Qt.ToolTipRole:
         if isinstance(suggestion, dict) and 'tool_tip' in suggestion:
             if 'tool_tip_format' in suggestion:
                 print suggestion["tool_tip_format"]
             return suggestion['tool_tip']
         elif isinstance(suggestion, BundleItemTreeNode):
             return suggestion.name
     elif role == QtCore.Qt.ForegroundRole:
         return QtCore.Qt.lightGray
Пример #21
0
 def data(self, index, role = QtCore.Qt.DisplayRole):
     if not index.isValid():
         return None
     suggestion = self.suggestions[index.row()]
     if role in (QtCore.Qt.DisplayRole, QtCore.Qt.EditRole):
         if isinstance(suggestion, dict) and index.column() == 0:
             if 'display' in suggestion:
                 return suggestion['display']
             elif 'title' in suggestion:
                 return suggestion['title']
         elif isinstance(suggestion, BundleItemTreeNode):
             #Es un bundle item
             if index.column() == 0:
                 return suggestion.tabTrigger
             elif index.column() == 1:
                 return suggestion.name
         elif isinstance(suggestion, tuple):
             return suggestion[index.column()]
         elif index.column() == 0:
             return suggestion
     elif role == QtCore.Qt.DecorationRole:
         if index.column() == 0:
             if isinstance(suggestion, dict) and 'image' in suggestion:
                 return resources.getIcon(suggestion['image'])
             elif isinstance(suggestion, BundleItemTreeNode):
                 return suggestion.icon
             else:
                 return resources.getIcon('inserttext')
     elif role == QtCore.Qt.ToolTipRole:
         if isinstance(suggestion, dict) and 'tool_tip' in suggestion:
             if 'tool_tip_format' in suggestion:
                 print suggestion["tool_tip_format"]
             return suggestion['tool_tip']
         elif isinstance(suggestion, BundleItemTreeNode):
             return suggestion.name
     elif role == QtCore.Qt.ForegroundRole:
         return QtCore.Qt.lightGray
Пример #22
0
class PMXCodeSymbolsDock(QtGui.QDockWidget, PMXBaseDock):
    SHORTCUT = "F7"
    ICON = resources.getIcon("code-class")
    PREFERED_AREA = QtCore.Qt.RightDockWidgetArea

    def __init__(self, parent):
        QtGui.QDockWidget.__init__(self, parent)
        self.setWindowTitle(_("Symbols"))
        self.setObjectName(_("SymbolsDock"))
        PMXBaseDock.__init__(self)
        self.tableViewSymbols = QtGui.QTableView()
        self.tableViewSymbols.setSelectionMode(
            QtGui.QAbstractItemView.SingleSelection)
        self.tableViewSymbols.setSelectionBehavior(
            QtGui.QAbstractItemView.SelectRows)
        self.tableViewSymbols.setShowGrid(False)
        self.tableViewSymbols.horizontalHeader().setVisible(False)
        self.tableViewSymbols.verticalHeader().setVisible(False)
        self.tableViewSymbols.horizontalHeader().setResizeMode(
            QtGui.QHeaderView.ResizeToContents)
        self.tableViewSymbols.verticalHeader().setResizeMode(
            QtGui.QHeaderView.ResizeToContents)
        self.tableViewSymbols.activated.connect(
            self.on_tableViewSymbols_activated)
        self.tableViewSymbols.doubleClicked.connect(
            self.on_tableViewSymbols_doubleClicked)
        self.setWidget(self.tableViewSymbols)

    def initialize(self, mainWindow):
        PMXBaseDock.initialize(self, mainWindow)
        mainWindow.currentEditorChanged.connect(
            self.on_mainWindow_currentEditorChanged)

    def on_mainWindow_currentEditorChanged(self, editor):
        if isinstance(editor, CodeEditor):
            self.tableViewSymbols.setModel(editor.symbolListModel)
        elif editor is None:
            #Clear
            self.tableViewSymbols.setModel(None)

    def on_tableViewSymbols_activated(self, index):
        block = index.internalPointer()
        self.mainWindow.currentEditor().goToBlock(block)
        self.mainWindow.currentEditor().setFocus()

    def on_tableViewSymbols_doubleClicked(self, index):
        block = index.internalPointer()
        self.mainWindow.currentEditor().goToBlock(block)
        self.mainWindow.currentEditor().setFocus()
Пример #23
0
class PMXTerminalSettings(QtGui.QWidget, SettingsTreeNode, Ui_Terminal):
    TITLE = "Terminal"
    ICON = resources.getIcon("utilities-terminal")

    def __init__(self, settingGroup, parent=None):
        QtGui.QWidget.__init__(self, parent)
        SettingsTreeNode.__init__(self, "terminal", settingGroup)
        self.setupUi(self)

        try:
            from QTermWidget import QTermWidget
        except ImportError:
            return

        t = QTermWidget()

        self.comboScrollBar.addItem(_("No scrollbar"), t.NoScrollBar)
        self.comboScrollBar.addItem(_("Left scrollbar"), t.ScrollBarLeft)
        self.comboScrollBar.addItem(_("Right scrollbar"), t.ScrollBarRight)

        for name in t.availableColorSchemes():
            self.comboColorScheme.addItem(name, name)

        del t

    def loadSettings(self):
        colorScheme = self.settingGroup.value('colorScheme')
        self.comboColorScheme.setCurrentIndex(
            self.comboColorScheme.findData(colorScheme))
        font = self.settingGroup.value('font')
        self.lineFont.setFont(font)
        self.lineFont.setText("%s, %d" % (font.family(), font.pointSize()))

    @QtCore.pyqtSlot(int)
    def on_comboColorScheme_activated(self, index):
        scheme = self.comboColorScheme.itemData(index)
        self.settingGroup.setValue('colorScheme', scheme)

    @QtCore.pyqtSlot()
    def on_pushButtonChangeFont_pressed(self):
        font = self.settingGroup.value('font')
        font, ok = QtGui.QFontDialog.getFont(font, self,
                                             _("Select terminal font"))
        if ok:
            self.settingGroup.setValue('font', font)
            self.lineFont.setFont(font)
            self.lineFont.setText("%s, %d" % (font.family(), font.pointSize()))
Пример #24
0
def create_action(parent, settings):
    """Create a QAction"""
    text = settings.get("text", "Action")
    action = QtGui.QAction(text, parent)
    action.setObjectName(text2objectname(text, prefix="action"))

    # attrs
    if settings.has_key("icon"):
        icon = settings["icon"]
        if isinstance(icon, basestring):
            icon = resources.getIcon(icon)
        action.setIcon(icon)
    if settings.has_key("shortcut"):
        action.setShortcut(settings["shortcut"])
    if settings.has_key("tip"):
        action.setToolTip(settings["tip"])
        action.setStatusTip(settings["tip"])
    if settings.has_key("data"):
        action.setData(settings["data"])
    if settings.has_key("menurole"):
        action.setMenuRole(settings["menurole"])
    if settings.has_key("checkable"):
        action.setCheckable(settings["checkable"])

    # callables
    if settings.has_key("callback"):
        action.callback = settings["callback"]
    if settings.has_key("testChecked"):
        action.testChecked = settings["testChecked"]

    if settings.has_key("triggered") and callable(settings["triggered"]):
        parent.connect(action, QtCore.SIGNAL("triggered()"),
                       settings["triggered"])
    if settings.has_key("toggled") and callable(settings["toggled"]):
        parent.connect(action, QtCore.SIGNAL("toggled(bool)"),
                       settings["toggled"])
        action.setCheckable(True)

    #TODO: Hard-code all shortcuts and choose context=QtCore.Qt.WidgetShortcut
    # (this will avoid calling shortcuts from another dockwidget
    #  since the context thing doesn't work quite well with these widgets)
    action.setShortcutContext(settings.get("context",
                                           QtCore.Qt.WindowShortcut))
    return action
Пример #25
0
    def __init__(self, application):
        """
        The main window
        @param parent: The QObject parent, in this case it should be the QApp
        @param files_to_open: The set of files to be opened when the window is shown in the screen.
        """
        QtGui.QMainWindow.__init__(self)
        self.application = application
        self.setupUi(self)

        self.setWindowIcon(resources.getIcon("prymatex"))

        self.setupDialogs()
        self.setupDockToolBars()
        self.setupMenu()

        self.setStatusBar(PMXStatusBar(self))

        # Connect Signals
        self.splitTabWidget.currentWidgetChanged.connect(
            self.on_currentWidgetChanged)
        self.splitTabWidget.currentWidgetChanged.connect(
            self.setWindowTitleForEditor)
        self.splitTabWidget.tabCloseRequest.connect(self.closeEditor)
        self.splitTabWidget.tabCreateRequest.connect(self.addEmptyEditor)
        self.application.supportManager.bundleItemTriggered.connect(
            self.on_bundleItemTriggered)

        center_widget(self, scale=(0.9, 0.8))
        self.dockers = []
        self.customEditorActions = {}
        self.customDockActions = {}

        self.setAcceptDrops(True)

        #self.setMainWindowAsActionParent()
        self.setupHelpMenuMiscConnections()

        self.popupMessage = PopupMessageWidget(self)

        #Processor de comandos local a la main window
        self.commandProcessor = MainWindowCommandProcessor(self)
        self.bundleItem_handler = self.insertBundleItem
Пример #26
0
class PMXSearchDock(QtGui.QDockWidget, Ui_SearchDock, PMXBaseDock):
    SHORTCUT = "Shift+F4"
    ICON = resources.getIcon("edit-find-project")
    PREFERED_AREA = QtCore.Qt.BottomDockWidgetArea

    def __init__(self, parent):
        QtGui.QDockWidget.__init__(self, parent)
        PMXBaseDock.__init__(self)
        self.setupUi(self)
        self.searchTreeModel = SearchTreeModel(self)
        self.treeView.setModel(self.searchTreeModel)

    def on_actionFileSearch_triggered(self):
        if not self.isVisible():
            self.show()
        self.raise_()
        fileSearch = PMXFileSearchDialog.search(self.searchTreeModel, self)
        #TODO: Si no se encontro nada o se cancelo cerrarlo

    @classmethod
    def contributeToMainMenu(cls, addonClasses):
        edit = {
            'items': [
                "-", {
                    'text': "File Search",
                    'callback': cls.on_actionFileSearch_triggered
                }
            ]
        }
        return {"Edit": edit}

    def on_treeView_activated(self, index):
        node = self.searchTreeModel.node(index)
        if isinstance(node, LineTreeNode):
            self.application.openFile(node.path(),
                                      cursorPosition=(node.lineNumber - 1, 0))

    def on_treeView_doubleClicked(self, index):
        node = self.searchTreeModel.node(index)
        if isinstance(node, LineTreeNode):
            self.application.openFile(node.path(),
                                      cursorPosition=(node.lineNumber - 1, 0))
Пример #27
0
class EditorSettingsWidget(QtGui.QWidget, SettingsTreeNode, Ui_EditorWidget):
    TITLE = "Editor"
    ICON = resources.getIcon("accessories-text-editor")

    def __init__(self, settingGroup, parent=None):
        QtGui.QWidget.__init__(self, parent)
        SettingsTreeNode.__init__(self, "editor", settingGroup)
        self.setupUi(self)
        self.checkBoxLineNumbers.toggled.connect(self.on_gutterOption_toggled)
        self.checkBoxFolding.toggled.connect(self.on_gutterOption_toggled)
        self.checkBoxBookmarks.toggled.connect(self.on_gutterOption_toggled)

    def loadSettings(self):
        flags = int(self.settingGroup.value('defaultFlags'))
        self.checkBoxFolding.setChecked(flags & CodeEditor.ShowFolding)
        self.checkBoxBookmarks.setChecked(flags & CodeEditor.ShowBookmarks)
        self.checkBoxLineNumbers.setChecked(flags & CodeEditor.ShowLineNumbers)
        self.comboBoxDefaultSyntax.setModel(
            self.application.supportManager.syntaxProxyModel)
        self.comboBoxDefaultSyntax.setModelColumn(0)
        uuid = self.settingGroup.value('defaultSyntax')
        syntax = self.application.supportManager.getBundleItem(uuid)
        model = self.comboBoxDefaultSyntax.model()
        index = model.findItemIndex(syntax)
        self.comboBoxDefaultSyntax.setCurrentIndex(index)

    def on_gutterOption_toggled(self, checked):
        flags = 0
        if self.checkBoxFolding.isChecked():
            flags |= CodeEditor.ShowFolding
        if self.checkBoxBookmarks.isChecked():
            flags |= CodeEditor.ShowBookmarks
        if self.checkBoxLineNumbers.isChecked():
            flags |= CodeEditor.ShowLineNumbers
        self.settingGroup.setValue('defaultFlags', flags)

    @QtCore.pyqtSlot(int)
    def on_comboBoxDefaultSyntax_activated(self, index):
        model = self.comboBoxDefaultSyntax.model()
        node = model.mapToSource(model.createIndex(index, 0))
        self.settingGroup.setValue('defaultSyntax',
                                   str(node.internalPointer().uuid).upper())
Пример #28
0
def create_action(parent, settings):
    """Create a QAction"""
    text = settings.get("text", "Action")
    action = QtGui.QAction(text, parent)
    action.setObjectName(text2objectname(text, prefix = "action"))
    
    # attrs
    if settings.has_key("icon"):
        icon = settings["icon"]
        if isinstance(icon, basestring):
            icon = resources.getIcon(icon)
        action.setIcon(icon)
    if settings.has_key("shortcut"):
        action.setShortcut(settings["shortcut"])
    if settings.has_key("tip"):
        action.setToolTip(settings["tip"])
        action.setStatusTip(settings["tip"])
    if settings.has_key("data"):
        action.setData(settings["data"])
    if settings.has_key("menurole"):
        action.setMenuRole(settings["menurole"])
    if settings.has_key("checkable"):
        action.setCheckable(settings["checkable"])
    
    # callables
    if settings.has_key("callback"):
        action.callback = settings["callback"]
    if settings.has_key("testChecked"):
        action.testChecked = settings["testChecked"]
    
    if settings.has_key("triggered") and callable(settings["triggered"]):
        parent.connect(action, QtCore.SIGNAL("triggered()"), settings["triggered"])
    if settings.has_key("toggled") and callable(settings["toggled"]):
        parent.connect(action, QtCore.SIGNAL("toggled(bool)"), settings["toggled"])
        action.setCheckable(True)
        
    #TODO: Hard-code all shortcuts and choose context=QtCore.Qt.WidgetShortcut
    # (this will avoid calling shortcuts from another dockwidget
    #  since the context thing doesn't work quite well with these widgets)
    action.setShortcutContext(settings.get("context", QtCore.Qt.WindowShortcut))
    return action
Пример #29
0
    def __init__(self, application):
        """
        The main window
        @param parent: The QObject parent, in this case it should be the QApp
        @param files_to_open: The set of files to be opened when the window is shown in the screen.
        """
        QtGui.QMainWindow.__init__(self)
        self.application = application
        self.setupUi(self)
        
        self.setWindowIcon(resources.getIcon("prymatex"))
        
        self.setupDialogs()
        self.setupDockToolBars()
        self.setupMenu()
        
        self.setStatusBar(PMXStatusBar(self))
        
        # Connect Signals
        self.splitTabWidget.currentWidgetChanged.connect(self.on_currentWidgetChanged)
        self.splitTabWidget.currentWidgetChanged.connect(self.setWindowTitleForEditor)
        self.splitTabWidget.tabCloseRequest.connect(self.closeEditor)
        self.splitTabWidget.tabCreateRequest.connect(self.addEmptyEditor)
        self.application.supportManager.bundleItemTriggered.connect(self.on_bundleItemTriggered)
        
        center_widget(self, scale = (0.9, 0.8))
        self.dockers = []
        self.customEditorActions = {}
        self.customDockActions = {}

        self.setAcceptDrops(True)
        
        #self.setMainWindowAsActionParent()
        self.setupHelpMenuMiscConnections()
        
        self.popupMessage = PopupMessageWidget(self)
        
        #Processor de comandos local a la main window
        self.commandProcessor = MainWindowCommandProcessor(self)
        self.bundleItem_handler = self.insertBundleItem
Пример #30
0
def create_menu(parent, settings, useSeparatorName = False, connectActions = False):
    text = settings.get("text", "Menu")
    menu = QtGui.QMenu(text, parent)
    menu.setObjectName(text2objectname(text, prefix = "menu"))

    # attrs
    if settings.has_key("icon"):
        icon = settings["icon"]
        if isinstance(icon, basestring):
            icon = resources.getIcon(icon)
        menu.setIcon(icon)

    # actions
    actions = extend_menu(menu, settings.get("items", []), useSeparatorName)
    if connectActions:
        for action in actions:
            if hasattr(action, 'callback'):
                if action.isCheckable():
                    parent.connect(action, QtCore.SIGNAL('triggered(bool)'), action.callback)
                else:
                    parent.connect(action, QtCore.SIGNAL('triggered()'), action.callback)
    return menu, actions
Пример #31
0
 def __init__(self, editor): 
     QtCore.QAbstractListModel.__init__(self, editor)
     self.editor = editor
     self.logger = editor.application.getLogger('.'.join([self.__class__.__module__, self.__class__.__name__]))
     self.symbolChanged = False
     self.editor.textChanged.connect(self.on_editor_textChanged)
     self.editor.beforeOpen.connect(self.on_editor_beforeOpen)
     self.editor.afterOpen.connect(self.on_editor_afterOpen)
     self.blocks = []
     self.icons = {
         "class": resources.getIcon("symbol-class"),
         "block": resources.getIcon("symbol-block"),
         "context": resources.getIcon("symbol-context"),
         "function": resources.getIcon("symbol-function"),
         "typedef": resources.getIcon("symbol-typedef"),
         "variable": resources.getIcon("symbol-variable")
     }
Пример #32
0
 def __init__(self, name, area, parent):
     QtGui.QToolBar.__init__(self, parent)
     assert isinstance(parent, QtGui.QMainWindow)
     assert area in self.DOCK_AREA_TO_TB
     self._area = area
     self.setObjectName(utils.textToObjectName(name, prefix="ToolBar"))
     self.setWindowTitle(name)
     
     #Button Style
     #self.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
     
     self.setFloatable(False)
     self.setMovable(False)
     self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.MinimumExpanding))
     self.setIconSize(QtCore.QSize(16,16));
     
     #Restore action
     self.restoreAction = QtGui.QAction(self)
     self.restoreAction.setIcon(resources.getIcon("stack"))
     self.restoreAction.triggered.connect(self.hide)
     self.addAction(self.restoreAction)
     
     self.visibilityChanged.connect(self.on_visibilityChanged)
Пример #33
0
 def __init__(self, editor):
     QtCore.QAbstractListModel.__init__(self, editor)
     self.editor = editor
     self.logger = editor.application.getLogger('.'.join(
         [self.__class__.__module__, self.__class__.__name__]))
     self.symbolChanged = False
     self.editor.textChanged.connect(self.on_editor_textChanged)
     self.editor.beforeOpen.connect(self.on_editor_beforeOpen)
     self.editor.afterOpen.connect(self.on_editor_afterOpen)
     self.blocks = []
     self.icons = {
         "class": resources.getIcon("symbol-class"),
         "block": resources.getIcon("symbol-block"),
         "context": resources.getIcon("symbol-context"),
         "function": resources.getIcon("symbol-function"),
         "typedef": resources.getIcon("symbol-typedef"),
         "variable": resources.getIcon("symbol-variable")
     }
Пример #34
0
class GeneralSettingsWidget(QtGui.QWidget, SettingsTreeNode, Ui_GeneralWidget):
    TITLE = "General"
    ICON = resources.getIcon("preferences-other")

    def __init__(self, settingGroup, parent=None):
        QtGui.QWidget.__init__(self, parent)
        SettingsTreeNode.__init__(self, "general", settingGroup)
        self.setupUi(self)

        #self.comboTabVisibility.addItem("Always shown", PMXTabWidget.TABBAR_ALWAYS_SHOWN)
        #self.comboTabVisibility.addItem("Show when more than one", PMXTabWidget.TABBAR_WHEN_MULTIPLE)
        #self.comboTabVisibility.addItem("Never show", PMXTabWidget.TABBAR_NEVER_SHOWN)

    @QtCore.pyqtSlot(int)
    def on_comboTabVisibility_currentIndexChanged(self, index):
        value = self.comboTabVisibility.itemData(index)
        self.settingGroup.setValue('showTabBar', value)

    def appendToCombo(self, text):
        current_index = self.comboApplicationTitle.currentIndex()
        current_text = self.comboApplicationTitle.currentText()
        text = unicode(current_text or '') + unicode(text or '')
        self.comboApplicationTitle.setItemText(current_index, text)

    def on_pushInsertAppName_pressed(self):
        self.appendToCombo("$APPNAME")

    def on_pushInsertFile_pressed(self):
        self.appendToCombo("$FILENAME")

    def on_pushInsertProject_pressed(self):
        self.appendToCombo("$PROJECT")

    @QtCore.pyqtSlot(str)
    def on_comboApplicationTitle_editTextChanged(self, text):
        self.settingGroup.setValue('windowTitleTemplate', text)
Пример #35
0
class ExternalProcessTableModel(QtCore.QAbstractTableModel):
    STATES_STRING = {0: "NotRunning", 1: "Starting", 2: "Running"}
    STATES_ICONS = {
        0: resources.getIcon("porcess-not-running"),
        1: resources.getIcon("porcess-starting"),
        2: resources.getIcon("porcess-running")
    }

    def __init__(self, manager, parent=None):
        QtCore.QAbstractTableModel.__init__(self, parent)
        self.manager = manager
        self.processItems = []

    def index(self, row, column, parent=None):
        return self.createIndex(row, column, self.processItems[row])

    def rowCount(self, parent=None):
        return len(self.processItems)

    def columnCount(self, parent):
        return 3

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if not index.isValid():
            return None
        item = self.processItems[index.row()]
        if role in [QtCore.Qt.DisplayRole, QtCore.Qt.ToolTipRole]:
            if index.column() == 0:
                return item["process"].pid()
            elif index.column() == 1:
                return item["description"]
            elif index.column() == 2:
                return self.STATES_STRING[item["process"].state()]
        elif role == QtCore.Qt.DecorationRole and index.column() == 0:
            return self.STATES_ICONS[item["process"].state()]

    def findRowIndex(self, process):
        items = filter(lambda item: item["process"] == process,
                       self.processItems)
        assert len(items) == 1, "No puede tener mas de uno"
        return self.processItems.index(items[0])

    def processForIndex(self, index):
        return self.processItems[index.row()]["process"]

    def appendProcess(self, process, description=""):
        self.beginInsertRows(QtCore.QModelIndex(), len(self.processItems),
                             len(self.processItems))
        self.processItems.append({
            "process": process,
            "description": description
        })
        self.endInsertRows()

    def removeProcess(self, process):
        index = self.findRowIndex(process)
        self.beginRemoveRows(QtCore.QModelIndex(), index, index)
        self.processItems.pop(index)
        self.endRemoveRows()

    def getAllItems(self):
        return map(lambda item: item["process"], self.processItems)
Пример #36
0
    def setupCornerWidget(self):
        widget = QtGui.QWidget()
        layout = QtGui.QHBoxLayout()
        # Add
        self.pushAddNewTerminal = QtGui.QPushButton()
        self.pushAddNewTerminal.setIcon(resources.getIcon('utilities-terminal'))
        self.pushAddNewTerminal.setToolTip(_("Add new terminal"))
        self.pushAddNewTerminal.setFlat(True)

        menuAddNew = QtGui.QMenu()
        actionNew = menuAddNew.addAction("Terminal")
        actionNew.triggered.connect(self.addTerminal)
        actionCustom = menuAddNew.addAction("Run in terminal...")
        actionCustom.triggered.connect(self.launchCustomCommandInTerminal)
        self.pushAddNewTerminal.setMenu(menuAddNew)
        layout.addWidget(self.pushAddNewTerminal)
        
        # Copy
        shortcutCopy = QtGui.QShortcut(QtGui.QKeySequence("Ctrl+c"), self)
        shortcutCopy.activated.connect(lambda s = self: s.currentWidget().copyClipboard())
        
        # Paste
        self.pushPasteIntoTerminal = QtGui.QPushButton()
        self.pushPasteIntoTerminal.setIcon(resources.getIcon('edit-paste'))
        self.pushPasteIntoTerminal.setObjectName('pushPasteIntoTerminal')
        self.pushPasteIntoTerminal.setToolTip('Paste text into terminal')
        self.pushPasteIntoTerminal.setFlat(True)
        self.pushPasteIntoTerminal.pressed.connect(lambda s=self: s.currentWidget().pasteClipboard())
        layout.addWidget(self.pushPasteIntoTerminal)
        
        # Config
        self.pushConfigTerminal = QtGui.QPushButton("C")
        
        #self.pushConfigTerminal.setIcon(getIcon('preference'))
        # self.pushConfigTerminal.setObjectName('pushConfigTerminal')
        # self.pushConfigTerminal.setToolTip('Configure terminal')
        # self.pushConfigTerminal.setFlat(True)
        # layout.addWidget(self.pushConfigTerminal)
        self.cornerMenuButton = QtGui.QPushButton()        
        self.cornerMenuButtonMenu = QtGui.QMenu()
        self.cornerMenuButton.setMenu(self.cornerMenuButtonMenu)
        self.cornerMenuButtonMenu.addAction("Alfa")
        self.cornerMenuButtonMenu.addAction("Beta")
        self.cornerMenuButtonMenu.addAction("Gama")
        
        layout.addWidget(self.cornerMenuButton)
        
        # Close
        self.pushCloseTerminal = QtGui.QPushButton()
        self.pushCloseTerminal.setIcon(resources.getIcon("close"))
        self.pushCloseTerminal.setObjectName("pushCloseTerminal")
        self.pushCloseTerminal.setToolTip(_("Close terminal"))
        self.pushCloseTerminal.setFlat(True)
        
        self.pushCloseTerminal.pressed.connect(lambda s=self: s.removeTab(s.currentIndex()))
        layout.addWidget(self.pushCloseTerminal)
        
        widget.setLayout(layout)
        
        # Save some space
        widget.setStyleSheet('''
        QPushButton {
            margin: 0px;
            padding: 0 0px 0 2px;
        }
        ''')
        self.setCornerWidget(widget)
Пример #37
0
 def icon(self):
     if self.manager.isOpen(self):
         return resources.getIcon("project-development")
Пример #38
0
class PMXProjectDock(QtGui.QDockWidget, Ui_ProjectsDock, PMXFileSystemTasks,
                     PMXBaseDock):
    SHORTCUT = "F8"
    ICON = resources.getIcon("project-development")
    PREFERED_AREA = QtCore.Qt.LeftDockWidgetArea

    #=======================================================================
    # Settings
    #=======================================================================
    SETTINGS_GROUP = 'Projects'

    @pmxConfigPorperty(default='')
    def customFilters(self, filters):
        self.projectTreeProxyModel.setFilterRegExp(filters)

    def __init__(self, parent):
        QtGui.QDockWidget.__init__(self, parent)
        PMXBaseDock.__init__(self)
        self.setupUi(self)
        self.projectManager = self.application.projectManager
        self.projectTreeProxyModel = self.projectManager.projectTreeProxyModel

        self.setupPropertiesDialog()
        self.setupTreeViewProjects()

    def initialize(self, mainWindow):
        PMXBaseDock.initialize(self, mainWindow)
        #TODO: ver el tema de proveer servicios esta instalacion en la main window es pedorra
        mainWindow.projects = self

    @classmethod
    def contributeToSettings(cls):
        from prymatex.gui.settings.project import ProjectSettingsWidget
        from prymatex.gui.settings.addons import AddonsSettingsWidgetFactory
        return [ProjectSettingsWidget, AddonsSettingsWidgetFactory("project")]

    def addFileSystemNodeFormater(self, formater):
        self.projectTreeProxyModel.addNodeFormater(formater)

    def saveState(self):
        expandedIndexes = filter(
            lambda index: self.treeViewProjects.isExpanded(index),
            self.projectTreeProxyModel.persistentIndexList())
        expandedPaths = map(
            lambda index: self.projectTreeProxyModel.node(index).path(),
            expandedIndexes)
        return {"expanded": expandedPaths}

    def restoreState(self, state):
        #Expanded Nodes
        map(
            lambda index: index.isValid() and self.treeViewProjects.
            setExpanded(index, True),
            map(lambda path: self.projectTreeProxyModel.indexForPath(path),
                state["expanded"]))

    def environmentVariables(self):
        environment = PMXBaseDock.environmentVariables(self)
        indexes = self.treeViewProjects.selectedIndexes()
        if indexes:
            node = self.currentNode()
            paths = map(
                lambda node: self.application.fileManager.normcase(node.path()
                                                                   ),
                [self.projectTreeProxyModel.node(index) for index in indexes])
            environment.update({
                'TM_SELECTED_FILE':
                node.path(),
                'TM_SELECTED_FILES':
                " ".join(["'%s'" % path for path in paths])
            })
        return environment

    def keyPressEvent(self, event):
        if not self.runKeyHelper(event):
            return QtGui.QDockWidget.keyPressEvent(self, event)

    def setupPropertiesDialog(self):
        from prymatex.gui.dialogs.properties import PMXPropertiesDialog
        from prymatex.gui.project.environment import EnvironmentWidget
        from prymatex.gui.project.resource import PMXResouceWidget
        self.application.populateComponent(PMXPropertiesDialog)
        self.propertiesDialog = PMXPropertiesDialog(self)
        self.application.extendComponent(EnvironmentWidget)
        self.application.extendComponent(PMXResouceWidget)
        self.propertiesDialog.register(EnvironmentWidget(self))
        self.propertiesDialog.register(PMXResouceWidget(self))
        #TODO: Para cada add-on registrar los correspondientes properties

    def setupTreeViewProjects(self):
        self.treeViewProjects.setModel(self.projectTreeProxyModel)

        self.treeViewProjects.setHeaderHidden(True)
        self.treeViewProjects.setUniformRowHeights(False)

        #Setup Context Menu
        optionsMenu = {
            "text":
            "Project Options",
            "items": [{
                "text":
                "Order",
                "items":
                [(self.actionOrderByName, self.actionOrderBySize,
                  self.actionOrderByDate, self.actionOrderByType), "-",
                 self.actionOrderDescending, self.actionOrderFoldersFirst]
            }]
        }

        self.actionOrderFoldersFirst.setChecked(True)
        self.actionOrderByName.trigger()

        self.projectOptionsMenu, _ = create_menu(self, optionsMenu)
        self.pushButtonOptions.setMenu(self.projectOptionsMenu)

        #Connect context menu
        self.treeViewProjects.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.treeViewProjects.customContextMenuRequested.connect(
            self.showProjectTreeViewContextMenu)

        #=======================================================================
        # Drag and Drop (see the proxy model)
        #=======================================================================
        self.treeViewProjects.setDragEnabled(True)
        self.treeViewProjects.setAcceptDrops(True)
        self.treeViewProjects.setDefaultDropAction(QtCore.Qt.MoveAction)
        self.treeViewProjects.setDropIndicatorShown(True)

        self.treeViewProjects.setAlternatingRowColors(True)
        self.treeViewProjects.setAnimated(True)

        # Selection Mode
        self.treeViewProjects.setSelectionMode(
            QtGui.QAbstractItemView.ExtendedSelection)

    #================================================
    # Build Menus
    #================================================
    def buildContextMenu(self, index):
        contextMenu = {
            "text":
            "Context",
            "items": [{
                "text":
                "New",
                "items": [
                    self.actionNewFolder,
                    self.actionNewFile,
                    "-",
                    self.actionNewFromTemplate,
                    self.actionNewProject,
                ]
            }, "--refresh", self.actionRefresh, "--bundles"]
        }
        if index.isValid():
            node = self.projectTreeProxyModel.node(index)
            self.extendFileSystemItemMenu(contextMenu, node)
            self.extendAddonsItemMenu(contextMenu, node)
            self.extendProjectBundleItemMenu(contextMenu, node)
        # contextMenu, contextMenuActions = create_menu(contextMenu, self, useSeparatorName = True)
        contextMenu, contextMenuActions = create_menu(self, contextMenu)

        for action in contextMenuActions:
            if hasattr(action, "callback"):
                action.triggered.connect(action.callback)

        contextMenu.aboutToShow.connect(self.on_contextMenu_aboutToShow)
        contextMenu.aboutToHide.connect(self.on_contextMenu_aboutToHide)
        contextMenu.triggered.connect(self.on_contextMenu_triggered)
        return contextMenu

    def on_contextMenu_aboutToShow(self):
        # TODO Quiza un metodo que haga esto en el manager
        self.application.supportManager.setEditorAvailable(False)
        self.application.supportManager.blockSignals(True)

    def on_contextMenu_aboutToHide(self):
        self.application.supportManager.setEditorAvailable(True)

        def restore_supportManager_signals():
            self.application.supportManager.blockSignals(False)

        # TODO No estoy muy contento con esto pero que le vamos a hacer
        QtCore.QTimer.singleShot(0, restore_supportManager_signals)

    def on_contextMenu_triggered(self, action):
        if hasattr(action, "bundleTreeNode"):
            node = self.currentNode()
            env = {
                'TM_FILEPATH': node.path(),
                'TM_FILENAME': node.nodeName(),
                'TM_DIRECTORY': node.parentNode().path()
            } if node.isfile else {
                'TM_DIRECTORY': node.path()
            }

            env.update(node.project().environmentVariables())
            self.mainWindow.insertBundleItem(action.bundleTreeNode,
                                             environment=env)

    def extendFileSystemItemMenu(self, menu, node):
        extend_menu_section(menu, [
            "--open", self.actionOpenSystemEditor, "--handlepaths",
            self.actionDelete, self.actionRename
        ])
        #extend_menu_section(menu, ["--interact", self.actionSetInTerminal ], section = -1)
        # TODO Quiza sea mejor ponerle un type y controlar contra una cadena
        if isinstance(node, ProjectTreeNode):
            extend_menu_section(menu, [self.actionPaste, self.actionRemove],
                                section="handlepaths",
                                position=0)
            #extend_menu_section(menu, [self.actionCloseProject, self.actionOpenProject], section = "refresh")
            #extend_menu_section(menu, [self.actionBashInit], section = "interact")
            extend_menu_section(menu, [self.actionBundleEditor],
                                section="bundles")
        else:
            extend_menu_section(
                menu, [self.actionCut, self.actionCopy, self.actionPaste],
                section="handlepaths",
                position=0)
        if node.isfile:
            extend_menu_section(menu,
                                self.actionOpen,
                                section="open",
                                position=0)

        #El final
        extend_menu_section(menu, ["--properties", self.actionProperties],
                            section=-1)

    def extendAddonsItemMenu(self, menu, node):
        #Menu de los addons
        addonMenues = ["-"]
        for addon in self.addons:
            addonMenues.extend(addon.contributeToContextMenu(node))
        if len(addonMenues) > 1:
            extend_menu_section(menu, addonMenues, section='properties')

    def extendProjectBundleItemMenu(self, menu, node):
        #Menu de los bundles relacionados al proyecto
        #Try get all bundles for project bundle definition
        bundles = map(
            lambda uuid: self.application.supportManager.getManagedObject(uuid
                                                                          ),
            node.project().bundleMenu or [])
        #Filter None bundles
        bundles = filter(lambda bundle: bundle is not None, bundles)
        #Sort by name
        bundles = sorted(bundles, key=lambda bundle: bundle.name)
        if bundles:
            bundleMenues = map(
                lambda bundle: self.application.supportManager.menuForBundle(
                    bundle), bundles)
            extend_menu_section(menu,
                                bundleMenues,
                                section="bundles",
                                position=0)

    #================================================
    # Tree View Project
    #================================================
    def showProjectTreeViewContextMenu(self, point):
        index = self.treeViewProjects.indexAt(point)
        if not index.isValid():
            index = self.treeViewProjects.currentIndex()
        self.buildContextMenu(index).popup(
            self.treeViewProjects.mapToGlobal(point))

    def on_treeViewProjects_doubleClicked(self, index):
        self.on_actionOpen_triggered()

    def currentPath(self):
        return self.projectTreeProxyModel.filePath(
            self.treeViewProjects.currentIndex())

    def currentNode(self):
        return self.projectTreeProxyModel.node(
            self.treeViewProjects.currentIndex())

    def currentDirectory(self):
        return self.application.fileManager.directory(self.currentPath())

    #================================================
    # Actions Create, Delete, Rename objects
    #================================================
    @QtCore.pyqtSlot()
    def on_actionNewFile_triggered(self):
        currentDirectory = self.currentDirectory()
        filePath = self.createFile(currentDirectory)
        if filePath is not None:
            self.application.openFile(filePath)
            #TODO: si esta en auto update ver como hacer los refresh
            self.projectTreeProxyModel.refreshPath(currentDirectory)

    @QtCore.pyqtSlot()
    def on_actionNewFromTemplate_triggered(self):
        currentDirectory = self.currentDirectory()
        filePath = self.createFileFromTemplate(currentDirectory)
        if filePath is not None:
            self.application.openFile(filePath)
            #TODO: si esta en auto update ver como hacer los refresh
            self.projectTreeProxyModel.refreshPath(currentDirectory)

    @QtCore.pyqtSlot()
    def on_actionNewFolder_triggered(self):
        currentDirectory = self.currentDirectory()
        dirPath = self.createDirectory(currentDirectory)
        if dirPath is not None:
            #TODO: si esta en auto update ver como hacer los refresh
            self.projectTreeProxyModel.refreshPath(currentDirectory)

    @QtCore.pyqtSlot()
    def on_actionNewProject_triggered(self):
        PMXNewProjectDialog.getNewProject(self)

    @QtCore.pyqtSlot()
    def on_actionDelete_triggered(self):
        currentIndex = self.treeViewProjects.currentIndex()
        treeNode = self.projectTreeProxyModel.node(currentIndex)
        if treeNode.isproject:
            #Es proyecto
            question = CheckableMessageBox.questionFactory(
                self, "Delete project",
                "Are you sure you want to delete project '%s' from the workspace?"
                % treeNode.name,
                "Delete project contents on disk (cannot be undone)",
                QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel,
                QtGui.QMessageBox.Ok)
            question.setDetailedText("Project location:\n%s" % treeNode.path())
            ret = question.exec_()
            if ret == QtGui.QMessageBox.Ok:
                self.application.projectManager.deleteProject(
                    treeNode, removeFiles=question.isChecked())
        else:
            #Es un path
            self.deletePath(treeNode.path())
        self.projectTreeProxyModel.refresh(currentIndex.parent())

    @QtCore.pyqtSlot()
    def on_actionRemove_triggered(self):
        treeNode = self.currentNode()
        if treeNode.isproject:
            ret = QtGui.QMessageBox.question(
                self, "Remove project",
                "Are you sure you want to remove project '%s' from the workspace?"
                % treeNode.name,
                QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel,
                QtGui.QMessageBox.Ok)
            if ret == QtGui.QMessageBox.Ok:
                self.application.projectManager.removeProject(treeNode)

    @QtCore.pyqtSlot()
    def on_actionRename_triggered(self):
        self.renamePath(self.currentPath())
        self.projectTreeProxyModel.refresh(
            self.treeViewProjects.currentIndex())

    @QtCore.pyqtSlot()
    def on_actionCloseProject_triggered(self):
        treeNode = self.currentNode()
        if treeNode.isproject:
            self.application.projectManager.closeProject(treeNode)

    @QtCore.pyqtSlot()
    def on_actionOpenProject_triggered(self):
        treeNode = self.currentNode()
        if treeNode.isproject:
            self.application.projectManager.openProject(treeNode)

    @QtCore.pyqtSlot()
    def on_actionProperties_triggered(self):
        self.propertiesDialog.exec_(self.currentNode())

    @QtCore.pyqtSlot()
    def on_actionRefresh_triggered(self):
        indexes = self.treeViewProjects.selectedIndexes()
        for index in indexes:
            self.projectTreeProxyModel.refresh(index)

    @QtCore.pyqtSlot()
    def on_actionOpen_triggered(self):
        node = self.currentNode()
        if node.isfile:
            self.application.openFile(node.path())

    @QtCore.pyqtSlot()
    def on_actionOpenSystemEditor_triggered(self):
        QtGui.QDesktopServices.openUrl(
            QtCore.QUrl("file://%s" % self.currentPath(),
                        QtCore.QUrl.TolerantMode))

    @QtCore.pyqtSlot()
    def on_pushButtonCollapseAll_pressed(self):
        self.treeViewProjects.collapseAll()

    @QtCore.pyqtSlot(bool)
    def on_pushButtonSync_toggled(self, checked):
        if checked:
            #Conectar señal
            self.mainWindow.currentEditorChanged.connect(
                self.on_mainWindow_currentEditorChanged)
            self.on_mainWindow_currentEditorChanged(
                self.mainWindow.currentEditor())
        else:
            #Desconectar señal
            self.mainWindow.currentEditorChanged.disconnect(
                self.on_mainWindow_currentEditorChanged)

    def on_mainWindow_currentEditorChanged(self, editor):
        if editor is not None and not editor.isNew():
            index = self.projectTreeProxyModel.indexForPath(editor.filePath)
            self.treeViewProjects.setCurrentIndex(index)

    @QtCore.pyqtSlot()
    def on_actionBundleEditor_triggered(self):
        project = self.currentNode()
        if project.namespace is None:
            self.application.supportManager.addProjectNamespace(project)
        self.projectManager.projectMenuProxyModel.setCurrentProject(project)
        self.application.bundleEditor.execEditor(
            namespaceFilter=project.namespace,
            filterText="Menu",
            filterModel=self.projectManager.projectMenuProxyModel)

    def on_actionCopy_triggered(self):
        mimeData = self.projectTreeProxyModel.mimeData(
            self.treeViewProjects.selectedIndexes())
        self.application.clipboard().setMimeData(mimeData)

    def on_actionCut_triggered(self):
        mimeData = self.projectTreeProxyModel.mimeData(
            self.treeViewProjects.selectedIndexes())
        self.application.clipboard().setMimeData(mimeData)

    def on_actionPaste_triggered(self):
        parentPath = self.currentPath()
        mimeData = self.application.clipboard().mimeData()
        if mimeData.hasUrls() and os.path.isdir(parentPath):
            for url in mimeData.urls():
                srcPath = url.toLocalFile()
                dstPath = os.path.join(
                    parentPath, self.application.fileManager.basename(srcPath))
                if os.path.isdir(srcPath):
                    self.application.fileManager.copytree(srcPath, dstPath)
                else:
                    self.application.fileManager.copy(srcPath, dstPath)
            self.projectTreeProxyModel.refresh(
                self.treeViewProjects.currentIndex())

    #================================================
    # Custom filters
    #================================================
    @QtCore.pyqtSlot()
    def on_pushButtonCustomFilters_pressed(self):
        filters, accepted = QtGui.QInputDialog.getText(
            self,
            _("Custom Filter"),
            _("Enter the filters (separated by comma)\nOnly * and ? may be used for custom matching"
              ),
            text=self.customFilters)
        if accepted:
            #Save and set filters
            self.settings.setValue('customFilters', filters)
            self.projectTreeProxyModel.setFilterRegExp(filters)

    #================================================
    # Sort and order Actions
    #================================================
    @QtCore.pyqtSlot()
    def on_actionOrderByName_triggered(self):
        self.projectTreeProxyModel.sortBy(
            "name", self.actionOrderFoldersFirst.isChecked(),
            self.actionOrderDescending.isChecked())

    @QtCore.pyqtSlot()
    def on_actionOrderBySize_triggered(self):
        self.projectTreeProxyModel.sortBy(
            "size", self.actionOrderFoldersFirst.isChecked(),
            self.actionOrderDescending.isChecked())

    @QtCore.pyqtSlot()
    def on_actionOrderByDate_triggered(self):
        self.projectTreeProxyModel.sortBy(
            "date", self.actionOrderFoldersFirst.isChecked(),
            self.actionOrderDescending.isChecked())

    @QtCore.pyqtSlot()
    def on_actionOrderByType_triggered(self):
        self.projectTreeProxyModel.sortBy(
            "type", self.actionOrderFoldersFirst.isChecked(),
            self.actionOrderDescending.isChecked())

    @QtCore.pyqtSlot()
    def on_actionOrderDescending_triggered(self):
        self.projectTreeProxyModel.sortBy(
            self.projectTreeProxyModel.orderBy,
            self.actionOrderFoldersFirst.isChecked(),
            self.actionOrderDescending.isChecked())

    @QtCore.pyqtSlot()
    def on_actionOrderFoldersFirst_triggered(self):
        self.projectTreeProxyModel.sortBy(
            self.projectTreeProxyModel.orderBy,
            self.actionOrderFoldersFirst.isChecked(),
            self.actionOrderDescending.isChecked())

    #================================================
    # Helper actions
    #================================================
    def refresh(self):
        self.on_actionRefresh_triggered()

    def copy(self):
        self.on_actionCopy_triggered()

    def paste(self):
        self.on_actionPaste_triggered()

    def cut(self):
        self.on_actionCut_triggereda()

    def delete(self):
        self.on_actionDelete_triggered()

    def rename(self):
        self.on_actionRefresh_triggered()
Пример #39
0
class ThemeSettingsWidget(QtGui.QWidget, SettingsTreeNode, Ui_FontThemeWidget):
    """Changes font and theme
    """
    DEFAULTS = {
        'settings': {
            'background': '#FFFFFF',
            'caret': '#000000',
            'foreground': '#000000',
            'invisibles': '#BFBFBF',
            'lineHighlight': '#00000012',
            'gutter': '#FFFFFF',
            'gutterForeground': '#000000',
            'lineHighlight': '#00000012',
            'selection': '#A6CBFF'
        },
        #Names and scopes
        'styles':
        [('Comment', 'comment'), ('String', 'string'),
         ('Number', 'constant.numeric'),
         ('Built-in constant', 'constant.language'),
         ('User-defined constant', 'constant.character, constant.other'),
         ('Variable', 'variable.language, variable.other'),
         ('Keyword', 'keyword'), ('Storage', 'storage'),
         ('Class name', 'entity.name.class'),
         ('Inherited class', 'entity.other.inherited-class'),
         ('Function name', 'entity.name.function'),
         ('Function argument', 'variable.parameter'),
         ('Tag name', 'entity.name.tag'),
         ('Tag attribute', 'entity.other.attribute-name'),
         ('Library function', 'support.function'),
         ('Library constant', 'support.constant'),
         ('Library class/type', 'support.type, support.class'),
         ('Library variable', 'support.other.variable'),
         ('Invalid', 'invalid')]
    }

    NAMESPACE = "editor"
    TITLE = "Font and Themes"
    ICON = resources.getIcon("fill-color")

    def __init__(self, settingGroup, parent=None):
        QtGui.QWidget.__init__(self, parent)
        SettingsTreeNode.__init__(self, "theme", settingGroup)
        self.setupUi(self)
        self.setupTableView()
        self.setupPushButton()

    def loadSettings(self):
        currentThemeUUID = self.settingGroup.hasValue(
            'theme') and self.settingGroup.value('theme').upper() or None
        currentTheme = self.application.supportManager.getTheme(
            currentThemeUUID)
        self.tableView.setModel(
            self.application.supportManager.themeStyleProxyModel)
        self.comboBoxThemes.setModel(
            self.application.supportManager.themeListModel)
        if currentTheme is not None:
            self.comboBoxThemes.setCurrentIndex(
                self.comboBoxThemes.model().findIndex(currentTheme))
            self.setThemeSettings(currentTheme, False)

    #==========================================================
    # ComboBoxThemes
    #==========================================================
    @QtCore.pyqtSlot(int)
    def on_comboBoxThemes_activated(self, index):
        theme = self.comboBoxThemes.model().themeForIndex(index)
        self.setThemeSettings(theme)

    #==========================================================
    # TableView
    #==========================================================
    def on_tableView_Activated(self, index):
        style = self.application.supportManager.themeStyleProxyModel.mapToSource(
            index).internalPointer()
        self.comboBoxScope.setEditText(style.scope)

    def on_comboBoxScope_changed(self, string):
        string = unicode(string)
        index = self.tableView.currentIndex()
        if index.isValid():
            style = self.application.supportManager.themeStyleProxyModel.mapToSource(
                index).internalPointer()
            if string != style.scope:
                self.application.supportManager.updateThemeStyle(style,
                                                                 scope=string)

    def setupTableView(self):
        self.tableView.horizontalHeader().setResizeMode(
            QtGui.QHeaderView.ResizeToContents)
        self.tableView.verticalHeader().setResizeMode(
            QtGui.QHeaderView.ResizeToContents)

        self.tableView.activated.connect(self.on_tableView_Activated)
        self.tableView.pressed.connect(self.on_tableView_Activated)
        self.tableView.setItemDelegateForColumn(1, PMXColorDelegate(self))
        self.tableView.setItemDelegateForColumn(2, PMXColorDelegate(self))
        self.tableView.setItemDelegateForColumn(3, PMXFontStyleDelegate(self))
        self.tableView.setEditTriggers(QtGui.QAbstractItemView.AllEditTriggers)

        #Conectar
        for _, scope in self.DEFAULTS['styles']:
            self.comboBoxScope.addItem(scope)
        self.comboBoxScope.currentIndexChanged[str].connect(
            self.on_comboBoxScope_changed)
        self.comboBoxScope.editTextChanged.connect(
            self.on_comboBoxScope_changed)

    #==========================================================
    # Push Button
    #==========================================================
    def setupPushButton(self):
        #Colors
        self.pushButtonForeground.pressed.connect(
            lambda element='foreground': self.on_pushButtonColor_pressed(
                element))
        self.pushButtonBackground.pressed.connect(
            lambda element='background': self.on_pushButtonColor_pressed(
                element))
        self.pushButtonSelection.pressed.connect(
            lambda element='selection': self.on_pushButtonColor_pressed(element
                                                                        ))
        self.pushButtonInvisibles.pressed.connect(
            lambda element='invisibles': self.on_pushButtonColor_pressed(
                element))
        self.pushButtonLineHighlight.pressed.connect(
            lambda element='lineHighlight': self.on_pushButtonColor_pressed(
                element))
        self.pushButtonCaret.pressed.connect(
            lambda element='caret': self.on_pushButtonColor_pressed(element))
        self.pushButtonGutter.pressed.connect(
            lambda element='gutter': self.on_pushButtonColor_pressed(element))
        #Font
        font = self.settingGroup.value('font')
        if font is not None:
            self.lineFont.setFont(font)
            self.lineFont.setText("%s, %d" % (font.family(), font.pointSize()))

    @QtCore.pyqtSignature('')
    def on_pushButtonChangeFont_pressed(self):
        font = self.settingGroup.value('font')
        font, ok = QtGui.QFontDialog.getFont(font, self,
                                             _("Select editor font"))
        if ok:
            self.settingGroup.setValue('font', font)
            self.lineFont.setFont(font)
            self.lineFont.setText("%s, %d" % (font.family(), font.pointSize()))

    @QtCore.pyqtSignature('')
    def on_pushButtonAdd_pressed(self):
        theme = self.comboBoxThemes.model().themeForIndex(
            self.comboBoxThemes.currentIndex())
        style = self.application.supportManager.createThemeStyle(
            'untitled', unicode(self.comboBoxScope.currentText()), theme)

    @QtCore.pyqtSignature('')
    def on_pushButtonRemove_pressed(self):
        index = self.tableView.currentIndex()
        if index.isValid():
            style = self.application.supportManager.themeStyleProxyModel.mapToSource(
                index).internalPointer()
            self.application.supportManager.deleteThemeStyle(style)

    def on_pushButtonColor_pressed(self, element):
        theme = self.comboBoxThemes.model().themeForIndex(
            self.comboBoxThemes.currentIndex())
        settings = theme.settings
        color, ok = QtGui.QColorDialog.getRgba(settings[element].rgba(), self)
        if ok:
            self.application.supportManager.updateTheme(
                theme, settings={element: color})
            self.setThemeSettings(theme)

    def setThemeSettings(self, theme, changeSettings=True):
        settings = theme.settings
        self.pushButtonForeground.setStyleSheet(
            "background-color: " + color2rgba(settings['foreground'])[:7])
        self.pushButtonBackground.setStyleSheet(
            "background-color: " + color2rgba(settings['background'])[:7])
        self.pushButtonSelection.setStyleSheet(
            "background-color: " + color2rgba(settings['selection'])[:7])
        self.pushButtonInvisibles.setStyleSheet(
            "background-color: " + color2rgba(settings['invisibles'])[:7])
        self.pushButtonLineHighlight.setStyleSheet(
            "background-color: " + color2rgba(settings['lineHighlight'])[:7])
        self.pushButtonCaret.setStyleSheet("background-color: " +
                                           color2rgba(settings['caret'])[:7])
        if 'gutter' in settings:
            #Not all themes has the gutter color
            self.pushButtonGutter.setStyleSheet(
                "background-color: " + color2rgba(settings['gutter'])[:7])
        self.application.supportManager.themeStyleProxyModel.setFilterRegExp(
            unicode(theme.uuid))

        #Set color for table view
        tableStyle = """QTableView {background-color: %s;
        color: %s;
        selection-background-color: %s; }""" % (settings['background'].name(),
                                                settings['foreground'].name(),
                                                settings['selection'].name())
        self.tableView.setStyleSheet(tableStyle)

        if changeSettings:
            self.settingGroup.setValue('theme', unicode(theme.uuid).upper())
            message = "<b>%s</b> theme set " % theme.name
            if theme.author is not None:
                message += "<i>(by %s)</i>" % theme.author
            self.application.showMessage(message)
Пример #40
0
 def icon(self):
     return resources.getIcon(self.path())
Пример #41
0
 def icon(self):
     return resources.getIcon("bundle-item-%s" % self.TYPE)
Пример #42
0
    def mousePressEvent(self, e):
        """ Reimplemented to handle mouse press events. """
        if e.button() == QtCore.Qt.RightButton:
            widget = self.widgetAtPos(e.pos())
            tabWidget = self.parent()
            tabSplitter = tabWidget.parent()
            tabMenu = { 
                "title": "Tab Menu",
                "items": [
                    {   "title": "Close",
                        "icon": resources.getIcon("close"),
                        "callback": partial(tabWidget._close_widget, widget) 
                    },
                    {   "title": "Close All",
                        "icon": resources.getIcon("closeall"),
                        "callback": tabSplitter.closeAll
                    },
                    {   "title": "Close Other",
                        "callback": partial(tabSplitter.closeAllExceptWidget, widget)
                    }
                ]
            }

            if self.parent().count() > 1:
                tabMenu["items"].append("-")
                tabMenu["items"].append({
                    "title": "Split Horizontally"                
                })
                tabMenu["items"].append({
                    "title": "Split Vertically"                
                })
            tabMenu["items"].append("-")
            # Create custom menu (
            tabMenu["items"].extend(widget.contributeToTabMenu())
            
            menu, actions = utils.createQMenu(tabMenu, self, connectActions = True)
            
            # Display menu
            menu.exec_(e.globalPos())
        elif e.button() == QtCore.Qt.LeftButton:

            # There is something odd in the focus handling where focus temporarily
            # moves elsewhere (actually to a View) when switching to a different
            # tab page.  We suppress the notification so that the workbench doesn't
            # temporarily make the View active.
            self._root._repeat_focus_changes = False
            QtGui.QTabBar.mousePressEvent(self, e)
            self._root._repeat_focus_changes = True
    
            # Update the current tab.
            self._root._set_current_tab(self.parent(), self.currentIndex())
            self._root._set_focus()
    
            if e.button() != QtCore.Qt.LeftButton:
                return
    
            if self._drag_state is not None:
                return
    
            # Potentially start dragging if the tab under the mouse is the current
            # one (which will eliminate disabled tabs).
            tab = self._tab_at(e.pos())
    
            if tab < 0 or tab != self.currentIndex():
                return
    
            self._drag_state = _DragState(self._root, self, tab, e.pos())
Пример #43
0
 def getIcon(self, index, default = None):
     if index in self.resources:
         return QtGui.QIcon(self.resources[index])
     return resources.getIcon(index)
Пример #44
0
class PMXFileSystemDock(QtGui.QDockWidget, Ui_FileSystemDock,
                        PMXFileSystemTasks, PMXBaseDock):
    SHORTCUT = "Shift+F8"
    ICON = resources.getIcon("system-file-manager")
    PREFERED_AREA = QtCore.Qt.LeftDockWidgetArea

    #=======================================================================
    # Settings
    #=======================================================================
    SETTINGS_GROUP = 'FileSystem'

    @pmxConfigPorperty(default='')
    def customFilters(self, filters):
        self.fileSystemProxyModel.setFilterRegExp(filters)

    _pushButtonHistoryBack = []
    _pushButtonHistoryForward = []

    def __init__(self, parent=None):
        QtGui.QDockWidget.__init__(self, parent)
        PMXBaseDock.__init__(self)
        self.setupUi(self)

        self.fileManager = self.application.fileManager

        #File System model
        self.fileSystemModel = QtGui.QFileSystemModel(self)
        self.fileSystemModel.setFilter(
            QtCore.QDir.NoDotAndDotDot | QtCore.QDir.AllEntries
        )  #http://doc.qt.nokia.com/latest/qdir.html#Filter-enum
        self.fileSystemModel.setRootPath(QtCore.QDir.rootPath())

        #Proxy para el file system tree view
        self.fileSystemProxyModel = SortFilterFileSystemProxyModel(self)
        self.fileSystemProxyModel.setSourceModel(self.fileSystemModel)

        self.setupComboBoxLocation()
        self.setupTreeViewFileSystem()

        self.treeViewFileSystem.installEventFilter(self)
        self.comboBoxLocation.installEventFilter(self)

        self.setupButtons()

    def initialize(self, mainWindow):
        PMXBaseDock.initialize(self, mainWindow)
        mainWindow.fileSystem = self

    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.KeyPress:
            if obj == self.comboBoxLocation:
                if event.key() == QtCore.Qt.Key_Return:
                    text = self.comboBoxLocation.lineEdit().text()
                    self.on_comboBoxLocation_currentIndexChanged(text)
                    return True
            elif obj == self.treeViewFileSystem:
                if event.key() == QtCore.Qt.Key_Backspace:
                    self.pushButtonUp.click()
                    return True
                elif event.key() == QtCore.Qt.Key_Return:
                    path = self.currentPath()
                    if os.path.isdir(path):
                        self.setPathAsRoot(path)
                        return True
                    elif os.path.isfile(path):
                        self.application.openFile(path)
                        return True

                if event.key() == QtCore.Qt.Key_F and event.modifiers(
                ) == QtCore.Qt.ControlModifier:
                    # FIXME: Get Ctrl + F before editor's find, all the foucs is belong to us right now :P
                    self.pushButtonCustomFilters.click()
                    return True
        return QtGui.QDockWidget.eventFilter(self, obj, event)

    def setupComboBoxLocation(self):
        #Combo Dir Model
        self.comboDirModel = QtGui.QDirModel(self)
        self.comboTreeView = QtGui.QTreeView(self)
        self.comboTreeView.setModel(self.comboDirModel)
        self.comboBoxLocation.setView(self.comboTreeView)
        self.comboBoxLocation.setModel(self.comboDirModel)
        #self.comboBoxLocation.setModelColumn(1)
        pIndex = self.treeViewFileSystem.rootIndex()
        rootPath = self.fileSystemProxyModel.filePath(pIndex)
        comboIndex = self.comboBoxLocation.model().index(rootPath)
        #self.comboBoxLocation.setRootModelIndex(comboIndex)
        self.comboBoxLocation.setCurrentIndex(comboIndex.row())

    def setupButtons(self):
        self.pushButtonSync.setCheckable(True)
        self.pushButtonBack.setEnabled(False)
        self.pushButtonFoward.setEnabled(False)

    def setupTreeViewFileSystem(self):
        self.treeViewFileSystem.setModel(self.fileSystemProxyModel)

        #self.treeViewFileSystem.setHeaderHidden(True)
        #self.treeViewFileSystem.setUniformRowHeights(False)

        #Setup Context Menu
        contextMenu = {
            "title":
            "File System",
            "items": [
                {
                    "text":
                    "New",
                    "items": [
                        self.actionNewFolder, self.actionNewFile,
                        self.actionNewFromTemplate
                    ]
                },
                "-",
                self.actionOpen,
                {
                    "text":
                    "Open With",
                    "items": [
                        self.actionOpenDefaultEditor,
                        self.actionOpenSystemEditor
                    ]
                },
                self.actionSetInTerminal,
                "-",
                self.actionRename,
                self.actionCut,
                self.actionCopy,
                self.actionPaste,
                self.actionDelete,
            ]
        }
        self.fileSystemMenu, self.fileSystemMenuActions = create_menu(
            self, contextMenu)

        #Setup Context Menu
        optionsMenu = {
            "title":
            "File System Options",
            "items": [{
                "text":
                "Order",
                "items":
                [(self.actionOrderByName, self.actionOrderBySize,
                  self.actionOrderByDate, self.actionOrderByType), "-",
                 self.actionOrderDescending, self.actionOrderFoldersFirst]
            }]
        }

        self.actionOrderFoldersFirst.setChecked(True)
        self.actionOrderByName.trigger()

        self.fileSystemOptionsMenu, _ = create_menu(self, optionsMenu)
        self.pushButtonOptions.setMenu(self.fileSystemOptionsMenu)

        #Connect context menu
        self.treeViewFileSystem.setContextMenuPolicy(
            QtCore.Qt.CustomContextMenu)
        self.treeViewFileSystem.customContextMenuRequested.connect(
            self.showTreeViewFileSystemContextMenu)

        #=======================================================================
        # Drag and Drop (see the proxy model)
        #=======================================================================
        self.treeViewFileSystem.setDragEnabled(True)
        self.treeViewFileSystem.setAcceptDrops(True)
        self.treeViewFileSystem.setDefaultDropAction(QtCore.Qt.MoveAction)
        self.treeViewFileSystem.setDropIndicatorShown(True)

        self.treeViewFileSystem.setAlternatingRowColors(True)
        self.treeViewFileSystem.setAnimated(True)

    @QtCore.pyqtSlot(str)
    def on_comboBoxLocation_currentIndexChanged(self, text):
        path = self.fileManager.expandVars(text)
        #TODO: Mostrar un error cuando sea None
        if path is not None:
            path = self.fileManager.normpath(path)
            self.setPathAsRoot(path)

    @QtCore.pyqtSlot()
    def on_pushButtonUp_pressed(self):
        index = self.treeViewFileSystem.rootIndex()
        sIndex = self.fileSystemProxyModel.mapToSource(index)
        dir = QtCore.QDir(self.fileSystemModel.filePath(sIndex))
        if dir.cdUp():
            self.setPathAsRoot(dir.path())
            self.comboBoxLocation.lineEdit().setText(dir.path())

    def addPathToFavourites(self, path):
        """
        Adds an entry to the File Manager 
        @param path: Adds parameter to path
        """
        if os.path.isdir(unicode(path)):
            root, dirname_part = path.rsplit(os.sep, 1)
            self.comboFavourites.addItem(dirname_part, {
                'path': path,
                'icon': QtGui.QIcon()
            })
        else:
            self.logger.debug("Not a directory %s" % path)

    #================================================
    # Tree View File System
    #================================================
    def showTreeViewFileSystemContextMenu(self, point):
        self.fileSystemMenu.popup(self.treeViewFileSystem.mapToGlobal(point))

    def on_treeViewFileSystem_doubleClicked(self, index):
        path = self.currentPath()
        if os.path.isfile(path):
            self.application.openFile(path)
        elif os.path.isdir(path):
            self.setPathAsRoot(path)

    #===========================================================================
    # Insted of using indexes, it's easier for history handling
    # to manage paths
    #===========================================================================
    def currentPath(self):
        return self.fileSystemProxyModel.filePath(
            self.treeViewFileSystem.currentIndex())

    def currentRootPath(self):
        ''' Returns current root path '''
        proxyIndex = self.treeViewFileSystem.rootIndex()
        return self.fileSystemModel.filePath(
            self.fileSystemProxyModel.mapToSource(proxyIndex))

    def setPathAsRoot(self, path, trackHistory=True):
        assert os.path.isdir(path), _("{0} is not a valid directory!").format(
            path)

        #Set del treeViewFileSystem
        oldPath = self.currentRootPath()
        sourceIndex = self.fileSystemModel.index(path)
        proxyIndex = self.fileSystemProxyModel.mapFromSource(sourceIndex)
        self.treeViewFileSystem.setRootIndex(proxyIndex)

        #Set del comboBoxLocation
        comboIndex = self.comboBoxLocation.model().index(path)
        #self.comboBoxLocation.setRootModelIndex(comboIndex)
        self.comboBoxLocation.setCurrentIndex(comboIndex.row())
        self.comboBoxLocation.lineEdit().setText(
            self.fileManager.normpath(path))

        #Store history
        if trackHistory and os.path.isdir(oldPath):
            self._pushButtonHistoryBack.append(oldPath)
            self.pushButtonBack.setEnabled(True)
            self._pushButtonHistoryForward = []
            self.pushButtonFoward.setEnabled(False)

    def on_pushButtonBack_pressed(self):
        if os.path.exists(self.currentPath()):
            self._pushButtonHistoryForward.append(self.currentPath())
            self.pushButtonFoward.setEnabled(True)
        destination = self._pushButtonHistoryBack.pop()
        self.pushButtonBack.setEnabled(bool(self._pushButtonHistoryBack))
        self.setPathAsRoot(destination, trackHistory=False)

    def on_pushButtonFoward_pressed(self):
        self._pushButtonHistoryBack.append(self.currentRootPath())
        self.pushButtonBack.setEnabled(True)
        destination = self._pushButtonHistoryForward.pop()
        self.setPathAsRoot(destination, trackHistory=False)
        if not len(self._pushButtonHistoryForward):
            self.pushButtonFoward.setEnabled(False)

    #================================================
    # Actions cut, copy, paste
    #================================================
    def on_actionCut_triggered(self):
        pass

    def on_actionCopy_triggered(self):
        mimeData = self.fileSystemProxyModel.mimeData(
            [self.treeViewFileSystem.currentIndex()])
        self.application.clipboard().setMimeData(mimeData)

    def on_actionPaste_triggered(self):
        parentPath = self.currentPath()
        mimeData = self.application.clipboard().mimeData()
        if mimeData.hasUrls() and os.path.isdir(parentPath):
            for url in mimeData.urls():
                srcPath = url.toLocalFile()
                dstPath = os.path.join(
                    parentPath, self.application.fileManager.basename(srcPath))
                if os.path.isdir(srcPath):
                    self.application.fileManager.copytree(srcPath, dstPath)
                else:
                    self.application.fileManager.copy(srcPath, dstPath)

    #================================================
    # Actions Create and Delete objects
    #================================================
    @QtCore.pyqtSlot()
    def on_actionNewFolder_triggered(self):
        basePath = self.currentPath()
        self.createDirectory(basePath)

    @QtCore.pyqtSlot()
    def on_actionNewFile_triggered(self):
        basePath = self.currentPath()
        self.createFile(basePath)

    @QtCore.pyqtSlot()
    def on_actionNewFromTemplate_triggered(self):
        basePath = self.currentPath()
        self.createFileFromTemplate(basePath)

    @QtCore.pyqtSlot()
    def on_actionDelete_triggered(self):
        basePath = self.currentPath()
        self.deletePath(basePath)

    @QtCore.pyqtSlot()
    def on_actionRename_triggered(self):
        basePath = self.currentPath()
        self.renamePath(basePath)

    #======================================================
    # Tree View Context Menu Actions
    # Some of them are in fstask's PMXFileSystemTasks mixin
    #======================================================
    def pathToClipboard(self, checked=False):
        basePath = self.currentPath()
        QtGui.QApplication.clipboard().setText(basePath)

    @QtCore.pyqtSlot()
    def on_actionOpen_triggered(self):
        path = self.fileSystemProxyModel.filePath(
            self.treeViewFileSystem.currentIndex())
        if os.path.isfile(path):
            self.application.openFile(path)

    @QtCore.pyqtSlot()
    def on_actionOpenSystemEditor_triggered(self):
        path = self.fileSystemProxyModel.filePath(
            self.treeViewFileSystem.currentIndex())
        QtGui.QDesktopServices.openUrl(
            QtCore.QUrl("file://%s" % path, QtCore.QUrl.TolerantMode))

    @QtCore.pyqtSlot()
    def on_actionOpenDefaultEditor_triggered(self):
        path = self.fileSystemProxyModel.filePath(
            self.treeViewFileSystem.currentIndex())
        if os.path.isfile(path):
            self.application.openFile(path)

    #================================================
    # Custom filters
    #================================================
    @QtCore.pyqtSlot()
    def on_pushButtonCustomFilters_pressed(self):
        filters, accepted = QtGui.QInputDialog.getText(
            self,
            _("Custom Filter"),
            _("Enter the filters (separated by comma)\nOnly * and ? may be used for custom matching"
              ),
            text=self.customFilters)
        if accepted:
            #Save and set filters
            self.settings.setValue('customFilters', filters)
            self.fileSystemProxyModel.setFilterRegExp(filters)

    @QtCore.pyqtSlot()
    def on_pushButtonCollapseAll_pressed(self):
        self.treeViewFileSystem.collapseAll()

    @QtCore.pyqtSlot(bool)
    def on_pushButtonSync_toggled(self, checked):
        if checked:
            #Conectar señal
            self.mainWindow.currentEditorChanged.connect(
                self.on_mainWindow_currentEditorChanged)
            self.on_mainWindow_currentEditorChanged(
                self.mainWindow.currentEditor())
        else:
            #Desconectar señal
            self.mainWindow.currentEditorChanged.disconnect(
                self.on_mainWindow_currentEditorChanged)

    @QtCore.pyqtSlot()
    def on_actionSetInTerminal_triggered(self):
        path = self.currentPath()
        directory = self.application.fileManager.getDirectory(path)
        self.mainWindow.terminal.chdir(directory)

    #================================================
    # Sort and order Actions
    #================================================
    @QtCore.pyqtSlot()
    def on_actionOrderByName_triggered(self):
        self.fileSystemProxyModel.sortBy(
            "name", self.actionOrderFoldersFirst.isChecked(),
            self.actionOrderDescending.isChecked())

    @QtCore.pyqtSlot()
    def on_actionOrderBySize_triggered(self):
        self.fileSystemProxyModel.sortBy(
            "size", self.actionOrderFoldersFirst.isChecked(),
            self.actionOrderDescending.isChecked())

    @QtCore.pyqtSlot()
    def on_actionOrderByDate_triggered(self):
        self.fileSystemProxyModel.sortBy(
            "date", self.actionOrderFoldersFirst.isChecked(),
            self.actionOrderDescending.isChecked())

    @QtCore.pyqtSlot()
    def on_actionOrderByType_triggered(self):
        self.fileSystemProxyModel.sortBy(
            "type", self.actionOrderFoldersFirst.isChecked(),
            self.actionOrderDescending.isChecked())

    @QtCore.pyqtSlot()
    def on_actionOrderDescending_triggered(self):
        self.fileSystemProxyModel.sortBy(
            self.fileSystemProxyModel.orderBy,
            self.actionOrderFoldersFirst.isChecked(),
            self.actionOrderDescending.isChecked())

    @QtCore.pyqtSlot()
    def on_actionOrderFoldersFirst_triggered(self):
        self.fileSystemProxyModel.sortBy(
            self.fileSystemProxyModel.orderBy,
            self.actionOrderFoldersFirst.isChecked(),
            self.actionOrderDescending.isChecked())

    @QtCore.pyqtSlot()
    def on_actionConvertIntoProject_triggered(self):
        _base, name = os.path.split(self.currentPath())
        PMXNewProjectDialog.getNewProject(self, self.currentPath(), name)

    def on_mainWindow_currentEditorChanged(self, editor):
        if editor is not None and not editor.isNew():
            index = self.fileSystemModel.index(editor.filePath)
            proxyIndex = self.fileSystemProxyModel.mapFromSource(index)
            self.treeViewFileSystem.setCurrentIndex(proxyIndex)
Пример #45
0
 def icon(self):
     if self.manager.isOpen(self):
         return resources.getIcon("projectopen")
     else:
         return resources.getIcon("projectclose")
Пример #46
0
 def icon(self):
     return resources.getIcon("bundle-item-%s" % self.TYPE)
Пример #47
0
class PMXProcessDock(QtGui.QDockWidget, PMXBaseDock):
    SHORTCUT = "F7"
    ICON = resources.getIcon("application-x-executable-script")
    PREFERED_AREA = QtCore.Qt.RightDockWidgetArea
    
    def __init__(self, parent):
        QtGui.QDockWidget.__init__(self, parent)
        self.setWindowTitle(_("External process"))
        self.setObjectName(_("ExternalProcessDock"))
        PMXBaseDock.__init__(self)
        self.processTableModel = self.application.supportManager.processTableModel
        self.tableViewProcess = QtGui.QTableView()
        self.tableViewProcess.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
        self.tableViewProcess.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self.tableViewProcess.setShowGrid(False)
        self.tableViewProcess.horizontalHeader().setVisible(False)
        self.tableViewProcess.verticalHeader().setVisible(False)
        self.tableViewProcess.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)
        self.tableViewProcess.verticalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)
        self.tableViewProcess.activated.connect(self.on_tableViewProcess_activated)
        self.tableViewProcess.doubleClicked.connect(self.on_tableViewProcess_doubleClicked)
        self.tableViewProcess.setModel(self.processTableModel)
        self.setWidget(self.tableViewProcess)

        #Setup Context Menu
        contextMenu = { 
            "text": "Process",
            "items": [ 
                { "text": "Close",
                  "callback": self.on_actionCloseProcess_triggered },
                { "text": "Kill",
                  "callback": self.on_actionKill_triggered },
                { "text": "Terminate",
                  "callback": self.on_actionTerminate_triggered },
                "-",
                { "text": "Send Signal",
                  "items": map(lambda (key, value):
                        { "text": "%s (%s)" % (key, value),
                          "callback": lambda _, signal = value: self.on_actionSendSignal_triggered(signal)
                        }, sorted(SIGNALS.iteritems(), key = lambda (k, v): v))
                }
            ]
        }
        self.processMenu, self.processMenuActions = create_menu(self, contextMenu)

        for action in self.processMenuActions:
            if hasattr(action, "callback"):
                action.triggered.connect(action.callback)
        
        self.tableViewProcess.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.tableViewProcess.customContextMenuRequested.connect(self.showtableViewProcessContextMenu)
        
    def showtableViewProcessContextMenu(self, point):
        index = self.tableViewProcess.indexAt(point)
        if index.isValid():
            self.processMenu.popup(self.tableViewProcess.mapToGlobal(point))
        
    def currentProcess(self):
        index = self.tableViewProcess.currentIndex()
        return self.processTableModel.processForIndex(index)

    def on_actionCloseProcess_triggered(self):
        """docstring for on_actionCloseProcess_triggered"""
        self.currentProcess().close()
    
    def on_actionKill_triggered(self):
        self.currentProcess().kill()
        
    def on_actionSendSignal_triggered(self, signal):
        os.kill(self.currentProcess().pid(), signal)
        
    def on_actionTerminate_triggered(self):
        self.currentProcess().terminate()
        
    def on_tableViewProcess_activated(self, index):
        self.currentProcess().terminate()
    
    def on_tableViewProcess_doubleClicked(self, index):
        self.currentProcess().terminate()
Пример #48
0
class PMXEnvVariablesWidget(QtGui.QWidget, SettingsTreeNode, Ui_Environment):
    """Environment variables
    """
    NAMESPACE = "general"
    TITLE = "Enviroment Variables"
    ICON = resources.getIcon("code-variable")

    def __init__(self, settingGroup, parent=None):
        QtGui.QWidget.__init__(self, parent)
        SettingsTreeNode.__init__(self, "environment", settingGroup)
        self.setupUi(self)
        self.setupVariablesTableModel()

    def loadSettings(self):
        self.model.addGroup('user',
                            self.application.supportManager.shellVariables,
                            editable=True,
                            checkable=True,
                            foreground=QtCore.Qt.blue)
        self.model.addGroup('prymatex',
                            self.application.supportManager.environment)
        self.model.addGroup('system',
                            os.environ,
                            foreground=QtCore.Qt.red,
                            visible=False)

    def setupVariablesTableModel(self):
        self.model = EnvironmentTableModel(self)
        self.model.variablesChanged.connect(
            self.on_variablesModel_userVariablesChanged)
        self.tableView.setModel(self.model)

        self.tableView.horizontalHeader().setResizeMode(
            QtGui.QHeaderView.Stretch)
        self.tableView.horizontalHeader().setResizeMode(
            QtGui.QHeaderView.ResizeToContents)
        self.tableView.verticalHeader().setResizeMode(
            QtGui.QHeaderView.ResizeToContents)
        self.model.rowsInserted.connect(self.tableView.resizeRowsToContents)
        self.model.rowsRemoved.connect(self.tableView.resizeRowsToContents)
        self.tableView.resizeRowsToContents()

        self.checkBox1.setText("User")
        self.checkBox1.setChecked(True)
        self.checkBox2.setText("Prymatex")
        self.checkBox2.setChecked(True)
        self.checkBox3.setText("System")

    @QtCore.pyqtSlot(bool)
    def on_checkBox1_clicked(self, checked):
        self.model.setVisibility('user', checked)

    @QtCore.pyqtSlot(bool)
    def on_checkBox2_clicked(self, checked):
        self.model.setVisibility('prymatex', checked)

    @QtCore.pyqtSlot(bool)
    def on_checkBox3_clicked(self, checked):
        self.model.setVisibility('system', checked)

    def on_variablesModel_userVariablesChanged(self, group, variables):
        self.settingGroup.setValue('shellVariables', variables)

    def on_pushAdd_pressed(self):
        self.model.insertVariable()

    def on_pushRemove_pressed(self):
        index = self.tableView.currentIndex()
        self.model.removeRows(index.row(), 1)