Пример #1
0
 def __createListWidget(self):
     iconList=QListWidget()
     iconList.setAlternatingRowColors(True)
     iconList.setContextMenuPolicy(Qt.CustomContextMenu)
     #iconList.setStyleSheet("QListWidget { background: red; } QListWidget::item { background: yellow; } QListWidget::item:selected { background: blue; }")
     iconList.setStyleSheet("QListWidget::item:selected:active { background: #28D9FF; color:#FFFFFF; } ")#that text color seems not to work!
     return iconList
Пример #2
0
class Completer(QCompleter):
    def __init__(self, editor, project):
        QCompleter.__init__(self)

        self.icons = {
            'function': QIcon(resources.images['function']),
            'instance': QIcon(resources.images['attribute']),
            'module': QIcon(resources.images['module']),
            'class': QIcon(resources.images['class'])
        }

        self._editor = editor
        self._fromProject = False
        if project is not None:
            self._project = project
            self._fromProject = True
        else:
            self._project = rope.base.project.Project(self._editor.path, None,
                                                      None)
        self.setWidget(self._editor)
        self.popupView = QListWidget()
        self.popupView.setAlternatingRowColors(True)
        self.popupView.setWordWrap(False)
        self.setPopup(self.popupView)
        self.setCompletionMode(QCompleter.PopupCompletion)
        self.setCaseSensitivity(Qt.CaseInsensitive)

        self.connect(self, SIGNAL("activated(QString)"),
                     self.insert_completion)

    def insert_completion(self, insert):
        extra = insert.length() - self.completionPrefix().length()
        self._editor.textCursor().insertText(insert.right(extra))

    def complete(self, cr):
        if self._project:
            try:
                self.popupView.clear()
                code = str(self._editor.toPlainText())
                start = self._editor.textCursor().position()
                end = code.find('\n', start)
                code = code[:start] + code[end:]
                if self._fromProject:
                    self._project.validate()
                proposals = codeassist.code_assist(self._project, code, start)
                proposals = codeassist.sorted_proposals(proposals)
                model = self.obtain_model_items(proposals)
                self.setModel(model)
                self.popup().setCurrentIndex(model.index(0, 0))
                cr.setWidth(self.popup().sizeHintForColumn(0) \
                    + self.popup().verticalScrollBar().sizeHint().width() + 10)
                self.popupView.updateGeometries()
                super(Completer, self).complete(cr)
            except Exception, reason:
                print reason
Пример #3
0
class Completer(QCompleter):

    def __init__(self, editor, project):
        QCompleter.__init__(self)

        self.icons = {'function':QIcon(resources.images['function']),
            'instance':QIcon(resources.images['attribute']),
            'module':QIcon(resources.images['module']),
            'class':QIcon(resources.images['class'])}

        self._editor = editor
        self._fromProject = False
        if project is not None:
            self._project = project
            self._fromProject = True
        else:
            self._project = rope.base.project.Project(self._editor.path, None, None)
        self.setWidget(self._editor)
        self.popupView = QListWidget()
        self.popupView.setAlternatingRowColors(True)
        self.popupView.setWordWrap(False)
        self.setPopup(self.popupView)
        self.setCompletionMode(QCompleter.PopupCompletion)
        self.setCaseSensitivity(Qt.CaseInsensitive)

        self.connect(self, SIGNAL("activated(QString)"), self.insert_completion)

    def insert_completion(self, insert):
        extra = insert.length() - self.completionPrefix().length()
        self._editor.textCursor().insertText(insert.right(extra))

    def complete(self, cr):
        if self._project:
            try:
                self.popupView.clear()
                code = str(self._editor.toPlainText())
                start = self._editor.textCursor().position()
                end = code.find('\n', start)
                code = code[:start] + code[end:]
                if self._fromProject:
                    self._project.validate()
                proposals = codeassist.code_assist(self._project, code, start)
                proposals = codeassist.sorted_proposals(proposals)
                model = self.obtain_model_items(proposals)
                self.setModel(model)
                self.popup().setCurrentIndex(model.index(0, 0))
                cr.setWidth(self.popup().sizeHintForColumn(0) \
                    + self.popup().verticalScrollBar().sizeHint().width() + 10)
                self.popupView.updateGeometries()
                super(Completer, self).complete(cr)
            except Exception, reason:
                print reason
