当前位置: 首页>>代码示例>>Python>>正文


Python SequenceIDGenerator.next方法代码示例

本文整理汇总了Python中ids_generators.SequenceIDGenerator.next方法的典型用法代码示例。如果您正苦于以下问题:Python SequenceIDGenerator.next方法的具体用法?Python SequenceIDGenerator.next怎么用?Python SequenceIDGenerator.next使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ids_generators.SequenceIDGenerator的用法示例。


在下文中一共展示了SequenceIDGenerator.next方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: EquipmentsPlugin

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]
class EquipmentsPlugin(common.IntervalPlugin):
    __slots__ = ('__generator',)

    def __init__(self, parent):
        super(EquipmentsPlugin, self).__init__(parent)
        self.__generator = SequenceIDGenerator()

    def start(self):
        super(EquipmentsPlugin, self).start()
        ctrl = g_sessionProvider.shared.equipments
        if ctrl is not None:
            ctrl.onEquipmentMarkerShown += self.__onEquipmentMarkerShown
        return

    def stop(self):
        ctrl = g_sessionProvider.shared.equipments
        if ctrl is not None:
            ctrl.onEquipmentMarkerShown -= self.__onEquipmentMarkerShown
        super(EquipmentsPlugin, self).stop()
        return

    def __onEquipmentMarkerShown(self, equipment, position, _, interval):
        uniqueID = self.__generator.next()
        marker = equipment.getMarker()
        if marker in settings.EQ_MARKER_TO_SYMBOL:
            symbol = settings.EQ_MARKER_TO_SYMBOL[marker]
        else:
            LOG_ERROR('Symbol is not found for equipment', equipment)
            return
        matrix = minimap_utils.makePositionMatrix(position)
        model = self._addEntryEx(uniqueID, symbol, _C_NAME.EQUIPMENTS, matrix=matrix, active=True)
        if model is not None:
            self._setCallback(uniqueID, int(interval))
        return
开发者ID:aevitas,项目名称:wotsdk,代码行数:36,代码来源:minimapplugins.py

示例2: _SquadInvitationsRecorder

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]
class _SquadInvitationsRecorder(_SquadInvitationsHandler):
    """ This class wraps _SquadInvitationsHandler in order to record player's
    actions with dyn squads during replay recording."""

    __slots__ = ("__idGen",)

    def __init__(self, setup):
        super(_SquadInvitationsRecorder, self).__init__(setup)
        self.__idGen = SequenceIDGenerator()

    def send(self, playerID):
        BattleReplay.g_replayCtrl.serializeCallbackData(_SEND_ACTION_NAME, (self.__idGen.next(), playerID))
        super(_SquadInvitationsRecorder, self).send(playerID)

    def accept(self, playerID):
        BattleReplay.g_replayCtrl.serializeCallbackData(_ACCEPT_ACTION_NAME, (self.__idGen.next(), playerID))
        super(_SquadInvitationsRecorder, self).accept(playerID)

    def reject(self, playerID):
        BattleReplay.g_replayCtrl.serializeCallbackData(_REJECT_ACTION_NAME, (self.__idGen.next(), playerID))
        super(_SquadInvitationsRecorder, self).reject(playerID)
开发者ID:aevitas,项目名称:wotsdk,代码行数:23,代码来源:arena_infoinvitations.py

示例3: _InvitesIDsManager

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]
class _InvitesIDsManager(object):

    def __init__(self):
        self.clear()

    def clear(self):
        self.__idsGen = SequenceIDGenerator()
        self.__idsMap = {'inviteIDs': {},
         'clubIDs': {}}

    def getInviteID(self, clubDbID, userDbID, creationTime):
        uniqueID = (clubDbID, userDbID, creationTime)
        if uniqueID not in self.__idsMap['clubIDs']:
            inviteID, showAt = self.__idsGen.next(), None
            self.__idsMap['inviteIDs'][inviteID] = uniqueID
            self.__idsMap['clubIDs'][uniqueID] = (inviteID, showAt)
        else:
            inviteID, showAt = self.__idsMap['clubIDs'][uniqueID]
        return (inviteID, showAt)

    def setShowTime(self, inviteID, showAt):
        uniqueID = self.__idsMap['inviteIDs'][inviteID]
        self.__idsMap['clubIDs'][uniqueID] = (inviteID, showAt)
开发者ID:webiumsk,项目名称:WOT0.9.10,代码行数:25,代码来源:items.py

