Пример #1
0
 def __fillLastTileComboWith(self, lastTiles, winnerTiles):
     """fill last meld combo with prepared content"""
     self.comboTilePairs = lastTiles
     idx = self.cbLastTile.currentIndex()
     if idx < 0:
         idx = 0
     indexedTile = str(self.cbLastTile.itemData(idx).toPyObject())
     restoredIdx = None
     self.cbLastTile.clear()
     if not winnerTiles:
         return
     pmSize = winnerTiles[0].board.tileset.faceSize
     pmSize = QSize(pmSize.width() * 0.5, pmSize.height() * 0.5)
     self.cbLastTile.setIconSize(pmSize)
     QPixmapCache.clear()
     self.__tilePixMaps = []
     shownTiles = set()
     for tile in winnerTiles:
         if tile.element in lastTiles and tile.element not in shownTiles:
             shownTiles.add(tile.element)
             self.cbLastTile.addItem(QIcon(tile.graphics.pixmapFromSvg(pmSize, withBorders=False)),
                     '', QVariant(tile.element))
             if indexedTile == tile.element:
                 restoredIdx = self.cbLastTile.count() - 1
     if not restoredIdx and indexedTile:
         # try again, maybe the tile changed between concealed and exposed
         indexedTile = indexedTile.lower()
         for idx in range(self.cbLastTile.count()):
             if indexedTile == str(self.cbLastTile.itemData(idx).toPyObject()).lower():
                 restoredIdx = idx
                 break
     if not restoredIdx:
         restoredIdx = 0
     self.cbLastTile.setCurrentIndex(restoredIdx)
     self.prevLastTile = self.computeLastTile()
    def drawOverlay(self, painter, option, index):
        """
                Paints the overlay color for this item if the current thumbnail
                based on whether or not it is the latest thumbnail available
                
                :param      painter:
                :type       <QPainter>:
                
                :param      option:
                :param      <QStyleOptionItem>:
                
                :param      index:
                :type       <QModelIndex>:
        """
        # extract the option's frame range information
        key = index.data(Qt.UserRole).toString()
        if not key:
            return

        pixmap = QPixmap()

        # restore the pixmap from cache
        if not QPixmapCache.find(key, pixmap):
            pixmap.load(settings.iconCachePath("%s.jpg" % key))
            QPixmapCache.insert(key, pixmap)

        # draw the overlay
        painter.drawPixmap(option.rect, pixmap)
Пример #3
0
 def horizontalGradient(self, painter, spanRect, clipRect):
     key = 'fancy vertical gradient %d %d %d %d %d'%(spanRect.width(), spanRect.height(), clipRect.width(),
                                          clipRect.height(), self.baseColor.rgb())
     pixmap = QPixmap()
     p = painter
     rect = QRect(clipRect)
     
     if self._usePixmapCache and not QPixmapCache.find(key, pixmap):
         pixmap = QPixmap(clipRect.size())
         p = QPainter(pixmap)
         rect = QRect(0, 0, clipRect.width(), clipRect.height())
     
     base = self.baseColor
     grad = QLinearGradient(QPointF(rect.topLeft()), QPointF(rect.bottomLeft()))
     grad.setColorAt(0, self.highlightColor.lighter(120))
     if rect.height() == self.navigationWidgetHeight:
         grad.setColorAt(0.4, self.highlightColor)
         grad.setColorAt(0.401, base)
     grad.setColorAt(1, self.shadowColor)
     p.fillRect(rect, grad)
     
     shadowGradient = QLinearGradient(QPointF(spanRect.topLeft()), QPointF(spanRect.topRight()))
     shadowGradient.setColorAt(0, QColor(0, 0, 0, 30))
     highlight = self.highlightColor.lighter(130)
     highlight.setAlpha(100)
     shadowGradient.setColorAt(0.7, highlight)
     shadowGradient.setColorAt(1, QColor(0, 0, 0, 40))
     p.fillRect(rect, shadowGradient)
 
     if self._usePixmapCache and not QPixmapCache.find(key, pixmap):
         painter.drawPixmap(clipRect.topLeft(), pixmap)
         p.end()
         del p
         QPixmapCache.insert(key, pixmap)
Пример #4
0
 def findIcon(self, name=str, size=int):
     for _name in name:
         pixmapName = ''.join(('$qt', str(_name), str(size)))
         if (QPixmapCache.find(pixmapName, self.pixmap)):
             logging.debug('Icon %s returned from cache' % _name)
             return self.pixmap
     self._themes = []
     if self.themeName:
         self._themes.append(self.themeName)
         for _name in name:
             self.pixmap = self.findIconHelper(int(size), self.themeName,
                                               _name)
             if not self.pixmap.isNull():
                 break
     if self.pixmap.isNull():
         for _name in name:
             self._themes.extend(self.themeIndex.parents)
             if len(self._themes) > 0:
                 self.pixmap = self.findIconHelper(int(size),
                                                   self._themes[0], _name)
                 if not self.pixmap.isNull():
                     break
     if not name:
         return QPixmap()
     pixmapName = ''.join(('$qt', str(_name), str(size)))
     if not self.pixmap.isNull():
         logging.debug('Icon cached with name: %s ' % pixmapName)
         QPixmapCache.insert(pixmapName, self.pixmap)
     return self.pixmap