Пример #4
0
class RMirrorBrowser(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        kwargs = {"local.only":False}
        m = robjects.r.getCRANmirrors(all=False, **kwargs)
        names = QStringList(list(m.rx('Name')[0]))
        urls = list(m.rx('URL')[0])
        self.links = dict(zip(names, urls))
        names = QStringList(names)
        self.setWindowTitle("manageR - Choose CRAN Mirror")
        self.setWindowIcon(QIcon(":icon"))
        self.links = dict(zip(names, urls))
        self.currentMirror = None
        self.mirrorList = QListWidget(self)
        self.mirrorList.setAlternatingRowColors(True)
        self.mirrorList.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.mirrorList.setSortingEnabled(True)
        self.mirrorList.setSelectionMode(QAbstractItemView.SingleSelection)
        self.mirrorList.setToolTip("Double-click to select mirror location")
        self.mirrorList.setWhatsThis("List of CRAN mirrors")
        self.mirrorList.insertItems(0, names)
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
        vbox = QVBoxLayout(self)
        vbox.addWidget(self.mirrorList)
        vbox.addWidget(buttonBox)

        self.connect(buttonBox, SIGNAL("accepted()"), self.accept)
        self.connect(buttonBox, SIGNAL("rejected()"), self.reject)
        self.connect(self.mirrorList,
            SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.accept)

    def currentMirror(self):
        return robjects.r("getOption('repos')")[0]

    def setCurrentMirror(self, mirror):
        robjects.r("options('repos'='%s')" % mirror)

    def accept(self):
        items = self.mirrorList.selectedItems()
        if len(items) > 0:
            name = items[0].text()
            url = self.links[name]
            self.setCurrentMirror(url)
            QDialog.accept(self)
        else:
            QMessageBox.warning(self, "manageR - Warning",
                "Please choose a valid CRAN mirror")
Пример #5
0
class CompleterWidget(QCompleter):

    def __init__(self, editor):
        QCompleter.__init__(self)

        self.setWidget(editor)
        self.popupView = QListWidget()
        self.popupView.setAlternatingRowColors(True)
        self.popupView.setWordWrap(False)
        self.setPopup(self.popupView)
        self.setCompletionMode(QCompleter.PopupCompletion)
        self.setCaseSensitivity(Qt.CaseInsensitive)

        self.connect(self.popupView, SIGNAL("itemClicked(QListWidgetItem*)"),
            self.insert_completion)

    def insert_completion(self):
        insert = self.popupView.currentItem().text()
        extra = insert.length() - self.completionPrefix().length()
        self.widget().textCursor().insertText(insert.right(extra))
        self.popup().hide()

    def complete(self, cr, results):
        self.popupView.clear()
        model = self.obtain_model_items(results)
        self.setModel(model)
        self.popup().setCurrentIndex(model.index(0, 0))
        cr.setWidth(self.popup().sizeHintForColumn(0) \
            + self.popup().verticalScrollBar().sizeHint().width() + 10)
        self.popupView.updateGeometries()
        QCompleter.complete(self, cr)

    def obtain_model_items(self, proposals):
        proposals.sort()
        for p in proposals:
            self.popupView.addItem(QListWidgetItem(p))
        return self.popupView.model()
Пример #6
0
class CodeCompletionWidget(QFrame):

    def __init__(self, editor):
        super(CodeCompletionWidget, self).__init__(
            None, Qt.FramelessWindowHint | Qt.ToolTip)
        self._editor = editor
        self._revision = 0
        self._block = 0
        self.stack_layout = QStackedLayout(self)
        self.stack_layout.setContentsMargins(0, 0, 0, 0)
        self.stack_layout.setSpacing(0)
        self.completion_list = QListWidget()
        self.completion_list.setMinimumHeight(200)
        self.completion_list.setAlternatingRowColors(True)
        self._list_index = self.stack_layout.addWidget(self.completion_list)

        self._icons = {'a': resources.IMAGES['attribute'],
            'f': resources.IMAGES['function'],
            'c': resources.IMAGES['class'],
            'm': resources.IMAGES['module']}

        self.cc = code_completion.CodeCompletion()
        self._completion_results = {}
        self._prefix = u''
        self.setVisible(False)
        self.source = ''
        self._key_operations = {
            Qt.Key_Up: self._select_previous_row,
            Qt.Key_Down: self._select_next_row,
            Qt.Key_PageUp: (lambda: self._select_previous_row(6)),
            Qt.Key_PageDown: (lambda: self._select_next_row(6)),
            Qt.Key_Right: lambda: None,
            Qt.Key_Left: lambda: None,
            Qt.Key_Enter: self.pre_key_insert_completion,
            Qt.Key_Return: self.pre_key_insert_completion,
            Qt.Key_Tab: self.pre_key_insert_completion,
            Qt.Key_Space: self.hide_completer,
            Qt.Key_Escape: self.hide_completer,
            Qt.Key_Backtab: self.hide_completer,
            Qt.NoModifier: self.hide_completer,
            Qt.ShiftModifier: self.hide_completer,
        }

        self.desktop = QApplication.instance().desktop()

        self.connect(self.completion_list,
            SIGNAL("itemClicked(QListWidgetItem*)"),
            self.pre_key_insert_completion)
        self.connect(self._editor.document(),
            SIGNAL("cursorPositionChanged(QTextCursor)"),
            self.update_metadata)

    def _select_next_row(self, move=1):
        new_row = self.completion_list.currentRow() + move
        if new_row < self.completion_list.count():
            self.completion_list.setCurrentRow(new_row)
        else:
            self.completion_list.setCurrentRow(0)
        return True

    def _select_previous_row(self, move=1):
        new_row = self.completion_list.currentRow() - move
        if new_row >= 0:
            self.completion_list.setCurrentRow(new_row)
        else:
            self.completion_list.setCurrentRow(
                self.completion_list.count() - move)
        return True

    def update_metadata(self, cursor):
        if settings.CODE_COMPLETION:
            if self._editor.document().revision() != self._revision and \
               cursor.block().blockNumber() != self._block:
                source = self._editor.get_text()
                source = source.encode(self._editor.encoding)
                self.cc.analyze_file(self._editor.ID, source)
                self._revision = self._editor.document().revision()
                self._block = cursor.block().blockNumber()

    def insert_completion(self, insert, type_=ord('a')):
        if insert != self._prefix:
            closing = ''
            if type_ in (ord('f'), ord('c')):
                closing = '()'
            extra = len(self._prefix) - len(insert)
            insertion = '%s%s' % (insert[extra:], closing)
            self._editor.textCursor().insertText(insertion)
        self.hide_completer()

    def _get_geometry(self):
        cr = self._editor.cursorRect()
        desktop_geometry = self.desktop.availableGeometry(self._editor)
        point = self._editor.mapToGlobal(cr.topLeft())
        cr.moveTopLeft(point)
        #Check new position according desktop geometry
        width = (self.completion_list.sizeHintForColumn(0) +
            self.completion_list.verticalScrollBar().sizeHint().width() + 10)
        height = 200
        orientation = (point.y() + height) < desktop_geometry.height()
        if orientation:
            cr.moveTop(cr.bottom())
        cr.setWidth(width)
        cr.setHeight(height)
        if not orientation:
            cr.moveBottom(cr.top())
        xpos = desktop_geometry.width() - (point.x() + width)
        if xpos < 0:
            cr.moveLeft(cr.left() + xpos)
        return cr

    def complete(self, results):
        self.add_list_items(results)
        self.completion_list.setCurrentRow(0)
        cr = self._get_geometry()
        self.setGeometry(cr)
        self.completion_list.updateGeometries()
        self.show()

    def add_list_items(self, proposals):
        self.completion_list.clear()
        for p in proposals:
            self.completion_list.addItem(
                QListWidgetItem(
                QIcon(self._icons.get(p[0], resources.IMAGES['attribute'])),
                p[1], type=ord(p[0])))

    def set_completion_prefix(self, prefix, valid=True):
        self._prefix = prefix
        proposals = []
        proposals += [('m', item)
            for item in self._completion_results.get('modules', [])
            if item.startswith(prefix)]
        proposals += [('c', item)
            for item in self._completion_results.get('classes', [])
            if item.startswith(prefix)]
        proposals += [('a', item)
            for item in self._completion_results.get('attributes', [])
            if item.startswith(prefix)]
        proposals += [('f', item)
            for item in self._completion_results.get('functions', [])
            if item.startswith(prefix)]
        if proposals and valid:
            self.complete(proposals)
        else:
            self.hide_completer()

    def _invalid_completion_position(self):
        result = False
        cursor = self._editor.textCursor()
        cursor.movePosition(QTextCursor.StartOfLine,
            QTextCursor.KeepAnchor)
        selection = unicode(cursor.selectedText())[:-1].split(' ')
        if len(selection) == 0 or selection[-1] == '' or \
           selection[-1].isdigit():
            result = True
        return result

    def fill_completer(self, force_completion=False):
        if not force_completion and (self._editor.cursor_inside_string() or
           self._editor.cursor_inside_comment() or
           self._invalid_completion_position()):
            return
        source = self._editor.get_text()
        source = source.encode(self._editor.encoding)
        offset = self._editor.textCursor().position()
        results = self.cc.get_completion(source, offset)
        self._completion_results = results
        if force_completion:
            cursor = self._editor.textCursor()
            cursor.movePosition(QTextCursor.StartOfWord,
                QTextCursor.KeepAnchor)
            prefix = cursor.selectedText()
        else:
            prefix = self._editor._text_under_cursor()
        self.set_completion_prefix(prefix)

    def hide_completer(self):
        self._prefix = ''
        self.hide()

    def pre_key_insert_completion(self):
        type_ = ord('a')
        current = self.completion_list.currentItem()
        insert = unicode(current.text())
        if not insert.endswith(')'):
            type_ = current.type()
        self.insert_completion(insert, type_)
        self.hide_completer()
        return True

    def process_pre_key_event(self, event):
        if not self.isVisible() or self._editor.lang != "python":
            return False
        skip = self._key_operations.get(event.key(), lambda: False)()
        self._key_operations.get(event.modifiers(), lambda: False)()
        if skip is None:
            skip = False
        return skip

    def process_post_key_event(self, event):
        if not settings.CODE_COMPLETION or self._editor.lang != "python":
            return
        if self.isVisible():
            source = self._editor.get_text()
            source = source.encode(self._editor.encoding)
            offset = self._editor.textCursor().position()
            prefix, valid = self.cc.get_prefix(source, offset)
            self.set_completion_prefix(prefix, valid)
            self.completion_list.setCurrentRow(0)
        force_completion = (event.key() == Qt.Key_Space and
                            event.modifiers() == Qt.ControlModifier)
        if event.key() == Qt.Key_Period or force_completion:
            self.fill_completer(force_completion)
class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.media = Phonon.MediaObject(self)
        ### video widget ####
        self.video = Phonon.VideoWidget(self)
        self.video.setMinimumSize(320,200)
        self.videoCuts = []
        self.myfilename = ""
        self.extension = ""
        self.t1 = ""
        self.t2 = ""
        self.t3 = ""
        self.t4 = ""
        self.t5 = ""
        self.t6 = ""

        ### open button ###
        self.button = QtGui.QPushButton('Choose Video', self)
        self.button.setFixedWidth(90)
        self.button.clicked.connect(self.handleButton)
        self.button.setStyleSheet(stylesheet(self))

		### context menu ####
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.popup2)

        ### play / pause button ###
        self.playbutton = QtGui.QPushButton('Play', self)
        self.playbutton.setFixedWidth(70)
        self.playbutton.clicked.connect(self.handlePlayButton)
        self.playbutton.setStyleSheet(stylesheet(self))
        self.connect(QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Space), self), QtCore.SIGNAL('activated()'), self.handlePlayButton)
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("Ctrl+o"), self), QtCore.SIGNAL('activated()'), self.handleButton)
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("Ctrl+s"), self), QtCore.SIGNAL('activated()'), self.handleSaveVideo)
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("Ctrl+q"), self), QtCore.SIGNAL('activated()'), self.handleQuit)
        ### save button ###
        self.savebutton = QtGui.QPushButton('Save Video', self)
        self.savebutton.setFixedWidth(90)
        self.savebutton.clicked.connect(self.handleSaveVideo)
        self.savebutton.setStyleSheet(stylesheet(self))

        ### seek slider ###
        self.slider = Phonon.SeekSlider(self.media)
        self.slider.setStyleSheet(stylesheet(self))
        isize = QSize(16,16)
        self.slider.setIconSize(isize)
        self.slider.setFocus()
       # self.slider.connect(self.handleLabel)

        ### connection position to label ###
        self.media.isSeekable()
        self.media.tick.connect(self.handleLabel)
        self.media.seekableChanged.connect(self.handleLabel)
        #self.slider.wheel.connect(self.handleLabel)

        ### table view ###
        self.iconList = QListWidget()
        self.iconList.setAlternatingRowColors(True)
        self.iconList.setFixedWidth(200)
        self.iconList.setContextMenuPolicy(Qt.CustomContextMenu)
        self.iconList.setStyleSheet("QListWidget::item:selected:active { background: #7D8ED9; color:#FFFFFF; } ")
        self.iconList.setViewMode(0)
        self.iconList.setSelectionBehavior(1)
        self.iconList.setIconSize(QSize(80, 80/1.78))
        self._hookListActions()
        self.iconList.customContextMenuRequested.connect(self._openListMenu)

                ### set start button ###
        self.startbutton = QtGui.QPushButton('set Start', self)
        self.startbutton.setFixedWidth(70)
        self.startbutton.clicked.connect(self.handleStartButton)
        self.startbutton.setStyleSheet(stylesheet(self))
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("s"), self), QtCore.SIGNAL('activated()'), self.handleStartButton)

                ### set end button ###
        self.endbutton = QtGui.QPushButton('set End', self)
        self.endbutton.setFixedWidth(70)
        self.endbutton.clicked.connect(self.handleEndButton)
        self.endbutton.setStyleSheet(stylesheet(self))
        self.connect(QtGui.QShortcut(QtGui.QKeySequence("e"), self), QtCore.SIGNAL('activated()'), self.handleEndButton)
                ### label ###
        self.mlabel = QtGui.QLabel('Frame', self)
        self.mlabel.setStyleSheet('QLabel \
				{background-color: transparent; color: white;}\nQLabel{color: darkcyan; font-size: 12px; background-color: transparent; border-radius: 5px; padding: 6px; text-align: center;}\n QLabel:hover{color: red;}')
        #self.mlabel.setFixedWidth(80)

        ### layout ###
        layout = QtGui.QGridLayout(self)
        layout.addWidget(self.iconList, 0, 0, 1, 1)
        layout.addWidget(self.video, 0, 1, 1, 6)
        layout.addWidget(self.slider, 1, 1, 1, 6)
        layout.addWidget(self.button, 2, 0, 1, 1)
        layout.addWidget(self.savebutton, 2, 1, 1, 1)
        layout.addWidget(self.playbutton, 2, 3, 1, 1)
        layout.addWidget(self.startbutton, 2, 5, 1, 1)
        layout.addWidget(self.endbutton, 2, 6, 1, 1)
        layout.addWidget(self.mlabel, 2, 4, 1, 1)

    def popup2(self, pos):	
        contextmenu = QMenu()
        contextmenu.addAction("Play / Pause (SPACE)", self.handlePlayButton)
        contextmenu.addSeparator()
        contextmenu.addAction("Load Video (Ctrl-O)", self.handleButton)
        contextmenu.addAction("Save Video (Ctrl-S)", self.handleSaveVideo)
        contextmenu.addSeparator()
        contextmenu.addAction("Info", self.handleInfo)
        contextmenu.addSeparator()
        contextmenu.addAction("Exit (q)", self.handleQuit)
        contextmenu.exec_(QCursor.pos())

    def handleInfo(self):
            msg = QMessageBox()
            #msg.setFixedSize(500, 300)
            #msg.setGeometry(100,100, 400, 200)
            msg.setIcon(QMessageBox.Information)
            msg.setText("Axel Schneider")
            msg.setInformativeText(unicode(u"©2016"))
            msg.setWindowTitle("Cut Video")
            msg.setDetailedText("Python Qt4")
            msg.setStandardButtons(QMessageBox.Ok)
	
            retval = msg.exec_()
            print "value of pressed message box button:", retval

    def handleQuit(self):
        app.quit()

    def handleButton(self):
        if self.media.state() == Phonon.PlayingState:
            self.media.stop()
        else:
            path = QtGui.QFileDialog.getOpenFileName(self, ("Video laden"),
                                                	'/Axel_1/Filme',
                                                	"Videos (*.ts *.mp4)")
            if path:
                self.myfilename = unicode(path) #.encode("utf-8")
                window.setWindowTitle(self.myfilename.split("/")[-1])
                self.extension = path.split(".")[1]
                print(self.extension)
                self.media.setCurrentSource(Phonon.MediaSource(path))
                self.video.setScaleMode(1)
                self.video.setAspectRatio(1)
                self.audio = Phonon.AudioOutput(Phonon.VideoCategory, self)
                Phonon.createPath(self.media, self.audio)
                Phonon.createPath(self.media, self.video)
                self.media.play()
                self.playbutton.setText('Pause')

    def handleSaveVideo(self):
        result = QFileDialog.getSaveFileName(self, ("Video speichern"),
             						'/tmp/film.' + str(self.extension),
             						"Videos (*.ts *.mp4)")
        if result:
            target = unicode(result)
            self.t1 = float(self.videoCuts[0])
            self.t2 = float(self.videoCuts[1])
            ffmpeg_extract_subclip(self.myfilename, self.t1, self.t2, targetname=target)
            window.setWindowTitle("Film gespeichert")
            self.purgeMarker()

    def handlePlayButton(self):
        if self.media.state() == Phonon.PlayingState:
            self.media.pause()
            self.playbutton.setText('Play')
				
        else:
            #print(self.iconList.count())
            self.media.play()
            self.playbutton.setText('Pause')

    def handleStartButton(self):
        if self.iconList.count() < 2:
            rm = str(self.media.currentTime() / 100.00 / 10.00)
            item = QListWidgetItem()
            img = QImage(self.video.snapshot())
            pix = QtGui.QPixmap.fromImage(img)
            item.setIcon(QIcon(pix))
            item.setText("Start: " + rm)
            self.iconList.addItem(item)
            self.videoCuts.append(rm)
        else:
            return

    def handleEndButton(self):
        if self.iconList.count() < 2:
            rm = str(self.media.currentTime() / 100.00 / 10.00)
            item = QListWidgetItem()
            #item.setSizeHint(QSize(150, 40))
            img = QImage(self.video.snapshot())
            pix = QtGui.QPixmap.fromImage(img)
            item.setIcon(QIcon(pix))
            item.setText("End: " + rm)
            self.iconList.addItem(item)
            self.videoCuts.append(rm)
            self.t3 = float(str(self.media.remainingTime()))
            print(self.t3)
            self.media.stop()
            self.playbutton.setText('Play')
        else:
            return

    def handleLabel(self):
            ms = self.media.currentTime()
            seconds=str((ms/1000)%60)
            minutes=str((ms/(1000*60))%60)
            hours=str((ms/(1000*60*60))%24)
            if int(seconds) < 10:
                seconds = "0" + seconds
            if int(minutes) < 10:
                minutes = "0" + minutes
            if int(hours) < 10:
                hours = "0" + hours
                s = hours + ":" + minutes + ":" + seconds
                self.mlabel.setText(s)

    def _hookListActions(self):
        #TOO bad-the list model -should be here...
        rmAction = QtGui.QAction(QtGui.QIcon('icons/close-x.png'), 'entfernen', self)
        rmAction.triggered.connect(self._removeMarker)
        rmAllAction = QtGui.QAction(QtGui.QIcon('icons/clear-all.png'), 'alle entfernen', self)
        rmAllAction.triggered.connect(self.purgeMarker)
        self.gotoAction = QtGui.QAction(QtGui.QIcon('icons/go-next.png'), 'zu dieser Position springen', self)
        self.gotoAction.triggered.connect(self._gotoFromMarker)

        #menus
        self._listMenu = QMenu()
        self._listMenu.addAction(self.gotoAction)
        self._listMenu.addSeparator()
        self._listMenu.addAction(rmAction)
        self._listMenu.addAction(rmAllAction)

    #---List widget context menu
    def _removeMarker(self,whatis):
        selectionList = self.iconList.selectedIndexes()
        if len(selectionList)==0:
            return
        item = selectionList[0]
        self.iconList.takeItem(item.row())
        #self.videoCuts.remove[1])

    def clearMarkerList(self):
        self.iconList.clear()

    #remove contents, remove file
    def purgeMarker(self):
        self.iconList.clear()
        self.videoCuts = []

    def _gotoFromMarker(self,whatis):
        selectionList = self.iconList.selectedIndexes()
        if len(selectionList)==0:
            return
        item = selectionList[0]
        pos = item.data().toString().replace("Start: ", "").replace("End: ", "")
        #frame = pos.ToInt()
        #self.video.currentTime = 1589
        self.setWindowTitle(pos)

    def _openListMenu(self,position):
        selectionList = self.iconList.selectedIndexes()
        if len(selectionList)==0:
            return
        self._listMenu.exec_(self.iconList.viewport().mapToGlobal(position))