示例4: BrowserController

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]
class BrowserController(Controller):
    _BROWSER_TEXTURE = 'BrowserBg'
    _ALT_BROWSER_TEXTURE = 'AltBrowserBg'

    def __init__(self, proxy):
        super(BrowserController, self).__init__(proxy)
        self.__browsers = {}
        self.__browsersCallbacks = {}
        self.__browserIDGenerator = SequenceIDGenerator()
        self.__eventMgr = Event.EventManager()
        self.onBrowserAdded = Event.Event(self.__eventMgr)
        self.onBrowserDeleted = Event.Event(self.__eventMgr)
        self.__urlMacros = URLMarcos()
        self.__pendingBrowsers = {}
        self.__creatingBrowserID = None
        self.__filters = _getGlobalFilters()
        return

    def fini(self):
        self.__filters = None
        self.__eventMgr.clear()
        self.__eventMgr = None
        self.__urlMacros.clear()
        self.__urlMacros = None
        self.__browserIDGenerator = None
        super(BrowserController, self).fini()
        return

    def onAvatarBecomePlayer(self):
        self.__stop()

    def onDisconnected(self):
        self.__stop()

    def addFilterHandler(self, handler):
        """ Adds given @handler to the browser urls filter chain. Calls
        it if there is a @tag in url onto opened browser page.
        Handler should receive url and list of client-specific tags,
        return bool as flag that routine have to stop
        """
        self.__filters.add(handler)

    def removeFilterHandler(self, handler):
        """ Remove given @handler from filtering chain. Handler description
        can be seen in addFilterhandler method doc-string
        """
        self.__filters.discard(handler)

    @async
    @process
    def load(self, url = None, title = None, showActionBtn = True, showWaiting = True, browserID = None, isAsync = False, browserSize = None, isDefault = True, callback = None, showCloseBtn = False, useBrowserWindow = True):
        url = yield self.__urlMacros.parse(url or GUI_SETTINGS.browser.url)
        suffix = yield self.__urlMacros.parse(GUI_SETTINGS.browser.params)
        concatenator = '&' if '?' in url else '?'
        if suffix not in url:
            url = concatenator.join([url, suffix])
        size = browserSize or BROWSER.SIZE
        webBrowserID = browserID
        if browserID is None:
            browserID = self.__browserIDGenerator.next()
            webBrowserID = browserID
        elif type(browserID) is not int:
            webBrowserID = self.__browserIDGenerator.next()
        ctx = {'url': url,
         'title': title,
         'showActionBtn': showActionBtn,
         'showWaiting': showWaiting,
         'browserID': browserID,
         'size': size,
         'isAsync': isAsync,
         'showCloseBtn': showCloseBtn,
         'showWindow': useBrowserWindow}
        texture = browserID not in self.__browsers and browserID not in self.__pendingBrowsers and self._BROWSER_TEXTURE
        app = g_appLoader.getApp()
        if not app:
            raise AssertionError('Application can not be None')
            browser = WebBrowser(webBrowserID, app, texture, size, url, handlers=self.__filters)
            self.__browsers[browserID] = browser
            if self.__isCreatingBrowser():
                self.__pendingBrowsers[browserID] = ctx
            else:
                self.__createBrowser(ctx)
        elif browserID in self.__pendingBrowsers:
            self.__pendingBrowsers[browserID] = ctx
        elif browserID in self.__browsers:
            self.__browsers[browserID].navigate(url)
        callback(browserID)
        return

    def getBrowser(self, browserID):
        return self.__browsers.get(browserID)

    def delBrowser(self, browserID):
        if browserID in self.__browsers:
            browser = self.__browsers.pop(browserID)
            loadStart, loadEnd = self.__browsersCallbacks.pop(browserID, (None, None))
            if loadStart is not None:
                browser.onLoadStart -= loadStart
            if loadEnd is not None:
                browser.onLoadEnd -= loadEnd
#.........这里部分代码省略.........
开发者ID:aevitas,项目名称:wotsdk,代码行数:103,代码来源:game_controlbrowsercontroller.py

示例5: InvitesManager

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]

#.........这里部分代码省略.........

    def getSentInviteCount(self):
        return len(self.getSentInvites())

    def getUnreadCount(self):
        return self.__unreadInvitesCount

    def resetUnreadCount(self):
        self.__unreadInvitesCount = 0

    def onUserNamesReceived(self, names):
        updated = defaultdict(list)
        rosterGetter = self.users.getUser
        inviteMaker = self._getNewInviteMaker(rosterGetter)
        prebattleInvitations = _getNewInvites()
        for invite in self.getInvites(version=_INVITE_VERSION.NEW):
            if invite.creatorDBID in names or invite.receiverDBID in names:
                inviteData = prebattleInvitations.get(invite.id)
                inviteID, invite = inviteMaker(inviteData)
                if inviteData and self._updateInvite(invite, rosterGetter):
                    updated[invite.isIncoming()].append(inviteID)

        for isIncoming, event in ((True, self.onReceivedInviteListModified), (False, self.onSentInviteListModified)):
            if updated[isIncoming]:
                event([], updated[isIncoming], [])

    def _makeInviteID(self, prebattleID, peripheryID, senderDBID, receiverDBID):
        inviteKey = (prebattleID,
         peripheryID,
         senderDBID,
         receiverDBID)
        inviteID = self._IDMap.get(inviteKey)
        if inviteID is None:
            inviteID = self._IDGen.next()
            self._IDMap[inviteKey] = inviteID
        return inviteID

    def _addInvite(self, invite, userGetter):
        if self.__isInviteSenderIgnoredInBattle(invite, userGetter):
            return False
        self.__invites[invite.clientID] = invite
        if invite.isActive():
            self.__unreadInvitesCount += 1
        return True

    def _updateInvite(self, other, userGetter):
        inviteID = other.clientID
        invite = self.__invites[inviteID]
        if invite == other or self.__isInviteSenderIgnoredInBattle(invite, userGetter):
            return False
        prevCount = invite.count
        invite = invite._merge(other)
        self.__invites[inviteID] = invite
        if invite.isActive() and prevCount < invite.count:
            self.__unreadInvitesCount += 1
        return True

    def _delInvite(self, inviteID):
        result = inviteID in self.__invites
        if result:
            self.__invites.pop(inviteID)
        return result

    def _buildReceivedInvitesList(self, invitesLists):
        if self.__inited & PRB_INVITES_INIT_STEP.DATA_BUILD == 0:
            self.__inited |= PRB_INVITES_INIT_STEP.DATA_BUILD
开发者ID:webiumsk,项目名称:WOT-0.9.15-CT,代码行数:70,代码来源:invites.py

