Exemple #1
0
    def __init__(self, parent):
        QtGui.QWidget.__init__(self, parent)

        # Create tool button
        self._up = QtGui.QToolButton(self)
        style = QtGui.qApp.style()
        self._up.setIcon(style.standardIcon(style.SP_ArrowLeft))
        self._up.setIconSize(QtCore.QSize(16, 16))

        # Create "path" line edit
        self._line = QtGui.QLineEdit(self)
        self._line.setReadOnly(True)
        self._line.setStyleSheet("QLineEdit { background:#ddd; }")
        self._line.setFocusPolicy(QtCore.Qt.NoFocus)

        # Create tree
        self._tree = WorkspaceTree(self)

        # Set layout
        layout = QtGui.QHBoxLayout()
        layout.addWidget(self._up, 0)
        layout.addWidget(self._line, 1)
        #
        mainLayout = QtGui.QVBoxLayout(self)
        mainLayout.addLayout(layout, 0)
        mainLayout.addWidget(self._tree, 1)
        mainLayout.setSpacing(2)
        self.setLayout(mainLayout)

        # Bind up event
        self._up.pressed.connect(self._tree._proxy.goUp)
Exemple #2
0
 def SetItems(parentItem, fictiveObjects, level):
     level += 1
     for object in fictiveObjects:
         type = object.type
         if not type in showTypes:
             continue
         # Construct text
         if type=='cell':
             type = '##'
         elif type=='attribute':
             type = 'attr'
         #
         if type == 'import':                   
             text = "%s (%s)" % (object.name, object.text)
         elif type=='todo':
             text = object.name
         else:
             text = "%s %s" % (type, object.name)
         # Create item
         thisItem = QtGui.QTreeWidgetItem(parentItem, [text])
         color = QtGui.QColor(colours[object.type])
         thisItem.setForeground(0, QtGui.QBrush(color))
         font = thisItem.font(0)
         font.setBold(True)
         thisItem.setFont(0, font)
         thisItem.linenr = object.linenr
         # Is this the current item?
         if ln and object.linenr <= ln and object.linenr2 > ln:
             selectedItem[0] = thisItem 
         # Any children that we should display?
         if object.children:
             SetItems(thisItem, object.children, level)
         # Set visibility 
         thisItem.setExpanded( bool(level < showLevel) )
Exemple #3
0
    def __init__(self, parent, i):
        QtGui.QWizardPage.__init__(self, parent)
        self._i = i

        # Create label for description
        self._text_label = QtGui.QLabel(self)
        self._text_label.setTextFormat(QtCore.Qt.RichText)
        self._text_label.setWordWrap(True)

        # Create label for image
        self._comicLabel = QtGui.QLabel(self)
        pm = QtGui.QPixmap()
        if 'logo' in self._image_filename:
            pm.load(
                os.path.join(iep.iepDir, 'resources', 'appicons',
                             self._image_filename))
        elif self._image_filename:
            pm.load(
                os.path.join(iep.iepDir, 'resources', 'images',
                             self._image_filename))
        self._comicLabel.setPixmap(pm)
        self._comicLabel.setAlignment(QtCore.Qt.AlignHCenter
                                      | QtCore.Qt.AlignVCenter)

        # Layout
        theLayout = QtGui.QVBoxLayout(self)
        self.setLayout(theLayout)
        #
        theLayout.addWidget(self._text_label)
        theLayout.addStretch()
        theLayout.addWidget(self._comicLabel)
        theLayout.addStretch()
Exemple #4
0
 def __init__(self, parent):
     QtGui.QWidget.__init__(self, parent)
     
     # create toolbar
     self._toolbar = QtGui.QToolBar(self)
     self._toolbar.setMaximumHeight(25)
     self._toolbar.setIconSize(QtCore.QSize(16,16))
     
     # create stack
     self._stack = QtGui.QStackedWidget(self)
     
     # Populate toolbar
     self._shellButton = ShellControl(self._toolbar, self._stack)
     self._dbc = DebugControl(self._toolbar)
     #
     self._toolbar.addWidget(self._shellButton)
     self._toolbar.addSeparator()
     # self._toolbar.addWidget(self._dbc) -> delayed, see addContextMenu()
     
     # widget layout
     layout = QtGui.QVBoxLayout()
     layout.setSpacing(0)
     layout.setContentsMargins(0, 0, 0, 0)
     layout.addWidget(self._toolbar)
     layout.addWidget(self._stack)
     self.setLayout(layout)
     
     # make callbacks
     self._stack.currentChanged.connect(self.onCurrentChanged)
