Esempio n. 1
0
 def parent(self, index):
     '''
     @param: index QModelIndex
     @return: QModelIndex
     '''
     return QModelIndex()
Esempio n. 2
0
 def rowCount(self, parent=QModelIndex()):
     return len(self.filtered_searches)
Esempio n. 3
0
 def parent(self, index):
     if not index.isValid() or index.internalId() == 0:
         return QModelIndex()
     return self.createIndex(index.internalId()-1, 0, 0)
Esempio n. 4
0
 def hide(self):
     self.setCurrentIndex(QModelIndex())
     QListView.hide(self)
Esempio n. 5
0
 def rowCount(self, parent=QModelIndex()):
     return len(self.jobs)
Esempio n. 6
0
    def flags(self, index: Qt.QModelIndex) -> Qt.Qt.ItemFlags:
        if not index.isValid():
            return cast(Qt.Qt.ItemFlags, Qt.Qt.ItemIsEnabled)

        return cast(Qt.Qt.ItemFlags,
                    super().flags(index) | Qt.Qt.ItemIsEditable)
Esempio n. 7
0
 def rowCount(self, parent=QModelIndex()):
     return 11 if self.is_half_star else 6
Esempio n. 8
0
 def columnCount(self, parent=QModelIndex()):
     return 5
Esempio n. 9
0
    def update(self, plot_data_collection, bd_option, interp_option, bd_plot):
        # reset the model in the first place and set data afterwards appropriately
        self.beginResetModel()
        self.reset_model()
        self.endResetModel()

        # there is no need to calculate a bd for just one curve
        if len(plot_data_collection) < 2:
            plt.close()
            return

        seq_set = set()
        config_set = set()
        identifier_list = []
        for i in plot_data_collection:
            # there is no reason for calculating a bjontegaard, if we want to plot
            # several variables from the same sequence and config, so return in that case
            # otherwise append the identifiers to the list and go on
            if identifier_list.__contains__(i.identifiers):
                return
            identifier_list.append(i.identifiers)

            seq_set.add(i.identifiers[0])
            config_set.add('+'.join(i.identifiers[1:]))
        seq_set = sorted(seq_set)
        config_set = sorted(config_set)

        if len(seq_set) > 1:
            plt.close()
            bd_plot = True

        # there is no need to calculate a bjontegaard delta, if only one configuration is loaded
        if len(config_set) < 2:
            plt.close()
            return
        elif len(config_set) > 5 and (not bd_plot):
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Information)
            msg.setText(
                "Your BD plot will contain more than 5 curves, do you really want to continue?"
            )
            msg.setWindowTitle("Info")
            msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
            result = msg.exec()

            if result == QMessageBox.Cancel:
                plt.close()
                bd_plot = True

        self._horizontal_headers = list(config_set)
        self._vertical_headers = list(seq_set)
        self._vertical_headers.append('AVG')

        # insert as many columns as we need for the selected data
        self.beginInsertColumns(QModelIndex(), 0, len(config_set) - 1)
        self.insertColumns(0, len(config_set), QModelIndex())
        self.endInsertColumns()

        # insert as many rows as we need for the selected data
        # and add one row for the average
        self.beginInsertRows(QModelIndex(), 0, len(seq_set))
        self.insertRows(0, len(seq_set), QModelIndex())
        self.endInsertRows()

        self._plot_data_collection = plot_data_collection

        self._data = np.zeros((len(seq_set) + 1, len(config_set)))

        if all(collection.label == ("kbps", "dB")
               for collection in plot_data_collection):
            self.update_table(bd_option, interp_option, 0, bd_plot)
        else:
            self.beginResetModel()
            self.reset_model()
            self.endResetModel()
            plt.close()
Esempio n. 10
0
 def setEditorData(self, editor: QWidget, index: QModelIndex) -> None:
     conf = index.data(role=Qt.EditRole)
     editor.config = conf
     super().setEditorData(editor, index)
