예제 #1
0
 def defineCatalog():
     """whatever this does"""
     if not Tileset.catalogDefined:
         KGlobal.dirs().addResourceType("kmahjonggtileset",
             "data", QString.fromLatin1("kmahjongglib/tilesets"))
         KGlobal.locale().insertCatalog("libkmahjongglib")
         Tileset.catalogDefined = True
예제 #2
0
 def defineCatalog():
     """whatever this does"""
     if not Background.catalogDefined:
         KGlobal.dirs().addResourceType("kmahjonggbackground",
             "data", QString.fromLatin1("kmahjongglib/backgrounds"))
         KGlobal.locale().insertCatalog("libkmahjongglib")
         Background.catalogDefined = True
예제 #3
0
 def defineCatalog():
     """whatever this does"""
     if not Background.catalogDefined:
         KGlobal.dirs().addResourceType(
             "kmahjonggbackground", "data",
             QString.fromLatin1("kmahjongglib/backgrounds"))
         KGlobal.locale().insertCatalog("libkmahjongglib")
         Background.catalogDefined = True
예제 #4
0
파일: util.py 프로젝트: ospalh/kajongg-fork
def appdataDir():
    """the per user directory with kajongg application information like the database"""
    if Internal.isServer:
        # the server might or might not have KDE installed, so to be on
        # the safe side we use our own .kajonggserver directory
        # the following code moves an existing kajonggserver.db to .kajonggserver
        # but only if .kajonggserver does not yet exist
        kdehome = os.environ.get('KDEHOME', '~/.kde')
        oldPath = os.path.expanduser(kdehome + '/share/apps/kajongg/kajonggserver.db')
        if not os.path.exists(oldPath):
            oldPath = os.path.expanduser('~/.kde4/share/apps/kajongg/kajonggserver.db')
        newPath = os.path.expanduser('~/.kajonggserver/')
        if os.path.exists(oldPath) and not os.path.exists(newPath):
            # upgrading an old kajonggserver installation
            os.makedirs(newPath)
            shutil.move(oldPath, newPath)
            logInfo('moved %s to %s' % (oldPath,  newPath))
        if not os.path.exists(newPath):
            try:
                os.makedirs(newPath)
            except OSError:
                pass
        return newPath
    else:
        result = os.path.dirname(unicode(KGlobal.dirs().locateLocal("appdata", ""))) + '/'
        return result
예제 #5
0
def appdataDir():
    """the per user directory with kajongg application information like the database"""
    if Internal.isServer:
        # the server might or might not have KDE installed, so to be on
        # the safe side we use our own .kajonggserver directory
        # the following code moves an existing kajonggserver.db to .kajonggserver
        # but only if .kajonggserver does not yet exist
        kdehome = os.environ.get('KDEHOME', '~/.kde')
        oldPath = os.path.expanduser(kdehome +
                                     '/share/apps/kajongg/kajonggserver.db')
        if not os.path.exists(oldPath):
            oldPath = os.path.expanduser(
                '~/.kde4/share/apps/kajongg/kajonggserver.db')
        newPath = os.path.expanduser('~/.kajonggserver/')
        if os.path.exists(oldPath) and not os.path.exists(newPath):
            # upgrading an old kajonggserver installation
            os.makedirs(newPath)
            shutil.move(oldPath, newPath)
            logInfo('moved %s to %s' % (oldPath, newPath))
        if not os.path.exists(newPath):
            try:
                os.makedirs(newPath)
            except OSError:
                pass
        return newPath
    else:
        result = os.path.dirname(
            unicode(KGlobal.dirs().locateLocal("appdata", ""))) + '/'
        return result