Exemple #5
0
 def setPenColor(self, color):
     """ setPenColor(color)
     Set the color of the pen. Color can be anything that can be passed to
     Qcolor().
     """
     pen = QtGui.QPen()
     if isinstance(color, tuple):
         pen.setColor(QtGui.QColor(*color))
     else:
         pen.setColor(QtGui.QColor(color))
     self._painter.setPen(pen)
Exemple #6
0
    def __init__(self, parent):
        QtGui.QWizard.__init__(self, parent)

        # Set some appearance stuff
        self.setMinimumSize(600, 500)
        self.setWindowTitle(translate('wizard', 'Getting started with IEP'))
        self.setWizardStyle(self.ModernStyle)
        self.setButtonText(self.CancelButton, 'Stop')

        # Set logo
        pm = QtGui.QPixmap()
        pm.load(
            os.path.join(iep.iepDir, 'resources', 'appicons', 'ieplogo48.png'))
        self.setPixmap(self.LogoPixmap, pm)

        # Define pages
        klasses = [
            IntroWizardPage, TwocomponentsWizardPage, EditorWizardPage,
            ShellWizardPage1, ShellWizardPage2, RuncodeWizardPage1,
            RuncodeWizardPage2, ToolsWizardPage1, ToolsWizardPage2, FinalPage
        ]

        # Create pages
        self._n = len(klasses)
        for i, klass in enumerate(klasses):
            self.addPage(klass(self, i))
Exemple #7
0
    def __init__(self, parent):
        QtGui.QTreeWidget.__init__(self, parent)

        # Set header stuff
        self.setHeaderHidden(False)
        self.setColumnCount(3)
        self.setHeaderLabels(['Name', 'Type', 'Repr'])
        #self.setColumnWidth(0, 100)
        self.setSortingEnabled(True)

        # Nice rows
        self.setAlternatingRowColors(True)
        self.setRootIsDecorated(False)

        # Create proxy
        self._proxy = WorkspaceProxy()
        self._proxy.haveNewData.connect(self.fillWorkspace)

        # For menu
        self.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
        self._menu = QtGui.QMenu()
        self._menu.triggered.connect(self.contextMenuTriggered)

        # Bind to events
        self.itemActivated.connect(self.onItemExpand)
Exemple #8
0
    def fillWorkspace(self):
        """ fillWorkspace()
        Update the workspace tree.
        """

        # Clear first
        self.clear()

        # Set name
        line = self.parent()._line
        line.setText(self._proxy._name)

        # Add elements
        for des in self._proxy._variables:

            # Get parts
            parts = des.split(',', 4)
            if len(parts) < 4:
                continue

            # Pop the 'kind' element
            kind = parts.pop(2)

            # Create item
            item = QtGui.QTreeWidgetItem(parts, 0)
            self.addTopLevelItem(item)

            # Set tooltip
            tt = '%s: %s' % (parts[0], parts[-1])
            item.setToolTip(0, tt)
            item.setToolTip(1, tt)
            item.setToolTip(2, tt)
