예제 #1
0
 def _packBonuses(self, model):
     packer = getDefaultBonusPacker()
     self.__tooltipData = {}
     packQuestBonusModelAndTooltipData(packer,
                                       model.getBonuses(),
                                       self._event,
                                       tooltipData=self.__tooltipData)
 def _updateEpicQuestModel(self, model, fullUpdate=False):
     _logger.debug('DailyQuestsView::_updateEpicQuestModel')
     epicQuest = self.eventsCache.getDailyEpicQuest()
     isEnabled = isEpicQuestEnabled() and epicQuest is not None
     with model.epicQuest.transaction() as tx:
         tx.setIsEnabled(isEnabled)
         if not isEnabled:
             _logger.info('Daily Quest Screen: Epic quest is not enabled.')
             return
         epicQuestId = epicQuest.getID()
         dqToken = first((t for t in epicQuest.accountReqs.getTokens() if t.isDailyQuest()))
         if dqToken is None:
             _logger.error('Epic quest does not require any dq tokens to complete.')
             return
         isTokeCountChanged = self.itemsCache.items.tokens.hasTokenCountChanged(dqToken.getID())
         isTokenNeededChanged = dqToken.getNeededCount() != tx.getTotal()
         isEpicQuestIdChanged = epicQuestId != tx.getId()
         if not fullUpdate and not isTokeCountChanged and not isEpicQuestIdChanged and not isTokenNeededChanged:
             return
         _logger.debug('DailyQuestsView::__updateQuestInModel')
         lastViewedTokenCount = self.itemsCache.items.tokens.getLastViewedProgress(dqToken.getID())
         currTokenCount = self.eventsCache.questsProgress.getTokenCount(dqToken.getID())
         earned = currTokenCount - lastViewedTokenCount if currTokenCount >= lastViewedTokenCount else currTokenCount
         tx.setId(epicQuestId)
         tx.setTotal(dqToken.getNeededCount())
         tx.setCurrent(currTokenCount)
         tx.setEarned(earned)
         epicQuestBonusesModel = tx.getBonuses()
         epicQuestBonusesModel.clear()
         self.__tooltipData[epicQuestId] = {}
         packQuestBonusModelAndTooltipData(getDefaultBonusPacker(), epicQuestBonusesModel, epicQuest, tooltipData=self.__tooltipData[epicQuestId])
         epicQuestBonusesModel.invalidate()
     return
예제 #3
0
 def _packBonuses(self, model):
     self._tooltipData = {}
     packer = getDefaultBonusPacker()
     bonuses = sorted(self._event.getBonuses(), key=self.__keySortOrder)
     packQuestBonusModelAndTooltipData(packer, model.getBonuses(),
                                       self._event, self._tooltipData,
                                       bonuses)
예제 #4
0
 def _setAwards(self, bonuses, data):
     rewards = self._convertNonQuestBonuses(bonuses)
     with self.viewModel.transaction() as tx:
         tx.setLevel(str(data.get('reason', '')))
         packBonusModelAndTooltipData(rewards,
                                      getDefaultBonusPacker(),
                                      tx.getMainRewards(),
                                      tooltipData=self.__tooltipItems)
예제 #5
0
 def __init__(self, bonuses, bonusPacker=None, *args, **kwargs):
     settings = ViewSettings(R.views.lobby.tooltips.AdditionalRewardsTooltip())
     settings.model = AdditionalRewardsTooltipModel()
     settings.args = args
     settings.kwargs = kwargs
     super(AdditionalRewardsTooltip, self).__init__(settings)
     self.__bonuses = bonuses
     self.__bonusPackers = bonusPacker or getDefaultBonusPacker()