示例6: ClientChat

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]
class ClientChat(object):
    __dataProcessors = ['_ClientChat__dataTimeProcessor', '_ClientChat__inviteDataTimeProcessor', '_ClientChat__systemMessageTimeProcessor']
    __actionHandlers = {CHAT_ACTIONS.receiveInvite.index(): '_ClientChat__onReceiveInvite'}

    def __init__(self):
        raise isinstance(self, BigWorld.Entity) or AssertionError
        self.__chatActionCallbacks = {}
        self._idGen = SequenceIDGenerator()

    def acquireRequestID(self):
        return self._idGen.next()

    def requestSystemChatChannels(self):
        self.__baseChatCommand(CHAT_COMMANDS.requestSystemChatChannels)

    def findChatChannels(self, sample, requestID = None):
        if requestID is None:
            requestID = self.acquireRequestID()
        try:
            self.__baseChatCommand(CHAT_COMMANDS.findChatChannels, stringArg1=sample, ignoreCooldown=False, requestID=requestID)
        except ChatError as ex:
            self._processChatError(CHAT_ACTIONS.requestChannels, 0, ex, requestID=requestID)

        return

    def getChannelInfoById(self, channelId):
        self.__baseChatCommand(CHAT_COMMANDS.getChannelInfoById, int64Arg=channelId)

    def requestChatChannelMembers(self, channelId):
        self.__baseChannelChatCommand(channelId, CHAT_COMMANDS.requestChatChannelMembers)

    def requestChatChannelMembersCount(self, channelId):
        self.__baseChannelChatCommand(channelId, CHAT_COMMANDS.getMembersCount)

    def createChatChannel(self, channelName, password = None):
        try:
            self.__baseChatCommand(CHAT_COMMANDS.createChatChannel, stringArg1=channelName, stringArg2=password if password is not None else '', ignoreCooldown=False)
        except ChatError as ex:
            self._processChatError(CHAT_COMMANDS.createChatChannel, 0, ex)

        return

    def destroyChatChannel(self, channelId):
        self.__baseChannelChatCommand(channelId, CHAT_COMMANDS.destroyChatChannel)

    def enterChat(self, channelId, password = None):
        self.__baseChannelChatCommand(channelId, CHAT_COMMANDS.enterChatChannel, stringArg1=password if password is not None else '')
        return

    def broadcast(self, channelId, message):
        if not len(message) or message.isspace():
            return
        message = message.rstrip()
        if not isCommandMessage(message):
            try:
                self.__baseChannelChatCommand(channelId, CHAT_COMMANDS.broadcast, stringArg1=message, ignoreCooldown=False)
            except ChatError as ex:
                self._processChatError(CHAT_ACTIONS.broadcast, channelId, ex)

        else:
            try:
                command, int64Arg, int16Arg, stringArg1, stringArg2 = parseCommandMessage(message)
                self.__baseChannelChatCommand(channelId, command, int64Arg, int16Arg, stringArg1, stringArg2, ignoreCooldown=False)
            except ChatCommandError as ex:
                self._processChatError(CHAT_ACTIONS.userChatCommand, channelId, ex)

    def leaveChat(self, channelId):
        self.__baseChannelChatCommand(channelId, CHAT_COMMANDS.leaveChatChannel)

    def onChatActionFailure(self, actionData):
        MessengerEntry.g_instance.protos.BW.onChatActionFailure(actionData)

    def onChatAction(self, chatActionData):
        global g_replayCtrl
        if g_replayCtrl is None:
            import BattleReplay
            g_replayCtrl = BattleReplay.g_replayCtrl
        if g_replayCtrl.isRecording:
            g_replayCtrl.cancelSaveCurrMessage()
        elif g_replayCtrl.isPlaying:
            g_replayCtrl.onChatAction(chatActionData)
            return
        for processor in self.__dataProcessors:
            getattr(self, processor)(chatActionData)

        if CHAT_RESPONSES[chatActionData['actionResponse']] != CHAT_RESPONSES.success:
            self.onChatActionFailure(chatActionData)
        else:
            hanlerName = self.__actionHandlers.get(chatActionData['action'], None)
            if hanlerName:
                getattr(self, hanlerName)(chatActionData)
            chId = chatActionData['channel']
            commonCallbacks = self.__getChatActionCallbacks(CHAT_ACTIONS[chatActionData['action']], 0)
            commonCallbacks(chatActionData)
            if chId != 0:
                channelCallbacks = self.__getChatActionCallbacks(CHAT_ACTIONS[chatActionData['action']], chId)
                channelCallbacks(chatActionData)
        return

    def requestLastSysMessages(self):
#.........这里部分代码省略.........
开发者ID:webiumsk,项目名称:WOT-0.9.15-CT,代码行数:103,代码来源:clientchat.py