Exemple #9
0
    def __init__(self, projectManager, *args, **kwds):
        QtGui.QDialog.__init__(self, *args, **kwds)

        # Set size and title
        size = 540, 300
        self.setMinimumSize(*size)
        self.setWindowTitle(iep.translate('Projects', 'Manage projects'))

        # Create widgets and layout
        self._createWidgets()

        # Store project manager and attach model for the list of projects
        self._projectManager = projectManager
        self._projectsModel = projectManager.projectsModel
        self._activeProject = None
        self.lstProjects.setModel(self._projectsModel)

        # Workaround for PySide bug 1041
        #  - QAbstractItemModel has wrong ownership policy for selectionModel()
        # Instantiate a new selectionModel in Python so Python retains ownerships
        self.lstProjects.setSelectionModel(
            QtGui.QItemSelectionModel(self.lstProjects.model()))

        # Signals
        self.btnAdd.clicked.connect(self.addProject)
        self.btnRemove.clicked.connect(self.removeProject)
        self.btnDone.clicked.connect(self.close)
        self.txtDescription.editingFinished.connect(self.onDescriptionChanged)
        self.chkAddToPath.stateChanged.connect(self.onAddToPathChanged)
        self.lstProjects.selectionModel().currentChanged.connect(
            self.onProjectChanged)
        # Update description label when project name is changed
        self.lstProjects.model().dataChanged.connect(
            lambda i1, i2: self.txtDescription.setText(self._activeProject.name
                                                       ))
Exemple #10
0
def loadIcons():
    """ loadIcons()
    Load all icons in the icon dir.
    """
    # Get directory containing the icons
    iconDir = os.path.join(iep.iepDir, 'resources', 'icons')

    # Construct other icons
    dummyIcon = IconArtist().finish()
    iep.icons = ssdf.new()
    for fname in os.listdir(iconDir):
        if fname.startswith('iep'):
            continue
        if fname.endswith('.png'):
            try:
                # Short and full name
                name = fname.split('.')[0]
                ffname = os.path.join(iconDir, fname)
                # Create icon
                icon = QtGui.QIcon()
                icon.addFile(ffname, QtCore.QSize(16, 16))
                # Store
                iep.icons[name] = icon
            except Exception as err:
                iep.icons[name] = dummyIcon
                print('Could not load icon %s: %s' % (fname, str(err)))
Exemple #11
0
 def getCrossIcon2(self):
     if hasattr(self, '_cross2'):
         pm = self._cross2
     else:
         pm = self._createCrossPixmap(240)
     # Set
     return QtGui.QIcon(pm)
Exemple #12
0
    def onLanguageChange(self):
        languageName = self._langBox.currentText()
        if iep.config.settings.language == languageName:
            return
        # Save new language
        iep.config.settings.language = languageName
        setLanguage(iep.config.settings.language)
        # Notify user
        text = translate(
            'wizard', """
        The language has been changed for this wizard.
        IEP needs to restart for the change to take effect application-wide.
        """)
        m = QtGui.QMessageBox(self)
        m.setWindowTitle(translate("wizard", "Language changed"))
        m.setText(text)
        m.setIcon(m.Information)
        m.exec_()

        # Get props of current wizard
        geo = self.wizard().geometry()
        parent = self.wizard().parent()
        # Close ourself!
        self.wizard().close()
        # Start new one
        w = IEPWizard(parent)
        w.setGeometry(geo)
        w.show()
Exemple #13
0
    def removeProject(self):
        if not self.lstProjects.currentIndex().isValid():
            return

        projectIndex = self.lstProjects.currentIndex()
        projectRow = projectIndex.row()
        project = self._projectsModel.projectFromIndex(projectIndex)

        confirm = QtGui.QMessageBox(QtGui.QMessageBox.Warning,
                                    "Remove project?",
                                    "Remove project '%s'?" % project.name)

        confirm.addButton("Remove", QtGui.QMessageBox.DestructiveRole)
        cancel = confirm.addButton("Cancel", QtGui.QMessageBox.RejectRole)
        confirm.setDefaultButton(cancel)
        confirm.setEscapeButton(cancel)

        confirm.setInformativeText("The project contents will not be removed.")
        confirm.exec_()

        if confirm.result() != 0:  #Cancel button pressed
            return

        self._projectsModel.remove(project)

        #Select another project (try the one before)
        if projectRow > 0:
            projectRow -= 1

        if self._projectsModel.projectFromRow(projectRow) is None:
            #If we deleted the last project
            projectRow = -1

        self.projectChanged(projectRow)