Esempio n. 11
0
    def onClickEdit(self):
        if (self.ui.cBTable.currentIndex() == 0):
            indMovie = self.ui.tableView.model().index(
                self.ui.tableView.currentIndex().row(), 0, QModelIndex())
            oldMovieName = self.ui.tableView.model().data(indMovie)
            indDirector = self.ui.tableView.model().index(
                self.ui.tableView.currentIndex().row(), 1, QModelIndex())
            oldDirectorName = self.ui.tableView.model().data(indDirector)
            indActors = self.ui.tableView.model().index(
                self.ui.tableView.currentIndex().row(), 2, QModelIndex())
            oldActorsName = self.ui.tableView.model().data(indActors)
            if (self.ui.tableView.currentIndex() == indMovie):
                movieName, ok = QInputDialog.getText(
                    self, 'Редактирование', 'Введите название фильма')
                if (not (ok)):
                    return
                query = QtSql.QSqlQuery()
                query.prepare("{CALL editMovie(?, ?)}")
                query.bindValue(0, oldMovieName)
                query.bindValue(1, movieName)
                query.exec()
            if (self.ui.tableView.currentIndex() == indDirector):
                directorName, ok = QInputDialog.getText(
                    self, 'Редактирование', 'Введите имя режиссера')
                if (not (ok)):
                    return
                query = QtSql.QSqlQuery()
                query.prepare("{CALL editMovieDirector(?, ?)}")
                query.bindValue(0, directorName)
                query.bindValue(1, oldMovieName)
                query.exec()

            if (self.ui.tableView.currentIndex() == indActors):
                actorsName, ok = QInputDialog.getText(
                    self, 'Редактирование',
                    'Введите имя актеров через запятую')
                if (not (ok)):
                    return
                query = QtSql.QSqlQuery()
                actorsNameList = oldActorsName.split(', ')
                for actorNameStr in actorsNameList:
                    query.prepare("{CALL deleteActorsMovie(?, ?)}")
                    query.bindValue(0, oldMovieName)
                    query.bindValue(1, actorNameStr)
                    query.exec()

                actorsNameList = actorsName.split(', ')
                for actorNameStr in actorsNameList:
                    query.prepare("{CALL editMovieActors(?, ?, ?)}")
                    query.bindValue(0, actorNameStr)
                    query.bindValue(1, oldActorsName)
                    query.bindValue(2, oldMovieName)
                    query.exec()

        if (self.ui.cBTable.currentIndex() == 1):
            ind = self.ui.tableView.model().index(
                self.ui.tableView.currentIndex().row(), 0, QModelIndex())
            directorName, ok = QInputDialog.getText(self, 'Редактирование',
                                                    'Введите имя режиссера')
            if (not (ok)):
                return
            query = QtSql.QSqlQuery()
            query.prepare("{CALL editDirector(?, ?)}")
            query.bindValue(0, self.ui.tableView.model().data(ind))
            query.bindValue(1, directorName)
            query.exec()

        if (self.ui.cBTable.currentIndex() == 2):
            ind = self.ui.tableView.model().index(
                self.ui.tableView.currentIndex().row(), 0, QModelIndex())
            actorName, ok = QInputDialog.getText(self, 'Редактирование',
                                                 'Введите имя актера')
            if (not (ok)):
                return
            query = QtSql.QSqlQuery()
            query.prepare("{CALL editActor(?, ?)}")
            query.bindValue(0, self.ui.tableView.model().data(ind))
            query.bindValue(1, actorName)
            query.exec()