Пример #5
0
    def drawOverlay(self, painter, option, index):
        """
                Paints the overlay color for this item if the current thumbnail
                based on whether or not it is the latest thumbnail available
                
                :param      painter:
                :type       <QPainter>:
                
                :param      option:
                :param      <QStyleOptionItem>:
                
                :param      index:
                :type       <QModelIndex>:
        """
        # extract the option's frame range information
        key = index.data(Qt.UserRole).toString()
        if (not key):
            return

        pixmap = QPixmap()

        # restore the pixmap from cache
        if (not QPixmapCache.find(key, pixmap)):
            pixmap.load(settings.iconCachePath('%s.jpg' % key))
            QPixmapCache.insert(key, pixmap)

        # draw the overlay
        painter.drawPixmap(option.rect, pixmap)
Пример #6
0
 def setColor(self, newColor):
     if (newColor == self._color):
         return
     oldKey = self._generateKey()
     QPixmapCache.remove(oldKey)
     self._color = QColor(newColor)
     self.update()
Пример #7
0
    def paint(self, painter, option, index):
        """
                Overloads the base paint method for a QItemDelegate
                to force the overlay color options to be drawn.
                
                :param      painter:
                :type       <QPainter>:
                
                :param      option:
                :type       <QStyleOptionViewItem>:
                
                :param      index:
                :type       <QModelIndex>:
        """
        self.drawBackground(painter, option, index)

        # extract the option's frame range information
        key = index.data(Qt.UserRole).toString()
        if (not key):
            return

        pixmap = QPixmap()

        # restore the pixmap from cache
        if (not QPixmapCache.find(key, pixmap)):
            pixmap.load(settings.iconCachePath('%s.jpg' % key))
            QPixmapCache.insert(key, pixmap)

        # draw the overlay
        painter.drawPixmap(option.rect, pixmap)
Пример #8
0
 def findIcon(self, name = str, size = int):
     for _name in name:
         pixmapName = ''.join(('$qt', str(_name), str(size)))
         if (QPixmapCache.find(pixmapName, self.pixmap)):
             logging.debug('Icon %s returned from cache' % _name)
             return self.pixmap
     self._themes = []
     if self.themeName:
         self._themes.append(self.themeName)
         for _name in name:
             self.pixmap = self.findIconHelper(int(size),
                     self.themeName, _name)
             if not self.pixmap.isNull():
                 break
     if self.pixmap.isNull():
         for _name in name:
             self._themes.extend(self.themeIndex.parents)
             if len(self._themes) > 0:
                 self.pixmap = self.findIconHelper(int(size),
                         self._themes[0] ,_name)
                 if not self.pixmap.isNull():
                     break
     if not name:
         return QPixmap()
     pixmapName = ''.join(('$qt', str(_name), str(size)))
     if not self.pixmap.isNull():
         logging.debug('Icon cached with name: %s ' % pixmapName)
         QPixmapCache.insert(pixmapName, self.pixmap)
     return self.pixmap
Пример #9
0
 def verticalGradient(self, painter, spanRect, clipRect):
     key = 'fancy vertical gradient %d %d %d %d %d'%(spanRect.width(), spanRect.height(), clipRect.width(),
                                          clipRect.height(), self.baseColor.rgb())
     pixmap = QPixmap()
     p = painter
     rect = QRect(clipRect)
     
     if self._usePixmapCache and not QPixmapCache.find(key, pixmap):
         pixmap = QPixmap(clipRect.size())
         p = QPainter(pixmap)
         rect = QRect(0, 0, clipRect.width(), clipRect.height())
     
     base = self.baseColor
     grad = QLinearGradient(QPointF(spanRect.topRight()), QPointF(spanRect.topLeft()))
     grad.setColorAt(0, self.highlightColor)
     grad.setColorAt(0.301, base)
     grad.setColorAt(1, self.shadowColor)
     p.fillRect(rect, grad)
     
     light = QColor(255, 255, 255, 80)
     p.setPen(light)
     p.drawLine(rect.topRight() - QPoint(1, 0), rect.bottomRight() - QPoint(1, 0))
     
     if self._usePixmapCache and not QPixmapCache.find(key, pixmap):
         painter.drawPixmap(clipRect.topLeft(), pixmap)
         p.end()
         del p
         QPixmapCache.insert(key, pixmap)
    def paint(self, painter, option, index):
        """
                Overloads the base paint method for a QItemDelegate
                to force the overlay color options to be drawn.
                
                :param      painter:
                :type       <QPainter>:
                
                :param      option:
                :type       <QStyleOptionViewItem>:
                
                :param      index:
                :type       <QModelIndex>:
        """
        self.drawBackground(painter, option, index)

        # extract the option's frame range information
        key = index.data(Qt.UserRole).toString()
        if not key:
            return

        pixmap = QPixmap()

        # restore the pixmap from cache
        if not QPixmapCache.find(key, pixmap):
            pixmap.load(settings.iconCachePath("%s.jpg" % key))
            QPixmapCache.insert(key, pixmap)

        # draw the overlay
        painter.drawPixmap(option.rect, pixmap)
Пример #11
0
 def __init__(self, thread):
     super(ThumbsItemModel, self).__init__()
     self.__thread = thread
     self.currentNodeDir = None
     self.initSignals()
     self.pixmapCache = QPixmapCache()
     self.pixmapCache.setCacheLimit(61440)
     self.__thread.pixmapCache = self.pixmapCache