Пример #8
0
class CodeCompletionWidget(QFrame):
    def __init__(self, editor):
        super(CodeCompletionWidget,
              self).__init__(None, Qt.FramelessWindowHint | Qt.ToolTip)
        self._editor = editor
        self._revision = 0
        self._block = 0
        self.stack_layout = QStackedLayout(self)
        self.stack_layout.setContentsMargins(0, 0, 0, 0)
        self.stack_layout.setSpacing(0)
        self.completion_list = QListWidget()
        self.completion_list.setMinimumHeight(200)
        self.completion_list.setAlternatingRowColors(True)
        self._list_index = self.stack_layout.addWidget(self.completion_list)

        self._icons = {
            'a': resources.IMAGES['attribute'],
            'f': resources.IMAGES['function'],
            'c': resources.IMAGES['class'],
            'm': resources.IMAGES['module']
        }

        self.cc = code_completion.CodeCompletion()
        self._completion_results = {}
        self._prefix = ''
        self.setVisible(False)
        self.source = ''
        self._key_operations = {
            Qt.Key_Up: self._select_previous_row,
            Qt.Key_Down: self._select_next_row,
            Qt.Key_PageUp: (lambda: self._select_previous_row(6)),
            Qt.Key_PageDown: (lambda: self._select_next_row(6)),
            Qt.Key_Right: lambda: None,
            Qt.Key_Left: lambda: None,
            Qt.Key_Enter: self.pre_key_insert_completion,
            Qt.Key_Return: self.pre_key_insert_completion,
            Qt.Key_Tab: self.pre_key_insert_completion,
            Qt.Key_Space: self.hide_completer,
            Qt.Key_Escape: self.hide_completer,
            Qt.Key_Backtab: self.hide_completer,
            Qt.NoModifier: self.hide_completer,
            Qt.ShiftModifier: self.hide_completer,
        }

        self.desktop = QApplication.instance().desktop()

        self.connect(self.completion_list,
                     SIGNAL("itemClicked(QListWidgetItem*)"),
                     self.pre_key_insert_completion)
        self.connect(self._editor.document(),
                     SIGNAL("cursorPositionChanged(QTextCursor)"),
                     self.update_metadata)

    def _select_next_row(self, move=1):
        new_row = self.completion_list.currentRow() + move
        if new_row < self.completion_list.count():
            self.completion_list.setCurrentRow(new_row)
        else:
            self.completion_list.setCurrentRow(0)
        return True

    def _select_previous_row(self, move=1):
        new_row = self.completion_list.currentRow() - move
        if new_row >= 0:
            self.completion_list.setCurrentRow(new_row)
        else:
            self.completion_list.setCurrentRow(self.completion_list.count() -
                                               move)
        return True

    def update_metadata(self, cursor):
        if settings.CODE_COMPLETION:
            if self._editor.document().revision() != self._revision and \
               cursor.block().blockNumber() != self._block:
                source = self._editor.get_text()
                source = source.encode(self._editor.encoding)
                self.cc.analyze_file(self._editor.ID, source,
                                     self._editor.indent, self._editor.useTabs)
                self._revision = self._editor.document().revision()
                self._block = cursor.block().blockNumber()

    def insert_completion(self, insert, type_=ord('a')):
        if insert != self._prefix:
            closing = ''
            if type_ in (ord('f'), ord('c')):
                closing = '()'
            extra = len(self._prefix) - len(insert)
            insertion = '%s%s' % (insert[extra:], closing)
            self._editor.textCursor().insertText(insertion)
        self.hide_completer()

    def _get_geometry(self):
        cr = self._editor.cursorRect()
        desktop_geometry = self.desktop.availableGeometry(self._editor)
        point = self._editor.mapToGlobal(cr.topLeft())
        cr.moveTopLeft(point)
        #Check new position according desktop geometry
        width = (self.completion_list.sizeHintForColumn(0) +
                 self.completion_list.verticalScrollBar().sizeHint().width() +
                 10)
        height = 200
        orientation = (point.y() + height) < desktop_geometry.height()
        if orientation:
            cr.moveTop(cr.bottom())
        cr.setWidth(width)
        cr.setHeight(height)
        if not orientation:
            cr.moveBottom(cr.top())
        xpos = desktop_geometry.width() - (point.x() + width)
        if xpos < 0:
            cr.moveLeft(cr.left() + xpos)
        return cr

    def complete(self, results):
        self.add_list_items(results)
        self.completion_list.setCurrentRow(0)
        cr = self._get_geometry()
        self.setGeometry(cr)
        self.completion_list.updateGeometries()
        self.show()

    def add_list_items(self, proposals):
        self.completion_list.clear()
        for p in proposals:
            self.completion_list.addItem(
                QListWidgetItem(QIcon(
                    self._icons.get(p[0], resources.IMAGES['attribute'])),
                                p[1],
                                type=ord(p[0])))

    def set_completion_prefix(self, prefix, valid=True):
        self._prefix = prefix
        proposals = []
        proposals += [('m', item)
                      for item in self._completion_results.get('modules', [])
                      if item.startswith(prefix)]
        proposals += [('c', item)
                      for item in self._completion_results.get('classes', [])
                      if item.startswith(prefix)]
        proposals += [
            ('a', item)
            for item in self._completion_results.get('attributes', [])
            if item.startswith(prefix)
        ]
        proposals += [
            ('f', item)
            for item in self._completion_results.get('functions', [])
            if item.startswith(prefix)
        ]
        if proposals and valid:
            self.complete(proposals)
        else:
            self.hide_completer()

    def _invalid_completion_position(self):
        result = False
        cursor = self._editor.textCursor()
        cursor.movePosition(QTextCursor.StartOfLine, QTextCursor.KeepAnchor)
        selection = cursor.selectedText()[:-1].split(' ')
        if len(selection) == 0 or selection[-1] == '' or \
           selection[-1].isdigit():
            result = True
        return result

    def fill_completer(self, force_completion=False):
        if not force_completion and (self._editor.cursor_inside_string()
                                     or self._editor.cursor_inside_comment()
                                     or self._invalid_completion_position()):
            return
        source = self._editor.get_text()
        source = source.encode(self._editor.encoding)
        offset = self._editor.textCursor().position()
        results = self.cc.get_completion(source, offset)
        self._completion_results = results
        if force_completion:
            cursor = self._editor.textCursor()
            cursor.movePosition(QTextCursor.StartOfWord,
                                QTextCursor.KeepAnchor)
            prefix = cursor.selectedText()
        else:
            prefix = self._editor._text_under_cursor()
        self.set_completion_prefix(prefix)

    def hide_completer(self):
        self._prefix = ''
        self.hide()

    def pre_key_insert_completion(self):
        type_ = ord('a')
        current = self.completion_list.currentItem()
        insert = current.text()
        if not insert.endswith(')'):
            type_ = current.type()
        self.insert_completion(insert, type_)
        self.hide_completer()
        return True

    def process_pre_key_event(self, event):
        if not self.isVisible() or self._editor.lang != "python":
            return False
        skip = self._key_operations.get(event.key(), lambda: False)()
        self._key_operations.get(event.modifiers(), lambda: False)()
        if skip is None:
            skip = False
        return skip

    def process_post_key_event(self, event):
        if not settings.CODE_COMPLETION or self._editor.lang != "python":
            return
        if self.isVisible():
            source = self._editor.get_text()
            source = source.encode(self._editor.encoding)
            offset = self._editor.textCursor().position()
            prefix, valid = self.cc.get_prefix(source, offset)
            self.set_completion_prefix(prefix, valid)
            self.completion_list.setCurrentRow(0)
        force_completion = (event.key() == Qt.Key_Space
                            and event.modifiers() == Qt.ControlModifier)
        if event.key() == Qt.Key_Period or force_completion:
            self.fill_completer(force_completion)
