コード例 #1
0
ファイル: text.py プロジェクト: Hainish/calibre
 def apply_theme(self, theme):
     self.theme = theme
     pal = self.palette()
     pal.setColor(pal.Base, theme_color(theme, 'Normal', 'bg'))
     pal.setColor(pal.AlternateBase, theme_color(theme, 'CursorLine', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'Normal', 'fg'))
     pal.setColor(pal.Highlight, theme_color(theme, 'Visual', 'bg'))
     pal.setColor(pal.HighlightedText, theme_color(theme, 'Visual', 'fg'))
     self.setPalette(pal)
     self.tooltip_palette = pal = QPalette()
     pal.setColor(pal.ToolTipBase, theme_color(theme, 'Tooltip', 'bg'))
     pal.setColor(pal.ToolTipText, theme_color(theme, 'Tooltip', 'fg'))
     self.line_number_palette = pal = QPalette()
     pal.setColor(pal.Base, theme_color(theme, 'LineNr', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'LineNr', 'fg'))
     pal.setColor(pal.BrightText, theme_color(theme, 'LineNrC', 'fg'))
     self.match_paren_format = theme_format(theme, 'MatchParen')
     font = self.font()
     ff = tprefs['editor_font_family']
     if ff is None:
         ff = default_font_family()
     font.setFamily(ff)
     font.setPointSize(tprefs['editor_font_size'])
     self.tooltip_font = QFont(font)
     self.tooltip_font.setPointSize(font.pointSize() - 1)
     self.setFont(font)
     self.highlighter.apply_theme(theme)
     w = self.fontMetrics()
     self.number_width = max(map(lambda x: w.width(str(x)), xrange(10)))
     self.size_hint = QSize(100 * w.averageCharWidth(), 50 * w.height())
     self.highlight_color = theme_color(theme, 'HighlightRegion', 'bg')
     self.highlight_cursor_line()
コード例 #2
0
 def _getHeaderTitlePalette(self):
     """
     Return a palette for header title (text) label. 
     """
     palette = QPalette()
     palette.setColor(QPalette.WindowText, pmHeaderTitleColor)
     return palette
コード例 #3
0
ファイル: prefs_widgets.py プロジェクト: vcsrc/nanoengineer
 def colorframe_bgcolor_setter(color):
     #e no convenient/clean way for Formula API to permit but not require this function to receive the formula,
     # unless we store it temporarily in env._formula (which we might as well do if this feature is ever needed)
     try:
         # make sure errors here don't stop the formula from running:
         # (Need to protect against certain kinds of erroneous color values? RGBf_to_QColor does it well enough.)
         ## Qt3 code used: colorframe.setPaletteBackgroundColor(RGBf_to_QColor(color))
         qcolor = RGBf_to_QColor(color)
         palette = QPalette(
         )  # QPalette(qcolor) would have window color set from qcolor, but that doesn't help us here
         qcolorrole = QPalette.Window
         ## http://doc.trolltech.com/4.2/qpalette.html#ColorRole-enum says:
         ##   QPalette.Window    10    A general background color.
         palette.setColor(QPalette.Active, qcolorrole,
                          qcolor)  # used when window is in fg and has focus
         palette.setColor(
             QPalette.Inactive, qcolorrole,
             qcolor)  # used when window is in bg or does not have focus
         palette.setColor(QPalette.Disabled, qcolorrole,
                          qcolor)  # used when widget is disabled
         colorframe.setPalette(palette)
         colorframe.setAutoFillBackground(True)
         # [Note: the above scheme was revised again by bruce 070430, for improved appearance
         #  (now has thin black border around color patch), based on Ninad's change in UserPrefs.py.]
         ## no longer needed: set color for qcolorrole = QPalette.ColorRole(role) for role in range(14)
         ## no longer needed: colorframe.setLineWidth(500) # width of outline of frame (at least half max possible size)
     except:
         print "data for following exception: ",
         print "colorframe %r has palette %r" % (colorframe,
                                                 colorframe.palette())
         # fyi: in Qt4, like in Qt3, colorframe is a QFrame
         print_compact_traceback(
             "bug (ignored): exception in formula-setter: "
         )  #e include formula obj in this msg?
     pass
コード例 #4
0
ファイル: PM_Colors.py プロジェクト: elfion/nanoengineer
def getPalette(palette, colorRole, color):
    """
    Assigns a color (based on color role) to palette and returns it.
    The color/color role is assigned to all color groups.
            
    @param palette: A palette. If palette is None, we create and return a new 
                   palette.
    @type  palette: QPalette
    
    @param colorRole: the Qt ColorRole
    @type  colorRole: Qt.ColorRole
    
    @param color: color
    @type  color: QColor
    
    @return: Returns the updated palette, or a new palette if none was supplied.
    @rtype : QPalette
    
    @see QPalette.setColor()
    """
    if palette:
        pass  # Make sure palette is QPalette.
    else:
        palette = QPalette()

    palette.setColor(colorRole, color)

    return palette
