示例#1
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)
示例#2
0
 def paintEvent(self, event):
     canvas_size = self.rect()
     width = self.current_pixmap_size.width()
     extrax = canvas_size.width() - width
     if extrax < 0: extrax = 0
     x = int(extrax / 2.)
     height = self.current_pixmap_size.height()
     extray = canvas_size.height() - height
     if extray < 0: extray = 0
     y = int(extray / 2.)
     target = QRect(x, y, width, height)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing
                      | QPainter.SmoothPixmapTransform)
     p.drawPixmap(
         target,
         self.pixmap.scaled(target.size(), Qt.KeepAspectRatio,
                            Qt.SmoothTransformation))
     if gprefs['bd_overlay_cover_size']:
         sztgt = target.adjusted(0, 0, 0, -4)
         f = p.font()
         f.setBold(True)
         p.setFont(f)
         sz = u'\u00a0%d x %d\u00a0' % (self.pixmap.width(),
                                        self.pixmap.height())
         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()
示例#3
0
    def set_style(self, style):
        pf = PF(style=style)
        self.styles = {}
        self.normal = self.base_fmt()
        self.background_color = pf.style.background_color
        self.color = 'black'

        for ttype, ndef in pf.style:
            fmt = self.base_fmt()
            fmt.setProperty(fmt.UserProperty, str(ttype))
            if ndef['color']:
                fmt.setForeground(QBrush(QColor('#%s'%ndef['color'])))
                fmt.setUnderlineColor(QColor('#%s'%ndef['color']))
                if ttype == Generic.Output:
                    self.color = '#%s'%ndef['color']
            if ndef['bold']:
                fmt.setFontWeight(QFont.Bold)
            if ndef['italic']:
                fmt.setFontItalic(True)
            if ndef['underline']:
                fmt.setFontUnderline(True)
            if ndef['bgcolor']:
                fmt.setBackground(QBrush(QColor('#%s'%ndef['bgcolor'])))
            if ndef['border']:
                pass # No support for borders

            self.styles[ttype] = fmt
示例#4
0
文件: diff.py 项目: sss/calibre
    def paintEvent(self, event):
        pmap = self.blank if self.pixmap is None or self.pixmap.isNull(
        ) else self.pixmap
        target = self.rect()
        scaled, width, height = fit_image(pmap.width(), pmap.height(),
                                          target.width(), target.height())
        target.setRect(target.x(), target.y(), width, height)
        p = QPainter(self)
        p.setRenderHints(QPainter.Antialiasing
                         | QPainter.SmoothPixmapTransform)
        p.drawPixmap(target, pmap)

        if self.pixmap is not None and not self.pixmap.isNull():
            sztgt = target.adjusted(0, 0, 0, -4)
            f = p.font()
            f.setBold(True)
            p.setFont(f)
            sz = u'\u00a0%d x %d\u00a0' % (self.pixmap.width(),
                                           self.pixmap.height())
            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()
示例#5
0
    def draw_spinner(self, painter, rect):
        width = rect.width()

        outer_radius = (width - 1) * 0.5
        inner_radius = (width - 1) * 0.5 * 0.38

        capsule_height = outer_radius - inner_radius
        capsule_width = int(capsule_height * (0.23 if width > 32 else 0.35))
        capsule_radius = capsule_width // 2

        painter.save()
        painter.setRenderHint(painter.Antialiasing)

        for i in xrange(12):
            color = QColor(self.color)
            color.setAlphaF(1.0 - (i / 12.0))
            painter.setPen(Qt.NoPen)
            painter.setBrush(color)
            painter.save()
            painter.translate(rect.center())
            painter.rotate(self.angle - i * 30.0)
            painter.drawRoundedRect(-capsule_width * 0.5,
                                    -(inner_radius + capsule_height),
                                    capsule_width, capsule_height,
                                    capsule_radius, capsule_radius)
            painter.restore()
        painter.restore()
示例#6
0
def drag_icon(self, cover, multiple):
    cover = cover.scaledToHeight(120, Qt.SmoothTransformation)
    if multiple:
        base_width = cover.width()
        base_height = cover.height()
        base = QImage(base_width + 21, base_height + 21,
                      QImage.Format_ARGB32_Premultiplied)
        base.fill(QColor(255, 255, 255, 0).rgba())
        p = QPainter(base)
        rect = QRect(20, 0, base_width, base_height)
        p.fillRect(rect, QColor('white'))
        p.drawRect(rect)
        rect.moveLeft(10)
        rect.moveTop(10)
        p.fillRect(rect, QColor('white'))
        p.drawRect(rect)
        rect.moveLeft(0)
        rect.moveTop(20)
        p.fillRect(rect, QColor('white'))
        p.save()
        p.setCompositionMode(p.CompositionMode_SourceAtop)
        p.drawImage(rect.topLeft(), cover)
        p.restore()
        p.drawRect(rect)
        p.end()
        cover = base
    return QPixmap.fromImage(cover)
示例#7
0
    def __init__(self,
                 parent,
                 x=0,
                 y=0,
                 width=None,
                 height=None,
                 img=None,
                 text=None,
                 togglable=False,
                 imgoff=None,
                 action=None,
                 params=None):
        Action.__init__(self, action, params)
        GLFrame.__init__(self, parent, x, y, width, height)

        self.img = img
        self.setText(text)
        self.textColor = QColor(0, 0, 0)
        self.togglable = togglable
        self.toggled = False
        self.imgoff = imgoff

        self.focus = False
        self.enabled = True
        self.__initialized__ = False
示例#8
0
    def draw_spinner(self, painter, rect):
        width = rect.width()

        outer_radius = (width-1)*0.5
        inner_radius = (width-1)*0.5*0.38

        capsule_height = outer_radius - inner_radius
        capsule_width  = int(capsule_height * (0.23 if width > 32 else 0.35))
        capsule_radius = capsule_width//2

        painter.save()
        painter.setRenderHint(painter.Antialiasing)

        for i in xrange(12):
            color = QColor(self.color)
            color.setAlphaF(1.0 - (i/12.0))
            painter.setPen(Qt.NoPen)
            painter.setBrush(color)
            painter.save()
            painter.translate(rect.center())
            painter.rotate(self.angle - i*30.0)
            painter.drawRoundedRect(-capsule_width*0.5,
                    -(inner_radius+capsule_height), capsule_width,
                    capsule_height, capsule_radius, capsule_radius)
            painter.restore()
        painter.restore()
示例#9
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)
示例#10
0
 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)
示例#11
0
    def add_image(self, img, cache_key):
        ref = self.get_image(cache_key)
        if ref is not None:
            return ref

        fmt = img.format()
        image = QImage(img)
        if (image.depth() == 1 and img.colorTable().size() == 2 and
            img.colorTable().at(0) == QColor(Qt.black).rgba() and
            img.colorTable().at(1) == QColor(Qt.white).rgba()):
            if fmt == QImage.Format_MonoLSB:
                image = image.convertToFormat(QImage.Format_Mono)
            fmt = QImage.Format_Mono
        else:
            if (fmt != QImage.Format_RGB32 and fmt != QImage.Format_ARGB32):
                image = image.convertToFormat(QImage.Format_ARGB32)
                fmt = QImage.Format_ARGB32

        w = image.width()
        h = image.height()
        d = image.depth()

        if fmt == QImage.Format_Mono:
            bytes_per_line = (w + 7) >> 3
            data = image.constBits().asstring(bytes_per_line * h)
            return self.write_image(data, w, h, d, cache_key=cache_key)

        has_alpha = False
        soft_mask = None

        if fmt == QImage.Format_ARGB32:
            tmask = image.constBits().asstring(4*w*h)[self.alpha_bit::4]
            sdata = bytearray(tmask)
            vals = set(sdata)
            vals.discard(255)  # discard opaque pixels
            has_alpha = bool(vals)
            if has_alpha:
                # Blend image onto a white background as otherwise Qt will render
                # transparent pixels as black
                background = QImage(image.size(), QImage.Format_ARGB32_Premultiplied)
                background.fill(Qt.white)
                painter = QPainter(background)
                painter.drawImage(0, 0, image)
                painter.end()
                image = background

        ba = QByteArray()
        buf = QBuffer(ba)
        image.save(buf, 'jpeg', 94)
        data = bytes(ba.data())

        if has_alpha:
            soft_mask = self.write_image(tmask, w, h, 8)

        return self.write_image(data, w, h, 32, dct=True,
                                soft_mask=soft_mask, cache_key=cache_key)
示例#12
0
 def __init__(self):
     self.labels_font = QFont('Verdana', 10)
     self.helper_font = self.labels_font
     self.helpers_color = QColor(0, 0, 0, 255)
     self.background_color = QColor(255, 255, 255, 255)
     self.axis_title_font = QFont('Verdana', 11, QFont.Bold)
     self.axis_font = QFont('Verdana', 10)
     self.labels_color = QColor(0, 0, 0, 255)
     self.axis_color = QColor(30, 30, 30, 255)
     self.axis_values_color = QColor(30, 30, 30, 255)