Пример #9
0
class Completer(QCompleter):
    def __init__(self, editor, project):
        QCompleter.__init__(self)

        self.icons = {
            'function': QIcon(resources.images['function']),
            'instance': QIcon(resources.images['attribute']),
            'module': QIcon(resources.images['module']),
            'class': QIcon(resources.images['class'])
        }

        self._editor = editor
        self._fromProject = False
        if project is not None:
            if type(project) is str:
                project = rope.base.project.Project(project, None,
                                                    '.ninjaproject')
            self._project = project
            self._fromProject = True
        else:
            self._project = rope.base.project.get_no_project()
        self.setWidget(self._editor)
        self.popupView = QListWidget()
        self.popupView.setAlternatingRowColors(True)
        self.popupView.setWordWrap(False)
        self.setPopup(self.popupView)
        self.setCompletionMode(QCompleter.PopupCompletion)
        self.setCaseSensitivity(Qt.CaseInsensitive)

        self.connect(self, SIGNAL("activated(QString)"),
                     self.insert_completion)

    def insert_completion(self, insert):
        extra = insert.length() - self.completionPrefix().length()
        self._editor.textCursor().insertText(insert.right(extra))

    def complete(self, cr):
        if self._project:
            try:
                self.popupView.clear()
                code = str(self._editor.toPlainText())
                start = self._editor.textCursor().position()
                if self._fromProject:
                    self._project.validate()
                proposals = codeassist.code_assist(self._project, code, start)
                proposals = codeassist.sorted_proposals(proposals)
                model = self.obtain_model_items(proposals)
                self.setModel(model)
                self.popup().setCurrentIndex(model.index(0, 0))
                cr.setWidth(self.popup().sizeHintForColumn(0) \
                    + self.popup().verticalScrollBar().sizeHint().width() + 10)
                self.popupView.updateGeometries()
                super(Completer, self).complete(cr)
            except:
                return

    def obtain_model_items(self, proposals):
        for p in proposals:
            if p.type == 'function':
                self.popupView.addItem(
                    QListWidgetItem(
                        self.icons[p.type], '%s(%s)' % (p.name, ', '.join([
                            n for n in p.pyname.get_object().get_param_names()
                            if n != 'self'
                        ]))))
            else:
                self.popupView.addItem(
                    QListWidgetItem(
                        self.icons.get(p.type, self.icons['class']), p.name))
        return self.popupView.model()

    def get_path_from_project(self):
        if self._fromProject:
            return self._project.root.real_path
        else:
            return None
Пример #10
0
class EkdConfigBox(QDialog) :
    """
    EkdConfigBox permet à l'utilisateur de configurer EkdConfig
    """
    def __init__(self, w=550, h=480, titre=u"Configuration de Ekd", parent=None):
        super(EkdConfigBox, self).__init__(parent)
        self.resize(w,h)
        self.w = w
        self.h = h
        self.setWindowTitle(titre)

        self.layout = QVBoxLayout(self)
        ## Menu contient l'ensemble des sections à paramétrer
        self.menu = QListWidget(self)
        self.layout.addWidget(self.menu)
        ## Pour chaque section à paramétrer, on utilise un Stack d'objets
        self.leftpart = QStackedLayout()
        self.leftpart.setSizeConstraint(QLayout.SetNoConstraint)
        self.layout.addLayout(self.leftpart)

        ## propWidget contient l'ensemble des objets propriété de toutes les section
        ## (il est nécessaire de les stocker pour être capable de les faire interagir)
        self.propWidget=[]
        wid = 0

        ## On crée les différentes parties de configuration qui ne sont pas inclues dans le tableau SECTION_MASK de EkdConfig
        for section in EkdConfig.SECTIONS :
            if not section in EkdConfig.SECTION_MASK :
                self.menu.addItem(EkdConfig.SECTIONS[section])
                allprops = EkdConfig.getAllProperties(EkdConfig.getConfigSection(section))
                scroll = QScrollArea()
                frame = QFrame()
                frame.setMinimumSize(self.w-50, self.h/2) # Ajouté le 10/12/2009 Pour que la partie réglage prenne toute la place dispo.
                frame.setMaximumSize(self.w, self.h)
                linelayout = QGridLayout(frame)

                linelayout.setSizeConstraint(QLayout.SetMinAndMaxSize)
                row = 0
                ## Insertion des propriété de la section en fonction de son type
                allkeys = allprops.keys()
                found = False
                for prop in allkeys :
                    if not prop in EkdConfig.PROPERTIES_MASK :
                        if prop in EkdConfig.PATH_PROPERTIES :
                            self.propWidget.append( EkdPathPropertie(prop, EkdConfig.PROPERTIES[prop], allprops[prop], section=section) )
                            linelayout.addWidget(self.propWidget[wid].label, row, 0)
                            linelayout.addWidget(self.propWidget[wid].widget, row, 1)
                            wid += 1
                            found = True
                        row += 1
                for prop in allkeys :
                    if not prop in EkdConfig.PROPERTIES_MASK :
                        if prop in EkdConfig.STYLE_PROPERTIES :
                            self.propWidget.append( EkdStylePropertie(prop, EkdConfig.PROPERTIES[prop], allprops[prop], EkdConfig.STYLE_PROPERTIES[prop], section=section ) )
                            linelayout.addWidget(self.propWidget[wid].label, row, 0)
                            linelayout.addWidget(self.propWidget[wid].widget, row, 1)
                            wid += 1
                            found = True
                        row += 1
                for prop in allkeys :
                    if not prop in EkdConfig.PROPERTIES_MASK :
                        if prop in EkdConfig.CODEC_PROPERTIES :
                            self.propWidget.append( EkdCodecPropertie(prop, EkdConfig.PROPERTIES[prop], allprops[prop], EkdConfig.CODEC_PROPERTIES[prop], section=section ) )
                            linelayout.addWidget(self.propWidget[wid].label, row, 0)
                            linelayout.addWidget(self.propWidget[wid].widget, row, 1)
                            wid += 1
                            found = True
                        row += 1
                for prop in allkeys :
                    if not prop in EkdConfig.PROPERTIES_MASK :
                        if prop in EkdConfig.BOOLEAN_PROPERTIES :
                            self.propWidget.append( EkdBoolPropertie(prop, EkdConfig.PROPERTIES[prop], allprops[prop], section=section) )
                            linelayout.addWidget(self.propWidget[wid].widget, row, 0, 1, 2)
                            wid += 1
                            found = True
                        row += 1
                for prop in allkeys :
                    if not prop in EkdConfig.PROPERTIES_MASK :
                        if prop in EkdConfig.NUM_PROPERTIES :
                            self.propWidget.append( EkdNumPropertie(prop, EkdConfig.PROPERTIES[prop], allprops[prop], section=section) )
                            linelayout.addWidget(self.propWidget[wid].label, row, 0)
                            linelayout.addWidget(self.propWidget[wid].widget, row, 1)
                            wid += 1
                            found = True
                        row += 1
                for prop in allkeys :
                    if not prop in EkdConfig.PROPERTIES_MASK :
                        if prop in EkdConfig.TIME_PROPERTIES :
                            self.propWidget.append( EkdTimePropertie(prop, EkdConfig.PROPERTIES[prop], allprops[prop], section=section) )
                            linelayout.addWidget(self.propWidget[wid].label, row, 0)
                            linelayout.addWidget(self.propWidget[wid].widget, row, 1)
                            wid += 1
                            found = True
                        row += 1
                for prop in allkeys :
                    if not prop in EkdConfig.PROPERTIES_MASK :
                        if prop in EkdConfig.COLOR_PROPERTIES :
                            self.propWidget.append( EkdColorPropertie(prop, EkdConfig.PROPERTIES[prop], allprops[prop], section=section) )
                            linelayout.addWidget(self.propWidget[wid].label, row, 0)
                            linelayout.addWidget(self.propWidget[wid].widget, row, 1)
                            wid += 1
                            found = True
                        elif not found:
                            line = QLineEdit(allprops[prop])
                            linelayout.addWidget(QLabel(prop), row, 0)
                            linelayout.addWidget(line, row, 1)
                        row += 1

                frame.setLineWidth(0)
                scroll.setWidget(frame)
                self.leftpart.addWidget(scroll)

        self.menu.setAlternatingRowColors(True)
        # Define the size of the list depending of its content
        self.menu.setFixedHeight(( self.menu.sizeHintForRow(0) + self.menu.verticalStepsPerItem() + 1)* self.menu.count())
        self.menu.updateGeometries()

        ## Boutton pour  fermer la boite de dialogue
        self.fermer = QPushButton(_(u"Fermer"))
        self.layout.addWidget(self.fermer)

        ## Lorsqu'on clique sur fermer, la fenêtre se ferme
        self.connect(self.fermer, SIGNAL("clicked()"), self.close)

        ## Lorsqu'on selectionne un élément du menu, on met à jour la partie droite du menu
        self.connect(self.menu, SIGNAL("currentItemChanged(QListWidgetItem *,QListWidgetItem *)"), self.updateMenu)

    def updateMenu(self):
        propriete = self.menu.currentRow()
        self.leftpart.setCurrentIndex(propriete)