예제 #6
0
 def __addRewards(self, model, vo):
     packer = getDefaultBonusPacker()
     tooltipIdx = 0
     rewardsModel = model.getRewards()
     rewardsModel.clear()
     for bonus in vo['rewards']:
         bonusList = packer.pack(bonus)
         bonusTooltipList = packer.getToolTip(bonus)
         for bonusIdx, item in enumerate(bonusList):
             item.setIndex(bonusIdx)
             tooltipId = str(tooltipIdx)
             item.setTooltipId(tooltipId)
             rewardsModel.addViewModel(item)
             self.__tooltipData[tooltipId] = bonusTooltipList[bonusIdx]
             tooltipIdx += 1
    def _onLoading(self, *args, **kwargs):
        super(ScenarioTooltip, self)._onLoading(*args, **kwargs)
        self.viewModel.setVehicleType(self._vehicleType)
        self.viewModel.setTeam(self._team)
        self.viewModel.setScenarioNum(SCENARIO_INDEXES[self._team,
                                                       self._vehicleType])
        self.viewModel.setMapId(self._mapId)
        targetsModel = self.viewModel.getTargets()
        for target in self._targets:
            targetsModel.addString(target)

        self.viewModel.setVehicleName(self._vehicleName)
        self.viewModel.setIsComplete(self._isComplete)
        packer = getDefaultBonusPacker()
        bonusArray = self.viewModel.getRewards()
        for bonus in self._rewards:
            bonusList = packer.pack(bonus)
            for bonusIndex, item in enumerate(bonusList):
                item.setIndex(bonusIndex)
                bonusArray.addViewModel(item)
예제 #8
0
 def __init__(self, *args, **kwargs):
     super(MapsTrainingView, self).__init__(
         viewResource=R.views.lobby.maps_training.MapsTrainingPage(),
         viewModel=MapsTrainingViewModel())
     self.__selectedMap = None
     self.__selectedScenario = 0
     self.__ctxVehicleType = ''
     self.__ctxSide = 0
     self.__ctxShowAnimation = False
     self.__tooltipData = {}
     self.__account = BigWorld.player()
     self.__mapsConfig = TacticalMapsConfigReader.readXml(
         self._TACTICAL_MAPS_CONFIG_PATH)
     self.__isDataLoaded = False
     self.__blur = CachedBlur(blurAnimRepeatCount=1, blurRadius=0.1)
     self.__blurRectId = None
     self.__packer = getDefaultBonusPacker()
     self.__hangarCameraManager = None
     self.__tickCallback = None
     self.__preferences = self.mapsTrainingController.preferences
     self.__markerPosOffset = 0.0
     self.__finalizationInProgress = False
     self.__initFromCtx(kwargs.get('ctx', {}))
     return