示例7: ServiceChannelManager

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]
class ServiceChannelManager(ChatActionsListener):
    def __init__(self):
        ChatActionsListener.__init__(self)
        self.__idGenerator = SequenceIDGenerator()
        self.__messages = deque([], SCH_MSGS_MAX_LENGTH)
        self.__unreadMessagesCount = 0

    def addListeners(self):
        self.addListener(self.onReceiveSysMessage, CHAT_ACTIONS.sysMessage)
        self.addListener(self.onReceivePersonalSysMessage, CHAT_ACTIONS.personalSysMessage)

    def clear(self):
        self.__messages.clear()
        self.__unreadMessagesCount = 0

    def switch(self, scope):
        if scope is MESSENGER_SCOPE.LOBBY:
            self.requestLastServiceMessages()

    def requestLastServiceMessages(self):
        BigWorld.player().requestLastSysMessages()

    def onReceiveSysMessage(self, chatAction):
        message = ServiceChannelMessage.fromChatAction(chatAction)
        self.__addServerMessage(message)

    def onReceivePersonalSysMessage(self, chatAction):
        message = ServiceChannelMessage.fromChatAction(chatAction, personal=True)
        self.__addServerMessage(message)

    def pushClientSysMessage(self, message, msgType, isAlert=False, priority=None):
        return self.__addClientMessage(
            message, SCH_CLIENT_MSG_TYPE.SYS_MSG_TYPE, isAlert=isAlert, auxData=[msgType.name(), priority]
        )

    def pushClientMessage(self, message, msgType, isAlert=False, auxData=None):
        return self.__addClientMessage(message, msgType, isAlert=isAlert, auxData=auxData)

    def getReadMessages(self):
        if self.__unreadMessagesCount > 0:
            messages = list(self.__messages)[: -self.__unreadMessagesCount]
        else:
            messages = self.__messages
        for clientID, message in messages:
            yield (clientID, message)

    def getMessage(self, clientID):
        mapping = dict(self.__messages)
        message = (False, None, None)
        if clientID in mapping:
            message = mapping[clientID]
        return message

    def getUnreadCount(self):
        return self.__unreadMessagesCount

    def resetUnreadCount(self):
        self.__unreadMessagesCount = 0

    def handleUnreadMessages(self):
        if not self.__unreadMessagesCount:
            return
        unread = list(self.__messages)[-self.__unreadMessagesCount :]
        serviceChannel = g_messengerEvents.serviceChannel
        for clientID, (isServerMsg, formatted, settings) in unread:
            if isServerMsg:
                serviceChannel.onServerMessageReceived(clientID, formatted, settings)
            else:
                serviceChannel.onClientMessageReceived(clientID, formatted, settings)

    @process
    def __addServerMessage(self, message):
        yield lambda callback: callback(True)
        formatter = collections_by_type.SERVER_FORMATTERS.get(message.type)
        serviceChannel = g_messengerEvents.serviceChannel
        serviceChannel.onChatMessageReceived(self.__idGenerator.next(), message)
        LOG_DEBUG("Server message received", message, formatter)
        if formatter:
            try:
                if formatter.isAsync():
                    formatted, settings = yield formatter.format(message)
                else:
                    formatted, settings = formatter.format(message)
            except:
                LOG_CURRENT_EXCEPTION()
                return

            if formatted:
                clientID = self.__idGenerator.next()
                self.__messages.append((clientID, (True, formatted, settings)))
                self.__unreadMessagesCount += 1
                serviceChannel.onServerMessageReceived(clientID, formatted, settings)
                customEvent = settings.getCustomEvent()
                if customEvent is not None:
                    serviceChannel.onCustomMessageDataReceived(clientID, customEvent)
            elif IS_DEVELOPMENT:
                LOG_WARNING("Not enough data to format. Action data : ", message)
        elif IS_DEVELOPMENT:
            LOG_WARNING("Formatter not found. Action data : ", message)
        return
#.........这里部分代码省略.........
开发者ID:webiumsk,项目名称:WOT-0.9.14-CT,代码行数:103,代码来源:servicechannelmanager.py

示例8: _generateUserName

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]
def _generateUserName():
    global _g_namesGenerator
    if _g_namesGenerator is None:
        _g_namesGenerator = SequenceIDGenerator()
    return '%s %d' % (USER_DEFAULT_NAME_PREFIX, _g_namesGenerator.next())
开发者ID:webiumsk,项目名称:WOT-0.9.15.1,代码行数:7,代码来源:entities.py

示例9: InvitesManager

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]

#.........这里部分代码省略.........
        try:
            prebattleID, peripheryID = self._IDMap['inviteIDs'][inviteID]
            return (prebattleID, peripheryID)
        except KeyError:
            return (0, 0)

    def getReceivedInviteCount(self):
        return len(self.__receivedInvites)

    def getReceivedInvite(self, inviteID):
        return self.__receivedInvites.get(inviteID)

    def getReceivedInvites(self, IDs = None):
        result = self.__receivedInvites.values()
        if IDs is not None:
            result = filter(lambda item: item[0].id in IDs, result)
        return result

    def getUnreadCount(self):
        return self.__unreadInvitesCount

    def resetUnreadCount(self):
        self.__unreadInvitesCount = 0

    def _doAccept(self, prebattleID, peripheryID):
        if connectionManager.peripheryID == peripheryID:
            BigWorld.player().prb_acceptInvite(prebattleID, peripheryID)
        else:
            LOG_ERROR('Invalid periphery', (prebattleID, peripheryID), connectionManager.peripheryID)

    def _makeInviteID(self, prebattleID, peripheryID):
        inviteID = self._IDMap['prbIDs'].get((prebattleID, peripheryID))
        if inviteID is None:
            inviteID = self._IDGen.next()
            self._IDMap['inviteIDs'][inviteID] = (prebattleID, peripheryID)
            self._IDMap['prbIDs'][prebattleID, peripheryID] = inviteID
        return inviteID

    def _addInvite(self, invite, userGetter):
        if g_settings.userPrefs.invitesFromFriendsOnly:
            user = userGetter(invite.creatorDBID)
            if user is None or not user.isFriend():
                LOG_DEBUG('Invite to be ignored:', invite)
                return False
        link = self.__linkFormatter.format(invite)
        if not len(link):
            if constants.IS_DEVELOPMENT:
                LOG_WARNING('Formatter not found. Invite data : ', invite)
            return False
        else:
            self.__receivedInvites[invite.id] = (invite, link)
            if invite.isActive():
                self.__unreadInvitesCount += 1
            return True

    def _updateInvite(self, other, userGetter):
        inviteID = other.id
        invite, _ = self.__receivedInvites[inviteID]
        if other.isActive() and g_settings.userPrefs.invitesFromFriendsOnly:
            user = userGetter(invite.creatorDBID)
            if user is None or not user.isFriend():
                LOG_DEBUG('Invite to be ignored:', invite)
                return False
        prevCount = invite.count
        invite = invite._merge(other)
        link = self.__linkFormatter.format(invite)