Пример #11
0
class CodeCompletionWidget(QFrame):
    def __init__(self, editor):
        super(CodeCompletionWidget, self).__init__(None, Qt.FramelessWindowHint | Qt.ToolTip)
        self._editor = editor
        self.stack_layout = QStackedLayout(self)
        self.stack_layout.setContentsMargins(0, 0, 0, 0)
        self.stack_layout.setSpacing(0)
        self.completion_list = QListWidget()
        self.completion_list.setMinimumHeight(200)
        self.completion_list.setAlternatingRowColors(True)
        self._list_index = self.stack_layout.addWidget(self.completion_list)

        self._icons = {
            "a": resources.IMAGES["attribute"],
            "f": resources.IMAGES["function"],
            "c": resources.IMAGES["class"],
        }

        self.cc = code_completion.CodeCompletion()
        self._completion_results = []
        self._prefix = u""
        self.setVisible(False)
        self.source = ""
        self._key_operations = {
            Qt.Key_Up: self._select_previous_row,
            Qt.Key_Down: self._select_next_row,
            Qt.Key_PageUp: (lambda: self._select_previous_row(6)),
            Qt.Key_PageDown: (lambda: self._select_next_row(6)),
            Qt.Key_Right: lambda: None,
            Qt.Key_Left: lambda: None,
            Qt.Key_Enter: self.pre_key_insert_completion,
            Qt.Key_Return: self.pre_key_insert_completion,
            Qt.Key_Tab: self.pre_key_insert_completion,
            Qt.Key_Space: self.hide_completer,
            Qt.Key_Escape: self.hide_completer,
            Qt.Key_Backtab: self.hide_completer,
            Qt.NoModifier: self.hide_completer,
            Qt.ShiftModifier: self.hide_completer,
        }

        desktop = QApplication.instance().desktop()
        self._desktop_geometry = desktop.availableGeometry()

        self.connect(self._editor.document(), SIGNAL("blockCountChanged(int)"), self.update_metadata)

    def _select_next_row(self, move=1):
        new_row = self.completion_list.currentRow() + move
        if new_row < self.completion_list.count():
            self.completion_list.setCurrentRow(new_row)
        else:
            self.completion_list.setCurrentRow(0)
        return True

    def _select_previous_row(self, move=1):
        new_row = self.completion_list.currentRow() - move
        if new_row >= 0:
            self.completion_list.setCurrentRow(new_row)
        else:
            self.completion_list.setCurrentRow(self.completion_list.count() - move)
        return True

    def update_metadata(self):
        source = self._editor.get_text()
        source = source.encode(self._editor.encoding)
        self.cc.analyze_file("", source)

    def insert_completion(self, insert):
        if insert != self._prefix:
            extra = len(self._prefix) - len(insert)
            self._editor.textCursor().insertText(insert[extra:])
        self.hide_completer()

    def _get_geometry(self):
        cr = self._editor.cursorRect()
        point = self._editor.mapToGlobal(cr.topLeft())
        cr.moveTopLeft(point)
        # Check new position according desktop geometry
        width = (
            self.completion_list.sizeHintForColumn(0) + self.completion_list.verticalScrollBar().sizeHint().width() + 10
        )
        height = 200
        orientation = (point.y() + height) < self._desktop_geometry.height()
        if orientation:
            cr.moveTop(cr.bottom())
        cr.setWidth(width)
        cr.setHeight(height)
        if not orientation:
            cr.moveBottom(cr.top())
        xpos = self._desktop_geometry.width() - (point.x() + width)
        if xpos < 0:
            cr.moveLeft(cr.left() + xpos)
        return cr

    def complete(self, results):
        self.add_list_items(results)
        self.completion_list.setCurrentRow(0)
        cr = self._get_geometry()
        self.setGeometry(cr)
        self.completion_list.updateGeometries()
        self.show()

    def add_list_items(self, proposals):
        self.completion_list.clear()
        for p in proposals:
            self.completion_list.addItem(
                QListWidgetItem(QIcon(self._icons.get(p[0], resources.IMAGES["attribute"])), p[1])
            )

    def set_completion_prefix(self, prefix):
        self._prefix = prefix
        proposals = []
        proposals += [("c", item) for item in self.completion_results.get("classes", []) if item.startswith(prefix)]
        proposals += [("a", item) for item in self.completion_results.get("attributes", []) if item.startswith(prefix)]
        proposals += [("f", item) for item in self.completion_results.get("functions", []) if item.startswith(prefix)]
        if proposals:
            self.complete(proposals)
        else:
            self.hide_completer()

    def fill_completer(self):
        source = self._editor.get_text()
        source = source.encode(self._editor.encoding)
        offset = self._editor.textCursor().position()
        results = self.cc.get_completion(source, offset)
        self.completion_results = results
        prefix = self._editor._text_under_cursor()
        self.set_completion_prefix(prefix)

    def hide_completer(self):
        self._prefix = ""
        self.hide()

    def pre_key_insert_completion(self):
        insert = unicode(self.completion_list.currentItem().text())
        self.insert_completion(insert)
        self.hide_completer()
        return True

    def process_pre_key_event(self, event):
        if not self.isVisible():
            return False
        skip = self._key_operations.get(event.key(), lambda: False)()
        self._key_operations.get(event.modifiers(), lambda: False)()
        if skip is None:
            skip = False
        return skip

    def process_post_key_event(self, event):
        if not settings.CODE_COMPLETION or self._editor.lang != "python":
            return
        if self.isVisible():
            source = self._editor.get_text()
            source = source.encode(self._editor.encoding)
            offset = self._editor.textCursor().position()
            prefix = self.cc.get_prefix(source, offset)
            self.set_completion_prefix(prefix)
            self.completion_list.setCurrentRow(0)
        if event.key() == Qt.Key_Period or (event.key() == Qt.Key_Space and event.modifiers() == Qt.ControlModifier):
            self.fill_completer()
Пример #12
0
class CodeCompletionWidget(QFrame):
    def __init__(self, editor):
        super(CodeCompletionWidget,
              self).__init__(None, Qt.FramelessWindowHint | Qt.ToolTip)
        self._editor = editor
        self.stack_layout = QStackedLayout(self)
        self.stack_layout.setContentsMargins(0, 0, 0, 0)
        self.stack_layout.setSpacing(0)
        self.completion_list = QListWidget()
        self.completion_list.setMinimumHeight(200)
        self.completion_list.setAlternatingRowColors(True)
        self._list_index = self.stack_layout.addWidget(self.completion_list)

        self._icons = {
            'a': resources.IMAGES['attribute'],
            'f': resources.IMAGES['function'],
            'c': resources.IMAGES['class'],
            'm': resources.IMAGES['module']
        }

        self.cc = code_completion.CodeCompletion()
        self._completion_results = {}
        self._prefix = u''
        self.setVisible(False)
        self.source = ''
        self._key_operations = {
            Qt.Key_Up: self._select_previous_row,
            Qt.Key_Down: self._select_next_row,
            Qt.Key_PageUp: (lambda: self._select_previous_row(6)),
            Qt.Key_PageDown: (lambda: self._select_next_row(6)),
            Qt.Key_Right: lambda: None,
            Qt.Key_Left: lambda: None,
            Qt.Key_Enter: self.pre_key_insert_completion,
            Qt.Key_Return: self.pre_key_insert_completion,
            Qt.Key_Tab: self.pre_key_insert_completion,
            Qt.Key_Space: self.hide_completer,
            Qt.Key_Escape: self.hide_completer,
            Qt.Key_Backtab: self.hide_completer,
            Qt.NoModifier: self.hide_completer,
            Qt.ShiftModifier: self.hide_completer,
        }

        desktop = QApplication.instance().desktop()
        self._desktop_geometry = desktop.availableGeometry()

        self.connect(self._editor.document(), SIGNAL("blockCountChanged(int)"),
                     self.update_metadata)

    def _select_next_row(self, move=1):
        new_row = self.completion_list.currentRow() + move
        if new_row < self.completion_list.count():
            self.completion_list.setCurrentRow(new_row)
        else:
            self.completion_list.setCurrentRow(0)
        return True

    def _select_previous_row(self, move=1):
        new_row = self.completion_list.currentRow() - move
        if new_row >= 0:
            self.completion_list.setCurrentRow(new_row)
        else:
            self.completion_list.setCurrentRow(self.completion_list.count() -
                                               move)
        return True

    def update_metadata(self):
        source = self._editor.get_text()
        source = source.encode(self._editor.encoding)
        self.cc.analyze_file('', source)

    def insert_completion(self, insert):
        if insert != self._prefix:
            extra = len(self._prefix) - len(insert)
            self._editor.textCursor().insertText(insert[extra:])
        self.hide_completer()

    def _get_geometry(self):
        cr = self._editor.cursorRect()
        point = self._editor.mapToGlobal(cr.topLeft())
        cr.moveTopLeft(point)
        #Check new position according desktop geometry
        width = (self.completion_list.sizeHintForColumn(0) + \
            self.completion_list.verticalScrollBar().sizeHint().width() + 10)
        height = 200
        orientation = (point.y() + height) < self._desktop_geometry.height()
        if orientation:
            cr.moveTop(cr.bottom())
        cr.setWidth(width)
        cr.setHeight(height)
        if not orientation:
            cr.moveBottom(cr.top())
        xpos = self._desktop_geometry.width() - (point.x() + width)
        if xpos < 0:
            cr.moveLeft(cr.left() + xpos)
        return cr

    def complete(self, results):
        self.add_list_items(results)
        self.completion_list.setCurrentRow(0)
        cr = self._get_geometry()
        self.setGeometry(cr)
        self.completion_list.updateGeometries()
        self.show()

    def add_list_items(self, proposals):
        self.completion_list.clear()
        for p in proposals:
            self.completion_list.addItem(
                QListWidgetItem(
                    QIcon(self._icons.get(p[0],
                                          resources.IMAGES['attribute'])),
                    p[1]))

    def set_completion_prefix(self, prefix, valid=True):
        self._prefix = prefix
        proposals = []
        proposals += [('m', item) \
            for item in self._completion_results.get('modules', []) \
            if item.startswith(prefix)]
        proposals += [('c', item) \
            for item in self._completion_results.get('classes', []) \
            if item.startswith(prefix)]
        proposals += [('a', item) \
            for item in self._completion_results.get('attributes', []) \
            if item.startswith(prefix)]
        proposals += [('f', item) \
            for item in self._completion_results.get('functions', []) \
            if item.startswith(prefix)]
        if proposals and valid:
            self.complete(proposals)
        else:
            self.hide_completer()

    def fill_completer(self):
        source = self._editor.get_text()
        source = source.encode(self._editor.encoding)
        offset = self._editor.textCursor().position()
        results = self.cc.get_completion(source, offset)
        self._completion_results = results
        prefix = self._editor._text_under_cursor()
        self.set_completion_prefix(prefix)

    def hide_completer(self):
        self._prefix = ''
        self.hide()

    def pre_key_insert_completion(self):
        insert = unicode(self.completion_list.currentItem().text())
        self.insert_completion(insert)
        self.hide_completer()
        return True

    def process_pre_key_event(self, event):
        if not self.isVisible() or self._editor.lang != "python":
            return False
        skip = self._key_operations.get(event.key(), lambda: False)()
        self._key_operations.get(event.modifiers(), lambda: False)()
        if skip is None:
            skip = False
        return skip

    def process_post_key_event(self, event):
        if not settings.CODE_COMPLETION or self._editor.lang != "python":
            return
        if self.isVisible():
            source = self._editor.get_text()
            source = source.encode(self._editor.encoding)
            offset = self._editor.textCursor().position()
            prefix, valid = self.cc.get_prefix(source, offset)
            self.set_completion_prefix(prefix, valid)
            self.completion_list.setCurrentRow(0)
        if event.key() == Qt.Key_Period  or (event.key() == Qt.Key_Space and \
           event.modifiers() == Qt.ControlModifier):
            self.fill_completer()