示例#13
0
def colorTagToQtColor(_colorTag, outputAlpha=False):

    if _colorTag is None:
        return QColor(Qt.yellow)

    colorTag = _colorTag.lower()

    if (colorTag == "red"):
        qtColor = QColor(Qt.red)
    elif (colorTag == "green"):
        qtColor = QColor(Qt.green)
    elif (colorTag == "blue"):
        qtColor = QColor(Qt.blue)
    elif (colorTag == "cyan"):
        qtColor = QColor(Qt.cyan)
    elif (colorTag == "darkGray"):
        qtColor = QColor(Qt.darkGray)
    elif (colorTag == "magenta"):
        qtColor = QColor(Qt.magenta)
    elif (colorTag == "yellow"):
        return QColor(Qt.yellow)
    elif (colorTag[0] == "#"):
        qtColor = hexColorStrToQtColor(colorTag, outputAlpha)
    else:
        qtColor = QColor(Qt.yellow)
    return qtColor
示例#14
0
文件: test.py 项目: sss/calibre
def brush(p, xmax, ymax):
    x = 0
    y = 0
    w = xmax / 2
    g = QLinearGradient(QPointF(x, y + w / 3), QPointF(x, y + (2 * w / 3)))
    g.setColorAt(0, QColor('#f00'))
    g.setColorAt(0.5, QColor('#fff'))
    g.setColorAt(1, QColor('#00f'))
    g.setSpread(g.ReflectSpread)
    p.fillRect(x, y, w, w, QBrush(g))
    p.drawRect(x, y, w, w)
示例#15
0
def read_color(col):
    if QColor.isValidColor(col):
        return QBrush(QColor(col))
    if col.startswith('rgb('):
        r, g, b = map(int, (x.strip() for x in col[4:-1].split(',')))
        return QBrush(QColor(r, g, b))
    try:
        r, g, b = col[0:2], col[2:4], col[4:6]
        r, g, b = int(r, 16), int(g, 16), int(b, 16)
        return QBrush(QColor(r, g, b))
    except Exception:
        pass
示例#16
0
文件: test.py 项目: sss/calibre
def full(p, xmax, ymax):
    p.drawRect(0, 0, xmax, ymax)
    p.drawPolyline(QPoint(0, 0), QPoint(xmax, 0), QPoint(xmax, ymax),
                   QPoint(0, ymax), QPoint(0, 0))
    pp = QPainterPath()
    pp.addRect(0, 0, xmax, ymax)
    p.drawPath(pp)
    p.save()
    for i in xrange(3):
        col = [0, 0, 0, 200]
        col[i] = 255
        p.setOpacity(0.3)
        p.fillRect(0, 0, xmax / 10, xmax / 10, QBrush(QColor(*col)))
        p.setOpacity(1)
        p.drawRect(0, 0, xmax / 10, xmax / 10)
        p.translate(xmax / 10, xmax / 10)
        p.scale(1, 1.5)
    p.restore()

    # p.scale(2, 2)
    # p.rotate(45)
    p.drawPixmap(0, 0, xmax / 4, xmax / 4, QPixmap(I('library.png')))
    p.drawRect(0, 0, xmax / 4, xmax / 4)

    f = p.font()
    f.setPointSize(20)
    # f.setLetterSpacing(f.PercentageSpacing, 200)
    f.setUnderline(True)
    # f.setOverline(True)
    # f.setStrikeOut(True)
    f.setFamily('Calibri')
    p.setFont(f)
    # p.setPen(QColor(0, 0, 255))
    # p.scale(2, 2)
    # p.rotate(45)
    p.drawText(QPoint(xmax / 3.9, 30), 'Some—text not By’s ū --- Д AV ff ff')

    b = QBrush(Qt.HorPattern)
    b.setColor(QColor(Qt.blue))
    pix = QPixmap(I('console.png'))
    w = xmax / 4
    p.fillRect(0, ymax / 3, w, w, b)
    p.fillRect(xmax / 3, ymax / 3, w, w, QBrush(pix))
    x, y = 2 * xmax / 3, ymax / 3
    p.drawTiledPixmap(QRectF(x, y, w, w), pix, QPointF(10, 10))

    x, y = 1, ymax / 1.9
    g = QLinearGradient(QPointF(x, y), QPointF(x + w, y + w))
    g.setColorAt(0, QColor('#00f'))
    g.setColorAt(1, QColor('#fff'))
    p.fillRect(x, y, w, w, QBrush(g))
示例#17
0
 def paintEvent(self, painter, width, height):
     painter.setBrush(QBrush(QColor(255, 0, 0), Qt.SolidPattern))
     if self.alive == False:
         painter.setBrush(QBrush(QColor(255, 0, 255), Qt.SolidPattern))
     painter.drawRect(self.headX * width, self.headY * height, width,
                      height)
     pX = self.headX
     pY = self.headY
     for pX, pY in self.getTailPoints():
         painter.drawRect(pX * width, pY * height, width, height)
     painter.setBrush(QBrush(QColor(0, 0, 255), Qt.SolidPattern))
     if self.alive == True:
         painter.drawRect(self.fruitX * width, self.fruitY * height, width,
                          height)
示例#18
0
    def load(self):
        st, ui = self.settings, self.ui
        self.fgcolor = QColor(st.value("color/messages/fg",
            self.app.palette().buttonText().color().name()).toString())
        self.bgcolor = QColor(st.value("color/messages/bg",
            self.app.palette().button().color().name()).toString())
        self.old = drug(fgcolor = self.fgcolor, bgcolor = self.bgcolor)

        ui.identicaidEdit.setText(st.value("account/identica/id").toString())
        ui.twitteridEdit.setText(st.value("account/twitter/id").toString())
        b = st.value("icon/isdark",True).toBool()
        ui.darkradioButton.setChecked(b)
        ui.lightradioButton.setChecked(not b)
        ui.fgcolorButton.setStyleSheet("background-color:"+self.fgcolor.name())
        ui.bgcolorButton.setStyleSheet("background-color:"+self.bgcolor.name())
示例#19
0
文件: preference.py 项目: dodo/blain
    def load(self):
        st, ui = self.settings, self.ui
        self.fgcolor = QColor(st.value("color/messages/fg",
            self.app.palette().buttonText().color().name()).toString())
        self.bgcolor = QColor(st.value("color/messages/bg",
            self.app.palette().button().color().name()).toString())
        self.old = drug(fgcolor = self.fgcolor, bgcolor = self.bgcolor)

        b = st.value("icon/isdark",True).toBool()
        ui.darkradioButton.setChecked(b)
        ui.lightradioButton.setChecked(not b)
        ui.fgcolorButton.setStyleSheet("background-color:"+self.fgcolor.name())
        ui.bgcolorButton.setStyleSheet("background-color:"+self.bgcolor.name())
        if self.app.notifier.buttons:
            self.app.notifier.resetRadioButtons()
示例#20
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:
             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)
示例#21
0
 def paint(self, painter, option,index):
     if index.column() ==1:
         painter.save()
         model = index.model()
         userNameIndex = model.index(index.row(),LabelDelegate.USER_NAME_COLUMN)
         msgCountIndex = model.index(index.row(),LabelDelegate.MSG_COUNT_COLUMN)
         
         userName = model.data(userNameIndex).toString()
         msgCount = model.data(msgCountIndex).toString()
         
         if option.state & QStyle.State_Selected:
             painter.fillRect(option.rect, option.palette.highlight())
         rect_x = option.rect.x()
         rect_y = option.rect.y()
         head_image_x_offset = 5
         head_image_y_offset = 10
         head_image_x = rect_x + head_image_x_offset
         head_image_y = rect_y + head_image_y_offset
         image = ("%s/.wechat/%s/%s.jpg")%(LabelDelegate.USER_HOME,LabelDelegate.CONTACT_HEAD_HOME,userName)
         if not os.path.exists(image):
             image = LabelDelegate.DEFAULT_IMAGE
         painter.drawPixmap(head_image_x,head_image_y,LabelDelegate.HEAD_IMG_WIDTH,LabelDelegate.HEAD_IMG_HEIGHT, QPixmap(image))
         if msgCount and msgCount > 0:
             white = QColor(255, 0, 0)
             painter.setPen(white)
             painter.setBrush(white)
             ellipse_r = 20
             ellipse_x = rect_x+LabelDelegate.HEAD_IMG_WIDTH-5
             ellipse_y = rect_y+head_image_y_offset-7.5
             
             painter.drawEllipse(ellipse_x,ellipse_y,ellipse_r,ellipse_r)
             red = QColor(255, 255, 255)
             painter.setPen(red)
             painter.setBrush(red)
             
             msg_count_x = rect_x+LabelDelegate.HEAD_IMG_WIDTH+2.5
             
             if msgCount >= 10 and msgCount < 100:
                 msg_count_x = msg_count_x - 0.5
             elif msgCount >= 100 and msgCount < 1000:
                 msg_count_x = msg_count_x - 3.5
             elif msgCount >= 1000 and msgCount < 10000:
                 msg_count_x = msg_count_x - 5
             msg_count_y = rect_y+head_image_y_offset + 5
             painter.drawText(msg_count_x,msg_count_y, str(msgCount))
         painter.restore()
     else:
         super(LabelDelegate, self).paint(painter, option, index)