Esempio n. 12
0
    def eventFilter(self, obj, event):  # noqa C901
        '''
        @param obj QObject
        @param event QEvent
        @return: bool
        '''
        # Event filter based on QCompleter::eventFilter from qcompleter.cpp
        if obj == self or obj == self._view or not self.isVisible():
            return False

        evtType = event.type()
        if obj == self._view.viewport():
            if evtType == QEvent.MouseButtonRelease:
                # QMouseEvent
                e = event
                index = self._view.indexAt(e.pos())
                if not index.isValid():
                    return False

                # Qt::MouseButton
                button = e.button()
                # Qt::KeyboardModifiers
                modifiers = e.modifiers()

                if button == Qt.LeftButton and modifiers == Qt.NoModifier:
                    self.indexActivated.emit(index)
                    return True

                if button == Qt.MiddleButton or (button == Qt.LeftButton
                                                 and modifiers
                                                 == Qt.ControlModifier):
                    self.indexCtrlActivated.emit(index)
                    return True

                if button == Qt.LeftButton and modifiers == Qt.ShiftModifier:
                    self.indexShiftActivated.emit(index)
                    return True

            return False

        if evtType == QEvent.KeyPress:
            # QKeyEvent
            keyEvent = event
            evtKey = keyEvent.key()
            modifiers = keyEvent.modifiers()
            index = self._view.currentIndex()
            item = self.model().index(0, 0)
            if item.data(LocationCompleterModel.VisitSearchItemRole):
                visitSearchIndex = item
            else:
                visitSearchIndex = QModelIndex()

            if (evtKey == Qt.Key_Up or evtKey == Qt.Key_Down) and \
                    self._view.currentIndex() != index:
                self._view.setCurrentIndex(index)  # TODO: ?

            if evtKey in (Qt.Key_Return, Qt.Key_Enter):
                if index.isValid():
                    if modifiers == Qt.NoModifier or modifiers == Qt.KeypadModifier:
                        self.indexActivated.emit(index)
                        return True

                    if modifiers == Qt.ControlModifier:
                        self.indexCtrlActivated.emit(index)
                        return True

                    if modifiers == Qt.ShiftModifier:
                        self.indexShiftActivated.emit(index)
                        return True

            elif evtKey == Qt.Key_End:
                if modifiers & Qt.ControlModifier:
                    self._view.setCurrentIndex(self.model().index(
                        self.model().rowCount() - 1, 0))
                    return True
                else:
                    self.close()

            elif evtKey == Qt.Key_Home:
                if modifiers & Qt.ControlModifier:
                    self._view.setCurrentIndex(self.model().index(0, 0))
                    self._view.scrollToTop()
                    return True
                else:
                    self.close()

            elif evtKey == Qt.Key_Escape:
                self.close()
                return True

            elif evtKey == Qt.Key_F4:
                if modifiers == Qt.AltModifier:
                    self.close()
                    return False

            elif evtKey in (Qt.Key_Tab, Qt.Key_Backtab):
                if modifiers != Qt.NoModifier and modifiers != Qt.ShiftModifier:
                    return False
                isBack = evtKey == Qt.Key_Backtab
                if evtKey == Qt.Key_Tab and modifiers == Qt.ShiftModifier:
                    isBack = True
                ev = QKeyEvent(QKeyEvent.KeyPress, isBack and Qt.Key_Up
                               or Qt.Key_Down, Qt.NoModifier)
                QApplication.sendEvent(self.focusProxy(), ev)
                return True

            elif evtKey in (Qt.Key_Up, Qt.Key_PageUp):
                if modifiers != Qt.NoModifier:
                    return False
                step = evtKey == Qt.Key_PageUp and 5 or 1
                if not index.isValid() or index == visitSearchIndex:
                    rowCount = self.model().rowCount()
                    lastIndex = self.model().index(rowCount - 1, 0)
                    self._view.setCurrentIndex(lastIndex)
                elif index.row() == 0:
                    self._view.setCurrentIndex(QModelIndex())
                else:
                    row = max(0, index.row() - step)
                    self._view.setCurrentIndex(self.model().index(row, 0))
                return True

            elif evtKey in (Qt.Key_Down, Qt.Key_PageDown):
                if modifiers != Qt.NoModifier:
                    return False
                step = evtKey == Qt.Key_PageDown and 5 or 1
                if not index.isValid():
                    firstIndex = self.model().index(0, 0)
                    self._view.setCurrentIndex(firstIndex)
                elif index != visitSearchIndex and index.row(
                ) == self.model().rowCount() - 1:
                    self._view.setCurrentIndex(visitSearchIndex)
                    self._view.scrollToTop()
                else:
                    row = min(self.model().rowCount() - 1, index.row() + step)
                    self._view.setCurrentIndex(self.model().index(row, 0))
                return True

            elif evtKey == Qt.Key_Delete:
                if index != visitSearchIndex and self._view.viewport().rect(
                ).contains(self._view.visualRect(index)):
                    self.indexDeleteRequested.emit(index)
                    return True

            elif evtKey == Qt.Key_Shift:
                self._delegate.setForceVisitItem(True)
                self._view.viewport().update()

            # end of switch evtKey

            if self.focusProxy():
                self.focusProxy().event(keyEvent)

            return True

        elif evtType == QEvent.KeyRelease:
            if event.key() == Qt.Key_Shift:
                self._delegate.setForceVisitItem(False)
                self._view.viewport().update()
                return True

        elif evtType in (QEvent.Wheel, QEvent.MouseButtonPress):
            if not self.underMouse():
                self.close()
                return False

        elif evtType == QEvent.FocusOut:
            # QFocusEvent
            focusEvent = event
            reason = focusEvent.reason()
            if reason != Qt.PopupFocusReason and reason != Qt.MouseFocusReason:
                self.close()

        elif evtType in (QEvent.Move, QEvent.Resize):
            w = obj
            if isinstance(w, QWidget) and w.isWindow() and self.focusProxy(
            ) and w == self.focusProxy().window():
                self.close()

        # end of switch evtType
        return False