Пример #12
0
    class __ThumbnailManager(QObject):
        def __init__(self):
            QObject.__init__(self)
            self.pixmapCache = QPixmapCache()
            self.pixmapCache.setCacheLimit(61440)
            self.thread = QThread()
            self.scaler = Scaler()
            self.scaler.moveToThread(self.thread)
            self.connect(self.scaler, SIGNAL("scaledFinished"), self.finished)
            self.thread.start()
            self.thumbnailers = []
            self.handledRequest = set()
            self.corruptionHandler = CorruptedPictureHandler()
            self.pixmapCorrupted = QPixmap(":file_broken.png")

        def register(self, thumbnailer):
            self.thumbnailers.append(thumbnailer)

        def unregister(self, thumbnailer):
            try:
                self.thumbnailers.remove(thumbnailer)
            except:
                pass

        def generate(self, config):
            pixmap = self.pixmapCache.find(str(config))
            if pixmap:
                return pixmap
            elif self.corruptionHandler.isCorrupted(config.node):
                return self.pixmapCorrupted
            else:
                if config not in self.handledRequest:
                    QApplication.postEvent(self.scaler, ScaleEvent(config))
                    self.handledRequest.add(config)

        def finished(self, config, scaledImage):
            if scaledImage:
                pixmap = QPixmap().fromImage(scaledImage)
                self.pixmapCache.insert(str(config), pixmap)
                self.emitUpdate(config, pixmap)
            else:
                self.corruptionHandler.setAttributes(config.node)
                self.emitUpdate(config, self.pixmapCorrupted)

        def emitUpdate(self, config, pixmap):
            for thumbnailer in self.thumbnailers:
                try:
                    if thumbnailer.request(config):
                        thumbnailer.emit(SIGNAL("ThumbnailUpdate"),
                                         config.node, pixmap)
                        thumbnailer.requestRemove(config)
                except:
                    pass
            try:
                self.handledRequest.remove(config)
            except KeyError:
                pass
Пример #13
0
    class __ThumbnailManager(QObject):
        def __init__(self):
            QObject.__init__(self)
            self.pixmapCache = QPixmapCache()
            self.pixmapCache.setCacheLimit(61440)
            self.thread = QThread()
            self.scaler = Scaler()
            self.scaler.moveToThread(self.thread)
            self.connect(self.scaler, SIGNAL("scaledFinished"), self.finished)
            self.thread.start()
            self.thumbnailers = []
            self.handledRequest = set()
            self.corruptionHandler = CorruptedPictureHandler()
            self.pixmapCorrupted = QPixmap(":file_broken.png")

        def register(self, thumbnailer):
            self.thumbnailers.append(thumbnailer)

        def unregister(self, thumbnailer):
            try:
                self.thumbnailers.remove(thumbnailer)
            except:
                pass

        def generate(self, config):
            pixmap = self.pixmapCache.find(str(config))
            if pixmap:
                return pixmap
            elif self.corruptionHandler.isCorrupted(config.node):
                return self.pixmapCorrupted
            else:
                if config not in self.handledRequest:
                    QApplication.postEvent(self.scaler, ScaleEvent(config))
                    self.handledRequest.add(config)

        def finished(self, config, scaledImage):
            if scaledImage:
                pixmap = QPixmap().fromImage(scaledImage)
                self.pixmapCache.insert(str(config), pixmap)
                self.emitUpdate(config, pixmap)
            else:
                self.corruptionHandler.setAttributes(config.node)
                self.emitUpdate(config, self.pixmapCorrupted)

        def emitUpdate(self, config, pixmap):
            for thumbnailer in self.thumbnailers:
                try:
                    if thumbnailer.request(config):
                        thumbnailer.emit(SIGNAL("ThumbnailUpdate"), config.node, pixmap)
                        thumbnailer.requestRemove(config)
                except:
                    pass
            try:
                self.handledRequest.remove(config)
            except KeyError:
                pass
Пример #14
0
    def __init__(self, desktopFileName=None):
        if desktopFileName is None:
            desktopFileName = 'default'
        self.__svg = None
        self.__pmap = None
        QPixmapCache.setCacheLimit(20480)  # the chinese landscape needs much
        self.defineCatalog()
        self.desktopFileName = desktopFileName
        self.path = locatebackground(desktopFileName + '.desktop')
        if self.path.isEmpty():
            self.path = locatebackground('default.desktop')
            if self.path.isEmpty():
                directories = '\n\n' + '\n'.join(
                    str(x) for x in KGlobal.dirs().resourceDirs(
                        "kmahjonggbackground"))
                logException(BackgroundException(m18n( \
                'cannot find any background in the following directories, is libkmahjongg installed?') + directories))
            else:
                logWarning(
                    m18n('cannot find background %1, using default',
                         desktopFileName))
                self.desktopFileName = 'default'
        config, group = konfigGroup(self.path, "KMahjonggBackground")
        assert config
        self.name = group.readEntry(
            "Name", "unknown background").toString()  # Returns translated data

        #Version control
        backgroundversion, entryOK = group.readEntry("VersionFormat",
                                                     QVariant(0)).toInt()
        #Format is increased when we have incompatible changes, meaning that
        # older clients are not able to use the remaining information safely
        if not entryOK or backgroundversion > BACKGROUNDVERSIONFORMAT:
            logException(BackgroundException('backgroundversion file / program: %d/%d' % \
                (backgroundversion, BACKGROUNDVERSIONFORMAT)))

        self.tiled = group.readEntry('Tiled') == '1'
        if self.tiled:
            self.imageWidth, entryOk = group.readEntry('Width').toInt()
            if not entryOk:
                raise Exception('cannot scan Width from background file')
            self.imageHeight, entryOk = group.readEntry('Height').toInt()
            if not entryOk:
                raise Exception('cannot scan Height from background file')
        self.isPlain = bool(group.readEntry('Plain'))
        if not self.isPlain:
            graphName = QString(group.readEntry("FileName"))
            self.__graphicspath = locatebackground(graphName)
            if self.__graphicspath.isEmpty():
                logException(BackgroundException(
                    'cannot find kmahjongglib/backgrounds/%s for %s' % \
                        (graphName, self.desktopFileName )))