Exemple #14
0
 def __init__(self, parent):
     
     # Create sub-widget
     self._edit = QtGui.QLineEdit(parent)
     self._edit.textEdited.connect(self.onEditChanged)
     
     # Instantiate
     ShellinfoWithSystemDefault.__init__(self, parent, self._edit, '$PYTHONSTARTUP') 
Exemple #15
0
    def __init__(self, parent, i):
        BaseIEPWizardPage.__init__(self, parent, i)

        # Create label and checkbox
        t1 = translate('wizard',
                       "This wizard can be opened using 'Help > IEP wizard'")
        t2 = translate('wizard', "Show this wizard on startup")
        self._label_info = QtGui.QLabel(t1, self)
        self._check_show = QtGui.QCheckBox(t2, self)
        self._check_show.stateChanged.connect(self._setNewUser)

        # Create language switcher
        self._langLabel = QtGui.QLabel(translate('wizard', "Select language"),
                                       self)
        #
        self._langBox = QtGui.QComboBox(self)
        self._langBox.setEditable(False)
        # Fill
        index, theIndex = -1, -1
        cur = iep.config.settings.language
        for lang in sorted(LANGUAGES):
            index += 1
            self._langBox.addItem(lang)
            if lang == LANGUAGE_SYNONYMS.get(cur, cur):
                theIndex = index
        # Set current index
        if theIndex >= 0:
            self._langBox.setCurrentIndex(theIndex)
        # Bind signal
        self._langBox.activated.connect(self.onLanguageChange)

        # Init check state
        if iep.config.state.newUser:
            self._check_show.setCheckState(QtCore.Qt.Checked)

        # Create sublayout
        layout = QtGui.QHBoxLayout()
        layout.addWidget(self._langLabel, 0)
        layout.addWidget(self._langBox, 0)
        layout.addStretch(2)
        self.layout().addLayout(layout)

        # Add to layout
        self.layout().addSpacing(10)
        self.layout().addWidget(self._label_info)
        self.layout().addWidget(self._check_show)
Exemple #16
0
    def __init__(self, icon=None):

        # Get pixmap from given icon (None creates empty pixmap)
        self._pm = self._getPixmap(icon)

        # Instantiate painter for the pixmap
        self._painter = QtGui.QPainter()
        self._painter.begin(self._pm)
Exemple #17
0
    def __init__(self, parent):
        QtGui.QWidget.__init__(self, parent)

        # Create text field, checkbox, and button
        self._text = QtGui.QLineEdit(self)
        self._printBut = QtGui.QPushButton("Print", self)

        # Create options button
        self._options = QtGui.QToolButton(self)
        self._options.setIcon(iep.icons.wrench)
        self._options.setIconSize(QtCore.QSize(16, 16))
        self._options.setPopupMode(self._options.InstantPopup)
        self._options.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)

        # Create options menu
        self._options._menu = QtGui.QMenu()
        self._options.setMenu(self._options._menu)

        # Create browser
        self._browser = QtGui.QTextBrowser(self)
        self._browser_text = initText

        # Create two sizers
        self._sizer1 = QtGui.QVBoxLayout(self)
        self._sizer2 = QtGui.QHBoxLayout()

        # Put the elements together
        self._sizer2.addWidget(self._text, 4)
        self._sizer2.addWidget(self._printBut, 0)
        self._sizer2.addStretch(1)
        self._sizer2.addWidget(self._options, 2)
        #
        self._sizer1.addLayout(self._sizer2, 0)
        self._sizer1.addWidget(self._browser, 1)
        #
        self._sizer1.setSpacing(2)
        self.setLayout(self._sizer1)

        # Set config
        toolId = self.__class__.__name__.lower()
        self._config = config = iep.config.tools[toolId]
        #
        if not hasattr(config, 'smartNewlines'):
            config.smartNewlines = True
        if not hasattr(config, 'fontSize'):
            if sys.platform == 'darwin':
                config.fontSize = 12
            else:
                config.fontSize = 10

        # Create callbacks
        self._text.returnPressed.connect(self.queryDoc)
        self._printBut.clicked.connect(self.printDoc)
        #
        self._options.pressed.connect(self.onOptionsPress)
        self._options._menu.triggered.connect(self.onOptionMenuTiggered)

        # Start
        self.setText()  # Set default text
        self.onOptionsPress()  # Fill menu
