Exemplo n.º 1
0
    def __init__(self, motor, glpane):

        QWidget.__init__(self)
        self.setupUi(self)      
        self.connect(self.cancel_btn,SIGNAL("clicked()"),self.reject)
        self.connect(self.ok_btn,SIGNAL("clicked()"),self.accept)
        self.connect(self.choose_color_btn,SIGNAL("clicked()"),self.change_jig_color)
        self.connect(self.lengthLineEdit,SIGNAL("returnPressed()"),self.change_motor_size)
        self.connect(self.radiusLineEdit,SIGNAL("returnPressed()"),self.change_motor_size)
        self.connect(self.sradiusLineEdit,SIGNAL("returnPressed()"),self.change_motor_size)
        self.jig = motor
        self.glpane = glpane
        self.nameLineEdit.setWhatsThis("""<b>Name</b><p>Name of Rotary Motor that appears in the Model
        Tree</p>""")
        self.torqueLineEdit.setWhatsThis("""<b>Torque </b><p>Simulations will begin with the motor's torque
        set to this value.</p>""")
        self.speedLineEdit.setWhatsThis("""<b>Final Speed</b><p>The final velocity of the motor's flywheel
        during simulations.</p>""")
        self.initialSpeedLineEdit.setWhatsThis("""<b>Initial Speed</b><p>Simulations will begin with the motor's
        flywheel rotating at this velocity.</p>""")
        self.dampers_textlabel.setWhatsThis("""<b>Dampers</b><p>If checked, the dampers are enabled for this
        motor during a simulation. See the Rotary Motor web page on the NanoEngineer-1 Wiki for more information.</p>""")
        self.textLabel1_5.setWhatsThis("""<b>Enable in Minimize <i>(experimental)</i></b><p>If checked,
        the torque specified above will be applied to the motor atoms during a structure minimization.  While intended to allow simulations
        to begin with rotary motors running at speed, this feature requires more work to be useful.</p>""")
        self.dampers_checkbox.setWhatsThis("""<b>Dampers</b><p>If checked, the dampers are enabled for this
        motor during a simulation. See the Rotary Motor web page on the NanoEngineer-1 Wiki for more information.</p>""")
        self.enable_minimize_checkbox.setWhatsThis("""<b>Enable in Minimize <i>(experimental)</i></b><p>If checked,
        the torque specified above will be applied to the motor atoms during a structure minimization.  While intended to allow simulations
        to begin with rotary motors running at speed, this feature requires more work to be useful.</p>""")
Exemplo n.º 2
0
    def make_widgets(self, parent, main_widget_class, extra_label_text=''):
        w = QWidget(parent)
        self.widgets = [QLabel('&'+self.col_metadata['name']+':', w), w]
        l = QHBoxLayout()
        l.setContentsMargins(0, 0, 0, 0)
        w.setLayout(l)
        self.main_widget = main_widget_class(w)
        l.addWidget(self.main_widget)
        l.setStretchFactor(self.main_widget, 10)
        self.a_c_checkbox = QCheckBox(_('Apply changes'), w)
        l.addWidget(self.a_c_checkbox)
        self.ignore_change_signals = True

        # connect to the various changed signals so we can auto-update the
        # apply changes checkbox
        if hasattr(self.main_widget, 'editTextChanged'):
            # editable combobox widgets
            self.main_widget.editTextChanged.connect(self.a_c_checkbox_changed)
        if hasattr(self.main_widget, 'textChanged'):
            # lineEdit widgets
            self.main_widget.textChanged.connect(self.a_c_checkbox_changed)
        if hasattr(self.main_widget, 'currentIndexChanged'):
            # combobox widgets
            self.main_widget.currentIndexChanged[int].connect(self.a_c_checkbox_changed)
        if hasattr(self.main_widget, 'valueChanged'):
            # spinbox widgets
            self.main_widget.valueChanged.connect(self.a_c_checkbox_changed)
        if hasattr(self.main_widget, 'dateTimeChanged'):
            # dateEdit widgets
            self.main_widget.dateTimeChanged.connect(self.a_c_checkbox_changed)
Exemplo n.º 3
0
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     self._layout = l = QGridLayout()
     self.setLayout(self._layout)
     self.header = QLabel(_('Double click on any entry to change the'
         ' keyboard shortcuts associated with it'))
     l.addWidget(self.header, 0, 0, 1, 3)
     self.view = QTreeView(self)
     self.view.setAlternatingRowColors(True)
     self.view.setHeaderHidden(True)
     self.view.setAnimated(True)
     l.addWidget(self.view, 1, 0, 1, 3)
     self.delegate = Delegate()
     self.view.setItemDelegate(self.delegate)
     self.delegate.sizeHintChanged.connect(self.editor_opened,
             type=Qt.QueuedConnection)
     self.delegate.changed_signal.connect(self.changed_signal)
     self.search = SearchBox2(self)
     self.search.initialize('shortcuts_search_history',
             help_text=_('Search for a shortcut by name'))
     self.search.search.connect(self.find)
     l.addWidget(self.search, 2, 0, 1, 1)
     self.nb = QPushButton(QIcon(I('arrow-down.png')), _('&Next'), self)
     self.pb = QPushButton(QIcon(I('arrow-up.png')), _('&Previous'), self)
     self.nb.clicked.connect(self.find_next)
     self.pb.clicked.connect(self.find_previous)
     l.addWidget(self.nb, 2, 1, 1, 1)
     l.addWidget(self.pb, 2, 2, 1, 1)
     l.setColumnStretch(0, 100)
Exemplo n.º 4
0
    def __init__(self, gui):
        QWidget.__init__(self, gui)
        self.setObjectName('jobs_pointer')
        self.setVisible(False)
        self.resize(100, 80)
        self.animation = QPropertyAnimation(self, "geometry", self)
        self.animation.setDuration(750)
        self.animation.setLoopCount(2)
        self.animation.setEasingCurve(QEasingCurve.Linear)
        self.animation.finished.connect(self.hide)

        taily, heady = 0, 55
        self.arrow_path = QPainterPath(QPointF(40, taily))
        self.arrow_path.lineTo(40, heady)
        self.arrow_path.lineTo(20, heady)
        self.arrow_path.lineTo(50, self.height())
        self.arrow_path.lineTo(80, heady)
        self.arrow_path.lineTo(60, heady)
        self.arrow_path.lineTo(60, taily)
        self.arrow_path.closeSubpath()

        c = self.palette().color(QPalette.Active, QPalette.WindowText)
        self.color = QColor(c)
        self.color.setAlpha(100)
        self.brush = QBrush(self.color, Qt.SolidPattern)
Exemplo n.º 5
0
    def __init__(self, plugin, parent):
        QWidget.__init__(self, parent)

        self.plugin = plugin

        self.l = l = QVBoxLayout()
        self.setLayout(l)
        self.c = c = QLabel(_('<b>Configure %(name)s</b><br>%(desc)s') % dict(
            name=plugin.name, desc=plugin.description))
        c.setAlignment(Qt.AlignHCenter)
        l.addWidget(c)

        self.config_widget = plugin.config_widget()
        self.l.addWidget(self.config_widget)

        self.bb = QDialogButtonBox(
                QDialogButtonBox.Save|QDialogButtonBox.Cancel,
                parent=self)
        self.bb.accepted.connect(self.finished)
        self.bb.rejected.connect(self.finished)
        self.bb.accepted.connect(self.commit)
        l.addWidget(self.bb)

        self.f = QFrame(self)
        self.f.setFrameShape(QFrame.HLine)
        l.addWidget(self.f)
Exemplo n.º 6
0
        def paintEvent(self, event):
            contents_y = self.edit.verticalScrollBar().value()
            page_bottom = contents_y + self.edit.viewport().height()
            font_metrics = self.fontMetrics()

            painter = QPainter(self)

            line_count = 0

            block = self.edit.document().begin()

            while block.isValid():
                line_count += 1

                # The top left position of the block in the document
                position = self.edit.document().documentLayout().blockBoundingRect(block).topLeft()

                # Check if the position of the block is out side of the visible
                # area.
                if position.y() > page_bottom:
                    break

                # Draw the line number right justified at the y position of the
                # line. 3 is a magic padding number. drawText(x, y, text).
                painter.drawText(-5 + self.width() - font_metrics.width(str(line_count)) - 3,
                                round(position.y()) - contents_y + font_metrics.ascent(),
                                str(line_count))

                block = block.next()

            self.highest_line = line_count
            painter.end()

            QWidget.paintEvent(self, event)
Exemplo n.º 7
0
    def setup_store_checks(self):
        first_run = self.config.get('first_run', True)

        # Add check boxes for each store so the user
        # can disable searching specific stores on a
        # per search basis.
        existing = {}
        for n in self.store_checks:
            existing[n] = self.store_checks[n].isChecked()

        self.store_checks = {}

        stores_check_widget = QWidget()
        store_list_layout = QGridLayout()
        stores_check_widget.setLayout(store_list_layout)

        icon = QIcon(I('donate.png'))
        for i, x in enumerate(sorted(self.gui.istores.keys(), key=lambda x: x.lower())):
            cbox = QCheckBox(x)
            cbox.setChecked(existing.get(x, first_run))
            store_list_layout.addWidget(cbox, i, 0, 1, 1)
            if self.gui.istores[x].base_plugin.affiliate:
                iw = QLabel(self)
                iw.setToolTip('<p>' + _('Buying from this store supports the calibre developer: %s</p>') % self.gui.istores[x].base_plugin.author + '</p>')
                iw.setPixmap(icon.pixmap(16, 16))
                store_list_layout.addWidget(iw, i, 1, 1, 1)
            self.store_checks[x] = cbox
        store_list_layout.setRowStretch(store_list_layout.rowCount(), 10)
        self.store_list.setWidget(stores_check_widget)

        self.config['first_run'] = False
Exemplo n.º 8
0
    def __init__(self, name, plugins, gui_name, parent=None):
        QWidget.__init__(self, parent)
        self._layout = QVBoxLayout()
        self.setLayout(self._layout)
        self.label = QLabel(gui_name)
        self.sep = QFrame(self)
        self.bf = QFont()
        self.bf.setBold(True)
        self.label.setFont(self.bf)
        self.sep.setFrameShape(QFrame.HLine)
        self._layout.addWidget(self.label)
        self._layout.addWidget(self.sep)

        self.plugins = plugins

        self.bar = QToolBar(self)
        self.bar.setStyleSheet(
                'QToolBar { border: none; background: none }')
        self.bar.setIconSize(QSize(32, 32))
        self.bar.setMovable(False)
        self.bar.setFloatable(False)
        self.bar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self._layout.addWidget(self.bar)
        self.actions = []
        for p in plugins:
            target = partial(self.triggered, p)
            ac = self.bar.addAction(QIcon(p.icon), p.gui_name, target)
            ac.setToolTip(textwrap.fill(p.description))
            ac.setWhatsThis(textwrap.fill(p.description))
            ac.setStatusTip(p.description)
            self.actions.append(ac)
            w = self.bar.widgetForAction(ac)
            w.setCursor(Qt.PointingHandCursor)
            w.setAutoRaise(True)
            w.setMinimumWidth(100)
Exemplo n.º 9
0
        def update(self, *args):
            width = self.fontMetrics().width(str(self.highest_line)) + 4

            if self.width() != width:
                self.setFixedWidth(width + 15)

            QWidget.update(self, *args)
Exemplo n.º 10
0
class MainWindowMixin(object):  # {{{

    def __init__(self, db):
        self.setObjectName('MainWindow')
        self.setWindowIcon(QIcon(I('lt.png')))
        self.setWindowTitle(__appname__)

        self.setContextMenuPolicy(Qt.NoContextMenu)
        self.centralwidget = QWidget(self)
        self.setCentralWidget(self.centralwidget)
        self._central_widget_layout = QVBoxLayout()
        self.centralwidget.setLayout(self._central_widget_layout)
        self.resize(1012, 740)
        self.donate_button = ThrobbingButton()
        self.location_manager = LocationManager(self)

        self.iactions['Fetch News'].init_scheduler(db)

        self.search_bar = SearchBar(self)
        self.bars_manager = BarsManager(self.donate_button,
                self.location_manager, self)
        for bar in self.bars_manager.main_bars:
            self.addToolBar(Qt.TopToolBarArea, bar)
        for bar in self.bars_manager.child_bars:
            self.addToolBar(Qt.BottomToolBarArea, bar)
        self.bars_manager.update_bars()
        # This is disabled because it introduces various toolbar related bugs
        # The width of the toolbar becomes the sum of both toolbars
        if tweaks['unified_title_toolbar_on_osx']:
            self.setUnifiedTitleAndToolBarOnMac(True)

        l = self.centralwidget.layout()
        l.addWidget(self.search_bar)
Exemplo n.º 11
0
    def __init__(self, preview, parent=None):
        QWidget.__init__(self, parent)
        self.preview = preview
        self.preview_is_refreshing = False
        self.refresh_needed = False
        preview.refresh_starting.connect(self.preview_refresh_starting)
        preview.refreshed.connect(self.preview_refreshed)
        self.apply_theme()
        self.setAutoFillBackground(True)
        self.update_timer = QTimer(self)
        self.update_timer.timeout.connect(self.update_data)
        self.update_timer.setSingleShot(True)
        self.update_timer.setInterval(500)
        self.now_showing = (None, None, None)

        self.stack = s = QStackedLayout(self)
        self.setLayout(s)

        self.clear_label = la = QLabel('<h3>' + _(
            'No style information found') + '</h3><p>' + _(
                'Move the cursor inside a HTML tag to see what styles'
                ' apply to that tag.'))
        la.setWordWrap(True)
        la.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        s.addWidget(la)

        self.box = box = Box(self)
        box.hyperlink_activated.connect(self.goto_declaration, type=Qt.QueuedConnection)
        self.scroll = sc = QScrollArea(self)
        sc.setWidget(box)
        sc.setWidgetResizable(True)
        s.addWidget(sc)
Exemplo n.º 12
0
    def __init__(self):
        QWidget.__init__(self)
        self.ui = Ui_InstallWidget()
        self.ui.setupUi(self)

        self.installProgress = InstallProgressWidget(self)

        self.timer = QTimer(self)
        QObject.connect(self.timer, SIGNAL("timeout()"), self.changeSlideshows)

        self.poll_timer = QTimer(self)
        QObject.connect(self.poll_timer, SIGNAL("timeout()"), self.checkQueueEvent)

        if ctx.consts.lang == "tr":
            self.installProgress.ui.progress.setFormat("%%p")

        self.iter_slideshows = iter_slideshows()

        # show first pic
        self.changeSlideshows()

        self.total = 0
        self.cur = 0
        self.has_errors = False

        # mutual exclusion
        self.mutex = None
        self.wait_condition = None
        self.queue = None

        self.retry_answer = False
        self.sys_copier = None
Exemplo n.º 13
0
    def __init__(self):
        QWidget.__init__(self)
        self.l = QVBoxLayout()
        self.setLayout(self.l)

        self.serialLabel = QLabel('eInk Kindle Serial numbers (First character B, 16 characters, use commas if more than one)')
        self.l.addWidget(self.serialLabel)

        self.serials = QLineEdit(self)
        self.serials.setText(prefs['serials'])
        self.l.addWidget(self.serials)
        self.serialLabel.setBuddy(self.serials)

        self.pidLabel = QLabel('Mobipocket PIDs (8 or 10 characters, use commas if more than one)')
        self.l.addWidget(self.pidLabel)

        self.pids = QLineEdit(self)
        self.pids.setText(prefs['pids'])
        self.l.addWidget(self.pids)
        self.pidLabel.setBuddy(self.serials)

        self.wpLabel = QLabel('For Linux only: WINEPREFIX (enter absolute path)')
        self.l.addWidget(self.wpLabel)

        self.wineprefix = QLineEdit(self)
        wineprefix = prefs['WINEPREFIX']
        if wineprefix is not None:
            self.wineprefix.setText(wineprefix)
        else:
            self.wineprefix.setText('')

        self.l.addWidget(self.wineprefix)
        self.wpLabel.setBuddy(self.wineprefix)
Exemplo n.º 14
0
 def show(self):
     """
     Unhides the checkbox and its label (if it has one).
     
     @see: L{hide}
     """
     QWidget.show(self)