コード例 #5
0
 def _updateColorFrame(self):
     """
     Updates the color frame with the current color.
     """
     colorframe = self.colorFrame
     try:
         qcolor = self.getQColor()
         palette = QPalette(
         )  # QPalette(qcolor) would have window color set from qcolor, but that doesn't help us here
         qcolorrole = QPalette.Window
         ## http://doc.trolltech.com/4.2/qpalette.html#ColorRole-enum says:
         ##   QPalette.Window    10    A general background color.
         palette.setColor(QPalette.Active, qcolorrole,
                          qcolor)  # used when window is in fg and has focus
         palette.setColor(
             QPalette.Inactive, qcolorrole,
             qcolor)  # used when window is in bg or does not have focus
         palette.setColor(QPalette.Disabled, qcolorrole,
                          qcolor)  # used when widget is disabled
         colorframe.setPalette(palette)
         colorframe.setAutoFillBackground(True)
     except:
         print "data for following exception: ",
         print "colorframe %r has palette %r" % (colorframe,
                                                 colorframe.palette())
     pass
コード例 #6
0
    def __init__(self, name, iconPath="", title=""):
        """
        Property Manager constructor.

        @param name: the name to assign the property manager dialog object.
        @type  name: str

        @param iconPath: the relative path for the icon (PNG image) that
                         appears in the header.
        @type  iconPath: str

        @param title: the title that appears in the header.
        @type  title: str
        """

        QDialog.__init__(self)

        self.setObjectName(name)
        self._widgetList = []

        # Main pallete for PropMgr.

        self.setPalette(QPalette(pmColor))

        # Main vertical layout for PropMgr.
        self.vBoxLayout = QVBoxLayout(self)
        self.vBoxLayout.setMargin(PM_MAINVBOXLAYOUT_MARGIN)
        self.vBoxLayout.setSpacing(PM_MAINVBOXLAYOUT_SPACING)

        # Add PropMgr's header, sponsor button, top row buttons and (hidden)
        # message group box.
        self._createHeader(iconPath, title)
        self._createSponsorButton()
        self._createTopRowBtns()  # Create top buttons row

        self.MessageGroupBox = PM_MessageGroupBox(self)

        # Keep the line below around; it might be useful.
        # I may want to use it now that I understand it.
        # Mark 2007-05-17.
        #QMetaObject.connectSlotsByName(self)

        self._addGroupBoxes()

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

        try:
            self._addToolTipText()
        except:
            print_compact_traceback("Error loading tool tip text for this "
                                    "property manager: ")

        #The following attr is used for comparison in method
        #'_update_UI_wanted_as_something_changed'
        self._previous_all_change_indicators = None
コード例 #7
0
    def __init__(self,
            prompt='>>> ',
            continuation='... ',
            parent=None):
        QTextEdit.__init__(self, parent)
        self.shutting_down = False
        self.compiler = CommandCompiler()
        self.buf = self.old_buf = []
        self.history = History([''], dynamic.get('console_history', []))
        self.prompt_frame = None
        self.allow_output = False
        self.prompt_frame_format = QTextFrameFormat()
        self.prompt_frame_format.setBorder(1)
        self.prompt_frame_format.setBorderStyle(QTextFrameFormat.BorderStyle_Solid)
        self.prompt_len = len(prompt)

        self.doc.setMaximumBlockCount(int(prefs['scrollback']))
        self.lexer = PythonLexer(ensurenl=False)
        self.tb_lexer = PythonTracebackLexer()

        self.context_menu = cm = QMenu(self) # {{{
        cm.theme = ThemeMenu(cm)
        # }}}

        self.formatter = Formatter(prompt, continuation, style=prefs['theme'])
        p = QPalette()
        p.setColor(p.Base, QColor(self.formatter.background_color))
        p.setColor(p.Text, QColor(self.formatter.color))
        self.setPalette(p)

        self.key_dispatcher = { # {{{
                Qt.Key_Enter : self.enter_pressed,
                Qt.Key_Return : self.enter_pressed,
                Qt.Key_Up : self.up_pressed,
                Qt.Key_Down : self.down_pressed,
                Qt.Key_Home : self.home_pressed,
                Qt.Key_End : self.end_pressed,
                Qt.Key_Left : self.left_pressed,
                Qt.Key_Right : self.right_pressed,
                Qt.Key_Backspace : self.backspace_pressed,
                Qt.Key_Delete : self.delete_pressed,
        } # }}}

        motd = textwrap.dedent('''\
        # Python {0}
        # {1} {2}
        '''.format(sys.version.splitlines()[0], __appname__,
            __version__))

        sys.excepthook = self.unhandled_exception

        self.controllers = []
        QTimer.singleShot(0, self.launch_controller)


        with EditBlock(self.cursor):
            self.render_block(motd)