Esempio n. 13
0
 def __init__(self, tab=None, index=QModelIndex()):
     self._tab = tab
     self._sourceIndex = index
     self._children = []  # QVector<TabMruModelItem>
Esempio n. 14
0
 def parent(self, index):
     return self._nodes[
         index.internalId()] if index.isValid() else QModelIndex()
Esempio n. 15
0
 def rowCount(self, index: QModelIndex = QModelIndex()):
     return len(self._data)
Esempio n. 16
0
 def plugin_to_index(self, display_plugin):
     for i, p in enumerate(self.display_plugins):
         if display_plugin == p:
             return self.index(i, 0, QModelIndex())
     return QModelIndex()
Esempio n. 17
0
 def index(self, row: int, column: int = 0, parent: QModelIndex = QModelIndex()):
     return self.createIndex(row, column)
Esempio n. 18
0
 def hide_all(self, *args):
     self.model.hide_jobs(list(xrange(0,
         self.model.rowCount(QModelIndex()))))
     self.proxy_model.beginResetModel(), self.proxy_model.endResetModel()
Esempio n. 19
0
 def addNewEntry(self):
     self.beginInsertRows(QModelIndex(), len(self._data), len(self._data) + 1)
     self._data.append(types.ServerConfig.default())
     self.endInsertRows()
     return len(self._data) - 1