示例#22
0
 def logError(self, msg):
     self.ui.logger.setFontWeight(90)
     self.ui.logger.setColor(QColor("red"))
     self.ui.logger.append(msg)
     self.ui.listOfModules.clear()
     self.modulesToUpload = []
     self.ui.uploadButton.setEnabled(True)
示例#23
0
    def penMoveEvent(self, pos, pressure, liftedDeque):
        pen_x = pos[0]
        pen_y = pos[1]
        pen_pressure = pressure

        # print(liftedDeque)
        # print(self.__lastPos)

        if self.__lastPos is None:
            self.__lastPos = QPoint(pen_x, pen_y)

        self.__currentPos = QPoint(pen_x, pen_y)
        self.__painter.begin(self.__board)

        if self.EraserMode == False:
            #Non-Eraser mode
            self.__penColor = QColor("blue")
            self.__painter.setPen(QPen(
                self.__penColor, self.__thickness))  #Set pen color, thickness
        else:
            #Eraser mode: pen color is white, thickness is 6
            self.__painter.setPen(QPen(Qt.white, 6))

        self.__painter.drawLine(self.__lastPos, self.__currentPos)
        self.__painter.end()
        self.__lastPos = self.__currentPos

        self.update()  #Show updates

        # If ever detected the pen is lifted, reset the __lastPos variable in order to reposition the pen
        if (True in liftedDeque):
            self.__lastPos = None
示例#24
0
 def fset(self, val):
     val = unicode(val or '')
     col = QColor(val)
     orig = self._color
     if col.isValid():
         self._color = val
         self.setText(val)
         p = QPixmap(self.iconSize())
         p.fill(col)
         self.setIcon(QIcon(p))
     else:
         self._color = None
         self.setText(self.choose_text)
         self.setIcon(QIcon())
     if orig != col:
         self.color_changed.emit(self._color)
    def drawScaleContents(self, painter, center, radius):
        dir = 90  #360 - int(roud(self.origin() - self.value()))
        arc = 90  #+ int(round(self.gradient * 90))
        skyColor = QColor(38, 151, 221)
        painter.save()
        painter.setBrush(skyColor)
        painter.drawChord(self.scaleContentsRect(), (dir - arc) * 16,
                          2 * arc * 16)
        direction1 = self.value() * M_PI / 180.0
        direction2 = self.value() * M_PI / 180.0 + M_PI_2

        triangleSize = qRound(radius * 0.15)
        p0 = (QPoint(center.x() + 0, center.y() + 0))
        p1 = qwtPolar2Pos(p0, 2, direction2)
        pa = QPolygon(3)
        pa.setPoint(0, qwtPolar2Pos(p1, 2 * triangleSize, direction2))
        pa.setPoint(1, qwtPolar2Pos(p1, triangleSize, direction2 + M_PI_2))
        pa.setPoint(2, qwtPolar2Pos(p1, triangleSize, direction2 - M_PI_2))
        color = self.palette().color(QPalette.Text)
        painter.setBrush(color)
        painter.drawPolygon(pa)

        p0 = (QPoint(center.x() + 0, center.y() + 0))
        color = self.palette().color(QPalette.Text)
        painter.setBrush(color)
        painter.setPen(QPen(color, 3))
        painter.drawLine(qwtPolar2Pos(p0, radius - 3, direction1),
                         qwtPolar2Pos(p0, radius - 3, direction1 - M_PI))

        painter.restore()
示例#26
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)
示例#27
0
 def draw_image_error(self, painter):
     font = painter.font()
     font.setPointSize(3 * font.pointSize())
     font.setBold(True)
     painter.setFont(font)
     painter.setPen(QColor(Qt.black))
     painter.drawText(self.rect(), Qt.AlignCenter, _('Not a valid image'))
示例#28
0
 def fset(self, val):
     val = unicode(val or '')
     col = QColor(val)
     orig = self._color
     if col.isValid():
         self._color = val
         self.setText(val)
         p = QPixmap(self.iconSize())
         p.fill(col)
         self.setIcon(QIcon(p))
     else:
         self._color = None
         self.setText(self.choose_text)
         self.setIcon(QIcon())
     if orig != col:
         self.color_changed.emit(self._color)
示例#29
0
    def initializeFormats(self):
        Config = self.Config
        Config["fontfamily"] = "monospace"
        #Config["fontsize"] = 10
        for name, color, bold, italic in (
                ("normal", "#000000", False, False),
                ("keyword", "#000080", True, False),
                ("builtin", "#0000A0", False, False),
                ("comment", "#007F00", False, True),
                ("string", "#808000", False, False),
                ("number", "#924900", False, False),
                ("lparen", "#000000", True, True),
                ("rparen", "#000000", True, True)):
            Config["%sfontcolor" % name] = color
            Config["%sfontbold" % name] = bold
            Config["%sfontitalic" % name] = italic

        baseFormat = QTextCharFormat()
        baseFormat.setFontFamily(Config["fontfamily"])
        #baseFormat.setFontPointSize(Config["fontsize"])

        for name in ("normal", "keyword", "builtin", "comment",
                     "string", "number", "lparen", "rparen"):
            format = QTextCharFormat(baseFormat)
            format.setForeground(QColor(Config["%sfontcolor" % name]))
            if Config["%sfontbold" % name]:
                format.setFontWeight(QFont.Bold)
            format.setFontItalic(Config["%sfontitalic" % name])
            self.Formats[name] = format
示例#30
0
    def paintArc(self, center_x, center_y, start_x, start_y, end_x, end_y):
        radius = math.sqrt(
            math.pow(center_x - start_x, 2) + math.pow(center_y - start_y, 2))
        rect = QRectF(center_x - radius, center_y - radius, radius * 2,
                      radius * 2)
        # start angle calculation
        startAngle = math.degrees(
            math.atan2(center_y - start_y, start_x - center_x))
        # end angle calculation
        endAngle = math.degrees(math.atan2(center_y - end_y, end_x - center_x))

        # span angle calculation
        spanAngle = endAngle - startAngle
        # assume user always wants to draw clock-wise
        if spanAngle > 0:
            spanAngle = -1 * (360 - spanAngle)
        #print("start angle is " + str(startAngle))
        #print("span angle is " + str(spanAngle))

        self.__painter.begin(self.__board)
        self.__penColor = QColor("black")
        self.__painter.setPen(QPen(self.__penColor, self.__thickness))
        self.__painter.drawArc(rect, 16 * startAngle, 16 * spanAngle)
        self.__painter.end()

        self.update()  #Show updates
示例#31
0
文件: model.py 项目: mrmac123/calibre
 def data(self, role):
     if role == Qt.DisplayRole:
         return QVariant(self.cdata + ' [%d]' % len(self.children))
     elif role == Qt.FontRole:
         return self.bold_font
     elif role == Qt.ForegroundRole and self.category == _('Scheduled'):
         return QVariant(QColor(0, 255, 0))
     return NONE
示例#32
0
def colorStrToQtColor(colorStr, outputAlpha=False):
    if colorStr is None:
        return QColor(Qt.yellow)

    if colorStr[0] == '#':
        return hexColorStrToQtColor(colorStr, outputAlpha)
    else:
        return colorTagToQtColor(colorStr, outputAlpha)
示例#33
0
 def changeGridColor(self):
     """
     Open the stand color chooser dialog to change grid line color
     """
     c = QColorDialog.getColor(QColor(222, 148, 0), self)
     if c.isValid():
         self.gridColorLabel.setPaletteBackgroundColor(c)
         self.command.setGridLineColor(c)
示例#34
0
    def drawSquare(self, painter, x, y, shape):
        colorTable = [0x000000, 0xCC6666, 0x66CC66, 0x6666CC,
                      0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00]

        color = QColor(colorTable[shape])
        painter.fillRect(x + 1, y + 1, self.squareWidth() - 2, 
            self.squareHeight() - 2, color)

        painter.setPen(color.light())
        painter.drawLine(x, y + self.squareHeight() - 1, x, y)
        painter.drawLine(x, y, x + self.squareWidth() - 1, y)

        painter.setPen(color.dark())
        painter.drawLine(x + 1, y + self.squareHeight() - 1,
            x + self.squareWidth() - 1, y + self.squareHeight() - 1)
        painter.drawLine(x + self.squareWidth() - 1, 
            y + self.squareHeight() - 1, x + self.squareWidth() - 1, y + 1)