コード例 #8
0
ファイル: alternate_views.py プロジェクト: smalldek/calibre
 def set_color(self):
     r, g, b = gprefs['cover_grid_color']
     pal = QPalette()
     col = QColor(r, g, b)
     pal.setColor(pal.Base, col)
     dark = (r + g + b) / 3.0 < 128
     pal.setColor(pal.Text, QColor(Qt.white if dark else Qt.black))
     self.setPalette(pal)
     self.delegate.highlight_color = pal.color(pal.Text)
コード例 #9
0
ファイル: base.py プロジェクト: VirtualPlants/flowerdemo
    def init(self):
        self.backButton.init()
        self.setForegroundColor(QColor(0, 0, 0))

        palette = QPalette(self.bottomwidget.palette())
        palette.setColor(QPalette.Background,
                         self.backgroundColor())  #Qt.black)
        self.bottomwidget.setAutoFillBackground(True)
        self.bottomwidget.setPalette(palette)
コード例 #10
0
    def _createHeader(self, iconPath, title):
        """
        Creates the Property Manager header, which contains an icon
        (a QLabel with a pixmap) and white text (a QLabel with text).
        
        @param iconPath: The relative path for the icon (PNG image) that 
                         appears in the header.
        @type  iconPath: str
        
        @param title: The title that appears in the header.
        @type  title: str
        """

        # Heading frame (dark gray), which contains
        # a pixmap and (white) heading text.
        self.headerFrame = QFrame(self)
        self.headerFrame.setFrameShape(QFrame.NoFrame)
        self.headerFrame.setFrameShadow(QFrame.Plain)

        self.headerFrame.setPalette(QPalette(pmHeaderFrameColor))
        self.headerFrame.setAutoFillBackground(True)

        # HBox layout for heading frame, containing the pixmap
        # and label (title).
        HeaderFrameHLayout = QHBoxLayout(self.headerFrame)
        # 2 pixels around edges --
        HeaderFrameHLayout.setMargin(PM_HEADER_FRAME_MARGIN)
        # 5 pixel between pixmap and label. --
        HeaderFrameHLayout.setSpacing(PM_HEADER_FRAME_SPACING)

        # PropMgr icon. Set image by calling setHeaderIcon().
        self.headerIcon = QLabel(self.headerFrame)
        self.headerIcon.setSizePolicy(
            QSizePolicy(QSizePolicy.Policy(QSizePolicy.Fixed),
                        QSizePolicy.Policy(QSizePolicy.Fixed)))

        self.headerIcon.setScaledContents(True)

        HeaderFrameHLayout.addWidget(self.headerIcon)

        # PropMgr header title text (a QLabel).
        self.headerTitle = QLabel(self.headerFrame)
        headerTitlePalette = self._getHeaderTitlePalette()
        self.headerTitle.setPalette(headerTitlePalette)
        self.headerTitle.setAlignment(PM_LABEL_LEFT_ALIGNMENT)

        # Assign header title font.
        self.headerTitle.setFont(self._getHeaderFont())
        HeaderFrameHLayout.addWidget(self.headerTitle)

        self.vBoxLayout.addWidget(self.headerFrame)

        # Set header icon and title text.
        self.setHeaderIcon(iconPath)
        self.setHeaderTitle(title)
コード例 #11
0
    def load_calibre_style(self):
        # On OS X QtCurve resets the palette, so we preserve it explicitly
        orig_pal = QPalette(self.palette())

        path = os.path.join(sys.extensions_location,
                            'calibre_style.' + ('pyd' if iswindows else 'so'))
        if not self.pi.load_style(path, 'Calibre'):
            prints('Failed to load calibre style')
        # On OSX, on some machines, colors can be invalid. See https://bugs.launchpad.net/bugs/1014900
        for role in (orig_pal.Button, orig_pal.Window):
            c = orig_pal.brush(role).color()
            if not c.isValid() or not c.toRgb().isValid():
                orig_pal.setColor(role, QColor(u'lightgray'))

        self.setPalette(orig_pal)
        style = self.style()
        icon_map = {}
        pcache = {}
        for k, v in {
                'DialogYesButton': u'ok.png',
                'DialogNoButton': u'window-close.png',
                'DialogCloseButton': u'window-close.png',
                'DialogOkButton': u'ok.png',
                'DialogCancelButton': u'window-close.png',
                'DialogHelpButton': u'help.png',
                'DialogOpenButton': u'document_open.png',
                'DialogSaveButton': u'save.png',
                'DialogApplyButton': u'ok.png',
                'DialogDiscardButton': u'trash.png',
                'MessageBoxInformation': u'dialog_information.png',
                'MessageBoxWarning': u'dialog_warning.png',
                'MessageBoxCritical': u'dialog_error.png',
                'MessageBoxQuestion': u'dialog_question.png',
                'BrowserReload': u'view-refresh.png',
                # These two are used to calculate the sizes for the doc widget
                # title bar buttons, therefore, they have to exist. The actual
                # icon is not used.
                'TitleBarCloseButton': u'window-close.png',
                'TitleBarNormalButton': u'window-close.png',
                'DockWidgetCloseButton': u'window-close.png',
        }.iteritems():
            if v not in pcache:
                p = I(v)
                if isinstance(p, bytes):
                    p = p.decode(filesystem_encoding)
                # if not os.path.exists(p): raise ValueError(p)
                pcache[v] = p
            v = pcache[v]
            icon_map[type('')(getattr(style, 'SP_' + k))] = v
        style.setProperty(u'calibre_icon_map', icon_map)
        self.__icon_map_memory_ = icon_map