Esempio n. 20
0
    def setData(self,
                index: Qt.QModelIndex,
                value: Any,
                role: int = Qt.Qt.EditRole) -> bool:
        from copy import deepcopy

        if not index.isValid():
            return False
        if role not in (Qt.Qt.EditRole, Qt.Qt.UserRole):
            return False

        row = index.row()
        column = index.column()
        scene = deepcopy(self.items[row])

        if column == self.START_FRAME_COLUMN:
            if not isinstance(value, Frame):
                raise TypeError
            if scene.start != scene.end:
                if value > scene.end:
                    return False
                scene.start = value
            else:
                scene.start = value
                scene.end = value
            proper_update = True
        elif column == self.END_FRAME_COLUMN:
            if not isinstance(value, Frame):
                raise TypeError
            if scene.start != scene.end:
                if value < scene.start:
                    return False
                scene.end = value
            else:
                scene.start = value
                scene.end = value
            proper_update = True
        elif column == self.START_TIME_COLUMN:
            if not isinstance(value, Time):
                raise TypeError
            frame = Frame(value)
            if scene.start != scene.end:
                if frame > scene.end:
                    return False
                scene.start = frame
            else:
                scene.start = frame
                scene.end = frame
            proper_update = True
        elif column == self.END_TIME_COLUMN:
            if not isinstance(value, Time):
                raise TypeError
            frame = Frame(value)
            if scene.start != scene.end:
                if frame < scene.start:
                    return False
                scene.end = frame
            else:
                scene.start = frame
                scene.end = frame
            proper_update = True
        elif column == self.LABEL_COLUMN:
            if not isinstance(value, str):
                raise TypeError
            scene.label = value
            proper_update = False

        if proper_update is True:
            i = bisect_right(self.items, scene)
            if i > row:
                i -= 1
            if i != row:
                self.beginMoveRows(self.createIndex(row, 0), row, row,
                                   self.createIndex(i, 0), i)
                del self.items[row]
                self.items.insert(i, scene)
                self.endMoveRows()
            else:
                self.items[index.row()] = scene
                self.dataChanged.emit(index, index)
        else:
            self.items[index.row()] = scene
            self.dataChanged.emit(index, index)
        return True
Esempio n. 21
0
 def removeEntry(self, row: int):
     if self.hasIndex(row, 0):
         self.beginRemoveRows(QModelIndex(), row, row)
         del self._data[row]
         self.endRemoveRows()
Esempio n. 22
0
    def paint(self, painter, option, index):
        QStyledItemDelegate.paint(
            self, painter, option,
            QModelIndex())  # draw the hover and selection highlights
        m = index.model()
        db = m.db
        try:
            book_id = db.id(index.row())
        except (ValueError, IndexError, KeyError):
            return
        if book_id in m.ids_to_highlight_set:
            painter.save()
            try:
                painter.setPen(self.highlight_color)
                painter.setRenderHint(QPainter.Antialiasing, True)
                painter.drawRoundedRect(option.rect, 10, 10, Qt.RelativeSize)
            finally:
                painter.restore()
        marked = db.data.get_marked(book_id)
        db = db.new_api
        cdata = self.cover_cache[book_id]
        device_connected = self.parent().gui.device_connected is not None
        on_device = device_connected and db.field_for('ondevice', book_id)

        emblem_rules = db.pref('cover_grid_icon_rules', default=())
        emblems = []
        if self.emblem_size > 0:
            mi = None
            for i, (kind, column, rule) in enumerate(emblem_rules):
                icon_name, mi = self.render_emblem(book_id, rule, i,
                                                   m.cover_grid_emblem_cache,
                                                   mi, db, m.formatter,
                                                   m.cover_grid_template_cache)
                if icon_name is not None:
                    pixmap = self.cached_emblem(m.cover_grid_bitmap_cache,
                                                icon_name)
                    if pixmap is not None:
                        emblems.append(pixmap)
            if marked:
                emblems.insert(
                    0,
                    self.cached_emblem(m.cover_grid_bitmap_cache, ':marked',
                                       m.marked_icon))
            if on_device:
                emblems.insert(
                    0,
                    self.cached_emblem(m.cover_grid_bitmap_cache, ':ondevice'))

        painter.save()
        right_adjust = 0
        try:
            rect = option.rect
            rect.adjust(self.MARGIN, self.MARGIN, -self.MARGIN, -self.MARGIN)
            if self.emblem_size > 0:
                self.paint_emblems(painter, rect, emblems)
            orect = QRect(rect)
            if cdata is None or cdata is False:
                title = db.field_for('title', book_id, default_value='')
                authors = ' & '.join(
                    db.field_for('authors', book_id, default_value=()))
                painter.setRenderHint(QPainter.TextAntialiasing, True)
                painter.drawText(rect, Qt.AlignCenter | Qt.TextWordWrap,
                                 '%s\n\n%s' % (title, authors))
                if cdata is False:
                    self.render_queue.put(book_id)
            else:
                if self.title_height != 0:
                    trect = QRect(rect)
                    rect.setBottom(rect.bottom() - self.title_height)
                if self.animating is not None and self.animating.row(
                ) == index.row():
                    cdata = cdata.scaled(cdata.size() * self._animated_size)
                dx = max(0, int((rect.width() - cdata.width()) / 2.0))
                dy = max(0, rect.height() - cdata.height())
                right_adjust = dx
                rect.adjust(dx, dy, -dx, 0)
                painter.drawPixmap(rect, cdata)
                if self.title_height != 0:
                    rect = trect
                    rect.setTop(rect.bottom() - self.title_height + 5)
                    painter.setRenderHint(QPainter.TextAntialiasing, True)
                    title = self.render_field(db, book_id)
                    metrics = painter.fontMetrics()
                    painter.setPen(self.highlight_color)
                    painter.drawText(
                        rect, Qt.AlignCenter | Qt.TextSingleLine,
                        metrics.elidedText(title, Qt.ElideRight, rect.width()))
            if self.emblem_size > 0:
                return  # We dont draw embossed emblems as the ondevice/marked emblems are drawn in the gutter
            if marked:
                try:
                    p = self.marked_emblem
                except AttributeError:
                    p = self.marked_emblem = m.marked_icon.pixmap(48, 48)
                self.paint_embossed_emblem(p, painter, orect, right_adjust)

            if on_device:
                try:
                    p = self.on_device_emblem
                except AttributeError:
                    p = self.on_device_emblem = QPixmap(I('ok.png')).scaled(
                        48, 48, transformMode=Qt.SmoothTransformation)
                self.paint_embossed_emblem(p,
                                           painter,
                                           orect,
                                           right_adjust,
                                           left=False)
        finally:
            painter.restore()