Exemplo n.º 15
0
 def __init__(self, parent=None, show_open_in_editor=False):
     QWidget.__init__(self, parent)
     self.changes = [[], [], []]
     self.delta = 0
     self.l = l = QHBoxLayout(self)
     self.setLayout(l)
     self.syncpos = 0
     l.setMargin(0), l.setSpacing(0)
     self.view = DiffSplit(self, show_open_in_editor=show_open_in_editor)
     l.addWidget(self.view)
     self.add_diff = self.view.add_diff
     self.scrollbar = QScrollBar(self)
     l.addWidget(self.scrollbar)
     self.syncing = False
     self.bars = []
     self.resize_timer = QTimer(self)
     self.resize_timer.setSingleShot(True)
     self.resize_timer.timeout.connect(self.resize_debounced)
     for i, bar in enumerate((self.scrollbar, self.view.left.verticalScrollBar(), self.view.right.verticalScrollBar())):
         self.bars.append(bar)
         bar.valueChanged[int].connect(partial(self.scrolled, i))
     self.view.left.resized.connect(self.resized)
     for i, v in enumerate((self.view.left, self.view.right, self.view.handle(1))):
         v.wheel_event.connect(self.scrollbar.wheelEvent)
         if i < 2:
             v.next_change.connect(self.next_change)
             v.line_activated.connect(self.line_activated)
             v.scrolled.connect(partial(self.scrolled, i + 1))
Exemplo n.º 16
0
    def __init__(self):
        QWidget.__init__(self)
        self.l = QGridLayout()
        self.setLayout(self.l)

        self.newFormatCheckboxLabel = QLabel("Generate new format data (SQLite3)")
        self.l.addWidget(self.newFormatCheckboxLabel, 0, 0, 1, 1)
        self.newFormatCheckbox = QCheckBox(self)
        self.l.addWidget(self.newFormatCheckbox, 0, 1, 1, 1)
        self.newFormatCheckbox.setChecked(prefs["newFormat"])

        # ARTTBD Maybe should be a native directory picker?  Works for now..
        self.cacheDirLabel = QLabel("Caching directory (optional, useful if re-running for a given book)")
        self.l.addWidget(self.cacheDirLabel, 1, 0, 1, 1)
        self.cacheDirEdit = QLineEdit(self)
        self.l.addWidget(self.cacheDirEdit, 1, 1, 1, 1)
        self.cacheDirEdit.setText(prefs["cacheDir"])

        self.autoExpandAliasesLabel = QLabel("Auto-generate aliases from character names")
        self.l.addWidget(self.autoExpandAliasesLabel, 2, 0, 1, 1)
        self.autoExpandAliasesCheckbox = QCheckBox(self)
        self.l.addWidget(self.autoExpandAliasesCheckbox, 2, 1, 1, 1)
        self.autoExpandAliasesCheckbox.setChecked(prefs["autoExpandAliases"])

        self.logfileLabel = QLabel("Log file (optional)")
        self.l.addWidget(self.logfileLabel, 3, 0, 1, 1)
        self.logfileEdit = QLineEdit(self)
        self.l.addWidget(self.logfileEdit, 3, 1, 1, 1)
        self.logfileEdit.setText(prefs["logfile"])
Exemplo n.º 17
0
    def __init__(self, esp_image, glpane):

        QWidget.__init__(self)
        self.setupUi(self)
        self.connect(self.ok_btn,SIGNAL("clicked()"),self.accept)
        self.connect(self.cancel_btn,SIGNAL("clicked()"),self.reject)
        self.connect(self.choose_border_color_btn,SIGNAL("clicked()"),self.change_border_color)
        self.connect(self.choose_fill_color_btn,SIGNAL("clicked()"),self.change_fill_color)
        self.connect(self.show_esp_bbox_checkbox,SIGNAL("toggled(bool)"),self.show_esp_bbox)
        self.connect(self.select_atoms_btn,SIGNAL("clicked()"),self.select_atoms_inside_esp_bbox)
        self.connect(self.highlight_atoms_in_bbox_checkbox,SIGNAL("toggled(bool)"),self.highlight_atoms_in_bbox)
        self.connect(self.calculate_esp_btn,SIGNAL("clicked()"),self.calculate_esp)
        self.connect(self.rotate_ccw_btn,SIGNAL("clicked()"),self.rotate_90)
        self.connect(self.rotate_cw_btn,SIGNAL("clicked()"),self.rotate_neg_90)
        self.connect(self.flip_btn,SIGNAL("clicked()"),self.flip_esp_image)
        self.connect(self.mirror_btn,SIGNAL("clicked()"),self.mirror_esp_image)
        self.connect(self.opacity_slider,SIGNAL("valueChanged(int)"),self.change_opacity)
        self.connect(self.choose_file_btn,SIGNAL("clicked()"),self.change_esp_image)
        self.connect(self.load_btn,SIGNAL("clicked()"),self.load_esp_image)
        self.connect(self.clear_btn,SIGNAL("clicked()"),self.clear_esp_image)
        self.connect(self.xaxis_spinbox,SIGNAL("valueChanged(int)"),self.change_xaxisOrient)
        self.connect(self.yaxis_spinbox,SIGNAL("valueChanged(int)"),self.change_yaxisOrient)
        self.connect(self.width_linedit,SIGNAL("returnPressed()"),self.change_jig_size)
        self.connect(self.edge_offset_linedit,SIGNAL("returnPressed()"),self.change_jig_size)
        self.connect(self.image_offset_linedit,SIGNAL("returnPressed()"),self.change_jig_size)
        self.jig = esp_image
        self.glpane = glpane
Exemplo n.º 18
0
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     self._pixmap = QPixmap(self)
     self.setMinimumSize(QSize(150, 200))
     ImageDropMixin.__init__(self)
     self.draw_border = True
     self.show_size = False
Exemplo n.º 19
0
 def paintEvent(self, event):
     QWidget.paintEvent(self, event)
     pmap = self._pixmap
     if pmap.isNull():
         return
     w, h = pmap.width(), pmap.height()
     ow, oh = w, h
     cw, ch = self.rect().width(), self.rect().height()
     scaled, nw, nh = fit_image(w, h, cw, ch)
     if scaled:
         pmap = pmap.scaled(nw, nh, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
     w, h = pmap.width(), pmap.height()
     x = int(abs(cw - w) / 2.0)
     y = int(abs(ch - h) / 2.0)
     target = QRect(x, y, w, h)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
     p.drawPixmap(target, pmap)
     if self.draw_border:
         pen = QPen()
         pen.setWidth(self.BORDER_WIDTH)
         p.setPen(pen)
         p.drawRect(target)
     if self.show_size:
         sztgt = target.adjusted(0, 0, 0, -4)
         f = p.font()
         f.setBold(True)
         p.setFont(f)
         sz = u"\u00a0%d x %d\u00a0" % (ow, oh)
         flags = Qt.AlignBottom | Qt.AlignRight | Qt.TextSingleLine
         szrect = p.boundingRect(sztgt, flags, sz)
         p.fillRect(szrect.adjusted(0, 0, 0, 4), QColor(0, 0, 0, 200))
         p.setPen(QPen(QColor(255, 255, 255)))
         p.drawText(sztgt, flags, sz)
     p.end()
Exemplo n.º 20
0
 def resizeEvent(self, event):
     """
     Reimplementation of the resizeEvent handler. It determines if the
     frame is being resized by the splitter (allowed) or programmably 
     via a resize of the part window (not allowed).
     """
     if self.parent.resizeTimer.isActive():
         # LeftFrame is being resized (programmably) by the part window
         # as the user drags the resize handle.
         # We don't want that, so don't change the splitter position.
         return
     
     # LeftFrame is most likely being resized by the user via the splitter,
     # but it is also possible that the user clicked the maximize/restore 
     # button. If the user did this, set the splitter position to the
     # "old" width (not the current width) since it has been changed
     # programmably (and we didn't want that).
     size = event.size()
     oldSize = event.oldSize()
     delta = abs(size.width() - oldSize.width())
     if delta < 10: # 10 pixels. Value chosen based on experimentation.
         self.parent.splitterPosition = size.width()
         if _DEBUG:
             print "New Size: ", self.parent.splitterPosition
     else:
         self.parent.splitterPosition = oldSize.width()
         if _DEBUG:
             print "Old Size: ", self.parent.splitterPosition
     QWidget.resizeEvent(self, event)
     return
Exemplo n.º 21
0
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.setupUi(self)

        self.connect(self.test_button, SIGNAL("clicked()"), self.do_test)
        self.connect(self.re.lineEdit(), SIGNAL("returnPressed()"), self.do_test)
        self.re.lineEdit().textChanged.connect(lambda x: self.changed_signal.emit())
Exemplo n.º 22
0
    def __init__(self, plugin):
        QWidget.__init__(self)
        self.plugin = plugin

        self.l = l = QGridLayout()
        self.setLayout(l)

        self.gb = QGroupBox(_('Downloaded metadata fields'), self)
        if plugin.config_help_message:
            self.pchm = QLabel(plugin.config_help_message)
            self.pchm.setWordWrap(True)
            self.pchm.setOpenExternalLinks(True)
            l.addWidget(self.pchm, 0, 0, 1, 2)
        l.addWidget(self.gb, l.rowCount(), 0, 1, 2)
        self.gb.l = QGridLayout()
        self.gb.setLayout(self.gb.l)
        self.fields_view = v = QListView(self)
        self.gb.l.addWidget(v, 0, 0)
        v.setFlow(v.LeftToRight)
        v.setWrapping(True)
        v.setResizeMode(v.Adjust)
        self.fields_model = FieldsModel(self.plugin)
        self.fields_model.initialize()
        v.setModel(self.fields_model)

        self.memory = []
        self.widgets = []
        for opt in plugin.options:
            self.create_widgets(opt)
Exemplo n.º 23
0
    def __init__(self):
        QWidget.__init__(self)
        self.l = QVBoxLayout()
        self.setLayout(self.l)

        self.url_label = QLabel('Casanova server:')
        self.l.addWidget(self.url_label)

        self.url_msg = QLineEdit(self)
        self.url_msg.setText(prefs['base_url'])
        self.l.addWidget(self.url_msg)

        self.url_label.setBuddy(self.url_msg)

        self.username_label = QLabel('Username:'******'username'])
        self.l.addWidget(self.username_msg)

        self.username_label.setBuddy(self.username_msg)        

        self.password_label = QLabel('password:'******'password'])
        self.l.addWidget(self.password_msg)

        self.password_label.setBuddy(self.password_msg)                
Exemplo n.º 24
0
 def __init__(self, parent, label, filename=None, dialog_label=None, file_types=None, default_suffix=None,
              file_mode=QFileDialog.AnyFile):
     QWidget.__init__(self, parent)
     lo = QHBoxLayout(self)
     lo.setContentsMargins(0, 0, 0, 0)
     lo.setSpacing(5)
     # label
     lab = QLabel(label, self)
     lo.addWidget(lab, 0)
     # text field
     self.wfname = QLineEdit(self)
     self.wfname.setReadOnly(True)
     self.setFilename(filename)
     lo.addWidget(self.wfname, 1)
     # selector
     wsel = QToolButton(self)
     wsel.setText("Choose...")
     QObject.connect(wsel, SIGNAL("clicked()"), self._chooseFile)
     lo.addWidget(wsel, 0)
     # other init
     self._file_dialog = None
     self._dialog_label = dialog_label or label
     self._file_types = file_types or "All files (*)"
     self._file_mode = file_mode
     self._default_suffix = default_suffix
     self._dir = None
Exemplo n.º 25
0
 def __init__(self, *args):
     QWidget.__init__(self, *args)
     lo = QHBoxLayout(self)
     lo.setContentsMargins(0, 0, 0, 0)
     lo.setSpacing(5)
     # type selector
     self.wtypesel = QComboBox(self)
     for i, tp in enumerate(self.ValueTypes):
         self.wtypesel.addItem(tp.__name__)
     QObject.connect(self.wtypesel, SIGNAL("activated(int)"), self._selectTypeNum)
     typesel_lab = QLabel("&Type:", self)
     typesel_lab.setBuddy(self.wtypesel)
     lo.addWidget(typesel_lab, 0)
     lo.addWidget(self.wtypesel, 0)
     self.wvalue = QLineEdit(self)
     self.wvalue_lab = QLabel("&Value:", self)
     self.wvalue_lab.setBuddy(self.wvalue)
     self.wbool = QComboBox(self)
     self.wbool.addItems(["false", "true"])
     self.wbool.setCurrentIndex(1)
     lo.addWidget(self.wvalue_lab, 0)
     lo.addWidget(self.wvalue, 1)
     lo.addWidget(self.wbool, 1)
     self.wvalue.hide()
     # make input validators
     self._validators = {int: QIntValidator(self), float: QDoubleValidator(self)}
     # select bool type initially
     self._selectTypeNum(0)
Exemplo n.º 26
0
    def __init__(self):
        QWidget.__init__(self)
        self.ui = Ui_KeyboardWidget()
        self.ui.setupUi(self)

        index = 0 # comboBox.addItem doesn't increase the currentIndex
        self.default_layout_index = None
        locales = sorted([(country, data) for country, data in yali.localedata.locales.items()])
        for country, data in locales:
            if data["xkbvariant"]:
                i = 0
                for variant in data["xkbvariant"]:
                    _d = dict(data)
                    _d["xkbvariant"] = variant[0]
                    _d["name"] = variant[1]
                    _d["consolekeymap"] = data["consolekeymap"][i]
                    self.ui.keyboard_list.addItem(_d["name"], QVariant(_d))
                    i += 1
            else:
                self.ui.keyboard_list.addItem(data["name"], QVariant(data))
            if ctx.consts.lang == country:
                if ctx.consts.lang == "tr":
                    self.default_layout_index = index + 1
                else:
                    self.default_layout_index = index
            index += 1


        self.ui.keyboard_list.setCurrentIndex(self.default_layout_index)

        self.connect(self.ui.keyboard_list, SIGNAL("currentIndexChanged(int)"),
                self.slotLayoutChanged)
Exemplo n.º 27
0
 def __init__(self, parent):
     QWidget.__init__(self, parent)
     
     self._radius = 350
     self._gw_distance = 2 * self._radius
     self._bus_distance = 4 * self._radius
     self._last_bus_pos = [0, 0]
     self._last_bus_steps = [0, 0]
     self._bus_node = {}
     self._bus_position = {}
     
     self._ecu_terminals = {}
     self._ecu_position = {}
     self._ecu_node = {}
     
     self._show_dict = {}
     
     
     self.lastClicked = []     
     self._all_points = []           
     self.create_widgets(parent)
     
     
     self.map_points = {}
     
     self.COLOR_ECU_AUTH = (255, 0, 0)
     self.COLOR_STR_AUTH = (0, 255, 0)
     self.COLOR_SIMPLE = (0, 0, 255)
     self.COLOR_PROCESS = (123, 123, 0)
     self.COLOR_PROCESS_2 = (0, 123, 123)
     
     self._init_categories()
     self._mode = 'LW_AUTH'
         
     self._pts_ecu = {} 
 def __init__(self, parent):
     QWidget.__init__(self, parent=None)
     self.setupUi(self)
     self.gui = parent.gui
     self.parent = parent
     self.prefs = parent.prefs
     self.verbose = parent.verbose
Exemplo n.º 29
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.l = l = QGridLayout(self)
        self.setLayout(l)
        l.setContentsMargins(0, 0, 0, 0)

        self.view = QTreeWidget(self)
        self.delegate = Delegate(self.view)
        self.view.setItemDelegate(self.delegate)
        self.view.setHeaderHidden(True)
        self.view.setAnimated(True)
        self.view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.view.customContextMenuRequested.connect(self.show_context_menu, type=Qt.QueuedConnection)
        self.view.itemActivated.connect(self.emit_navigate)
        self.view.itemPressed.connect(self.item_pressed)
        pi = plugins['progress_indicator'][0]
        if hasattr(pi, 'set_no_activate_on_click'):
            pi.set_no_activate_on_click(self.view)
        self.view.itemDoubleClicked.connect(self.emit_navigate)
        l.addWidget(self.view)

        self.refresh_action = QAction(QIcon(I('view-refresh.png')), _('&Refresh'), self)
        self.refresh_action.triggered.connect(self.refresh)
        self.refresh_timer = t = QTimer(self)
        t.setInterval(1000), t.setSingleShot(True)
        t.timeout.connect(self.auto_refresh)
        self.toc_name = None
        self.currently_editing = None
Exemplo n.º 30
0
 def paintEvent(self, event):
     QWidget.paintEvent(self, event)
     pmap = self._pixmap
     if pmap.isNull():
         return
     w, h = pmap.width(), pmap.height()
     cw, ch = self.rect().width(), self.rect().height()
     scaled, nw, nh = fit_image(w, h, cw, ch)
     if scaled:
         pmap = pmap.scaled(nw, nh, Qt.IgnoreAspectRatio,
                 Qt.SmoothTransformation)
     w, h = pmap.width(), pmap.height()
     x = int(abs(cw - w)/2.)
     y = int(abs(ch - h)/2.)
     target = QRect(x, y, w, h)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
     p.drawPixmap(target, pmap)
     pen = QPen()
     pen.setWidth(self.BORDER_WIDTH)
     p.setPen(pen)
     if self.draw_border:
         p.drawRect(target)
     #p.drawRect(self.rect())
     p.end()