Exemple #18
0
    def _addOverlays(self, icon, *overlays):

        # Get pixmap
        pm0 = icon.pixmap(16, 16)

        # Create painter
        painter = QtGui.QPainter()
        painter.begin(pm0)

        for overlay in overlays:
            pm1 = overlay.pixmap(16, 16)
            painter.drawPixmap(0, 0, pm1)

        # Finish
        painter.end()

        # Done (return resulting icon)
        return QtGui.QIcon(pm0)
Exemple #19
0
 def updateItems(self):
     """ updateItems()
     
     Update the appearance of the items.
     
     """
     
     # Get items and tab bar
     items = self.items()
     tabBar = self.tabBar()
     
     for i in range(len(items)):
         
         # Get item
         item = items[i]
         if item is None:
             continue
         
         # Update name and tooltip
         if item.dirty:
             #tabBar.setTabText(i, '*'+item.name)
             tabBar.setTabToolTip(i, item.filename + ' [modified]')
         else:
             tabBar.setTabText(i, item.name)
             tabBar.setTabToolTip(i, item.filename)
         
         # Determine text color. Is main file? Is current?
         if self._mainFile == item.id:
             tabBar.setTabTextColor(i, QtGui.QColor('#008'))
         elif i == self.currentIndex():
             tabBar.setTabTextColor(i, QtGui.QColor('#000'))
         else:
             tabBar.setTabTextColor(i, QtGui.QColor('#444'))
         
         # Get number of blocks
         nBlocks = item.editor.blockCount()
         if nBlocks == 1 and not item.editor.toPlainText():
             nBlocks = 0
         
         # Update appearance of icon
         but = tabBar.tabButton(i, QtGui.QTabBar.LeftSide)
         but.updateIcon(item.dirty, self._mainFile==item.id, 
                     item.pinned, nBlocks)
Exemple #20
0
 def __init__(self, parent):
     
     # Create sub-widget
     self._edit = QtGui.QTextEdit(parent)
     self._edit.setMaximumHeight(80)
     self._edit.setMinimumWidth(400)
     self._edit.textChanged.connect(self.onEditChanged)
     
     # Instantiate
     ShellinfoWithSystemDefault.__init__(self, parent, self._edit, '$PYTHONPATH') 
Exemple #21
0
 def __init__(self, parent):
     QtGui.QWidget.__init__(self, parent)
     
     # Create layout
     self._formLayout = QtGui.QFormLayout(self)
     
     # Collect classes of widgets to instantiate
     classes = []
     for t in self.INFO_KEYS:
         className = 'ShellInfo_' + t.key
         cls = globals()[className]
         classes.append((t, cls))
     
     # Instantiate all classes
     self._shellInfoWidgets = {}
     for t, cls in classes:
         # Instantiate and store
         instance = cls(self)
         self._shellInfoWidgets[t.key] = instance
         # Create label 
         label = QtGui.QLabel(t, self)
         label.setToolTip(t.tt)
         # Add to layout
         self._formLayout.addRow(label, instance)
     
     # Add delete button  
     
     t = translate('shell', 'Delete ::: Delete this shell configuration')
     label = QtGui.QLabel('', self)        
     instance = QtGui.QPushButton(iep.icons.cancel, t, self)
     instance.setToolTip(t.tt)
     instance.setAutoDefault(False)
     instance.clicked.connect(self.parent().parent().onTabClose)
     deleteLayout = QtGui.QHBoxLayout()
     deleteLayout.addWidget(instance, 0)
     deleteLayout.addStretch(1)
     # Add to layout
     self._formLayout.addRow(label, deleteLayout)
     
     # Apply layout
     self._formLayout.setSpacing(15)
     self.setLayout(self._formLayout)
