Example #1
0
File: game.py Project: KDE/kajongg
    def debug(self, msg, btIndent=None, prevHandId=False):
        """
        Log a debug message.

        @param msg: The message.
        @type msg: A string.
        @param btIndent: If given, message is indented by
        depth(backtrace)-btIndent
        @type btIndent: C{int}
        @param prevHandId: If True, do not use current handId but previous
        @type prevHandId: C{bool}
        """
        if self.belongsToRobotPlayer():
            prefix = u'R'
        elif self.belongsToHumanPlayer():
            prefix = u'C'
        elif self.belongsToGameServer():
            prefix = u'S'
        else:
            logDebug(msg, btIndent=btIndent)
            return
        handId = self._prevHandId if prevHandId else self.handId
        handId = unicodeString(handId.prompt(withMoveCount=True))
        logDebug(
            u'%s%s: %s' % (prefix, handId, unicodeString(msg)),
            withGamePrefix=False,
            btIndent=btIndent)
Example #2
0
File: rule.py Project: KDE/kajongg
 def createRule(self, name, definition='', **kwargs):
     """shortcut for simpler definition of predefined rulesets"""
     name = unicodeString(name)
     definition = unicodeString(definition)
     defParts = definition.split(u'||')
     rule = None
     description = kwargs.get('description', '')
     for cls in [IntRule, BoolRule, StrRule]:
         if defParts[0].startswith(cls.prefix):
             rule = cls(
                 name,
                 definition,
                 description=description,
                 parameter=kwargs['parameter'])
             break
     if not rule:
         if 'parameter' in kwargs:
             del kwargs['parameter']
         ruleType = type(str(ruleKey(name)) + 'Rule', (Rule, ), {})
         rule = ruleType(name, definition, **kwargs)
         if defParts[0] == 'FCallingHand':
             parts1 = defParts[1].split('=')
             assert parts1[0] == 'Ohand', definition
             ruleClassName = parts1[1] + 'Rule'
             if ruleClassName not in RuleBase.ruleClasses:
                 logDebug(
                     u'we want %s, definition:%s' %
                     (ruleClassName, definition))
                 logDebug(u'we have %s' % RuleBase.ruleClasses.keys())
             ruleType.limitHand = RuleBase.ruleClasses[ruleClassName]
     self.add(rule)
Example #3
0
File: move.py Project: KDE/kajongg
 def prettyKwargs(kwargs):
     """this is also used by the server, but the server does not use class Move"""
     result = u''
     for key in sorted(kwargs.keys()):
         value = kwargs[key]
         if key == 'token':
             continue
         if isinstance(value, (list, tuple)) and isinstance(value[0], (list, tuple)):
             oldValue = value
             tuples = []
             for oldTuple in oldValue:
                 tuples.append(u''.join(unicodeString(x) for x in oldTuple))
             value = u','.join(tuples)
         if Debug.neutral and key == 'gameid':
             result += u' gameid:GAMEID'
         elif isinstance(value, bool) and value:
             result += u' %s' % key
         elif isinstance(value, bool):
             pass
         elif isinstance(value, bytes):
             result += u' %s:%s' % (key, unicodeString(value))
         else:
             result += u' %s:%s' % (key, value)
     for old, new in ((u"('", u"("), (u"')", u")"), (u" '", u""),
                      (u"',", u","), (u"[(", u"("), (u"])", u")")):
         result = result.replace(old, new)
     return result
Example #4
0
File: query.py Project: KDE/kajongg
 def __upgrade(self):
     """upgrade the structure of an existing kajongg database"""
     try:
         Internal.db = DBHandle(self.path)
         if isPython3:
             allVersions = list(['4.13.0', '8300'])
         else:
             allVersions = list(['4.13.0', '8200'])
         assert allVersions[-1] == str(Internal.defaultPort), '{} != {}'.format(
             allVersions[-1], str(Internal.defaultPort))
         # skip versions before current db versions:
         currentVersion = self.__currentVersion()
         while allVersions and allVersions[0] <= currentVersion:
             allVersions = allVersions[1:]
         for version in allVersions:
             currentVersion = self.__currentVersion()
             with Internal.db:  # transaction
                 updateMethodName = 'updateToVersion{}'.format(version.replace('.', '_'))
                 if hasattr(self, updateMethodName):
                     getattr(self, updateMethodName)()
                 Query('UPDATE general SET schemaversion=?', (version,))
             logInfo(m18n('Database %1 updated from schema %2 to %3',
                          Internal.db.path, currentVersion, version), showDialog=True)
     except sqlite3.Error as exc:
         logException(
             u'opening %s: %s' %
             (unicodeString(self.path), exc.message))
     finally:
         Internal.db.close(silent=True)