예제 #6
0
 def availableVoices():
     """a list of all voice directories"""
     if not Voice.__availableVoices and Internal.haveKDE:
         result = []
         for parentDirectory in KGlobal.dirs().findDirs("appdata", "voices"):
             parentDirectory = unicode(parentDirectory)
             for (dirpath, _, _) in os.walk(parentDirectory, followlinks=True):
                 if os.path.exists(os.path.join(dirpath, 's1.ogg')):
                     result.append(Voice(dirpath))
         config = KGlobal.config()
         group = KConfigGroup(config, 'Locale')
         prefLanguages = uniqueList(':'.join(['local', str(group.readEntry('Language')), 'en_uS']).split(':'))
         prefLanguages = dict((x[1], x[0]) for x in enumerate(prefLanguages))
         result = sorted(result, key=lambda x: prefLanguages.get(x.language(), 9999))
         if Debug.sound:
             logDebug('found voices:%s' % [str(x) for x in result])
         Voice.__availableVoices = result
     return Voice.__availableVoices
예제 #7
0
파일: tileset.py 프로젝트: KDE/kajongg
 def __noTilesetFound():
     """No tilesets found"""
     directories = '\n'.join(
         str(x) for x in KGlobal.dirs().resourceDirs("kmahjonggtileset"))
     directories = '\n\n' + directories
     logException(
         TileException(m18n(
             'cannot find any tileset in the following directories, '
             'is libkmahjongg installed?') + directories))
예제 #8
0
    def __init__(self, desktopFileName=None):
        if desktopFileName is None:
            desktopFileName = 'default'
        self.tileSize = None
        self.faceSize = None
        self.__renderer = None
        self.__shadowOffsets = None
        self.defineCatalog()
        self.path = locateTileset(desktopFileName + '.desktop')
        if self.path.isEmpty():
            self.path = locateTileset('default.desktop')
            if self.path.isEmpty():
                directories = '\n\n' +'\n'.join(str(x) for x in KGlobal.dirs().resourceDirs("kmahjonggtileset"))
                logException(TileException(m18n( \
                'cannot find any tileset in the following directories, is libkmahjongg installed?') + directories))
            else:
                logWarning(m18n('cannot find tileset %1, using default', desktopFileName))
                self.desktopFileName = 'default'
        else:
            self.desktopFileName = desktopFileName
        self.darkenerAlpha = 120 if self.desktopFileName == 'jade' else 50
        tileconfig = KConfig(self.path, KConfig.SimpleConfig)
        group = KConfigGroup(tileconfig.group("KMahjonggTileset"))

        self.name = group.readEntry("Name", "unknown tileset").toString() # Returns translated data
        self.author = group.readEntry("Author", "unknown author").toString()
        self.description = group.readEntry("Description", "no description available").toString()
        self.authorEmail = group.readEntry("AuthorEmail", "no E-Mail address available").toString()

        #Version control
        tileversion, 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 tileversion > TILESETVERSIONFORMAT:
            logException(TileException('tileversion file / program: %d/%d' % \
                (tileversion, TILESETVERSIONFORMAT)))

        graphName = QString(group.readEntry("FileName"))
        self.__graphicspath = locateTileset(graphName)
        if self.__graphicspath.isEmpty():
            logException(TileException('cannot find kmahjongglib/tilesets/%s for %s' % \
                        (graphName, self.desktopFileName )))
        self.renderer() # now that we get the sizes from the svg, we need the renderer right away

        self.svgName = { 'wn': 'WIND_1', 'ws': 'WIND_2', 'we': 'WIND_3', 'ww': 'WIND_4',
            'db': 'DRAGON_1', 'dg': 'DRAGON_2', 'dr': 'DRAGON_3'}
        for value in '123456789':
            self.svgName['s%s' % value] = 'ROD_%s' % value
            self.svgName['b%s' % value] = 'BAMBOO_%s' % value
            self.svgName['c%s' % value] = 'CHARACTER_%s' % value
        for idx, wind in enumerate('eswn'):
            self.svgName['f%s' % wind] = 'FLOWER_%d' % (idx + 1)
            self.svgName['y%s' % wind] = 'SEASON_%d' % (idx + 1)
예제 #9
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 )))
예제 #10
0
파일: background.py 프로젝트: KDE/kajongg
    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)))