예제 #9
0
class SelectableRewardBase(ViewImpl):
    __slots__ = ('__selectedTab', '__tabs', '__selectableRewards', '__cart',
                 '_packer')
    _helper = SelectableRewardManager
    _packer = getDefaultBonusPacker()

    def __init__(self, layoutID, selectableRewards, model=None):
        settings = ViewSettings(layoutID)
        settings.model = (model or SelectableRewardBaseModel)()
        self.__selectableRewards = selectableRewards
        self.__selectedTab = None
        self.__tabs = OrderedDict()
        self.__cart = OrderedDict()
        self.__processTabs()
        if self.__tabs:
            self.__processRewards()
            self._sortContent()
        super(SelectableRewardBase, self).__init__(settings)
        return

    @property
    def viewModel(self):
        return super(SelectableRewardBase, self).getViewModel()

    def createToolTip(self, event):
        if event.contentID == R.views.common.tooltip_window.backport_tooltip_content.BackportTooltipContent(
        ):
            tooltipData = self.getTooltipData(event)
            if tooltipData is None:
                return
            window = backport.BackportTooltipWindow(tooltipData,
                                                    self.getParentWindow())
            if window is None:
                return
            window.load()
            return window
        else:
            return super(SelectableRewardBase, self).createToolTip(event)

    def createToolTipContent(self, event, contentID):
        if contentID == R.views.lobby.common.tooltips.SelectedRewardsTooltipView(
        ):
            self._sortCart()
            return SelectedRewardsTooltipView(self.__cart,
                                              self.__getTotalCount())
        return super(SelectableRewardBase,
                     self).createToolTipContent(event, contentID)

    def _onLoading(self, *args, **kwargs):
        super(SelectableRewardBase, self)._onLoading()
        self.__fillTabs()
        if self.__tabs:
            self.__selectTab(
                self.viewModel.selectableRewardModel.getTabs()[0].getType(),
                initial=True)
            self.__updateTotalCount()

    def _initialize(self, *args, **kwargs):
        super(SelectableRewardBase, self)._initialize()
        selectableVM = self.viewModel.selectableRewardModel
        selectableVM.onOkClick += self._onOkClick
        selectableVM.onCloseClick += self._onCloseClick
        selectableVM.onTabClick += self._onTabClick
        selectableVM.onRewardAdd += self._onRewardAdd
        selectableVM.onRewardReduce += self._onRewardReduce

    def _finalize(self):
        selectableVM = self.viewModel.selectableRewardModel
        selectableVM.onOkClick -= self._onOkClick
        selectableVM.onCloseClick -= self._onCloseClick
        selectableVM.onTabClick -= self._onTabClick
        selectableVM.onRewardAdd -= self._onRewardAdd
        selectableVM.onRewardReduce -= self._onRewardReduce
        self.__tabs = None
        self.__selectableRewards = None
        self.__cart = None
        super(SelectableRewardBase, self)._finalize()
        return

    def _onOkClick(self):
        self._makeOrder()

    def _onCloseClick(self):
        self.destroyWindow()

    def _onTabClick(self, event):
        tabName = self.__getName(event)
        self.__selectTab(tabName, initial=False)

    def _onRewardAdd(self, event):
        rewardName = self.__getName(event)
        item = self.__tabs[self.__selectedTab]['rewards'][rewardName]
        self.__cart.setdefault(self.__selectedTab, {})
        currentTabCart = self.__cart[self.__selectedTab]
        currentTabCart.setdefault(rewardName, [])
        if (len(currentTabCart[rewardName]) < item['limit']
                or item['limit'] == 0) and self.__checkTabLimit():
            currentTabCart[rewardName].append(item)
            self.__tabs[self.__selectedTab]['count'] += 1
            self.__updateTabViewModel(self.__selectedTab)
            self.__updateRewardViewModel(rewardName)
        self.__updateRewardsState()
        self.__updateTotalCount()

    def _onRewardReduce(self, event):
        rewardName = self.__getName(event)
        currentTabCart = self.__cart.get(self.__selectedTab, OrderedDict())
        if currentTabCart.get(rewardName):
            currentTabCart[rewardName].pop(-1)
            if not currentTabCart[rewardName]:
                currentTabCart.pop(rewardName)
            self.__tabs[self.__selectedTab]['count'] -= 1
            self.__updateTabViewModel(self.__selectedTab)
            self.__updateRewardViewModel(rewardName)
        if self.__selectedTab in self.__cart and not self.__cart[
                self.__selectedTab]:
            self.__cart.pop(self.__selectedTab)
        self.__updateRewardsState()
        self.__updateTotalCount()

    def _processReceivedRewards(self, result):
        pass

    def _makeOrder(self):
        order = {}
        for tab in self.__cart.itervalues():
            for reward in tab.values():
                for value in reward:
                    self.__addItemToOrder(order, value)

        self._helper.chooseRewards(order.values(),
                                   self._processReceivedRewards)

    def _sortContent(self):
        self.__tabs = OrderedDict(
            sorted(self.__tabs.iteritems(), cmp=self._getTypesComparator()))
        for tabName in self.__tabs:
            self.__tabs[tabName]['rewards'] = OrderedDict(
                sorted(self.__tabs[tabName]['rewards'].iteritems(),
                       cmp=self._getItemsComparator(tabName)))

    def _sortCart(self):
        self.__cart = OrderedDict(
            sorted(self.__cart.iteritems(), cmp=self._getTypesComparator()))
        for catName in self.__cart:
            self.__cart[catName] = OrderedDict(
                sorted(self.__cart[catName].iteritems(),
                       cmp=self._getItemsComparator(catName)))

    def _getTypesComparator(self):
        def _defaultCompare(first, second):
            return cmp(first[0], second[0])

        return _defaultCompare

    def _getItemsComparator(self, tabName):
        def _defaultCompare(first, second):
            return cmp(first[0], second[0])

        return _defaultCompare

    @classmethod
    def __addItemToOrder(cls, order, item):
        for selectableReward, offerID in item['selectableReward']:
            rewardType = id(selectableReward)
            if rewardType in order:
                if len(order[rewardType][1]) < cls._helper.getRemainedChoices(
                        selectableReward):
                    order[rewardType][1].append(offerID)
                    break
                else:
                    continue
            order[rewardType] = (selectableReward, [offerID])
            break

    def __updateTotalCount(self):
        self.viewModel.selectableRewardModel.setTotalRewardCount(
            self.__getTotalCount())

    def __getTotalCount(self):
        result = 0
        for tab in self.__tabs:
            result += self.__getTotalTabCount(tab)

        return result

    def __checkTabLimit(self):
        result = self.__getTotalTabCount(
            self.__selectedTab) < self.__tabs[self.__selectedTab]['limit']
        return result

    def __updateRewardsState(self):
        with self.viewModel.selectableRewardModel.getRewards().transaction(
        ) as vm:
            for rewardName, _, _, _, state in self.__prepareRewardsData(
                    self.__selectedTab):
                for rewardModel in vm:
                    if rewardModel.getType() != rewardName:
                        continue
                    if rewardModel.getState(
                    ) != SelectableRewardItemModel.STATE_RECEIVED:
                        rewardModel.setState(state)

    def __getTotalTabCount(self, tabName):
        totalCount = 0
        for rewardList in self.__cart.get(tabName, {}).itervalues():
            totalCount += len(rewardList)

        return totalCount

    def _getReceivedRewards(self, rewardName):
        return self.__tabs[
            self.__selectedTab]['rewards'][rewardName]['receivedRewards']

    def _getRewardsInCartCount(self, rewardName):
        return len(self.__cart.get(self.__selectedTab, {}).get(rewardName, {}))

    def __updateTabViewModel(self, tabName):
        with self.viewModel.selectableRewardModel.getTabs().transaction(
        ) as vm:
            for tab in vm:
                if tab.getType() == tabName:
                    tab.setCount(self.__tabs[tabName]['count'])

    def __updateRewardViewModel(self, rewardName):
        count = self._getReceivedRewards(
            rewardName) + self._getRewardsInCartCount(rewardName)
        packSize = self.__tabs[
            self.__selectedTab]['rewards'][rewardName]['packSize']
        with self.viewModel.selectableRewardModel.getRewards().transaction(
        ) as vm:
            for reward in vm:
                if reward.getType() == rewardName:
                    reward.setCount(count)
                    resultSize = packSize * count or packSize
                    if (resultSize > 1 or resultSize <= 1
                            and packSize == 1) and reward.getState(
                            ) != SelectableRewardItemModel.STATE_RECEIVED:
                        reward.setPackSize(resultSize)

    def __selectTab(self, tabName, initial=False):
        if self.__selectedTab != tabName:
            self.__selectedTab = tabName
            self.viewModel.selectableRewardModel.setSelectedTab(tabName)
            self.__fillRewards(self.__selectedTab, initial=initial)

    @staticmethod
    def __getName(event):
        return event.get('type', '')

    def __fillRewards(self, tabName, initial=False):
        rewards = self.viewModel.selectableRewardModel.getRewards()
        with rewards.transaction() as vm:
            vm.clear()
            for rewardName, reward, _, packSize, state in self.__prepareRewardsData(
                    tabName):
                newReward = SelectableRewardItemModel()
                newReward.setType(rewardName)
                newReward.setCount(
                    0 if initial else self._getRewardsInCartCount(rewardName))
                if state != SelectableRewardItemModel.STATE_RECEIVED:
                    newReward.setPackSize(packSize)
                newReward.setStorageCount(reward['storageCount'])
                newReward.setState(state)
                vm.addViewModel(newReward)

    def __prepareRewardsData(self, tabName):
        for rewardName, reward in self.__tabs[tabName]['rewards'].iteritems():
            count = self._getRewardsInCartCount(
                rewardName) + reward['receivedRewards']
            resultSize = 1
            if reward['receivedRewards'] >= reward['limit'] > 0:
                state = SelectableRewardItemModel.STATE_RECEIVED
            elif count >= reward['limit'] > 0 or count >= self.__tabs[tabName][
                    'limit'] or self.__getTotalTabCount(
                        tabName) >= self.__tabs[tabName]['limit']:
                state = SelectableRewardItemModel.STATE_LIMITED
            else:
                state = SelectableRewardItemModel.STATE_NORMAL
            if state != SelectableRewardItemModel.STATE_RECEIVED:
                resultSize = reward['packSize'] * count or reward['packSize']
            yield (rewardName, reward, count, resultSize, state)

    def __fillTabs(self):
        with self.viewModel.selectableRewardModel.transaction() as vm:
            tabs = vm.getTabs()
            tabs.clear()
            for tabName, tabContent in self.__tabs.iteritems():
                newTab = SelectableRewardTabModel()
                newTab.setType(tabName)
                newTab.setCount(tabContent['count'])
                newTab.setLimit(tabContent['limit'])
                tabs.addViewModel(newTab)

    def __processTabs(self):
        for reward in self.__selectableRewards:
            tabType = reward.getType()
            if self.__tabs.get(tabType) is None:
                self.__tabs[tabType] = {}
            tabContent = self.__tabs[tabType]
            tabContent.setdefault('limit', 0)
            tabContent.setdefault('count', 0)
            tabContent.setdefault('rewards', OrderedDict())
            tabContent['limit'] += self._helper.getRemainedChoices(reward)
            tabContent['tooltip'] = self._helper.getTabTooltipData(reward)

        return

    def __processRewards(self):
        for selectableReward in self.__selectableRewards:
            offer = self._helper.getBonusOptions(selectableReward)
            currentTab = self.__tabs[selectableReward.getType()]
            for giftID, gift in offer.iteritems():
                if currentTab.get('rewards') is None:
                    currentTab['rewards'] = {}
                if gift['option'] is None:
                    continue
                rewardName = gift['option'].getLightViewModelData()[0]
                rewardOp = self.__createReward if currentTab['rewards'].get(
                    rewardName) is None else self.__updateReward
                rewardOp(currentTab['rewards'], rewardName, gift, giftID,
                         selectableReward)

            receivedRewards = self._helper.getBonusReceivedOptions(
                selectableReward)
            for receivedReward, receivedRewardCount in receivedRewards:
                rewardName = receivedReward.getLightViewModelData()[0]
                currentTab['rewards'][rewardName][
                    'receivedRewards'] += receivedRewardCount

        return

    def __createReward(self, rewards, rewardName, gift, giftID,
                       selectableReward):
        rewards[rewardName] = {
            'packSize': gift['count'],
            'limit': gift['limit'],
            'storageCount': gift['option'].getInventoryCount(),
            'selectableReward': [(selectableReward, giftID)],
            'receivedRewards': 0,
            'tooltip': self._packer.getToolTip(gift['option'])
        }

    @staticmethod
    def __updateReward(rewards, rewardName, gift, giftID, selectableReward):
        rewards[rewardName]['selectableReward'].append(
            (selectableReward, giftID))
        if rewards[rewardName]['limit'] != 0 or gift['limit'] != 0:
            rewards[rewardName]['limit'] += gift['limit']
        else:
            rewards[rewardName]['limit'] = 0

    def getTooltipData(self, event):
        rewardType = event.getArgument('type')
        tooltips = self.__tabs.get(rewardType, {}).get('tooltip')
        if tooltips:
            return tooltips
        else:
            tooltips = self.__tabs[self.__selectedTab]['rewards'].get(
                rewardType, {}).get('tooltip')
            return tooltips[0] if tooltips else None