Exemplo n.º 31
0
 def __init__(self, parent):
     QWidget.__init__(self, parent)
     self.l = QHBoxLayout()
     self.setLayout(self.l)
     self.l.addStretch(10)
Exemplo n.º 32
0
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     self.settings = {}
     self._prevent_changed = False
     self.Setting = namedtuple(
         'Setting', 'name prefs widget getter setter initial_value')
Exemplo n.º 33
0
    def __init__(self, settings, all_formats, supports_subdirs,
                 must_read_metadata, supports_use_author_sort,
                 extra_customization_message, device):

        QWidget.__init__(self)
        Ui_ConfigWidget.__init__(self)
        self.setupUi(self)

        self.settings = settings

        all_formats = set(all_formats)
        self.calibre_known_formats = device.FORMATS
        self.device_name = device.get_gui_name()
        if device.USER_CAN_ADD_NEW_FORMATS:
            all_formats = set(all_formats) | set(BOOK_EXTENSIONS)

        format_map = settings.format_map
        disabled_formats = list(set(all_formats).difference(format_map))
        for format in format_map + list(sorted(disabled_formats)):
            item = QListWidgetItem(format, self.columns)
            item.setData(Qt.UserRole, QVariant(format))
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
                          | Qt.ItemIsSelectable)
            item.setCheckState(Qt.Checked if format in
                               format_map else Qt.Unchecked)

        self.column_up.clicked.connect(self.up_column)
        self.column_down.clicked.connect(self.down_column)

        if device.HIDE_FORMATS_CONFIG_BOX:
            self.groupBox.hide()

        if supports_subdirs:
            self.opt_use_subdirs.setChecked(self.settings.use_subdirs)
        else:
            self.opt_use_subdirs.hide()
        if not must_read_metadata:
            self.opt_read_metadata.setChecked(self.settings.read_metadata)
        else:
            self.opt_read_metadata.hide()
        if supports_use_author_sort:
            self.opt_use_author_sort.setChecked(self.settings.use_author_sort)
        else:
            self.opt_use_author_sort.hide()
        if extra_customization_message:

            def parse_msg(m):
                msg, _, tt = m.partition(':::') if m else ('', '', '')
                return msg.strip(), textwrap.fill(tt.strip(), 100)

            if isinstance(extra_customization_message, list):
                self.opt_extra_customization = []
                if len(extra_customization_message) > 6:
                    row_func = lambda x, y: ((x / 2) * 2) + y
                    col_func = lambda x: x % 2
                else:
                    row_func = lambda x, y: x * 2 + y
                    col_func = lambda x: 0

                for i, m in enumerate(extra_customization_message):
                    label_text, tt = parse_msg(m)
                    if not label_text:
                        self.opt_extra_customization.append(None)
                        continue
                    if isinstance(settings.extra_customization[i], bool):
                        self.opt_extra_customization.append(
                            QCheckBox(label_text))
                        self.opt_extra_customization[-1].setToolTip(tt)
                        self.opt_extra_customization[i].setChecked(
                            bool(settings.extra_customization[i]))
                    else:
                        self.opt_extra_customization.append(QLineEdit(self))
                        l = QLabel(label_text)
                        l.setToolTip(tt)
                        self.opt_extra_customization[i].setToolTip(tt)
                        l.setBuddy(self.opt_extra_customization[i])
                        l.setWordWrap(True)
                        self.opt_extra_customization[i].setText(
                            settings.extra_customization[i])
                        self.opt_extra_customization[i].setCursorPosition(0)
                        self.extra_layout.addWidget(l, row_func(i, 0),
                                                    col_func(i))
                    self.extra_layout.addWidget(
                        self.opt_extra_customization[i], row_func(i, 1),
                        col_func(i))
            else:
                self.opt_extra_customization = QLineEdit()
                label_text, tt = parse_msg(extra_customization_message)
                l = QLabel(label_text)
                l.setToolTip(tt)
                l.setBuddy(self.opt_extra_customization)
                l.setWordWrap(True)
                if settings.extra_customization:
                    self.opt_extra_customization.setText(
                        settings.extra_customization)
                    self.opt_extra_customization.setCursorPosition(0)
                self.opt_extra_customization.setCursorPosition(0)
                self.extra_layout.addWidget(l, 0, 0)
                self.extra_layout.addWidget(self.opt_extra_customization, 1, 0)
        self.opt_save_template.setText(settings.save_template)
Exemplo n.º 34
0
    def __init__(self, parent, db):
        QDialog.__init__(self, parent)
        self.db = db

        self.setWindowTitle(_('Check Library -- Problems Found'))
        self.setWindowIcon(QIcon(I('debug.png')))

        self._tl = QHBoxLayout()
        self.setLayout(self._tl)
        self.splitter = QSplitter(self)
        self.left = QWidget(self)
        self.splitter.addWidget(self.left)
        self.helpw = QTextEdit(self)
        self.splitter.addWidget(self.helpw)
        self._tl.addWidget(self.splitter)
        self._layout = QVBoxLayout()
        self.left.setLayout(self._layout)
        self.helpw.setReadOnly(True)
        self.helpw.setText(
            _('''\
        <h1>Help</h1>

        <p>calibre stores the list of your books and their metadata in a
        database. The actual book files and covers are stored as normal
        files in the calibre library folder. The database contains a list of the files
        and covers belonging to each book entry. This tool checks that the
        actual files in the library folder on your computer match the
        information in the database.</p>

        <p>The result of each type of check is shown to the left. The various
        checks are:
        </p>
        <ul>
        <li><b>Invalid titles</b>: These are files and folders appearing
        in the library where books titles should, but that do not have the
        correct form to be a book title.</li>
        <li><b>Extra titles</b>: These are extra files in your calibre
        library that appear to be correctly-formed titles, but have no corresponding
        entries in the database</li>
        <li><b>Invalid authors</b>: These are files appearing
        in the library where only author folders should be.</li>
        <li><b>Extra authors</b>: These are folders in the
        calibre library that appear to be authors but that do not have entries
        in the database</li>
        <li><b>Missing book formats</b>: These are book formats that are in
        the database but have no corresponding format file in the book's folder.
        <li><b>Extra book formats</b>: These are book format files found in
        the book's folder but not in the database.
        <li><b>Unknown files in books</b>: These are extra files in the
        folder of each book that do not correspond to a known format or cover
        file.</li>
        <li><b>Missing cover files</b>: These represent books that are marked
        in the database as having covers but the actual cover files are
        missing.</li>
        <li><b>Cover files not in database</b>: These are books that have
        cover files but are marked as not having covers in the database.</li>
        <li><b>Folder raising exception</b>: These represent folders in the
        calibre library that could not be processed/understood by this
        tool.</li>
        </ul>

        <p>There are two kinds of automatic fixes possible: <i>Delete
        marked</i> and <i>Fix marked</i>.</p>
        <p><i>Delete marked</i> is used to remove extra files/folders/covers that
        have no entries in the database. Check the box next to the item you want
        to delete. Use with caution.</p>

        <p><i>Fix marked</i> is applicable only to covers and missing formats
        (the three lines marked 'fixable'). In the case of missing cover files,
        checking the fixable box and pushing this button will tell calibre that
        there is no cover for all of the books listed. Use this option if you
        are not going to restore the covers from a backup. In the case of extra
        cover files, checking the fixable box and pushing this button will tell
        calibre that the cover files it found are correct for all the books
        listed. Use this when you are not going to delete the file(s). In the
        case of missing formats, checking the fixable box and pushing this
        button will tell calibre that the formats are really gone. Use this if
        you are not going to restore the formats from a backup.</p>

        '''))

        self.log = QTreeWidget(self)
        self.log.itemChanged.connect(self.item_changed)
        self.log.itemExpanded.connect(self.item_expanded_or_collapsed)
        self.log.itemCollapsed.connect(self.item_expanded_or_collapsed)
        self._layout.addWidget(self.log)

        self.check_button = QPushButton(_('&Run the check again'))
        self.check_button.setDefault(False)
        self.check_button.clicked.connect(self.run_the_check)
        self.copy_button = QPushButton(_('Copy &to clipboard'))
        self.copy_button.setDefault(False)
        self.copy_button.clicked.connect(self.copy_to_clipboard)
        self.ok_button = QPushButton(_('&Done'))
        self.ok_button.setDefault(True)
        self.ok_button.clicked.connect(self.accept)
        self.delete_button = QPushButton(_('Delete &marked'))
        self.delete_button.setToolTip(
            _('Delete marked files (checked subitems)'))
        self.delete_button.setDefault(False)
        self.delete_button.clicked.connect(self.delete_marked)
        self.fix_button = QPushButton(_('&Fix marked'))
        self.fix_button.setDefault(False)
        self.fix_button.setEnabled(False)
        self.fix_button.setToolTip(
            _('Fix marked sections (checked fixable items)'))
        self.fix_button.clicked.connect(self.fix_items)
        self.bbox = QDialogButtonBox(self)
        self.bbox.addButton(self.check_button, QDialogButtonBox.ActionRole)
        self.bbox.addButton(self.delete_button, QDialogButtonBox.ActionRole)
        self.bbox.addButton(self.fix_button, QDialogButtonBox.ActionRole)
        self.bbox.addButton(self.copy_button, QDialogButtonBox.ActionRole)
        self.bbox.addButton(self.ok_button, QDialogButtonBox.AcceptRole)

        h = QHBoxLayout()
        ln = QLabel(_('Names to ignore:'))
        h.addWidget(ln)
        self.name_ignores = QLineEdit()
        self.name_ignores.setText(
            db.prefs.get('check_library_ignore_names', ''))
        self.name_ignores.setToolTip(
            _('Enter comma-separated standard file name wildcards, such as synctoy*.dat'
              ))
        ln.setBuddy(self.name_ignores)
        h.addWidget(self.name_ignores)
        le = QLabel(_('Extensions to ignore'))
        h.addWidget(le)
        self.ext_ignores = QLineEdit()
        self.ext_ignores.setText(
            db.prefs.get('check_library_ignore_extensions', ''))
        self.ext_ignores.setToolTip(
            _('Enter comma-separated extensions without a leading dot. Used only in book folders'
              ))
        le.setBuddy(self.ext_ignores)
        h.addWidget(self.ext_ignores)
        self._layout.addLayout(h)

        self._layout.addWidget(self.bbox)
        self.resize(950, 500)
        self.bbox.setEnabled(True)
Exemplo n.º 35
0
class CheckLibraryDialog(QDialog):
    def __init__(self, parent, db):
        QDialog.__init__(self, parent)
        self.db = db

        self.setWindowTitle(_('Check Library -- Problems Found'))
        self.setWindowIcon(QIcon(I('debug.png')))

        self._tl = QHBoxLayout()
        self.setLayout(self._tl)
        self.splitter = QSplitter(self)
        self.left = QWidget(self)
        self.splitter.addWidget(self.left)
        self.helpw = QTextEdit(self)
        self.splitter.addWidget(self.helpw)
        self._tl.addWidget(self.splitter)
        self._layout = QVBoxLayout()
        self.left.setLayout(self._layout)
        self.helpw.setReadOnly(True)
        self.helpw.setText(
            _('''\
        <h1>Help</h1>

        <p>calibre stores the list of your books and their metadata in a
        database. The actual book files and covers are stored as normal
        files in the calibre library folder. The database contains a list of the files
        and covers belonging to each book entry. This tool checks that the
        actual files in the library folder on your computer match the
        information in the database.</p>

        <p>The result of each type of check is shown to the left. The various
        checks are:
        </p>
        <ul>
        <li><b>Invalid titles</b>: These are files and folders appearing
        in the library where books titles should, but that do not have the
        correct form to be a book title.</li>
        <li><b>Extra titles</b>: These are extra files in your calibre
        library that appear to be correctly-formed titles, but have no corresponding
        entries in the database</li>
        <li><b>Invalid authors</b>: These are files appearing
        in the library where only author folders should be.</li>
        <li><b>Extra authors</b>: These are folders in the
        calibre library that appear to be authors but that do not have entries
        in the database</li>
        <li><b>Missing book formats</b>: These are book formats that are in
        the database but have no corresponding format file in the book's folder.
        <li><b>Extra book formats</b>: These are book format files found in
        the book's folder but not in the database.
        <li><b>Unknown files in books</b>: These are extra files in the
        folder of each book that do not correspond to a known format or cover
        file.</li>
        <li><b>Missing cover files</b>: These represent books that are marked
        in the database as having covers but the actual cover files are
        missing.</li>
        <li><b>Cover files not in database</b>: These are books that have
        cover files but are marked as not having covers in the database.</li>
        <li><b>Folder raising exception</b>: These represent folders in the
        calibre library that could not be processed/understood by this
        tool.</li>
        </ul>

        <p>There are two kinds of automatic fixes possible: <i>Delete
        marked</i> and <i>Fix marked</i>.</p>
        <p><i>Delete marked</i> is used to remove extra files/folders/covers that
        have no entries in the database. Check the box next to the item you want
        to delete. Use with caution.</p>

        <p><i>Fix marked</i> is applicable only to covers and missing formats
        (the three lines marked 'fixable'). In the case of missing cover files,
        checking the fixable box and pushing this button will tell calibre that
        there is no cover for all of the books listed. Use this option if you
        are not going to restore the covers from a backup. In the case of extra
        cover files, checking the fixable box and pushing this button will tell
        calibre that the cover files it found are correct for all the books
        listed. Use this when you are not going to delete the file(s). In the
        case of missing formats, checking the fixable box and pushing this
        button will tell calibre that the formats are really gone. Use this if
        you are not going to restore the formats from a backup.</p>

        '''))

        self.log = QTreeWidget(self)
        self.log.itemChanged.connect(self.item_changed)
        self.log.itemExpanded.connect(self.item_expanded_or_collapsed)
        self.log.itemCollapsed.connect(self.item_expanded_or_collapsed)
        self._layout.addWidget(self.log)

        self.check_button = QPushButton(_('&Run the check again'))
        self.check_button.setDefault(False)
        self.check_button.clicked.connect(self.run_the_check)
        self.copy_button = QPushButton(_('Copy &to clipboard'))
        self.copy_button.setDefault(False)
        self.copy_button.clicked.connect(self.copy_to_clipboard)
        self.ok_button = QPushButton(_('&Done'))
        self.ok_button.setDefault(True)
        self.ok_button.clicked.connect(self.accept)
        self.delete_button = QPushButton(_('Delete &marked'))
        self.delete_button.setToolTip(
            _('Delete marked files (checked subitems)'))
        self.delete_button.setDefault(False)
        self.delete_button.clicked.connect(self.delete_marked)
        self.fix_button = QPushButton(_('&Fix marked'))
        self.fix_button.setDefault(False)
        self.fix_button.setEnabled(False)
        self.fix_button.setToolTip(
            _('Fix marked sections (checked fixable items)'))
        self.fix_button.clicked.connect(self.fix_items)
        self.bbox = QDialogButtonBox(self)
        self.bbox.addButton(self.check_button, QDialogButtonBox.ActionRole)
        self.bbox.addButton(self.delete_button, QDialogButtonBox.ActionRole)
        self.bbox.addButton(self.fix_button, QDialogButtonBox.ActionRole)
        self.bbox.addButton(self.copy_button, QDialogButtonBox.ActionRole)
        self.bbox.addButton(self.ok_button, QDialogButtonBox.AcceptRole)

        h = QHBoxLayout()
        ln = QLabel(_('Names to ignore:'))
        h.addWidget(ln)
        self.name_ignores = QLineEdit()
        self.name_ignores.setText(
            db.prefs.get('check_library_ignore_names', ''))
        self.name_ignores.setToolTip(
            _('Enter comma-separated standard file name wildcards, such as synctoy*.dat'
              ))
        ln.setBuddy(self.name_ignores)
        h.addWidget(self.name_ignores)
        le = QLabel(_('Extensions to ignore'))
        h.addWidget(le)
        self.ext_ignores = QLineEdit()
        self.ext_ignores.setText(
            db.prefs.get('check_library_ignore_extensions', ''))
        self.ext_ignores.setToolTip(
            _('Enter comma-separated extensions without a leading dot. Used only in book folders'
              ))
        le.setBuddy(self.ext_ignores)
        h.addWidget(self.ext_ignores)
        self._layout.addLayout(h)

        self._layout.addWidget(self.bbox)
        self.resize(950, 500)
        self.bbox.setEnabled(True)

    def do_exec(self):
        self.run_the_check()

        probs = 0
        for c in self.problem_count:
            probs += self.problem_count[c]
        if probs == 0:
            return False
        self.exec_()
        return True

    def accept(self):
        self.db.prefs['check_library_ignore_extensions'] = \
                                            unicode(self.ext_ignores.text())
        self.db.prefs['check_library_ignore_names'] = \
                                            unicode(self.name_ignores.text())
        QDialog.accept(self)

    def box_to_list(self, txt):
        return [f.strip() for f in txt.split(',') if f.strip()]

    def run_the_check(self):
        checker = CheckLibrary(self.db.library_path, self.db)
        checker.scan_library(
            self.box_to_list(unicode(self.name_ignores.text())),
            self.box_to_list(unicode(self.ext_ignores.text())))

        plaintext = []

        def builder(tree, checker, check):
            attr, h, checkable, fixable = check
            list = getattr(checker, attr, None)
            if list is None:
                self.problem_count[attr] = 0
                return
            else:
                self.problem_count[attr] = len(list)

            tl = Item()
            tl.setText(0, h)
            if fixable and list:
                tl.setText(1, _('(fixable)'))
                tl.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
                tl.setCheckState(1, False)
            self.top_level_items[attr] = tl

            for problem in list:
                it = Item()
                if checkable:
                    it.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
                    it.setCheckState(1, False)
                else:
                    it.setFlags(Qt.ItemIsEnabled)
                it.setText(0, problem[0])
                it.setData(0, Qt.UserRole, problem[2])
                it.setText(1, problem[1])
                tl.addChild(it)
                self.all_items.append(it)
                plaintext.append(','.join([h, problem[0], problem[1]]))
            tree.addTopLevelItem(tl)

        t = self.log
        t.clear()
        t.setColumnCount(2)
        t.setHeaderLabels([_('Name'), _('Path from library')])
        self.all_items = []
        self.top_level_items = {}
        self.problem_count = {}
        for check in CHECKS:
            builder(t, checker, check)

        t.resizeColumnToContents(0)
        t.resizeColumnToContents(1)
        self.delete_button.setEnabled(False)
        self.text_results = '\n'.join(plaintext)

    def item_expanded_or_collapsed(self, item):
        self.log.resizeColumnToContents(0)
        self.log.resizeColumnToContents(1)

    def item_changed(self, item, column):
        self.fix_button.setEnabled(False)
        for it in self.top_level_items.values():
            if it.checkState(1):
                self.fix_button.setEnabled(True)

        self.delete_button.setEnabled(False)
        for it in self.all_items:
            if it.checkState(1):
                self.delete_button.setEnabled(True)
                return

    def delete_marked(self):
        if not confirm(
                '<p>' + _('The marked files and folders will be '
                          '<b>permanently deleted</b>. Are you sure?') +
                '</p>', 'check_library_editor_delete', self):
            return

        # Sort the paths in reverse length order so that we can be sure that
        # if an item is in another item, the sub-item will be deleted first.
        items = sorted(self.all_items,
                       key=lambda x: len(x.text(1)),
                       reverse=True)
        for it in items:
            if it.checkState(1):
                try:
                    p = os.path.join(self.db.library_path, unicode(it.text(1)))
                    if os.path.isdir(p):
                        delete_tree(p)
                    else:
                        delete_file(p)
                except:
                    prints(
                        'failed to delete',
                        os.path.join(self.db.library_path,
                                     unicode(it.text(1))))
        self.run_the_check()

    def fix_missing_formats(self):
        tl = self.top_level_items['missing_formats']
        child_count = tl.childCount()
        for i in range(0, child_count):
            item = tl.child(i)
            id = item.data(0, Qt.UserRole).toInt()[0]
            all = self.db.formats(id, index_is_id=True, verify_formats=False)
            all = set([f.strip() for f in all.split(',')]) if all else set()
            valid = self.db.formats(id, index_is_id=True, verify_formats=True)
            valid = set([f.strip()
                         for f in valid.split(',')]) if valid else set()
            for fmt in all - valid:
                self.db.remove_format(id, fmt, index_is_id=True, db_only=True)

    def fix_missing_covers(self):
        tl = self.top_level_items['missing_covers']
        child_count = tl.childCount()
        for i in range(0, child_count):
            item = tl.child(i)
            id = item.data(0, Qt.UserRole).toInt()[0]
            self.db.set_has_cover(id, False)

    def fix_extra_covers(self):
        tl = self.top_level_items['extra_covers']
        child_count = tl.childCount()
        for i in range(0, child_count):
            item = tl.child(i)
            id = item.data(0, Qt.UserRole).toInt()[0]
            self.db.set_has_cover(id, True)

    def fix_items(self):
        for check in CHECKS:
            attr = check[0]
            fixable = check[3]
            tl = self.top_level_items[attr]
            if fixable and tl.checkState(1):
                func = getattr(self, 'fix_' + attr, None)
                if func is not None and callable(func):
                    func()
        self.run_the_check()

    def copy_to_clipboard(self):
        QApplication.clipboard().setText(self.text_results)