Example #5
0
File: query.py Project: KDE/kajongg
 def name(self):
     """get name for log messages. Readonly."""
     stack = list(x[2] for x in traceback.extract_stack())
     name = stack[-3]
     if name in ('__exit__', '__init__'):
         name = stack[-4]
     return u'%s on %s (%x)' % (name, unicodeString(self.path), id(self))
Example #6
0
 def status(self):
     """a status string"""
     result = u''
     if self.suspendedAt:
         result = m18nc('table status', 'Suspended')
         result += u' ' + unicodeString(datetime.datetime.strptime(self.suspendedAt,
                                                                   '%Y-%m-%dT%H:%M:%S').strftime('%c'))
     if self.running:
         result += u' ' + m18nc('table status', 'Running')
     return result or m18nc('table status', 'New')
Example #7
0
File: query.py Project: KDE/kajongg
 def close(self, silent=False):
     """just for logging"""
     if not silent and (Debug.sql or Debug.quit):
         if self is Internal.db:
             logDebug(u'Closing Internal.db: %s' % unicodeString(self.path))
         else:
             logDebug(
                 u'Closing DBHandle %s: %s' %
                 (self, unicodeString(self.path)))
     if self is Internal.db:
         Internal.db = None
     try:
         self.commit(silent=True)
     except sqlite3.Error:
         self.rollback()
     try:
         sqlite3.Connection.close(self)
     except sqlite3.Error as exc:
         logDebug(exc)
Example #8
0
File: query.py Project: KDE/kajongg
 def __init__(self, path):
     assert Internal.db is None, id(self)
     Internal.db = self
     self.inTransaction = None
     self.path = path
     self.identifier = None
     try:
         sqlite3.Connection.__init__(self, self.path, timeout=10.0)
     except sqlite3.Error as exc:
         logException(
             u'opening %s: %s' %
             (unicodeString(self.path), exc.message))
     if self.hasTable('general'):
         cursor = self.cursor()
         cursor.execute('select ident from general')
         self.identifier = cursor.fetchone()[0]
     if Debug.sql:
         logDebug(u'Opened %s with identifier %s' % (
             unicodeString(self.path), self.identifier))
Example #9
0
File: log.py Project: KDE/kajongg
def m18nc(context, englishText, *args):
    """
    Wrapper around i18n. i18n only accepts and returns
    native strings.

    @param context: The context for this string.
    @type context: C{str}
    @param englishText : The text template.
    @type englishText: C{str} (utf-8) or C{unicode}.

    @param args : Arguments for the text template.
    @type args: A list or tuple of strings.

    @return: The translated text with args inserted.
    @rtype: C{unicode}.
    """
    result = unicodeString(
        i18nc(
            context,
            nativeString(englishText),
            *unicodeStringArgs(args)))
    if not args:
        ENGLISHDICT[result] = unicodeString(englishText)
    return result
Example #10
0
File: log.py Project: KDE/kajongg
def m18n(englishText, *args):
    """
    Wrapper around i18n.

    @param englishText : The text template.
    @type englishText: C{str} (utf-8)  or C{unicode}.

    @param args : Arguments for the text template.
    @type args: A list or tuple of strings.

    @return: The translated text with args inserted.
    @rtype: C{unicode}.

    Since when do args have to be unicode? utf-8
    encoded fails.
    """
    result = unicodeString(
        i18n(
            nativeString(
                englishText),
            *unicodeStringArgs(args)))
    if not args:
        ENGLISHDICT[result] = unicodeString(englishText)
    return result
Example #11
0
def parseOptions():
    """parse command line options and save the values"""
    args = KCmdLineArgs.parsedArgs()
    Internal.app = APP
    Options.playOpen |= args.isSet("playopen")
    Options.showRulesets |= args.isSet("rulesets")
    Options.rulesetName = str(args.getOption("ruleset"))
    if args.isSet("host"):
        Options.host = str(args.getOption("host"))
    if args.isSet("player"):
        Options.player = unicodeString(args.getOption("player"))
    if args.isSet("rounds"):
        Options.rounds = int(args.getOption("rounds"))
    if args.isSet("ai"):
        Options.AI = str(args.getOption("ai"))
    if args.isSet("csv"):
        Options.csv = str(args.getOption("csv"))
    if args.isSet("socket"):
        Options.socket = str(args.getOption("socket"))
    if args.isSet("port"):
        Options.port = str(args.getOption("port"))
    SingleshotOptions.game = str(args.getOption("game"))
    Options.gui |= args.isSet("gui")
    if args.isSet("table"):
        SingleshotOptions.table = int(args.getOption("table"))
    if args.isSet("join"):
        SingleshotOptions.join = int(args.getOption("join"))
    Options.demo |= args.isSet("demo")
    Options.demo |= not Options.gui
    Internal.autoPlay = Options.demo
    msg = Debug.setOptions(str(args.getOption("debug")))
    if msg:
        Internal.logger.debug(msg)
        logging.shutdown()
        sys.exit(2)
    from query import initDb

    if not initDb():
        raise SystemExit("Cannot initialize database")
    initRulesets()
    Options.fixed = True  # may not be changed anymore