示例#35
0
 def value_as_QColor(self, value=None):  ###k untested??
     #e API is getting a bit klugy... we're using a random instance as knowing about the superset of colors,
     # and using its default value as the value here...
     if value is None:
         value = self.get_defaultValue()
     rgb = self.value_as_int_tuple(value)
     from PyQt4.Qt import QColor
     return QColor(rgb[0], rgb[1], rgb[2])  #k guess
示例#36
0
 def __init__(self, text, rect, right_align=False, color_role=QPalette.WindowText, swatch=None, is_overriden=False):
     self.rect, self.text = rect, text
     self.right_align = right_align
     self.is_overriden = is_overriden
     self.color_role = color_role
     self.override_color = None
     self.swatch = swatch
     if swatch is not None:
         self.swatch = QColor(swatch[0], swatch[1], swatch[2], int(255 * swatch[3]))
示例#37
0
文件: themes.py 项目: BorviX/calibre
def read_color(col):
    if QColor.isValidColor(col):
        return QBrush(QColor(col))
    try:
        r, g, b = col[0:2], col[2:4], col[4:6]
        r, g, b = int(r, 16), int(g, 16), int(b, 16)
        return QBrush(QColor(r, g, b))
    except Exception:
        pass
示例#38
0
文件: themes.py 项目: randy1/calibre
def read_color(col):
    if QColor.isValidColor(col):
        return QBrush(QColor(col))
    if col.startswith('rgb('):
        r, g, b = map(int, (x.strip() for x in col[4:-1].split(',')))
        return QBrush(QColor(r, g, b))
    try:
        r, g, b = col[0:2], col[2:4], col[4:6]
        r, g, b = int(r, 16), int(g, 16), int(b, 16)
        return QBrush(QColor(r, g, b))
    except Exception:
        pass
示例#39
0
    def __init__(self, *args, **kwargs):

        super(Figure, self).__init__(*args, **kwargs)

        # Creation of the Plotting class:
        # Then we add it as background of the View:
        self._context = QGLWidget(QGLFormat(QGL.NoAccumBuffer))
        self.setViewport(self._context)

        # create the context for Opengl
        self._context.makeCurrent()

        # And we set it as scene for the View:
        self.scene = OGLWidget()
        self.setScene(self.scene)
        self.scene.initializeGL()

        # Set some properties and palette to have a black background:
        color = QColor()
        color.black()
        self.background_color = color

        # unset the context ???
        self._context.doneCurrent()
示例#40
0
 def __init__(self, name, color0=QColor("black"), color1=QColor("white"), alpha=(1, 1)):
     QObject.__init__(self)
     self.name = name
     # color is either specified as one argument (which should then be a [3,n] or [4,n] array),
     # or as two QColors orstring names.
     if isinstance(color0, (list, tuple)):
         self._rgb = numpy.array(color0)
         if self._rgb.shape[1] != 3 or self._rgb.shape[0] < 2:
             raise TypeError("expected [N,3] (N>=2) array as first argument")
     else:
         if isinstance(color0, str):
             color0 = QColor(color0)
         if isinstance(color1, str):
             color1 = QColor(color1)
         self._rgb = numpy.array([[color0.red(), color0.green(), color0.blue()],
                                  [color1.red(), color1.green(), color1.blue()]]) / 255.
     self._rgb_arg = numpy.arange(self._rgb.shape[0]) / (self._rgb.shape[0] - 1.0)
     # alpha array
     self._alpha = numpy.array(alpha).astype(float)
     self._alpha_arg = numpy.arange(len(alpha)) / (len(alpha) - 1.0)
     # background brush
     self._brush = None
示例#41
0
文件: icons.py 项目: dodo/blain
def magnify_icons(a, b):
    a = a.pixmap(16,16)
    b = b.pixmap(16,16)
    img = [QPixmap(16,16), QPixmap(16,16)]
    for i in img:
        i.fill(QColor(0, 0, 0, 0))
        g = a.toImage()
        for n in range(256):
            x, y = n%16, n//16
            c = QColor(g.pixel(x, y))
            s = (c.redF() + c.greenF() + c.blueF()) / 3.0
            l = s * 4.2
            if l > 1.0: l = 1.0
            c.setRgbF(s, s, s, l)
            g.setPixel(x, y, c.rgba())
        p = QPainter()
        p.begin(i)
        p.drawImage( QRectF(6, 0,  8, 16), g, QRectF(0, 0, 10, 16))
        p.drawPixmap(QRectF(0, 0, 10, 16), b, QRectF(6, 1,  10, 15))
        p.end()
        a, b = b, a
    return tuple(map(QIcon, img))
示例#42
0
    def __init__(self, parent, text, mi=None, fm=None, color_field=None):
        QDialog.__init__(self, parent)
        Ui_TemplateDialog.__init__(self)
        self.setupUi(self)

        self.coloring = color_field is not None
        if self.coloring:
            cols = sorted([k for k in displayable_columns(fm)])
            self.colored_field.addItems(cols)
            self.colored_field.setCurrentIndex(self.colored_field.findText(color_field))
            colors = QColor.colorNames()
            colors.sort()
            self.color_name.addItems(colors)
        else:
            self.colored_field.setVisible(False)
            self.colored_field_label.setVisible(False)
            self.color_chooser_label.setVisible(False)
            self.color_name.setVisible(False)
            self.color_copy_button.setVisible(False)
        if mi:
            self.mi = mi
        else:
            self.mi = Metadata(None, None)

        # Remove help icon on title bar
        icon = self.windowIcon()
        self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
        self.setWindowIcon(icon)

        self.last_text = ''
        self.highlighter = TemplateHighlighter(self.textbox.document())
        self.textbox.cursorPositionChanged.connect(self.text_cursor_changed)
        self.textbox.textChanged.connect(self.textbox_changed)

        self.textbox.setTabStopWidth(10)
        self.source_code.setTabStopWidth(10)
        self.documentation.setReadOnly(True)
        self.source_code.setReadOnly(True)

        if text is not None:
            self.textbox.setPlainText(text)
        self.buttonBox.button(QDialogButtonBox.Ok).setText(_('&OK'))
        self.buttonBox.button(QDialogButtonBox.Cancel).setText(_('&Cancel'))
        self.color_copy_button.clicked.connect(self.color_to_clipboard)

        try:
            with open(P('template-functions.json'), 'rb') as f:
                self.builtin_source_dict = json.load(f, encoding='utf-8')
        except:
            self.builtin_source_dict = {}

        self.funcs = formatter_functions().get_functions()
        self.builtins = formatter_functions().get_builtins()

        func_names = sorted(self.funcs)
        self.function.clear()
        self.function.addItem('')
        self.function.addItems(func_names)
        self.function.setCurrentIndex(0)
        self.function.currentIndexChanged[str].connect(self.function_changed)
        self.textbox_changed()
        self.rule = (None, '')

        tt = _('Template language tutorial')
        self.template_tutorial.setText(
                '<a href="http://manual.calibre-ebook.com/template_lang.html">'
                '%s</a>'%tt)
        tt = _('Template function reference')
        self.template_func_reference.setText(
                '<a href="http://manual.calibre-ebook.com/template_ref.html">'
                '%s</a>'%tt)