开发者ID:19colt87,项目名称:WOTDecompiled,代码行数:70,代码来源:invites.py

示例10: SortiesCache

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]

#.........这里部分代码省略.........
    def __buildCache(self):
        cache = {}
        fort = self.__controller.getFort()
        if not fort:
            LOG_WARNING('Client fort is not found')
            return cache
        sorties = fort.getSorties()
        selectedID = self.getSelectedID()
        found = False
        for sortieID, sortie in sorties.iteritems():
            item = SortieItem(sortieID, sortie)
            if not found and item.getID() == selectedID:
                found = True
            cache[sortieID] = item

        if not found:
            self.clearSelectedID()
        return cache

    def __updateItem(self, sortieID, fort):
        sortie = fort.getSortieShortData(*sortieID)
        if sortie is None:
            LOG_ERROR('Sortie is not found', sortieID, fort.sorties)
            return
        else:
            if sortieID in self.__cache:
                item = self.__cache[sortieID]
                item._updateItemData(sortie)
                if item._isDirty and self.__selectedID == item.getID() and item.filter(self.getRosterTypeID()):
                    self.__selectedUnit = None
                    self._requestSortieUnit(sortieID)
            else:
                item = SortieItem(sortieID, sortie)
                self.__cache[sortieID] = item
            return item

    def __requestCallback(self, _):
        Waiting.hide('fort/sortie/get')
        self.__isRequestInProcess = False

    def __removeItem(self, sortieID):
        result = False
        if sortieID in self.__cache:
            self.__cache.pop(sortieID)
            result = True
        if self.getSelectedID() == sortieID:
            self.clearSelectedID()
        clientIdx = self.__idToIndex.pop(sortieID, None)
        if clientIdx is not None:
            self.__indexToID.pop(clientIdx, None)
        return result

    def __getClientIdx(self, sortieID):
        if sortieID == (0, 0):
            return 0
        if sortieID not in self.__idToIndex:
            clientIdx = self.__idGen.next()
            self.__idToIndex[sortieID] = clientIdx
            self.__indexToID[clientIdx] = sortieID
        else:
            clientIdx = self.__idToIndex[sortieID]
        return clientIdx

    def __getUnit(self, sortieID):
        fort = self.__controller.getFort()
        if not fort:
            LOG_WARNING('Client fort is not found')
            return
        else:
            isSelected = self.getSelectedID() == sortieID
            if isSelected and self.__selectedUnit is not None:
                return self.__selectedUnit
            unit = fort.getSortieUnit(*sortieID)
            if isSelected:
                self.__selectedUnit = unit
            return unit

    def __fort_onSortieChanged(self, unitMgrID, peripheryID):
        fort = self.__controller.getFort()
        sortieID = (unitMgrID, peripheryID)
        if fort:
            item = self.__updateItem(sortieID, fort)
            if item:
                self.__controller._listeners.notify('onSortieChanged', self, item)

    def __fort_onSortieRemoved(self, unitMgrID, peripheryID):
        sortieID = (unitMgrID, peripheryID)
        if self.__removeItem(sortieID):
            self.__controller._listeners.notify('onSortieRemoved', self, sortieID)

    def __fort_onSortieUnitReceived(self, unitMgrID, peripheryID):
        fort = self.__controller.getFort()
        sortieID = (unitMgrID, peripheryID)
        if fort:
            if unitMgrID in self.__cache:
                self.__cache[sortieID]._isDirty = False
            if self.getSelectedID() == sortieID:
                self.__selectedUnit = None
            self.__controller._listeners.notify('onSortieUnitReceived', self.__getClientIdx(sortieID))
        return
开发者ID:webiumsk,项目名称:WOT-0.9.14-CT,代码行数:104,代码来源:fort_seqs.py