コード例 #12
0
ファイル: alternate_views.py プロジェクト: Gondulf/calibre
 def set_color(self):
     r, g, b = gprefs['cover_grid_color']
     pal = QPalette()
     col = QColor(r, g, b)
     pal.setColor(pal.Base, col)
     tex = gprefs['cover_grid_texture']
     if tex:
         from calibre.gui2.preferences.texture_chooser import texture_path
         path = texture_path(tex)
         if path:
             pal.setBrush(pal.Base, QBrush(QPixmap(path)))
     dark = (r + g + b)/3.0 < 128
     pal.setColor(pal.Text, QColor(Qt.white if dark else Qt.black))
     self.setPalette(pal)
     self.delegate.highlight_color = pal.color(pal.Text)
コード例 #13
0
    def _set_widget_erase_color(self):  # revised, bruce 071011
        """
        Change this widget's erase color (seen only if it's resized,
        and only briefly -- it's independent of OpenGL clearColor) to
        self.backgroundColor. This is intended to minimize the visual
        effect of widget resizes which temporarily show the erase
        color. See comments in this method for caveats about that.
        """
        # Note: this was called in GLPane.update_after_new_graphicsMode
        # when the graphicsMode could determine the background color,
        # but that's no longer true, so it could probably
        # just be called at startup and whenever the background color is changed.
        # Try that sometime, it might be an optim. For now it continues
        # to be called from there. [bruce 071011, still true 080910]
        #
        # REVIEW: what is self.backgroundColor when we're using the new default
        # of "Blue Sky Gradient". For best effect here, what it ought to be
        # is the average or central bg color in that gradient. I think it's not,
        # which makes me wonder if this bugfix is still needed at all. [bruce 071011]
        #
        # Note: calling this fixed the bug in which the glpane or its edges
        # flickered to black during a main-window resize. [bruce 050408]
        #
        # Note: limited this to Mac [in caller], since it turns out that bug (which has
        # no bug number yet) was Mac-specific, but this change caused a new bug 530
        # on Windows. (Not sure about Linux.) See also bug 141 (black during
        # mode-change), related but different. [bruce 050413]
        #
        # Note: for graphicsModes with a translucent surface covering the screen
        # (i.e. Build Atoms water surface), it would be better to blend that surface
        # color with self.backgroundColor for passing to this method, to approximate
        # the effective background color. Alternatively, we could change how those
        # graphicsModes set up OpenGL clearcolor, so that their empty space areas
        # looked like self.backgroundColor.) [bruce 050615 comment]

        bgcolor = self.backgroundColor
        r = int(bgcolor[0] * 255 +
                0.5)  # (same formula as in elementSelector.py)
        g = int(bgcolor[1] * 255 + 0.5)
        b = int(bgcolor[2] * 255 + 0.5)
        pal = QPalette()
        pal.setColor(self.backgroundRole(), QColor(r, g, b))
        self.setPalette(pal)
        # see Qt docs for this and for backgroundRole
        return