示例#43
0
    def __init__(self, parent, editing, standard_colheads, standard_colnames):
        QDialog.__init__(self, parent)
        Ui_QCreateCustomColumn.__init__(self)
        self.setupUi(self)
        self.setWindowTitle(_("Create a custom column"))
        self.heading_label.setText(_("Create a custom column"))
        # Remove help icon on title bar
        icon = self.windowIcon()
        self.setWindowFlags(self.windowFlags() & (~Qt.WindowContextHelpButtonHint))
        self.setWindowIcon(icon)

        self.simple_error = partial(error_dialog, self, show=True, show_copy_button=False)
        self.button_box.accepted.connect(self.accept)
        self.button_box.rejected.connect(self.reject)
        self.shortcuts.linkActivated.connect(self.shortcut_activated)
        text = "<p>" + _("Quick create:")
        for col, name in [
            ("isbn", _("ISBN")),
            ("formats", _("Formats")),
            ("yesno", _("Yes/No")),
            ("tags", _("Tags")),
            ("series", _("Series")),
            ("rating", _("Rating")),
            ("people", _("People's names")),
        ]:
            text += ' <a href="col:%s">%s</a>,' % (col, name)
        text = text[:-1]
        self.shortcuts.setText(text)

        for sort_by in [_("Text"), _("Number"), _("Date"), _("Yes/No")]:
            self.composite_sort_by.addItem(sort_by)

        self.parent = parent
        self.editing_col = editing
        self.standard_colheads = standard_colheads
        self.standard_colnames = standard_colnames
        self.column_type_box.setMaxVisibleItems(len(self.column_types))
        for t in self.column_types:
            self.column_type_box.addItem(self.column_types[t]["text"])
        self.column_type_box.currentIndexChanged.connect(self.datatype_changed)
        if not self.editing_col:
            self.datatype_changed()
            self.exec_()
            return
        self.setWindowTitle(_("Edit a custom column"))
        self.heading_label.setText(_("Edit a custom column"))
        self.shortcuts.setVisible(False)
        idx = parent.opt_columns.currentRow()
        if idx < 0:
            self.simple_error(_("No column selected"), _("No column has been selected"))
            return
        col = unicode(parent.opt_columns.item(idx).data(Qt.UserRole).toString())
        if col not in parent.custcols:
            self.simple_error("", _("Selected column is not a user-defined column"))
            return

        c = parent.custcols[col]
        self.column_name_box.setText(c["label"])
        self.column_heading_box.setText(c["name"])
        ct = c["datatype"]
        if c["is_multiple"]:
            ct = "*" + ct
        self.orig_column_number = c["colnum"]
        self.orig_column_name = col
        column_numbers = dict(map(lambda x: (self.column_types[x]["datatype"], x), self.column_types))
        self.column_type_box.setCurrentIndex(column_numbers[ct])
        self.column_type_box.setEnabled(False)
        if ct == "datetime":
            if c["display"].get("date_format", None):
                self.date_format_box.setText(c["display"].get("date_format", ""))
        elif ct in ["composite", "*composite"]:
            self.composite_box.setText(c["display"].get("composite_template", ""))
            sb = c["display"].get("composite_sort", "text")
            vals = ["text", "number", "date", "bool"]
            if sb in vals:
                sb = vals.index(sb)
            else:
                sb = 0
            self.composite_sort_by.setCurrentIndex(sb)
            self.composite_make_category.setChecked(c["display"].get("make_category", False))
            self.composite_contains_html.setChecked(c["display"].get("contains_html", False))
        elif ct == "enumeration":
            self.enum_box.setText(",".join(c["display"].get("enum_values", [])))
            self.enum_colors.setText(",".join(c["display"].get("enum_colors", [])))
        elif ct in ["int", "float"]:
            if c["display"].get("number_format", None):
                self.number_format_box.setText(c["display"].get("number_format", ""))
        self.datatype_changed()
        if ct in ["text", "composite", "enumeration"]:
            self.use_decorations.setChecked(c["display"].get("use_decorations", False))
        elif ct == "*text":
            self.is_names.setChecked(c["display"].get("is_names", False))

        all_colors = [unicode(s) for s in list(QColor.colorNames())]
        self.enum_colors_label.setToolTip("<p>" + ", ".join(all_colors) + "</p>")

        self.composite_contains_html.setToolTip(
            "<p>"
            + _(
                "If checked, this column will be displayed as HTML in "
                "book details and the content server. This can be used to "
                "construct links with the template language. For example, "
                "the template "
                "<pre>&lt;big&gt;&lt;b&gt;{title}&lt;/b&gt;&lt;/big&gt;"
                "{series:| [|}{series_index:| [|]]}</pre>"
                "will create a field displaying the title in bold large "
                'characters, along with the series, for example <br>"<big><b>'
                'An Oblique Approach</b></big> [Belisarius [1]]". The template '
                '<pre>&lt;a href="http://www.beam-ebooks.de/ebook/{identifiers'
                ':select(beam)}"&gt;Beam book&lt;/a&gt;</pre> '
                "will generate a link to the book on the Beam ebooks site."
            )
            + "</p>"
        )
        self.exec_()
示例#44
0
    def accept(self):
        col = unicode(self.column_name_box.text()).strip()
        if not col:
            return self.simple_error('', _('No lookup name was provided'))
        if col.startswith('#'):
            col = col[1:]
        if re.match('^\w*$', col) is None or not col[0].isalpha() or col.lower() != col:
            return self.simple_error('', _('The lookup name must contain only '
                    'lower case letters, digits and underscores, and start with a letter'))
        if col.endswith('_index'):
            return self.simple_error('', _('Lookup names cannot end with _index, '
                    'because these names are reserved for the index of a series column.'))
        col_heading = unicode(self.column_heading_box.text()).strip()
        col_type = self.column_types[self.column_type_box.currentIndex()]['datatype']
        if col_type[0] == '*':
            col_type = col_type[1:]
            is_multiple = True
        else:
            is_multiple = False
        if not col_heading:
            return self.simple_error('', _('No column heading was provided'))

        db = self.parent.gui.library_view.model().db
        key = db.field_metadata.custom_field_prefix+col
        bad_col = False
        if key in self.parent.custcols:
            if not self.editing_col or \
                    self.parent.custcols[key]['colnum'] != self.orig_column_number:
                bad_col = True
        if bad_col:
            return self.simple_error('', _('The lookup name %s is already used')%col)

        bad_head = False
        for t in self.parent.custcols:
            if self.parent.custcols[t]['name'] == col_heading:
                if not self.editing_col or \
                        self.parent.custcols[t]['colnum'] != self.orig_column_number:
                    bad_head = True
        for t in self.standard_colheads:
            if self.standard_colheads[t] == col_heading:
                bad_head = True
        if bad_head:
            return self.simple_error('', _('The heading %s is already used')%col_heading)

        display_dict = {}

        if col_type == 'datetime':
            if unicode(self.date_format_box.text()).strip():
                display_dict = {'date_format':unicode(self.date_format_box.text()).strip()}
            else:
                display_dict = {'date_format': None}
        elif col_type == 'composite':
            if not unicode(self.composite_box.text()).strip():
                return self.simple_error('', _('You must enter a template for'
                    ' composite columns'))
            display_dict = {'composite_template':unicode(self.composite_box.text()).strip(),
                            'composite_sort': ['text', 'number', 'date', 'bool']
                                        [self.composite_sort_by.currentIndex()],
                            'make_category': self.composite_make_category.isChecked(),
                            'contains_html': self.composite_contains_html.isChecked(),
                        }
        elif col_type == 'enumeration':
            if not unicode(self.enum_box.text()).strip():
                return self.simple_error('', _('You must enter at least one'
                    ' value for enumeration columns'))
            l = [v.strip() for v in unicode(self.enum_box.text()).split(',') if v.strip()]
            l_lower = [v.lower() for v in l]
            for i,v in enumerate(l_lower):
                if v in l_lower[i+1:]:
                    return self.simple_error('', _('The value "{0}" is in the '
                    'list more than once, perhaps with different case').format(l[i]))
            c = unicode(self.enum_colors.text())
            if c:
                c = [v.strip() for v in unicode(self.enum_colors.text()).split(',')]
            else:
                c = []
            if len(c) != 0 and len(c) != len(l):
                return self.simple_error('', _('The colors box must be empty or '
                'contain the same number of items as the value box'))
            for tc in c:
                if tc not in QColor.colorNames():
                    return self.simple_error('',
                            _('The color {0} is unknown').format(tc))

            display_dict = {'enum_values': l, 'enum_colors': c}
        elif col_type == 'text' and is_multiple:
            display_dict = {'is_names': self.is_names.isChecked()}
        elif col_type in ['int', 'float']:
            if unicode(self.number_format_box.text()).strip():
                display_dict = {'number_format':unicode(self.number_format_box.text()).strip()}
            else:
                display_dict = {'number_format': None}

        if col_type in ['text', 'composite', 'enumeration'] and not is_multiple:
            display_dict['use_decorations'] = self.use_decorations.checkState()

        if not self.editing_col:
            self.parent.custcols[key] = {
                    'label':col,
                    'name':col_heading,
                    'datatype':col_type,
                    'display':display_dict,
                    'normalized':None,
                    'colnum':None,
                    'is_multiple':is_multiple,
                }
            item = QListWidgetItem(col_heading, self.parent.opt_columns)
            item.setData(Qt.UserRole, QVariant(key))
            item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable)
            item.setCheckState(Qt.Checked)
        else:
            idx = self.parent.opt_columns.currentRow()
            item = self.parent.opt_columns.item(idx)
            item.setText(col_heading)
            self.parent.custcols[self.orig_column_name]['label'] = col
            self.parent.custcols[self.orig_column_name]['name'] = col_heading
            self.parent.custcols[self.orig_column_name]['display'].update(display_dict)
            self.parent.custcols[self.orig_column_name]['*edited'] = True
            self.parent.custcols[self.orig_column_name]['*must_restart'] = True
        QDialog.accept(self)