Example #12
0
File: log.py Project: KDE/kajongg
def logMessage(msg, prio, showDialog, showStack=False, withGamePrefix=True):
    """writes info message to log and to stdout"""
    # pylint: disable=R0912
    if isinstance(msg, Exception):
        msg = __exceptionToString(msg)
    msg = unicodeString(msg)
    msg = translateServerMessage(msg)
    __logUnicodeMessage(prio, __enrichMessage(msg, withGamePrefix))
    if showStack:
        if showStack is True:
            lower = 2
        else:
            lower = -showStack - 3
        for line in traceback.format_stack()[lower:-3]:
            if 'logException' not in line:
                __logUnicodeMessage(prio, '  ' + line.strip())
    if showDialog and not Internal.isServer:
        if prio == logging.INFO:
            return Information(msg)
        else:
            return Sorry(msg)
    return NoPrompt(msg)
Example #13
0
File: rule.py Project: KDE/kajongg
 def __init__(self, name, definition, description):
     self.__name = unicodeString(name)
     self.definition = unicodeString(definition)
     self.description = unicodeString(description)
     self.hasSelectable = False
     self.ruleClasses[self.__class__.__name__] = self.__class__
Example #14
0
File: log.py Project: KDE/kajongg
def m18ncE(dummyContext, englishText):
    """use this if you want to get the english text right now but still have the string translated"""
    return unicodeString(englishText)
Example #15
0
 def __unicode__(self):
     return unicodeString(self.name)
Example #16
0
 def data(self, index, role=Qt.DisplayRole):
     """score table"""
     # pylint: disable=too-many-branches,too-many-locals,redefined-variable-type
     result = toQVariant()
     if role == Qt.TextAlignmentRole:
         if index.column() == 0:
             result = toQVariant(int(Qt.AlignHCenter | Qt.AlignVCenter))
         else:
             result = toQVariant(int(Qt.AlignLeft | Qt.AlignVCenter))
     if index.isValid() and (0 <= index.row() < len(self.tables)):
         table = self.tables[index.row()]
         if role == Qt.DisplayRole and index.column() in (0, 1):
             result = toQVariant(table.tableid)
         elif role == Qt.DisplayRole and index.column() == 2:
             players = []
             zipped = list(zip(table.playerNames, table.playersOnline))
             for idx, pair in enumerate(zipped):
                 name, online = pair[0], pair[1]
                 if idx < len(zipped) - 1:
                     name += ', '
                 palette = KApplication.palette()
                 if online:
                     color = palette.color(
                         QPalette.Active,
                         QPalette.WindowText).name()
                     style = ('font-weight:normal;'
                              'font-style:normal;color:%s'
                              % color)
                 else:
                     color = palette.color(
                         QPalette.Disabled,
                         QPalette.WindowText).name()
                     style = ('font-weight:100;font-style:italic;color:%s'
                              % color)
                 players.append(
                     '<nobr style="%s">' %
                     style +
                     name +
                     '</nobr>')
             names = ''.join(players)
             result = toQVariant(names)
         elif role == Qt.DisplayRole and index.column() == 3:
             status = table.status()
             if table.suspendedAt:
                 dateVal = u' ' + unicodeString(datetime.datetime.strptime(
                     table.suspendedAt,
                     '%Y-%m-%dT%H:%M:%S').strftime('%c'))
                 status = u'Suspended'
             else:
                 dateVal = u''
             result = toQVariant(m18nc('table status', status) + dateVal)
         elif index.column() == 4:
             if role == Qt.DisplayRole:
                 result = toQVariant(
                     m18n((
                         table.myRuleset if table.myRuleset
                         else table.ruleset).name))
             elif role == Qt.ForegroundRole:
                 palette = KApplication.palette()
                 color = palette.windowText() if table.myRuleset else 'red'
                 result = toQVariant(QColor(color))
     return result