Пример #15
0
 def __init__(self):
     QObject.__init__(self)
     self.pixmapCache = QPixmapCache()
     self.pixmapCache.setCacheLimit(61440)
     self.thread = QThread()
     self.scaler = Scaler()
     self.scaler.moveToThread(self.thread)
     self.connect(self.scaler, SIGNAL("scaledFinished"), self.finished)
     self.thread.start()
     self.thumbnailers = []
     self.handledRequest = set()
     self.corruptionHandler = CorruptedPictureHandler()
     self.pixmapCorrupted = QPixmap(":file_broken.png")
Пример #16
0
    def load(self, name, size=128, forceCache=False):
        icon = QIcon()
        size = int(size)
        self.pixmap = QPixmap()
        if not type(name) in (list, tuple):
            name = [str(name)]
        if forceCache or self._forceCache:
            for _name in name:
                for _size in self.iconSizes:
                    if (QPixmapCache.find('$qt' + str(_name) + str(_size),
                                          self.pixmap)):
                        logging.debug('Icon %s returned from cache' % _name)
                        return self.pixmap

        logging.debug('Getting icon : %s size: %s' % (','.join(name), size))
        pix = self.findIcon(name, size)
        if pix.isNull():
            for _size in self.iconSizes:
                pix = self.findIcon(name, _size)
                if not pix.isNull():
                    if size == _size:
                        return pix
                    icon.addPixmap(pix)
            if icon.isNull():
                return self.pixmap
            return icon.pixmap(QSize(size, size))
        return pix
Пример #17
0
    def load(self, name, size = 128, forceCache = False):
        icon = QIcon()
        size = int(size)
        self.pixmap = QPixmap()
        if not type(name) in (list, tuple):
            name = [str(name)]
        if forceCache or self._forceCache:
            for _name in name:
                for _size in self.iconSizes:
                    if (QPixmapCache.find('$qt'+str(_name)+str(_size),
                        self.pixmap)):
                        logging.debug('Icon %s returned from cache' % _name)
                        return self.pixmap

        logging.debug('Getting icon : %s size: %s' % (','.join(name), size))
        pix = self.findIcon(name, size)
        if pix.isNull():
            for _size in self.iconSizes:
                pix = self.findIcon(name, _size)
                if not pix.isNull():
                    if size == _size:
                        return pix
                    icon.addPixmap(pix)
            if icon.isNull():
                return self.pixmap
            return icon.pixmap(QSize(size, size))
        return pix
Пример #18
0
    def __init__(self, thread):
        super(ThumbsItemModel,  self).__init__()
        self.__thread = thread
        self.currentNodeDir = None
        self.initSignals()
        self.pixmapCache = QPixmapCache()     
        self.pixmapCache.setCacheLimit(61440) 
	self.__thread.pixmapCache = self.pixmapCache
Пример #19
0
    def __init__(self, desktopFileName=None):
        if desktopFileName is None:
            desktopFileName = 'default'
        self.__svg = None
        self.__pmap = None
        QPixmapCache.setCacheLimit(20480) # the chinese landscape needs much
        self.defineCatalog()
        self.desktopFileName = desktopFileName
        self.path = locatebackground(desktopFileName + '.desktop')
        if self.path.isEmpty():
            self.path = locatebackground('default.desktop')
            if self.path.isEmpty():
                directories = '\n\n' +'\n'.join(str(x) for x in KGlobal.dirs().resourceDirs("kmahjonggbackground"))
                logException(BackgroundException(m18n( \
                'cannot find any background in the following directories, is libkmahjongg installed?') + directories))
            else:
                logWarning(m18n('cannot find background %1, using default', desktopFileName))
                self.desktopFileName = 'default'
        config, group = konfigGroup(self.path, "KMahjonggBackground")
        assert config
        self.name = group.readEntry("Name", "unknown background").toString() # Returns translated data

        #Version control
        backgroundversion, entryOK = group.readEntry("VersionFormat", QVariant(0)).toInt()
        #Format is increased when we have incompatible changes, meaning that
        # older clients are not able to use the remaining information safely
        if not entryOK or backgroundversion > BACKGROUNDVERSIONFORMAT:
            logException(BackgroundException('backgroundversion file / program: %d/%d' % \
                (backgroundversion, BACKGROUNDVERSIONFORMAT)))

        self.tiled = group.readEntry('Tiled') == '1'
        if self.tiled:
            self.imageWidth, entryOk = group.readEntry('Width').toInt()
            if not entryOk:
                raise Exception('cannot scan Width from background file')
            self.imageHeight, entryOk = group.readEntry('Height').toInt()
            if not entryOk:
                raise Exception('cannot scan Height from background file')
        self.isPlain = bool(group.readEntry('Plain'))
        if not self.isPlain:
            graphName = QString(group.readEntry("FileName"))
            self.__graphicspath = locatebackground(graphName)
            if self.__graphicspath.isEmpty():
                logException(BackgroundException(
                    'cannot find kmahjongglib/backgrounds/%s for %s' % \
                        (graphName, self.desktopFileName )))