Exemple #22
0
    def _populate(self):

        # Delayed imports
        from iep.iepcore.editorTabs import EditorTabs
        from iep.iepcore.shellStack import ShellStackWidget
        from iep.iepcore import codeparser
        from iep.tools import ToolManager

        # Instantiate tool manager
        iep.toolManager = ToolManager()

        # Instantiate and start source-code parser
        if iep.parser is None:
            iep.parser = codeparser.Parser()
            iep.parser.start()

        # Create editor stack and make the central widget
        iep.editors = EditorTabs(self)
        self.setCentralWidget(iep.editors)

        # Create floater for shell
        self._shellDock = dock = QtGui.QDockWidget(self)
        dock.setFeatures(dock.DockWidgetMovable)
        dock.setObjectName('shells')
        dock.setWindowTitle('Shells')
        self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock)

        # Create shell stack
        iep.shells = ShellStackWidget(self)
        dock.setWidget(iep.shells)

        # Create the default shell when returning to the event queue
        callLater(iep.shells.addShell)

        # Create statusbar
        if iep.config.view.showStatusbar:
            iep.status = self.statusBar()
        else:
            iep.status = None
            self.setStatusBar(None)

        # Create menu
        from iep.iepcore import menu
        iep.keyMapper = menu.KeyMapper()
        menu.buildMenus(self.menuBar())

        # Add the context menu to the editor
        iep.editors.addContextMenu()
        iep.shells.addContextMenu()

        # Load tools
        if iep.config.state.loadedTools:
            for toolId in iep.config.state.loadedTools:
                iep.toolManager.loadTool(toolId)
Exemple #23
0
def simpleDialog(item, action, question, options, defaultOption):
    """ simpleDialog(editor, action, question, options, defaultOption)
    
    Options with special buttons
    ----------------------------
    ok, open, save, cancel, close, discard, apply, reset, restoredefaults,
    help, saveall, yes, yestoall, no, notoall, abort, retry, ignore.
    
    Returns the selected option as a string, or None if canceled.
    
    """
    
    # Get filename
    if isinstance(item, FileItem):
        filename = item.id
    else:
        filename = item.id()
    
    # create button map
    mb = QtGui.QMessageBox
    M = {   'ok':mb.Ok, 'open':mb.Open, 'save':mb.Save, 'cancel':mb.Cancel,
            'close':mb.Close, 'discard':mb.Discard, 'apply':mb.Apply, 
            'reset':mb.Reset, 'restoredefaults':mb.RestoreDefaults, 
            'help':mb.Help, 'saveall':mb.SaveAll, 'yes':mb.Yes, 
            'yestoall':mb.YesToAll, 'no':mb.No, 'notoall':mb.NoToAll, 
            'abort':mb.Abort, 'retry':mb.Retry, 'ignore':mb.Ignore}
    
    # setup dialog
    dlg = QtGui.QMessageBox(iep.main)
    dlg.setWindowTitle('IEP')
    dlg.setText(action + " file:\n{}".format(filename))
    dlg.setInformativeText(question)
    
    # process options
    buttons = {}
    for option in options:
        option_lower = option.lower()
        # Use standard button?
        if option_lower in M:
            button = dlg.addButton(M[option_lower]) 
        else:        
            button = dlg.addButton(option, dlg.AcceptRole)
        buttons[button] = option
        # Set as default?
        if option_lower == defaultOption.lower():
            dlg.setDefaultButton(button)
    
    # get result
    result = dlg.exec_()
    button = dlg.clickedButton()
    if button in buttons:
        return buttons[button]
    else:
        return None
Exemple #24
0
    def _getPixmap(self, icon):

        # Get icon if given by name
        if isinstance(icon, str):
            icon = iep.icons[icon]

        # Create pixmap
        if icon is None:
            pm = QtGui.QPixmap(16, 16)
            pm.fill(QtGui.QColor(0, 0, 0, 0))
            return pm
        elif isinstance(icon, tuple):
            pm = QtGui.QPixmap(icon[0], icon[1])
            pm.fill(QtGui.QColor(0, 0, 0, 0))
            return pm
        elif isinstance(icon, QtGui.QPixmap):
            return icon
        elif isinstance(icon, QtGui.QIcon):
            return icon.pixmap(16, 16)
        else:
            raise ValueError(
                'Icon for IconArtis should be icon, pixmap or name.')