Exemplo n.º 36
0
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     if hasattr(self, 'setupUi'):
         self.setupUi(self)
     self.settings = {}
Exemplo n.º 37
0
   def __init__(self, main):

      self.main = main

      ##########################################################################
      ##### Display the conversion values based on the Coinbase API
      self.lastPriceFetch = 0
      self.lblHeader    = QRichLabel(tr("""<b>Tracking buy and sell prices on 
         Coinbase every 60 seconds</b>"""), doWrap=False)
      self.lblLastTime  = QRichLabel('', doWrap=False)
      self.lblSellLabel = QRichLabel(tr('Coinbase <b>Sell</b> Price (USD):'), doWrap=False)
      self.lblBuyLabel  = QRichLabel(tr('Coinbase <b>Buy</b> Price (USD):'),  doWrap=False)
      self.lblSellPrice = QRichLabel('<Not Available>')
      self.lblBuyPrice  = QRichLabel('<Not Available>')

      self.lastSellStr = ''
      self.lastBuyStr = ''

      self.btnUpdate = QPushButton(tr('Check Now'))
      self.main.connect(self.btnUpdate, SIGNAL('clicked()'), self.checkUpdatePrice)

      ##########################################################################
      ##### A calculator for converting prices between USD and BTC
      lblCalcTitle = QRichLabel(tr("""Convert between USD and BTC using 
         Coinbase sell price"""), hAlign=Qt.AlignHCenter, doWrap=False)
      self.edtEnterUSD = QLineEdit()
      self.edtEnterBTC = QLineEdit()
      self.lblEnterUSD1 = QRichLabel('$')
      self.lblEnterUSD2 = QRichLabel('USD')
      self.lblEnterBTC = QRichLabel('DGB')
      btnClear = QPushButton('Clear')

      self.main.connect(self.edtEnterUSD, SIGNAL('textEdited(QString)'), self.updateCalcBTC)
      self.main.connect(self.edtEnterBTC, SIGNAL('textEdited(QString)'), self.updateCalcUSD)

      def clearCalc():
         self.edtEnterUSD.setText('')
         self.edtEnterBTC.setText('')

      self.main.connect(btnClear, SIGNAL('clicked()'), clearCalc)

      frmCalcMid = makeHorizFrame( [self.lblEnterUSD1,
                                    self.edtEnterUSD,
                                    self.lblEnterUSD2,
                                    'Stretch',
                                    self.edtEnterBTC,
                                    self.lblEnterBTC])

      frmCalcClear = makeHorizFrame(['Stretch', btnClear, 'Stretch'])
      frmCalc = makeVertFrame([lblCalcTitle, frmCalcMid, frmCalcClear], STYLE_PLAIN)

      ##########################################################################
      ##### A table showing you the total balance of each wallet in USD and BTC
      lblWltTableTitle = QRichLabel(tr("Wallet balances converted to USD"), 
                                            doWrap=False, hAlign=Qt.AlignHCenter)
      numWallets = len(self.main.walletMap)
      self.wltTable = QTableWidget(self.main)
      self.wltTable.setRowCount(numWallets)
      self.wltTable.setColumnCount(4)
      self.wltTable.horizontalHeader().setStretchLastSection(True)
      self.wltTable.setMinimumWidth(600)


      ##########################################################################
      ##### Setup the main layout for the tab
      mainLayout = QGridLayout()
      i=0
      mainLayout.addWidget(self.lblHeader,      i,0,  1,3)
      i+=1
      mainLayout.addItem(QSpacerItem(15,15),    i,0)
      mainLayout.addWidget(self.lblSellLabel,   i,1)
      mainLayout.addWidget(self.lblSellPrice,   i,2)
      i+=1
      mainLayout.addItem(QSpacerItem(15,15),    i,0)
      mainLayout.addWidget(self.lblBuyLabel,    i,1)
      mainLayout.addWidget(self.lblBuyPrice,    i,2)
      i+=1
      mainLayout.addWidget(self.lblLastTime,    i,0,  1,2)
      mainLayout.addWidget(self.btnUpdate,      i,2)
      i+=1
      mainLayout.addItem(QSpacerItem(20,20),    i,0)
      i+=1
      mainLayout.addWidget(frmCalc,             i,0,  1,3)
      i+=1
      mainLayout.addItem(QSpacerItem(30,30),    i,0)
      i+=1
      mainLayout.addWidget(lblWltTableTitle,    i,0,  1,3)
      i+=1
      mainLayout.addWidget(self.wltTable,       i,0,  1,3)

      mainLayout.setColumnStretch(0,0)
      mainLayout.setColumnStretch(1,1)
      mainLayout.setColumnStretch(2,1)
      tabWidget = QWidget()
      tabWidget.setLayout(mainLayout)

      frmH = makeHorizFrame(['Stretch', tabWidget, 'Stretch'])
      frm  = makeVertFrame(['Space(20)', frmH, 'Stretch'])


      # Now set the scrollarea widget to the layout
      self.tabToDisplay = QScrollArea()
      self.tabToDisplay.setWidgetResizable(True)
      self.tabToDisplay.setWidget(frm)
Exemplo n.º 38
0
    def __init__(self, parent, hide_on_close=False):
        QMainWindow.__init__(self, parent)
        self._hide_on_close = hide_on_close
        # replace the BusyIndicator class with a GUI-aware one
        Purr.BusyIndicator = BusyIndicator
        self._pounce = False
        # we keep a small stack of previously active purrers. This makes directory changes
        # faster (when going back and forth between dirs)
        # current purrer
        self.purrer = None
        self.purrer_stack = []
        # Purr pipes for receiving remote commands
        self.purrpipes = {}
        # init GUI
        self.setWindowTitle("PURR")
        self.setWindowIcon(pixmaps.purr_logo.icon())
        cw = QWidget(self)
        self.setCentralWidget(cw)
        cwlo = QVBoxLayout(cw)
        cwlo.setContentsMargins(0, 0, 0, 0)
        cwlo.setMargin(5)
        cwlo.setSpacing(0)
        toplo = QHBoxLayout()
        cwlo.addLayout(toplo)

        # About dialog
        self._about_dialog = QMessageBox(self)
        self._about_dialog.setWindowTitle("About PURR")
        self._about_dialog.setText(self.about_message + """
        <P>PURR is not watching any directories right now. You may need to restart it, and give it
  some directory names on the command line.</P>""")
        self._about_dialog.setIconPixmap(pixmaps.purr_logo.pm())
        # Log viewer dialog
        self.viewer_dialog = HTMLViewerDialog(
            self,
            config_name="log-viewer",
            buttons=
            [(pixmaps.blue_round_reload, "Regenerate",
              """<P>Regenerates your log's HTML code from scratch. This can be useful if
                                                        your PURR version has changed, or if there was an error of some kind
                                                        the last time the files were generated.</P>
                                                        """)])
        self._viewer_timestamp = None
        self.connect(self.viewer_dialog, SIGNAL("Regenerate"),
                     self._regenerateLog)
        self.connect(self.viewer_dialog, SIGNAL("viewPath"), self._viewPath)

        # Log title toolbar
        title_tb = QToolBar(cw)
        title_tb.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        title_tb.setIconSize(QSize(16, 16))
        cwlo.addWidget(title_tb)
        title_label = QLabel("Purrlog title:", title_tb)
        title_tb.addWidget(title_label)
        self.title_editor = QLineEdit(title_tb)
        title_tb.addWidget(self.title_editor)
        self.connect(self.title_editor, SIGNAL("editingFinished()"),
                     self._titleChanged)
        tip = """<P>This is your current log title. To rename the log, enter new name here and press Enter.</P>"""
        title_label.setToolTip(tip)
        self.title_editor.setToolTip(tip)
        self.wviewlog = title_tb.addAction(pixmaps.openbook.icon(), "View",
                                           self._showViewerDialog)
        self.wviewlog.setToolTip(
            "Click to see an HTML rendering of your current log.")
        qa = title_tb.addAction(pixmaps.purr_logo.icon(), "About...",
                                self._about_dialog.exec_)
        qa.setToolTip(
            "<P>Click to see the About... dialog, which will tell you something about PURR.</P>"
        )

        self.wdirframe = QFrame(cw)
        cwlo.addWidget(self.wdirframe)
        self.dirs_lo = QVBoxLayout(self.wdirframe)
        self.dirs_lo.setMargin(5)
        self.dirs_lo.setContentsMargins(5, 0, 5, 5)
        self.dirs_lo.setSpacing(0)
        self.wdirframe.setFrameStyle(QFrame.Box | QFrame.Raised)
        self.wdirframe.setLineWidth(1)

        ## Directories toolbar
        dirs_tb = QToolBar(self.wdirframe)
        dirs_tb.setToolButtonStyle(Qt.ToolButtonIconOnly)
        dirs_tb.setIconSize(QSize(16, 16))
        self.dirs_lo.addWidget(dirs_tb)
        label = QLabel("Monitoring directories:", dirs_tb)
        self._dirs_tip = """<P>PURR can monitor your working directories for new or updated files. If there's a checkmark
      next to the directory name in this list, PURR is monitoring it.</P>

      <P>If the checkmark is grey, PURR is monitoring things unobtrusively. When a new or updated file is detected in he monitored directory,
      it is quietly added to the list of files in the "New entry" window, even if this window is not currently visible.</P>

      <P>If the checkmark is black, PURR will be more obtrusive. Whenever a new or updated file is detected, the "New entry" window will
      pop up automatically. This is called "pouncing", and some people find it annoying.</P>
      """
        label.setToolTip(self._dirs_tip)
        label.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Minimum)
        dirs_tb.addWidget(label)

        # add directory list widget
        self.wdirlist = DirectoryListWidget(self.wdirframe)
        self.wdirlist.setToolTip(self._dirs_tip)
        QObject.connect(self.wdirlist, SIGNAL("directoryStateChanged"),
                        self._changeWatchedDirState)
        self.dirs_lo.addWidget(self.wdirlist)
        # self.wdirlist.setMaximumSize(1000000,64)

        # add directory button
        add = dirs_tb.addAction(pixmaps.list_add.icon(), "Add",
                                self._showAddDirectoryDialog)
        add.setToolTip(
            "<P>Click to add another directory to be monitored.</P>")

        # remove directory button
        delbtn = dirs_tb.addAction(pixmaps.list_remove.icon(), "Remove",
                                   self.wdirlist.removeCurrent)
        delbtn.setEnabled(False)
        delbtn.setToolTip(
            "<P>Click to removed the currently selected directory from the list.</P>"
        )
        QObject.connect(self.wdirlist, SIGNAL("hasSelection"),
                        delbtn.setEnabled)

        #    # qa = dirs_tb.addAction(pixmaps.blue_round_reload.icon(),"Rescan",self._forceRescan)
        #    # qa.setToolTip("Click to rescan the directories for any new or updated files.")
        #    self.wshownew = QCheckBox("show new files",dirs_tb)
        #    dirs_tb.addWidget(self.wshownew)
        #    self.wshownew.setCheckState(Qt.Checked)
        #    self.wshownew.setToolTip("""<P>If this is checked, the "New entry" window will pop up automatically whenever
        #  new or updated files are detected. If this is unchecked, the files will be added to the window quietly
        #        and unobtrusively; you can show the window manually by clicking on the "New entry..." button below.</P>""")
        #    self._dir_entries = {}

        cwlo.addSpacing(5)

        wlogframe = QFrame(cw)
        cwlo.addWidget(wlogframe)
        log_lo = QVBoxLayout(wlogframe)
        log_lo.setMargin(5)
        log_lo.setContentsMargins(5, 5, 5, 5)
        log_lo.setSpacing(0)
        wlogframe.setFrameStyle(QFrame.Box | QFrame.Raised)
        wlogframe.setLineWidth(1)

        # listview of log entries
        self.etw = LogEntryTree(cw)
        log_lo.addWidget(self.etw, 1)
        self.etw.header().setDefaultSectionSize(128)
        self.etw.header().setMovable(False)
        self.etw.setHeaderLabels(["date", "entry title", "comment"])
        if hasattr(QHeaderView, 'ResizeToContents'):
            self.etw.header().setResizeMode(0, QHeaderView.ResizeToContents)
        else:
            self.etw.header().setResizeMode(0, QHeaderView.Custom)
            self.etw.header().resizeSection(0, 120)
        self.etw.header().setResizeMode(1, QHeaderView.Interactive)
        self.etw.header().setResizeMode(2, QHeaderView.Stretch)
        self.etw.header().show()
        try:
            self.etw.setAllColumnsShowFocus(True)
        except AttributeError:
            pass
            # Qt 4.2+
        # self.etw.setShowToolTips(True)
        self.etw.setSortingEnabled(False)
        # self.etw.setColumnAlignment(2,Qt.AlignLeft|Qt.AlignTop)
        self.etw.setSelectionMode(QTreeWidget.ExtendedSelection)
        self.etw.setRootIsDecorated(True)
        self.connect(self.etw, SIGNAL("itemSelectionChanged()"),
                     self._entrySelectionChanged)
        self.connect(self.etw, SIGNAL("itemActivated(QTreeWidgetItem*,int)"),
                     self._viewEntryItem)
        self.connect(self.etw, SIGNAL("itemContextMenuRequested"),
                     self._showItemContextMenu)
        # create popup menu for data products
        self._archived_dp_menu = menu = QMenu(self)
        self._archived_dp_menu_title = QLabel()
        self._archived_dp_menu_title.setMargin(5)
        self._archived_dp_menu_title_wa = wa = QWidgetAction(self)
        wa.setDefaultWidget(self._archived_dp_menu_title)
        menu.addAction(wa)
        menu.addSeparator()
        menu.addAction(pixmaps.editcopy.icon(),
                       "Restore file(s) from archived copy",
                       self._restoreItemFromArchive)
        menu.addAction(pixmaps.editpaste.icon(),
                       "Copy pathname of archived copy to clipboard",
                       self._copyItemToClipboard)
        self._current_item = None
        # create popup menu for entries
        self._entry_menu = menu = QMenu(self)
        self._entry_menu_title = QLabel()
        self._entry_menu_title.setMargin(5)
        self._entry_menu_title_wa = wa = QWidgetAction(self)
        wa.setDefaultWidget(self._entry_menu_title)
        menu.addAction(wa)
        menu.addSeparator()
        menu.addAction(pixmaps.filefind.icon(), "View this log entry",
                       self._viewEntryItem)
        menu.addAction(pixmaps.editdelete.icon(), "Delete this log entry",
                       self._deleteSelectedEntries)
        # buttons at bottom
        log_lo.addSpacing(5)
        btnlo = QHBoxLayout()
        log_lo.addLayout(btnlo)
        self.wnewbtn = QPushButton(pixmaps.filenew.icon(), "New entry...", cw)
        self.wnewbtn.setToolTip("Click to add a new log entry.")
        # self.wnewbtn.setFlat(True)
        self.wnewbtn.setEnabled(False)
        btnlo.addWidget(self.wnewbtn)
        btnlo.addSpacing(5)
        self.weditbtn = QPushButton(pixmaps.filefind.icon(), "View entry...",
                                    cw)
        self.weditbtn.setToolTip(
            "Click to view or edit the selected log entry/")
        # self.weditbtn.setFlat(True)
        self.weditbtn.setEnabled(False)
        self.connect(self.weditbtn, SIGNAL("clicked()"), self._viewEntryItem)
        btnlo.addWidget(self.weditbtn)
        btnlo.addSpacing(5)
        self.wdelbtn = QPushButton(pixmaps.editdelete.icon(), "Delete", cw)
        self.wdelbtn.setToolTip(
            "Click to delete the selected log entry or entries.")
        # self.wdelbtn.setFlat(True)
        self.wdelbtn.setEnabled(False)
        self.connect(self.wdelbtn, SIGNAL("clicked()"),
                     self._deleteSelectedEntries)
        btnlo.addWidget(self.wdelbtn)
        # enable status line
        self.statusBar().show()
        Purr.progressMessage = self.message
        self._prev_msg = None
        # editor dialog for new entry
        self.new_entry_dialog = Purr.Editors.NewLogEntryDialog(self)
        self.connect(self.new_entry_dialog, SIGNAL("newLogEntry"),
                     self._newLogEntry)
        self.connect(self.new_entry_dialog, SIGNAL("filesSelected"),
                     self._addDPFiles)
        self.connect(self.wnewbtn, SIGNAL("clicked()"),
                     self.new_entry_dialog.show)
        self.connect(self.new_entry_dialog, SIGNAL("shown"),
                     self._checkPounceStatus)
        # entry viewer dialog
        self.view_entry_dialog = Purr.Editors.ExistingLogEntryDialog(self)
        self.connect(self.view_entry_dialog, SIGNAL("previous()"),
                     self._viewPrevEntry)
        self.connect(self.view_entry_dialog, SIGNAL("next()"),
                     self._viewNextEntry)
        self.connect(self.view_entry_dialog, SIGNAL("viewPath"),
                     self._viewPath)
        self.connect(self.view_entry_dialog, SIGNAL("filesSelected"),
                     self._addDPFilesToOldEntry)
        self.connect(self.view_entry_dialog, SIGNAL("entryChanged"),
                     self._entryChanged)
        # saving a data product to an older entry will automatically drop it from the
        # new entry dialog
        self.connect(self.view_entry_dialog, SIGNAL("creatingDataProduct"),
                     self.new_entry_dialog.dropDataProducts)
        # resize selves
        width = Config.getint('main-window-width', 512)
        height = Config.getint('main-window-height', 512)
        self.resize(QSize(width, height))
        # create timer for pouncing
        self._timer = QTimer(self)
        self.connect(self._timer, SIGNAL("timeout()"), self._rescan)
        # create dict mapping index.html paths to entry numbers
        self._index_paths = {}