示例11: BWChatProvider

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]
class BWChatProvider(object):
    __slots__ = ('__weakref__', '__handlers', '__msgFilters', '__coolDown', '__idGen', '__isEnabled', '__queue')

    def __init__(self):
        super(BWChatProvider, self).__init__()
        self.__handlers = defaultdict(set)
        self.__msgFilters = None
        self.__coolDown = _ChatCooldownManager()
        self.__idGen = SequenceIDGenerator()
        self.__isEnabled = False
        self.__queue = []
        return

    def clear(self):
        self.__handlers.clear()

    def setEnable(self, value):
        if self.__isEnabled == value:
            return
        self.__isEnabled = value
        if self.__isEnabled:
            self.__sendActionsFromQueue()
        else:
            self.__queue = []

    def doAction(self, actionID, args = None, response = False, skipCoolDown = False):
        success, reqID = False, 0
        if self.__coolDown.isInProcess(actionID):
            if not skipCoolDown:
                g_messengerEvents.onErrorReceived(createCoolDownError(actionID))
        else:
            if response:
                reqID = self.__idGen.next()
            if self.__isEnabled:
                success = self.__sendAction(actionID, reqID, args)
            else:
                success = self.__addActionToQueue(actionID, reqID, args)
        return (success, reqID)

    def onActionReceived(self, actionID, reqID, args):
        handlers = self.__handlers[actionID]
        for handler in handlers:
            try:
                handler((actionID, reqID), args)
            except TypeError:
                LOG_ERROR('Handler has been invoked with error', handler)
                LOG_CURRENT_EXCEPTION()

    def setFilters(self, msgFilterChain):
        self.__msgFilters = msgFilterChain

    def filterInMessage(self, message):
        text = self.__msgFilters.chainIn(message.accountDBID, message.text)
        if not text:
            result = None
        else:
            message.text = text
            result = message
        return result

    def filterOutMessage(self, text, limits):
        return self.__msgFilters.chainOut(text, limits)

    def setActionCoolDown(self, actionID, coolDown):
        self.__coolDown.process(actionID, coolDown)

    def isActionInCoolDown(self, actionID):
        return self.__coolDown.isInProcess(actionID)

    def getActionCoolDown(self, actionID):
        return self.__coolDown.getTime(actionID)

    def clearActionCoolDown(self, actionID):
        self.__coolDown.reset(actionID)

    def registerHandler(self, actionID, handler):
        handlers = self.__handlers[actionID]
        if handler in handlers:
            LOG_WARNING('Handler already is exist', actionID, handler)
        else:
            if not hasattr(handler, '__self__') or not isinstance(handler.__self__, ActionsHandler):
                LOG_ERROR('Class of handler is not subclass of ActionsHandler', handler)
                return
            if callable(handler):
                handlers.add(handler)
            else:
                LOG_ERROR('Handler is invalid', handler)

    def unregisterHandler(self, actionID, handler):
        handlers = self.__handlers[actionID]
        if handler in handlers:
            handlers.remove(handler)

    def __sendAction(self, actionID, reqID, args = None):
        player = BigWorld.player()
        if player:
            player.base.messenger_onActionByClient_chat2(actionID, reqID, args or messageArgs())
            return True
        else:
            LOG_ERROR('Player is not defined')
#.........这里部分代码省略.........
开发者ID:webiumsk,项目名称:WOT-0.9.15-CT,代码行数:103,代码来源:provider.py

示例12: BWChatProvider

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]
class BWChatProvider(object):

    def __init__(self):
        super(BWChatProvider, self).__init__()
        self.__handlers = defaultdict(set)
        self.__msgFilters = None
        self.__coolDown = _ChatCooldownManager()
        self.__idGen = SequenceIDGenerator()



    def clear(self):
        self.__handlers.clear()



    def doAction(self, actionID, args = None, response = False, skipCoolDown = False):
        player = BigWorld.player()
        (success, reqID,) = (False, 0)
        if player:
            if self.__coolDown.isInProcess(actionID):
                if not skipCoolDown:
                    g_messengerEvents.onServerErrorReceived(createCoolDownError(actionID))
            elif response:
                reqID = self.__idGen.next()
            player.base.messenger_onActionByClient_chat2(actionID, reqID, args or messageArgs())
            success = True
        else:
            LOG_ERROR('Player is not defined')
        return (success, reqID)



    def onActionReceived(self, actionID, reqID, args):
        handlers = self.__handlers[actionID]
        for handler in handlers:
            try:
                handler((actionID, reqID), args)
            except TypeError:
                LOG_ERROR('Handler has been invoked with error', handler)
                LOG_CURRENT_EXCEPTION()




    def setFilters(self, msgFilterChain):
        self.__msgFilters = msgFilterChain



    def filterInMessage(self, message):
        text = self.__msgFilters.chainIn(message.accountDBID, message.text)
        if not text:
            result = None
        else:
            message.text = text
            result = message
        return result



    def filterOutMessage(self, text, limits):
        return self.__msgFilters.chainOut(text, limits)



    def setActionCoolDown(self, actionID, coolDown):
        self.__coolDown.process(actionID, coolDown)



    def isActionInCoolDown(self, actionID):
        return self.__coolDown.isInProcess(actionID)



    def getActionCoolDown(self, actionID):
        return self.__coolDown.getTime(actionID)



    def clearActionCoolDown(self, actionID):
        self.__coolDown.reset(actionID)



    def registerHandler(self, actionID, handler):
        handlers = self.__handlers[actionID]
        if handler in handlers:
            LOG_WARNING('Handler already is exist', actionID, handler)
        elif not hasattr(handler, '__self__') or not isinstance(handler.__self__, ActionsHandler):
            LOG_ERROR('Class of handler is not subclass of ActionsHandler', handler)
            return 
        if callable(handler):
            handlers.add(handler)
        else:
            LOG_ERROR('Handler is invalid', handler)



#.........这里部分代码省略.........
开发者ID:Infernux,项目名称:Projects,代码行数:103,代码来源:provider.py