示例#45
0
文件: preference.py 项目: dodo/blain
class Preferencer:

    def __init__(self, app):
        self.app = app
        self.settings = QSettings("blain", "blain")
        self.ui = PreferencesDialog(app)


    def connect(self):
        ui, ft = self.ui, self.app.filters
        self.app.window.ui.actionPreferences.triggered.connect(self.show)
        #connect preference window
        ui.fgcolorButton.clicked.connect(self.change_fgcolor)
        ui.bgcolorButton.clicked.connect(self.change_bgcolor)
        ui.resetcolorButton.clicked.connect(self.reset_color)
        ui.buttonBox.accepted.connect(self.accept)
        ui.buttonBox.rejected.connect(self.reject)
        ui.buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.save)
        ui.listWidget.currentRowChanged.connect(
            ui.stackedWidget.setCurrentIndex)


    def setup(self):
        self.load()


    def show(self, _):
        self.app.window.disable()
        self.ui.show()


    def hide(self):
        self.ui.hide()
        self.app.window.enable()


    def reject(self):
        self.hide()
        self.load()


    def accept(self):
        self.hide()
        self.save()


    def save(self):
        app, st, ui = self.app, self.settings, self.ui
        st.setValue("icon/isdark", ui.darkradioButton.isChecked())
        st.setValue("color/messages/fg", self.fgcolor.name())
        st.setValue("color/messages/bg", self.bgcolor.name())
        self.app.notifier.saveRadioButtons()
        self.app.icons.update_window_icon()
        self.app.icons.update_tray()
        if self.fgcolor != self.old.fgcolor or self.bgcolor != self.old.bgcolor:
            self.old = drug(fgcolor = self.fgcolor, bgcolor = self.bgcolor)
            self.app.reader.update_messages_colors()


    def load(self):
        st, ui = self.settings, self.ui
        self.fgcolor = QColor(st.value("color/messages/fg",
            self.app.palette().buttonText().color().name()).toString())
        self.bgcolor = QColor(st.value("color/messages/bg",
            self.app.palette().button().color().name()).toString())
        self.old = drug(fgcolor = self.fgcolor, bgcolor = self.bgcolor)

        b = st.value("icon/isdark",True).toBool()
        ui.darkradioButton.setChecked(b)
        ui.lightradioButton.setChecked(not b)
        ui.fgcolorButton.setStyleSheet("background-color:"+self.fgcolor.name())
        ui.bgcolorButton.setStyleSheet("background-color:"+self.bgcolor.name())
        if self.app.notifier.buttons:
            self.app.notifier.resetRadioButtons()


    def change_fgcolor(self):
        self.change_color('fgcolor')


    def change_bgcolor(self):
        self.change_color('bgcolor')


    def change_color(self, color_name):
        if not hasattr(self, color_name): return
        color = getattr(self, color_name)
        color = QColorDialog.getColor(color, self.ui)
        setattr(self, color_name, color)
        getattr(self.ui, color_name+"Button").setStyleSheet(
            "background-color:" + color.name())


    def reset_color(self):
        app, ui = self.app, self.ui
        self.fgcolor = app.palette().buttonText().color()
        self.bgcolor = app.palette().button().color()
        ui.fgcolorButton.setStyleSheet("background-color:"+self.fgcolor.name())
        ui.bgcolorButton.setStyleSheet("background-color:"+self.bgcolor.name())
示例#46
0
    def __init__(self, parent, editing, standard_colheads, standard_colnames):
        QDialog.__init__(self, parent)
        Ui_QCreateCustomColumn.__init__(self)
        self.setupUi(self)
        self.setWindowTitle(_('Create a custom column'))
        self.heading_label.setText(_('Create a custom column'))
        # Remove help icon on title bar
        icon = self.windowIcon()
        self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
        self.setWindowIcon(icon)

        self.simple_error = partial(error_dialog, self, show=True,
            show_copy_button=False)
        self.button_box.accepted.connect(self.accept)
        self.button_box.rejected.connect(self.reject)
        self.shortcuts.linkActivated.connect(self.shortcut_activated)
        text = '<p>'+_('Quick create:')
        for col, name in [('isbn', _('ISBN')), ('formats', _('Formats')),
                ('yesno', _('Yes/No')),
                ('tags', _('Tags')), ('series', _('Series')), ('rating',
                    _('Rating')), ('people', _("People's names"))]:
            text += ' <a href="col:%s">%s</a>,'%(col, name)
        text = text[:-1]
        self.shortcuts.setText(text)

        for sort_by in [_('Text'), _('Number'), _('Date'), _('Yes/No')]:
            self.composite_sort_by.addItem(sort_by)

        self.parent = parent
        self.editing_col = editing
        self.standard_colheads = standard_colheads
        self.standard_colnames = standard_colnames
        self.column_type_box.setMaxVisibleItems(len(self.column_types))
        for t in self.column_types:
            self.column_type_box.addItem(self.column_types[t]['text'])
        self.column_type_box.currentIndexChanged.connect(self.datatype_changed)
        if not self.editing_col:
            self.datatype_changed()
            self.exec_()
            return
        self.setWindowTitle(_('Edit a custom column'))
        self.heading_label.setText(_('Edit a custom column'))
        self.shortcuts.setVisible(False)
        idx = parent.opt_columns.currentRow()
        if idx < 0:
            self.simple_error(_('No column selected'),
                    _('No column has been selected'))
            return
        col = unicode(parent.opt_columns.item(idx).data(Qt.UserRole).toString())
        if col not in parent.custcols:
            self.simple_error('', _('Selected column is not a user-defined column'))
            return

        c = parent.custcols[col]
        self.column_name_box.setText(c['label'])
        self.column_heading_box.setText(c['name'])
        ct = c['datatype']
        if c['is_multiple']:
            ct = '*' + ct
        self.orig_column_number = c['colnum']
        self.orig_column_name = col
        column_numbers = dict(map(lambda x:(self.column_types[x]['datatype'], x),
                                  self.column_types))
        self.column_type_box.setCurrentIndex(column_numbers[ct])
        self.column_type_box.setEnabled(False)
        if ct == 'datetime':
            if c['display'].get('date_format', None):
                self.date_format_box.setText(c['display'].get('date_format', ''))
        elif ct in ['composite', '*composite']:
            self.composite_box.setText(c['display'].get('composite_template', ''))
            sb = c['display'].get('composite_sort', 'text')
            vals = ['text', 'number', 'date', 'bool']
            if sb in vals:
                sb = vals.index(sb)
            else:
                sb = 0
            self.composite_sort_by.setCurrentIndex(sb)
            self.composite_make_category.setChecked(
                                c['display'].get('make_category', False))
            self.composite_contains_html.setChecked(
                                c['display'].get('contains_html', False))
        elif ct == 'enumeration':
            self.enum_box.setText(','.join(c['display'].get('enum_values', [])))
            self.enum_colors.setText(','.join(c['display'].get('enum_colors', [])))
        elif ct in ['int', 'float']:
            if c['display'].get('number_format', None):
                self.number_format_box.setText(c['display'].get('number_format', ''))
        self.datatype_changed()
        if ct in ['text', 'composite', 'enumeration']:
            self.use_decorations.setChecked(c['display'].get('use_decorations', False))
        elif ct == '*text':
            self.is_names.setChecked(c['display'].get('is_names', False))

        all_colors = [unicode(s) for s in list(QColor.colorNames())]
        self.enum_colors_label.setToolTip('<p>' + ', '.join(all_colors) + '</p>')

        self.composite_contains_html.setToolTip('<p>' +
                _('If checked, this column will be displayed as HTML in '
                  'book details and the content server. This can be used to '
                  'construct links with the template language. For example, '
                  'the template '
                  '<pre>&lt;big&gt;&lt;b&gt;{title}&lt;/b&gt;&lt;/big&gt;'
                  '{series:| [|}{series_index:| [|]]}</pre>'
                  'will create a field displaying the title in bold large '
                  'characters, along with the series, for example <br>"<big><b>'
                  'An Oblique Approach</b></big> [Belisarius [1]]". The template '
                  '<pre>&lt;a href="http://www.beam-ebooks.de/ebook/{identifiers'
                  ':select(beam)}"&gt;Beam book&lt;/a&gt;</pre> '
                  'will generate a link to the book on the Beam ebooks site.')
                        + '</p>')
        self.exec_()