コード例 #14
0
    def load_calibre_style(self):
        # On OS X QtCurve resets the palette, so we preserve it explicitly
        orig_pal = QPalette(self.palette())

        from calibre.constants import plugins
        pi = plugins['progress_indicator'][0]
        path = os.path.join(sys.extensions_location,
                            'calibre_style.' + ('pyd' if iswindows else 'so'))
        pi.load_style(path, 'Calibre')
        # On OSX, on some machines, colors can be invalid. See https://bugs.launchpad.net/bugs/1014900
        for role in (orig_pal.Button, orig_pal.Window):
            c = orig_pal.brush(role).color()
            if not c.isValid() or not c.toRgb().isValid():
                orig_pal.setColor(role, QColor(u'lightgray'))

        self.setPalette(orig_pal)
        style = self.style()
        icon_map = {}
        pcache = {}
        for k, v in {
                'DialogYesButton': u'ok.png',
                'DialogNoButton': u'window-close.png',
                'DialogCloseButton': u'window-close.png',
                'DialogOkButton': u'ok.png',
                'DialogCancelButton': u'window-close.png',
                'DialogHelpButton': u'help.png',
                'DialogOpenButton': u'document_open.png',
                'DialogSaveButton': u'save.png',
                'DialogApplyButton': u'ok.png',
                'DialogDiscardButton': u'trash.png',
                'MessageBoxInformation': u'dialog_information.png',
                'MessageBoxWarning': u'dialog_warning.png',
                'MessageBoxCritical': u'dialog_error.png',
                'MessageBoxQuestion': u'dialog_question.png',
        }.iteritems():
            if v not in pcache:
                p = I(v)
                if isinstance(p, bytes):
                    p = p.decode(filesystem_encoding)
                # if not os.path.exists(p): raise ValueError(p)
                pcache[v] = p
            v = pcache[v]
            icon_map[type('')(getattr(style, 'SP_' + k))] = v
        style.setProperty(u'calibre_icon_map', icon_map)
        self.__icon_map_memory_ = icon_map
コード例 #15
0
    def _initialize_collections(self):
        '''
        Populate the data model with current collection assignments
        Hook click, doubleClick events
        '''
        self._log_location()

        # Set the bg color of the description text fields to the dialog bg color
        if False:
            bgcolor = self.palette().color(QPalette.Background)
            palette = QPalette()
            palette.setColor(QPalette.Base, bgcolor)
            self.calibre_lw.setPalette(palette)
            self.marvin_lw.setPalette(palette)

        if self.calibre_collections is not None:
            for ca in self.calibre_collections:
                item = ListWidgetItem(ca)
                item.setData(Qt.UserRole, ca)
                if RENAMING_ENABLED:
                    item.setFlags(item.flags() | Qt.ItemIsEditable)
                self.calibre_lw.addItem(item)

        for ma in self.marvin_collections:
            item = ListWidgetItem(ma)
            item.setData(Qt.UserRole, ma)
            if RENAMING_ENABLED:
                item.setFlags(item.flags() | Qt.ItemIsEditable)
            self.marvin_lw.addItem(item)

        # Capture click events to clear selections in opposite list
        self.calibre_lw.clicked.connect(self._clear_marvin_selection)
        self.marvin_lw.clicked.connect(self._clear_calibre_selection)

        # Hook double-click events
        if RENAMING_ENABLED:
            self.calibre_lw.doubleClicked.connect(self.rename_calibre_tag)
            self.marvin_lw.doubleClicked.connect(self.rename_marvin_tag)

        # Enable sorting
        if self.calibre_collections is not None:
            self.calibre_lw.setSortingEnabled(True)
        self.marvin_lw.setSortingEnabled(True)
コード例 #16
0
 def set_color(self):
     r, g, b = gprefs['cover_grid_color']
     pal = QPalette()
     col = QColor(r, g, b)
     pal.setColor(pal.Base, col)
     tex = gprefs['cover_grid_texture']
     if tex:
         from calibre.gui2.preferences.texture_chooser import texture_path
         path = texture_path(tex)
         if path:
             pm = QPixmap(path)
             if not pm.isNull():
                 val = pm.scaled(1, 1).toImage().pixel(0, 0)
                 r, g, b = qRed(val), qGreen(val), qBlue(val)
                 pal.setBrush(pal.Base, QBrush(pm))
     dark = (r + g + b) / 3.0 < 128
     pal.setColor(pal.Text, QColor(Qt.white if dark else Qt.black))
     self.setPalette(pal)
     self.delegate.highlight_color = pal.color(pal.Text)
コード例 #17
0
    def _populate_description(self):
        # Set the bg color of the description text fields to the dialog bg color
        bgcolor = self.palette().color(QPalette.Background)
        palette = QPalette()
        palette.setColor(QPalette.Base, bgcolor)
        self.calibre_description.setPalette(palette)
        self.marvin_description.setPalette(palette)

        if 'comments' in self.mismatches:
            self.calibre_description_label.setText(
                self.YELLOW_BG.format("<b>Description</b>"))
            if self.mismatches['comments']['calibre']:
                self.calibre_description.setText(
                    self.mismatches['comments']['calibre'])

            self.marvin_description_label.setText(
                self.YELLOW_BG.format("<b>Description</b>"))
            if self.mismatches['comments']['Marvin']:
                self.marvin_description.setText(
                    self.mismatches['comments']['Marvin'])
        else:
            if self.installed_book.comments:
                self.calibre_description.setText(self.installed_book.comments)
                self.marvin_description.setText(self.installed_book.comments)