Exemplo n.º 39
0
class RuleEditor(QDialog):  # {{{
    def __init__(self, fm, pref_name, parent=None):
        QDialog.__init__(self, parent)
        self.fm = fm

        if pref_name == 'column_color_rules':
            self.rule_kind = 'color'
            rule_text = _('coloring')
        else:
            self.rule_kind = 'icon'
            rule_text = _('icon')

        self.setWindowIcon(QIcon(I('format-fill-color.png')))
        self.setWindowTitle(
            _('Create/edit a column {0} rule').format(rule_text))

        self.l = l = QGridLayout(self)
        self.setLayout(l)

        self.l1 = l1 = QLabel(
            _('Create a column {0} rule by'
              ' filling in the boxes below'.format(rule_text)))
        l.addWidget(l1, 0, 0, 1, 8)

        self.f1 = QFrame(self)
        self.f1.setFrameShape(QFrame.HLine)
        l.addWidget(self.f1, 1, 0, 1, 8)

        self.l2 = l2 = QLabel(_('Set the'))
        l.addWidget(l2, 2, 0)

        if self.rule_kind == 'color':
            l.addWidget(QLabel(_('color')))
        else:
            self.kind_box = QComboBox(self)
            for tt, t in icon_rule_kinds:
                self.kind_box.addItem(tt, t)
            l.addWidget(self.kind_box, 2, 1)
            self.kind_box.setToolTip(
                textwrap.fill(
                    _('If you choose composed icons and multiple rules match, then all the'
                      ' matching icons will be combined, otherwise the icon from the'
                      ' first rule to match will be used.')))

        self.l3 = l3 = QLabel(_('of the column:'))
        l.addWidget(l3, 2, 2)

        self.column_box = QComboBox(self)
        l.addWidget(self.column_box, 2, 3)

        self.l4 = l4 = QLabel(_('to'))
        l.addWidget(l4, 2, 4)

        if self.rule_kind == 'color':
            self.color_box = QComboBox(self)
            self.color_label = QLabel('Sample text Sample text')
            self.color_label.setTextFormat(Qt.RichText)
            l.addWidget(self.color_box, 2, 5)
            l.addWidget(self.color_label, 2, 6)
            l.addItem(QSpacerItem(10, 10, QSizePolicy.Expanding), 2, 7)
        else:
            self.filename_box = QComboBox()
            d = os.path.join(config_dir, 'cc_icons')
            self.icon_file_names = []
            if os.path.exists(d):
                for icon_file in os.listdir(d):
                    icon_file = lower(icon_file)
                    if os.path.exists(os.path.join(d, icon_file)):
                        if icon_file.endswith('.png'):
                            self.icon_file_names.append(icon_file)
            self.icon_file_names.sort(key=sort_key)

            vb = QVBoxLayout()
            self.multiple_icon_cb = QCheckBox(_('Choose more than one icon'))
            vb.addWidget(self.multiple_icon_cb)
            self.update_filename_box()
            self.multiple_icon_cb.clicked.connect(self.multiple_box_clicked)
            vb.addWidget(self.filename_box)
            l.addLayout(vb, 2, 5)

            self.filename_button = QPushButton(QIcon(I('document_open.png')),
                                               _('&Add icon'))
            l.addWidget(self.filename_button, 2, 6)
            l.addWidget(QLabel(_('Icons should be square or landscape')), 2, 7)
            l.setColumnStretch(7, 10)

        self.l5 = l5 = QLabel(
            _('Only if the following conditions are all satisfied:'))
        l.addWidget(l5, 3, 0, 1, 7)

        self.scroll_area = sa = QScrollArea(self)
        sa.setMinimumHeight(300)
        sa.setMinimumWidth(950)
        sa.setWidgetResizable(True)
        l.addWidget(sa, 4, 0, 1, 8)

        self.add_button = b = QPushButton(QIcon(I('plus.png')),
                                          _('Add another condition'))
        l.addWidget(b, 5, 0, 1, 8)
        b.clicked.connect(self.add_blank_condition)

        self.l6 = l6 = QLabel(
            _('You can disable a condition by'
              ' blanking all of its boxes'))
        l.addWidget(l6, 6, 0, 1, 8)

        self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        l.addWidget(bb, 7, 0, 1, 8)

        self.conditions_widget = QWidget(self)
        sa.setWidget(self.conditions_widget)
        self.conditions_widget.setLayout(QVBoxLayout())
        self.conditions_widget.layout().setAlignment(Qt.AlignTop)
        self.conditions = []

        if self.rule_kind == 'color':
            for b in (self.column_box, self.color_box):
                b.setSizeAdjustPolicy(b.AdjustToMinimumContentsLengthWithIcon)
                b.setMinimumContentsLength(15)

        for key in sorted(displayable_columns(fm),
                          key=lambda (k): sort_key(fm[k]['name'])
                          if k != color_row_key else 0):
            if key == color_row_key and self.rule_kind != 'color':
                continue
            name = all_columns_string if key == color_row_key else fm[key][
                'name']
            if name:
                self.column_box.addItem(name, key)
        self.column_box.setCurrentIndex(0)

        if self.rule_kind == 'color':
            self.color_box.addItems(QColor.colorNames())
            self.color_box.setCurrentIndex(0)
            self.update_color_label()
            self.color_box.currentIndexChanged.connect(self.update_color_label)
        else:
            self.rule_icon_files = []
            self.filename_button.clicked.connect(self.filename_button_clicked)

        self.resize(self.sizeHint())

    def multiple_box_clicked(self):
        self.update_filename_box()
        self.update_icon_filenames_in_box()

    def update_filename_box(self):
        doing_multiple = self.multiple_icon_cb.isChecked()

        model = QStandardItemModel()
        self.filename_box.setModel(model)
        self.icon_file_names.sort(key=sort_key)
        if doing_multiple:
            item = QStandardItem(_('Open to see checkboxes'))
        else:
            item = QStandardItem('')
        model.appendRow(item)

        for i, filename in enumerate(self.icon_file_names):
            item = QStandardItem(filename)
            if doing_multiple:
                item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                item.setData(Qt.Unchecked, Qt.CheckStateRole)
            else:
                item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
            icon = QIcon(os.path.join(config_dir, 'cc_icons', filename))
            item.setIcon(icon)
            model.appendRow(item)

    def update_color_label(self):
        pal = QApplication.palette()
        bg1 = unicode(pal.color(pal.Base).name())
        bg2 = unicode(pal.color(pal.AlternateBase).name())
        c = unicode(self.color_box.currentText())
        self.color_label.setText('''
            <span style="color: {c}; background-color: {bg1}">&nbsp;{st}&nbsp;</span>
            <span style="color: {c}; background-color: {bg2}">&nbsp;{st}&nbsp;</span>
            '''.format(c=c, bg1=bg1, bg2=bg2, st=_('Sample Text')))

    def filename_button_clicked(self):
        try:
            path = choose_files(self,
                                'choose_category_icon',
                                _('Select Icon'),
                                filters=[('Images',
                                          ['png', 'gif', 'jpg', 'jpeg'])],
                                all_files=False,
                                select_only_single_file=True)
            if path:
                icon_path = path[0]
                icon_name = lower(
                    sanitize_file_name_unicode(
                        os.path.splitext(os.path.basename(icon_path))[0] +
                        '.png'))
                if icon_name not in self.icon_file_names:
                    self.icon_file_names.append(icon_name)
                    self.update_filename_box()
                    try:
                        p = QIcon(icon_path).pixmap(QSize(128, 128))
                        d = os.path.join(config_dir, 'cc_icons')
                        if not os.path.exists(os.path.join(d, icon_name)):
                            if not os.path.exists(d):
                                os.makedirs(d)
                            with open(os.path.join(d, icon_name), 'wb') as f:
                                f.write(pixmap_to_data(p, format='PNG'))
                    except:
                        import traceback
                        traceback.print_exc()
                if self.multiple_icon_cb.isChecked():
                    if icon_name not in self.rule_icon_files:
                        self.rule_icon_files.append(icon_name)
                    self.update_icon_filenames_in_box()
                else:
                    self.filename_box.setCurrentIndex(
                        self.filename_box.findText(icon_name))
                self.filename_box.adjustSize()
        except:
            import traceback
            traceback.print_exc()
        return

    def get_filenames_from_box(self):
        if self.multiple_icon_cb.isChecked():
            model = self.filename_box.model()
            fnames = []
            for i in range(1, model.rowCount()):
                item = model.item(i, 0)
                if item.checkState() == Qt.Checked:
                    fnames.append(lower(unicode(item.text())))
            fname = ' : '.join(fnames)
        else:
            fname = lower(unicode(self.filename_box.currentText()))
        return fname

    def update_icon_filenames_in_box(self):
        if self.rule_icon_files:
            if not self.multiple_icon_cb.isChecked():
                idx = self.filename_box.findText(self.rule_icon_files[0])
                if idx >= 0:
                    self.filename_box.setCurrentIndex(idx)
                else:
                    self.filename_box.setCurrentIndex(0)
            else:
                model = self.filename_box.model()
                for icon in self.rule_icon_files:
                    idx = self.filename_box.findText(icon)
                    if idx >= 0:
                        item = model.item(idx)
                        item.setCheckState(Qt.Checked)

    def add_blank_condition(self):
        c = ConditionEditor(self.fm, parent=self.conditions_widget)
        self.conditions.append(c)
        self.conditions_widget.layout().addWidget(c)

    def apply_rule(self, kind, col, rule):
        if kind == 'color':
            if rule.color:
                idx = self.color_box.findText(rule.color)
                if idx >= 0:
                    self.color_box.setCurrentIndex(idx)
        else:
            for i, tup in enumerate(icon_rule_kinds):
                if kind == tup[1]:
                    self.kind_box.setCurrentIndex(i)
                    break
            self.rule_icon_files = [ic.strip() for ic in rule.color.split(':')]
            if len(self.rule_icon_files) > 1:
                self.multiple_icon_cb.setChecked(True)
            self.update_filename_box()
            self.update_icon_filenames_in_box()

        for i in range(self.column_box.count()):
            c = unicode(self.column_box.itemData(i).toString())
            if col == c:
                self.column_box.setCurrentIndex(i)
                break

        for c in rule.conditions:
            ce = ConditionEditor(self.fm, parent=self.conditions_widget)
            self.conditions.append(ce)
            self.conditions_widget.layout().addWidget(ce)
            try:
                ce.condition = c
            except:
                import traceback
                traceback.print_exc()

    def accept(self):
        if self.rule_kind != 'color':
            fname = self.get_filenames_from_box()
            if not fname:
                error_dialog(self,
                             _('No icon selected'),
                             _('You must choose an icon for this rule'),
                             show=True)
                return
        if self.validate():
            QDialog.accept(self)

    def validate(self):
        r = Rule(self.fm)
        for c in self.conditions:
            condition = c.condition
            if condition is not None:
                try:
                    r.add_condition(*condition)
                except Exception as e:
                    import traceback
                    error_dialog(self,
                                 _('Invalid condition'),
                                 _('One of the conditions for this rule is'
                                   ' invalid: <b>%s</b>') % e,
                                 det_msg=traceback.format_exc(),
                                 show=True)
                    return False
        if len(r.conditions) < 1:
            error_dialog(self,
                         _('No conditions'),
                         _('You must specify at least one non-empty condition'
                           ' for this rule'),
                         show=True)
            return False
        return True

    @property
    def rule(self):
        r = Rule(self.fm)
        if self.rule_kind != 'color':
            r.color = self.get_filenames_from_box()
        else:
            r.color = unicode(self.color_box.currentText())
        idx = self.column_box.currentIndex()
        col = unicode(self.column_box.itemData(idx).toString())
        for c in self.conditions:
            condition = c.condition
            if condition is not None:
                r.add_condition(*condition)
        if self.rule_kind == 'icon':
            kind = unicode(
                self.kind_box.itemData(
                    self.kind_box.currentIndex()).toString())
        else:
            kind = 'color'

        return kind, col, r