Пример #13
0
class RRepositoryBrowser(QDialog):

    def __init__(self, pipe, parent=None):
        QDialog.__init__(self, parent)
        mirror = robjects.r.getOption('repos')
        contrib_url = robjects.r.get('contrib.url', mode='function')
        available_packages = robjects.r.get('available.packages', mode='function')
        self.setWindowTitle("manageR - Install R Packages")
        self.setWindowIcon(QIcon(":icon"))
        p = available_packages()
        self.pipe = pipe
        self.names = QStringList(p.rownames)
        self.parent = parent
        self.packageList = QListWidget(self)
        self.packageList.setAlternatingRowColors(True)
        self.packageList.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.packageList.setSortingEnabled(True)
        self.packageList.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.packageList.setToolTip("Select packages to install")
        self.packageList.setWhatsThis("List of packages available on CRAN")
        self.packageList.insertItems(0, self.names)
        self.dependCheckbox = QCheckBox(self)
        self.dependCheckbox.setText("Install all dependencies")
        self.dependCheckbox.setChecked(True)
        self.closeCheckbox = QCheckBox(self)
        self.closeCheckbox.setText("Close dialog on completion")
        self.closeCheckbox.setChecked(False)
        filterEdit = QLineEdit(self)
        filterLabel = QLabel("Filter packages", self)
        self.outputEdit = QTextEdit(self)
        self.outputEdit.setReadOnly(True)
        self.outputEdit.setVisible(False)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Close)
        self.buttonBox.addButton("Details >>", QDialogButtonBox.ActionRole)
        vbox = QVBoxLayout(self)
        hbox = QHBoxLayout()
        hbox.addWidget(filterLabel)
        hbox.addWidget(filterEdit)
        vbox.addLayout(hbox)
        vbox.addWidget(self.dependCheckbox)
        vbox.addWidget(self.packageList)
        vbox.addWidget(self.closeCheckbox)
        vbox.addWidget(self.outputEdit)
        vbox.addWidget(self.buttonBox)
        self.started = False
        self.setMinimumSize(80,50)

        self.connect(filterEdit, SIGNAL("textChanged(QString)"), self.filterPackages)
        #self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        self.connect(self.buttonBox, SIGNAL("clicked(QAbstractButton*)"), self.buttonClicked)

    def buttonClicked(self, button):
        if button.text() == "Details >>":
            self.showDetails()
            button.setText("Details <<")
        elif button.text() == "Details <<":
            self.hideDetails()
            button.setText("Details >>")
        if not self.started:
            if self.buttonBox.standardButton(button) == QDialogButtonBox.Apply:
                self.installPackages()
            else:
                self.reject()

    def showDetails(self):
        self.outputEdit.setVisible(True)

    def hideDetails(self):
        self.outputEdit.setVisible(False)

    def filterPackages(self, text):
        self.packageList.clear()
        self.packageList.insertItems(0, self.names.filter(QRegExp(r"^%s" % text)))
        firstItem = self.packageList.item(0)
        if firstItem.text().startsWith(text):
            self.packageList.setCurrentItem(firstItem)
#        else:
#            self.packageList.clearSelection()

    def currentPackages(self):
        return [unicode(item.text()) for item in self.packageList.selectedItems()]

    def installPackages(self):
        pkgs = self.currentPackages()
        count = len(pkgs)
        if count < 1:
            QMessageBox.warning(self, "manageR - Warning",
            "Please choose at least one valid package")
            return False
        pkgs = QStringList(pkgs).join("','")
        checked = self.dependCheckbox.isChecked()
        if checked: depends = "TRUE"
        else: depends = "FALSE"
        self.pipe.send("install.packages(c('%s'), dependencies=%s, repos=%s)" 
            % (pkgs, depends, robjects.r.getOption("repos")))
        self.started = True
        self.startTimer(30)
        return True

    def timerEvent(self, e):
        if self.started:
            try:
                output = self.pipe.recv()
                if output is None:
                    self.started=False
                    self.killTimer(e.timerId())
                else:
                    self.printOutput(output)
            except EOFError:
                pass
        QApplication.processEvents()

    def printOutput(self, output):
        self.outputEdit.insertPlainText(output)
        self.outputEdit.ensureCursorVisible()
Пример #14
0
class Completer(QCompleter):

    def __init__(self, editor, project):
        QCompleter.__init__(self)

        self.icons = {'function': QIcon(resources.images['function']),
            'instance': QIcon(resources.images['attribute']),
            'module': QIcon(resources.images['module']),
            'class': QIcon(resources.images['class'])}

        self._editor = editor
        self._fromProject = False
        if project is not None:
            if type(project) is str:
                project = rope.base.project.Project(project, None, '.ninjaproject')
            self._project = project
            self._fromProject = True
        else:
            self._project = rope.base.project.get_no_project()
        self.setWidget(self._editor)
        self.popupView = QListWidget()
        self.popupView.setAlternatingRowColors(True)
        self.popupView.setWordWrap(False)
        self.setPopup(self.popupView)
        self.setCompletionMode(QCompleter.PopupCompletion)
        self.setCaseSensitivity(Qt.CaseInsensitive)

        self.connect(self, SIGNAL("activated(QString)"), self.insert_completion)

    def insert_completion(self, insert):
        extra = insert.length() - self.completionPrefix().length()
        self._editor.textCursor().insertText(insert.right(extra))

    def complete(self, cr):
        if self._project:
            try:
                self.popupView.clear()
                code = str(self._editor.toPlainText())
                start = self._editor.textCursor().position()
                if self._fromProject:
                    self._project.validate()
                proposals = codeassist.code_assist(self._project, code, start)
                proposals = codeassist.sorted_proposals(proposals)
                model = self.obtain_model_items(proposals)
                self.setModel(model)
                self.popup().setCurrentIndex(model.index(0, 0))
                cr.setWidth(self.popup().sizeHintForColumn(0) \
                    + self.popup().verticalScrollBar().sizeHint().width() + 10)
                self.popupView.updateGeometries()
                super(Completer, self).complete(cr)
            except:
                return

    def obtain_model_items(self, proposals):
        for p in proposals:
            if p.type == 'function':
                self.popupView.addItem(QListWidgetItem(self.icons[p.type], 
                    '%s(%s)' % (p.name, ', '.join(
                    [n for n in p.pyname.get_object().get_param_names() if n != 'self']))))
            else:
                self.popupView.addItem(QListWidgetItem(
                    self.icons.get(p.type, self.icons['class']), p.name))
        return self.popupView.model()

    def get_path_from_project(self):
        if self._fromProject:
            return self._project.root.real_path
        else:
            return None
Пример #15
0
class SeriesPreview(QDialog):

    def __init__(self, parent=None):
        super(SeriesPreview, self).__init__(parent)

        self.data = None
        self.workingSet = None

        self.list = QListWidget()
        self.cancel = QPushButton('Close')
        self.apply = QPushButton('Update')

        self.layout = QGridLayout()
        self.layout.addWidget(self.list, 0, 0, 1, 2)
        self.layout.addWidget(self.apply, 1, 0)
        self.layout.addWidget(self.cancel, 1, 1)
        self.setLayout(self.layout)

        self.initComponents()
        self.initActions()

    def initComponents(self):
        self.setWindowFlags(Qt.Tool)
        self.setWindowTitle("Time series")

        self.setStyleSheet('''QPushButton {
                                color: #333;
                                border: 1px solid #555;
                                border-radius: 11px;
                                padding: 2px;
                                background: qradialgradient(cx: 0.3, cy: -0.4,
                                fx: 0.3, fy: -0.4,
                                radius: 1.35, stop: 0 #fff, stop: 1 #888);
                                min-width: 80px;
                            }
                            QPushButton:hover {
                                color: #fff;
                                background: qradialgradient(cx: 0.3, cy: -0.4,
                                fx: 0.3, fy: -0.4,
                                radius: 1.35, stop: 0 #fff, stop: 1 #bbb);}
                            QPushButton:pressed {
                                background: qradialgradient(cx: 0.4, cy: -0.1,
                                fx: 0.4, fy: -0.1,
                                radius: 1.35, stop: 0 #fff, stop: 1 #ddd);}
                            QPushButton:checked {
                                background: qradialgradient(cx: 0.4, cy: -0.1,
                                fx: 0.4, fy: -0.1,
                                radius: 1.35, stop: 0 #fff, stop: 1 #ddd);}
                            QListView::focus {
                                border: 2px solid black;
                                border-radius: 6px;
                            }
                            QScrollBar:vertical {
                              width: 20px;
                              border: 1px solid grey;
                              border-radius: 6px;
                              background-color: transparent;
                              margin: 28px 0 28px 0;
                            }
                            QScrollBar::add-line:vertical {
                              background: transparent;
                              height: 32px;
                              subcontrol-position: bottom;
                              subcontrol-origin: margin;
                            }
                            QScrollBar::sub-line:vertical {
                              background: transparent;
                              height: 32px;
                              subcontrol-position: top;
                              subcontrol-origin: margin;
                            }
                            QScrollBar::up-arrow:vertical {
                              width: 20px;
                              height: 32px;
                              background: transparent;
                              image: url(../res/icons/arrow_up.png);
                            }
                            QScrollBar::up-arrow:hover {
                              bottom: 2px;
                            }
                            QScrollBar::down-arrow:vertical {
                              width: 20px;
                              height: 32px;
                              background: transparent;
                              image: url(../res/icons/arrow_down.png);
                            }
                            QScrollBar::down-arrow:hover {
                              top: 2px;
                            }
                            QScrollBar::handle:vertical {
                                border-radius: 6px;
                                background: url(../res/icons/handle.png) 0% center no-repeat;
                                background-color: white;
                                min-height: 32px;
                            }
                            QScrollBar::handle:hover {
                                background: url(../res/icons/handle_hover.png) 0% center no-repeat;
                                background-color: white;
                                border: 1px solid gray;
                            }''')

        self.list.setAlternatingRowColors(True)
        self.list.setStyleSheet('''QListView::item:selected:active {
                 background: qlineargradient(x1: 1, y1: 0, x2: 0, y2: 3, stop: 0 #cbdaf1, stop: 1 #bfcde4);
            }
            QListView::item {
                border: 1px solid #d9d9d9;
                border-top-color: transparent;
                border-bottom-color: transparent;
            }
            QListView::item:hover {
                 background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #e7effd, stop: 1 #cbdaf1);
                 border: 1px solid #bfcde4;
            }''')

        self.list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.list.setContextMenuPolicy(Qt.ActionsContextMenu)

    def initActions(self):
        self.apply.clicked.connect(self.applyChanges)
        self.cancel.clicked.connect(self.close)

        self.list.itemDoubleClicked.connect(self.removeFromList)
        self.list.addAction(QAction('&Remove selected', self, triggered=self.removeItems))

    #--- actions ---#
    def updateData(self, data):
        self.data = data
        self.workingSet = data[0][:]
        self.updateList()

    def updateList(self):
        self.list.clear()
        for item in self.workingSet:
            item = QListWidgetItem(str(item))
            item.setTextAlignment(Qt.AlignCenter)
            self.list.addItem(item)

    def applyChanges(self):
        self.data = (self.workingSet, self.data[1])

    def removeFromList(self, item):
        self.workingSet.remove(float(item.text()))
        self.list.takeItem(self.list.indexFromItem(item).row())

    def removeItems(self):
        for item in self.list.selectedItems():
            self.workingSet.remove(float(item.text()))
            self.list.takeItem(self.list.indexFromItem(item).row())