コード例 #18
0
    def initialize(self,
                   parent,
                   content,
                   book_id,
                   installed_book,
                   marvin_db_path,
                   use_qwv=True):
        '''
        __init__ is called on SizePersistedDialog()
        '''
        self.setupUi(self)
        self.book_id = book_id
        self.connected_device = parent.opts.gui.device_manager.device
        self.installed_book = installed_book
        self.marvin_db_path = marvin_db_path
        self.opts = parent.opts
        self.parent = parent
        self.stored_command = None
        self.verbose = parent.verbose
        self._log_location(installed_book.title)

        # Subscribe to Marvin driver change events
        self.connected_device.marvin_device_signals.reader_app_status_changed.connect(
            self.marvin_status_changed)

        # Set the icon
        self.setWindowIcon(self.parent.icon)

        # Set or hide the header
        if content['header']:
            self.header.setText(content['header'])
        else:
            self.header.setVisible(False)

        # Set the titles
        self.setWindowTitle(content['title'])
        self.html_gb.setTitle(content['group_box_title'])
        if content['toolTip']:
            self.html_gb.setToolTip(content['toolTip'])

        # Set the bg color of the content to the dialog bg color
        bgcolor = self.palette().color(QPalette.Background)
        palette = QPalette()
        palette.setColor(QPalette.Base, bgcolor)

        #self._log(repr(content['html_content']))

        # Initialize the window content
        if use_qwv:
            # Add a QWebView to layout
            self.html_wv = QWebView()
            self.html_wv.setHtml(content['html_content'])
            self.html_wv.sizeHint = self.wv_sizeHint
            self.html_wv.setSizePolicy(QSizePolicy.MinimumExpanding,
                                       QSizePolicy.MinimumExpanding)
            self.html_wv.page().setLinkDelegationPolicy(
                QWebPage.DelegateAllLinks)
            self.html_wv.linkClicked.connect(self.link_clicked)

            self.html_gb_vl.addWidget(self.html_wv)
            self.html_tb.setVisible(False)
        else:
            # Initialize the contents of the TextBrowser
            self.html_tb.setText(content['html_content'])
            #self.html_tb.setPalette(palette)

        # Set or hide the footer
        if content['footer']:
            self.footer.setText(content['footer'])
        else:
            self.footer.setVisible(False)

        # Add Copy to Clipboard button
        self.ctc_button = self.bb.addButton('&Copy to clipboard',
                                            self.bb.ActionRole)
        self.ctc_button.clicked.connect(self.copy_to_clipboard)
        self.ctc_button.setIcon(QIcon(I('edit-copy.png')))
        self.ctc_button.setObjectName('copy_to_clipboard_button')
        self.ctc_button.setToolTip(
            '<p>Copy plain text to clipboard, <b>Alt/Option-click</b> for HTML</p>'
        )

        self.copy_action = QAction(self)
        self.addAction(self.copy_action)
        self.copy_action.setShortcuts(QKeySequence.Copy)
        self.copy_action.triggered.connect(self.copy_to_clipboard)

        # Add Refresh button if enabled
        if content['refresh']:
            self.refresh_method = content['refresh']['method']
            self.refresh_button = self.bb.addButton(
                "Refresh '%s'" % content['refresh']['name'],
                self.bb.ActionRole)
            self.refresh_button.setIcon(
                QIcon(
                    os.path.join(self.parent.opts.resources_path, 'icons',
                                 'from_marvin.png')))
            self.refresh_button.setObjectName('refresh_button')
            self.refresh_button.setEnabled(bool(self.installed_book.cid))

        # Hook the button events
        self.bb.clicked.connect(self.dispatch_button_click)

        # Restore position
        self.resize_dialog()