Пример #20
0
    def menuGradient(cls, painter, spanRect, clipRect):
        if StyleHelper.usePixmapCache():
            key = "mh_menu {} {} {} {} {}".format(
                spanRect.width(), spanRect.height(), clipRect.width(),
                clipRect.height(), StyleHelper.baseColor().rgb())

            pixmap = QPixmap()
            if not QPixmapCache.find(key, pixmap):
                pixmap = QPixmap(clipRect.size())
                p = QPainter(pixmap)
                rect = QRect(0, 0, clipRect.width(), clipRect.height())
                cls._menuGradientHelper(p, spanRect, rect)
                p.end()
                QPixmapCache.insert(key, pixmap)

            painter.drawPixmap(clipRect.topLeft(), pixmap)
        else:
            cls._menuGradientHelper(painter, spanRect, clipRect)
Пример #21
0
    def verticalGradient(cls, painter: QPainter, spanRect: QRect, clipRect: QRect, lightColored=False):
        if StyleHelper.usePixmapCache():
            keyColor = cls.baseColor(lightColored)
            key = "mh_vertical {1} {2} {3} {4} {5}".format(
                spanRect.width(), spanRect.height(), clipRect.width(),
                clipRect.height(), keyColor.rgb())

            pixmap = QPixmap()
            if not QPixmapCache.find(key, pixmap):
                pixmap = QPixmap(clipRect.size())
                p = QPainter(pixmap)
                rect = QRect(0, 0, clipRect.width(), clipRect.height())
                StyleHelper._verticalGradientHelper(p, spanRect, rect, lightColored)
                p.end()
                QPixmapCache.insert(key, pixmap)

            painter.drawPixmap(clipRect.topLeft(), pixmap)
        else:
            StyleHelper._verticalGradientHelper(painter, spanRect, clipRect, lightColored)
Пример #22
0
 def __init__(self, imagePath, width=64, height=0, quality=0, Cache=True, keepRatio=True, magnify=False):
     """
     imagePath : chemin de l'image a charger
     size : taille de la préview a générer
     quality : qualité de la preview (0=mavaise, 10=très bonne)
     keepRation : garde-t-on les proportion de l'image
     magnify : agrandit-on l'image si la preview demandée est plus grande que l'image originale
     """
     self.preview = QPixmap()
     if width == 0:
         width = 64
     if height == 0:
         height = width
     self.size = QSize(width, height)
     self.quality = quality
     self.imageName = imagePath
     self.keepRatio = keepRatio
     self.magnify = magnify
     self.cache = Cache
     QPixmapCache.setCacheLimit(50*1024)
     self.update()
Пример #23
0
def pixmap_cache ( name ):
    """ Return the QPixmap corresponding to a filename.  If the filename does
        not contain a path component then the local 'images' directory is used.
    """
    if name[:1] == '@':
        image = image_for( name )
        if image is not None:
            return image.bitmap

    path, _ = split( name )
    if not path:
        name = join( dirname( __file__ ), 'images', name )

    pm = QPixmap()

    if not QPixmapCache.find( name, pm ):
        if not pm.load( name ) :
            print "WARNING: could not load pixmap file", name

        QPixmapCache.insert( name, pm )

    return pm
Пример #24
0
    def update(self):
        """ Fonction de mise à jour de la préview :
            * Si la taille de l'image est plus petite que la taille souhaité, on n'agrandi pas l'image, on prend la plus petite des deux
            * Le cache contient en index les images+size"""
        miniImg = QImage()
        image = QImageReader(self.imageName)
        self.origineSize = image.size()
        image.setQuality(self.quality)
        if not self.magnify :
            if ( ( self.size.width() + self.size.height() ) > (image.size().width() + image.size().height() ) ) :
                self.size = image.size()

        if self.keepRatio :
            image.setScaledSize(QSize(self.size.width(), image.size().height() * self.size.width() / image.size().width() ) )
        else :
            image.setScaledSize(self.size)

        if not QPixmapCache.find(self.imageName + str(self.size), self.preview) or not self.cache:
            image.read(miniImg)
            self.preview = self.preview.fromImage(miniImg)
            if self.cache :
                QPixmapCache.insert(self.imageName + str(self.size), self.preview)
Пример #25
0
 def __init__(self):
     QObject.__init__(self)
     self.pixmapCache = QPixmapCache()
     self.pixmapCache.setCacheLimit(61440)
     self.thread = QThread()
     self.scaler = Scaler()
     self.scaler.moveToThread(self.thread)
     self.connect(self.scaler, SIGNAL("scaledFinished"), self.finished)
     self.thread.start()
     self.thumbnailers = []
     self.handledRequest = set()
     self.corruptionHandler = CorruptedPictureHandler()
     self.pixmapCorrupted = QPixmap(":file_broken.png")