Exemplo n.º 40
0
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self._layout = l = QHBoxLayout()
        self.setLayout(self._layout)
        self._layout.setContentsMargins(0,5,0,0)

        x = QToolButton(self)
        x.setText(_('Vi&rtual Library'))
        x.setIcon(QIcon(I('lt.png')))
        x.setObjectName("virtual_library")
        x.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        l.addWidget(x)
        parent.virtual_library = x

        x = QToolButton(self)
        x.setIcon(QIcon(I('minus.png')))
        x.setObjectName('clear_vl')
        l.addWidget(x)
        x.setVisible(False)
        x.setToolTip(_('Close the Virtual Library'))
        parent.clear_vl = x

        x = QLabel(self)
        x.setObjectName("search_count")
        l.addWidget(x)
        parent.search_count = x
        x.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

        parent.advanced_search_button = x = QToolButton(self)
        parent.advanced_search_toggle_action = ac = QAction(parent)
        parent.addAction(ac)
        parent.keyboard.register_shortcut('advanced search toggle',
                _('Advanced search'), default_keys=("Shift+Ctrl+F",),
                action=ac)
        ac.triggered.connect(x.click)
        x.setIcon(QIcon(I('search.png')))
        l.addWidget(x)
        x.setToolTip(_("Advanced search"))

        x = parent.search = SearchBox2(self)
        x.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
        x.setObjectName("search")
        x.setToolTip(_("<p>Search the list of books by title, author, publisher, "
                       "tags, comments, etc.<br><br>Words separated by spaces are ANDed"))
        x.setMinimumContentsLength(10)
        l.addWidget(x)

        self.search_button = QToolButton()
        self.search_button.setToolButtonStyle(Qt.ToolButtonTextOnly)
        self.search_button.setText(_('&Go!'))
        l.addWidget(self.search_button)
        self.search_button.setSizePolicy(QSizePolicy.Minimum,
                QSizePolicy.Minimum)
        self.search_button.clicked.connect(parent.do_search_button)
        self.search_button.setToolTip(
            _('Do Quick Search (you can also press the Enter key)'))

        x = parent.clear_button = QToolButton(self)
        x.setIcon(QIcon(I('clear_left.png')))
        x.setObjectName("clear_button")
        l.addWidget(x)
        x.setToolTip(_("Reset Quick Search"))

        x = parent.highlight_only_button = QToolButton(self)
        x.setIcon(QIcon(I('arrow-down.png')))
        l.addWidget(x)

        x = parent.saved_search = SavedSearchBox(self)
        x.setMaximumSize(QSize(150, 16777215))
        x.setMinimumContentsLength(10)
        x.setObjectName("saved_search")
        l.addWidget(x)

        x = parent.copy_search_button = QToolButton(self)
        x.setIcon(QIcon(I("search_copy_saved.png")))
        x.setObjectName("copy_search_button")
        l.addWidget(x)
        x.setToolTip(_("Copy current search text (instead of search name)"))

        x = parent.save_search_button = QToolButton(self)
        x.setIcon(QIcon(I("search_add_saved.png")))
        x.setObjectName("save_search_button")
        l.addWidget(x)
Exemplo n.º 41
0
    def __init__(self, parent, request, isNew):
        QWidget.__init__(self, parent.parent)
        self.setupUi(self)
        self.parent = parent
        self.origrequest = request
        self.isNew = isNew

        if self.origrequest.exists:
            self.filesystemLabel.hide()
            self.filesystemMenu.hide()
        else:
            self.formatRadio.hide()
            self.formatCombo.hide()
            self.migrateRadio.hide()
            self.migrateCombo.hide()

        # Mountpoints
        storageGuiHelpers.fillMountpointMenu(self.mountpointMenu,
                                             self.origrequest)

        # Format options filesystems
        if not self.origrequest.exists:
            storageGuiHelpers.fillFilesystemMenu(
                self.filesystemMenu,
                self.origrequest.format,
                ignores=["mdmember", "efi", "prepboot", "appleboot"])
            QObject.connect(self.filesystemMenu,
                            SIGNAL("currentIndexChanged(int)"),
                            self.formatTypeChanged)
        else:
            if self.origrequest.format.formattable or not self.origrequest.format.type:
                storageGuiHelpers.fillFilesystemMenu(
                    self.formatCombo,
                    self.origrequest.format,
                    ignores=["mdmember", "efi", "prepboot", "appleboot"])
                self.formatRadio.setChecked(
                    self.origrequest.format.formattable
                    and not self.origrequest.format.exists)
                QObject.connect(self.formatCombo,
                                SIGNAL("currentIndexChanged(int)"),
                                self.formatTypeChanged)
            else:
                self.formatRadio.hide()
                self.formatCombo.hide()

            if self.origrequest.format.migratable and self.origrequest.format.exists:
                storageGuiHelpers.fillFilesystemMenu(
                    self.migrateCombo,
                    self.origrequest.format,
                    availables=[self.origrequest.format.migrationTarget])
                self.migrateRadio.setChecked(
                    self.origrequest.format.migrate
                    and not self.formatRadio.isChecked())
                QObject.connect(self.migrateCombo,
                                SIGNAL("currentIndexChanged(int)"),
                                self.formatTypeChanged)
            else:
                self.migrateRadio.hide()
                self.migrateCombo.hide()

        # Raid Members
        availraidparts = self.parent.storage.unusedRaidMembers(
            array=self.origrequest)
        storageGuiHelpers.fillRaidMembers(self.raidMembers, availraidparts,
                                          self.origrequest.devices,
                                          self.origrequest.format)
        if self.origrequest.exists:
            self.raidMembers.setEnabled(False)

        # Raid Minors
        if not self.origrequest.exists:
            availminors = self.parent.storage.unusedRaidMinors[:16]
            if self.origrequest.minor is not None and self.origrequest.minor not in availminors:
                availminors.append(self.origrequest.minor)

            availminors.sort()
            storageGuiHelpers.fillRaidMinors(self.raidMinors, availminors,
                                             self.origrequest.minor)
        else:
            self.raidMinors.addItem(self.origrequest.name)
            self.raidMinors.setEnabled(0)

        # Raid Level
        if not self.origrequest.exists:
            storageGuiHelpers.fillRaidLevels(self.raidLevels, raid.raid_levels,
                                             self.origrequest.level)
        else:
            self.raidLevels.addItem(str(self.origrequest.level))
            self.raidLevels.setEnabled(0)

        QObject.connect(self.raidLevels, SIGNAL("currentIndexChanged(int)"),
                        self.raidLevelChanged)

        # Raid Spares
        if not self.origrequest.exists:
            numparts = len(availraidparts)
            if self.origrequest.spares:
                spares = self.origrequest.spares
            else:
                spares = 0

            if self.origrequest.level:
                maxspares = raid.get_raid_max_spares(self.origrequest.level,
                                                     numparts)
            else:
                maxspares = 0

            self.spareSpin.setRange(0, maxspares)
            self.spareSpin.setValue(spares)

            if maxspares > 0:
                self.spareSpin.setEnabled(True)
            else:
                self.spareSpin.setEnabled(False)
                self.spareSpin.setValue(0)
        else:
            self.spareSpin.setValue(self.origrequest.spares)
            self.spareSpin.setEnabled(0)

        if self.origrequest.level is not None and self.origrequest.level == raid.RAID0:
            self.spareSpin.setEnabled(False)

        self.connect(self.buttonBox, SIGNAL("accepted()"),
                     self.parent.dialog.accept)
        self.connect(self.buttonBox, SIGNAL("rejected()"),
                     self.parent.dialog.reject)
Exemplo n.º 42
0
    def __init__(self, fm, pref_name, parent=None):
        QDialog.__init__(self, parent)
        self.fm = fm

        if pref_name == 'column_color_rules':
            self.rule_kind = 'color'
            rule_text = _('coloring')
        else:
            self.rule_kind = 'icon'
            rule_text = _('icon')

        self.setWindowIcon(QIcon(I('format-fill-color.png')))
        self.setWindowTitle(
            _('Create/edit a column {0} rule').format(rule_text))

        self.l = l = QGridLayout(self)
        self.setLayout(l)

        self.l1 = l1 = QLabel(
            _('Create a column {0} rule by'
              ' filling in the boxes below'.format(rule_text)))
        l.addWidget(l1, 0, 0, 1, 8)

        self.f1 = QFrame(self)
        self.f1.setFrameShape(QFrame.HLine)
        l.addWidget(self.f1, 1, 0, 1, 8)

        self.l2 = l2 = QLabel(_('Set the'))
        l.addWidget(l2, 2, 0)

        if self.rule_kind == 'color':
            l.addWidget(QLabel(_('color')))
        else:
            self.kind_box = QComboBox(self)
            for tt, t in icon_rule_kinds:
                self.kind_box.addItem(tt, t)
            l.addWidget(self.kind_box, 2, 1)
            self.kind_box.setToolTip(
                textwrap.fill(
                    _('If you choose composed icons and multiple rules match, then all the'
                      ' matching icons will be combined, otherwise the icon from the'
                      ' first rule to match will be used.')))

        self.l3 = l3 = QLabel(_('of the column:'))
        l.addWidget(l3, 2, 2)

        self.column_box = QComboBox(self)
        l.addWidget(self.column_box, 2, 3)

        self.l4 = l4 = QLabel(_('to'))
        l.addWidget(l4, 2, 4)

        if self.rule_kind == 'color':
            self.color_box = QComboBox(self)
            self.color_label = QLabel('Sample text Sample text')
            self.color_label.setTextFormat(Qt.RichText)
            l.addWidget(self.color_box, 2, 5)
            l.addWidget(self.color_label, 2, 6)
            l.addItem(QSpacerItem(10, 10, QSizePolicy.Expanding), 2, 7)
        else:
            self.filename_box = QComboBox()
            d = os.path.join(config_dir, 'cc_icons')
            self.icon_file_names = []
            if os.path.exists(d):
                for icon_file in os.listdir(d):
                    icon_file = lower(icon_file)
                    if os.path.exists(os.path.join(d, icon_file)):
                        if icon_file.endswith('.png'):
                            self.icon_file_names.append(icon_file)
            self.icon_file_names.sort(key=sort_key)

            vb = QVBoxLayout()
            self.multiple_icon_cb = QCheckBox(_('Choose more than one icon'))
            vb.addWidget(self.multiple_icon_cb)
            self.update_filename_box()
            self.multiple_icon_cb.clicked.connect(self.multiple_box_clicked)
            vb.addWidget(self.filename_box)
            l.addLayout(vb, 2, 5)

            self.filename_button = QPushButton(QIcon(I('document_open.png')),
                                               _('&Add icon'))
            l.addWidget(self.filename_button, 2, 6)
            l.addWidget(QLabel(_('Icons should be square or landscape')), 2, 7)
            l.setColumnStretch(7, 10)

        self.l5 = l5 = QLabel(
            _('Only if the following conditions are all satisfied:'))
        l.addWidget(l5, 3, 0, 1, 7)

        self.scroll_area = sa = QScrollArea(self)
        sa.setMinimumHeight(300)
        sa.setMinimumWidth(950)
        sa.setWidgetResizable(True)
        l.addWidget(sa, 4, 0, 1, 8)

        self.add_button = b = QPushButton(QIcon(I('plus.png')),
                                          _('Add another condition'))
        l.addWidget(b, 5, 0, 1, 8)
        b.clicked.connect(self.add_blank_condition)

        self.l6 = l6 = QLabel(
            _('You can disable a condition by'
              ' blanking all of its boxes'))
        l.addWidget(l6, 6, 0, 1, 8)

        self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        l.addWidget(bb, 7, 0, 1, 8)

        self.conditions_widget = QWidget(self)
        sa.setWidget(self.conditions_widget)
        self.conditions_widget.setLayout(QVBoxLayout())
        self.conditions_widget.layout().setAlignment(Qt.AlignTop)
        self.conditions = []

        if self.rule_kind == 'color':
            for b in (self.column_box, self.color_box):
                b.setSizeAdjustPolicy(b.AdjustToMinimumContentsLengthWithIcon)
                b.setMinimumContentsLength(15)

        for key in sorted(displayable_columns(fm),
                          key=lambda (k): sort_key(fm[k]['name'])
                          if k != color_row_key else 0):
            if key == color_row_key and self.rule_kind != 'color':
                continue
            name = all_columns_string if key == color_row_key else fm[key][
                'name']
            if name:
                self.column_box.addItem(name, key)
        self.column_box.setCurrentIndex(0)

        if self.rule_kind == 'color':
            self.color_box.addItems(QColor.colorNames())
            self.color_box.setCurrentIndex(0)
            self.update_color_label()
            self.color_box.currentIndexChanged.connect(self.update_color_label)
        else:
            self.rule_icon_files = []
            self.filename_button.clicked.connect(self.filename_button_clicked)

        self.resize(self.sizeHint())
Exemplo n.º 43
0
 def __init__(self, *args, **kwargs):
     QWidget.__init__(self, *args)
     self.setTextEdit(kwargs.pop('edit', None))
     # This is used to update the width of the control.
     # It is the highest possible line number.
     self.highest_line = 1
Exemplo n.º 44
0
    def __init__(self, parent, request, isNew=0):
        QWidget.__init__(self, parent.parent)
        self.setupUi(self)
        self.parent = parent
        self.origrequest = request
        self.isNew = isNew

        if not self.origrequest.exists:
            if self.origrequest.name:
                self.name.setText(self.origrequest.lvname)
            else:
                self.name.setText(
                    self.parent.storage.createSuggestedVolumeGroupName(
                        self.origrequest.vg))
        else:
            self.name.setText(self.origrequest.lvname)

        storageGuiHelpers.fillMountpointMenu(self.mountpointMenu,
                                             self.origrequest,
                                             excludes=["/boot"])
        QObject.connect(self.mountpointMenu,
                        SIGNAL("currentIndexChanged(int)"),
                        self.mountPointChanged)

        # This empty radioButton is hack about enabling autoExclusive formatRadio according to mountpoint.(#16446)
        self.radioButton.hide()

        # Partition Type
        if not self.origrequest.exists:
            storageGuiHelpers.fillFilesystemMenu(
                self.filesystemMenu,
                self.origrequest.format,
                ignores=["mdmember", "efi", "lvmpv"])
            QObject.connect(self.filesystemMenu,
                            SIGNAL("currentIndexChanged(int)"),
                            self.formatTypeChanged)
            default_format = self.filesystemMenu.findText("ext4")
            self.filesystemMenu.setCurrentIndex(default_format)
            self.resizeRadio.hide()
            self.resizeSlider.hide()
            self.resizeSpin.hide()
            self.formatRadio.hide()
            self.formatCombo.hide()
            self.migrateRadio.hide()
            self.migrateCombo.hide()
        else:
            self.filesystemLabel.hide()
            self.filesystemMenu.hide()
            if self.origrequest.format.formattable or not self.origrequest.format.type:
                storageGuiHelpers.fillFilesystemMenu(
                    self.formatCombo,
                    self.origrequest.format,
                    ignores=["mdmember", "lvmpv", "vfat"])
                self.formatRadio.setChecked(
                    self.origrequest.format.formattable
                    and not self.origrequest.format.exists)
                QObject.connect(self.formatRadio, SIGNAL("toggled(bool)"),
                                self.formatRadioToggled)
                QObject.connect(self.formatCombo,
                                SIGNAL("currentIndexChanged(int)"),
                                self.formatTypeChanged)
            else:
                self.formatRadio.hide()
                self.formatCombo.hide()

            if self.origrequest.format.migratable and self.origrequest.format.exists:
                storageGuiHelpers.fillFilesystemMenu(
                    self.migrateCombo,
                    self.origrequest.format,
                    availables=[self.origrequest.format.migrationTarget])
                self.migrateRadio.setChecked(
                    self.origrequest.format.migrate
                    and not self.formatRadio.isChecked())
                QObject.connect(self.migrateCombo,
                                SIGNAL("currentIndexChanged(int)"),
                                self.formatTypeChanged)
            else:
                self.migrateRadio.hide()
                self.migrateCombo.hide()

            if self.origrequest.resizable and self.origrequest.format.exists:
                if self.origrequest.targetSize is not None:
                    value = self.origrequest.targetSize
                else:
                    value = self.origrequest.size

                reqlower = 1
                requpper = self.origrequest.maxSize
                if self.origrequest.format.exists:
                    reqlower = self.origrequest.minSize

                    if self.origrequest.type == "partition":
                        geomsize = self.origrequest.partedPartition.geometry.getSize(
                            unit="MB")
                        if (geomsize != 0) and (requpper > geomsize):
                            requpper = geomsize

                self.resizeSpin.setMinimum(reqlower)
                self.resizeSpin.setMaximum(requpper)
                self.resizeSpin.setValue(value)
                self.resizeSlider.setMinimum(reqlower)
                self.resizeSlider.setMaximum(requpper)
                self.resizeSlider.setValue(value)
            else:
                self.resizeRadio.hide()
                self.resizeSpin.hide()
                self.resizeSlider.hide()

        #Size and maximum size
        if not self.origrequest.exists:
            maximumGrow = self.origrequest.vg.freeSpace / self.origrequest.stripes
            self.sizeSpin.setMaximum(
                min(lvm.getMaxLVSize(), self.origrequest.size + maximumGrow))
            self.sizeSpin.setValue(self.origrequest.size)
            self.sizeSlider.setMaximum(
                min(lvm.getMaxLVSize(), self.origrequest.size + maximumGrow))
            self.sizeSlider.setValue(self.origrequest.size)
        else:
            self.sizeLabel.hide()
            self.sizeSlider.hide()
            self.sizeSpin.hide()

        self.connect(self.buttonBox, SIGNAL("accepted()"),
                     self.parent.dialog.accept)
        self.connect(self.buttonBox, SIGNAL("rejected()"),
                     self.parent.dialog.reject)