コード例 #19
0
ファイル: view.py プロジェクト: mrmac123/calibre
 def __init__(self, right=False, parent=None, show_open_in_editor=False):
     PlainTextEdit.__init__(self, parent)
     self.setFrameStyle(0)
     self.show_open_in_editor = show_open_in_editor
     self.side_margin = 0
     self.setContextMenuPolicy(Qt.CustomContextMenu)
     self.customContextMenuRequested.connect(self.show_context_menu)
     self.setFocusPolicy(Qt.NoFocus)
     self.right = right
     self.setReadOnly(True)
     w = self.fontMetrics()
     self.number_width = max(map(lambda x: w.width(str(x)), xrange(10)))
     self.space_width = w.width(' ')
     self.setLineWrapMode(self.WidgetWidth)
     self.setTabStopWidth(tprefs['editor_tab_stop_width'] *
                          self.space_width)
     font = self.font()
     ff = tprefs['editor_font_family']
     if ff is None:
         ff = default_font_family()
     font.setFamily(ff)
     font.setPointSize(tprefs['editor_font_size'])
     self.setFont(font)
     font = self.heading_font = QFont(self.font())
     font.setPointSize(int(tprefs['editor_font_size'] * 1.5))
     font.setBold(True)
     theme = get_theme(tprefs['editor_theme'])
     pal = self.palette()
     pal.setColor(pal.Base, theme_color(theme, 'Normal', 'bg'))
     pal.setColor(pal.AlternateBase, theme_color(theme, 'CursorLine', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'Normal', 'fg'))
     pal.setColor(pal.Highlight, theme_color(theme, 'Visual', 'bg'))
     pal.setColor(pal.HighlightedText, theme_color(theme, 'Visual', 'fg'))
     self.setPalette(pal)
     self.viewport().setCursor(Qt.ArrowCursor)
     self.line_number_area = LineNumbers(self)
     self.blockCountChanged[int].connect(self.update_line_number_area_width)
     self.updateRequest.connect(self.update_line_number_area)
     self.line_number_palette = pal = QPalette()
     pal.setColor(pal.Base, theme_color(theme, 'LineNr', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'LineNr', 'fg'))
     pal.setColor(pal.BrightText, theme_color(theme, 'LineNrC', 'fg'))
     self.line_number_map = LineNumberMap()
     self.search_header_pos = 0
     self.changes, self.headers, self.images = [], [], OrderedDict()
     self.setVerticalScrollBarPolicy(
         Qt.ScrollBarAlwaysOff), self.setHorizontalScrollBarPolicy(
             Qt.ScrollBarAlwaysOff)
     self.diff_backgrounds = {
         'replace':
         theme_color(theme, 'DiffReplace', 'bg'),
         'insert':
         theme_color(theme, 'DiffInsert', 'bg'),
         'delete':
         theme_color(theme, 'DiffDelete', 'bg'),
         'replacereplace':
         theme_color(theme, 'DiffReplaceReplace', 'bg'),
         'boundary':
         QBrush(theme_color(theme, 'Normal', 'fg'), Qt.Dense7Pattern),
     }
     self.diff_foregrounds = {
         'replace': theme_color(theme, 'DiffReplace', 'fg'),
         'insert': theme_color(theme, 'DiffInsert', 'fg'),
         'delete': theme_color(theme, 'DiffDelete', 'fg'),
         'boundary': QColor(0, 0, 0, 0),
     }
     for x in ('replacereplace', 'insert', 'delete'):
         f = QTextCharFormat()
         f.setBackground(self.diff_backgrounds[x])
         setattr(self, '%s_format' % x, f)
コード例 #20
0
    def initialize(self, parent, book_id, cid, installed_book,
                   enable_metadata_updates, marvin_db_path):
        '''
        __init__ is called on SizePersistedDialog()
        shared attributes of interest:
            .authors
            .author_sort
            .cover_hash
            .pubdate
            .publisher
            .series
            .series_index
            .title
            .title_sort
            .comments
            .tags
            .uuid
        '''
        self.setupUi(self)
        self.book_id = book_id
        self.cid = cid
        self.connected_device = parent.opts.gui.device_manager.device
        self.installed_book = installed_book
        self.marvin_db_path = marvin_db_path
        self.opts = parent.opts
        self.parent = parent
        self.stored_command = None
        self.verbose = parent.verbose
        self.BORDER_LR = 4
        self.BORDER_TB = 8
        self.GREY_FG = '<font style="color:#A0A0A0">{0}</font>'
        self.YELLOW_BG = '<font style="background:#FDFF99">{0}</font>'

        self._log_location(installed_book.title)

        # Subscribe to Marvin driver change events
        self.connected_device.marvin_device_signals.reader_app_status_changed.connect(
            self.marvin_status_changed)

        #self._log("mismatches:\n%s" % repr(installed_book.metadata_mismatches))
        self.mismatches = installed_book.metadata_mismatches

        self._populate_title()
        self._populate_title_sort()
        self._populate_series()
        self._populate_authors()
        self._populate_author_sort()
        self._populate_uuid()
        self._populate_covers()
        self._populate_subjects()
        self._populate_publisher()
        self._populate_pubdate()
        self._populate_description()

        # ~~~~~~~~ Export to Marvin button ~~~~~~~~
        self.export_to_marvin_button.setIcon(
            QIcon(
                os.path.join(self.parent.opts.resources_path, 'icons',
                             'from_calibre.png')))
        self.export_to_marvin_button.clicked.connect(
            partial(self.store_command, 'export_metadata'))
        self.export_to_marvin_button.setEnabled(enable_metadata_updates)

        # ~~~~~~~~ Import from Marvin button ~~~~~~~~
        self.import_from_marvin_button.setIcon(
            QIcon(
                os.path.join(self.parent.opts.resources_path, 'icons',
                             'from_marvin.png')))
        self.import_from_marvin_button.clicked.connect(
            partial(self.store_command, 'import_metadata'))
        self.import_from_marvin_button.setEnabled(enable_metadata_updates)

        # If no calibre book, or no mismatches, adjust the display accordingly
        if not self.cid:
            #self._log("self.cid: %s" % repr(self.cid))
            #self._log("self.mismatches: %s" % repr(self.mismatches))
            self.calibre_gb.setVisible(False)
            self.import_from_marvin_button.setVisible(False)
            self.setWindowTitle(u'Marvin metadata')
        elif not self.mismatches:
            # Show both panels, but hide the transfer buttons
            self.export_to_marvin_button.setVisible(False)
            self.import_from_marvin_button.setVisible(False)
        else:
            self.setWindowTitle(u'Metadata Summary')

        if False:
            # Set the Marvin QGroupBox to Marvin red
            marvin_red = QColor()
            marvin_red.setRgb(189, 17, 20, alpha=255)
            palette = QPalette()
            palette.setColor(QPalette.Background, marvin_red)
            self.marvin_gb.setPalette(palette)

        # ~~~~~~~~ Add a Close or Cancel button ~~~~~~~~
        self.close_button = QPushButton(QIcon(I('window-close.png')), 'Close')
        if self.mismatches:
            self.close_button.setText('Cancel')
        self.bb.addButton(self.close_button, QDialogButtonBox.RejectRole)

        self.bb.clicked.connect(self.dispatch_button_click)

        # Restore position
        self.resize_dialog()