Пример #26
0
 def pixmap(self, size):
     """returns a background pixmap or None for isPlain"""
     self.__pmap = None
     if not self.isPlain:
         width = size.width()
         height = size.height()
         if self.tiled:
             width = self.imageWidth
             height = self.imageHeight
         cachekey = QString("%1W%2H%3") \
             .arg(self.name).arg(width).arg(height)
         self.__pmap = QPixmapCache.find(cachekey)
         if not self.__pmap:
             renderer = QSvgRenderer(self.__graphicspath)
             if not renderer.isValid():
                 logException(BackgroundException( \
                 m18n('file <filename>%1</filename> contains no valid SVG', self.__graphicspath)))
             self.__pmap = QPixmap(width, height)
             self.__pmap.fill(Qt.transparent)
             painter = QPainter(self.__pmap)
             renderer.render(painter)
             QPixmapCache.insert(cachekey, self.__pmap)
     return self.__pmap
Пример #27
0
 def pixmap(self, size):
     """returns a background pixmap or None for isPlain"""
     self.__pmap = None
     if not self.isPlain:
         width = size.width()
         height = size.height()
         if self.tiled:
             width = self.imageWidth
             height = self.imageHeight
         cachekey = QString("%1W%2H%3") \
             .arg(self.name).arg(width).arg(height)
         self.__pmap = QPixmapCache.find(cachekey)
         if not self.__pmap:
             renderer = QSvgRenderer(self.__graphicspath)
             if not renderer.isValid():
                 logException(BackgroundException( \
                 m18n('file <filename>%1</filename> contains no valid SVG', self.__graphicspath)))
             self.__pmap = QPixmap(width, height)
             self.__pmap.fill(Qt.transparent)
             painter = QPainter(self.__pmap)
             renderer.render(painter)
             QPixmapCache.insert(cachekey, self.__pmap)
     return self.__pmap
Пример #28
0
    def paintEvent(self, event):
        w = self.width()
        h = self.height()
        s = min(w, h)

        key = self._generateKey()
        pixmap = QPixmapCache.find(key)
        if not pixmap:
            pixmap = QPixmap(w, h)
            pixmap.fill(self, QPoint(0,
                                     0))  # Fill pixmap with widget background

            pixPainter = QPainter(pixmap)
            pixPainter.setRenderHint(QPainter.Antialiasing)

            # Offsets for centering
            ox = int(0.5 * (w - s))
            oy = int(0.5 * (h - s))

            insideColor = self._color
            if not self._value:
                insideColor = insideColor.darker(250)
            gradient = QRadialGradient(ox + 0.5 * s, oy + 0.5 * s, 0.5 * s)
            gradient.setColorAt(0.27, insideColor)
            gradient.setColorAt(0.6, insideColor.darker(120))
            gradient.setColorAt(1.0, insideColor.darker(160))
            pixPainter.setBrush(gradient)
            pixPainter.setPen(QPen(Qt.black, 2))
            pixPainter.drawEllipse(1 + ox, 1 + oy, s - 2, s - 2)
            pixPainter.end()
            QPixmapCache.insert(key, pixmap)

        p = QPainter()
        p.begin(self)
        p.drawPixmap(QPoint(0, 0), pixmap)
        p.end()
Пример #29
0
    def drawArrow(element, painter, option):
        """
        :type element: QStyle.PrimitiveElement
        :type painter: QPainter
        :type option: QStyleOption
        """
        # From windows style but modified to enable AA
        if option.rect.width() <= 1 or option.rect.height() <= 1:
            return

        r = option.rect
        size = min(r.height(), r.width())
        pixmap = QPixmap()
        pixmapName = "arrow-{}-{}-{}-{}-{}".format("$qt_ia",
                                                   int(option.state), element,
                                                   size, option.palette.cacheKey())
        if not QPixmapCache.find(pixmapName, pixmap):
            border = int(size / 5)
            sqsize = int(2 * (size / 2))
            image = QImage(sqsize, sqsize, QImage.Format_ARGB32)
            image.fill(Qt.transparent)
            imagePainter = QPainter(image)
            imagePainter.setRenderHint(QPainter.Antialiasing, True)
            imagePainter.translate(0.5, 0.5)
            a = QPolygon()
            if element == QStyle.PE_IndicatorArrowUp:
                a.setPoints(3, border, sqsize / 2, sqsize / 2, border, sqsize - border, sqsize / 2)
            elif element == QStyle.PE_IndicatorArrowDown:
                a.setPoints(3, border, sqsize / 2, sqsize / 2, sqsize - border, sqsize - border, sqsize / 2)
            elif element == QStyle.PE_IndicatorArrowRight:
                a.setPoints(3, sqsize - border, sqsize / 2, sqsize / 2, border, sqsize / 2, sqsize - border)
            elif element == QStyle.PE_IndicatorArrowLeft:
                a.setPoints(3, border, sqsize / 2, sqsize / 2, border, sqsize / 2, sqsize - border)

            bsx = 0
            bsy = 0

            if option.state & QStyle.State_Sunken:
                bsx = QApplication.style().pixelMetric(QStyle.PM_ButtonShiftHorizontal)
                bsy = QApplication.style().pixelMetric(QStyle.PM_ButtonShiftVertical)

            bounds = a.boundingRect()
            sx = int(sqsize / 2 - bounds.center().x() - 1)
            sy = int(sqsize / 2 - bounds.center().y() - 1)
            imagePainter.translate(sx + bsx, sy + bsy)

            if not (option.state & QStyle.State_Enabled):
                foreGround = QColor(150, 150, 150, 150)
                imagePainter.setBrush(option.palette.mid().color())
                imagePainter.setPen(option.palette.mid().color())
            else:
                shadow = QColor(0, 0, 0, 100)
                imagePainter.translate(0, 1)
                imagePainter.setPen(shadow)
                imagePainter.setBrush(shadow)
                foreGround = QColor(255, 255, 255, 210)
                imagePainter.drawPolygon(a)
                imagePainter.translate(0, -1)
                imagePainter.setPen(foreGround)
                imagePainter.setBrush(foreGround)
            imagePainter.drawPolygon(a)
            imagePainter.end()
            pixmap = QPixmap.fromImage(image)
            QPixmapCache.insert(pixmapName, pixmap)

        xOffset = int(r.x() + (r.width() - size) / 2)
        yOffset = int(r.y() + (r.height() - size) / 2)
        painter.drawPixmap(xOffset, yOffset, pixmap)
