def main():
    if not os.path.exists(os.path.expanduser("~/.pyqlogger")):
        os.mkdir(os.path.expanduser("~/.pyqlogger"))    
    settings = Settings.Settings.load()
    UI.prepareModule(settings)
    app =  UI.API.KQApplication(sys.argv, None)
    stat = UI.API.prepareCommandLine()    
    pic = QPixmap ( 150, 50)
    pic.fill()
    loginsplash = QSplashScreen( pic )
    pixmap = QPixmap( "splash.png" )
    splash = QSplashScreen( pixmap )
    splash.show()
    splash.message( "Loading forms...",alignflag )
    qApp.processEvents()
    load_forms(splash,app,settings)
    splash.message( "Loading plugins...",alignflag )
    qApp.processEvents()
    manager = Manager.load(__FORMS__["Main"]["Impl"])
    del splash
    acc = None
    pwd = None
    if settings.AutoLogin: # check if we have auto login info
        acc = settings.accountByName(settings.AutoLogin)
        pwd = acc.Password

    while True:
        if not acc:
            wnd = __FORMS__["Login"]
            if wnd["Impl"].init(settings,__FORMS__,manager):
                if wnd["Class"].exec_loop() == QDialog.Accepted:
                    acc = wnd["Impl"].acc
                    pwd = str(wnd["Impl"].edtPassword.text())
        if not acc or not pwd:
            break
        else:
            (acc.Password,oldpwd) = (pwd,acc.Password)            
            acc.init()
            loginsplash.show()
            loginsplash.message( "Logging in...",Qt.AlignCenter)            
            logres = acc.login()
            loginsplash.hide()
            acc.Password = oldpwd
            if not logres:
                QMessageBox.warning(None,"Failed!","""Cannot login!""")
                acc = None
            else:
                wnd = __FORMS__["Main"]
                acc.init()
                wnd["Impl"].init(settings,__FORMS__, acc, pwd,\
                                 manager)
                app.setMainWidget(wnd["Class"])
                wnd["Class"].show()
                #splash.finish(wnd["Class"])
                app.exec_loop()
                if wnd["Impl"].reload:
                    acc = None
                else:
                    break
def main():
    if not os.path.exists(os.path.expanduser("~/.pyqlogger")):
        os.mkdir(os.path.expanduser("~/.pyqlogger"))
    settings = Settings.Settings.load()
    UI.prepareModule(settings)
    app = UI.API.KQApplication(sys.argv, None)
    stat = UI.API.prepareCommandLine()
    pic = QPixmap(150, 50)
    pic.fill()
    loginsplash = QSplashScreen(pic)
    pixmap = QPixmap("splash.png")
    splash = QSplashScreen(pixmap)
    splash.show()
    splash.message("Loading forms...", alignflag)
    qApp.processEvents()
    load_forms(splash, app, settings)
    splash.message("Loading plugins...", alignflag)
    qApp.processEvents()
    manager = Manager.load(__FORMS__["Main"]["Impl"])
    del splash
    acc = None
    pwd = None
    if settings.AutoLogin:  # check if we have auto login info
        acc = settings.accountByName(settings.AutoLogin)
        pwd = acc.Password

    while True:
        if not acc:
            wnd = __FORMS__["Login"]
            if wnd["Impl"].init(settings, __FORMS__, manager):
                if wnd["Class"].exec_loop() == QDialog.Accepted:
                    acc = wnd["Impl"].acc
                    pwd = str(wnd["Impl"].edtPassword.text())
        if not acc or not pwd:
            break
        else:
            (acc.Password, oldpwd) = (pwd, acc.Password)
            acc.init()
            loginsplash.show()
            loginsplash.message("Logging in...", Qt.AlignCenter)
            logres = acc.login()
            loginsplash.hide()
            acc.Password = oldpwd
            if not logres:
                QMessageBox.warning(None, "Failed!", """Cannot login!""")
                acc = None
            else:
                wnd = __FORMS__["Main"]
                acc.init()
                wnd["Impl"].init(settings,__FORMS__, acc, pwd,\
                                 manager)
                app.setMainWidget(wnd["Class"])
                wnd["Class"].show()
                #splash.finish(wnd["Class"])
                app.exec_loop()
                if wnd["Impl"].reload:
                    acc = None
                else:
                    break