コード例 #21
0
    def initGraphics(self):

        # LED color palettes
        self.green_palette = QPalette()
        self.green_palette.setColor(QPalette.Window, QColor(0, 255, 0))

        self.red_palette = QPalette()
        self.red_palette.setColor(QPalette.Window, QColor(255, 0, 0))

        self.yellow_palette = QPalette()
        self.yellow_palette.setColor(QPalette.Window, QColor(200, 200, 50))

        self.gray_palette = QPalette()
        self.gray_palette.setColor(QPalette.Window, QColor(80, 80, 80))

        # CAN RX LEDs
        self._widget.throttle_led.setText('')
        self._widget.throttle_led.setPalette(self.red_palette)
        self._widget.brake_led.setText('')
        self._widget.brake_led.setPalette(self.red_palette)
        self._widget.steering_led.setText('')
        self._widget.steering_led.setPalette(self.red_palette)
        self._widget.gear_led.setText('')
        self._widget.gear_led.setPalette(self.red_palette)

        # BOO LED
        self._widget.boo_led.setText('')
        self._widget.boo_led.setPalette(self.gray_palette)

        # Fault and driver override LEDs
        self._widget.throttle_driver_led.setText('')
        self._widget.throttle_driver_led.setPalette(self.gray_palette)
        self._widget.throttle_flt1_led.setText('')
        self._widget.throttle_flt1_led.setPalette(self.gray_palette)
        self._widget.throttle_flt2_led.setText('')
        self._widget.throttle_flt2_led.setPalette(self.gray_palette)
        self._widget.throttle_fltcon_led.setText('')
        self._widget.throttle_fltcon_led.setPalette(self.gray_palette)

        self._widget.brake_driver_led.setText('')
        self._widget.brake_driver_led.setPalette(self.gray_palette)
        self._widget.brake_flt1_led.setText('')
        self._widget.brake_flt1_led.setPalette(self.gray_palette)
        self._widget.brake_flt2_led.setText('')
        self._widget.brake_flt2_led.setPalette(self.gray_palette)
        self._widget.brake_fltcon_led.setText('')
        self._widget.brake_fltcon_led.setPalette(self.gray_palette)
        self._widget.brake_fltb_led.setText('')
        self._widget.brake_fltb_led.setPalette(self.gray_palette)

        self._widget.steering_driver_led.setText('')
        self._widget.steering_flt1_led.setText('')
        self._widget.steering_flt2_led.setText('')
        self._widget.steering_fltcon_led.setText('')

        self._widget.gear_driver_led.setText('')
        self._widget.gear_fltbus_led.setText('')

        # Steering wheel buttons
        self._widget.on_off_led.setText('')
        self._widget.on_off_led.setPalette(self.gray_palette)
        self._widget.res_cncl_led.setText('')
        self._widget.res_cncl_led.setPalette(self.gray_palette)
        self._widget.set_inc_led.setText('')
        self._widget.set_inc_led.setPalette(self.gray_palette)
        self._widget.set_dec_led.setText('')
        self._widget.set_dec_led.setPalette(self.gray_palette)
        self._widget.gap_inc_led.setText('')
        self._widget.gap_inc_led.setPalette(self.gray_palette)
        self._widget.gap_dec_led.setText('')
        self._widget.gap_dec_led.setPalette(self.gray_palette)
        self._widget.la_on_off_led.setText('')
        self._widget.la_on_off_led.setPalette(self.gray_palette)
コード例 #22
0
ファイル: look_feel.py プロジェクト: shamray/calibre
 def set_cg_color(self, val):
     pal = QPalette()
     pal.setColor(QPalette.Window, QColor(*val))
     self.cover_grid_color_label.setPalette(pal)