Exemple #25
0
    def saveFile(self, editor=None, filename=None):
        """ Save the file. 
        returns: True if succesfull, False if fails
        """
        
        # get editor
        if editor is None:
            editor = self.getCurrentEditor()
        elif isinstance(editor, int):
            index = editor
            editor = None
            if index>=0:
                item = self._tabs.items()[index]
                editor = item.editor
        if editor is None:
            return False
        
        # get filename
        if filename is None:
            filename = editor._filename
        if not filename:
            return self.saveFileAs(editor)

        
        # let the editor do the low level stuff...
        try:
            editor.save(filename)
        except Exception as err:
            # Notify in logger
            print("Error saving file:",err)
            # Make sure the user knows
            m = QtGui.QMessageBox(self)
            m.setWindowTitle("Error saving file")
            m.setText(str(err))
            m.setIcon(m.Warning)
            m.exec_()
            # Return now            
            return False
        
        # get actual normalized filename
        filename = editor._filename
        
        # notify
        # TODO: message concerining line endings
        print("saved file: {} ({})".format(filename, editor.lineEndingsHumanReadable))
        self._tabs.updateItems()
        
        # todo: this is where we once detected whether the file being saved was a style file.
        
        # Notify done
        return True
Exemple #26
0
    def __init__(self, parent):
        QtGui.QWidget.__init__(self, parent)

        # Create label widget and costumize
        self._label = QtGui.QLabel(self)
        self._label.setTextFormat(QtCore.Qt.RichText)
        self._label.setOpenExternalLinks(True)
        self._label.setWordWrap(True)
        self._label.setMargin(20)

        # Set font a wee bit larger
        font = self._label.font()
        font.setPointSize(font.pointSize() + 1)
        self._label.setFont(font)

        # Set text
        self._label.setText(license_text1)

        layout = QtGui.QVBoxLayout(self)
        self.setLayout(layout)
        layout.addStretch(1)
        layout.addWidget(self._label, 0)
        layout.addStretch(1)
Exemple #27
0
 def loadFile(self, filename, updateTabs=True):
     """ Load the specified file. 
     On success returns the item of the file, also if it was
     already open."""
     
     # Note that by giving the name of a tempfile, we can select that
     # temp file.
     
     # normalize path
     if filename[0] != '<':
         filename = normalizePath(filename)
     if not filename:
         return None
     
     # if the file is already open...
     for item in self._tabs.items():
         if item.id == filename:
             # id gets _filename or _name for temp files
             break
     else:
         item = None
     if item:
         self._tabs.setCurrentItem(item)
         print("File already open: '{}'".format(filename))
         return item
     
     # create editor
     try:
         editor = createEditor(self, filename)
     except Exception as err:
         # Notify in logger
         print("Error loading file: ", err)
         # Make sure the user knows
         m = QtGui.QMessageBox(self)
         m.setWindowTitle("Error loading file")
         m.setText(str(err))
         m.setIcon(m.Warning)
         m.exec_()
         return None
     
     # create list item
     item = FileItem(editor)
     self._tabs.addItem(item, updateTabs)        
     if updateTabs:
         self._tabs.setCurrentItem(item)
     
     # store the path
     self._lastpath = os.path.dirname(item.filename)
     
     return item