示例#47
0
    def __init__(self, parent, text, mi=None, fm=None, color_field=None,
                 icon_field_key=None, icon_rule_kind=None):
        QDialog.__init__(self, parent)
        Ui_TemplateDialog.__init__(self)
        self.setupUi(self)

        self.coloring = color_field is not None
        self.iconing = icon_field_key is not None

        cols = []
        if fm is not None:
            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 not self.coloring:
                    continue
                from calibre.gui2.preferences.coloring import all_columns_string
                name = all_columns_string if key == color_row_key else fm[key]['name']
                if name:
                    cols.append((name, key))

        self.color_layout.setVisible(False)
        self.icon_layout.setVisible(False)

        if self.coloring:
            self.color_layout.setVisible(True)
            for n1, k1 in cols:
                self.colored_field.addItem(n1, k1)
            self.colored_field.setCurrentIndex(self.colored_field.findData(color_field))
            colors = QColor.colorNames()
            colors.sort()
            self.color_name.addItems(colors)
        elif self.iconing:
            self.icon_layout.setVisible(True)
            for n1, k1 in cols:
                self.icon_field.addItem(n1, k1)
            self.icon_file_names = []
            d = os.path.join(config_dir, 'cc_icons')
            if os.path.exists(d):
                for icon_file in os.listdir(d):
                    icon_file = icu_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)
            self.update_filename_box()
            self.icon_with_text.setChecked(True)
            if icon_rule_kind == 'icon_only':
                self.icon_without_text.setChecked(True)
            self.icon_field.setCurrentIndex(self.icon_field.findData(icon_field_key))

        if mi:
            self.mi = mi
        else:
            self.mi = Metadata(_('Title'), [_('Author')])
            self.mi.author_sort = _('Author Sort')
            self.mi.series = _('Series')
            self.mi.series_index = 3
            self.mi.rating = 4.0
            self.mi.tags = [_('Tag 1'), _('Tag 2')]
            self.mi.languages = ['eng']
            if fm is not None:
                self.mi.set_all_user_metadata(fm.custom_field_metadata())

        # Remove help icon on title bar
        icon = self.windowIcon()
        self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
        self.setWindowIcon(icon)

        self.last_text = ''
        self.highlighter = TemplateHighlighter(self.textbox.document())
        self.textbox.cursorPositionChanged.connect(self.text_cursor_changed)
        self.textbox.textChanged.connect(self.textbox_changed)

        self.textbox.setTabStopWidth(10)
        self.source_code.setTabStopWidth(10)
        self.documentation.setReadOnly(True)
        self.source_code.setReadOnly(True)

        if text is not None:
            self.textbox.setPlainText(text)
        self.buttonBox.button(QDialogButtonBox.Ok).setText(_('&OK'))
        self.buttonBox.button(QDialogButtonBox.Cancel).setText(_('&Cancel'))
        self.color_copy_button.clicked.connect(self.color_to_clipboard)
        self.filename_button.clicked.connect(self.filename_button_clicked)
        self.icon_copy_button.clicked.connect(self.icon_to_clipboard)

        try:
            with open(P('template-functions.json'), 'rb') as f:
                self.builtin_source_dict = json.load(f, encoding='utf-8')
        except:
            self.builtin_source_dict = {}

        self.funcs = formatter_functions().get_functions()
        self.builtins = formatter_functions().get_builtins()

        func_names = sorted(self.funcs)
        self.function.clear()
        self.function.addItem('')
        self.function.addItems(func_names)
        self.function.setCurrentIndex(0)
        self.function.currentIndexChanged[str].connect(self.function_changed)
        self.textbox_changed()
        self.rule = (None, '')

        tt = _('Template language tutorial')
        self.template_tutorial.setText(
                '<a href="http://manual.calibre-ebook.com/template_lang.html">'
                '%s</a>'%tt)
        tt = _('Template function reference')
        self.template_func_reference.setText(
                '<a href="http://manual.calibre-ebook.com/template_ref.html">'
                '%s</a>'%tt)
    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
            .rating
            .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_rating()
        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()
示例#49
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.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()
            self.filename_box.setInsertPolicy(self.filename_box.InsertAlphabetically)
            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)
            self.update_filename_box()

            l.addWidget(self.filename_box, 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.filename_button.clicked.connect(self.filename_button_clicked)

        self.resize(self.sizeHint())
示例#50
0
    def accept(self):
        col = unicode(self.column_name_box.text()).strip()
        if not col:
            return self.simple_error("", _("No lookup name was provided"))
        if col.startswith("#"):
            col = col[1:]
        if re.match("^\w*$", col) is None or not col[0].isalpha() or col.lower() != col:
            return self.simple_error(
                "",
                _(
                    "The lookup name must contain only "
                    "lower case letters, digits and underscores, and start with a letter"
                ),
            )
        if col.endswith("_index"):
            return self.simple_error(
                "",
                _(
                    "Lookup names cannot end with _index, "
                    "because these names are reserved for the index of a series column."
                ),
            )
        col_heading = unicode(self.column_heading_box.text()).strip()
        col_type = self.column_types[self.column_type_box.currentIndex()]["datatype"]
        if col_type[0] == "*":
            col_type = col_type[1:]
            is_multiple = True
        else:
            is_multiple = False
        if not col_heading:
            return self.simple_error("", _("No column heading was provided"))

        db = self.parent.gui.library_view.model().db
        key = db.field_metadata.custom_field_prefix + col
        bad_col = False
        if key in self.parent.custcols:
            if not self.editing_col or self.parent.custcols[key]["colnum"] != self.orig_column_number:
                bad_col = True
        if bad_col:
            return self.simple_error("", _("The lookup name %s is already used") % col)

        bad_head = False
        for t in self.parent.custcols:
            if self.parent.custcols[t]["name"] == col_heading:
                if not self.editing_col or self.parent.custcols[t]["colnum"] != self.orig_column_number:
                    bad_head = True
        for t in self.standard_colheads:
            if self.standard_colheads[t] == col_heading:
                bad_head = True
        if bad_head:
            return self.simple_error("", _("The heading %s is already used") % col_heading)

        display_dict = {}

        if col_type == "datetime":
            if unicode(self.date_format_box.text()).strip():
                display_dict = {"date_format": unicode(self.date_format_box.text()).strip()}
            else:
                display_dict = {"date_format": None}
        elif col_type == "composite":
            if not unicode(self.composite_box.text()).strip():
                return self.simple_error("", _("You must enter a template for" " composite columns"))
            display_dict = {
                "composite_template": unicode(self.composite_box.text()).strip(),
                "composite_sort": ["text", "number", "date", "bool"][self.composite_sort_by.currentIndex()],
                "make_category": self.composite_make_category.isChecked(),
                "contains_html": self.composite_contains_html.isChecked(),
            }
        elif col_type == "enumeration":
            if not unicode(self.enum_box.text()).strip():
                return self.simple_error("", _("You must enter at least one" " value for enumeration columns"))
            l = [v.strip() for v in unicode(self.enum_box.text()).split(",") if v.strip()]
            l_lower = [v.lower() for v in l]
            for i, v in enumerate(l_lower):
                if v in l_lower[i + 1 :]:
                    return self.simple_error(
                        "",
                        _('The value "{0}" is in the ' "list more than once, perhaps with different case").format(l[i]),
                    )
            c = unicode(self.enum_colors.text())
            if c:
                c = [v.strip() for v in unicode(self.enum_colors.text()).split(",")]
            else:
                c = []
            if len(c) != 0 and len(c) != len(l):
                return self.simple_error(
                    "", _("The colors box must be empty or " "contain the same number of items as the value box")
                )
            for tc in c:
                if tc not in QColor.colorNames():
                    return self.simple_error("", _("The color {0} is unknown").format(tc))

            display_dict = {"enum_values": l, "enum_colors": c}
        elif col_type == "text" and is_multiple:
            display_dict = {"is_names": self.is_names.isChecked()}
        elif col_type in ["int", "float"]:
            if unicode(self.number_format_box.text()).strip():
                display_dict = {"number_format": unicode(self.number_format_box.text()).strip()}
            else:
                display_dict = {"number_format": None}

        if col_type in ["text", "composite", "enumeration"] and not is_multiple:
            display_dict["use_decorations"] = self.use_decorations.checkState()

        if not self.editing_col:
            self.parent.custcols[key] = {
                "label": col,
                "name": col_heading,
                "datatype": col_type,
                "display": display_dict,
                "normalized": None,
                "colnum": None,
                "is_multiple": is_multiple,
            }
            item = QListWidgetItem(col_heading, self.parent.opt_columns)
            item.setData(Qt.UserRole, QVariant(key))
            item.setData(Qt.DecorationRole, QVariant(QIcon(I("column.png"))))
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable)
            item.setCheckState(Qt.Checked)
        else:
            idx = self.parent.opt_columns.currentRow()
            item = self.parent.opt_columns.item(idx)
            item.setText(col_heading)
            self.parent.custcols[self.orig_column_name]["label"] = col
            self.parent.custcols[self.orig_column_name]["name"] = col_heading
            self.parent.custcols[self.orig_column_name]["display"].update(display_dict)
            self.parent.custcols[self.orig_column_name]["*edited"] = True
            self.parent.custcols[self.orig_column_name]["*must_restart"] = True
        QDialog.accept(self)