Example #3
0
 def genWindPixmap(self):
     """prepare wind tiles"""
     pwind = PlayerWind(self.__wind)
     pwind.prevailing = self.__wind == Wind.all4[min(self.__roundsFinished, 3)]
     pMap = QPixmap(40, 40)
     pMap.fill(Qt.transparent)
     painter = QPainter(pMap)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.scale(0.40, 0.40)
     pwind.paint(painter, QStyleOptionGraphicsItem())
     for child in pwind.childItems():
         if isinstance(child, QGraphicsSvgItem):
             with Painter(painter):
                 painter.translate(child.mapToParent(0.0, 0.0))
                 child.paint(painter, QStyleOptionGraphicsItem())
     return pMap
Example #4
0
File: board.py Project: KDE/kajongg
 def genWINDPIXMAPS():
     """prepare wind tiles"""
     tileset = Tileset(Internal.Preferences.windTilesetName)
     for wind in Wind.all4:
         for prevailing in False, True:
             pwind = PlayerWind(wind, tileset, prevailing)
             pMap = QPixmap(40, 40)
             pMap.fill(Qt.transparent)
             painter = QPainter(pMap)
             painter.setRenderHint(QPainter.Antialiasing)
             painter.scale(0.40, 0.40)
             pwind.paint(painter, QStyleOptionGraphicsItem())
             for child in pwind.childItems():
                 if isinstance(child, QGraphicsSvgItem):
                     with Painter(painter):
                         painter.translate(child.mapToParent(0.0, 0.0))
                         child.paint(painter, QStyleOptionGraphicsItem())
             WINDPIXMAPS[(wind, prevailing)] = pMap
Example #5
0
 def __fillLastMeldComboWith(self, winnerMelds, indexedMeld, lastTile):
     """fill last meld combo with prepared content"""
     winner = self.game.winner
     faceWidth = winner.handBoard.tileset.faceSize.width() * 0.5
     faceHeight = winner.handBoard.tileset.faceSize.height() * 0.5
     restoredIdx = None
     for meld in winnerMelds:
         pixMap = QPixmap(faceWidth * len(meld), faceHeight)
         pixMap.fill(Qt.transparent)
         self.__meldPixMaps.append(pixMap)
         painter = QPainter(pixMap)
         for element in meld:
             painter.drawPixmap(
                 0,
                 0,
                 winner.handBoard.tilesByElement(element)[0].pixmapFromSvg(
                     QSize(faceWidth, faceHeight), withBorders=False
                 ),
             )
             painter.translate(QPointF(faceWidth, 0.0))
         self.cbLastMeld.addItem(QIcon(pixMap), "", toQVariant(str(meld)))
         if indexedMeld == str(meld):
             restoredIdx = self.cbLastMeld.count() - 1
     if not restoredIdx and indexedMeld:
         # try again, maybe the meld changed between concealed and exposed
         indexedMeld = indexedMeld.lower()
         for idx in range(self.cbLastMeld.count()):
             meldContent = str(variantValue(self.cbLastMeld.itemData(idx)))
             if indexedMeld == meldContent.lower():
                 restoredIdx = idx
                 if lastTile not in meldContent:
                     lastTile = lastTile.swapped
                     assert lastTile in meldContent
                     with BlockSignals(self.cbLastTile):  # we want to continue right here
                         idx = self.cbLastTile.findData(toQVariant(lastTile))
                         self.cbLastTile.setCurrentIndex(idx)
                 break
     if not restoredIdx:
         restoredIdx = 0
     self.cbLastMeld.setCurrentIndex(restoredIdx)
     self.cbLastMeld.setIconSize(QSize(faceWidth * 3, faceHeight))