예제 #11
0
파일: util.py 프로젝트: ospalh/kajongg-fork
def cacheDir():
    """the cache directory for this user"""
    if Internal.isServer:
        result = os.path.join(appdataDir(), 'cache')
    else:
        result = os.path.dirname(unicode(KGlobal.dirs().locateLocal("cache", "")))
        result = os.path.join(result, 'kajongg')
    if not os.path.exists(result):
        try:
            os.makedirs(result)
        except OSError:
            pass
    return result
예제 #12
0
def cacheDir():
    """the cache directory for this user"""
    if Internal.isServer:
        result = os.path.join(appdataDir(), 'cache')
    else:
        result = os.path.dirname(
            unicode(KGlobal.dirs().locateLocal("cache", "")))
        result = os.path.join(result, 'kajongg')
    if not os.path.exists(result):
        try:
            os.makedirs(result)
        except OSError:
            pass
    return result
예제 #13
0
 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 = 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(backgrounds-set(['default']))
         backgrounds = sortedBackgrounds
     return [Background(x) for x in backgrounds]
예제 #14
0
 def availableVoices():
     """a list of all voice directories"""
     if not Voice.__availableVoices and Internal.haveKDE:
         result = []
         for parentDirectory in KGlobal.dirs().findDirs(
                 "appdata", "voices"):
             parentDirectory = unicode(parentDirectory)
             for (dirpath, _, _) in os.walk(parentDirectory,
                                            followlinks=True):
                 if os.path.exists(os.path.join(dirpath, 's1.ogg')):
                     result.append(Voice(dirpath))
         config = KGlobal.config()
         group = KConfigGroup(config, 'Locale')
         prefLanguages = uniqueList(':'.join(
             ['local', str(group.readEntry('Language')),
              'en_uS']).split(':'))
         prefLanguages = dict(
             (x[1], x[0]) for x in enumerate(prefLanguages))
         result = sorted(
             result, key=lambda x: prefLanguages.get(x.language(), 9999))
         if Debug.sound:
             logDebug('found voices:%s' % [str(x) for x in result])
         Voice.__availableVoices = result
     return Voice.__availableVoices
예제 #15
0
 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 = 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(backgrounds - set(['default']))
         backgrounds = sortedBackgrounds
     return [Background(x) for x in backgrounds]
예제 #16
0
 def tilesAvailable():
     """returns all available tile sets"""
     Tileset.defineCatalog()
     tilesAvailableQ = KGlobal.dirs().findAllResources(
         "kmahjonggtileset", "*.desktop", KStandardDirs.Recursive)
     # now we have a list of full paths. Use the base name minus .desktop
     # put result into a set, avoiding duplicates
     tilesets = set(str(x).rsplit('/')[-1].split('.')[0] for x in tilesAvailableQ)
     if 'default' in tilesets:
         # we want default to be first in list
         sortedTilesets = ['default']
         sortedTilesets.extend(tilesets-set(['default']))
         tilesets = sortedTilesets
     for dontWant in ['alphabet', 'egypt']:
         if dontWant in tilesets:
             tilesets.remove(dontWant)
     return [Tileset(x) for x in tilesets]
예제 #17
0
파일: kajongg.py 프로젝트: KDE/kajongg
        EventData(receiver, event)
        return QObject.eventFilter(self, receiver, event)


from util import gitHead

ABOUT = About()
KCmdLineArgs.init(sys.argv, ABOUT.about)
KCmdLineArgs.addCmdLineOptions(defineOptions())
if usingQt4:
    KApplication.setGraphicsSystem("raster")
APP = KApplication()
parseOptions()

if Debug.neutral:
    KGlobal.locale().setLanguage("en_US")

if Debug.events:
    EVHANDLER = EvHandler()
    APP.installEventFilter(EVHANDLER)

from config import SetupPreferences

SetupPreferences()

if Options.csv:
    if gitHead() == "current":
        Internal.logger.debug("You cannot write to %s with changes uncommitted to git", Options.csv)
        sys.exit(2)
from mainwindow import MainWindow