Exemplo n.º 45
0
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.setLayout(QVBoxLayout())

        self.la = la = QLabel(
            '<b>' + _('Select a destination for the Table of Contents entry'))
        self.layout().addWidget(la)
        self.splitter = sp = QSplitter(self)
        self.layout().addWidget(sp)
        self.layout().setStretch(1, 10)
        sp.setOpaqueResize(False)
        sp.setChildrenCollapsible(False)

        self.dest_list = dl = QListWidget(self)
        dl.setMinimumWidth(250)
        dl.currentItemChanged.connect(self.current_changed)
        sp.addWidget(dl)

        w = self.w = QWidget(self)
        l = w.l = QGridLayout()
        w.setLayout(l)
        self.view = WebView(self)
        self.view.elem_clicked.connect(self.elem_clicked)
        l.addWidget(self.view, 0, 0, 1, 3)
        sp.addWidget(w)

        self.search_text = s = QLineEdit(self)
        s.setPlaceholderText(_('Search for text...'))
        l.addWidget(s, 1, 0)
        self.ns_button = b = QPushButton(QIcon(I('arrow-down.png')),
                                         _('Find &next'), self)
        b.clicked.connect(self.find_next)
        l.addWidget(b, 1, 1)
        self.ps_button = b = QPushButton(QIcon(I('arrow-up.png')),
                                         _('Find &previous'), self)
        l.addWidget(b, 1, 2)
        b.clicked.connect(self.find_previous)

        self.f = f = QFrame()
        f.setFrameShape(f.StyledPanel)
        f.setMinimumWidth(250)
        l = f.l = QVBoxLayout()
        f.setLayout(l)
        sp.addWidget(f)

        f.la = la = QLabel('<p>' + _(
            'Here you can choose a destination for the Table of Contents\' entry'
            ' to point to. First choose a file from the book in the left-most panel. The'
            ' file will open in the central panel.<p>'
            'Then choose a location inside the file. To do so, simply click on'
            ' the place in the central panel that you want to use as the'
            ' destination. As you move the mouse around the central panel, a'
            ' thick green line appears, indicating the precise location'
            ' that will be selected when you click.'))
        la.setStyleSheet('QLabel { margin-bottom: 20px }')
        la.setWordWrap(True)
        l.addWidget(la)

        f.la2 = la = QLabel('<b>' + _('&Name of the ToC entry:'))
        l.addWidget(la)
        self.name = QLineEdit(self)
        la.setBuddy(self.name)
        l.addWidget(self.name)

        self.base_msg = '<b>' + _('Currently selected destination:') + '</b>'
        self.dest_label = la = QLabel(self.base_msg)
        la.setWordWrap(True)
        la.setStyleSheet('QLabel { margin-top: 20px }')
        l.addWidget(la)

        l.addStretch()

        state = gprefs.get('toc_edit_splitter_state', None)
        if state is not None:
            sp.restoreState(state)
Exemplo n.º 46
0
 def __init__(self, parent):
     QWidget.__init__(self, parent)
Exemplo n.º 47
0
    def __init__(self, parent=None, one_line_toolbar=False):
        QWidget.__init__(self, parent)
        self.toolbar1 = QToolBar(self)
        self.toolbar2 = QToolBar(self)
        self.toolbar3 = QToolBar(self)
        for i in range(1, 4):
            t = getattr(self, 'toolbar%d' % i)
            t.setIconSize(QSize(18, 18))
        self.editor = EditorWidget(self)
        self.tabs = QTabWidget(self)
        self.tabs.setTabPosition(self.tabs.South)
        self.wyswyg = QWidget(self.tabs)
        self.code_edit = QPlainTextEdit(self.tabs)
        self.source_dirty = False
        self.wyswyg_dirty = True

        self._layout = QVBoxLayout(self)
        self.wyswyg.layout = l = QVBoxLayout(self.wyswyg)
        self.setLayout(self._layout)
        l.setContentsMargins(0, 0, 0, 0)
        if one_line_toolbar:
            tb = QHBoxLayout()
            l.addLayout(tb)
        else:
            tb = l
        tb.addWidget(self.toolbar1)
        tb.addWidget(self.toolbar2)
        tb.addWidget(self.toolbar3)
        l.addWidget(self.editor)
        self._layout.addWidget(self.tabs)
        self.tabs.addTab(self.wyswyg, _('Normal view'))
        self.tabs.addTab(self.code_edit, _('HTML Source'))
        self.tabs.currentChanged[int].connect(self.change_tab)
        self.highlighter = Highlighter(self.code_edit.document())
        self.layout().setContentsMargins(0, 0, 0, 0)

        # toolbar1 {{{
        self.toolbar1.addAction(self.editor.action_undo)
        self.toolbar1.addAction(self.editor.action_redo)
        self.toolbar1.addAction(self.editor.action_select_all)
        self.toolbar1.addAction(self.editor.action_remove_format)
        self.toolbar1.addAction(self.editor.action_clear)
        self.toolbar1.addSeparator()

        for x in ('copy', 'cut', 'paste'):
            ac = getattr(self.editor, 'action_' + x)
            self.toolbar1.addAction(ac)

        self.toolbar1.addSeparator()
        self.toolbar1.addAction(self.editor.action_background)
        # }}}

        # toolbar2 {{{
        for x in ('', 'un'):
            ac = getattr(self.editor, 'action_%sordered_list' % x)
            self.toolbar2.addAction(ac)
        self.toolbar2.addSeparator()
        for x in ('superscript', 'subscript', 'indent', 'outdent'):
            self.toolbar2.addAction(getattr(self.editor, 'action_' + x))
            if x in ('subscript', 'outdent'):
                self.toolbar2.addSeparator()

        self.toolbar2.addAction(self.editor.action_block_style)
        w = self.toolbar2.widgetForAction(self.editor.action_block_style)
        w.setPopupMode(w.InstantPopup)
        self.toolbar2.addAction(self.editor.action_insert_link)
        # }}}

        # toolbar3 {{{
        for x in ('bold', 'italic', 'underline', 'strikethrough'):
            ac = getattr(self.editor, 'action_' + x)
            self.toolbar3.addAction(ac)
        self.toolbar3.addSeparator()

        for x in ('left', 'center', 'right', 'justified'):
            ac = getattr(self.editor, 'action_align_' + x)
            self.toolbar3.addAction(ac)
        self.toolbar3.addSeparator()
        self.toolbar3.addAction(self.editor.action_color)
        # }}}

        self.code_edit.textChanged.connect(self.code_dirtied)
        self.editor.page().contentsChanged.connect(self.wyswyg_dirtied)
Exemplo n.º 48
0
def startWizard(args, mainwin, modal=True):
    """
    Parses list of directories ('args') and attaches to purrlogs appropriately.
    'mainwin' is a Purr.MainWindow object.

    Return value:
      * if modal=True: True if arguments parse OK and Purr.MainWindow should be shown, False on error.
      * if modal=False: True if attached to purrlog and Purr.MainWindow should be shown, False otherwise.

    If modal=False, it will keep displaying the startup dialog as a modeless dialog, and attach the
  mainwin to the specified purrlog when the dialog is closed.

    Use cases:
     $ purr <dirname> [<more dirs>]
        1. If dirname does not exist:
          * find other purrlogs in parent dir
          * pop up wizard, with the name as the default "create" option, and create selected
        2. If dirname exists:
          2a. Not a directory: report error
          2b. If dir is a purrlog, attach and add dirs
          2c. If dir contains 1 valid purrlog, attach, and add more dirs.
          2d. If dir contains 2+ purrlogs, offer choice (or create new), add more dirs
          2e. If dir contains no purrlogs, offer to create one (or to attach to one), add "more dirs" to watchlist if creating new, ignore if attaching
     $ purr
         * same as "purr ."
     $ from meqbrowser, when cd into a directory:
         * if purr dialog is visible, do same as "purr ."
     $ from meqbrowser, when purr button is pressed and purr is not yet visible
         * do "purr ."
     $ from Calico, when an MS is selected:
         * do purr MS.purrlog .
    """

    args = args or [os.getcwd()]
    dirname = os.path.abspath(args[0])
    moredirs = args[1:]

    # case 1: dirname does not exist, or refers to a non-directory
    if not os.path.exists(dirname) or not os.path.isdir(dirname):
        message = """To begin with, PURR must load an existing purrlog, or start a new purrlog. <tt>%s</tt> does not look to be an existing purrlog.
            What would you like to do?""" % Kittens.utils.collapseuser(dirname)
        create = dirname
        dirname = os.getcwd()
        parent = os.path.dirname(os.path.normpath(create)) or os.getcwd()
        # if parent is valid dir, find purrlogs in parent (to offer as an option)
        if os.path.isdir(parent):
            purrlogs = list(filter(Purr.Purrer.is_purrlog, glob.glob(os.path.join(parent, "*"))))
        # else use "." as dirname, and do not offer any purrlogs
        else:
            purrlogs = []
    # case 2: dirname exists:
    else:
        create = None
        # case 2b: is a valid purrlog
        if Purr.Purrer.is_purrlog(dirname):
            mainwin.attachPurrlog(dirname, moredirs)
            mainwin.show()
            return True
        # case 2c-2e. Look for purrlogs in dirname
        purrlogs = list(filter(Purr.Purrer.is_purrlog, glob.glob(os.path.join(dirname, "*"))))
        # case 2c: exactly one purrlog. Attach without asking.
        if len(purrlogs) == 1:
            mainwin.show()
            mainwin.attachPurrlog(purrlogs[0], moredirs)
            return True
        # else setup messages
        if purrlogs:
            message = """To begin with, PURR must load an existing purrlog, or start a new purrlog. The directory <tt>%s</tt> contains
          several purrlogs. What would you like to do?""" % Kittens.utils.collapseuser(dirname)
        else:
            message = """To begin with, PURR must load an existing purrlog, or create a new purrlog. The directory <tt>%s</tt> contains
          no purrlogs. What would you like to do?""" % Kittens.utils.collapseuser(dirname)

    # case 1, 2d or 2e: make wizard dialog

    # kill old wizard, if showing
    global wizard_dialog
    if wizard_dialog:
        wizard_dialog.hide()
        dum = QWidget()
        wizard_dialog.setParent(dum)
        dum = wizard_dialog = None

    # create new wizard
    wizard_dialog = PurrStartupWizard(mainwin, dirname, purrlogs, moredirs=moredirs, create=create, message=message)

    if modal:
        if wizard_dialog.exec_() == QDialog.Rejected:
            return False
        return True;
    else:
        wizard_dialog.setModal(False)
        wizard_dialog.show()
        return False
Exemplo n.º 49
0
 def __init__(self):
     QWidget.__init__(self)
     self.layout = QGridLayout(self)
     self.networkConnector = pds.container.PNetworkManager(self)
     self.layout.addWidget(self.networkConnector)
Exemplo n.º 50
0
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     self.l = QGridLayout()
     self.setLayout(self.l)
     self.setToolTip(textwrap.dedent(self.HELP))
Exemplo n.º 51
0
 def __init__(self, *args, **kwargs):
     QWidget.__init__(self, *args, **kwargs)
     
     self.create_widgets()
Exemplo n.º 52
0
    def __init__(self, parentWidget, title="", showWidget=True):
        """
        Constructor for PM_dockWidget

        @param showWidget: If true, this class will show the widget
        immediately in the __init__ method itself. This is the default behavior
        and subclasses may pass appropriate value to this flag
        @type showWidget: bool
        """
        self.labelWidget = None
        self._title = ""
        self._widgetList = []
        self._rowCount = 0

        QDockWidget.__init__(self, parentWidget)

        self.parentWidget = parentWidget

        self._title = title

        self.label = ''
        self.labelColumn = 0
        self.spanWidth = True
        self.labelWidget = None

        if self.label:  # Create this widget's QLabel.
            self.labelWidget = QLabel()
            self.labelWidget.setText(self.label)

        self.setEnabled(True)
        self.setFloating(False)
        self.setVisible(showWidget)
        self.setWindowTitle(self._title)
        self.setAutoFillBackground(True)
        self.setPalette(getPalette(None, QPalette.Window, pmGrpBoxColor))

        self.parentWidget.addDockWidget(Qt.BottomDockWidgetArea, self)

        #Define layout
        self._containerWidget = QWidget()
        self.setWidget(self._containerWidget)

        # Create vertical box layout
        self.vBoxLayout = QVBoxLayout(self._containerWidget)
        self.vBoxLayout.setMargin(1)
        self.vBoxLayout.setSpacing(0)

        # Create grid layout
        self.gridLayout = QGridLayout()
        self.gridLayout.setMargin(1)
        self.gridLayout.setSpacing(1)

        # Insert grid layout in its own vBoxLayout
        self.vBoxLayout.addLayout(self.gridLayout)

        #self.parentWidget.addPmWidget(self)
        self._loadWidgets()

        try:
            self._addWhatsThisText()
        except:
            print_compact_traceback("Error loading whatsthis text for this " \
                                    "property manager dock widget.")

        try:
            self._addToolTipText()
        except:
            print_compact_traceback("Error loading tool tip text for this " \
                                    "property manager dock widget.")
Exemplo n.º 53
0
 def __init__(self, *args):
     QWidget.__init__(self, *args)
     self.edit = None
     # This is used to update the width of the control.
     # It is the highest line that is currently visible.
     self.highest_line = 0