Example #6
0
 def pixmapFromSvg(self, pmapSize=None, withBorders=None):
     """returns a pixmap with default size as given in SVG
     and optional borders/shadows"""
     if withBorders is None:
         withBorders = Internal.Preferences.showShadows
     if withBorders:
         wantSize = self.tileset.tileSize.toSize()
     else:
         wantSize = self.tileset.faceSize.toSize()
     if not pmapSize:
         pmapSize = wantSize
     result = QPixmap(pmapSize)
     result.fill(Qt.transparent)
     painter = QPainter(result)
     if not painter.isActive():
         logException(
             'painter is not active. Wanted size: %s' %
             str(pmapSize))
     try:
         xScale = float(pmapSize.width()) / wantSize.width()
         yScale = float(pmapSize.height()) / wantSize.height()
     except ZeroDivisionError:
         xScale = 1
         yScale = 1
     if not withBorders:
         painter.scale(*self.tileset.tileFaceRelation())
         painter.translate(-self.facePos())
     renderer = self.tileset.renderer()
     renderer.render(painter, self.__elementId())
     painter.resetTransform()
     self._drawDarkness(painter)
     if self.showFace():
         faceSize = self.tileset.faceSize.toSize()
         faceSize = QSize(
             faceSize.width() * xScale,
             faceSize.height() * yScale)
         painter.translate(self.facePos())
         renderer.render(painter, self.tileset.svgName[self.tile.exposed],
                         QRectF(QPointF(), QSizeF(faceSize)))
     return result
Example #7
0
 def pixmapFromSvg(self, pmapSize=None, withBorders=None):
     """returns a pixmap with default size as given in SVG
     and optional borders/shadows"""
     if withBorders is None:
         withBorders = Internal.Preferences.showShadows
     if withBorders:
         wantSize = self.tileset.tileSize.toSize()
     else:
         wantSize = self.tileset.faceSize.toSize()
     if not pmapSize:
         pmapSize = wantSize
     result = QPixmap(pmapSize)
     result.fill(Qt.transparent)
     painter = QPainter(result)
     if not painter.isActive():
         logException(
             'painter is not active. Wanted size: %s' %
             str(pmapSize))
     try:
         xScale = float(pmapSize.width()) / wantSize.width()
         yScale = float(pmapSize.height()) / wantSize.height()
     except ZeroDivisionError:
         xScale = 1
         yScale = 1
     if not withBorders:
         painter.scale(*self.tileset.tileFaceRelation())
         painter.translate(-self.facePos())
     renderer = self.tileset.renderer()
     renderer.render(painter, self.__elementId())
     painter.resetTransform()
     self._drawDarkness(painter)
     if self.showFace():
         faceSize = self.tileset.faceSize.toSize()
         faceSize = QSize(
             faceSize.width() * xScale,
             faceSize.height() * yScale)
         painter.translate(self.facePos())
         renderer.render(painter, self.tileset.svgName[self.tile.exposed],
                         QRectF(QPointF(), QSizeF(faceSize)))
     return result
Example #8
0
 def __fillLastMeldComboWith(self, winnerMelds, indexedMeld, lastTile):
     """fill last meld combo with prepared content"""
     winner = self.game.winner
     faceWidth = winner.handBoard.tileset.faceSize.width() * 0.5
     faceHeight = winner.handBoard.tileset.faceSize.height() * 0.5
     restoredIdx = None
     for meld in winnerMelds:
         pixMap = QPixmap(faceWidth * len(meld), faceHeight)
         pixMap.fill(Qt.transparent)
         self.__meldPixMaps.append(pixMap)
         painter = QPainter(pixMap)
         for element in meld:
             painter.drawPixmap(
                 0, 0,
                 winner.handBoard.tilesByElement(element)[0].pixmapFromSvg(
                     QSize(faceWidth, faceHeight), withBorders=False))
             painter.translate(QPointF(faceWidth, 0.0))
         self.cbLastMeld.addItem(QIcon(pixMap), '', str(meld))
         if indexedMeld == str(meld):
             restoredIdx = self.cbLastMeld.count() - 1
     if not restoredIdx and indexedMeld:
         # try again, maybe the meld changed between concealed and exposed
         indexedMeld = indexedMeld.lower()
         for idx in range(self.cbLastMeld.count()):
             meldContent = str(self.cbLastMeld.itemData(idx))
             if indexedMeld == meldContent.lower():
                 restoredIdx = idx
                 if lastTile not in meldContent:
                     lastTile = lastTile.swapped
                     assert lastTile in meldContent
                     with BlockSignals(self.cbLastTile
                                       ):  # we want to continue right here
                         idx = self.cbLastTile.findData(lastTile)
                         self.cbLastTile.setCurrentIndex(idx)
                 break
     if not restoredIdx:
         restoredIdx = 0
     self.cbLastMeld.setCurrentIndex(restoredIdx)
     self.cbLastMeld.setIconSize(QSize(faceWidth * 3, faceHeight))