Пример #16
0
class ProjectPropertiesDialog( QDialog, object ):
    """ project properties dialog implementation """

    def __init__( self, project = None, parent = None ):

        QDialog.__init__( self, parent )

        # The dialog caller reads this member if the dialog was finished
        # successfully.
        self.absProjectFileName = None

        self.__createLayout()
        self.__project = project

        if project is None:
            # It a new project creation
            self.setWindowTitle( "New Project Properties" )

            userRecord = pwd.getpwuid( os.getuid() )

            if not userRecord[ 5 ].endswith( os.path.sep ):
                self.dirEdit.setText( userRecord[ 5 ] + os.path.sep )
            else:
                self.dirEdit.setText( userRecord[ 5 ] )
            self.initialDirName = self.dirEdit.text()
            self.lastProjectName = ""

            if userRecord[ 4 ] != "":
                self.authorEdit.setText( userRecord[ 4 ].split( ',' )[ 0 ].strip() )
            else:
                self.authorEdit.setText( userRecord[ 0 ] )

            try:
                self.emailEdit.setText( userRecord[ 0 ] +
                                        "@" + socket.gethostname() )
            except:
                pass

            self.versionEdit.setText( "0.0.1" )
            self.licenseEdit.setText( "GPL v3" )
            self.copyrightEdit.setText( "Copyright (c) " +
                                        self.authorEdit.text() + ", " +
                                        str( datetime.date.today().year ) )
            self.creationDateEdit.setText( getLocaleDate() )
            self.nameEdit.setFocus()

        elif type( project ) == type( "" ):
            self.setWindowTitle( "Viewing Project Properties" )

            # This is viewing properties and the argument is the path to the
            # project file
            scriptName, importDirs, creationDate, author, lic, \
            copy_right, description, \
            version, email, uuid = getProjectProperties( project )

            if not os.path.isabs( scriptName ) and scriptName != "":
                scriptName = os.path.normpath( os.path.dirname( project ) +
                                               os.path.sep + scriptName )

            self.nameEdit.setText( os.path.basename( project ) )
            self.nameEdit.setToolTip( "" )
            self.dirEdit.setText( os.path.dirname( project ) )
            self.dirEdit.setToolTip( "" )
            self.scriptEdit.setText( scriptName )
            self.versionEdit.setText( version )
            self.authorEdit.setText( author )
            self.emailEdit.setText( email )
            self.licenseEdit.setText( lic )
            self.copyrightEdit.setText( copy_right )
            self.descriptionEdit.setText( description )
            self.creationDateEdit.setText( creationDate )
            self.uuidEdit.setText( str( uuid ) )
            self.uuidEdit.setToolTip( settingsDir + str( uuid ) + os.path.sep +
                                      " (double click to copy path)"  )

            for item in importDirs:
                self.importDirList.addItem( item )

            self.disableEditing()

        else:
            self.setWindowTitle( "Editing Project Properties" )

            # This is editing the loaded project.
            self.nameEdit.setText( os.path.basename( project.fileName ) )
            self.nameEdit.setToolTip( "" )
            self.dirEdit.setText( project.getProjectDir() )
            self.dirEdit.setToolTip( "" )
            self.scriptEdit.setText( project.getProjectScript() )
            self.versionEdit.setText( project.version )
            self.authorEdit.setText( project.author )
            self.emailEdit.setText( project.email )
            self.licenseEdit.setText( project.license )
            self.copyrightEdit.setText( project.copyright )
            self.descriptionEdit.setText( project.description )
            self.creationDateEdit.setText( project.creationDate )
            self.uuidEdit.setText( str( project.uuid ) )
            self.uuidEdit.setToolTip( project.userProjectDir +
                                      " (double click to copy path)" )
            self.setReadOnly()

            for item in project.importDirs:
                self.importDirList.addItem( item )
            if self.importDirList.count() > 0:
                self.importDirList.setCurrentRow( 0 )
                self.delImportDirButton.setEnabled( True )

            # The project could be the one belonging to another user
            # so there might be no write permissions.
            if not os.access( project.fileName, os.W_OK ):
                # Disable editing
                self.setWindowTitle( "Viewing Project Properties (no write permissions)" )
                self.disableEditing()
            else:
                self.scriptEdit.setFocus()

        return

    def __createLayout( self ):
        """ Creates the dialog layout """

        self.resize( 600, 400 )
        self.setSizeGripEnabled( True )

        verticalLayout = QVBoxLayout( self )
        gridLayout = QGridLayout()

        # Project name
        nameLabel = QLabel( self )
        nameLabel.setText( "Project name:" )
        gridLayout.addWidget( nameLabel, 0, 0, 1, 1 )
        self.nameEdit = QLineEdit( self )
        self.nameEdit.setToolTip( "Type a project name without a path" )
        self.nameEdit.installEventFilter( self )
        gridLayout.addWidget( self.nameEdit, 0, 1, 1, 1 )

        # Project dir
        dirLabel = QLabel( self )
        dirLabel.setText( "Project directory:" )
        gridLayout.addWidget( dirLabel, 1, 0, 1, 1 )
        self.dirEdit = QLineEdit( self )
        self.dirEdit.setToolTip( "Not existed directories will be created" )
        gridLayout.addWidget( self.dirEdit, 1, 1, 1, 1 )
        self.dirButton = QPushButton( self )
        self.dirButton.setText( "..." )
        gridLayout.addWidget( self.dirButton, 1, 2, 1, 1 )
        self.dirCompleter = DirCompleter( self.dirEdit )

        # Project script
        mainScriptLabel = QLabel( "Main script:", self )
        gridLayout.addWidget( mainScriptLabel, 2, 0, 1, 1 )
        self.scriptEdit = QLineEdit( self )
        self.scriptEdit.setToolTip( "Project main script, "
                                    "used when the project is run" )
        gridLayout.addWidget( self.scriptEdit, 2, 1, 1, 1 )
        self.scriptButton = QPushButton( "...", self )
        gridLayout.addWidget( self.scriptButton, 2, 2, 1, 1 )
        self.fileCompleter = FileCompleter( self.scriptEdit )

        # Import dirs
        importLabel = QLabel( self )
        importLabel.setText( "Import directories:" )
        importLabel.setAlignment( Qt.AlignTop )
        gridLayout.addWidget( importLabel, 3, 0, 1, 1 )
        self.importDirList = QListWidget( self )
        self.importDirList.setAlternatingRowColors( True )
        self.importDirList.setSelectionMode( QAbstractItemView.SingleSelection )
        self.importDirList.setSelectionBehavior( QAbstractItemView.SelectRows )
        self.importDirList.setItemDelegate( NoOutlineHeightDelegate( 4 ) )
        self.importDirList.setToolTip( "Directories where to look for "
                                       "project specific imports" )
        gridLayout.addWidget( self.importDirList, 3, 1, 1, 1 )

        self.addImportDirButton = QPushButton( self )
        self.addImportDirButton.setText( "Add dir" )
        self.delImportDirButton = QPushButton( self )
        self.delImportDirButton.setText( "Delete dir" )
        self.delImportDirButton.setEnabled( False )
        vLayout = QVBoxLayout()
        vLayout.addWidget( self.addImportDirButton )
        vLayout.addWidget( self.delImportDirButton )
        vLayout.addStretch( 0 )
        gridLayout.addLayout( vLayout, 3, 2, 1, 1 )

        # Version
        versionLabel = QLabel( self )
        versionLabel.setText( "Version:" )
        gridLayout.addWidget( versionLabel, 4, 0, 1, 1 )
        self.versionEdit = QLineEdit( self )
        gridLayout.addWidget( self.versionEdit, 4, 1, 1, 1 )

        # Author
        authorLabel = QLabel( self )
        authorLabel.setText( "Author:" )
        gridLayout.addWidget( authorLabel, 5, 0, 1, 1 )
        self.authorEdit = QLineEdit( self )
        gridLayout.addWidget( self.authorEdit, 5, 1, 1, 1 )

        # E-mail
        emailLabel = QLabel( self )
        emailLabel.setText( "E-mail:" )
        gridLayout.addWidget( emailLabel, 6, 0, 1, 1 )
        self.emailEdit = QLineEdit( self )
        gridLayout.addWidget( self.emailEdit, 6, 1, 1, 1 )

        # License
        licenseLabel = QLabel( self )
        licenseLabel.setText( "License:" )
        gridLayout.addWidget( licenseLabel, 7, 0, 1, 1 )
        self.licenseEdit = QLineEdit( self )
        gridLayout.addWidget( self.licenseEdit, 7, 1, 1, 1 )

        # Copyright
        copyrightLabel = QLabel( self )
        copyrightLabel.setText( "Copyright:" )
        gridLayout.addWidget( copyrightLabel, 8, 0, 1, 1 )
        self.copyrightEdit = QLineEdit( self )
        gridLayout.addWidget( self.copyrightEdit, 8, 1, 1, 1 )

        # Description
        descriptionLabel = QLabel( self )
        descriptionLabel.setText( "Description:" )
        descriptionLabel.setAlignment( Qt.AlignTop )
        gridLayout.addWidget( descriptionLabel, 9, 0, 1, 1 )
        self.descriptionEdit = QTextEdit( self )
        self.descriptionEdit.setTabChangesFocus( True )
        self.descriptionEdit.setAcceptRichText( False )
        gridLayout.addWidget( self.descriptionEdit, 9, 1, 1, 1 )

        # Creation date
        creationDateLabel = QLabel( self )
        creationDateLabel.setText( "Creation date:" )
        gridLayout.addWidget( creationDateLabel, 10, 0, 1, 1 )
        self.creationDateEdit = FramedLabelWithDoubleClick()
        self.creationDateEdit.setToolTip( "Double click to copy" )
        gridLayout.addWidget( self.creationDateEdit, 10, 1, 1, 1 )

        # Project UUID
        uuidLabel = QLabel( self )
        uuidLabel.setText( "UUID:" )
        gridLayout.addWidget( uuidLabel, 11, 0, 1, 1 )
        self.uuidEdit = FramedLabelWithDoubleClick( "", self.__copyProjectPath )
        gridLayout.addWidget( self.uuidEdit, 11, 1, 1, 1 )

        verticalLayout.addLayout( gridLayout )

        # Buttons at the bottom
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Cancel | \
                                      QDialogButtonBox.Ok )
        verticalLayout.addWidget( buttonBox )

        nameLabel.setBuddy( self.nameEdit )
        dirLabel.setBuddy( self.dirEdit )
        versionLabel.setBuddy( self.versionEdit )
        authorLabel.setBuddy( self.authorEdit )
        emailLabel.setBuddy( self.emailEdit )
        licenseLabel.setBuddy( self.licenseEdit )
        copyrightLabel.setBuddy( self.copyrightEdit )
        descriptionLabel.setBuddy( self.descriptionEdit )

        buttonBox.accepted.connect( self.onOKButton )
        buttonBox.rejected.connect( self.reject )
        self.dirButton.clicked.connect( self.onDirButton )
        self.scriptButton.clicked.connect( self.onScriptButton )
        self.importDirList.currentRowChanged.connect( self.onImportDirRowChanged )
        self.addImportDirButton.clicked.connect( self.onAddImportDir )
        self.delImportDirButton.clicked.connect( self.onDelImportDir )
        self.nameEdit.textEdited.connect( self.onProjectNameChanged )

        self.setTabOrder( self.nameEdit, self.dirEdit )
        self.setTabOrder( self.dirEdit, self.dirButton )
        self.setTabOrder( self.dirButton, self.scriptEdit )
        self.setTabOrder( self.scriptEdit, self.scriptButton )
        self.setTabOrder( self.scriptButton, self.importDirList )
        self.setTabOrder( self.importDirList, self.addImportDirButton )
        self.setTabOrder( self.addImportDirButton, self.delImportDirButton )
        self.setTabOrder( self.delImportDirButton, self.versionEdit )
        self.setTabOrder( self.versionEdit, self.authorEdit )
        self.setTabOrder( self.authorEdit, self.emailEdit )
        self.setTabOrder( self.emailEdit, self.licenseEdit )
        self.setTabOrder( self.licenseEdit, self.copyrightEdit )
        self.setTabOrder( self.copyrightEdit, self.descriptionEdit )
        self.setTabOrder( self.descriptionEdit, buttonBox )
        return

    def eventFilter( self, obj, event ):
        " Event filter for the project name field "

        # Do not allow path separators
        if event.type() == QEvent.KeyPress:
            if event.key() == ord( os.path.sep ):
                return True
        return QObject.eventFilter( self, obj, event )


    def onDirButton( self ):
        " Displays a directory selection dialog "

        dirName = QFileDialog.getExistingDirectory( self,
                    "Select project directory",
                    self.dirEdit.text(),
                    QFileDialog.Options( QFileDialog.ShowDirsOnly ) )

        if dirName:
            self.dirEdit.setText( os.path.normpath( dirName ) )
        return

    def onScriptButton( self ):
        " Displays a file selection dialog "
        scriptName = QFileDialog.getOpenFileName( self,
                        "Select project main script",
                        self.dirEdit.text() )

        if scriptName:
            self.scriptEdit.setText( os.path.normpath( scriptName ) )
        return

    def onImportDirRowChanged( self, row ):
        " Triggered when a current row in the import dirs is changed "
        self.delImportDirButton.setEnabled( row != -1 )
        return

    def onAddImportDir( self ):
        " Displays a directory selection dialog "

        dirName = QFileDialog.getExistingDirectory( self,
                    "Select import directory",
                    self.dirEdit.text(),
                    QFileDialog.Options( QFileDialog.ShowDirsOnly ) )

        if not dirName:
            return

        # There are 2 cases: new project or
        # editing the existed project properties
        if self.__project is None:
            # It a new project; the project path could be editedd
            dirToInsert = dirName
        else:
            # This is an existed project; no way the project path is changed
            # Let's decide it a relative path should be used here
            if self.__project.isProjectDir( dirName ):
                dirToInsert = relpath( dirName, self.dirEdit.text() )
            else:
                dirToInsert = dirName

        index = 0
        while index < self.importDirList.count():
            if self.importDirList.item( index ).text() == dirToInsert:
                logging.warning( "The directory '" + dirName +
                                 "' is already in the list of "
                                 "imported directories and is not added." )
                return
            index += 1

        self.importDirList.addItem( dirToInsert )
        self.importDirList.setCurrentRow( self.importDirList.count() - 1 )
        return

    def onDelImportDir( self ):
        " Triggered when an import dir should be deleted "

        rowToDelete = self.importDirList.currentRow()
        if  rowToDelete == -1:
            self.delImportDirButton.setEnabled( False )
            return

        self.importDirList.takeItem( rowToDelete )
        if self.importDirList.count() == 0:
            self.delImportDirButton.setEnabled( False )
        else:
            self.importDirList.setCurrentRow( self.importDirList.count() - 1 )
        return

    def onOKButton( self ):
        " Checks that the mandatory fields are filled properly "

        # The checks must be done for a new project only
        if not self.nameEdit.isEnabled():
            self.accept()
            return

        # Check that the project name does not have path separators and is not
        # empty
        if not self.nameEdit.text().strip():
            QMessageBox.critical( self, "Error",
                                  "The project name must not be empty" )
            return
        if os.path.sep in self.nameEdit.text():
            QMessageBox.critical( self, "Error",
                                  "The project name must not "
                                  "contain path separators" )
            return

        # Check that the project directory is given
        dirName = self.dirEdit.text().strip()
        if not dirName:
            QMessageBox.critical( self, "Error",
                                  "The project directory must not be empty" )
            return

        dirName = os.path.abspath( dirName )
        self.dirEdit.setText( dirName )
        # Check that the project file does not exist
        projectFileName = dirName
        if not projectFileName.endswith( os.path.sep ):
            projectFileName += os.path.sep
        projectFileName += self.nameEdit.text().strip()
        if not projectFileName.endswith( ".cdm" ):
            projectFileName += ".cdm"

        if os.path.exists( projectFileName ):
            QMessageBox.critical( self, "Error",
                                  "The project file " + projectFileName +
                                  " exists. Please provide another "
                                  "directory / project name." )
            return

        # Check that the project dir is not a file
        if os.path.exists( dirName ):
            # It might be a link, so read it first
            dirName = os.path.realpath( dirName )
            if not os.path.exists( dirName ):
                QMessageBox.critical( self, "Error",
                                      "Broken link: " + dirName )
                return
            if not os.path.isdir( dirName ):
                QMessageBox.critical( self, "Error",
                                      "The project directory "
                                      "may not be a file" )
                return
            # Check that the dir is writable
            if not os.access( dirName, os.W_OK ):
                QMessageBox.critical( self, "Error",
                                      "You don't have write permissions on " +
                                      dirName )
                return
        else:
            # Create the directory
            try:
                os.makedirs( dirName )
            except OSError:
                QMessageBox.critical( self, "Error",
                                      "Cannot create the project directory" )
                return

        # Save the absolute file name for further reading it by the caller
        self.absProjectFileName = projectFileName

        # The minimum is provided so we can accept it
        self.accept()
        return

    def onProjectNameChanged( self, newName ):
        " Called when the project name changed "

        if newName.endswith( ".cdm" ):
            newName = newName[ :-4 ]
        if self.dirEdit.text().strip() == (self.initialDirName +
                                           self.lastProjectName):
            self.dirEdit.setText( self.initialDirName + newName )
            self.lastProjectName = newName
        return

    def setReadOnly( self ):
        """ Disables editing some fields """

        self.dirEdit.setReadOnly( True )
        self.dirEdit.setFocusPolicy( Qt.NoFocus )
        self.dirEdit.setDisabled( True )
        self.dirButton.setDisabled( True )
        self.dirButton.setFocusPolicy( Qt.NoFocus )
        self.nameEdit.setReadOnly( True )
        self.nameEdit.setFocusPolicy( Qt.NoFocus )
        self.nameEdit.setDisabled( True )
        return

    def disableEditing( self ):
        " Disables all the editing "

        self.nameEdit.setDisabled( True )
        self.dirEdit.setDisabled( True )
        self.dirButton.setDisabled( True )
        self.scriptEdit.setDisabled( True )
        self.scriptButton.setDisabled( True )
        self.importDirList.setDisabled( True )
        self.addImportDirButton.setDisabled( True )
        self.delImportDirButton.setDisabled( True )
        self.versionEdit.setDisabled( True )
        self.authorEdit.setDisabled( True )
        self.emailEdit.setDisabled( True )
        self.licenseEdit.setDisabled( True )
        self.copyrightEdit.setDisabled( True )
        self.descriptionEdit.setDisabled( True )
        return

    def __copyProjectPath( self ):
        " Copies the project path when a label is double clicked "
        text = self.uuidEdit.text().strip()
        if text:
            path = settingsDir + text + os.path.sep
            QApplication.clipboard().setText( path )
        return
Пример #17
0
if config_options['translucent background']:
    main_window.setAttribute(Qt.WA_TranslucentBackground)
main_window.setWindowFlags(Qt.FramelessWindowHint)
main_window.show()

layout = QVBoxLayout(main_window)

search_bar = QLineEdit()
search_bar.textChanged.connect(searcher.search)
search_bar.returnPressed.connect(launch_first_item)

layout.addWidget(search_bar)

result_list_widget = QListWidget()
result_list_widget.setIconSize(QSize(*(config_options['icon size'],) * 2))
result_list_widget.setAlternatingRowColors(True)
result_list_widget.setTextElideMode(Qt.ElideMiddle)
result_list_widget.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)
result_list_widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
result_list_widget.itemActivated.connect(launch_item)

# Prepare alternating row colors for transparency
palette = result_list_widget.palette()
color = palette.brush(QPalette.Base).color()
color.setAlphaF(0.9)
palette.setBrush(QPalette.Base, QBrush(color))
color = palette.brush(QPalette.AlternateBase).color()
color.setAlphaF(0.5)
palette.setBrush(QPalette.AlternateBase, QBrush(color))
main_window.setPalette(palette)