Exemplo n.º 54
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.l = gl = QGridLayout(self)
        self.setLayout(gl)
        self.changed = False

        self.bars = b = QComboBox(self)
        b.addItem(_('Choose which toolbar you want to customize'))
        ft = _('Tools for %s editors')
        for name, text in (
            (
                'global_book_toolbar',
                _('Book wide actions'),
            ),
            (
                'global_tools_toolbar',
                _('Book wide tools'),
            ),
            (
                'editor_html_toolbar',
                ft % 'HTML',
            ),
            (
                'editor_css_toolbar',
                ft % 'CSS',
            ),
            (
                'editor_xml_toolbar',
                ft % 'XML',
            ),
            (
                'editor_format_toolbar',
                _('Text formatting actions'),
            ),
        ):
            b.addItem(text, name)
        self.la = la = QLabel(_('&Toolbar to customize:'))
        la.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        la.setBuddy(b)
        gl.addWidget(la), gl.addWidget(b, 0, 1)
        self.sl = l = QGridLayout()
        gl.addLayout(l, 1, 0, 1, -1)

        self.gb1 = gb1 = QGroupBox(_('A&vailable actions'), self)
        self.gb2 = gb2 = QGroupBox(_('&Current actions'), self)
        gb1.setFlat(True), gb2.setFlat(True)
        gb1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        gb2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        l.addWidget(gb1, 0, 0, -1, 1), l.addWidget(gb2, 0, 2, -1, 1)
        self.available, self.current = ToolbarList(self), ToolbarList(self)
        self.ub = b = QToolButton(self)
        b.clicked.connect(partial(self.move, up=True))
        b.setToolTip(_('Move selected action up')), b.setIcon(
            QIcon(I('arrow-up.png')))
        self.db = b = QToolButton(self)
        b.clicked.connect(partial(self.move, up=False))
        b.setToolTip(_('Move selected action down')), b.setIcon(
            QIcon(I('arrow-down.png')))
        self.gl1 = gl1 = QVBoxLayout()
        gl1.addWidget(self.available), gb1.setLayout(gl1)
        self.gl2 = gl2 = QGridLayout()
        gl2.addWidget(self.current, 0, 0, -1, 1)
        gl2.addWidget(self.ub, 0, 1), gl2.addWidget(self.db, 2, 1)
        gb2.setLayout(gl2)
        self.lb = b = QToolButton(self)
        b.setToolTip(_('Add selected actions to toolbar')), b.setIcon(
            QIcon(I('forward.png')))
        l.addWidget(b, 1, 1), b.clicked.connect(self.add_action)
        self.rb = b = QToolButton(self)
        b.setToolTip(_('Remove selected actions from toolbar')), b.setIcon(
            QIcon(I('back.png')))
        l.addWidget(b, 3, 1), b.clicked.connect(self.remove_action)
        self.si = QSpacerItem(20,
                              10,
                              hPolicy=QSizePolicy.Preferred,
                              vPolicy=QSizePolicy.Expanding)
        l.setRowStretch(0, 10), l.setRowStretch(2, 10), l.setRowStretch(4, 10)
        l.addItem(self.si, 4, 1)

        self.read_settings()
        self.toggle_visibility(False)
        self.bars.currentIndexChanged.connect(self.bar_changed)
Exemplo n.º 55
0
    def __init__(self,
                 main=None,
                 interpreter_locals=None,
                 consola_lanas=None,
                 ventana_interprete=None,
                 *args):
        QWidget.__init__(self, *args)
        self.setupUi(self)
        self.setLayout(self.vertical_layout)
        self.ruta_del_archivo_actual = None
        self.consola_lanas = consola_lanas
        self.ventana_interprete = ventana_interprete

        if interpreter_locals is None:
            interpreter_locals = locals()

        self.interpreter_locals = interpreter_locals
        self.lista_actores_como_strings = []

        self.editor = Editor(self, interpreter_locals, consola_lanas,
                             ventana_interprete)
        self.editor.setFrameStyle(QFrame.NoFrame)
        self.editor.setAcceptRichText(False)

        self.number_bar = self.NumberBar()
        self.number_bar.setTextEdit(self.editor)

        # Agregando editor y number_bar a hbox_editor layout
        self.hbox_editor.addWidget(self.number_bar)
        self.hbox_editor.addWidget(self.editor)

        # Boton Abrir
        self.set_icon(self.boton_abrir, 'iconos/abrir.png')
        self.boton_abrir.connect(self.boton_abrir, QtCore.SIGNAL('clicked()'),
                                 self.editor.abrir_archivo_con_dialogo)

        # Boton Guardar
        self.set_icon(self.boton_guardar, 'iconos/guardar.png')
        self.boton_guardar.connect(self.boton_guardar,
                                   QtCore.SIGNAL('clicked()'),
                                   self.editor.guardar_contenido_directamente)

        # Boton Guardar Como ...
        self.set_icon(self.boton_guardar_como, 'iconos/guardar_como.png')
        self.boton_guardar_como.connect(
            self.boton_guardar_como, QtCore.SIGNAL('clicked()'),
            self.editor.guardar_contenido_con_dialogo)

        # Boton actualizar
        self.set_icon(self.boton_actualizar, 'iconos/actualizar.png')
        self.boton_actualizar.connect(self.boton_actualizar,
                                      QtCore.SIGNAL('clicked()'),
                                      self.actualizar_el_listado_de_archivos)

        # Boton actualizar
        self.set_icon(self.boton_nuevo, 'iconos/nuevo.png')
        self.boton_nuevo.connect(self.boton_nuevo, QtCore.SIGNAL('clicked()'),
                                 self.pulsa_boton_crear_archivo_nuevo)

        self.deshabilitar_boton_nuevo()

        # Boton Ejecutar
        self.set_icon(self.boton_ejecutar, 'iconos/ejecutar.png')
        self.boton_ejecutar.connect(self.boton_ejecutar,
                                    QtCore.SIGNAL('clicked()'),
                                    self.cuando_pulsa_el_boton_ejecutar)

        # Boton Pausar
        self.set_icon(self.boton_pausar, 'iconos/pausa.png')
        self.boton_pausar.connect(self.boton_pausar,
                                  QtCore.SIGNAL('clicked()'),
                                  self.cuando_pulsa_el_boton_pausar)

        # Boton Siguiente
        self.set_icon(self.boton_siguiente, 'iconos/siguiente.png')
        self.boton_siguiente.connect(self.boton_siguiente,
                                     QtCore.SIGNAL('clicked()'),
                                     self.cuando_pulsa_el_boton_siguiente)

        self._vincular_atajos_de_teclado()

        self.editor.installEventFilter(self)
        self.editor.viewport().installEventFilter(self)

        self.timer_id = self.startTimer(1000 / 2.0)
        self.lista_actores.currentItemChanged.connect(
            self.cuando_selecciona_item)

        self.selector_archivos.activated[str].connect(
            self.cuando_cambia_archivo_seleccionado)
        self.actualizar_el_listado_de_archivos()
Exemplo n.º 56
0
    def setupUi(self):
        """
        Setup the UI for the command toolbar.
        """
        #ninad 070123 : It's important to set the Vertical size policy of the
        # cmd toolbar widget. otherwise the flyout QToolbar messes up the
        #layout (makes the command toolbar twice as big)
        #I have set the vertical policy as fixed. Works fine. There are some
        # MainWindow resizing problems for but those are not due to this
        #size policy AFAIK
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        layout_cmdtoolbar = QHBoxLayout(self)
        layout_cmdtoolbar.setMargin(2)
        layout_cmdtoolbar.setSpacing(2)

        #See comment at the top for details about this flag
        if DEFINE_CONTROL_AREA_AS_A_QWIDGET:
            self.cmdToolbarControlArea = QWidget(self)
        else:
            self.cmdToolbarControlArea = QToolBar_WikiHelp(self)

        self.cmdToolbarControlArea.setAutoFillBackground(True)

        self.ctrlAreaPalette = self.getCmdMgrCtrlAreaPalette()
        self.cmdToolbarControlArea.setPalette(self.ctrlAreaPalette)

        self.cmdToolbarControlArea.setMinimumHeight(62)
        self.cmdToolbarControlArea.setMinimumWidth(380)
        self.cmdToolbarControlArea.setSizePolicy(QSizePolicy.Fixed,
                                                 QSizePolicy.Fixed)

        #See comment at the top for details about this flag
        if DEFINE_CONTROL_AREA_AS_A_QWIDGET:
            layout_controlArea = QHBoxLayout(self.cmdToolbarControlArea)
            layout_controlArea.setMargin(0)
            layout_controlArea.setSpacing(0)

        self.cmdButtonGroup = QButtonGroup()
        btn_index = 0

        for name in ('Build', 'Insert', 'Tools', 'Move', 'Simulation'):
            btn = QToolButton(self.cmdToolbarControlArea)
            btn.setObjectName(name)
            btn.setMinimumWidth(75)
            btn.setMaximumWidth(75)
            btn.setMinimumHeight(62)
            btn.setAutoRaise(True)
            btn.setCheckable(True)
            btn.setAutoExclusive(True)
            iconpath = "ui/actions/Command Toolbar/ControlArea/" + name + ".png"
            btn.setIcon(geticon(iconpath))
            btn.setIconSize(QSize(22, 22))
            btn.setText(name)
            btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
            btn.setPalette(self.ctrlAreaPalette)
            self.cmdButtonGroup.addButton(btn, btn_index)
            btn_index += 1
            #See comment at the top for details about this flag
            if DEFINE_CONTROL_AREA_AS_A_QWIDGET:
                layout_controlArea.addWidget(btn)
            else:
                self.cmdToolbarControlArea.layout().addWidget(btn)
                #following has issues. so not adding widget directly to the
                #toolbar. (instead adding it in its layout)-- ninad 070124
                ##self.cmdToolbarControlArea.addWidget(btn)

        layout_cmdtoolbar.addWidget(self.cmdToolbarControlArea)

        #Flyout Toolbar in the command toolbar
        self.flyoutToolBar = FlyoutToolBar(self)

        layout_cmdtoolbar.addWidget(self.flyoutToolBar)

        #ninad 070116: Define a spacer item. It will have the exact geometry
        # as that of the flyout toolbar. it is added to the command toolbar
        # layout only when the Flyout Toolbar is hidden. It is required
        # to keep the 'Control Area' widget fixed in its place (otherwise,
        #after hiding the flyout toolbar, the layout adjusts the position of
        #remaining widget items)

        self.spacerItem = QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding,
                                      QtGui.QSizePolicy.Minimum)
        self.spacerItem.setGeometry = self.flyoutToolBar.geometry()

        for btn in self.cmdButtonGroup.buttons():
            if str(btn.objectName()) == 'Build':
                btn.setMenu(self.win.buildStructuresMenu)
                btn.setPopupMode(QToolButton.MenuButtonPopup)
                btn.setToolTip("Build Commands")
                whatsThisTextForCommandToolbarBuildButton(btn)
            if str(btn.objectName()) == 'Insert':
                btn.setMenu(self.win.insertMenu)
                btn.setPopupMode(QToolButton.MenuButtonPopup)
                btn.setToolTip("Insert Commands")
                whatsThisTextForCommandToolbarInsertButton(btn)
            if str(btn.objectName()) == 'Tools':
                #fyi: cmd stands for 'command toolbar' - ninad070406
                self.win.cmdToolsMenu = QtGui.QMenu(self.win)
                self.win.cmdToolsMenu.addAction(self.win.toolsExtrudeAction)
                self.win.cmdToolsMenu.addAction(self.win.toolsFuseChunksAction)
                self.win.cmdToolsMenu.addSeparator()
                self.win.cmdToolsMenu.addAction(self.win.modifyMergeAction)
                self.win.cmdToolsMenu.addAction(self.win.modifyMirrorAction)
                self.win.cmdToolsMenu.addAction(self.win.modifyInvertAction)
                self.win.cmdToolsMenu.addAction(self.win.modifyStretchAction)
                btn.setMenu(self.win.cmdToolsMenu)
                btn.setPopupMode(QToolButton.MenuButtonPopup)
                btn.setToolTip("Tools")
                whatsThisTextForCommandToolbarToolsButton(btn)
            if str(btn.objectName()) == 'Move':
                self.win.moveMenu = QtGui.QMenu(self.win)
                self.win.moveMenu.addAction(self.win.toolsMoveMoleculeAction)
                self.win.moveMenu.addAction(self.win.rotateComponentsAction)
                self.win.moveMenu.addSeparator()
                self.win.moveMenu.addAction(
                    self.win.modifyAlignCommonAxisAction)
                ##self.win.moveMenu.addAction(\
                ##    self.win.modifyCenterCommonAxisAction)
                btn.setMenu(self.win.moveMenu)
                btn.setPopupMode(QToolButton.MenuButtonPopup)
                btn.setToolTip("Move Commands")
                whatsThisTextForCommandToolbarMoveButton(btn)
            if str(btn.objectName()) == 'Dimension':
                btn.setMenu(self.win.dimensionsMenu)
                btn.setPopupMode(QToolButton.MenuButtonPopup)
                btn.setToolTip("Dimensioning Commands")
            if str(btn.objectName()) == 'Simulation':
                btn.setMenu(self.win.simulationMenu)
                btn.setPopupMode(QToolButton.MenuButtonPopup)
                btn.setToolTip("Simulation Commands")
                whatsThisTextForCommandToolbarSimulationButton(btn)

            # Convert all "img" tags in the button's "What's This" text
            # into abs paths (from their original rel paths).
            # Partially fixes bug 2943. --mark 2008-12-07
            # [bruce 081209 revised this -- removed mac = False]
            fix_QAction_whatsthis(btn)
        return
Exemplo n.º 57
0
 def leaveEvent(self, ev):
     self.hovering = False
     self.update()
     return QWidget.leaveEvent(self, ev)
Exemplo n.º 58
0
 def eventFilter(self, obj, event):
     if obj in (self.editor, self.editor.viewport()):
         self.number_bar.update()
         return False
     return QWidget.eventFilter(obj, event)
Exemplo n.º 59
0
 def enterEvent(self, ev):
     self.hovering = True
     self.update()
     return QWidget.enterEvent(self, ev)
Exemplo n.º 60
0
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle("My Main Window")
        self.setMinimumWidth(MAIN_WINDOW_SIZE[0])
        self.setMinimumHeight(MAIN_WINDOW_SIZE[1])

        self.statusbar = QtGui.QStatusBar(self)
        self.statusbar.showMessage("Status message")
        self.setStatusBar(self.statusbar)

        ################################################

        self.menubar = self.menuBar()
        # Any menu action makes the status bar message disappear

        fileMenu = QtGui.QMenu(self.menubar)
        fileMenu.setTitle("File")
        self.menubar.addAction(fileMenu.menuAction())

        newAction = QtGui.QAction("New", self)
        newAction.setIcon(QtGui.QtIcon(icons + '/GroupPropDialog_image0.png'))
        fileMenu.addAction(newAction)
        openAction = QtGui.QAction("Open", self)
        openAction.setIcon(QtGui.QtIcon(icons + "/MainWindowUI_image1"))
        fileMenu.addAction(openAction)
        saveAction = QtGui.QAction("Save", self)
        saveAction.setIcon(QtGui.QtIcon(icons + "/MainWindowUI_image2"))
        fileMenu.addAction(saveAction)

        self.connect(newAction,SIGNAL("activated()"),self.fileNew)
        self.connect(openAction,SIGNAL("activated()"),self.fileOpen)
        self.connect(saveAction,SIGNAL("activated()"),self.fileSave)

        for otherMenuName in ('Edit', 'View', 'Display', 'Select', 'Modify', 'NanoHive-1'):
            otherMenu = QtGui.QMenu(self.menubar)
            otherMenu.setTitle(otherMenuName)
            self.menubar.addAction(otherMenu.menuAction())

        helpMenu = QtGui.QMenu(self.menubar)
        helpMenu.setTitle("Help")
        self.menubar.addAction(helpMenu.menuAction())

        aboutAction = QtGui.QAction("About", self)
        aboutAction.setIcon(QtGui.QtIcon(icons + '/MainWindowUI_image0.png'))
        helpMenu.addAction(aboutAction)

        self.connect(aboutAction,SIGNAL("activated()"),self.helpAbout)

        ##############################################

        self.setMenuBar(self.menubar)

        centralwidget = QWidget()
        self.setCentralWidget(centralwidget)
        layout = QVBoxLayout(centralwidget)
        layout.setMargin(0)
        layout.setSpacing(0)
        middlewidget = QWidget()

        self.bigButtons = QWidget()
        bblo = QHBoxLayout(self.bigButtons)
        bblo.setMargin(0)
        bblo.setSpacing(0)
        self.bigButtons.setMinimumHeight(50)
        self.bigButtons.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        for name in ('Features', 'Sketch', 'Build', 'Dimension', 'Simulator'):
            btn = QPushButton(self.bigButtons)
            btn.setMaximumWidth(80)
            btn.setMinimumHeight(50)
            btn.setText(name)
            self.bigButtons.layout().addWidget(btn)
        self.bigButtons.hide()
        layout.addWidget(self.bigButtons)

        self.littleIcons = QWidget()
        self.littleIcons.setMinimumHeight(30)
        self.littleIcons.setMaximumHeight(30)
        lilo = QHBoxLayout(self.littleIcons)
        lilo.setMargin(0)
        lilo.setSpacing(0)
        pb = QPushButton(self.littleIcons)
        pb.setIcon(QIcon(icons + '/GroupPropDialog_image0.png'))
        self.connect(pb,SIGNAL("clicked()"),self.fileNew)
        lilo.addWidget(pb)
        for x in "1 2 4 5 6 7 8 18 42 10 43 150 93 94 97 137".split():
            pb = QPushButton(self.littleIcons)
            pb.setIcon(QIcon(icons + '/MainWindowUI_image' + x + '.png'))
            lilo.addWidget(pb)
        layout.addWidget(self.littleIcons)

        layout.addWidget(middlewidget)

        self.layout = QGridLayout(middlewidget)
        self.layout.setMargin(0)
        self.layout.setSpacing(2)
        self.gridPosition = GridPosition()
        self.numParts = 0

        self.show()
        explainWindow = AboutWindow("Select <b>Help-&gt;About</b>"
                                    " for instructions...",
                                    200, 3)