示例13: XmppPlugin

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]
class XmppPlugin(IProtoPlugin):
    DISCONNECT_BY_REQUEST = 0
    DISCONNECT_AUTHENTICATION = 1
    DISCONNECT_OTHER_ERROR = 2
    USE_MOCK_DATA = False
    ALLOWED_ROSTER_ACTIONS = [USER_ROSTER_ACTION.AddToFriend,
     USER_ROSTER_ACTION.AddToIgnored,
     USER_ROSTER_ACTION.RemoveFromFriend,
     USER_ROSTER_ACTION.RemoveFromIgnored]

    def __init__(self):
        self.__client = BigWorld.XmppClient()
        self.__currentUser = None
        self.__xmppRoster = None
        self.__usersMgr = None
        self.__model = None
        self.__bwRoster = None
        self.__reconnectCount = 0
        self.__reconnectCallbackId = None
        self.__bwConnected = False
        self.__isEnabled = False
        self.__idsGen = SequenceIDGenerator()
        self.__pendingBattleMode = None
        self.__databaseID = None
        return

    @storage_getter('users')
    def usersStorage(self):
        return None

    @property
    def isConnected(self):
        """
        Shows current XMPP connection status
        """
        if self.__model is not None:
            return self.__model.isConnected
        else:
            return False

    def logState(self):
        if self.__isEnabled:
            if self.__model is not None and self.__model.isConnected:
                itemsStrList = ['XMPP:logState - XMPP is connected. Logging XMPP roster state:']
                itemsStrList.append('Curr.User JID: {0}  Status: {1}'.format(self.__currentUser.bareJid, self.__currentUser.getPresenceStr(self.__currentUser.presence)))
                for jid, item in self.__xmppRoster.items():
                    itemsStrList.append('Contact   JID: {0}  Status: {1}  Name: {2}'.format(jid, item.getPresenceStr(item.presence), item.name))

                LOG_DEBUG('\n'.join(itemsStrList))
            else:
                LOG_DEBUG('XMPP:logState - XMPP is not connected yet. Try to run your command later')
        else:
            LOG_DEBUG('XMPP:logState - You are not logged in or connection to XMPP is disabled by server settings')
        return

    def connect(self, scope = None):
        if scope is not None:
            self._setBattleMode(scope)
        if self.isConnected:
            return
        else:
            self.__bwConnected = True
            self._cancelReconnectCallback()
            settings = self._getServerSettings()
            if settings.get('xmpp_enabled', False):
                self.__isEnabled = bool(int(settings.get('jdCutouts', 0)))
                if self.__isEnabled:
                    self._subscribeToActions()
                    LOG_DEBUG('XMPP:connect - XMPP functionality is enabled. Starting connection to XMPP server')
                    if self.__model is None:
                        self.__model = XmppConnectionModel(settings.get('xmpp_host'), settings.get('xmpp_port'), settings.get('xmpp_resource'), False, None, None)
                    else:
                        self.__model = self.__model._replace(host=settings.get('xmpp_host'), port=settings.get('xmpp_port'), resourceName=settings.get('xmpp_resource'), isConnected=False)
                    if self.__model.host is None:
                        raise Exception, 'XMPP: server xmpp_host is not defined'
                    connections = settings.get('xmpp_connections', [])
                    if len(connections) > 0:
                        self.__model = self.__model._replace(connection=random.choice(connections))
                    else:
                        self.__model = self.__model._replace(connection=(self.__model.host, self.__model.port))
                        LOG_DEBUG('XMPP:connect - no xmpp_connections are passed - using default connection', self.__model.connection)
                    if self.__model.token is None:
                        Account.g_accountRepository and Account.g_accountRepository.onChatTokenReceived.clear()
                        Account.g_accountRepository.onChatTokenReceived += self._tokenCallback
                    BigWorld.player().requestChatToken(self.__idsGen.next())
                else:
                    LOG_DEBUG('XMPP:connect - trying to connect using token from previous connection')
                    self._tokenCallback(cPickle.dumps({'error': None,
                     'token': self.__model.token,
                     'databaseID': self.__databaseID}))
            else:
                LOG_DEBUG('XMPP:connect - XMPP functionality is disabled. Stopping execution')
            return

    def disconnect(self):
        LOG_DEBUG('XMPP:disconnect')
        if Account.g_accountRepository:
            Account.g_accountRepository.onChatTokenReceived.clear()
        self.__bwConnected = False
        if self.isConnected:
#.........这里部分代码省略.........
开发者ID:19colt87,项目名称:WOTDecompiled,代码行数:103,代码来源:__init__.py

示例14: BrowserController

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]
class BrowserController(Controller):
    _BROWSER_TEXTURE = "BrowserBg"
    _ALT_BROWSER_TEXTURE = "AltBrowserBg"

    def __init__(self, proxy):
        super(BrowserController, self).__init__(proxy)
        self.__browsers = {}
        self.__browsersCallbacks = {}
        self.__browserIDGenerator = SequenceIDGenerator()
        self.__eventMgr = Event.EventManager()
        self.onBrowserAdded = Event.Event(self.__eventMgr)
        self.onBrowserDeleted = Event.Event(self.__eventMgr)
        self.__urlMacros = URLMarcos()

    def fini(self):
        self.__eventMgr.clear()
        self.__eventMgr = None
        self.__urlMacros.clear()
        self.__urlMacros = None
        self.__browserIDGenerator = None
        super(BrowserController, self).fini()
        return

    def onAvatarBecomePlayer(self):
        self.__stop()

    def onDisconnected(self):
        self.__stop()

    @async
    @process
    def load(
        self,
        url=None,
        title=None,
        showActionBtn=True,
        showWaiting=True,
        browserID=None,
        isAsync=False,
        browserSize=None,
        background=None,
        isDefault=True,
        callback=None,
        showCloseBtn=False,
    ):
        url = url or GUI_SETTINGS.browser.url
        suffix = yield self.__urlMacros.parse(GUI_SETTINGS.browser.params)
        concatenator = "&" if "?" in url else "?"
        if suffix not in url:
            url = concatenator.join([url, suffix])
        size = browserSize or BROWSER.SIZE
        background = background or BROWSER.BACKGROUND
        if browserID is None:
            browserID = self.__browserIDGenerator.next()
        if browserID not in self.__browsers:
            texture = self._BROWSER_TEXTURE if isDefault else self._ALT_BROWSER_TEXTURE
            app = g_appLoader.getApp()
            if not app:
                raise AssertionError("Application can not be None")
                self.__browsers[browserID] = WebBrowser(browserID, app, texture, size, url, backgroundUrl=background)
                self.onBrowserAdded(browserID)
            ctx = {
                "url": url,
                "title": title,
                "showActionBtn": showActionBtn,
                "showWaiting": showWaiting,
                "browserID": browserID,
                "size": size,
                "isDefault": isDefault,
                "isAsync": isAsync,
                "showCloseBtn": showCloseBtn,
            }

            def browserCallback(*args):
                self.__clearCallback(browserID)
                self.__showBrowser(browserID, ctx)

            self.__browsersCallbacks[browserID] = isAsync and (None, browserCallback)
            self.__browsers[browserID].onLoadEnd += browserCallback
        else:
            self.__browsersCallbacks[browserID] = (browserCallback, None)
            self.__browsers[browserID].onLoadStart += browserCallback
        callback(browserID)
        return

    def getBrowser(self, browserID):
        return self.__browsers.get(browserID)

    def delBrowser(self, browserID):
        if browserID in self.__browsers:
            browser = self.__browsers.pop(browserID)
            loadStart, loadEnd = self.__browsersCallbacks.pop(browserID, (None, None))
            if loadStart is not None:
                browser.onLoadStart -= loadStart
            if loadEnd is not None:
                browser.onLoadEnd -= loadEnd
            browser.destroy()
        self.onBrowserDeleted(browserID)
        return