Exemple #28
0
def loadAppIcons():
    """ loadAppIcons()
    Load the application iconsr.
    """
    # Get directory containing the icons
    appiconDir = os.path.join(iep.iepDir, 'resources', 'appicons')

    # Determine template for filename of the application icon-files.
    # Use the Pyzo logo if in pyzo_mode.
    if iep.pyzo_mode:
        fnameT = 'pyzologo{}.png'
    else:
        fnameT = 'ieplogo{}.png'

    # Construct application icon. Include a range of resolutions. Note that
    # Qt somehow does not use the highest possible res on Linux/Gnome(?), even
    # the logo of qt-designer when alt-tabbing looks a bit ugly.
    iep.icon = QtGui.QIcon()
    for sze in [16, 32, 48, 64, 128, 256]:
        fname = os.path.join(appiconDir, fnameT.format(sze))
        if os.path.isfile(fname):
            iep.icon.addFile(fname, QtCore.QSize(sze, sze))

    # Set as application icon. This one is used as the default for all
    # windows of the application.
    QtGui.qApp.setWindowIcon(iep.icon)

    # Construct another icon to show when the current shell is busy
    artist = IconArtist(iep.icon)  # extracts the 16x16 version
    artist.setPenColor('#0B0')
    for x in range(11, 16):
        d = x - 11  # runs from 0 to 4
        artist.addLine(x, 6 + d, x, 15 - d)
    pm = artist.finish().pixmap(16, 16)
    #
    iep.iconRunning = QtGui.QIcon(iep.icon)
    iep.iconRunning.addPixmap(pm)  # Change only 16x16 icon
Exemple #29
0
    def __init__(self, parent):
        QtGui.QWidget.__init__(self, parent)

        # Get config
        toolId = self.__class__.__name__.lower(
        ) + '2'  # This is v2 of the file browser
        if toolId not in iep.config.tools:
            iep.config.tools[toolId] = ssdf.new()
        self.config = iep.config.tools[toolId]

        # Ensure three main attributes in config
        for name in ['expandedDirs', 'starredDirs']:
            if name not in self.config:
                self.config[name] = []

        # Ensure path in config
        if 'path' not in self.config or not os.path.isdir(self.config.path):
            self.config.path = os.path.expanduser('~')

        # Check expandedDirs and starredDirs.
        # Make Path instances and remove invalid dirs. Also normalize case,
        # should not be necessary, but maybe the config was manually edited.
        expandedDirs, starredDirs = [], []
        for d in self.config.starredDirs:
            if 'path' in d and 'name' in d and 'addToPythonpath' in d:
                if os.path.isdir(d.path):
                    d.path = Path(d.path).normcase()
                    starredDirs.append(d)
        for p in set([str(p) for p in self.config.expandedDirs]):
            if os.path.isdir(p):
                p = Path(p).normcase()
                # Add if it is a subdir of a starred dir
                for d in starredDirs:
                    if p.startswith(d.path):
                        expandedDirs.append(p)
                        break
        self.config.expandedDirs, self.config.starredDirs = expandedDirs, starredDirs

        # Create browser(s).
        self._browsers = []
        for i in [0]:
            self._browsers.append(Browser(self, self.config))

        # Layout
        layout = QtGui.QVBoxLayout(self)
        self.setLayout(layout)
        layout.addWidget(self._browsers[0])
        layout.setSpacing(0)
        layout.setContentsMargins(4, 4, 4, 4)
Exemple #30
0
    def _setMaxWidthOfAllItems(self):
        """ _setMaxWidthOfAllItems()
        
        Sets the maximum width of all items now, by eliding the names.
        Returns whether any items were elided.
        
        """

        # Prepare for measuring font sizes
        font = self.font()
        metrics = QtGui.QFontMetrics(font)

        # Get whether an item was reduced in size
        itemReduced = False

        for i in range(self.count()):

            # Get width
            w = self._alignWidth

            # Get name
            name = name0 = self._compactTabBarData(i).name

            # Check if we can reduce the name size, correct w if necessary
            if ((w + 1) < len(name0)) and self._preventEqualTexts:

                # Increase w untill there are no names that start the same
                allNames = self._getAllNames()
                hasSimilarNames = True
                diff = 2
                w -= 1
                while hasSimilarNames and w < len(name0):
                    w += 1
                    w2 = w - (diff - 1)
                    shortName = name[:w2]
                    similarnames = [n for n in allNames if n[:w2] == shortName]
                    hasSimilarNames = len(similarnames) > 1

            # Check again, with corrected w
            if (w + 1) < len(name0):
                name = name[:w] + ELLIPSIS
                itemReduced = True

            # Set text now
            QtGui.QTabBar.setTabText(self, i, name)

        # Done
        return itemReduced