Example #9
0
class Background(Resource):
    """represents a background"""

    resourceName = 'background'
    configGroupName = 'KMahjonggBackground'
    cache = {}

    def __init__(self, name):
        """continue __build"""
        super(Background, self).__init__(name)
        self.__svg = None
        self.__pmap = None
        self.graphicsPath = None
        QPixmapCache.setCacheLimit(20480)  # the chinese landscape needs much

        self.tiled = self.group.readEntry('Tiled') == '1'
        if self.tiled:
            try:
                self.imageWidth = self.group.readInteger('Width')
                self.imageHeight = self.group.readInteger('Height')
            except Exception as exc:
                logException(
                    exc)  # TODO: simplify if we switch to twisted logger
                raise
        self.isPlain = bool(self.group.readEntry('Plain'))
        if not self.isPlain:
            graphName = self.group.readEntry("FileName")
            self.graphicsPath = self.locate(graphName)
            if not self.graphicsPath:
                logException('cannot find kmahjongglib/backgrounds/%s for %s' %
                             (graphName, self.desktopFileName))

    def pixmap(self, size):
        """returns a background pixmap or None for isPlain"""
        self.__pmap = QBrush()
        if not self.isPlain:
            width = size.width()
            height = size.height()
            if self.tiled:
                width = self.imageWidth
                height = self.imageHeight
            cachekey = '{name}W{width}H{height}'.format(name=self.name,
                                                        width=width,
                                                        height=height)
            self.__pmap = QPixmapCache.find(cachekey)
            if not self.__pmap:
                renderer = QSvgRenderer(self.graphicsPath)
                if not renderer.isValid():
                    logException(
                        i18n(
                            '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

    def brush(self, size):
        """background brush"""
        return QBrush(self.pixmap(size))

    def setPalette(self, onto):
        """sets a background palette for widget onto"""
        palette = QPalette()
        mybrush = self.brush(onto.size())
        palette.setBrush(QPalette.Window, mybrush)
        onto.setPalette(palette)
Example #10
0
class Background(object):

    """represents a background"""
    catalogDefined = False

    @staticmethod
    def defineCatalog():
        """whatever this does"""
        if not Background.catalogDefined:
            KGlobal.dirs().addResourceType("kmahjonggbackground",
                                           "data", QString("kmahjongglib/backgrounds"))
            KGlobal.locale().insertCatalog("libkmahjongglib")
            Background.catalogDefined = True

    @staticmethod
    def backgroundsAvailable():
        """returns all available backgrounds"""
        Background.defineCatalog()
        backgroundsAvailableQ = KGlobal.dirs().findAllResources(
            "kmahjonggbackground", "*.desktop", KStandardDirs.Recursive)
        # now we have a list of full paths. Use the base name minus .desktop:
        # put the result into a set, avoiding duplicates
        backgrounds = list(set(str(x).rsplit('/')[-1].split('.')[0]
                               for x in backgroundsAvailableQ))
        if 'default' in backgrounds:
            # we want default to be first in list
            sortedBackgrounds = ['default']
            sortedBackgrounds.extend(set(backgrounds) - set(['default']))
            backgrounds = sortedBackgrounds
        return [Background(x) for x in backgrounds]

    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 = KConfig(self.path)
        group = config.group("KMahjonggBackground")
        self.name = group.readEntry("Name") or m18n("unknown background")

        # Version control
        backgroundversion = int(group.readEntry("VersionFormat")) or 0
        # Format is increased when we have incompatible changes, meaning that
        # older clients are not able to use the remaining information safely
        if 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)))

    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(u'{name}W{width}H{height}'.format(
                name=self.name, width=width, height=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

    def brush(self, size):
        """background brush"""
        return QBrush(self.pixmap(size))

    def setPalette(self, onto):
        """sets a background palette for widget onto"""
        palette = QPalette()
        mybrush = self.brush(onto.size())
        palette.setBrush(QPalette.Window, mybrush)
        onto.setPalette(palette)