Esempio n. 23
0
 def _is_index_valid(self, index: QModelIndex) -> bool:
     if index.row() < 0 or index.row() >= self.rowCount(
     ) or not index.isValid():
         return False
     return True
Esempio n. 24
0
from calibre.gui2.preferences import ConfigWidgetBase, test_widget, AbortCommit
from calibre.gui2.preferences.tweaks_ui import Ui_Form
from calibre.gui2 import error_dialog, info_dialog
from calibre.utils.config import read_raw_tweaks, write_tweaks
from calibre.gui2.widgets import PythonHighlighter
from calibre import isbytestring
from calibre.utils.icu import lower
from calibre.utils.search_query_parser import (ParseException,
                                               SearchQueryParser)

from PyQt5.Qt import (QAbstractListModel, Qt, QStyledItemDelegate, QStyle,
                      QStyleOptionViewItem, QFont, QDialogButtonBox, QDialog,
                      QApplication, QVBoxLayout, QPlainTextEdit, QLabel,
                      QModelIndex, QMenu, QIcon)

ROOT = QModelIndex()


class AdaptSQP(SearchQueryParser):
    def __init__(self, *args, **kwargs):
        pass


class Delegate(QStyledItemDelegate):  # {{{
    def __init__(self, view):
        QStyledItemDelegate.__init__(self, view)
        self.view = view

    def paint(self, p, opt, idx):
        copy = QStyleOptionViewItem(opt)
        copy.showDecorationSelected = True
Esempio n. 25
0
 def index(self, row, column, parent=QModelIndex()):
     return self.createIndex(row, column)
Esempio n. 26
0
    def clear(self):
        """Remove all items except the *root* item from the tree."""

        for child in self.root:
            self.remove_item(self.root[child], QModelIndex())
Esempio n. 27
0
 def get_ids_from_selected_rows():
     rows = self.gui.library_view.selectionModel().selectedRows()
     if not rows or len(rows) < 2:
         rows = xrange(self.gui.library_view.model().rowCount(QModelIndex()))
     ids = map(self.gui.library_view.model().id, rows)
     return ids