示例#51
0
    def run(self):
        
        self.exit = False

        global psi1, psi2, psi3, psi4, M, N, x0, X, y0, Y, t0, T, n, f, phi
        
        global Max, Min        
              
        U0 = []
        
        global K
        
        for k in xrange(K+1):
                U0.append([phi(x0+m*h1,y0+k*h2) for m in xrange(M+1)]) 
        
        #self.MU.append(U0)
        
        img = QImage(M+1,K+1,QImage.Format_RGB32)
        
        c = QColor()
        
        U = U0
            
        for i in xrange(len(U)):
            for j in xrange(len(U[0])):
                c.setHsvF(0.833333333*(1.0-(U[i][j]-Min)/(Max-Min)),1,1)
                img.setPixel(i,j,c.rgb())
        
        self.Images.append(img)
        
        global u,tau
        
        for n in xrange(N+1):
            U = vardir(f, U0, psi1, psi2, psi3, psi4, M, K, N, x0, X, y0, Y, t0, T, n)
            #U=[]
            #for k in xrange(K+1):
            #    U.append([u(t0+n*tau,x0+m*h1,y0+k*h2) for m in xrange(M+1)]) 
            U0 = []
            for k in xrange(K+1):
                U0.append(U[k])
            #self.MU.append(U0)
            
            #print (n/float(N)*100)
            
            img = QImage(M+1,K+1,QImage.Format_RGB32)
            
            c = QColor()
            
            for i in xrange(len(U)):
                for j in xrange(len(U[0])):
                    #print U[i][j] 
                    fl = min(max(0, 0.833333333*(1.0-(U[i][j]-Min)/(Max-Min))), 1)
                    c.setHsvF(fl,1,1)
                    img.setPixel(i,j,c.rgb())
                    
            self.Images.append(img)
            
            self.progr = (int(n/float(N)*100))
            
            if(self.exit):
                break
示例#52
0
class Preferencer:

    def __init__(self, app):
        if not hasattr(app, 'filters'):
            print("preferences: need 'filters' from app.")
            exit(1)
        self.app = app
        self.settings = QSettings("blain", "blain")
        self.ui = PreferencesDialog(app)


    def connect(self):
        ui, ft = self.ui, self.app.filters
        self.app.window.ui.actionPreferences.triggered.connect(self.show)
        # connect filters
        ui.filtersComboBox.currentIndexChanged.connect(ft.changeDescription)
        ui.filtersComboBox_new.currentIndexChanged.connect(ft.changeNew)
        ui.addfilterButton.clicked.connect(ft.install)
        ui.updatefilterButton.clicked.connect(lambda: ft.update())
        ui.removefilterButton.clicked.connect(ft.remove)
        #connect preference window
        ui.fgcolorButton.clicked.connect(self.change_fgcolor)
        ui.bgcolorButton.clicked.connect(self.change_bgcolor)
        ui.resetcolorButton.clicked.connect(self.reset_color)
        ui.buttonBox.accepted.connect(self.accept)
        ui.buttonBox.rejected.connect(self.reject)
        ui.buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.save)
        ui.listWidget.currentRowChanged.connect(
            ui.stackedWidget.setCurrentIndex)


    def setup(self):
        self.load()
        self.app.filters.changeNew(0)
        self.app.filters.changeDescription(0)


    def show(self, _):
        self.app.window.disable()
        self.ui.show()


    def hide(self):
        self.ui.hide()
        self.app.window.enable()


    def reject(self):
        self.hide()
        self.load()


    def accept(self):
        self.hide()
        self.save()


    def save(self):
        app, st, ui = self.app, self.settings, self.ui
        st.setValue("account/twitter/id", ui.twitteridEdit.text())
        st.setValue("account/identica/id", ui.identicaidEdit.text())
        st.setValue("icon/isdark", ui.darkradioButton.isChecked())
        st.setValue("color/messages/fg", self.fgcolor.name())
        st.setValue("color/messages/bg", self.bgcolor.name())
        self.app.icons.loadWindow()
        if self.fgcolor != self.old.fgcolor or self.bgcolor != self.old.bgcolor:
            self.old = drug(fgcolor = self.fgcolor, bgcolor = self.bgcolor)
            self.app.window.update_messages_colors()


    def load(self):
        st, ui = self.settings, self.ui
        self.fgcolor = QColor(st.value("color/messages/fg",
            self.app.palette().buttonText().color().name()).toString())
        self.bgcolor = QColor(st.value("color/messages/bg",
            self.app.palette().button().color().name()).toString())
        self.old = drug(fgcolor = self.fgcolor, bgcolor = self.bgcolor)

        ui.identicaidEdit.setText(st.value("account/identica/id").toString())
        ui.twitteridEdit.setText(st.value("account/twitter/id").toString())
        b = st.value("icon/isdark",True).toBool()
        ui.darkradioButton.setChecked(b)
        ui.lightradioButton.setChecked(not b)
        ui.fgcolorButton.setStyleSheet("background-color:"+self.fgcolor.name())
        ui.bgcolorButton.setStyleSheet("background-color:"+self.bgcolor.name())


    def change_fgcolor(self):
        self.change_color('fgcolor')


    def change_bgcolor(self):
        self.change_color('bgcolor')


    def change_color(self, color_name):
        if not hasattr(self, color_name): return
        color = getattr(self, color_name)
        color = QColorDialog.getColor(color, self.ui)
        setattr(self, color_name, color)
        getattr(self.ui, color_name+"Button").setStyleSheet(
            "background-color:" + color.name())


    def reset_color(self):
        app, ui = self.app, self.ui
        self.fgcolor = app.palette().buttonText().color()
        self.bgcolor = app.palette().button().color()
        ui.fgcolorButton.setStyleSheet("background-color:"+self.fgcolor.name())
        ui.bgcolorButton.setStyleSheet("background-color:"+self.bgcolor.name())
示例#53
0
    def __init__(self, fm, parent=None):
        QDialog.__init__(self, parent)
        self.fm = fm

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

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

        self.l1 = l1 = QLabel(_('Create a coloring rule by'
            ' filling in the boxes below'))
        l.addWidget(l1, 0, 0, 1, 5)

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

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

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

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

        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, 3)
        l.addWidget(self.color_label, 2, 4)
        l.addItem(QSpacerItem(10, 10, QSizePolicy.Expanding), 2, 5)

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

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

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

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

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

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

        for b in (self.column_box, self.color_box):
            b.setSizeAdjustPolicy(b.AdjustToMinimumContentsLengthWithIcon)
            b.setMinimumContentsLength(15)

        for key in sorted(
                displayable_columns(fm),
                key=sort_key):
            name = fm[key]['name']
            if name:
                self.column_box.addItem(key, key)
        self.column_box.setCurrentIndex(0)

        self.color_box.addItems(QColor.colorNames())
        self.color_box.setCurrentIndex(0)

        self.update_color_label()
        self.color_box.currentIndexChanged.connect(self.update_color_label)
        self.resize(self.sizeHint())
示例#54
0
class Pointer(QWidget):

    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)

        # from PyQt4.Qt import QTimer
        # QTimer.singleShot(1000, self.start)

    @property
    def gui(self):
        return self.parent()

    def point_at(self, frac):
        return (self.path.pointAtPercent(frac).toPoint() -
                QPoint(self.rect().center().x(), self.height()))

    def rect_at(self, frac):
        return QRect(self.point_at(frac), self.size())

    def abspos(self, widget):
        pos = widget.pos()
        parent = widget.parent()
        while parent is not self.gui:
            pos += parent.pos()
            parent = parent.parent()
        return pos

    def start(self):
        if config['disable_animations']:
            return
        self.setVisible(True)
        self.raise_()
        end = self.abspos(self.gui.jobs_button)
        end = QPointF( end.x() + self.gui.jobs_button.width()/3.0, end.y()+20)
        start = QPointF(end.x(), end.y() - 0.5*self.height())
        self.path = QPainterPath(QPointF(start))
        self.path.lineTo(end)
        self.path.closeSubpath()
        self.animation.setStartValue(self.rect_at(0.0))
        self.animation.setEndValue(self.rect_at(1.0))
        self.animation.setDirection(self.animation.Backward)
        num_keys = 100
        for i in xrange(1, num_keys):
            i /= num_keys
            self.animation.setKeyValueAt(i, self.rect_at(i))
        self.animation.start()

    def paintEvent(self, ev):
        p = QPainter(self)
        p.setRenderHints(p.Antialiasing)
        p.setBrush(self.brush)
        p.setPen(Qt.NoPen)
        p.drawPath(self.arrow_path)
        p.end()