#.........这里部分代码省略.........
开发者ID:webiumsk,项目名称:WOT-0.9.12-CT,代码行数:103,代码来源:browsercontroller.py

示例15: BrowserController

# 需要导入模块: from ids_generators import SequenceIDGenerator [as 别名]
# 或者: from ids_generators.SequenceIDGenerator import next [as 别名]
class BrowserController(Controller, AppRef):
    _BROWSER_TEXTURE = 'BrowserBg'
    _ALT_BROWSER_TEXTURE = 'AltBrowserBg'

    def __init__(self, proxy):
        super(BrowserController, self).__init__(proxy)
        self.__browsers = {}
        self.__browsersCallbacks = {}
        self.__browserIDGenerator = SequenceIDGenerator()
        self.__eventMgr = Event.EventManager()
        self.onBrowserAdded = Event.Event(self.__eventMgr)
        self.onBrowserDeleted = Event.Event(self.__eventMgr)
        self.__urlMacros = URLMarcos()

    def fini(self):
        self.__eventMgr.clear()
        self.__eventMgr = None
        self.__urlMacros.clear()
        self.__urlMacros = None
        self.__browserIDGenerator = None
        super(BrowserController, self).fini()
        return

    def onBattleStarted(self):
        self.__stop()

    def onDisconnected(self):
        self.__stop()

    @async
    @process
    def load(self, url = None, title = None, showActionBtn = True, showWaiting = True, browserID = None, isAsync = False, browserSize = None, background = None, isDefault = True, callback = None):
        url = url or GUI_SETTINGS.browser.url
        suffix = yield self.__urlMacros.parse(GUI_SETTINGS.browser.params)
        concatenator = '&' if '?' in url else '?'
        if suffix not in url:
            url = concatenator.join([url, suffix])
        size = browserSize or BROWSER.SIZE
        background = background or BROWSER.BACKGROUND
        if browserID not in self.__browsers:
            browserID = self.__browserIDGenerator.next()
            texture = self._BROWSER_TEXTURE if isDefault else self._ALT_BROWSER_TEXTURE
            self.__browsers[browserID] = WebBrowser(browserID, self.app, texture, size, url, backgroundUrl=background)
            self.onBrowserAdded(browserID)
        ctx = {'url': url,
         'title': title,
         'showActionBtn': showActionBtn,
         'showWaiting': showWaiting,
         'browserID': browserID,
         'size': size,
         'isDefault': isDefault,
         'isAsync': isAsync}

        def browserCallback(*args):
            self.__clearCallback(browserID)
            self.__showBrowser(browserID, ctx)

        if isAsync:
            self.__browsersCallbacks[browserID] = (None, browserCallback)
            self.__browsers[browserID].onLoadEnd += browserCallback
        else:
            self.__browsersCallbacks[browserID] = (browserCallback, None)
            self.__browsers[browserID].onLoadStart += browserCallback
        callback(browserID)
        return

    def getBrowser(self, browserID):
        return self.__browsers.get(browserID)

    def delBrowser(self, browserID):
        if browserID in self.__browsers:
            browser = self.__browsers.pop(browserID)
            loadStart, loadEnd = self.__browsersCallbacks.pop(browserID, (None, None))
            if loadStart is not None:
                browser.onLoadStart -= loadStart
            if loadEnd is not None:
                browser.onLoadEnd -= loadEnd
            browser.destroy()
        self.onBrowserDeleted(browserID)
        return

    def __stop(self):
        while self.__browsers:
            browserID, browser = self.__browsers.popitem()
            loadStart, loadEnd = self.__browsersCallbacks.pop(browserID, (None, None))
            if loadStart is not None:
                browser.onLoadStart -= loadStart
            if loadEnd is not None:
                browser.onLoadEnd -= loadEnd
            browser.destroy()

        return

    def __clearCallback(self, browserID):
        if browserID in self.__browsersCallbacks:
            loadStart, loadEnd = self.__browsersCallbacks.pop(browserID, (None, None))
            if loadStart is not None:
                self.__browsers[browserID].onLoadStart -= loadStart
            if loadEnd is not None:
                self.__browsers[browserID].onLoadEnd -= loadEnd
#.........这里部分代码省略.........
开发者ID:webiumsk,项目名称:WoT,代码行数:103,代码来源:browsercontroller.py


注:本文中的ids_generators.SequenceIDGenerator.next方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。