#               in the playlistwidget
#
#   \author     Dr. D Studios
#   \date       08/09/11
#

from PyQt4.QtCore import Qt

from PyQt4.QtGui import QPixmap, QPixmapCache

from ....delegates.griddelegate import GridDelegate
from ..... import settings
from ..... import resources

# up the cache limit since this is a graphics heavy app
QPixmapCache.setCacheLimit(10240 * 48)  # in kilobytes


class ThumbnailDelegate(GridDelegate):
    def drawOverlay(self, painter, option, index):
        """
                Paints the overlay color for this item if the current thumbnail
                based on whether or not it is the latest thumbnail available
                
                :param      painter:
                :type       <QPainter>:
                
                :param      option:
                :param      <QStyleOptionItem>:
                
                :param      index:
Пример #31
0
class ThumbsItemModel(QStandardItemModel):
    def __init__(self, thread):
        super(ThumbsItemModel,  self).__init__()
        self.__thread = thread
        self.currentNodeDir = None
        self.initSignals()
        self.pixmapCache = QPixmapCache()     
        self.pixmapCache.setCacheLimit(61440) 
	self.__thread.pixmapCache = self.pixmapCache
 
    def initSignals(self):
        self.connect(self.__thread, 
                     SIGNAL("addIcon"),
                     self.addIcon)
        self.connect(self.__thread, 
                     SIGNAL("addIconFromCache"),
                     self.addIconFromCache)
        self.connect(self.__thread, 
                     SIGNAL("addIconFromImage"),
                     self.addIconFromImage)
   
    def removeAll(self):
        if self.rowCount() > 0:
            for i in range(0,  self.rowCount()) :
                item = self.item(i)
                del item
            self.removeRows(0, self.rowCount())
        self.reset()
    

    def addIcon(self, node):
        item = NodeItem(node)
        if node.next.empty():
          icon = QIcon(":folder_empty_128.png")
        else:
          if node.attr.size != 0: 
   	    icon = QIcon(":folder_documents_128.png") 
          else:
	    icon = QIcon(":folder_128.png")
        item.setIcon(icon)
        item.setText(str(node.name))
        item.setEditable(False)
        items = []
        items.append(item)
        self.appendRow(items)
   
    def addIconFromCache(self, node):
        item = NodeItem(node)
	pixmap = self.pixmapCache.find(node.path + "/" + node.name)
        icon = QIcon(pixmap)
        item.setIcon(icon)
        item.setText(str(node.name))
        item.setEditable(False)
        items = []
        items.append(item)
        self.appendRow(items)

    def addIconFromImage(self, img, node):
        item = NodeItem(node)
        pixmap = QPixmap()
        pixmap = pixmap.fromImage(img)
        self.pixmapCache.insert(node.path + "/" + node.name, pixmap) 
        icon = QIcon(pixmap)
        item.setIcon(icon)
        item.setText(str(node.name))
        item.setEditable(False)
        items = []
        items.append(item)
        self.appendRow(items)
Пример #32
0
class ThumbsItemModel(QStandardItemModel):
    def __init__(self, thread):
        super(ThumbsItemModel, self).__init__()
        self.__thread = thread
        self.currentNodeDir = None
        self.initSignals()
        self.pixmapCache = QPixmapCache()
        self.pixmapCache.setCacheLimit(61440)
        self.__thread.pixmapCache = self.pixmapCache

    def initSignals(self):
        self.connect(self.__thread, SIGNAL("addIcon"), self.addIcon)
        self.connect(self.__thread, SIGNAL("addIconFromCache"),
                     self.addIconFromCache)
        self.connect(self.__thread, SIGNAL("addIconFromImage"),
                     self.addIconFromImage)

    def removeAll(self):
        if self.rowCount() > 0:
            for i in range(0, self.rowCount()):
                item = self.item(i)
                del item
            self.removeRows(0, self.rowCount())
        self.reset()

    def addIcon(self, node):
        item = NodeItem(node)
        if node.next.empty():
            icon = QIcon(":folder_empty_128.png")
        else:
            if node.attr.size != 0:
                icon = QIcon(":folder_documents_128.png")
            else:
                icon = QIcon(":folder_128.png")
        item.setIcon(icon)
        item.setText(str(node.name))
        item.setEditable(False)
        items = []
        items.append(item)
        self.appendRow(items)

    def addIconFromCache(self, node):
        item = NodeItem(node)
        pixmap = self.pixmapCache.find(node.path + "/" + node.name)
        icon = QIcon(pixmap)
        item.setIcon(icon)
        item.setText(str(node.name))
        item.setEditable(False)
        items = []
        items.append(item)
        self.appendRow(items)

    def addIconFromImage(self, img, node):
        item = NodeItem(node)
        pixmap = QPixmap()
        pixmap = pixmap.fromImage(img)
        self.pixmapCache.insert(node.path + "/" + node.name, pixmap)
        icon = QIcon(pixmap)
        item.setIcon(icon)
        item.setText(str(node.name))
        item.setEditable(False)
        items = []
        items.append(item)
        self.appendRow(items)
Пример #33
0
#
#   \author     Dr. D Studios
#   \date       08/09/11
#

from PyQt4.QtCore import Qt

from PyQt4.QtGui                import  QPixmap,\
                                        QPixmapCache

from ....delegates.griddelegate import GridDelegate
from ..... import settings
from ..... import resources

# up the cache limit since this is a graphics heavy app
QPixmapCache.setCacheLimit(10240 * 48)  # in kilobytes


class ThumbnailDelegate(GridDelegate):
    def drawOverlay(self, painter, option, index):
        """
                Paints the overlay color for this item if the current thumbnail
                based on whether or not it is the latest thumbnail available
                
                :param      painter:
                :type       <QPainter>:
                
                :param      option:
                :param      <QStyleOptionItem>:
                
                :param      index:
Пример #34
0
    def drawIconWithShadow(cls, icon, rect, painter, iconMode,
                           dipRadius=3, color=QColor(0, 0, 0, 130),
                           dipOffset=QPoint(1, -2)):
        """
        :type icon: QIcon
        :type rect: QRect
        :type painter: QPainter
        :type iconMode:  QIcon.Mode
        :type dipRadius: int
        :type color: QColor
        :type dipOffset: QPoint
        """
        cache = QPixmap()
        pixmapName = "icon {0} {1} {2}".format(icon.cacheKey(), iconMode, rect.height())

        if not QPixmapCache.find(pixmapName, cache):
            # High-dpi support: The in parameters (rect, radius, offset) are in
            # device-independent pixels. The call to QIcon.pixmap() below might
            # return a high-dpi pixmap, which will in that case have a devicePixelRatio
            # different than 1. The shadow drawing calculations are done in device
            # pixels.
            from math import ceil

            px = icon.pixmap(rect.size())
            devicePixelRatio = int(ceil(cls.pixmapDevicePixelRatio(px)))
            radius = dipRadius * devicePixelRatio
            offset = dipOffset * devicePixelRatio # result = QPoint, like dipOffset
            cache = QPixmap(px.size() + QSize(radius * 2, radius * 2))
            cache.fill(Qt.transparent)

            cachePainter = QPainter(cache)
            if iconMode == QIcon.Disabled:
                im = px.toImage().convertToFormat(QImage.Format_ARGB32)
                for y in range(0, im.height()):
                    scanLine = abs(im.scanLine(y))
                    for x in range(0, im.width()):
                        pixel = scanLine
                        intensity = qGray(pixel)
                        scanLine = qRgba(intensity, intensity, intensity, qAlpha(pixel))
                        scanLine += 1

                px = QPixmap.fromImage(im)

            # Draw shadow
            tmp = QImage(px.size() + QSize(radius * 2, radius * 2 + 1), QImage.Format_ARGB32_Premultiplied)
            tmp.fill(Qt.transparent)

            tmpPainter = QPainter(tmp)
            tmpPainter.setCompositionMode(QPainter.CompositionMode_Source)
            tmpPainter.drawPixmap(QRect(radius, radius, px.width(), px.height()), px)
            tmpPainter.end()

            # blur the alpha channel
            blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied)
            blurred.fill(Qt.transparent)
            blurPainter = QPainter(blurred)
            # qt_blurImage is not available in PyQt4, skip it
            # qt_blurImage(&blurPainter, tmp, radius, false, true)
            blurPainter.end()

            tmp = blurred

            # blacken the image...
            tmpPainter.begin(tmp)
            tmpPainter.setCompositionMode(QPainter.CompositionMode_SourceIn)
            tmpPainter.fillRect(tmp.rect(), color)
            tmpPainter.end()

            tmpPainter.begin(tmp)
            tmpPainter.setCompositionMode(QPainter.CompositionMode_SourceIn)
            tmpPainter.fillRect(tmp.rect(), color)
            tmpPainter.end()

            # draw the blurred drop shadow...
            cachePainter.drawImage(QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp)

            # Draw the actual pixmap...
            cachePainter.drawPixmap(QRect(QPoint(radius, radius) + offset, QSize(px.width(), px.height())), px)
            import PyQt4

            if StrictVersion(PyQt4.QtCore.__version__).version[0] == 5:
                cache.setDevicePixelRatio(devicePixelRatio)
            QPixmapCache.insert(pixmapName, cache)

        targetRect = cache.rect()
        targetRect.setSize(targetRect.size() / cls.pixmapDevicePixelRatio(cache))
        targetRect.moveCenter(rect.center() - dipOffset)
        painter.drawPixmap(targetRect, cache)
Пример #35
0
import re

from api.types.libtypes import Variant, vtime
from api.vfs.libvfs import VFS
from api.events.libevents import EventHandler

from Queue import *

HNAME = 0
HSIZE = 1
HMODULE = 2
HCHANGED = 3
HMODIFIED = 4
HACCESSED = 5

pixmapCache = QPixmapCache()
pixmapCache.setCacheLimit(61440)

class ImageThumb():
  def __init__(self):
    pass

  def getImage(self, type, node, index):
    buff = ""
    tags = None
    img = QImage()
    if type.find('jpeg') != -1:
      try:
        buff = self.getThumb(node)
        load = img.loadFromData(buff, type)
	if load == False: