示例#1
0
class NamePopupWnd(Window):
    __guid__ = 'form.NamePopupWnd'
    default_width = 240
    default_height = 90
    default_minSize = (default_width, default_height)
    default_windowID = 'setNewName'

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        self.DefineButtons(uiconst.OKCANCEL, okFunc=self.Confirm, cancelFunc=self.Cancel)
        caption = attributes.get('caption', localization.GetByLabel('UI/Common/Name/TypeInName'))
        if caption is None:
            caption = localization.GetByLabel('UI/Common/Name/TypeInName')
        self.SetCaption(caption)
        self.SetTopparentHeight(0)
        self.MakeUnResizeable()
        self.label = attributes.get('label', localization.GetByLabel('UI/Common/Name/TypeInName'))
        if self.label is None:
            self.label = localization.GetByLabel('UI/Common/Name/TypeInName')
        self.setvalue = attributes.get('setvalue', '')
        self.maxLength = attributes.get('maxLength', None)
        self.passwordChar = attributes.get('passwordChar', None)
        self.funcValidator = attributes.validator or self.CheckName
        self.ConstructLayout()

    def ConstructLayout(self):
        cont = uiprimitives.Container(parent=self.sr.main, align=uiconst.TOALL, pos=(const.defaultPadding,
         16,
         const.defaultPadding,
         const.defaultPadding))
        self.newName = SinglelineEdit(name='namePopup', parent=cont, label=self.label, setvalue=self.setvalue, align=uiconst.TOTOP, maxLength=self.maxLength, passwordCharacter=self.passwordChar, autoselect=True, OnReturn=self.Confirm)
        uicore.registry.SetFocus(self.newName)

    def CheckName(self, name, *args):
        name = self.newName.GetValue()
        if not len(name) or len(name) and len(name.strip()) < 1:
            return localization.GetByLabel('UI/Common/PleaseTypeSomething')

    def Confirm(self, *args):
        if not hasattr(self, 'newName'):
            return
        newName = self.newName.GetValue()
        error = self.funcValidator(newName)
        if error:
            eve.Message('CustomInfo', {'info': error})
        else:
            self.result = newName
            self.SetModalResult(1)

    def Cancel(self, *args):
        self.result = None
        self.SetModalResult(0)
示例#2
0
class NameAndDescBaseWnd(Window):
    default_name = 'nameAndDescBaseWnd'
    default_windowID = 'NameAndDescBaseWnd'
    default_width = 200
    default_height = 200
    default_topParentHeight = 0
    confirmLabelPath = ''
    nameLabelPath = ''
    descriptionLabelPath = ''

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        self.MakeUnResizeable()
        self.controller = attributes.controller
        self.btnGroup = ButtonGroup(parent=self.sr.main, idx=0, line=True)
        self.btnGroup.AddButton(GetByLabel(self.confirmLabelPath),
                                self.OnConfirmClicked)
        self.btnGroup.AddButton(GetByLabel('UI/Commands/Cancel'), self.Cancel)
        self.groupNameField = SinglelineEdit(parent=self.sr.main,
                                             align=uiconst.TOTOP,
                                             label=GetByLabel(
                                                 self.nameLabelPath),
                                             padding=4,
                                             top=10,
                                             maxLength=30)
        EveLabelSmall(name='titleHeader',
                      parent=self.sr.main,
                      text=GetByLabel(self.descriptionLabelPath),
                      align=uiconst.TOTOP,
                      top=6,
                      padLeft=4)
        self.groupDescField = EditPlainText(parent=self.sr.main,
                                            padding=(4, 0, 4, 4),
                                            maxLength=200)
        self.PopulateFields()

    def PopulateFields(self):
        pass

    def OnConfirmClicked(self, *args):
        name = self.groupNameField.GetValue().strip()
        desc = self.groupDescField.GetValue().strip()
        if name:
            self.Confirm(name, desc)
            self.CloseByUser()
        else:
            uicore.Message('uiwarning03')

    def Confirm(self, name, desc):
        pass

    def Cancel(self, *args):
        self.CloseByUser()
示例#3
0
class EditWithLabel(Container):
    default_align = uiconst.TOTOP
    default_height = 20
    default_padTop = 8

    def ApplyAttributes(self, attributes):
        Container.ApplyAttributes(self, attributes)
        self.label = EveLabelSmall(text=attributes.text,
                                   parent=self,
                                   state=uiconst.UI_DISABLED,
                                   align=uiconst.CENTERLEFT,
                                   width=LABELWIDTH)
        self.edit = SinglelineEdit(name='passwordEdit',
                                   parent=self,
                                   maxLength=64,
                                   align=uiconst.TOLEFT,
                                   padLeft=LABELWIDTH,
                                   width=140,
                                   setvalue=attributes.value,
                                   OnReturn=attributes.OnReturn,
                                   OnChange=attributes.OnChange,
                                   OnSetFocus=attributes.OnSetFocus)
        self.incorrectFill = GradientSprite(bgParent=self.edit,
                                            opacity=0.0,
                                            rgbData=[(0, (0.55, 0.0, 0.0))],
                                            alphaData=[(0, 0.5), (0.949, 0.75),
                                                       (0.95, 1.0),
                                                       (1.0, 1.0)])

    def GetValue(self, *args, **kwds):
        return self.edit.GetValue(*args, **kwds)

    def SetIncorrect(self):
        uicore.animations.FadeIn(self.incorrectFill)

    def SetCorrect(self):
        uicore.animations.FadeOut(self.incorrectFill)
示例#4
0
class MultiBuy(SellBuyItemsWindow):
    __guid__ = 'form.BuyItems'
    default_iconNum = 'res:/UI/Texture/classes/MultiSell/multiBuy.png'
    default_windowID = 'MultiBuy'
    default_name = 'multiBuy'
    captionTextPath = 'UI/Inventory/ItemActions/MultiBuy'
    scrollId = 'MultiBuyScroll'
    tradeForCorpSettingConfig = 'buyUseCorp'
    tradeTextPath = 'UI/Market/MarketQuote/CommandBuy'
    orderCap = 'MultiBuyOrderCap'
    tradeOnConfirm = False
    dropLabelPath = 'UI/Market/Marketbase/DropItemsToAddToBuy'
    cannotBeTradeLabelPath = 'UI/Market/MarketQuote/CannotBeBought'
    badDeltaWarningPath = 'UI/Market/MarketQuote/MultiBuyTypesAboveAverage'
    corpCheckboxTop = 0
    numbersGridTop = 1
    showTaxAndBrokersFee = False
    belowColor = '<color=0xff00ff00>'
    aboveColor = '<color=0xffff5050>'
    __notifyevents__ = ['OnOwnOrdersChanged', 'OnSessionChanged']

    def ApplyAttributes(self, attributes):
        self.blinkEditBG = None
        SellBuyItemsWindow.ApplyAttributes(self, attributes)
        self.dropCont.OnDropData = self.DropItems
        self.infoCont.height = 40
        self.totalAmt.LoadTooltipPanel = self.LoadTotalTooltip
        self.itemsScroll.OnDropData = self.DropItems
        self.AddImportButton()
        self.DrawStationWarning()
        self.AddToLocationCont()
        self.StartAddItemsThread()

    def InitializeVariables(self, attributes):
        SellBuyItemsWindow.InitializeVariables(self, attributes)
        self.entriesInScrollByTypeID = {}
        self.orderMultiplier = 1
        self.activeOrders = set()
        self.orderDisabled = False
        self.preItems = self.GetKeyValsForWantedTypes(
            attributes.get('wantToBuy'))
        self.reloadingItemsCounter = 0
        self.verifyMultiplierTimer = None
        self.expiredOrders = {}

    def GetKeyValsForWantedTypes(self, wantToBuy):
        keyVals = []
        for typeID, qty in wantToBuy.iteritems():
            keyVals.append(KeyVal(typeID=typeID, qty=qty))

        return keyVals

    def AddToLocationCont(self):
        self.locationCont.height = 28
        self.orderMultiplierEdit = SinglelineEdit(
            name='orderMultiplierEdit',
            parent=self.locationCont,
            align=uiconst.TOPRIGHT,
            label=GetByLabel('UI/Market/MarketQuote/NumberOfOrders'),
            adjustWidth=True,
            ints=[1, 1000],
            left=const.defaultPadding,
            OnChange=self.OnMultiplierEditChange)
        self.stationCombo = Combo(
            parent=self.locationCont,
            callback=self.OnStationChanged,
            left=const.defaultPadding,
            width=200,
            noChoiceLabel=GetByLabel(
                'UI/Market/MarketQuote/NotStationsAvailable'))
        self.LoadStationOptions()

    def AddImportButton(self):
        if boot.region == 'optic':
            return
        self.dropCont.padLeft = 30
        importMenu = UtilMenu(
            menuAlign=uiconst.TOPLEFT,
            parent=self.mainCont,
            align=uiconst.TOPLEFT,
            pos=(4, 0, 28, 28),
            GetUtilMenu=self.GetImportMenu,
            texturePath='res:/UI/Texture/Shared/pasteFrom.png',
            iconSize=28,
            hint=GetByLabel('UI/Market/MarketQuote/ImportShoppingListHint'))

    def GetImportMenu(self, menuParent):
        hint = GetByLabel('UI/Market/MarketQuote/ImportShoppingListOptionHint',
                          type1=const.typeVeldspar,
                          type2=const.typeTritanium)
        menuParent.AddIconEntry(
            icon=ACTION_ICON,
            text=GetByLabel('UI/Market/MarketQuote/ImportShoppingListOption'),
            hint=hint,
            callback=self.ImportShoppingList)

    def ImportShoppingList(self, *args):
        localizedDecimal = eveLocalization.GetDecimalSeparator(
            localization.SYSTEM_LANGUAGE)
        localizedSeparator = eveLocalization.GetThousandSeparator(
            localization.SYSTEM_LANGUAGE)
        multibuyImporter = ImportMultibuy(localizedDecimal, localizedSeparator)
        text = GetClipboardData()
        toAdd, failedLines = multibuyImporter.GetTypesAndQty(text)
        self.AddToOrder(toAdd)
        if failedLines:
            text = '%s<br>' % GetByLabel('UI/SkillQueue/CouldNotReadLines')
            text += '<br>'.join(failedLines)
            eve.Message('CustomInfo', {'info': text}, modal=False)

    def LoadStationOptions(self):
        currentSelection = self.stationCombo.GetValue()
        stations = self.GetStations()
        if currentSelection:
            select = currentSelection
        elif session.stationid2:
            select = session.stationid2
        elif stations:
            select = stations[0][1]
        else:
            select = None
        self.stationCombo.LoadOptions(stations, select)
        self.stationCombo.Confirm()

    def DrawStationWarning(self):
        self.stationWarning = EveLabelLargeBold(parent=self.bottomLeft,
                                                text='',
                                                align=uiconst.CENTERBOTTOM)
        self.stationWarning.SetRGB(*COL_RED)
        self.stationWarning.display = False

    def AddToOrder(self, wantToBuy):
        wantedTypes = self.GetKeyValsForWantedTypes(wantToBuy)
        self.AddPreItems(wantedTypes)

    def AddPreItems(self, preItems):
        self.reloadingItemsCounter += 1
        items = self.CheckOrderAvailability(preItems)
        self.ClearErrorLists()
        for item in items:
            self.AddItem(item)

        self.DisplayErrorHints()
        self.reloadingItemsCounter -= 1

    def AddItem(self, itemKeyVal):
        if not self.IsBuyable(itemKeyVal):
            return
        existingEntry = self.entriesInScrollByTypeID.get(
            itemKeyVal.typeID, None)
        if existingEntry and not existingEntry.destroyed:
            existingEntry.AddQtyToEntry(itemKeyVal.qty)
        else:
            self.DoAddItem(itemKeyVal)

    def AddItemToCollection(self, itemKeyVal, itemEntry):
        self.entriesInScrollByTypeID[itemKeyVal.typeID] = itemEntry

    def GetItemEntry(self, itemKeyVal):
        itemEntry = BuyItemContainer(typeID=itemKeyVal.typeID,
                                     qty=int(itemKeyVal.qty),
                                     parentFunc=self.RemoveItem,
                                     editFunc=self.OnEntryEdit,
                                     stationID=self.baseStationID,
                                     orderMultiplier=self.orderMultiplier,
                                     dropParentFunc=self.DropItems)
        return itemEntry

    def PerformTrade(self, *args):
        useCorp = self.TradingForCorp()
        buyItemList, failedItems = self.GetValidatedAndFailedTypes()
        if not len(buyItemList):
            uicore.Message('uiwarning03')
            return
        if not self.ContinueAfterWarning(buyItemList):
            return
        with ExceptionEater():
            self.LogBuy(buyItemList)
        ordersCreated = sm.GetService('marketQuote').BuyMulti(
            self.baseStationID, buyItemList, useCorp)
        orderIDs = {order.orderID for order in ordersCreated}
        self.activeOrders.update(orderIDs)
        self.CreateNewBuyOrder(failedItems)
        self.VerifyExpiredOrders()

    def GetItemsWithBadDelta(self, buyItemList):
        highItems = []
        for item in buyItemList:
            if item.delta > 1.0:
                highItems.append((item.delta, item))

        return highItems

    def GetOrderDeltaTextForWarning(self):
        orderPercentage = self.GetOrderDelta()
        orderText = ''
        if orderPercentage > 1.0:
            percText = GetByLabel('UI/Common/Percentage',
                                  percentage=FmtAmt(abs(orderPercentage * 100),
                                                    showFraction=0))
            orderText = GetByLabel(
                'UI/Market/MarketQuote/MultiBuyAboveAverage',
                percentage=percText)
        return orderText

    def GetValidatedAndFailedTypes(self):
        allItems = self.GetItems()
        failedItemsList = []
        buyItemsList = []
        for item in allItems:
            if item.isUpdating:
                return ([], [])
            if item.newBestPrice:
                validatedItem = self.GetValidatedItem(item)
                if validatedItem:
                    buyItemsList.append(validatedItem)
                    continue
            failedBuyInfo = KeyVal(typeID=item.typeID, qty=item.GetTotalQty())
            failedItemsList.append(failedBuyInfo)

        return (buyItemsList, failedItemsList)

    def GetValidatedItem(self, item):
        if item.isUpdating:
            return
        price = item.GetPrice()
        if not price:
            return
        if price > self.MAX_PRICE:
            return
        price = round(price, 2)
        qty = item.GetTotalQty()
        if qty < 1:
            return
        validatedItem = GetBuyItemInfo(stationID=session.stationid
                                       or session.structureid,
                                       typeID=item.typeID,
                                       price=price,
                                       quantity=qty,
                                       minVolume=1,
                                       delta=item.GetDelta())
        return validatedItem

    def CreateNewBuyOrder(self, failedItems):
        self.ChangeOrderUIState(disable=True)
        self.RemoveAllItem()
        if self.orderMultiplierEdit.GetValue() != 1:
            self.BlinkNumOrdersEdit()
        self.orderMultiplierEdit.SetValue(1)
        if failedItems:
            self.AddPreItems(failedItems)

    def ChangeOrderUIState(self, disable):
        if disable:
            opacity = 0.5
        else:
            opacity = 1.0
        mainArea = self.GetMainArea()
        mainArea.opacity = opacity
        self.orderDisabled = disable

    def GetStations(self):
        solarsytemItems = sm.GetService('map').GetSolarsystemItems(
            session.solarsystemid2, True, False)
        stations = {
            i
            for i in solarsytemItems if i.groupID == const.groupStation
        }
        currentStation = session.stationid2 or session.structureid
        stationList = []
        for eachStation in stations:
            if eachStation.itemID == currentStation:
                continue
            sortValue = (eachStation.celestialIndex, eachStation.orbitIndex,
                         eachStation.itemName)
            stationList.append(
                (sortValue, (eachStation.itemName, eachStation.itemID)))

        stationList = SortListOfTuples(stationList)
        if currentStation:
            stationName = cfg.evelocations.Get(currentStation).name
            currentStationOption = (GetByLabel(
                'UI/Market/MarketQuote/CurrentStation',
                stationName=stationName), currentStation)
            stationList = [currentStationOption] + stationList
        return stationList

    def RemoveItemFromCollection(self, itemEntry):
        self.entriesInScrollByTypeID.pop(itemEntry.typeID, None)

    def OnMultiplierEditChange(self, *args):
        self.UpdateOrderMultiplierInEntries()
        if self.verifyMultiplierTimer:
            self.verifyMultiplierTimer.KillTimer()
        self.verifyMultiplierTimer = AutoTimer(
            2000, self.VerifyOrderMultiplier_thread)

    def UpdateOrderMultiplierInEntries(self, force=True):
        self.orderMultiplier = self.orderMultiplierEdit.GetValue()
        for item in self.GetItemsIterator():
            if force or item.orderMultiplier != self.orderMultiplier:
                item.UpdateOrderMultiplier(self.orderMultiplier)

    def VerifyOrderMultiplier_thread(self):
        self.verifyMultiplierTimer = None
        self.UpdateOrderMultiplierInEntries(force=False)

    def OnEntryEdit(self, *args):
        uthread.new(self.UpdateNumbers)

    def UpdateNumbers(self):
        totalShown = self.GetSum()
        if totalShown >= MILLION:
            totalAmtText = '%s (%s)' % (FmtISK(totalShown),
                                        FmtISKWithDescription(totalShown,
                                                              justDesc=True))
        else:
            totalAmtText = FmtISK(totalShown)
        self.totalAmt.text = totalAmtText
        self.totalAmt.SetRGB(*COL_RED)
        self.ShowOrHideStationWarning()

    def ShowOrHideStationWarning(self):
        currentStation = session.stationid2 or session.structureid
        if self.baseStationID is None:
            self.stationWarning.text = GetByLabel(
                'UI/Market/MarketQuote/NoStationSelected')
            self.stationWarning.display = True
        elif self.baseStationID == currentStation:
            self.stationWarning.display = False
        else:
            self.stationWarning.text = GetByLabel(
                'UI/Market/MarketQuote/StationWarning')
            self.stationWarning.display = True

    def GetSum(self):
        totalSum = 0
        for item in self.GetItemsIterator():
            totalSum += item.GetTotalSum()

        return totalSum

    def LoadTotalTooltip(self, tooltipPanel, *args):
        totalShown = self.GetSum()
        if not totalShown or not self.orderMultiplier:
            return
        numTypes, numAvailableTypes = self.GetNumTypesAndNumAvailableTypes()
        pricePerOrder = totalShown / float(self.orderMultiplier)
        tooltipPanel.LoadGeneric2ColumnTemplate()
        tooltipPanel.cellPadding = (4, 1, 4, 1)
        tooltipPanel.AddLabelMedium(
            text=GetByLabel('UI/Market/MarketQuote/NumOrders'))
        tooltipPanel.AddLabelMedium(text=FmtAmt(self.orderMultiplier),
                                    align=uiconst.CENTERRIGHT)
        tooltipPanel.AddLabelMedium(
            text=GetByLabel('UI/Market/MarketQuote/PricePerOrder'))
        tooltipPanel.AddLabelMedium(text=FmtISK(pricePerOrder),
                                    align=uiconst.CENTERRIGHT)
        if pricePerOrder >= MILLION:
            tooltipPanel.AddCell()
            tooltipPanel.AddLabelMedium(
                text='=%s' %
                FmtISKWithDescription(pricePerOrder, justDesc=True),
                align=uiconst.CENTERRIGHT)
        buyingText = GetByLabel(
            'UI/Market/MarketQuote/TypesAvailableAndTotalInOrder',
            numAvailable=numAvailableTypes,
            numTypes=numTypes)
        buyingLabel = tooltipPanel.AddLabelSmall(text=buyingText,
                                                 align=uiconst.CENTERRIGHT,
                                                 colSpan=tooltipPanel.columns)
        buyingLabel.SetAlpha(0.6)
        tooltipPanel.AddSpacer(1, 8, colSpan=tooltipPanel.columns)
        deltaText = self.GetOrderDeltaText()
        tooltipPanel.AddLabelMedium(text=deltaText,
                                    colSpan=tooltipPanel.columns)

    def GetOrderDelta(self):
        totalPrice = sum(
            (i.GetTotalSum() for i in self.GetItemsIterator(onlyValid=True)))
        change = 0
        for item in self.GetItemsIterator(onlyValid=True):
            price = item.GetTotalSum()
            qty = item.GetTotalQty()
            avgPriceForQty = qty * item.averagePrice
            change += (price -
                       avgPriceForQty) / avgPriceForQty * price / totalPrice

        return change

    def GetOrderDeltaText(self):
        percentage = self.GetOrderDelta()
        if percentage == 0:
            return ''
        if percentage < 0:
            percColor = self.belowColor
            devLabelPath = 'UI/Market/MarketQuote/BelowRegionalAverageWithPercentage'
        else:
            percColor = self.aboveColor
            devLabelPath = 'UI/Market/MarketQuote/AboveRegionalAverageWithPercentage'
        percentage = abs(percentage)
        percentageText = FmtAmt(percentage * 100, showFraction=1)
        percText = '%s%s</color>' % (percColor,
                                     GetByLabel('UI/Common/Percentage',
                                                percentage=percentageText))
        return GetByLabel(devLabelPath, percentage=percText)

    def GetNumTypesAndNumAvailableTypes(self):
        numTypes = 0
        numAvailableTypes = 0
        for item in self.GetItemsIterator():
            numTypes += 1
            if item.GetPrice():
                numAvailableTypes += 1

        return (numTypes, numAvailableTypes)

    def DropItems(self, dragObj, nodes):
        if dragObj is None:
            return
        items = self.CheckOrderAvailability(nodes)
        self.ClearErrorLists()
        for node in items:
            typeID = GetTypeIDFromDragItem(node)
            if typeID:
                self.AddItem(KeyVal(typeID=typeID, qty=1))

        self.DisplayErrorHints()

    def GetTypeIDFromDragItem(self, node):
        return GetTypeIDFromDragItem(node)

    def OnStationChanged(self, combo, key, value):
        self.baseStationID = value
        self.UpdateStationID()

    def UpdateStationID(self):
        for item in self.GetItemsIterator():
            item.UpdateStationID(self.baseStationID)

        self.UpdateHeaderCount()
        self.UpdateNumbers()

    def OnOwnOrdersChanged(self, orders, reason, isCorp):
        if reason != 'Expiry':
            return
        orderIDs = set()
        for eachOrder in orders:
            self.expiredOrders[eachOrder.orderID] = eachOrder
            orderIDs.add(eachOrder.orderID)

        self._ProccessExpiredOrders(orderIDs)

    def _ProccessExpiredOrders(self, orderIDs):
        failedItems = []
        for eachOrderID in orderIDs:
            if eachOrderID not in self.activeOrders:
                continue
            eachOrder = self.expiredOrders.get(eachOrderID, None)
            if eachOrder and eachOrder.volRemaining != 0:
                failedBuyInfo = KeyVal(typeID=eachOrder.typeID,
                                       qty=eachOrder.volRemaining)
                failedItems.append(failedBuyInfo)
            self.activeOrders.discard(eachOrderID)

        if failedItems:
            self.AddPreItems(failedItems)
        if not failedItems and not self.AreStillItemsInWindow():
            self.Close()
            return
        if self.orderDisabled and not self.activeOrders:
            self.ChangeOrderUIState(disable=False)

    def VerifyExpiredOrders(self):
        expiredOrders = set(self.expiredOrders.keys())
        expiredOrdersNotProcessed = self.activeOrders.intersection(
            expiredOrders)
        if expiredOrdersNotProcessed:
            self._ProccessExpiredOrders(expiredOrdersNotProcessed)

    def AreStillItemsInWindow(self):
        if self.activeOrders:
            return True
        if self.reloadingItemsCounter > 0:
            return True
        if self.itemList:
            return True
        return False

    def RemoveAllItem(self):
        self.itemsScroll.Flush()
        self.itemList = []
        self.entriesInScrollByTypeID = {}
        self.UpdateNumbers()
        self.UpdateHeaderCount()
        self.ClearErrorLists()

    def OnSessionChanged(self, isRemote, session, change):
        if 'solarsystemid2' in change or 'stationid2' in change:
            self.LoadStationOptions()

    def IsBuyable(self, itemKeyVal):
        buyable = True
        if evetypes.GetMarketGroupID(itemKeyVal.typeID) is None:
            self.cannotTradeItemList.append(itemKeyVal)
            buyable = False
        return buyable

    def BlinkNumOrdersEdit(self):
        self.ConstructBlinkBG()
        uicore.animations.FadeTo(self.blinkEditBG,
                                 0.0,
                                 0.5,
                                 duration=0.5,
                                 curveType=uiconst.ANIM_WAVE,
                                 loops=2)

    def ConstructBlinkBG(self):
        if self.blinkEditBG is None:
            self.blinkEditBG = Sprite(
                name='blinkEditBG',
                bgParent=self.orderMultiplierEdit,
                align=uiconst.TOALL,
                state=uiconst.UI_DISABLED,
                texturePath='res:/UI/Texture/classes/InvItem/bgSelected.png',
                opacity=0.0,
                idx=0)

    def LogBuy(self, buyItemList):
        totalDisplayed = self.totalAmt.text
        totalSum = self.GetSum()
        multiplier = self.orderMultiplierEdit.GetValue()
        buyTextList = []
        for eachItem in buyItemList:
            text = '[typeID=%s, price=%s, qty=%s]' % (
                eachItem.typeID, eachItem.price, eachItem.quantity)
            buyTextList.append(text)

        buyText = ','.join(buyTextList)
        logInfo = 'Multibuy: totalDisplayed=%s, totalSum=%s, multiplier=%s, buyText=%s' % (
            totalDisplayed, totalSum, multiplier, buyText)
        log.LogNotice(logInfo)

    def Close(self, *args, **kwds):
        self.verifyMultiplierTimer = None
        return SellBuyItemsWindow.Close(self, *args, **kwds)

    def DisplayErrorHints(self):
        hintTextList = self.GetErrorHints()
        if hintTextList:
            hintText = '<br>'.join(hintTextList)
            eve.Message('CustomInfo', {'info': hintText})
class AuctionEntry(BaseTeamEntry):
    default_name = 'AuctionEntry'

    def ApplyAttributes(self, attributes):
        BaseTeamEntry.ApplyAttributes(self, attributes)
        self.auctionCost = self.node.auctionCost
        self.AddColumnAuction()
        self.pathFinder = sm.GetService('clientPathfinderService')
        self.teamHandlerClient = sm.GetService('industryTeamSvc')
        self.minAmount = 0

    def AddColumnAuction(self):
        col = self.AddColumnContainer()
        col.OnMouseEnter = self.OnMouseEnter
        col.OnMouseExit = self.OnMouseExit
        col.OnClick = self.OnClick
        col.state = uiconst.UI_NORMAL
        col.GetMenu = self.GetMenu
        col.LoadTooltipPanel = self.LoadAuctionHintPanel
        bidCont = Container(parent=col, align=uiconst.TORIGHT, width=50)
        costCont = Container(parent=col, align=uiconst.TOALL, clipChildren=True)
        costText = FmtISK(self.auctionCost, 0)
        self.costLabel = EveLabelMedium(text=costText, parent=costCont, align=uiconst.CENTERLEFT, left=6)
        self.bidUtilMenu = UtilMenu(menuAlign=uiconst.TOPRIGHT, align=uiconst.CENTERLEFT, parent=bidCont, GetUtilMenu=self.BidOnTeamMenu, texturePath='res:/UI/Texture/Icons/73_16_50.png', left=2, label=GetByLabel('UI/Industry/Bid'))
        bidCont.width = self.bidUtilMenu.width + 10
        self.bidUtilMenu.hint = GetByLabel('UI/Industry/BidBtnHint')

    def BidOnTeamMenu(self, menuParent):
        cont = menuParent.AddContainer(align=uiconst.TOTOP, padding=const.defaultPadding)
        cont.GetEntryWidth = lambda mc = cont: 300
        topCont = Container(parent=cont, height=20, align=uiconst.TOTOP)
        self.searchCont = Container(parent=topCont)
        self.resultCont = Container(parent=topCont)
        self.resultCont.display = False
        self.systemLabel = EveLabelMediumBold(parent=self.resultCont, left=2, top=4)
        self.searchEdit = SinglelineEdit(parent=self.searchCont, align=uiconst.TOALL, hinttext=GetByLabel('UI/Industry/SearchForSystem'), width=0, top=0)
        self.searchEdit.OnReturn = lambda *args: self.SearchForLocation(self.searchEdit, *args)
        self.searchEdit.OnTab = lambda *args: self.SearchForLocation(self.searchEdit, *args)
        self.searchEdit.displayHistory = False
        ButtonIcon(parent=self.resultCont, align=uiconst.CENTERRIGHT, width=16, iconSize=16, texturePath='res:/UI/Texture/Icons/73_16_210.png', hint=GetByLabel('UI/Inventory/Clear'), func=self.ClearSystemSearch)
        self.resultScroll = Scroll(parent=cont, id='ResultScroll', align=uiconst.TOTOP, height=70)
        self.resultScroll.display = False
        Container(parent=cont, height=8, align=uiconst.TOTOP)
        self.bidHint = EveLabelMedium(parent=cont, align=uiconst.TOTOP, padding=(2, 4, 2, 4))
        bottomCont = Container(parent=cont, height=20, align=uiconst.TOTOP, padBottom=4)
        self.bidButton = Button(parent=bottomCont, label=GetByLabel('UI/Industry/Bid'), align=uiconst.TORIGHT, func=self.BidOnTeam)
        self.bidButton.OnMouseHover = self.BidHint
        self.bidButton.Disable()
        self.bidAmountEdit = SinglelineEdit(parent=bottomCont, align=uiconst.TOALL, width=0, floats=[0, 100000000000L, 0], padRight=4, top=0, hinttext='Enter amount')
        self.bidAmountEdit.OnReturn = self.BidOnTeam

    def BidHint(self):
        if self.bidButton.disabled:
            if self.searchEdit.GetValue():
                self.bidButton.hint = GetByLabel('UI/Industry/BidBtnSearchHint')
        else:
            self.bidButton.hint = ''

    def BidOnTeam(self, *args):
        if not self.searchedSystem:
            return
        if self.IsUnreachable():
            self.bidAmountEdit.SetValue('')
            self.bidHint.text = GetByLabel('UI/Industry/UnreachableSystem')
            return
        amount = self.bidAmountEdit.GetValue()
        if not self.HasSolarSystemBidForAuctionID() and amount <= self.minAmount:
            self.bidAmountEdit.SetValue('')
            self.bidHint.text = GetByLabel('UI/Industry/TeamBidTooLow', minAmount=FmtAmt(self.minAmount, showFraction=0))
            return
        self.teamHandlerClient.BidOnTeam(self.team.teamID, self.searchedSystem, amount)
        self.costLabel.text = self.GetForcedAuctionCost()
        self.bidUtilMenu.CloseMenu()

    def SearchForLocation(self, edit, *args):
        searchText = edit.GetValue()
        if not searchText or searchText == '':
            return
        groupIDList = [const.searchResultSolarSystem, const.searchResultWormHoles]
        searchResult = QuickSearch(searchText.strip(), groupIDList)
        noOfResults = len(searchResult)
        if noOfResults == 1:
            self.ConfirmSystem(searchResult[0])
        elif noOfResults:
            self.resultScroll.display = True
            scrollList = self.GetScrollList(searchResult)
            self.resultScroll.LoadContent(contentList=scrollList)
        else:
            edit.SetHintText(GetByLabel('UI/Station/BountyOffice/NoOneFound'))

    def LoadAuctionHintPanel(self, tooltipPanel, *args):
        tooltipPanel.LoadGeneric3ColumnTemplate()
        tooltipPanel.AddLabelLarge(text=GetByLabel('UI/Industry/SystemBidList'), colSpan=tooltipPanel.columns, align=uiconst.CENTER)
        tooltipPanel.AddSpacer(colSpan=tooltipPanel.columns, width=0, height=2)
        topSystems = self.GetTopSystems()
        if topSystems:
            for i, (amount, solarSystemID) in enumerate(topSystems):
                if i > 2:
                    break
                systemName = self.FormatSystemName(solarSystemID)
                systemLabel = '%i %s' % (i + 1, systemName)
                tooltipPanel.AddLabelSmall(text=systemLabel, colSpan=1)
                tooltipPanel.AddSpacer(width=10, height=0)
                tooltipPanel.AddLabelSmall(text=FmtISK(amount, 0), colSpan=1, align=uiconst.TORIGHT)

        myBids = self.GetMyBids()
        if myBids:
            tooltipPanel.AddSpacer(colSpan=tooltipPanel.columns, width=0, height=6)
            tooltipPanel.AddLabelLarge(text=GetByLabel('UI/Industry/MyBidList'), colSpan=tooltipPanel.columns, align=uiconst.CENTER)
            tooltipPanel.AddSpacer(colSpan=tooltipPanel.columns, width=0, height=2)
            for solarSystemID, amount in myBids:
                systemName = self.FormatSystemName(solarSystemID)
                tooltipPanel.AddLabelSmall(text=systemName, colSpan=1)
                tooltipPanel.AddSpacer(width=10, height=0)
                tooltipPanel.AddLabelSmall(text=FmtISK(amount, 0), colSpan=1, align=uiconst.TORIGHT)

    def GetTopSystems(self):
        bids = self.GetBids()
        return bids.GetRankedBids()

    def GetMyBids(self):
        bids = self.GetBids()
        myBids = GetMyBidsBySolarSystem(session.charid, bids)
        if myBids:
            return sorted(myBids.iteritems(), key=itemgetter(1), reverse=True)

    def GetScrollList(self, results):
        scrollList = []
        for solarSystemID in results:
            data = util.KeyVal()
            data.label = self.FormatSystemName(solarSystemID)
            data.OnDblClick = self.DblClickEntry
            data.solarSystemID = solarSystemID
            entry = listentry.Get('Generic', data)
            scrollList.append(entry)

        return scrollList

    def FormatSystemName(self, solarSystemID):
        systemName = cfg.evelocations.Get(solarSystemID).name
        secStatus = self.GetSecurityLabel(solarSystemID)
        return '%s %s' % (systemName, secStatus)

    def DblClickEntry(self, entry, *args):
        solarSystemID = entry.sr.node.solarSystemID
        if solarSystemID:
            self.ConfirmSystem(solarSystemID)

    def ConfirmSystem(self, solarSystemID):
        self.resultScroll.display = False
        self.searchCont.display = False
        self.resultCont.display = True
        self.searchEdit.SetValue('')
        self.searchedSystem = solarSystemID
        self.systemLabel.text = self.FormatSystemName(solarSystemID)
        if self.IsUnreachable():
            self.bidHint.text = GetByLabel('UI/Industry/UnreachableSystem')
        elif not self.HasSolarSystemBidForAuctionID():
            self.minAmount = GetDistanceCost(self.pathFinder, self.team.solarSystemID, solarSystemID)
            self.bidHint.text = GetByLabel('UI/Industry/TeamMinBid', minAmount=FmtAmt(self.minAmount, showFraction=0))
        self.bidButton.Enable()
        uicore.registry.SetFocus(self.bidAmountEdit)

    def ClearSystemSearch(self, *args):
        self.searchedSystem = None
        self.resultCont.display = False
        self.systemLabel.text = ''
        self.bidHint.text = ''
        self.bidHint.height = 0
        self.searchCont.display = True
        self.bidButton.Disable()

    def GetForcedAuctionCost(self):
        return FmtISK(GetHighestBid(self.GetBids()), 0)

    def HasSolarSystemBidForAuctionID(self):
        return self.teamHandlerClient.HasSolarSystemBidForAuctionID(self.team.teamID, self.searchedSystem)

    def IsUnreachable(self):
        return bool(not util.IsWormholeSystem(self.searchedSystem) and self.pathFinder.GetJumpCount(self.team.solarSystemID, self.searchedSystem) > 1000)

    @staticmethod
    def GetDefaultColumnWidth():
        return {GetByLabel('UI/Industry/Team'): 160,
         GetByLabel('UI/Common/LocationTypes/System'): 80,
         GetByLabel('UI/Common/Jumps'): 50,
         GetByLabel('UI/Common/Security'): 55,
         GetByLabel('UI/Industry/Bonuses'): 310,
         GetByLabel('UI/Industry/Salary'): 50,
         GetByLabel('UI/Industry/AuctionEnds'): 110,
         GetByLabel('UI/Industry/Auction'): 110}

    @staticmethod
    def GetHeaders():
        return (GetByLabel('UI/Industry/Team'),
         GetByLabel('UI/Common/LocationTypes/System'),
         GetByLabel('UI/Common/Jumps'),
         GetByLabel('UI/Common/Security'),
         GetByLabel('UI/Industry/Activity'),
         GetByLabel('UI/Industry/Bonuses'),
         GetByLabel('UI/Industry/Salary'),
         GetByLabel('UI/Industry/AuctionEnds'),
         GetByLabel('UI/Industry/Auction'))

    @staticmethod
    def GetColumnSortValues(teamData, teamName, bonusSum, expiryTime, teamCost, auctionCost):
        return (teamName,
         cfg.evelocations.Get(teamData.team.solarSystemID).name,
         sm.GetService('clientPathfinderService').GetJumpCountFromCurrent(teamData.team.solarSystemID),
         sm.GetService('map').GetSecurityStatus(teamData.team.solarSystemID),
         teamData.team.activity,
         bonusSum,
         teamCost,
         expiryTime,
         auctionCost)

    def GetBids(self):
        return self.teamHandlerClient.GetBids(self.team.teamID)

    def GetQAMenu(self):
        return [['QA: Expire Auction', self.GMExpireAuction, [self.team.teamID]], ['QA: Print Bids', self.ShowBids, []], ['QA: Set Expiry time', self.SetExpiryTime]]

    def SetExpiryTime(self):
        ret = uiutil.NamePopup(caption='Set Expiry Time', label='Type in Expiry Time', setvalue=util.FmtDate(self.node.expiryTime))
        if ret is None:
            return
        newTime = util.ParseDateTime(ret)
        self.teamHandlerClient.GMSetAuctionExpiryTime(self.team.teamID, newTime)
示例#6
0
class SearchCont(Container):
    def ApplyAttributes(self, attributes):
        Container.ApplyAttributes(self, attributes)
        self.controller = attributes.controller
        searchWidth, rotation = self.GetWidthAndRotation()
        texturePath = 'res:/UI/Texture/WindowIcons/peopleandplaces.png'
        searchIconHint = GetByLabel(
            'UI/Structures/AccessGroups/SearchButtonHint')
        self.searchIcon = ButtonIcon(name='searchIcon',
                                     parent=self,
                                     align=uiconst.CENTERRIGHT,
                                     pos=(2, 0, 24, 24),
                                     iconSize=24,
                                     texturePath=texturePath,
                                     func=self.OnSearchBtnClicked,
                                     hint=searchIconHint)
        arrowTexturePath = 'res:/UI/Texture/Icons/1_16_99.png'
        self.arrowCont = Transform(name='arrowCont',
                                   parent=self,
                                   pos=(24, 0, 16, 16),
                                   align=uiconst.CENTERRIGHT,
                                   rotation=rotation)
        self.expandArrow = ButtonIcon(name='expandArrow',
                                      parent=self.arrowCont,
                                      pos=(0, 0, 16, 16),
                                      iconSize=16,
                                      texturePath=arrowTexturePath,
                                      func=self.OnExpanderClicked)
        hintText = GetByLabel('UI/Structures/AccessGroups/SearchFieldHint')
        self.searchField = SinglelineEdit(parent=self,
                                          align=uiconst.CENTERRIGHT,
                                          pos=(40, 0, searchWidth, 0),
                                          OnReturn=self.DoSearch,
                                          hinttext=hintText,
                                          isCharCorpOrAllianceField=True)
        self.searchField.OnClearButtonClick = self.OnClearingSearchField
        self.searchField.ShowClearButton(hint=GetByLabel('UI/Inventory/Clear'))
        self.memberNamesByMemberID = {}
        self.height = max(self.searchField.height, self.searchIcon.height)
        self.width = self.searchField.left + EXPANDED_SEARCH_WIDTH + 10

    def OnSearchBtnClicked(self, *args):
        if settings.user.ui.Get('accessGroup_searchExpanded', False):
            self.DoSearch()
        else:
            self.OnExpanderClicked()

    def OnExpanderClicked(self, *args):
        isExpandedNow = settings.user.ui.Get('accessGroup_searchExpanded',
                                             False)
        settings.user.ui.Set('accessGroup_searchExpanded', not isExpandedNow)
        newWidth, newRotation = self.GetWidthAndRotation()
        uicore.animations.MorphScalar(self.arrowCont,
                                      'rotation',
                                      self.arrowCont.rotation,
                                      newRotation,
                                      duration=0.35)
        uicore.animations.MorphScalar(self.searchField,
                                      'width',
                                      startVal=self.searchField.width,
                                      endVal=newWidth,
                                      duration=0.35)
        if not isExpandedNow:
            self.PrimeMembers()

    def GetWidthAndRotation(self):
        if settings.user.ui.Get('accessGroup_searchExpanded', False):
            return (EXPANDED_SEARCH_WIDTH, math.pi)
        return (0, 0)

    def DoSearch(self, *args):
        searchString = self.searchField.GetValue().lower()
        if len(searchString) < 3:
            self.controller.SetCurrentSearchResults(None)
            return
        allMemberInfo = self.PrimeMembers()
        groupsWithMatchedMembers = set()
        matchedMembers = set()
        for groupID, membersDict in allMemberInfo.iteritems():
            for eachMemberID in membersDict.iterkeys():
                memberName = self.GetMemberName(eachMemberID)
                if memberName.find(searchString) > -1:
                    groupsWithMatchedMembers.add(groupID)
                    matchedMembers.add(eachMemberID)

        searchResults = (matchedMembers, groupsWithMatchedMembers)
        self.controller.SetCurrentSearchResults(searchResults)

    def PrimeMembers(self):
        allMemberInfo, allMemberIDs = self.controller.GetAllMyMemberIDs()
        cfg.eveowners.Prime(allMemberIDs)
        return allMemberInfo

    def GetMemberName(self, memberID):
        memberName = self.memberNamesByMemberID.get(memberID)
        if memberName:
            return memberName
        memberName = cfg.eveowners.Get(memberID).name.lower()
        self.memberNamesByMemberID[memberID] = memberName
        return memberName

    def OnClearingSearchField(self):
        SinglelineEdit.OnClearButtonClick(self.searchField)
        self.DoSearch()
示例#7
0
class MultiFitWnd(Window):
    __guid__ = 'form.MultiFitWnd'
    __notifyevents__ = ['OnSessionChanged']
    default_topParentHeight = 70
    default_height = 400
    default_width = 320
    default_windowID = 'multiFitWnd'
    default_captionLabelPath = 'UI/Fitting/FittingWindow/FittingManagement/MultiFitHeader'
    layoutColumns = 3

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        self.fitting = None
        self.MakeUnResizeable()
        self.MakeUnstackable()
        self.canFitNum = 0
        self.tryingToFitNum = 1
        self.currentProgress = 0
        self.ConstructUI()
        fitting = attributes.fitting
        self.tryingToFitNum = attributes.get('qty', 1)
        self.LoadWindow(fitting, self.tryingToFitNum)
        self.SetInventoryStatus()
        sm.RegisterNotify(self)

    def ConstructUI(self):
        self.BuildTopParentUI()
        self.AddButtons()
        numColumns = 2
        self.layoutGrid = layoutGrid = LayoutGrid(parent=self.sr.main,
                                                  columns=numColumns,
                                                  cellSpacing=(4, 10))
        spacer = Container(pos=(0, 0, 50, 0), align=uiconst.TOPLEFT)
        layoutGrid.AddCell(cellObject=spacer, colSpan=1)
        layoutGrid.FillRow()
        self.BuildNumToFitUI()
        self.BuildWarningUI()
        self.BuildRefreshInventory()
        self.missingLayoutGrid = LayoutGrid(parent=self.layoutGrid,
                                            columns=2,
                                            cellSpacing=(4, 10))
        self.BuildAvailableShipsUI()
        self.BuildEquipmentUI()
        self.BuildProgressUI()
        self.MakeRigCbUI()

    def BuildTopParentUI(self):
        self.sr.topParent.padding = (2 * const.defaultPadding, 0,
                                     2 * const.defaultPadding, 0)
        self.shipIcon = Icon(name='shipIcon',
                             parent=self.sr.topParent,
                             state=uiconst.UI_NORMAL,
                             size=64,
                             ignoreSize=True)
        self.shipIcon.GetDragData = self.GetFittingDragData
        self.shipIcon.OnClick = self.OpenFitting
        self.shipIcon.hint = GetByLabel('UI/Fitting/ShowFitting')
        self.techSprite = Sprite(name='techIcon',
                                 parent=self.sr.topParent,
                                 align=uiconst.RELATIVE,
                                 width=16,
                                 height=16,
                                 idx=0)
        self.fitNameEdit = SinglelineEdit(
            name='fitNameEdit',
            parent=self.sr.topParent,
            left=72,
            width=150,
            maxLength=20,
            hint=GetByLabel('UI/Common/ShipName'))
        top = self.fitNameEdit.top + self.fitNameEdit.height + 5
        self.shipNameLabel = EveLabelMedium(name='shipNameLabel',
                                            parent=self.sr.topParent,
                                            left=77,
                                            top=top,
                                            state=uiconst.UI_NORMAL)

    def AddButtons(self):
        btnCont = FlowContainer(name='buttonParent',
                                parent=self.sr.main,
                                align=uiconst.TOBOTTOM,
                                padding=6,
                                autoHeight=True,
                                centerContent=True,
                                contentSpacing=uiconst.BUTTONGROUPMARGIN,
                                idx=0)
        text = GetByLabel(
            'UI/Fitting/FittingWindow/FittingManagement/FitShips', numToFit=1)
        self.fitBtn = Button(parent=btnCont,
                             label=text,
                             func=self.DoFitShips,
                             align=uiconst.NOALIGN)
        self.cancelBtn = Button(parent=btnCont,
                                label=GetByLabel('UI/Commands/Cancel'),
                                func=self.Cancel,
                                align=uiconst.NOALIGN)

    def BuildNumToFitUI(self):
        maxShipsAllowed = int(
            sm.GetService('machoNet').GetGlobalConfig().get(
                'bulkFit_maxShips', 30))
        numCont = Container(name='numCont',
                            align=uiconst.TOTOP,
                            height=30,
                            padLeft=LEFT_EDGE)
        text = GetByLabel(
            'UI/Fitting/FittingWindow/FittingManagement/NumShipsToFit')
        self.numToFitLabel = EveLabelLarge(name='numToFitLabel',
                                           parent=numCont,
                                           text=text,
                                           width=250,
                                           autoFitToText=True)
        left = self.numToFitLabel.left + self.numToFitLabel.textwidth + 10
        self.numToFitEdit = SinglelineEdit(name='numToFitEdit',
                                           parent=numCont,
                                           ints=[1, maxShipsAllowed],
                                           OnChange=self.OnNumChanged,
                                           left=left,
                                           align=uiconst.CENTERLEFT)
        numCont.height = max(self.numToFitLabel.textheight,
                             self.numToFitEdit.height)
        self.layoutGrid.AddCell(cellObject=numCont,
                                colSpan=self.layoutGrid.columns)

    def BuildWarningUI(self):
        self.numWarningLabel = EveCaptionSmall(name='numWarningLabel',
                                               state=uiconst.UI_NORMAL,
                                               align=uiconst.CENTERTOP,
                                               width=MAX_TEXT_WIDTH,
                                               autoFitToText=True)
        self.numWarningLabel.SetRGBA(*WARNING_COLOR)
        self.numWarningLabel.LoadTooltipPanel = self.LoadMissingTooltip
        self.layoutGrid.AddCell(cellObject=self.numWarningLabel,
                                colSpan=self.layoutGrid.columns)
        self.layoutGrid.FillRow()

    def BuildRefreshInventory(self):
        self.refreshCont = Transform(parent=self.layoutGrid,
                                     pos=(0, 0, 32, 32),
                                     align=uiconst.CENTER)
        self.refreshIcon = ButtonIcon(name='refreshSprite',
                                      parent=self.refreshCont,
                                      width=32,
                                      height=32,
                                      align=uiconst.CENTER,
                                      texturePath=REFRESH_TEXTUREPATH,
                                      iconSize=32,
                                      func=self.OnRefreshClicked)
        self.refreshIcon.hint = GetByLabel(
            'UI/Fitting/FittingWindow/FittingManagement/RefreshInventoryStatusHint'
        )

    def OnRefreshClicked(self, *args):
        uthread.new(self.refreshCont.StartRotationCycle, cycles=1)
        self.SetInventoryStatus()

    def BuildAvailableShipsUI(self):
        self.shipCounter = EveCaptionMedium(name='shipCounter',
                                            parent=self.missingLayoutGrid,
                                            state=uiconst.UI_NORMAL,
                                            align=uiconst.CENTERRIGHT,
                                            left=4)
        self.shipCounter.LoadTooltipPanel = self.LoadShipCounterTooltipPanel
        self.shipCounter.missingDict = {}
        shipText = GetByLabel(
            'UI/Fitting/FittingWindow/FittingManagement/PackagedShipsInHangar')
        self.availableShipsLabel = EveLabelLarge(name='availableShipsLabel',
                                                 parent=self.missingLayoutGrid,
                                                 state=uiconst.UI_NORMAL,
                                                 text=shipText,
                                                 align=uiconst.CENTERLEFT,
                                                 width=MAX_TEXT_WIDTH,
                                                 autoFitToText=True)
        self.availableShipsLabel.hint = GetByLabel(
            'UI/Fitting/FittingWindow/FittingManagement/PackagedShipsInHangarHint'
        )
        self.layoutGrid.FillRow()

    def BuildEquipmentUI(self):
        self.equipmentCounter = EveCaptionMedium(name='equipmentCounter',
                                                 parent=self.missingLayoutGrid,
                                                 state=uiconst.UI_NORMAL,
                                                 align=uiconst.CENTERRIGHT,
                                                 left=4)
        self.equipmentCounter.LoadTooltipPanel = self.LoadEqCounterTooltipPanel
        self.equipmentCounter.missingDict = {}
        eqText = GetByLabel(
            'UI/Fitting/FittingWindow/FittingManagement/RoundsOfFittingsInHangar'
        )
        self.availableEquipmentLabel = EveLabelLarge(
            name='availableEquipmentLabel',
            parent=self.missingLayoutGrid,
            state=uiconst.UI_NORMAL,
            text=eqText,
            align=uiconst.CENTERLEFT,
            width=MAX_TEXT_WIDTH,
            autoFitToText=True)
        self.layoutGrid.FillRow()

    def BuildProgressUI(self):
        self.progressCont = Container(parent=self.sr.main,
                                      height=36,
                                      align=uiconst.TOBOTTOM,
                                      padding=(10, 0, 10, 10))
        self.progressCounter = EveCaptionMedium(name='progressCounter',
                                                parent=self.progressCont,
                                                state=uiconst.UI_NORMAL,
                                                align=uiconst.CENTERTOP)
        self.progressBar = ProgressBar(parent=self.progressCont,
                                       height=10,
                                       align=uiconst.TOBOTTOM)
        self.progressCont.display = False

    def MakeRigCbUI(self):
        checked = settings.user.ui.Get('fitting_rigCB', True)
        text = GetByLabel('UI/Fitting/FittingWindow/FittingManagement/FitRigs')
        self.rigCB = Checkbox(name='rigCB',
                              text=text,
                              OnChange=self.OnCbChanged,
                              left=LEFT_EDGE,
                              checked=checked,
                              prefstype=('user', 'ui'),
                              configName='fitting_rigCB')
        self.rigCB.hint = GetByLabel(
            'UI/Fitting/FittingWindow/FittingManagement/FitRigsHint')
        self.layoutGrid.AddCell(cellObject=self.rigCB,
                                colSpan=self.layoutGrid.columns)

    def OnNumChanged(self, *args):
        self.onNumChangedTimer = AutoTimer(100, self.SetInventoryStatus)

    def OnCbChanged(self, *args):
        self.SetInventoryStatus()

    def OpenFitting(self, *args):
        sm.GetService('fittingSvc').DisplayFitting(self.fitting)

    def LoadWindow(self, fitting, qty=1):
        self.fitting = fitting
        self.shipCounter.missingDict = {}
        self.equipmentCounter.missingDict = {}
        shipTypeID = fitting.shipTypeID
        self.shipIcon.LoadIconByTypeID(shipTypeID)
        uix.GetTechLevelIcon(self.techSprite, typeID=shipTypeID)
        self.numToFitEdit.text = qty
        self.fitNameEdit.SetValue(fitting.name)
        self.shipNameLabel.text = GetShowInfoLink(shipTypeID,
                                                  evetypes.GetName(shipTypeID))
        self.SetInventoryStatus()
        self.missingLayoutGrid.RefreshGridLayout()
        self.layoutGrid.RefreshGridLayout()
        layoutWidth, layoutHeight = self.layoutGrid.GetSize()
        newHeight = layoutHeight + self.fitBtn.height + self.progressCont.height + self.sr.topParent.height + 20
        self.height = max(newHeight, self.default_height)
        self.width = max(layoutWidth + 20, self.default_width)

    def SetInventoryStatus(self):
        self.onNumChangedTimer = None
        fitting = self.fitting
        shipTypeID = fitting.shipTypeID
        fittingSvc = sm.GetService('fittingSvc')
        chargesByType, dronesByType, fightersByTypeID, iceByType, itemTypes, modulesByFlag, rigsToFit, subsystems = fittingSvc.GetTypesToFit(
            fitting, None)
        if rigsToFit:
            self.rigCB.display = True
        else:
            self.rigCB.display = False
        numToFit = self.numToFitEdit.GetValue()
        self.tryingToFitNum = numToFit
        maxAvailableFitting, missingForFullFit = self._GetMaxAvailabeAndMissingForFullFit(
            itemTypes, modulesByFlag, numToFit)
        nonSingletonShipsNumDict = fittingSvc.GetQt0yInHangarByTypeIDs(
            [shipTypeID], onlyGetNonSingletons=True)
        packagedShipsNum = nonSingletonShipsNumDict.get(shipTypeID, 0)
        self.canFitNum = min(packagedShipsNum, maxAvailableFitting, numToFit)
        btnText = GetByLabel(
            'UI/Fitting/FittingWindow/FittingManagement/FitShips',
            numToFit=self.canFitNum)
        self.fitBtn.SetLabel(btnText)
        if self.canFitNum < 1:
            self.fitBtn.Disable()
        else:
            self.fitBtn.Enable()
        missingNumShips = max(0, numToFit - packagedShipsNum)
        if missingNumShips:
            missingDict = {shipTypeID: missingNumShips}
        else:
            missingDict = {}
        self.shipCounter.missingDict = missingDict
        if missingForFullFit:
            missingDict = missingForFullFit
        else:
            missingDict = {}
        self.equipmentCounter.missingDict = missingDict
        if missingForFullFit or missingNumShips:
            missingText = GetByLabel(
                'UI/Fitting/FittingWindow/FittingManagement/MissingShipEquipment'
            )
            self.numWarningLabel.text = missingText
        else:
            self.numWarningLabel.text = ''
            self.numWarningLabel.height = 0
        self.SetAvailabilityShipOrEq(self.shipCounter, packagedShipsNum,
                                     numToFit)
        self.SetAvailabilityShipOrEq(self.equipmentCounter,
                                     maxAvailableFitting, numToFit)

    def _GetMaxAvailabeAndMissingForFullFit(self, itemTypes, modulesByFlag,
                                            numToFit):
        fittingSvc = sm.GetService('fittingSvc')
        qtyByTypeID = fittingSvc.GetQt0yInHangarByTypeIDs(itemTypes)
        rigTypeIDs = {
            t
            for f, t in modulesByFlag.iteritems() if f in const.rigSlotFlags
        }
        maxAvailableFitting, missingForFullFit = fittingSvc.GetMaxAvailabeAndMissingForFullFit(
            True, itemTypes, numToFit, qtyByTypeID, rigTypeIDs)
        return (maxAvailableFitting, missingForFullFit)

    def SetAvailabilityShipOrEq(self, label, available, numToFit):
        label.text = available
        if available < numToFit:
            label.SetRGB(*WARNING_COLOR)
        else:
            label.SetRGB(*NORMAL_COLOR)

    def DoFitShips(self, *args):
        fitting = self.fitting
        fitRigs = self.rigCB.GetValue()
        toActuallyFit = self.canFitNum
        fittingName = self.fitNameEdit.GetValue()
        fittingSvc = sm.GetService('fittingSvc')
        chargesByType, dronesByType, fightersByTypeID, iceByType, itemTypes, modulesByFlag, rigsToFit, subsystems = fittingSvc.GetTypesToFit(
            fitting, None)
        if fitRigs or not rigsToFit:
            cargoItemsByType = {}
        else:
            cargoItemsByType = defaultdict(int)
            for flagID, typeID in modulesByFlag.iteritems():
                if flagID in const.rigSlotFlags:
                    cargoItemsByType[typeID] += 1

            cargoItemsByType = dict(cargoItemsByType)
        lobby = GetLobbyClass().GetIfOpen()
        if lobby is None:
            return
        lobby.CheckCanAccessService('fitting')
        maxAvailableFitting, missingForFullFit = self._GetMaxAvailabeAndMissingForFullFit(
            itemTypes, modulesByFlag, toActuallyFit)
        if missingForFullFit:
            self.SetInventoryStatus()
            eve.Message('uiwarning03')
            return
        try:
            self.PrepareForMultiFitCall()
            fittingSvc.DoFitManyShips(chargesByType, dronesByType,
                                      fightersByTypeID, fitRigs, fitting,
                                      iceByType, cargoItemsByType,
                                      toActuallyFit, modulesByFlag,
                                      fittingName)
        finally:
            uthread.new(self.ResetUIAfterFitting)

    def PrepareForMultiFitCall(self):
        self.fitBtn.Disable()
        self.cancelBtn.Disable()
        self.currentProgress = 0
        self.progressCounter.text = self.currentProgress
        self.progressCont.display = True
        self.layoutGrid.Disable()
        self.layoutGrid.opacity = 0.2
        sm.RegisterForNotifyEvent(self, 'OnItemChange')

    def ResetUIAfterFitting(self):
        sm.UnregisterForNotifyEvent(self, 'OnItemChange')
        self.currentProgress = 0
        uicore.animations.BlinkOut(self.progressCont,
                                   startVal=0.0,
                                   endVal=1.0,
                                   duration=0.5,
                                   loops=3,
                                   sleep=True)
        self.progressCont.display = False
        self.progressCounter.text = self.currentProgress
        self.cancelBtn.Enable()
        self.layoutGrid.Enable()
        self.layoutGrid.opacity = 1.0
        self.SetInventoryStatus()

    def Cancel(self, *args):
        self.CloseByUser()

    def GetFittingDragData(self):
        entry = KeyVal()
        entry.fitting = self.fitting
        entry.label = self.fitting.name
        entry.displayText = self.fitting.name
        entry.__guid__ = 'listentry.FittingEntry'
        return [entry]

    def LoadMissingTooltip(self, tooltipPanel, *args):
        text = GetByLabel(
            'UI/Fitting/FittingWindow/FittingManagement/MissingItems',
            numToFit=self.tryingToFitNum,
            fittingName=self.fitting.name)
        tooltipPanel.AddLabelLarge(text=text, padBottom=8)
        self.LoadShipCounterTooltipPanel(tooltipPanel,
                                         singleGroupShowing=False)
        self.LoadEqCounterTooltipPanel(tooltipPanel, singleGroupShowing=False)
        missingDict = {}
        missingDict.update(self.shipCounter.missingDict)
        missingDict.update(self.equipmentCounter.missingDict)
        self.AddBuyAllBtn(tooltipPanel, missingDict)

    def LoadShipCounterTooltipPanel(self, tooltipPanel, *args, **kwargs):
        missingDict = self.shipCounter.missingDict
        if not missingDict:
            return
        singleGroupShowing = kwargs.get('singleGroupShowing', True)
        text = GetByLabel(
            'UI/Fitting/FittingWindow/FittingManagement/MissingShips',
            numToFit=self.tryingToFitNum,
            fittingName=self.fitting.name)
        return self.LoadCounterTooltip(tooltipPanel, missingDict, text,
                                       singleGroupShowing)

    def LoadEqCounterTooltipPanel(self, tooltipPanel, *args, **kwargs):
        missingDict = self.equipmentCounter.missingDict
        if not missingDict:
            return
        singleGroupShowing = kwargs.get('singleGroupShowing', True)
        text = GetByLabel(
            'UI/Fitting/FittingWindow/FittingManagement/MissingEquipment',
            numToFit=self.tryingToFitNum,
            fittingName=self.fitting.name)
        self.LoadCounterTooltip(tooltipPanel, missingDict, text,
                                singleGroupShowing)

    def LoadCounterTooltip(self,
                           tooltipPanel,
                           missingDict,
                           text,
                           singleGroupShowing=True):
        tooltipPanel.LoadGeneric1ColumnTemplate()
        tooltipPanel.state = uiconst.UI_NORMAL
        if singleGroupShowing:
            tooltipPanel.AddLabelLarge(text=text, padBottom=8)
        typeList = []
        for eachTypeID, eachQty in missingDict.iteritems():
            typeName = evetypes.GetName(eachTypeID)
            typeList.append((typeName.lower(), (eachTypeID, eachQty)))

        typeList = SortListOfTuples(typeList)
        for eachTypeID, eachQty in typeList[:MAX_TOOLTIP_ENTRIES]:
            typeCont = TooltipEntry(parent=tooltipPanel,
                                    typeID=eachTypeID,
                                    qty=eachQty)

        if len(typeList) > MAX_TOOLTIP_ENTRIES:
            numItemsNotDisplayed = len(typeList) - MAX_TOOLTIP_ENTRIES
            text = GetByLabel(
                'UI/Fitting/FittingWindow/FittingManagement/MoreItemTypesMissing',
                numMoreItems=numItemsNotDisplayed)
            tooltipPanel.AddLabelMedium(text=text, align=uiconst.CENTERLEFT)
        if singleGroupShowing:
            self.AddBuyAllBtn(tooltipPanel, missingDict)

    def AddBuyAllBtn(self, tooltipPanel, missingDict):
        def BuyAll(*args):
            BuyMultipleTypesWithQty(missingDict)

        Button(parent=tooltipPanel,
               label=GetByLabel('UI/Market/MarketQuote/BuyAll'),
               func=BuyAll,
               align=uiconst.CENTER)
        if session.role & ROLE_GMH == ROLE_GMH:
            Button(parent=tooltipPanel,
                   label='GM: Give all',
                   func=self.GiveAllGM,
                   align=uiconst.CENTERRIGHT,
                   args=(missingDict, ))

    def GiveAllGM(self, missingDict):
        numToCountTo = len(missingDict) + 1
        header = 'GM Item Gift'
        sm.GetService('loading').ProgressWnd(header, '', 1, numToCountTo)
        counter = 1
        for typeID, qty in missingDict.iteritems():
            counter += 1
            sm.GetService('loading').ProgressWnd(header, '', counter,
                                                 numToCountTo)
            sm.RemoteSvc('slash').SlashCmd('/create %s %s' % (typeID, qty))

        sm.GetService('loading').ProgressWnd('Done', '', numToCountTo,
                                             numToCountTo)

    def OnItemChange(self, item, change):
        if item.typeID != self.fitting.shipTypeID:
            return
        if const.ixSingleton in change:
            self.currentProgress += 1
            self.progressCounter.text = '%s / %s' % (self.currentProgress,
                                                     self.canFitNum)

    def OnSessionChanged(self, isRemote, sess, change):
        if not IsDocked():
            self.CloseByUser()
示例#8
0
class UITree(Window):
    default_windowID = 'uitree'
    default_caption = 'UI Roots'
    default_width = 300
    default_height = 400
    default_minSize = (default_width, default_height)
    default_left = '__center__'
    default_top = '__center__'
    filterString = None

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        mainArea = self.GetMainArea()
        mainArea.padding = 6
        self._selectedObject = None
        self.SetTopparentHeight(0)
        self._infoContainer = Container(parent=mainArea,
                                        align=uiconst.TOTOP,
                                        height=72)
        self.searchInput = SinglelineEdit(parent=self._infoContainer,
                                          align=uiconst.BOTTOMRIGHT,
                                          left=4,
                                          top=8,
                                          width=100,
                                          OnChange=self.OnSearchInputChange,
                                          hinttext='Search')
        self.searchInput.SetHistoryVisibility(False)
        self.searchInput.ShowClearButton()
        m = UtilMenu(menuAlign=uiconst.TOPRIGHT,
                     parent=self._infoContainer,
                     align=uiconst.TOPRIGHT,
                     GetUtilMenu=self.SettingMenu)
        self._infoLabel = Label(parent=self._infoContainer,
                                state=uiconst.UI_DISABLED,
                                color=(1.0, 1.0, 1.0, 0.75),
                                left=2)
        self.searchResultParent = ContainerAutoSize(parent=mainArea,
                                                    align=uiconst.TOTOP_NOPUSH,
                                                    padding=(26, -6, 4, 0),
                                                    bgColor=(0.5, 0.5, 0.5, 1))
        self.attributeScroll = Scroll(parent=mainArea,
                                      align=uiconst.TOBOTTOM,
                                      name='attributeScroll')
        self.attributeScroll.height = min(
            self.height / 2,
            max(72, settings.user.ui.Get('uitree_attributeScroll_height',
                                         200)))
        settings.user.ui.Set('uitree_attributeScroll_height',
                             self.attributeScroll.height)
        self.divider = Divider(align=uiconst.TOBOTTOM,
                               parent=mainArea,
                               height=11,
                               state=uiconst.UI_NORMAL)
        self.divider.OnChange_ = self.OnDividerMove
        self.divider.OnChangeStart_ = self.OnDividerMoveStart
        Fill(parent=self.divider, align=uiconst.CENTER, pos=(0, 0, 20, 1))
        self.scroll = Scroll(parent=mainArea, name='treeScroll')
        self._hiliteFrame = Fill(parent=uicore.desktop,
                                 align=uiconst.ABSOLUTE,
                                 color=(0, 1, 0, 0.3),
                                 idx=0,
                                 state=uiconst.UI_DISABLED)
        self._selectedFrame = Frame(parent=uicore.desktop,
                                    align=uiconst.ABSOLUTE,
                                    color=(0, 1, 0, 0.3),
                                    idx=0,
                                    state=uiconst.UI_DISABLED)
        self.ReloadUIRoots()
        uthread.new(self.UpdateInfo)
        self._keyDownCookie = uicore.uilib.RegisterForTriuiEvents(
            [uiconst.UI_KEYDOWN], self.OnGlobalKeyDown)

    def OnSearchInputChange(self, *args):
        self.searchThread = base.AutoTimer(250, self.SearchTree)

    def SearchTree(self):
        self.searchThread = None
        self.filterString = self.searchInput.GetValue()
        if not self.filterString:
            self.searchResultParent.Hide()
            self.searchResultParent.Flush()
            return
        self.searchResultParent.Flush()
        res = []
        searchFor = self.filterString.lower()

        def Crawl(obj, path):
            if obj is self:
                return
            if searchFor in obj.name.lower():
                if path:
                    res.append((obj, path + '/ <b>' + obj.name + '</b>'))
                else:
                    res.append((obj, '<b>' + obj.name + '</b>'))
            if hasattr(obj, 'children'):
                for each in obj.children:
                    if path:
                        Crawl(each, path + '/' + obj.name)
                    else:
                        Crawl(each, obj.name)

        for root in uicore.uilib.rootObjects:
            Crawl(root, '')

        if res:
            for obj, path in res[:20]:
                label = Label(parent=self.searchResultParent,
                              align=uiconst.TOTOP,
                              text=path,
                              state=uiconst.UI_NORMAL,
                              padding=(10, 2, 10, 2))
                label._searchObj = obj
                label.hint = path
                label.OnClick = (self.OnSearchResultClick, obj)

            if len(res) > 20:
                Label(parent=self.searchResultParent,
                      align=uiconst.TOTOP,
                      text='and even more... (%s found)' % len(res),
                      padding=(10, 2, 10, 2))
        else:
            Label(parent=self.searchResultParent,
                  align=uiconst.TOTOP,
                  text='No Match!',
                  padding=(10, 3, 10, 3))
        self.searchResultParent.Show()

    def OnSearchResultClick(self, obj):
        self.searchResultParent.Hide()
        self.ShowUIObject(obj)

    def _OnSizeChange_NoBlock(self, *args, **kwds):
        Window._OnSizeChange_NoBlock(self, *args, **kwds)
        self.attributeScroll.height = min(
            self.height / 2,
            max(72, settings.user.ui.Get('uitree_attributeScroll_height',
                                         200)))
        settings.user.ui.Set('uitree_attributeScroll_height',
                             self.attributeScroll.height)

    def OnDividerMove(self, divider, dx, dy):
        self.attributeScroll.height = min(
            self.height / 2, max(72, self._initAttributeScrollHeight - dy))
        settings.user.ui.Set('uitree_attributeScroll_height',
                             self.attributeScroll.height)

    def OnDividerMoveStart(self, *args):
        self._initAttributeScrollHeight = self.attributeScroll.height

    def SettingMenu(self, menuParent, *args):
        checked = settings.user.ui.Get('uitreeShowPickHilite', True)
        menuParent.AddCheckBox(text='Show pick hilite',
                               checked=checked,
                               callback=(self.ToggleCheckboxSetting,
                                         'ShowPickHilite'))
        checked = settings.user.ui.Get('uitreeIgnoreFullScreenPick', False)
        menuParent.AddCheckBox(text='Ignore fullscreen hilite',
                               checked=checked,
                               callback=(self.ToggleCheckboxSetting,
                                         'IgnoreFullScreenPick'))
        menuParent.AddIconEntry(icon=None,
                                text='Move To Desktop',
                                callback=self.MoveToDesktop)
        menuParent.AddIconEntry(icon=None,
                                text='Reload Textures',
                                callback=self.ReloadTextures)

    def ReloadTextures(self):
        import blue
        for resPath in blue.motherLode.GetNonCachedKeys(
        ) + blue.motherLode.GetCachedKeys():
            if resPath.lower().startswith('res:/ui'):
                res = blue.motherLode.Lookup(resPath)
                if res:
                    if hasattr(res, 'Reload'):
                        res.Reload()

    def MoveToDesktop(self):
        self.SetParent(uicore.desktop, idx=0)

    def ToggleCheckboxSetting(self, settingName, *args):
        checked = settings.user.ui.Get('uitree' + settingName, True)
        settings.user.ui.Set('uitree' + settingName, not checked)

    def Close(self, *args, **kwds):
        frame = getattr(self, '_hiliteFrame', None)
        if frame:
            frame.Close()
        if getattr(self, '_selectedFrame', None):
            self._selectedFrame.Close()
        Window.Close(self, *args, **kwds)

    def OnGlobalKeyDown(self, *args, **kwds):
        if self.destroyed:
            return False
        ctrl = uicore.uilib.Key(uiconst.VK_CONTROL)
        alt = uicore.uilib.Key(uiconst.VK_MENU)
        if ctrl and not (IsUnder(uicore.uilib.mouseOver, self)
                         or uicore.uilib.mouseOver is self):
            self.ShowUIObject(uicore.uilib.mouseOver)
        return True

    def UpdateInfo(self):
        while not self.destroyed:
            mo = uicore.uilib.mouseOver
            if mo:
                infoText = 'MouseOver: %s' % mo.name
            else:
                infoText = 'MouseOver: None'
            active = uicore.registry.GetActive()
            if active:
                infoText += '<br>Active: %s' % active.name
            else:
                infoText += '<br>Active: None'
            focus = uicore.registry.GetFocus()
            if focus:
                infoText += '<br>Focus: %s' % (focus.name or focus.__guid__)
            else:
                infoText += '<br>Focus: None'
            capture = uicore.uilib.GetMouseCapture()
            if capture:
                infoText += '<br>Capture: %s' % (capture.name
                                                 or capture.__guid__)
            else:
                infoText += '<br>Capture: None'
            infoText += '<br>MouseX/Y: %s, %s' % (uicore.uilib.x,
                                                  uicore.uilib.y)
            showHilite = settings.user.ui.Get('uitreeShowPickHilite', True)
            ignoreFullScreenPick = settings.user.ui.Get(
                'uitreeIgnoreFullScreenPick', False)
            hiliteUIObject = None
            if showHilite:
                if IsUnder(mo, self):
                    if IsUnder(mo, self.scroll):
                        uiObjectGetAbs = GetAttrs(mo, 'sr', 'node', 'uiObject',
                                                  'GetAbsolute')
                        if uiObjectGetAbs:
                            hiliteUIObject = GetAttrs(mo, 'sr', 'node',
                                                      'uiObject')
                elif mo is not uicore.desktop and mo is not self and not IsUnder(
                        mo, self) and self.state == uiconst.UI_NORMAL:
                    hiliteUIObject = mo
            if hiliteUIObject and ignoreFullScreenPick and isinstance(
                    hiliteUIObject, (LayerCore, UIRoot)):
                hiliteUIObject = None
            self.ShowHilitedObjectInUI(hiliteUIObject)
            selectedObject = None
            if self._selectedObject:
                selectedObject = self._selectedObject()
                if getattr(selectedObject, 'destroyed', False):
                    selectedObject = None
            for node in self.scroll.sr.nodes:
                if node.panel:
                    node.panel.UpdateSelected(selectedObject)
                    node.panel.UpdatePickHilite(hiliteUIObject)
                    if getattr(node.uiObject, 'destroyed', False):
                        node.panel.CheckDestroyed()

            self.ShowSelectedObjectInUI(selectedObject)
            self._infoLabel.text = infoText
            self._infoContainer.height = self._infoLabel.textheight + 5
            blue.pyos.synchro.SleepWallclock(100)

    def ShowSelectedObjectInUI(self, uiObject):
        if uiObject and hasattr(uiObject, 'GetAbsolute'):
            self._selectedFrame.pos = uiObject.GetAbsolute()
            self._selectedFrame.display = True
        else:
            self._selectedFrame.display = False

    def ShowHilitedObjectInUI(self, uiObject):
        if self.destroyed:
            return
        if uiObject:
            self._hiliteFrame.pos = uiObject.GetAbsolute()
            self._hiliteFrame.display = True
        else:
            self._hiliteFrame.display = False

    def ReloadUIRoots(self, *args):
        startRoot = uicore.uilib.rootObjects
        scrollNodes = []
        for root in startRoot:
            self._CrawlUIObject(root, scrollNodes, 0)

        self.scroll.LoadContent(contentList=scrollNodes)

    def _AddUIObject(self,
                     uiObject,
                     scrollList,
                     lvl,
                     isExpanded=False,
                     objectLabel=None,
                     isExpandable=False):
        if len(scrollList) > 1 and lvl:
            for i in xrange(1, len(scrollList) - 1):
                last = scrollList[-i]
                if last.level < lvl:
                    break
                if lvl not in last.connectLevels:
                    last.connectLevels.append(lvl)

        node = ScrollEntryNode(decoClass=UITreeEntry,
                               uiObject=uiObject,
                               level=lvl,
                               isExpanded=isExpanded,
                               objectLabel=objectLabel,
                               isExpandable=isExpandable,
                               connectLevels=[lvl])
        scrollList.append(node)

    def IsExpanded(self, uiObject):
        desktopObjectID = id(uicore.desktop)
        allPrefs = settings.user.ui.Get('UITreeExpandedObjects', {})
        if desktopObjectID not in allPrefs:
            return False
        uiObjectID = id(uiObject)
        if getattr(uiObject, 'parent', None):
            uiObjectID = (id(uiObject.parent), uiObjectID)
        return uiObjectID in allPrefs[desktopObjectID]

    def ExpandUIObject(self, uiObject):
        uiObjectID = id(uiObject)
        if getattr(uiObject, 'parent', None):
            uiObjectID = (id(uiObject.parent), uiObjectID)
        desktopObjectID = id(uicore.desktop)
        allPrefs = settings.user.ui.Get('UITreeExpandedObjects', {})
        if desktopObjectID not in allPrefs:
            allPrefs[desktopObjectID] = []
        if uiObjectID not in allPrefs[desktopObjectID]:
            allPrefs[desktopObjectID].append(uiObjectID)
        settings.user.ui.Set('UITreeExpandedObjects', allPrefs)

    def ToggleExpandedObject(self, uiObject):
        uiObjectID = id(uiObject)
        if getattr(uiObject, 'parent', None):
            uiObjectID = (id(uiObject.parent), uiObjectID)
        desktopObjectID = id(uicore.desktop)
        allPrefs = settings.user.ui.Get('UITreeExpandedObjects', {})
        if desktopObjectID not in allPrefs:
            allPrefs[desktopObjectID] = []
        if uiObjectID in allPrefs[desktopObjectID]:
            allPrefs[desktopObjectID].remove(uiObjectID)
        else:
            allPrefs[desktopObjectID].append(uiObjectID)
        settings.user.ui.Set('UITreeExpandedObjects', allPrefs)
        self.ReloadUIRoots()

    def _CrawlUIObject(self, uiObject, scrollNodes, lvl, objectLabel=None):
        """Defines what to show in the tree"""
        isExpandable = UITree._IsExpandable(uiObject)
        if isExpandable:
            isExpanded = self.IsExpanded(uiObject)
        else:
            isExpanded = False
        self._AddUIObject(uiObject,
                          scrollNodes,
                          lvl,
                          isExpanded,
                          objectLabel=objectLabel,
                          isExpandable=isExpandable)
        if isExpanded:
            if isinstance(uiObject, Base):
                allPy = dir(uiObject)
                for propertyName in allPy:
                    if propertyName.startswith(
                            '_') or propertyName in IGNORE_PROPERTIES:
                        continue
                    try:
                        prop = getattr(uiObject, propertyName, None)
                    except:
                        print 'Failed on property', propertyName
                        continue

                    try:
                        if getattr(prop, 'TypeInfo', None):
                            self._CrawlUIObject(prop,
                                                scrollNodes,
                                                lvl + 1,
                                                objectLabel=propertyName)
                    except (KeyError, RuntimeError):
                        pass

                for dictName in PYOBJECT_SUBDICTS:
                    dct = getattr(uiObject, dictName, {})
                    if dct:
                        for k, v in dct.iteritems():
                            self._CrawlUIObject(v,
                                                scrollNodes,
                                                lvl + 1,
                                                objectLabel='%s: %s' %
                                                (dictName.lstrip('_'), k))

                for listName in PYOBJECT_SUBLISTS:
                    lst = getattr(uiObject, listName, [])
                    if lst:
                        for objChild in lst:
                            if listName == 'background':
                                self._CrawlUIObject(objChild,
                                                    scrollNodes,
                                                    lvl + 1,
                                                    objectLabel=listName)
                            else:
                                self._CrawlUIObject(objChild, scrollNodes,
                                                    lvl + 1)

            else:
                allC = dir(uiObject)
                for propertyName in allC:
                    if propertyName.startswith('_'):
                        continue
                    prop = getattr(uiObject, propertyName, None)
                    if callable(prop):
                        continue
                    if getattr(prop, '__bluetype__', None) == 'blue.List':
                        isExpanded = self.IsExpanded(prop)
                        self._AddUIObject(prop,
                                          scrollNodes,
                                          lvl + 1,
                                          isExpanded,
                                          isExpandable=True,
                                          objectLabel='%s (%s)' %
                                          (propertyName, len(prop)))
                        if isExpanded:
                            for each in prop:
                                self._CrawlUIObject(each, scrollNodes, lvl + 2)

                        continue
                    elif getattr(prop, '__bluetype__', None) == 'blue.Dict':
                        isExpanded = self.IsExpanded(prop)
                        self._AddUIObject(prop,
                                          scrollNodes,
                                          lvl + 1,
                                          isExpanded,
                                          isExpandable=True,
                                          objectLabel=propertyName)
                        if isExpanded:
                            for k, v in prop.items():
                                self._CrawlUIObject(v,
                                                    scrollNodes,
                                                    lvl + 2,
                                                    objectLabel=k)

                        continue
                    elif hasattr(prop, 'TypeInfo'):
                        self._CrawlUIObject(prop,
                                            scrollNodes,
                                            lvl + 1,
                                            objectLabel=propertyName)

    @classmethod
    def _IsExpandable(cls, uiObject):
        if isinstance(uiObject, Base):
            return True
        allC = dir(uiObject)
        for propertyName in allC:
            if propertyName.startswith('_'):
                continue
            prop = getattr(uiObject, propertyName, None)
            if getattr(prop, '__bluetype__',
                       None) in ('blue.List', 'blue.Dict'):
                return True
            if hasattr(prop, 'TypeInfo'):
                return True

        return False

    def ShowUIObject(self, uiObject):
        traceUp = [uiObject]
        parent = uiObject.parent
        while parent:
            traceUp.insert(0, parent)
            parent = parent.parent

        for each in traceUp:
            self.ExpandUIObject(each)

        self.ShowPropertiesForObject(uiObject)
        for node in self.scroll.sr.nodes:
            if node.uiObject is uiObject:
                self.scroll.ShowNodeIdx(node.idx)
                break

    def ShowPropertiesForObject(self, uiObject):
        if uiObject is None:
            return
        try:
            len(uiObject)
            self.attributeScroll.LoadContent(contentList=[])
            return
        except:
            pass

        self._selectedObject = weakref.ref(uiObject)
        level = 0
        newNodes = []
        if isinstance(uiObject, Base):
            combined = []
            if hasattr(uiObject, 'color'):
                combined.append(
                    ('color', ('color.r', 'color.g', 'color.b', 'color.a')))
            for propertyName, subs in combined:
                propertyNode = ScrollEntryNode(decoClass=UITreePropertyEntry,
                                               uiObject=uiObject,
                                               level=level,
                                               propertyName=propertyName,
                                               combineProperties=subs)
                newNodes.append(propertyNode)

            basics = [
                'name', 'pos', 'opacity', 'padding', 'displayRect', 'display',
                'pickState', 'align', 'clipChildren', 'pickRadius',
                'absoluteCoordinates', 'cacheContents', 'text', 'blendMode',
                'spriteEffect', 'effectAmount', 'effectAmount2', 'glowColor',
                'glowFactor', 'glowExpand', 'useSizeFromTexture', 'rotation',
                'rotationCenter', 'scale', 'scalingCenter', 'scalingRotation',
                '', '__guid__', '__class__'
            ]
            for propertyName in basics:
                prop = getattr(uiObject, propertyName, '_!_')
                if prop == '_!_':
                    continue
                propertyNode = ScrollEntryNode(decoClass=UITreePropertyEntry,
                                               uiObject=uiObject,
                                               level=level,
                                               propertyName=propertyName)
                newNodes.append(propertyNode)

        else:
            for attr in dir(uiObject):
                if attr[0] == attr[0].upper():
                    continue
                if attr[0] == '_':
                    continue
                if attr in ('children', 'background'):
                    continue
                propertyNode = ScrollEntryNode(decoClass=UITreePropertyEntry,
                                               uiObject=uiObject,
                                               level=level,
                                               propertyName=attr)
                newNodes.append((attr, propertyNode))

            newNodes = SortListOfTuples(newNodes)
        self.ReloadUIRoots()
        self.attributeScroll.LoadContent(contentList=newNodes)
示例#9
0
class SellItemContainer(Container):
    __guid__ = 'uicls.SellItemContainer'
    default_height = 40
    default_align = uiconst.TOTOP
    default_state = uiconst.UI_NORMAL

    def ApplyAttributes(self, attributes):
        Container.ApplyAttributes(self, attributes)
        self.parentFunc = attributes.parentFunc
        self.padding = (0, 2, 0, 2)
        self.item = attributes.item
        self.singleton = self.item.singleton
        self.parentEditFunc = attributes.editFunc
        self.typeID = self.item.typeID
        self.itemID = self.item.itemID
        self.invType = cfg.invtypes.Get(self.typeID)
        self.itemName = self.invType.name
        self.brokersFee = 0.0
        self.salesTax = 0.0
        self.totalSum = 0.0
        self.quote = sm.GetService('marketQuote')
        self.limits = self.quote.GetSkillLimits()
        self.stationID, officeFolderID, officeID = sm.GetService(
            'invCache').GetStationIDOfficeFolderIDOfficeIDOfItem(self.item)
        self.located = None
        if officeFolderID is not None:
            self.located = [officeFolderID, officeID]
        station = sm.GetService('ui').GetStation(self.stationID)
        self.solarSystemID = station.solarSystemID
        self.regionID = self.GetRegionID(self.stationID)
        self.averagePrice = self.quote.GetAveragePrice(self.typeID)
        self.bestBid = self.quote.GetBestBid(self.typeID,
                                             locationID=self.solarSystemID)
        self.GetBestPrice()
        self.deltaCont = Container(parent=self,
                                   align=uiconst.TORIGHT,
                                   width=30)
        theRestCont = Container(parent=self, align=uiconst.TOALL)
        self.totalCont = Container(parent=theRestCont,
                                   align=uiconst.TORIGHT_PROP,
                                   width=0.3)
        self.priceCont = Container(parent=theRestCont,
                                   align=uiconst.TORIGHT_PROP,
                                   width=0.22)
        self.qtyCont = Container(parent=theRestCont,
                                 align=uiconst.TORIGHT_PROP,
                                 width=0.15)
        self.itemCont = Container(parent=theRestCont,
                                  align=uiconst.TORIGHT_PROP,
                                  width=0.33)
        self.deleteCont = Container(parent=self.itemCont,
                                    align=uiconst.TORIGHT,
                                    width=24)
        self.deleteButton = ButtonIcon(
            texturePath='res:/UI/Texture/Icons/73_16_210.png',
            pos=(0, 0, 16, 16),
            align=uiconst.CENTERRIGHT,
            parent=self.deleteCont,
            hint=GetByLabel('UI/Generic/RemoveItem'),
            idx=0,
            func=self.RemoveItem)
        self.deleteCont.display = False
        self.textCont = Container(parent=self.itemCont, align=uiconst.TOALL)
        self.errorBg = ErrorFrame(bgParent=self)
        self.DrawItem()
        self.DrawQty()
        self.DrawPrice()
        self.DrawTotal()
        self.DrawDelta()
        self.GetTotalSum()
        self.GetBrokersFee()
        self.GetSalesTax()
        self.ShowNoSellOrders()

    def RemoveItem(self, *args):
        self.parentFunc(self, *args)

    def GetRegionID(self, stationID):
        regionID = cfg.evelocations.Get(stationID).Station().regionID
        return regionID

    def ShowNoSellOrders(self):
        wnd = SellItems.GetIfOpen()
        if not wnd:
            return
        if wnd.durationCombo.GetValue() == 0 and self.bestBid is None:
            uicore.animations.FadeIn(self.errorBg, 0.35, duration=0.3)

    def HideNoSellOrders(self):
        uicore.animations.FadeOut(self.errorBg, duration=0.3)

    def DrawQty(self):
        qty = self.item.stacksize
        self.qtyEdit = SinglelineEdit(name='qtyEdit',
                                      parent=self.qtyCont,
                                      align=uiconst.TOTOP,
                                      top=11,
                                      padLeft=4)
        self.qtyEdit.IntMode(*(1, long(qty)))
        self.qtyEdit.SetValue(qty)
        self.qtyEdit.OnChange = self.OnChange
        self.qtyEdit.hint = GetByLabel('UI/Common/Quantity')

    def DrawTotal(self):
        self.totalLabel = EveLabelMediumBold(text=self.totalSum,
                                             parent=self.totalCont,
                                             left=4,
                                             align=uiconst.CENTERRIGHT,
                                             state=uiconst.UI_NORMAL,
                                             autoFadeSides=35)
        self.totalLabel.hint = GetByLabel('UI/Market/MarketQuote/AskTotal')

    def DrawPrice(self):
        self.priceEdit = SinglelineEdit(name='priceEdit',
                                        parent=self.priceCont,
                                        align=uiconst.TOTOP,
                                        top=11,
                                        padLeft=8)
        self.priceEdit.FloatMode(*(0.01, 9223372036854.0, 2))
        self.priceEdit.SetValue(self.bestPrice)
        self.priceEdit.OnChange = self.OnChange
        self.priceEdit.hint = GetByLabel('UI/Market/MarketQuote/AskPrice')

    def DrawDelta(self):
        self.deltaContainer = DeltaContainer(parent=self.deltaCont,
                                             delta=self.GetDelta(),
                                             func=self.OpenMarket,
                                             align=uiconst.CENTERRIGHT)
        self.deltaContainer.LoadTooltipPanel = self.LoadDeltaTooltip
        self.UpdateDelta()

    def OnMouseEnter(self, *args):
        self.mouseovertimer = AutoTimer(1, self.UpdateMouseOver)
        self.deleteCont.display = True

    def UpdateMouseOver(self):
        mo = uicore.uilib.mouseOver
        if mo in (self.itemNameLabel, self, self.deleteCont, self.deleteButton,
                  self.totalLabel):
            return
        self.mouseovertimer = None
        self.deleteCont.display = False

    def Close(self, *args):
        self.mouseovertimer = None
        self.parentFunc = None
        Container.Close(self, *args)

    def OpenMarket(self, *args):
        sm.GetService('marketutils').ShowMarketDetails(self.typeID, None)
        wnd = SellItems.GetIfOpen()
        wnd.SetOrder(0)

    def LoadDeltaTooltip(self, tooltipPanel, *args):
        tooltipPanel.LoadGeneric2ColumnTemplate()
        tooltipPanel.cellPadding = (4, 1, 4, 1)
        tooltipPanel.AddLabelLarge(
            text=GetByLabel('UI/Market/MarketQuote/AskPrice'))
        tooltipPanel.AddLabelLarge(text=FmtISK(self.priceEdit.GetValue()),
                                   align=uiconst.CENTERRIGHT)
        tooltipPanel.AddSpacer(1, 8, colSpan=tooltipPanel.columns)
        tooltipPanel.AddLabelMedium(
            text='%s %s' %
            (GetByLabel('UI/Market/MarketQuote/RegionalAdverage'),
             self.GetDeltaText()))
        tooltipPanel.AddLabelMedium(text=FmtISK(self.averagePrice),
                                    align=uiconst.CENTERRIGHT)
        tooltipPanel.AddLabelMedium(
            text=GetByLabel('UI/Market/MarketQuote/BestRegional'))
        bestMatch = tooltipPanel.AddLabelMedium(text='',
                                                align=uiconst.CENTERRIGHT)
        bestMatchDetails = tooltipPanel.AddLabelSmall(
            text='', align=uiconst.CENTERRIGHT, colSpan=tooltipPanel.columns)
        if not self.bestBid:
            bestMatch.text = GetByLabel('UI/Contracts/ContractEntry/NoBids')
            bestMatchDetails.text = GetByLabel(
                'UI/Market/MarketQuote/ImmediateWillFail')
            bestMatch.color = (1.0, 0.275, 0.0, 1.0)
            bestMatchDetails.color = (1.0, 0.275, 0.0, 1.0)
        else:
            bestMatch.text = FmtISK(self.bestBid.price)
            bestMatchText, volRemaining = self.GetBestMatchText()
            bestMatchDetails.text = bestMatchText
            bestMatchDetails.SetAlpha(0.6)
            if volRemaining:
                vol = tooltipPanel.AddLabelSmall(text=volRemaining,
                                                 align=uiconst.CENTERRIGHT,
                                                 colSpan=tooltipPanel.columns)
                vol.SetAlpha(0.6)

    def GetDeltaText(self):
        price = self.GetPrice()
        percentage = (price - self.averagePrice) / self.averagePrice
        if percentage < 0:
            color = '<color=0xffff5050>'
        else:
            color = '<color=0xff00ff00>'
        percText = '%s%s</color>' % (
            color,
            GetByLabel('UI/Common/Percentage',
                       percentage=FmtAmt(percentage * 100, showFraction=1)))
        return percText

    def GetBestMatchText(self):
        jumps = max(self.bestBid.jumps - max(0, self.bestBid.range), 0)
        minVolumeText = None
        if jumps == 0 and self.stationID == self.bestBid.stationID:
            jumpText = GetByLabel('UI/Market/MarketQuote/ItemsInSameStation')
        else:
            jumpText = GetByLabel('UI/Market/MarketQuote/JumpsFromThisSystem',
                                  jumps=jumps)
        if self.bestBid.minVolume > 1 and self.bestBid.volRemaining >= self.bestBid.minVolume:
            minVolumeText = GetByLabel(
                'UI/Market/MarketQuote/SimpleMinimumVolume',
                min=self.bestBid.minVolume)
        return (GetByLabel('UI/Market/MarketQuote/SellQuantity',
                           volRemaining=long(self.bestBid.volRemaining),
                           jumpText=jumpText), minVolumeText)

    def GetDelta(self):
        price = self.GetPrice()
        percentage = (price - self.averagePrice) / self.averagePrice
        return percentage

    def UpdateDelta(self):
        delta = self.GetDelta()
        self.deltaContainer.UpdateDelta(delta)

    def DrawItem(self):
        iconCont = Container(parent=self.textCont,
                             align=uiconst.TOLEFT,
                             width=32,
                             padding=4)
        self.icon = Icon(parent=iconCont,
                         typeID=self.typeID,
                         state=uiconst.UI_DISABLED)
        self.icon.SetSize(32, 32)
        itemName = GetByLabel('UI/Contracts/ContractsWindow/ShowInfoLink',
                              showInfoName=self.itemName,
                              info=('showinfo', self.typeID, self.item.itemID))
        self.itemNameLabel = Label(text=itemName,
                                   parent=self.textCont,
                                   left=40,
                                   align=uiconst.CENTERLEFT,
                                   state=uiconst.UI_NORMAL,
                                   autoFadeSides=35,
                                   fontsize=12)

    def GetBestPrice(self):
        bestMatchableBid = self.quote.GetBestMatchableBid(
            self.typeID, self.stationID, self.item.stacksize)
        if bestMatchableBid:
            self.bestPrice = bestMatchableBid.price
        else:
            self.bestPrice = self.averagePrice

    def GetBrokersFee(self):
        fee = self.quote.BrokersFee(self.stationID, self.totalSum,
                                    self.limits['fee'])
        feeAmount = fee.amt
        self.brokersFee = feeAmount

    def GetSalesTax(self):
        tax = self.totalSum * self.limits['acc']
        self.salesTax = tax

    def GetTotalSum(self):
        price = self.GetPrice()
        qty = self.GetQty()
        self.totalSum = price * qty
        self.totalLabel.text = FmtISK(self.totalSum)
        return self.totalSum

    def OnChange(self, *args):
        self.GetTotalSum()
        self.GetBrokersFee()
        self.GetSalesTax()
        self.UpdateDelta()
        if self.parentEditFunc:
            self.parentEditFunc(args)

    def GetPrice(self):
        price = self.priceEdit.GetValue()
        return price

    def GetQty(self):
        qty = self.qtyEdit.GetValue()
        return qty

    def MakeSingle(self):
        self.height = 80
        self.qtyCont.width = 0
        self.itemCont.width = 0.42
        self.totalCont.width = 0.36
        self.itemNameLabel.fontsize = 14
        self.totalLabel.fontsize = 14
        self.itemNameLabel.left = 72
        self.icon.SetSize(64, 64)
        self.icon.top = 4
        self.priceEdit.padLeft = 4
        self.priceEdit.align = uiconst.TOBOTTOM
        self.qtyEdit.top = 20
        self.priceEdit.top = 20
        self.qtyEdit.SetParent(self.priceCont)

    def RemoveSingle(self):
        self.height = 40
        self.qtyCont.width = 0.15
        self.itemCont.width = 0.33
        self.totalCont.width = 0.3
        self.itemNameLabel.fontsize = 12
        self.totalLabel.fontsize = 12
        self.itemNameLabel.left = 40
        self.icon.SetSize(32, 32)
        self.icon.top = 0
        self.priceEdit.align = uiconst.TOTOP
        self.qtyEdit.top = 11
        self.priceEdit.top = 11
        self.priceEdit.padLeft = 8
        self.qtyEdit.SetParent(self.qtyCont)
示例#10
0
class PurchaseDetailsPanel(BasePurchasePanel):
    default_name = 'purchaseDetailsPanel'

    def ApplyAttributes(self, attributes):
        super(PurchaseDetailsPanel, self).ApplyAttributes(attributes)
        self.button = None
        self.offer = attributes.offer
        self.aurumBalance = attributes.aurumBalance
        self.buyOfferCallback = attributes.buyOfferCallback
        self.previewCallback = attributes.previewCallback
        self.CreateProductLayout(self.offer)
        self.CreateBuyLayout(self.offer, self.aurumBalance)

    def CreateProductLayout(self, offer):
        productContainer = Container(name='productContainer',
                                     parent=self,
                                     align=uiconst.TOTOP,
                                     height=PRODUCTSCROLL_PANEL_HEIGHT)
        productScroll = ScrollContainer(parent=productContainer,
                                        align=uiconst.TOALL,
                                        padTop=16)
        productQuantities = GetSortedTokens(offer.productQuantities)
        for typeID, quantity in productQuantities:
            VgsDetailProduct(parent=productScroll,
                             typeID=typeID,
                             quantity=quantity,
                             onClick=self.previewCallback)

    def CreateBuyLayout(self, offer, aurumBalance):
        self.buyContainer = Container(name='buyContainer',
                                      parent=self,
                                      align=uiconst.TOTOP,
                                      height=BUY_PANEL_HEIGHT)
        self.priceLabel = AurLabelLarge(parent=self.buyContainer,
                                        align=uiconst.TOLEFT,
                                        amount=offer.price,
                                        baseAmount=offer.basePrice,
                                        padding=(10, 7, 0, 6))
        self.button = DetailButton(parent=self.buyContainer,
                                   align=uiconst.TORIGHT,
                                   left=TEXT_PADDING,
                                   padTop=8,
                                   padBottom=8)
        self.UpdateButton(offer.price)
        self.quantityEdit = SinglelineEdit(
            parent=self.buyContainer,
            integermode=True,
            width=40,
            fontsize=VGS_FONTSIZE_MEDIUM,
            align=uiconst.TORIGHT,
            left=TEXT_PADDING,
            padTop=6,
            padBottom=10,
            bgColor=TAG_COLOR,
            OnChange=self.OnQuantityChange,
            maxLength=2,
            hint=localization.GetByLabel('UI/Common/Quantity'))
        self.quantityEdit.IntMode(minint=QUANTITY_MIN, maxint=QUANTITY_MAX)
        self.quantityEdit.sr.background.Hide()

    def UpdateButton(self, offerPrice):
        if self.aurumBalance >= offerPrice:
            buttonLabel = localization.GetByLabel(
                'UI/VirtualGoodsStore/OfferDetailBuyNowButton')
            buttonFunc = self.OnBuyClick
            color = BUY_BUTTON_COLOR
        else:
            buttonLabel = localization.GetByLabel(
                'UI/VirtualGoodsStore/BuyAurOnline')
            buttonFunc = self._BuyAurum
            color = BUY_AUR_BUTTON_COLOR
        self.button.OnClick = buttonFunc
        self.button.SetText(buttonLabel)
        self.button.color.SetRGB(*color)

    def OnQuantityChange(self, text):
        try:
            quantity = int(text)
            quantity = max(QUANTITY_MIN, min(quantity, QUANTITY_MAX))
        except ValueError:
            quantity = QUANTITY_MIN

        newOfferPrice = self.offer.price * quantity
        self.priceLabel.SetAmount(newOfferPrice,
                                  self.offer.basePrice * quantity)
        self.UpdateButton(newOfferPrice)

    def _BuyAurum(self):
        sm.GetService('audio').SendUIEvent('store_aur')
        sm.GetService('viewState').GetView(
            ViewState.VirtualGoodsStore)._LogBuyAurum('DetailButton')
        uicore.cmd.BuyAurumOnline()

    def OnBuyClick(self, *args):
        logger.debug('OnBuyClick %s' % (self.offer, ))
        sm.GetService('audio').SendUIEvent('store_buy')
        self.button.Disable()
        self.buyOfferCallback(self.offer,
                              quantity=self.quantityEdit.GetValue())
示例#11
0
class LabelEditable(Container):
    default_height = 40
    default_width = 100
    default_align = uiconst.TOPLEFT
    default_state = uiconst.UI_PICKCHILDREN

    def ApplyAttributes(self, attributes):
        Container.ApplyAttributes(self, attributes)
        self.defaultText = attributes.get('defaultText', None)
        self.currentText = attributes['text']
        hint = attributes.get('hint', None)
        self.configName = attributes['configName']
        self.maxLength = attributes.get('maxLength', None)
        self.minLength = attributes.get('minLength', None)
        fontsize = attributes.get('fontsize', DEFAULT_FONTSIZE)
        self.editField = SinglelineEdit(name='editField',
                                        parent=self,
                                        align=uiconst.CENTERLEFT,
                                        pos=(0, 0, 100, 0),
                                        setvalue=self.currentText,
                                        OnFocusLost=self.OnEditFieldLostFocus,
                                        OnChange=self.OnEditFieldChanged,
                                        OnReturn=self.OnEditFieldLostFocus,
                                        maxLength=self.maxLength,
                                        fontsize=fontsize)
        self.editField.display = False
        self.textLabel = Label(name='textLabel',
                               parent=self,
                               left=SinglelineEdit.TEXTLEFTMARGIN +
                               self.editField._textClipper.padLeft,
                               state=uiconst.UI_NORMAL,
                               maxLines=1,
                               align=uiconst.CENTERLEFT,
                               fontsize=self.editField.sr.text.fontsize,
                               text=self.currentText)
        self.textLabel.color.SetRGBA(1.0, 1.0, 1.0, 1.0)
        self.textLabel.cursor = uiconst.UICURSOR_IBEAM
        self.editField.width = self.textLabel.textwidth + 20
        self.width = self.editField.width
        self.height = self.editField.height
        self.textLabel.OnClick = self.OnLabelClicked
        if hint:
            self.textLabel.hint = hint

    def OnLabelClicked(self, *args):
        self.textLabel.display = False
        self.editField.display = True
        uicore.registry.SetFocus(self.editField)

    def OnEditFieldLostFocus(self, *args):
        currentText = self.currentText
        if self.minLength and len(
                currentText) < self.minLength and self.defaultText:
            currentText = self.defaultText
            self.SetValue(currentText)
        self.textLabel.display = True
        self.editField.display = False
        settings.user.ui.Set(self.configName, currentText)

    def OnEditFieldChanged(self, *args):
        self.currentText = self.editField.GetValue()
        self.textLabel.text = self.currentText
        self.editField.width = self.editField.sr.text.textwidth + 20
        self.width = self.editField.width

    def GetValue(self):
        return self.currentText.strip()

    def SetValue(self, text):
        self.currentText = text
        self.textLabel.text = self.currentText
        self.editField.SetText(text)
        self.OnEditFieldChanged()
class ChannelPasswordWindow(Window):
    MAX_TRIES = 3

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        self.title = attributes.title
        self.channelID = attributes.channelID
        self.channelName = attributes.channelName
        self.displayName = attributes.displayName
        self.SetMinSize([250, 250])
        self.SetCaption(localization.GetByLabel('UI/Menusvc/PasswordRequired'))
        self.SetTopparentHeight(0)
        self.tries = 0
        settings.user.ui.Set('%sPassword' % self.channelName, '')
        parentGrid = LayoutGrid(parent=self.sr.main,
                                columns=1,
                                state=uiconst.UI_PICKCHILDREN,
                                align=uiconst.TOPLEFT,
                                left=10,
                                top=4)
        topLabel = EveLabelMedium(text=attributes.title,
                                  state=uiconst.UI_DISABLED,
                                  align=uiconst.TOPLEFT,
                                  width=300)
        parentGrid.AddCell(cellObject=topLabel)
        passwordLabel = localization.GetByLabel(
            'UI/Menusvc/PleaseEnterPassword')
        self.passwordLabel = EveLabelMedium(text=passwordLabel,
                                            state=uiconst.UI_DISABLED,
                                            align=uiconst.TOPLEFT,
                                            padTop=10)
        parentGrid.AddCell(cellObject=self.passwordLabel)
        self.passwordEdit = SinglelineEdit(name='passwordEdit',
                                           align=uiconst.TOTOP,
                                           passwordCharacter=u'\u2022',
                                           top=4)
        parentGrid.AddCell(cellObject=self.passwordEdit)
        savePasswordLabel = localization.GetByLabel('UI/Chat/SavePassword')
        self.rememberPwdCb = Checkbox(text=savePasswordLabel,
                                      configName='rememberPwdCb',
                                      retval=1,
                                      checked=0,
                                      groupname=None,
                                      align=uiconst.TOTOP)
        parentGrid.AddCell(cellObject=self.rememberPwdCb)
        parentGrid.RefreshGridLayout()
        self.btnGroup = ButtonGroup(parent=self.sr.main, idx=0)
        self.btnGroup.AddButton(
            localization.GetByLabel('UI/Chat/ChannelWindow/JoinChannel'),
            self.TryPassword, ())
        self.btnGroup.AddButton(localization.GetByLabel('UI/Common/Cancel'),
                                self.Close, ())
        self.height = self.btnGroup.height + parentGrid.height + self.sr.headerParent.height + parentGrid.top + 10
        self.width = parentGrid.width + 2 * parentGrid.left
        self.MakeUnResizeable()
        self.MakeUnMinimizable()
        self.MakeUncollapseable()

    def TryPassword(self):
        password = self.passwordEdit.GetValue()
        password = password.strip()
        if len(password) < 1:
            eve.Message('CustomInfo', {
                'info':
                localization.GetByLabel('UI/Common/PleaseTypeSomething')
            })
            return
        self.tries += 1
        savePassword = self.rememberPwdCb.GetValue()
        didWork = sm.GetService('LSC').TryOpenChannel(self.channelID,
                                                      self.channelName,
                                                      password, savePassword)
        if didWork is True:
            self.Close()
            return
        self.passwordEdit.SetValue('')
        uicore.Message('uiwarning03')
        self.passwordLabel.text = localization.GetByLabel(
            'UI/Menusvc/PleaseTryEnteringPasswordAgain')
        if self.tries >= self.MAX_TRIES:
            if didWork is False and password is not None:
                sm.GetService('LSC').OpenChannel(
                    self.channelID, 0, ('LSCWrongPassword', {
                        'channelName': self.displayName
                    }))
            self.Close()
示例#13
0
class PerformanceBenchmarkWindow(Window):
    default_caption = 'Performance Tools'
    default_windowID = 'PerformanceToolsWindowID'
    default_width = 220
    default_height = 200
    default_topParentHeight = 0
    default_minSize = (default_width, default_height)
    default_wontUseThis = 10

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        self.lastPitch = 0.0
        self.lastYaw = 0.0
        self.camLock = False
        self.benchmarkDuration = BENCHMARK_DEFAULT_DURATION_IN_MS
        self.benchmarkRunning = False
        self.sceneDirector = SceneDirector()
        self.testOptions = [('classic cube of death', CUBE_CLASSIC),
                            ('capital wrecks of death', CUBE_CAPITAL_WRECKS),
                            ('AmarrCube', CUBE_AMARR),
                            ('CaldariCube', CUBE_CALDARI),
                            ('GallenteCube', CUBE_GALLENTE),
                            ('MinmatarCube', CUBE_MINMATAR),
                            ('UltraLODCube', CUBE_LOD),
                            ('Add More Here', CUBE_ADD_MORE_HERE)]
        self.testCaseDescription = {
            CUBE_CLASSIC: 'Spawns a cube with a lot of different ships.',
            CUBE_CAPITAL_WRECKS: 'Spawns a cube with a lot of wrecks.',
            CUBE_AMARR: 'Spawns a cube of Amarr ships.',
            CUBE_CALDARI: 'Spawns a cube of Caldari ships.',
            CUBE_GALLENTE: 'Spawns a cube of Gallente ships.',
            CUBE_MINMATAR: 'Spawns a cube of Minmatar ships.',
            CUBE_LOD: 'Spawns a cube of ships around the camera.',
            CUBE_ADD_MORE_HERE: 'Does nothing useful.'
        }
        self.camPresetOptions = [('None', CAMERA_PRESET_NONE),
                                 ('Deathcube Far', CAMERA_PRESET_FAR),
                                 ('Deathcube Near', CAMERA_PRESET_NEAR),
                                 ('Deathcube UltraLOD',
                                  CAMERA_PRESET_ULTRA_LOD)]
        self._AddHeader('Test Cases')
        self._SetupTestCasePanel(self.sr.main)
        self._AddHeader('Camera')
        self._SetupCameraPanel(self.sr.main)
        self._AddHeader('Duration')
        self._SetupDurationPanel(self.sr.main)
        self.benchmarkButton = Button(name='myButton',
                                      parent=self.sr.main,
                                      align=uiconst.CENTERBOTTOM,
                                      label='Start Benchmark',
                                      func=self.ToggleBenchmark,
                                      width=40,
                                      padding=(0, 0, 0, 6))

    def _AddHeader(self, text):
        EveHeaderSmall(parent=self.sr.main,
                       text=text,
                       align=uiconst.TOTOP,
                       padding=(8, 6, 0, 3))

    def _SetupTestCasePanel(self, mainCont):
        cont = Container(name='cont',
                         parent=mainCont,
                         align=uiconst.TOTOP,
                         padLeft=4,
                         padRight=4,
                         height=40)
        self.testCombo = Combo(parent=cont,
                               align=uiconst.TOTOP,
                               options=self.testOptions,
                               callback=self.TestComboChanged)
        self.testCombo.SetHint(self.testCaseDescription[1])
        buttonBox = Container(name='buttonBox',
                              parent=cont,
                              align=uiconst.TOTOP,
                              padTop=3,
                              height=20)
        self.stayHereCheckbox = Checkbox(parent=buttonBox,
                                         text=u'Stay where you are',
                                         align=uiconst.TOLEFT,
                                         checked=False,
                                         height=18,
                                         width=120)
        Button(parent=buttonBox,
               label='Spawn',
               align=uiconst.TORIGHT,
               func=self.SpawnTestcase,
               width=40,
               height=18)
        Button(parent=buttonBox,
               label='Clear',
               align=uiconst.TORIGHT,
               func=self.sceneDirector.ClearAll,
               width=40,
               height=18)
        Button(parent=buttonBox,
               label='Damage',
               align=uiconst.TORIGHT,
               func=self.sceneDirector.ApplyDamage,
               width=40,
               height=18,
               hint='Wait for ships to load before calling this')

    def _SetupCameraPanel(self, mainCont):
        presetCont = Container(name='presetCont',
                               parent=mainCont,
                               align=uiconst.TOTOP,
                               height=20,
                               padLeft=4,
                               padRight=4)
        Label(name='presetCombo',
              parent=presetCont,
              align=uiconst.TOLEFT,
              width=40,
              text='Preset')
        self.cboCamPresets = Combo(parent=presetCont,
                                   align=uiconst.TOTOP,
                                   options=self.camPresetOptions,
                                   callback=self.OnCamPreset)
        pitchCont = Container(name='pitchCont',
                              parent=mainCont,
                              align=uiconst.TOTOP,
                              height=20,
                              padLeft=4,
                              padRight=4)
        Label(name='pitchLabel',
              parent=pitchCont,
              align=uiconst.TOLEFT,
              width=40,
              padTop=3,
              text='Pitch')
        self.pitchField = SinglelineEdit(name='pitchField',
                                         parent=pitchCont,
                                         align=uiconst.TOTOP,
                                         floats=[-90.0, 90.0, 1],
                                         setvalue=str(self.lastPitch))
        self.pitchField.OnChange = self.OnCamChange
        yawCont = Container(name='yawCont',
                            parent=mainCont,
                            align=uiconst.TOTOP,
                            height=20,
                            padLeft=4,
                            padRight=4)
        Label(name='yawLabel',
              parent=yawCont,
              align=uiconst.TOLEFT,
              width=40,
              padTop=3,
              text='Yaw')
        self.yawField = SinglelineEdit(name='yawField',
                                       parent=yawCont,
                                       align=uiconst.TOTOP,
                                       floats=[-180.0, 180.0, 1],
                                       setvalue=str(self.lastYaw))
        self.yawField.OnChange = self.OnCamChange
        panCont = Container(name='panCont',
                            parent=mainCont,
                            align=uiconst.TOTOP,
                            height=20,
                            padLeft=4,
                            padRight=4)
        Label(name='panLabel',
              parent=panCont,
              align=uiconst.TOLEFT,
              width=40,
              padTop=3,
              text='Pan')
        self.panField = SinglelineEdit(
            name='panField',
            parent=panCont,
            align=uiconst.TOTOP,
            ints=[MIN_PAN_DISTANCE, MAX_PAN_DISTANCE],
            setvalue=0)
        self.panField.OnChange = self.OnCamChange
        buttonBox = Container(name='buttonBox',
                              parent=mainCont,
                              align=uiconst.TOTOP,
                              padTop=3,
                              height=20)
        Button(
            parent=buttonBox,
            label='Capture camera coords',
            align=uiconst.TORIGHT,
            func=self.OnStoreCurrentCameraValues,
            width=40,
            height=18,
            hint=
            'Captures the current camera coordinates and saves them in the input fields'
        )
        uthread.new(self._GetCurrentCameraValues)

    def _SetupDurationPanel(self, parent):
        maxSeconds = int(BENCHMARK_MAX_DURATION_IN_MS / 1000)
        defaultSeconds = int(BENCHMARK_DEFAULT_DURATION_IN_MS / 1000)
        self.durationSlider = Slider(
            name='mySlider',
            parent=parent,
            minValue=1,
            maxValue=maxSeconds,
            startVal=defaultSeconds,
            increments=[i + 1 for i in xrange(maxSeconds)],
            onsetvaluefunc=self._OnTimeChanged,
            align=uiconst.TOTOP,
            padLeft=10,
            padRight=10)
        self.progress = Gauge(name='progress',
                              parent=parent,
                              color=Color.WHITE,
                              align=uiconst.TOTOP,
                              padTop=20,
                              padLeft=10,
                              padRight=10)
        self._OnTimeChanged(self.durationSlider)

    def _OnTimeChanged(self, slider):
        self.benchmarkDuration = slider.GetValue() * 1000

    def TestComboChanged(self, *args):
        self.testCombo.SetHint(
            self.testCaseDescription[self.testCombo.GetValue()])

    def OnCamChange(self, *args):
        if self.camLock:
            return
        self.lastPitch = float(self.pitchField.GetValue())
        self.lastYaw = float(self.yawField.GetValue())
        self.pan = int(self.panField.GetValue())
        self.sceneDirector.SetCamera(self.lastYaw, self.lastPitch, self.pan)

    def OnCamPreset(self, *args):
        presId = self.cboCamPresets.GetValue()
        if presId == 0:
            return
        pitch, yaw, pan = CAMERA_PRESETS[presId]
        self.camLock = True
        self.pitchField.SetValue(pitch)
        self.yawField.SetValue(yaw)
        self.panField.SetValue(pan)
        self.camLock = False
        self.OnCamChange()

    def _GetMemoryUsage(self):
        try:
            meg = 1.0 / 1024.0 / 1024.0
            mem, pymem, workingset, pagefaults, bluemem = blue.pyos.cpuUsage[
                -1][2]
            return mem * meg
        except:
            pass

        return 0

    def ToggleBenchmark(self, *args):
        self.progress.SetValue(0)

        def _thread():
            frameTimes = []
            graphData = {}
            t0 = blue.os.GetWallclockTime()
            startTime = blue.os.GetWallclockTime()
            startMem = self._GetMemoryUsage()
            while self.benchmarkRunning:
                blue.synchro.Yield()
                t1 = blue.os.GetWallclockTime()
                ms = float(blue.os.TimeDiffInUs(t0, t1)) / 1000.0
                t0 = t1
                frameTimes.append(ms)
                timeFromStartInMs = float(blue.os.TimeDiffInUs(startTime,
                                                               t1)) / 1000.0
                graphData[timeFromStartInMs] = ms
                if blue.os.TimeDiffInMs(startTime,
                                        t1) > self.benchmarkDuration:
                    self.benchmarkRunning = False
                    break
                self.progress.SetValue(timeFromStartInMs /
                                       self.benchmarkDuration,
                                       animate=False)

            frameTimes.sort()
            median = frameTimes[len(frameTimes) / 2]
            minMS = frameTimes[0]
            maxMS = frameTimes[-1]
            summed = reduce(lambda x, y: x + y, frameTimes)
            avg = summed / len(frameTimes)
            result = 'Min: %0.1fms Max: %0.1fms\n' % (minMS, maxMS)
            result += 'Median:  %0.1fms %0.1ffps\n' % (median, 1000.0 / median)
            result += 'Average: %0.1fms %0.1ffps\n' % (avg, 1000.0 / avg)
            endMem = self._GetMemoryUsage()
            result += 'Start Memory Usage: %0.1fmb\n' % (startMem, )
            result += 'End Memory Usage: %0.1fmb\n' % (endMem, )
            ResultDialog.Open(resultText=result, graphData=graphData)
            self.benchmarkButton.SetLabel('Start Benchmark')

        if self.benchmarkRunning:
            self.benchmarkRunning = False
        else:
            self.benchmarkRunning = True
            self.benchmarkButton.SetLabel('Stop Benchmark')
            uthread.new(_thread)

    def OnStoreCurrentCameraValues(self, *args):
        self._GetCurrentCameraValues()

    def _GetCurrentCameraValues(self):
        self.camLock = True
        cam = sm.GetService('sceneManager').GetActiveCamera()
        self.lastPitch = math.degrees(cam.pitch)
        self.lastYaw = math.degrees(cam.yaw)
        self.pan = pan = ClampPan(int(cam.GetZoomDistance()))
        self.pitchField.SetValue(self.lastPitch)
        self.yawField.SetValue(self.lastYaw)
        self.panField.SetValue(self.pan)
        self.camLock = False
        self.OnCamChange()

    def SpawnTestcase(self, *args):
        testID = self.testCombo.GetValue()
        stayHere = self.stayHereCheckbox.GetValue()
        startPos = self.sceneDirector.GoToAndReturnStartPosition(stayHere)
        self.sceneDirector.SpawnTestcase(testID, startPos)
示例#14
0
class AttributeInspector(Window):
    __guid__ = 'form.AttributeInspector'
    default_windowID = 'AttributeInspector'

    def __init__(self, **kwargs):
        super(AttributeInspector, self).__init__(**kwargs)

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        self.itemID = attributes.itemID
        self.typeID = attributes.typeID
        self.nameFilter = None
        self.stateManager = sm.GetService('godma').GetStateManager()
        self.SetCaption('Attribute Inspector')
        self.SetWndIcon(None)
        self.SetTopparentHeight(0)
        main = Container(name='main',
                         parent=uiutil.GetChild(self, 'main'),
                         pos=(const.defaultPadding, const.defaultPadding,
                              const.defaultPadding, const.defaultPadding))
        top = Container(name='top',
                        parent=main,
                        height=20,
                        align=uiconst.TOTOP)
        Button(parent=top,
               label='Refresh',
               align=uiconst.TORIGHT,
               func=self.Refresh)
        self.input = SinglelineEdit(name='itemID',
                                    parent=top,
                                    width=-1,
                                    height=-1,
                                    align=uiconst.TOALL)
        self.input.readonly = not eve.session.role & ROLE_GMH
        self.input.OnReturn = self.Refresh
        self.input.SetValue(str(self.itemID))
        Container(name='div', parent=main, height=5, align=uiconst.TOTOP)
        self.scroll = Scroll(parent=main)
        self.Refresh()

    def _GetListEntryForAttr(self, attrID, attrName, clientValsByAttrID,
                             godmaValsByAttrID, serverValsByAttrID,
                             baseValsByAttrID):
        notApplicable = '<color=green>[n/a]</color>'
        try:
            clientValue = clientValsByAttrID[attrID]
        except KeyError:
            clientValue = notApplicable

        try:
            godmaValue = self.stateManager.GetAttribute(self.itemID, attrName)
        except KeyError:
            godmaValue = notApplicable

        try:
            serverValue = serverValsByAttrID[attrID]
        except KeyError:
            serverValue = notApplicable

        try:
            baseValue = baseValsByAttrID[attrID]
        except KeyError:
            baseValue = notApplicable

        color = (0, 0, 0, 0)
        if godmaValue != serverValue:
            color = (1, 0, 0, 0.25)
        elif baseValue == notApplicable:
            color = (1, 1, 0, 0.25)
        baseColor = serverColor = clientColor = godmaColor = ''
        if clientValue != godmaValue:
            if clientValue == serverValue:
                clientColor = 'yellow'
            elif clientValue == baseValue:
                clientColor = 'blue'
            else:
                clientColor = 'red'
        if godmaValue != serverValue:
            if godmaValue == baseValue:
                godmaColor = 'blue'
            else:
                godmaColor = 'red'
        if serverValue != baseValue:
            serverColor = 'yellow'
        colorize = '<color={}>{}</color>'
        if clientColor:
            clientValue = colorize.format(clientColor, clientValue)
        if godmaColor:
            godmaValue = colorize.format(godmaColor, godmaValue)
        if serverColor:
            serverValue = colorize.format(serverColor, serverValue)
        entry = listentry.Get(
            'DgmAttrEntry', {
                'label':
                u'{attrID}<t>{attrName}<t>{clientValue}<t>{godmaValue}<t>{serverValue}<t>{baseValue}'
                .format(**locals()),
                'color':
                color,
                'attributeID':
                attrID,
                'attributeName':
                attrName,
                'actualValue':
                godmaValue,
                'baseValue':
                baseValue,
                'ShowAttribute':
                self.ShowAttribute,
                'itemID':
                self.itemID
            })
        return entry

    def AttrID_FromName(self, attrName):
        attrID = self.stateManager.attributesByName[attrName].attributeID
        return attrID

    def AttrName_FromID(self, attrID):
        attrName = self.stateManager.attributesByID[attrID].attributeName
        return attrName

    def _GetClientValsByAttrID(self):
        cDLM = sm.GetService('clientDogmaIM').GetDogmaLocation()
        try:
            clientDogmaAttribs = cDLM.dogmaItems[self.itemID].attributes
            clientValsByAttribID = {
                attrID: clientDogmaAttribs[attrID].GetValue()
                for attrID in clientDogmaAttribs
            }
        except KeyError:
            clientValsByAttribID = {}

        return clientValsByAttribID

    def _GetGodmaValsByAttrID(self):
        godmaValsByAttributeName = self.stateManager.GetAttributes(self.itemID)
        godmaValsByAttributeID = {
            self.AttrID_FromName(name): val
            for name, val in godmaValsByAttributeName.iteritems()
        }
        return godmaValsByAttributeID

    def _GetServerValsByAttrID(self):
        serverValsByAttribID = self.GetServerDogmaLM(
        ).QueryAllAttributesForItem(self.itemID)
        return serverValsByAttribID

    def _GetBaseValsByAttrID(self):
        baseValsByAttribID = sm.GetService('info').GetAttributeDictForType(
            self.typeID)
        return baseValsByAttribID

    def Refresh(self, *args):
        inputValue = self.input.GetValue()
        subLocPattern = '\\(\\d*L?, \\d*, \\d*\\)'
        subLocPart = re.match(subLocPattern, inputValue)
        if subLocPart:
            itemKey = subLocPart.group(0)
            itemID, flagID, typeID = itemKey.replace('(',
                                                     '').replace(')',
                                                                 '').split(',')
            self.itemID = (long(itemID), int(flagID), int(typeID))
            self.typeID = int(typeID)
        else:
            itemID = int(filter('0123456789'.__contains__, inputValue))
            if itemID != self.itemID or not self.typeID:
                self.itemID = itemID
                self.typeID = None
                m = util.Moniker('i2', GetLocationBindParams())
                if m.IsPrimed(self.itemID):
                    self.typeID = m.GetItem(self.itemID).typeID
        nameFilter = inputValue.replace(str(self.itemID), '').lstrip().rstrip()
        if nameFilter != self.nameFilter and (nameFilter.isalpha()
                                              or nameFilter == ''):
            self.nameFilter = nameFilter
        log.LogInfo('Refresh: itemID = %s, typeID = %s, nameFilter = %s' %
                    (self.itemID, self.typeID, self.nameFilter or 'None'))
        contentList = []
        if self.typeID:
            clientValsByAttrID = self._GetClientValsByAttrID()
            godmaValsByAttrID = self._GetGodmaValsByAttrID()
            serverValsByAttrID = self._GetServerValsByAttrID()
            baseValsByAttrID = self._GetBaseValsByAttrID()
            allMyAttribIDs = set(
                itertools.chain(clientValsByAttrID, godmaValsByAttrID,
                                serverValsByAttrID, baseValsByAttrID))
            for attrID in allMyAttribIDs:
                attrName = self.AttrName_FromID(attrID)
                if not self.nameFilter or self.nameFilter.lower(
                ) in attrName.lower():
                    contentList.append(
                        self._GetListEntryForAttr(attrID, attrName,
                                                  clientValsByAttrID,
                                                  godmaValsByAttrID,
                                                  serverValsByAttrID,
                                                  baseValsByAttrID))

        self.scroll.Load(contentList=contentList,
                         headers=[
                             'ID', 'Name', 'ClientVal', 'GodmaVal',
                             'ServerVal', 'Base'
                         ],
                         fixedEntryHeight=18)
        self.scroll.Sort('Name')

    def GetServerDogmaLM(self):
        return self.stateManager.GetDogmaLM()

    def ShowAttribute(self, attributeID, showServerSideGraph=True):
        l = locals
        attrName = self.stateManager.attributesByID[attributeID].attributeName
        try:
            godmaVal = self.stateManager.GetAttribute(self.itemID, attrName)
        except (KeyError, RuntimeError, ZeroDivisionError):
            sys.exc_clear()
            godmaVal = '[None]'

        serverValue, baseValue, extraInfo = self.GetDetailedServerValues(
            self.itemID, attributeID, godmaVal)
        if not showServerSideGraph:
            clientDogmaIM = sm.GetService('clientDogmaIM')
            clientDogmaLM = clientDogmaIM.GetDogmaLocation()
            extraInfo = ['Client-side Graph:', '']
            clientGraph = clientDogmaLM.DescribeModifierGraphForDebugWindow(
                self.itemID, attributeID).split('\n')
            extraInfo += clientGraph
        x = [
            'Godma/Server/Base values: {} {} {}'.format(
                godmaVal, serverValue, baseValue), ''
        ] + extraInfo
        x = [HTMLEncode(s) for s in x]
        title = 'Attribute Info: %s' % attrName
        bodyText = '<br>'.join(x)
        newWindow = AttributeDetailsWindow(caption=title, bodyText=bodyText)
        newWindow.SetActive()

    def GetDetailedServerValues(self, itemID, attributeID, godmaVal):
        l = locals
        sDLM = self.GetServerDogmaLM()
        descr = sDLM.FullyDescribeAttribute(
            itemID, attributeID,
            'Just Inspecting -- Godma Value on client was %s.' % godmaVal)
        serverValue = descr[2].split(':')[1]
        baseValue = descr[3].split(':')[1]
        extraInfo = descr[4:]
        extraInfo[0] = extraInfo[0].replace('Attribute modification graph:',
                                            'Server-side graph:')
        queriedValue = sDLM.QueryAttributeValue(itemID, attributeID)
        if str(queriedValue) != serverValue:
            LogNotice('INCONSISTENT!')
        return (serverValue, baseValue, extraInfo)
示例#15
0
class SellItemContainer(BuySellItemContainerBase):
    __guid__ = 'uicls.SellItemContainer'
    belowColor = '<color=0xffff5050>'
    aboveColor = '<color=0xff00ff00>'
    totaLabelPath = 'UI/Market/MarketQuote/AskTotal'

    def ApplyAttributes(self, attributes):
        self.item = attributes.item
        self.typeID = self.item.typeID
        BuySellItemContainerBase.ApplyAttributes(self, attributes)
        self.adjustQtyAndPriceTimer = None
        self.isUpdating = False
        self.singleton = self.item.singleton
        self.itemID = self.item.itemID
        self.itemName = evetypes.GetName(self.typeID)
        self.brokersFee = 0.0
        self.salesTax = 0.0
        self.totalSum = 0.0
        self.stationID = attributes.stationID
        self.limits = self.quoteSvc.GetSkillLimits(self.stationID)
        self.solarSystemID = attributes.solarSystemID
        self.regionID = self.GetRegionID()
        self.locationID = self.item.locationID
        self.bestBid = attributes.bestBid
        self.bestPrice = attributes.bestPrice
        self.totalStrikethroughLine = None
        self.priceAmountWarning = None
        self.deltaCont = Container(parent=self,
                                   align=uiconst.TORIGHT,
                                   width=30)
        theRestCont = Container(name='theRestCont',
                                parent=self,
                                align=uiconst.TOALL)
        self.totalCont = Container(name='totalCont',
                                   parent=theRestCont,
                                   align=uiconst.TORIGHT_PROP,
                                   width=0.3)
        self.priceCont = Container(name='priceCont',
                                   parent=theRestCont,
                                   align=uiconst.TORIGHT_PROP,
                                   width=0.22)
        self.qtyCont = Container(name='qtyCont',
                                 parent=theRestCont,
                                 align=uiconst.TORIGHT_PROP,
                                 width=0.15)
        self.itemCont = Container(name='itemCont',
                                  parent=theRestCont,
                                  align=uiconst.TORIGHT_PROP,
                                  width=0.33)
        self.deleteCont = Container(name='deleteCont',
                                    parent=self.itemCont,
                                    align=uiconst.TORIGHT,
                                    width=24)
        self.deleteButton = ButtonIcon(
            texturePath='res:/UI/Texture/Icons/73_16_210.png',
            pos=(0, 0, 16, 16),
            align=uiconst.CENTERRIGHT,
            parent=self.deleteCont,
            hint=GetByLabel('UI/Generic/RemoveItem'),
            idx=0,
            func=self.RemoveItem)
        self.deleteCont.display = False
        self.textCont = Container(name='textCont',
                                  parent=self.itemCont,
                                  align=uiconst.TOALL)
        self.errorBg = ErrorFrame(bgParent=self)
        self.DrawItem()
        self.DrawQty()
        self.DrawPrice()
        self.DrawTotal()
        self.DrawDelta()
        self.estimatedSellCount = self.GetSellCountEstimate()
        self.SetTotalSumAndLabel()
        self.brokersFeePerc = self.limits.GetBrokersFeeForLocation(
            self.stationID)
        self.UpdateBrokersFee()
        self.GetSalesTax()
        self.ShowNoSellOrders()
        self.UpdateOrderStateInUI()

    def GetRegionID(self):
        return cfg.mapSystemCache.Get(session.solarsystemid2).regionID

    def OnDurationChanged(self, duration):
        self.OnChange()

    def ShowNoSellOrders(self, force=False):
        if self.IsImmediateOrder() and (self.bestBid is None or force):
            uicore.animations.FadeIn(self.errorBg, 0.35, duration=0.3)

    def GetDuration(self):
        from eve.client.script.ui.shared.market.sellMulti import SellItems
        wnd = SellItems.GetIfOpen()
        if not wnd:
            return
        return wnd.durationCombo.GetValue()

    def DrawQty(self):
        qty = self.item.stacksize
        self.qtyEdit = SinglelineEdit(name='qtyEdit',
                                      parent=self.qtyCont,
                                      align=uiconst.TOTOP,
                                      top=11,
                                      padLeft=4)
        self.qtyEdit.IntMode(*(1, long(qty)))
        self.qtyEdit.SetValue(qty)
        self.qtyEdit.OnChange = self.OnChange
        self.qtyEdit.hint = GetByLabel('UI/Common/Quantity')

    def DrawPrice(self):
        self.priceEdit = SinglelineEdit(name='priceEdit',
                                        parent=self.priceCont,
                                        align=uiconst.TOTOP,
                                        top=11,
                                        padLeft=8)
        self.priceEdit.FloatMode(*(0.01, 9223372036854.0, 2))
        self.priceEdit.SetValue(self.bestPrice)
        self.priceEdit.OnChange = self.OnChange
        self.priceEdit.hint = GetByLabel('UI/Market/MarketQuote/AskPrice')

    def DrawDelta(self):
        self.deltaContainer = SellDeltaContainer(parent=self.deltaCont,
                                                 delta=self.GetDelta(),
                                                 func=self.OpenMarket,
                                                 align=uiconst.CENTERRIGHT)
        self.deltaContainer.LoadTooltipPanel = self.LoadDeltaTooltip
        self.UpdateDelta()

    def GetTradeWndClass(self):
        from eve.client.script.ui.shared.market.sellMulti import SellItems
        return SellItems

    def LoadDeltaTooltip(self, tooltipPanel, *args):
        tooltipPanel.LoadGeneric2ColumnTemplate()
        tooltipPanel.cellPadding = (4, 1, 4, 1)
        tooltipPanel.AddLabelLarge(
            text=GetByLabel('UI/Market/MarketQuote/AskPrice'))
        tooltipPanel.AddLabelLarge(text=FmtISK(self.priceEdit.GetValue()),
                                   align=uiconst.CENTERRIGHT)
        tooltipPanel.AddSpacer(1, 8, colSpan=tooltipPanel.columns)
        tooltipPanel.AddLabelMedium(
            text='%s %s' %
            (GetByLabel('UI/Market/MarketQuote/RegionalAdverage'),
             self.GetDeltaText()))
        tooltipPanel.AddLabelMedium(text=FmtISK(self.averagePrice),
                                    align=uiconst.CENTERRIGHT)
        tooltipPanel.AddLabelMedium(
            text=GetByLabel('UI/Market/MarketQuote/BestRegional'))
        bestMatch = tooltipPanel.AddLabelMedium(text='',
                                                align=uiconst.CENTERRIGHT)
        bestMatchDetails = tooltipPanel.AddLabelSmall(
            text='', align=uiconst.CENTERRIGHT, colSpan=tooltipPanel.columns)
        if not self.bestBid:
            bestMatch.text = GetByLabel('UI/Contracts/ContractEntry/NoBids')
            bestMatchDetails.text = GetByLabel(
                'UI/Market/MarketQuote/ImmediateWillFail')
            bestMatch.color = (1.0, 0.275, 0.0, 1.0)
            bestMatchDetails.color = (1.0, 0.275, 0.0, 1.0)
        else:
            bestMatch.text = FmtISK(self.bestBid.price)
            bestMatchText, volRemaining = self.GetBestMatchText()
            bestMatchDetails.text = bestMatchText
            bestMatchDetails.SetAlpha(0.6)
            if volRemaining:
                vol = tooltipPanel.AddLabelSmall(text=volRemaining,
                                                 align=uiconst.CENTERRIGHT,
                                                 colSpan=tooltipPanel.columns)
                vol.SetAlpha(0.6)

    def GetBestMatchText(self):
        jumps = max(self.bestBid.jumps - max(0, self.bestBid.range), 0)
        minVolumeText = None
        if jumps == 0 and self.stationID == self.bestBid.stationID:
            jumpText = GetByLabel('UI/Market/MarketQuote/ItemsInSameStation')
        else:
            jumpText = GetByLabel('UI/Market/MarketQuote/JumpsFromThisSystem',
                                  jumps=jumps)
        if self.bestBid.minVolume > 1 and self.bestBid.volRemaining >= self.bestBid.minVolume:
            minVolumeText = GetByLabel(
                'UI/Market/MarketQuote/SimpleMinimumVolume',
                min=self.bestBid.minVolume)
        return (GetByLabel('UI/Market/MarketQuote/SellQuantity',
                           volRemaining=long(self.bestBid.volRemaining),
                           jumpText=jumpText), minVolumeText)

    def DrawItem(self):
        iconCont = Container(parent=self.textCont,
                             align=uiconst.TOLEFT,
                             width=32,
                             padding=4)
        self.iconInnerCont = Container(name='iconInnerCont',
                                       parent=iconCont,
                                       align=uiconst.CENTERLEFT,
                                       pos=(0, 0, 32, 32))
        self.wheel = LoadingWheel(parent=self.iconInnerCont,
                                  pos=(0, 0, 48, 48),
                                  align=uiconst.CENTER,
                                  idx=0)
        self.wheel.display = False
        self.techIcon = Sprite(parent=self.iconInnerCont,
                               pos=(0, 0, 16, 16),
                               align=uiconst.TOPLEFT,
                               state=uiconst.UI_NORMAL)
        self.icon = Icon(parent=self.iconInnerCont,
                         typeID=self.typeID,
                         state=uiconst.UI_DISABLED,
                         ignoreSize=True,
                         pos=(0, 0, 32, 32))
        GetTechLevelIcon(self.techIcon, 1, self.typeID)
        itemName = GetByLabel('UI/Contracts/ContractsWindow/ShowInfoLink',
                              showInfoName=self.itemName,
                              info=('showinfo', self.typeID, self.item.itemID))
        self.itemNameLabel = Label(text=itemName,
                                   parent=self.textCont,
                                   left=40,
                                   align=uiconst.CENTERLEFT,
                                   state=uiconst.UI_NORMAL,
                                   autoFadeSides=35,
                                   fontsize=12)

    def UpdateBrokersFee(self):
        fee = self.quoteSvc.BrokersFee(self.stationID, self.totalSum,
                                       self.brokersFeePerc)
        feeAmount = fee.amt
        self.brokersFee = feeAmount

    def GetSalesTax(self):
        tax = self.totalSum * self.limits['acc']
        self.salesTax = tax

    def GetTotalSum(self):
        self.GetTotalSumAndDisplaySum()
        return self.totalSum

    def GetTotalSumAndDisplaySum(self):
        price = self.GetPrice()
        qty = self.GetQty()
        sumToDisplay = price * qty
        totalSum = sumToDisplay
        if self.IsImmediateOrder():
            if self.estimatedSellCount == 0:
                totalSum = 0
            elif self.estimatedSellCount < qty:
                sumToDisplay = self.estimatedSellCount * price
                totalSum = sumToDisplay
        self.totalSum = totalSum
        return (totalSum, sumToDisplay)

    def UpdateTotalSumLabel(self, totalSum, sumToDisplay):
        self.totalLabel.text = FmtISK(sumToDisplay)
        if sumToDisplay != totalSum:
            self.ConstructTotalStrikethroughLine()
            self.totalStrikethroughLine.width = self.totalLabel.textwidth
        else:
            self.ChangeTotalStrikethroughDisplay(display=False)

    def OnChange(self, *args):
        if self.adjustQtyAndPriceTimer:
            self.adjustQtyAndPriceTimer.KillTimer()
        self.adjustQtyAndPriceTimer = AutoTimer(200,
                                                self.AdjustQtyAndPrice_thread,
                                                *args)
        self.SetItemLoading()

    def AdjustQtyAndPrice_thread(self, *args):
        self.adjustQtyTimer = None
        if self.destroyed:
            return
        self.estimatedSellCount = self.GetSellCountEstimate()
        self.SetTotalSumAndLabel()
        self.UpdateBrokersFee()
        self.GetSalesTax()
        self.deltaContainer.display = True
        self.UpdateDelta()
        self.wheel.display = False
        self.isUpdating = False
        if self.parentEditFunc:
            self.parentEditFunc(args)
        self.UpdateOrderStateInUI()

    def SetItemLoading(self):
        self.totalLabel.text = NA_CHAR
        self.deltaContainer.display = False
        self.wheel.display = True
        self.isUpdating = True

    def SetTotalSumAndLabel(self):
        totalSum, displaySum = self.GetTotalSumAndDisplaySum()
        self.UpdateTotalSumLabel(totalSum, displaySum)

    def UpdateOrderStateInUI(self):
        duration = self.GetDuration()
        if duration != 0:
            self.ChangePriceAmountWarningDisplay(display=False)
            self.HideNoSellOrders()
            return
        qty = self.GetQty()
        if self.estimatedSellCount == 0:
            self.ShowNoSellOrders(force=True)
            self.ChangePriceAmountWarningDisplay(display=False)
        elif self.estimatedSellCount < qty:
            self.HideNoSellOrders()
            self.PrepareWarningInfo(self.estimatedSellCount, qty)
        else:
            self.HideNoSellOrders()
            self.ChangePriceAmountWarningDisplay(display=False)

    def PrepareWarningInfo(self, estimatedSellCount, qtyToSell):
        self.ConstructPriceAmountWarning()
        self.ConstructQtyBg()
        self.ChangePriceAmountWarningDisplay(display=True)
        self.priceAmountWarning.info = (estimatedSellCount, qtyToSell)

    def GetPrice(self):
        price = self.priceEdit.GetValue()
        return price

    def GetQty(self):
        qty = self.qtyEdit.GetValue()
        return qty

    def GetQtyToSell(self):
        qty = self.GetQty()
        if self.IsImmediateOrder():
            return min(self.estimatedSellCount, qty)
        else:
            return qty

    def IsImmediateOrder(self):
        isImmediate = self.GetDuration() == 0
        return isImmediate

    def SetQtyAndPrice(self, newQty, newPrice):
        self.qtyEdit.SetValue(newQty)
        self.priceEdit.SetValue(newPrice)
        self.OnChange()

    def GetSellCountEstimate(self):
        return self.quoteSvc.GetSellCountEstimate(self.typeID, self.stationID,
                                                  self.GetPrice(),
                                                  self.GetQty())

    def MakeSingle(self):
        self.height = 80
        self.qtyCont.width = 0
        self.itemCont.width = 0.42
        self.totalCont.width = 0.36
        self.itemNameLabel.fontsize = 14
        self.totalLabel.fontsize = 14
        self.itemNameLabel.left = 72
        self.icon.SetSize(64, 64)
        self.wheel.SetSize(64, 64)
        self.iconInnerCont.SetSize(64, 64)
        self.priceEdit.padLeft = 4
        self.priceEdit.align = uiconst.TOBOTTOM
        self.qtyEdit.top = 20
        self.priceEdit.top = 20
        self.qtyEdit.SetParent(self.priceCont)
        if self.priceAmountWarning:
            self.priceAmountWarning.top = -10

    def RemoveSingle(self):
        self.height = 40
        self.qtyCont.width = 0.15
        self.itemCont.width = 0.33
        self.totalCont.width = 0.3
        self.itemNameLabel.fontsize = 12
        self.totalLabel.fontsize = 12
        self.itemNameLabel.left = 40
        self.icon.SetSize(32, 32)
        self.wheel.SetSize(48, 48)
        self.iconInnerCont.SetSize(32, 32)
        self.priceEdit.align = uiconst.TOTOP
        self.qtyEdit.top = 11
        self.priceEdit.top = 11
        self.priceEdit.padLeft = 8
        self.qtyEdit.SetParent(self.qtyCont)
        if self.priceAmountWarning:
            self.priceAmountWarning.top = 0

    def ConstructPriceAmountWarning(self):
        if self.priceAmountWarning:
            return None
        cont = Container(name='priceAmountWarning',
                         parent=self.itemCont,
                         align=uiconst.TORIGHT,
                         left=-4,
                         width=16,
                         idx=0)
        self.priceAmountWarning = Sprite(
            parent=cont,
            pos=(0, 0, 16, 16),
            align=uiconst.CENTER,
            texturePath='res:/ui/texture/icons/44_32_7.png')
        self.priceAmountWarning.SetRGB(1.0, 0.3, 0.3, 0.8)
        self.priceAmountWarning.info = (None, None)
        self.priceAmountWarning.GetHint = self.GetWarningHint

    def ConstructQtyBg(self):
        if getattr(self.qtyEdit, 'warningBg', None):
            return
        warningBg = Fill(bgParent=self.qtyEdit, color=(1, 0, 0, 0.3))
        self.qtyEdit.warningBg = warningBg

    def ConstructTotalStrikethroughLine(self):
        if self.totalStrikethroughLine:
            return
        self.totalStrikethroughLine = Line(parent=self.totalCont,
                                           align=uiconst.CENTERRIGHT,
                                           pos=(2, 0, 0, 1),
                                           idx=0,
                                           color=(1, 1, 1, 0.8))

    def ChangeTotalStrikethroughDisplay(self, display=False):
        if self.totalStrikethroughLine:
            self.totalStrikethroughLine.display = display

    def ChangePriceAmountWarningDisplay(self, display=False):
        if self.priceAmountWarning:
            self.priceAmountWarning.display = display
        if getattr(self.qtyEdit, 'warningBg', None):
            self.qtyEdit.warningBg.display = display

    def GetWarningHint(self):
        estimatedSellCount, qtyToSell = self.priceAmountWarning.info
        if estimatedSellCount is None or qtyToSell is None:
            return
        txt = GetByLabel('UI/Market/MarketQuote/QtyPriceWarning',
                         estimatedSellNum=int(estimatedSellCount),
                         tryingToSellNum=qtyToSell)
        return txt
示例#16
0
class AutoBotWindow(Window):
    """ An Insider window which makes it easy to debug UI containers """
    default_windowID = 'AutoBotWindow'
    default_width = 360
    default_height = 300
    default_topParentHeight = 0
    default_minSize = (default_width, default_height)
    default_caption = 'AutoBot Control Box'

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        self.CreateLocationSelector()
        self.CreateSecurityFilter()
        self.CreateShipSelector()
        self.CreatePasses()
        self.CreateButtons()
        self.CreateLogDisplay()

    def CreateButtons(self):
        buttonCont = FlowContainer(name='SubCategoryButtons',
                                   parent=self.sr.main,
                                   centerContent=True,
                                   align=uiconst.TOBOTTOM,
                                   contentSpacing=(2, 1),
                                   state=uiconst.UI_PICKCHILDREN,
                                   padding=(0, 4, 0, 4))
        Button(parent=buttonCont,
               label='Roll out!!',
               func=self.StartBot,
               align=uiconst.NOALIGN,
               padding=2)
        Button(parent=buttonCont,
               label='Stop',
               func=self.StopBot,
               align=uiconst.NOALIGN,
               padding=2)
        Button(parent=buttonCont,
               label='Clear Log',
               func=self.ClearLogs,
               align=uiconst.NOALIGN,
               padding=2)

    def CreateLocationSelector(self):
        EveLabelSmall(
            parent=self.sr.main,
            text=
            '<color=orange>This is a tool for automating visits to solar systems and locations within them. There are several actions available while visiting each location.',
            align=uiconst.TOTOP,
            padding=4)
        EveLabelSmall(parent=self.sr.main,
                      text='Systems, Constellations or Regions',
                      align=uiconst.TOTOP,
                      padding=4)
        self.locationsEdit = EditPlainText(parent=self.sr.main,
                                           align=uiconst.TOTOP,
                                           height=50,
                                           padding=4)

    def CreateSecurityFilter(self):
        secCont = Container(parent=self.sr.main,
                            height=20,
                            padding=2,
                            align=uiconst.TOTOP)
        EveLabelSmall(parent=secCont,
                      text='Security Band:',
                      align=uiconst.TOLEFT,
                      padding=4)
        EveLabelSmall(parent=secCont,
                      text='Min Security',
                      align=uiconst.TOLEFT,
                      padding=4)
        self.minSecEdit = SinglelineEdit(parent=secCont,
                                         name='minSec',
                                         width=30,
                                         floats=(-1.0, 1.0, 1),
                                         align=uiconst.TOLEFT,
                                         padTop=-3,
                                         setvalue='-1.0')
        EveLabelSmall(parent=secCont,
                      text='Max Security',
                      align=uiconst.TOLEFT,
                      padding=4)
        self.maxSecEdit = SinglelineEdit(parent=secCont,
                                         name='maxSec',
                                         width=30,
                                         floats=(-1.0, 1.0, 1),
                                         align=uiconst.TOLEFT,
                                         padTop=-3,
                                         setvalue='1.0')

    def CreateShipSelector(self):
        cont = Container(parent=self.sr.main,
                         name='ship_options',
                         align=uiconst.TOTOP,
                         height=20)
        self.spawnShipCheckbox = Checkbox(parent=cont,
                                          align=uiconst.TOLEFT,
                                          text='Spawn new ship',
                                          checked=False,
                                          padLeft=8,
                                          callback=self.OnChangeSpawnShip,
                                          width=150)
        Container(parent=cont, width=16, align=uiconst.TOLEFT)
        EveLabelSmall(parent=cont, text='DNA', align=uiconst.TOLEFT, padding=4)
        self.dnaEdit = SinglelineEdit(parent=cont,
                                      setvalue='DNA:593:2528:20197',
                                      align=uiconst.TOLEFT,
                                      width=200)

    def CreatePasses(self):
        EveLabelSmall(parent=self.sr.main,
                      text='Actions for each system visited',
                      align=uiconst.TOTOP,
                      padding=4)
        self.CreateSystemPass(1)
        self.CreateSystemPass(2)

    def CreateSystemPass(self, passNumber):
        def GetLocationsMenu(menuParent):
            passConfig = GetPassConfig()[passNumber]
            menuParent.AddHeader(text='Locations to visit')
            for groupId in (const.groupAsteroidBelt, const.groupStargate,
                            const.groupStation):
                menuParent.AddCheckBox(
                    text=cfg.invgroups.Get(groupId).groupName,
                    checked=groupId in passConfig['locations'],
                    callback=(ToggleLocationGroupForPass, passNumber, groupId))

            menuParent.AddDivider()
            menuParent.AddHeader(text='Actions')
            menuParent.AddCheckBox(text='Nuke location',
                                   checked=passConfig['nuke'],
                                   callback=(ToggleNuke, passNumber))

        passConfig = {
            'locations': {const.groupAsteroidBelt},
            'nuke': False,
            'enabled': passNumber == 1,
            'minTime': 1
        }
        GetPassConfig()[passNumber] = passConfig
        menuCont = Container(name='pass%d' % passNumber,
                             parent=self.sr.main,
                             align=uiconst.TOTOP,
                             height=20,
                             padLeft=4)
        cont = Container(parent=menuCont, width=100, align=uiconst.TOLEFT)
        Checkbox(parent=cont,
                 text='Enable Pass %s' % passNumber,
                 align=uiconst.CENTERLEFT,
                 checked=passConfig['enabled'],
                 callback=lambda checkbox: SetPass(checkbox, passNumber),
                 width=200)
        cont = Container(parent=menuCont, width=100, align=uiconst.TOLEFT)
        EveLabelSmall(parent=cont,
                      text='Min time (sec)',
                      align=uiconst.CENTERRIGHT,
                      left=4)
        SinglelineEdit(
            parent=menuCont,
            ints=(1, 999),
            OnChange=lambda textValue: SetPassMinTime(textValue, passNumber),
            setvalue=passConfig['minTime'],
            align=uiconst.TOLEFT,
            width=50)
        UtilMenu(menuAlign=uiconst.TOPRIGHT,
                 parent=menuCont,
                 align=uiconst.TOLEFT,
                 GetUtilMenu=GetLocationsMenu,
                 label='Options',
                 texturePath='res:/UI/Texture/Icons/38_16_229.png',
                 closeTexturePath='res:/UI/Texture/Icons/38_16_230.png')

    def CreateLogDisplay(self):
        self.logEdit = EditPlainText(parent=self.sr.main,
                                     align=uiconst.TOALL,
                                     readonly=True,
                                     padTop=4)

    def OnChangeSpawnShip(self, checkbox):
        if checkbox.GetValue():
            self.dnaEdit.SetReadOnly(False)
            self.dnaEdit.opacity = 1.0
        else:
            self.dnaEdit.SetReadOnly(True)
            self.dnaEdit.opacity = 0.5

    def StartBot(self, *args):
        config = GetConfig()
        locations = SplitLocationsText(self.locationsEdit.GetValue())
        config['locations'] = locations
        config['minSecurity'] = self.minSecEdit.GetValue()
        config['maxSecurity'] = self.maxSecEdit.GetValue()
        if self.spawnShipCheckbox.GetValue():
            config['shipDna'] = self.dnaEdit.GetValue()
        else:
            config['shipDna'] = None
        sm.GetService('autobot').StartBot()
        self.logUpdated = AutoTimer(2000, self.UpdateLogText)

    def PauseBot(self, *args):
        sm.GetService('autobot').PauseBot()

    def StopBot(self, *args):
        sm.GetService('autobot').StopBot()
        self.logUpdated = None

    def ClearLogs(self, *args):
        sm.GetService('autobot').ClearLogs()

    def UpdateLogText(self):
        logLines = sm.GetService('autobot').logLines
        self.logEdit.SetValue('\n'.join([str(x) for x in reversed(logLines)]))
示例#17
0
class WindowManager(Window):
    __guid__ = 'form.WindowManager'
    default_windowID = 'WindowManager'

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        self.SetWndIcon(None)
        self.SetCaption('Window manager')
        self.SetTopparentHeight(10)
        self.SetMinSize([360, 220])
        options = []
        for wndCls in Window.__subclasses__():
            options.append((wndCls.__name__, wndCls))

        options.sort()
        topCont = Container(name='params', parent=self.sr.main, align=uiconst.TOTOP, pad=(5, 5, 5, 5), pos=(0, 10, 0, 30))
        self.mainCont = Container(name='params', parent=self.sr.main, align=uiconst.TOTOP, pos=(0, 0, 0, 50), padding=(5, 15, 5, 5))
        self.extrasCont = Container(name='params', parent=self.sr.main, align=uiconst.TOALL, padding=(5, 15, 5, 5))
        self.combo = Combo(parent=topCont, label='Select window', options=options, name='', select=settings.user.ui.Get('windowManagerOpenWindow'), callback=self.OnComboChanged, pos=(5, 0, 0, 0), width=150, align=uiconst.TOPLEFT)
        self.startupArgs = SinglelineEdit(name='', label='attributes', parent=topCont, setvalue='', align=uiconst.TOPLEFT, left=165, width=100)
        Button(parent=topCont, label='Load', align=uiconst.RELATIVE, func=self.OpenWindow, pos=(300, 0, 0, 0))
        self.filenameEdit = SinglelineEdit(name='', label='Location', parent=self.mainCont, setvalue='', align=uiconst.TOTOP, top=15, readonly=True)
        Label(text='RELOAD', parent=self.extrasCont, top=10, state=uiconst.UI_NORMAL)
        Line(parent=self.extrasCont, align=uiconst.TOTOP)
        buttonCont = Container(name='buttonCont', parent=self.extrasCont, align=uiconst.TOTOP, pos=(0, 30, 0, 30))
        Button(parent=buttonCont, label='ShipUI', align=uiconst.TOLEFT, func=self.ReloadShipUI)
        Button(parent=buttonCont, label='NEOCOM', align=uiconst.TOLEFT, func=self.ReloadNeocom, padLeft=1)
        Button(parent=buttonCont, label='Info Panels', align=uiconst.TOLEFT, func=self.ReloadInfoPanels, padLeft=1)
        Button(parent=buttonCont, label='Lobby', align=uiconst.TOLEFT, func=self.ReloadLobby, padLeft=1)
        Button(parent=buttonCont, label='Overview', align=uiconst.TOLEFT, func=self.ReloadOverview, padLeft=1)
        Button(parent=buttonCont, label='Mapbrowser', align=uiconst.TOLEFT, func=self.ReloadMapBrowser, padLeft=1)
        self.UpdateInfo(self.combo.GetKey(), self.combo.GetValue())

    def OnComboChanged(self, combo, key, wndCls):
        self.UpdateInfo(key, wndCls)

    def UpdateInfo(self, key, wndCls):
        self.filenameEdit.SetValue(wndCls.ApplyAttributes.func_code.co_filename)
        settings.user.ui.Set('windowManagerOpenWindow', wndCls)

    def OpenWindow(self, *args):
        windowClass = self.combo.GetValue()
        windowClass.CloseIfOpen()
        attributes = {}
        try:
            attributesStr = self.startupArgs.GetValue()
            if attributesStr:
                for s in attributesStr.split(','):
                    keyword, value = s.split('=')
                    keyword = keyword.strip()
                    value = value.strip()
                    try:
                        if value.find('.') != -1:
                            value = float(value)
                        else:
                            value = int(value)
                    except ValueError:
                        pass

                    if value == 'None':
                        value = None
                    attributes[keyword] = value

        except:
            eve.Message('CustomInfo', {'info': 'attributes must be on the form: attr1=1, attr2=Some random text'})
            raise

        windowClass.Open(**attributes)

    def ReloadShipUI(self, *args):
        if eve.session.stationid is None:
            uicore.layer.shipui.CloseView()
            uicore.layer.shipui.OpenView()

    def ReloadNeocom(self, *args):
        sm.GetService('neocom').Reload()

    def ReloadInfoPanels(self, *args):
        sm.GetService('infoPanel').Reload()

    def ReloadLobby(self, *args):
        if session.stationid or session.structureid:
            from eve.client.script.ui.shared.dockedUI import ReloadLobbyWnd
            ReloadLobbyWnd()

    def ReloadMapBrowser(self, *args):
        MapBrowserWnd.CloseIfOpen()
        uicore.cmd.OpenMapBrowser()

    def ReloadOverview(self, *args):
        OverView.CloseIfOpen()
        if session.solarsystemid:
            sm.GetService('tactical').InitOverview()
        ActiveItem.CloseIfOpen()
        if session.solarsystemid:
            sm.GetService('tactical').InitSelectedItem()
        DroneView.CloseIfOpen()
        if session.solarsystemid:
            sm.GetService('tactical').InitDrones()
示例#18
0
class StoreFleetSetupWnd(Window):
    default_width = 270
    default_height = 90
    default_minSize = (default_width, default_height)
    default_windowID = 'StoreFleetSetupWnd'

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        self.DefineButtons(uiconst.OKCANCEL,
                           okFunc=self.Confirm,
                           cancelFunc=self.Cancel)
        caption = localization.GetByLabel(
            'UI/Fleet/FleetWindow/StoreFleetSetup')
        self.SetCaption(caption)
        self.SetTopparentHeight(0)
        self.MakeUnResizeable()
        oldSetupName = attributes.get('oldSetupName', None)
        self.maxLength = 15
        self.funcValidator = self.CheckName
        self.ConstructLayout(oldSetupName)

    def ConstructLayout(self, oldSetupName):
        cont = uicontrols.ContainerAutoSize(parent=self.sr.main,
                                            align=uiconst.TOTOP,
                                            padding=(const.defaultPadding, 0,
                                                     const.defaultPadding,
                                                     const.defaultPadding),
                                            alignMode=uiconst.TOTOP)
        if oldSetupName:
            label = localization.GetByLabel(
                'UI/Fleet/FleetWindow/StoreFleetSetupTextWithLastLoaded',
                oldFleetSetupName=oldSetupName)
        else:
            label = localization.GetByLabel(
                'UI/Fleet/FleetWindow/StoreFleetSetupText')
        nameLabel = uicontrols.EveLabelSmall(parent=cont,
                                             name='nameLabel',
                                             align=uiconst.TOTOP,
                                             text=label,
                                             padLeft=6)
        self.newName = SinglelineEdit(name='namePopup',
                                      parent=cont,
                                      align=uiconst.TOTOP,
                                      maxLength=self.maxLength,
                                      OnReturn=self.Confirm,
                                      padLeft=6)
        motdText = localization.GetByLabel('UI/Fleet/FleetWindow/IncludeMotd')
        self.motdCb = uicontrols.Checkbox(text=motdText,
                                          parent=cont,
                                          configName='motdCb',
                                          checked=False,
                                          padLeft=6,
                                          align=uiconst.TOTOP)
        voiceText = localization.GetByLabel(
            'UI/Fleet/FleetWindow/IncludeVoiceEnabledSetting')
        self.voiceCb = uicontrols.Checkbox(text=voiceText,
                                           parent=cont,
                                           configName='voiceCb',
                                           checked=False,
                                           padLeft=6,
                                           align=uiconst.TOTOP)
        freeMoveText = localization.GetByLabel(
            'UI/Fleet/FleetWindow/IncludeFreeMoveSetting')
        self.freeMoveCb = uicontrols.Checkbox(text=freeMoveText,
                                              parent=cont,
                                              configName='freeMoveCb',
                                              checked=False,
                                              padLeft=6,
                                              align=uiconst.TOTOP)
        cw, ch = cont.GetAbsoluteSize()
        self.height = ch + 50
        uicore.registry.SetFocus(self.newName)

    def CheckName(self, name, *args):
        name = self.newName.GetValue()
        if not len(name) or len(name) and len(name.strip()) < 1:
            return localization.GetByLabel('UI/Common/PleaseTypeSomething')

    def Confirm(self, *args):
        newName = self.newName.GetValue()
        storeMotd = self.motdCb.GetValue()
        storeVoiceSettings = self.voiceCb.GetValue()
        storeFreeMove = self.freeMoveCb.GetValue()
        error = self.funcValidator(newName)
        if error:
            eve.Message('CustomInfo', {'info': error})
        else:
            self.result = {
                'setupName': newName,
                'storeMotd': storeMotd,
                'storeVoiceSettings': storeVoiceSettings,
                'storeFreeMove': storeFreeMove
            }
            self.SetModalResult(1)

    def Cancel(self, *args):
        self.result = None
        self.SetModalResult(0)
示例#19
0
class DebugMapBrowser(Window):
    default_windowID = 'DebugMapBrowser'
    default_caption = 'Map Debug View'
    autoLoadTimer = None
    loadedObjectID = None
    currentMap = None
    clipRect = None

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        self.SetTopparentHeight(0)
        uthread.new(self.LoadOptions)

    def LoadOptions(self):
        PrimeMapData()
        self.objectIDs = sorted(uicore.mapObjectDataByID.keys())
        main = self.GetMainArea()
        main.clipChildren = True
        main.padding = 6
        lg = LayoutGrid(parent=main,
                        columns=3,
                        cellPadding=2,
                        align=uiconst.TOTOP)
        self.objectLabel = EveLabelLarge(bold=True)
        lg.AddCell(self.objectLabel, colSpan=lg.columns - 1)
        self.inputEdit = SinglelineEdit(OnReturn=self.OnInputConfirm,
                                        align=uiconst.TOPRIGHT)
        self.inputEdit.SetHistoryVisibility(True)
        lg.AddCell(self.inputEdit, colSpan=1)
        b = Button(func=self.BrowsePrev, label='Previous')
        lg.AddCell(b, colSpan=2)
        Button(parent=lg,
               func=self.BrowseNext,
               label='Next',
               align=uiconst.TOPRIGHT)
        lg.FillRow()
        lg.AddCell(Line(align=uiconst.TOTOP),
                   colSpan=lg.columns,
                   cellPadding=(0, 4, 0, 4))
        b = Button(func=self.BrowseNextLoop,
                   label='Browse next loop',
                   fixedwidth=240)
        lg.AddCell(b, colSpan=lg.columns)
        self.browseLoopButton = b
        settings.user.ui.Set('mapDebugViewRefreshLayout', 0)
        c = Checkbox(configName='mapDebugViewRefreshLayout',
                     text='Refresh layouts',
                     align=uiconst.TOPLEFT,
                     checked=settings.user.ui.Get('mapDebugViewRefreshLayout',
                                                  0),
                     wrapLabel=False,
                     callback=self.OnCheckBoxChange)
        lg.AddCell(c, colSpan=lg.columns)
        c = Checkbox(configName='mapDebugViewStopOnErrors',
                     text='Stop on error',
                     align=uiconst.TOPLEFT,
                     checked=settings.user.ui.Get('mapDebugViewStopOnErrors',
                                                  0),
                     wrapLabel=False,
                     callback=self.OnCheckBoxChange)
        lg.AddCell(c, colSpan=lg.columns)
        c = Checkbox(configName='mapDebugViewIgnoreFixed',
                     text='Ignore fixed layouts',
                     align=uiconst.TOPLEFT,
                     checked=settings.user.ui.Get('mapDebugViewIgnoreFixed',
                                                  0),
                     wrapLabel=False,
                     callback=self.OnCheckBoxChange)
        lg.AddCell(c, colSpan=lg.columns)
        c = Checkbox(configName='mapDebugViewEditEnabled',
                     text='Editmode enabled',
                     align=uiconst.TOPLEFT,
                     checked=settings.user.ui.Get('mapDebugViewEditEnabled',
                                                  0),
                     wrapLabel=False,
                     callback=self.OnCheckBoxChange)
        lg.AddCell(c, colSpan=lg.columns)
        c = Checkbox(configName='mapDebugSubdivision',
                     text='Show Grid Subdivision',
                     align=uiconst.TOPLEFT,
                     checked=settings.user.ui.Get('mapDebugSubdivision', 0),
                     wrapLabel=False,
                     callback=self.OnCheckBoxChange)
        lg.AddCell(c, colSpan=lg.columns)
        c = Checkbox(configName='mapLoadCombined',
                     text='Load Combined',
                     align=uiconst.TOPLEFT,
                     checked=settings.user.ui.Get('mapLoadCombined', 0),
                     wrapLabel=False,
                     callback=self.OnCheckBoxChange)
        lg.AddCell(c, colSpan=lg.columns)
        c = Checkbox(configName='mapDebugShowIDs',
                     text='Show IDs',
                     align=uiconst.TOPLEFT,
                     checked=settings.user.ui.Get('mapDebugShowIDs', 0),
                     wrapLabel=False,
                     callback=self.OnCheckBoxChange)
        lg.AddCell(c, colSpan=lg.columns)
        c = Checkbox(configName='mapDebugLoadHexLines',
                     text='Load Hex Lines',
                     align=uiconst.TOPLEFT,
                     checked=settings.user.ui.Get('mapDebugLoadHexLines', 0),
                     wrapLabel=False,
                     callback=self.OnCheckBoxChange)
        lg.AddCell(c, colSpan=lg.columns)
        c = Checkbox(configName='mapDebugShowExitPoints',
                     text='Show Exit Points',
                     align=uiconst.TOPLEFT,
                     checked=settings.user.ui.Get('mapDebugShowExitPoints', 0),
                     wrapLabel=False,
                     callback=self.OnCheckBoxChange)
        lg.AddCell(c, colSpan=lg.columns)
        lg.FillRow()
        lg.AddCell(Line(align=uiconst.TOTOP),
                   colSpan=lg.columns,
                   cellPadding=(0, 4, 0, 4))
        b = Button(func=self.ScanCurrent, label='Scan Current', fixedwidth=240)
        lg.AddCell(b, colSpan=lg.columns)
        b = Button(func=self.AutoFitSize, label='Auto Fit', fixedwidth=240)
        lg.AddCell(b, colSpan=lg.columns)
        self.statsLabel = EveLabelMedium(parent=lg)
        lg.FillRow()
        self.clipRect = Container(parent=uicore.layer.main,
                                  align=uiconst.CENTER,
                                  width=800,
                                  height=600,
                                  clipChildren=True)
        Frame(bgParent=self.clipRect)
        Fill(bgParent=self.clipRect, color=(0, 0, 0, 1))
        self.LoadObjectID(loadObjectID=10000001)

    def Close(self, *args, **kwds):
        Window.Close(self, *args, **kwds)
        if self.currentMap and not self.currentMap.destroyed:
            self.currentMap.Close()
            self.currentMap = None
        if self.clipRect:
            self.clipRect.Close()
            self.clipRect = None

    def OnCheckBoxChange(self, *args, **kwds):
        if self.loadedObjectID:
            uthread.new(self.LoadObjectID, self.loadedObjectID)

    def LoadObjectID(self, loadObjectID, *args, **kwds):
        self.loadedObjectID = loadObjectID
        self.objectLabel.text = '%s %s/%s' % (
            loadObjectID, self.objectIDs.index(loadObjectID) + 1,
            len(self.objectIDs))
        if getattr(self, 'currentMap', None):
            self.currentMap.Close()
        inEditMode = settings.user.ui.Get('mapDebugViewEditEnabled', 0)
        from eve.client.script.ui.shared.mapView.hexagonal.hexMap import HexMap
        self.currentMap = HexMap(parent=self.clipRect,
                                 state=uiconst.UI_NORMAL,
                                 editMode=inEditMode)
        stopOnErrors = settings.user.ui.Get('mapDebugViewStopOnErrors', 0)
        ignoreFixed = settings.user.ui.Get('mapDebugViewIgnoreFixed', 0)
        refreshLayout = settings.user.ui.Get('mapDebugViewRefreshLayout', 0)
        if refreshLayout:
            refreshLayout = loadObjectID != const.locationUniverse
        if refreshLayout:
            resolved = PlotMapObjects(self.currentMap, loadObjectID)
            if not resolved and stopOnErrors:
                self.autoLoadTimer = None
        else:
            self.currentMap.LoadMapData(loadObjectID,
                                        ignoreFixedLayout=ignoreFixed)
            if loadObjectID > 9 and not settings.user.ui.Get(
                    'mapLoadCombined', 0):
                ol, ll, penalty = ScanAllOverlap(self.currentMap)
                if penalty:
                    print 'Loaded', loadObjectID, 'penalty', penalty
                    if stopOnErrors:
                        self.autoLoadTimer = None

    def BrowsePrev(self, *args, **kwds):
        self.autoLoadTimer = None
        if self.loadedObjectID:
            ctrl = uicore.uilib.Key(uiconst.VK_CONTROL)
            if ctrl:
                i = 1
            else:
                i = self.objectIDs.index(self.loadedObjectID)
            self.LoadObjectID(self.objectIDs[max(0, i - 1)])

    def BrowseNext(self, *args, **kwds):
        if self.destroyed:
            self.autoLoadTimer = None
            return
        if self.loadedObjectID:
            i = self.objectIDs.index(self.loadedObjectID)
            if i + 1 < len(self.objectIDs):
                self.LoadObjectID(self.objectIDs[i + 1])
                return True

    def AutoFitSize(self, *args):
        self._AutoFitSize(self, *args)

    def _AutoFitSize(self, *args):
        print 'meee'
        hexMap = self.currentMap
        layout = hexMap.GetCurrentLayout()
        newlayout, size = AutoFitLayout(layout)
        for objectID, column_row in newlayout.iteritems():
            hexCell = hexMap.objectByID[objectID]
            hexCell.MoveToCR(*column_row)

        hexMap.UpdateJumpLines()
        hexMap.SetMapSize(size)

    def ScanCurrent(self, *args):
        self._ScanCurrent(*args)

    def _ScanCurrent(self, *args):
        if self.currentMap:
            ol, ll, penalty = ScanAllOverlap(self.currentMap)
            print penalty

    def MakePattern(self, *args):
        pass

    def BrowseNextLoop(self, *args):
        if self.autoLoadTimer:
            self.browseLoopButton.SetLabel('Browse next loop')
            self.autoLoadTimer = None
        else:
            self.browseLoopButton.SetLabel('Stop')
            self.autoLoadTimer = AutoTimer(1, self.AutoBrowse)

    def AutoBrowse(self):
        stillLoading = self.BrowseNext()
        if not stillLoading:
            self.autoLoadTimer = None

    def OnInputConfirm(self, *args, **kwds):
        try:
            toInt = int(self.inputEdit.GetValue())
            if toInt in self.objectIDs:
                self.LoadObjectID(toInt)
        except:
            pass
示例#20
0
class DirectionalScanner(Window):
    __notifyevents__ = ['OnSessionChanged', 'OnOverviewPresetSaved']
    default_windowID = 'directionalScanner'
    default_width = 400
    default_height = 350
    default_minSize = (350, 175)
    default_captionLabelPath = 'UI/Inflight/Scanner/DirectionalScan'

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        self.scanSvc = sm.GetService('scanSvc')
        self.busy = False
        self.scanresult = []
        self.scanangle = DegToRad(90)
        self.scope = 'inflight'
        self.SetTopparentHeight(0)
        self.SetWndIcon(None)
        self.HideMainIcon()
        directionBox = Container(name='direction', parent=self.sr.main, align=uiconst.TOALL, left=const.defaultPadding, width=const.defaultPadding, top=const.defaultPadding, height=const.defaultPadding)
        self.SetupDScanUI(directionBox)

    def SetupDScanUI(self, directionBox):
        directionSettingsBox = Container(name='direction', parent=directionBox, align=uiconst.TOTOP, height=70, clipChildren=True, padLeft=2)
        self.sr.dirscroll = Scroll(name='dirscroll', parent=directionBox)
        self.sr.dirscroll.sr.id = 'scanner_dirscroll'
        presetGrid = LayoutGrid(parent=directionSettingsBox, columns=2, state=uiconst.UI_PICKCHILDREN, align=uiconst.TOPLEFT, left=0, top=3)
        paddingBtwElements = 8
        checked = settings.user.ui.Get('scannerusesoverviewsettings', 0)
        self.sr.useoverview = Checkbox(text=GetByLabel('UI/Inflight/Scanner/UsePreset'), parent=presetGrid, configName='', retval=0, checked=checked, left=0, align=uiconst.TOPLEFT, callback=self.UseOverviewChanged, width=320, wrapLabel=False)
        presetSelected = settings.user.ui.Get('scanner_presetInUse', None)
        presetOptions = self.GetPresetOptions()
        self.presetsCombo = Combo(label='', parent=presetGrid, options=presetOptions, name='comboTabOverview', select=presetSelected, align=uiconst.TOPLEFT, width=120, left=10, callback=self.OnProfileInUseChanged)
        if not checked:
            self.presetsCombo.Disable()
            self.presetsCombo.opacity = 0.5
            self.sr.useoverview.sr.label.opacity = 0.5
        self.rangeCont = Container(parent=directionSettingsBox, name='rangeCont', align=uiconst.TOTOP, height=24, top=self.sr.useoverview.height)
        self.angleCont = Container(parent=directionSettingsBox, name='rangeCont', align=uiconst.TOTOP, height=24)
        textLeft = 2
        rangeText = GetByLabel('UI/Inflight/Scanner/Range')
        rangeLabel = EveLabelSmall(text=rangeText, parent=self.rangeCont, align=uiconst.CENTERLEFT, state=uiconst.UI_DISABLED, left=textLeft)
        angleText = GetByLabel('UI/Inflight/Scanner/Angle')
        angleLabel = EveLabelSmall(text=angleText, parent=self.angleCont, align=uiconst.CENTERLEFT, state=uiconst.UI_DISABLED, left=textLeft)
        innerLeft = max(rangeLabel.textwidth, angleLabel.textwidth) + paddingBtwElements + textLeft
        innerRangeCont = Container(parent=self.rangeCont, align=uiconst.TOALL, padLeft=innerLeft)
        innderAngleCont = Container(parent=self.angleCont, align=uiconst.TOALL, padLeft=innerLeft)
        maxAuRange = 14.3
        startingKmValue = settings.user.ui.Get('dir_scanrange', const.AU * maxAuRange)
        startingAuValue = ConvertKmToAu(startingKmValue)
        distanceSliderCont = Container(name='distanceSliderCont', parent=innerRangeCont, align=uiconst.CENTERLEFT, state=uiconst.UI_PICKCHILDREN, pos=(0, -1, 100, 18))
        smallestAU = ConvertKmToAu(1000000)
        self.distanceSlider = Slider(name='distanceSlider', parent=distanceSliderCont, sliderID='distanceSlider', minValue=0, maxValue=maxAuRange, endsliderfunc=self.EndSetDistanceSliderValue, onsetvaluefunc=self.OnSetDistanceSliderValue, increments=[smallestAU,
         1,
         5,
         10,
         maxAuRange], height=20, barHeight=10)
        self.distanceSlider.label.display = False
        self.distanceSlider.SetValue(startingAuValue, updateHandle=True, useIncrements=False)
        left = distanceSliderCont.width + paddingBtwElements
        maxAuRangeInKm = ConvertAuToKm(maxAuRange)
        self.dir_rangeinput = SinglelineEdit(name='dir_rangeinput', parent=innerRangeCont, ints=(0, maxAuRangeInKm), setvalue=startingKmValue, align=uiconst.CENTERLEFT, pos=(left,
         0,
         90,
         0), maxLength=len(str(maxAuRangeInKm)) + 1, OnReturn=self.DirectionSearch)
        self.dir_rangeinput.OnChar = self.OnKmChar
        self.dir_rangeinput.OnMouseWheel = self.OnMouseWheelKm
        self.dir_rangeinput.ChangeNumericValue = self.ChangeNumericValueKm
        kmText = GetByLabel('UI/Inflight/Scanner/UnitKMAndSeparator')
        left = self.dir_rangeinput.left + self.dir_rangeinput.width + paddingBtwElements / 2
        kmLabel = EveLabelSmall(text=kmText, parent=innerRangeCont, align=uiconst.CENTERLEFT, pos=(left,
         0,
         0,
         0), state=uiconst.UI_DISABLED)
        left = kmLabel.left + kmLabel.textwidth + paddingBtwElements
        self.dir_rangeinputAu = SinglelineEdit(name='dir_rangeinputAu', parent=innerRangeCont, setvalue=startingAuValue, floats=(0, maxAuRange, 1), align=uiconst.CENTERLEFT, pos=(left,
         0,
         45,
         0), maxLength=4, OnReturn=self.DirectionSearch)
        self.dir_rangeinputAu.OnChar = self.OnAuChar
        self.dir_rangeinputAu.OnMouseWheel = self.OnMouseWheelAu
        self.dir_rangeinputAu.ChangeNumericValue = self.ChangeNumericValueAu
        auText = GetByLabel('UI/Inflight/Scanner/UnitAU')
        left = self.dir_rangeinputAu.left + self.dir_rangeinputAu.width + paddingBtwElements / 2
        auLabel = EveLabelSmall(text=auText, parent=innerRangeCont, align=uiconst.CENTERLEFT, pos=(left,
         0,
         0,
         0), state=uiconst.UI_DISABLED)
        angleSliderCont = Container(name='sliderCont', parent=innderAngleCont, align=uiconst.CENTERLEFT, state=uiconst.UI_PICKCHILDREN, pos=(0, -1, 100, 18))
        self.angleSliderLabel = EveLabelSmall(text='', parent=innderAngleCont, align=uiconst.CENTERLEFT, pos=(0, 0, 0, 0), state=uiconst.UI_DISABLED)
        startingAngle = settings.user.ui.Get('scan_angleSlider', 360)
        startingAngle = max(0, min(startingAngle, 360))
        self.degreeCone = PieCircle(parent=innderAngleCont, left=0, align=uiconst.CENTERLEFT, setValue=startingAngle)
        self.degreeCone.opacity = 0.3
        self.scanangle = DegToRad(startingAngle)
        angleSlider = Slider(name='angleSlider', parent=angleSliderCont, sliderID='angleSlider', startVal=startingAngle, minValue=5, maxValue=360, increments=[5,
         15,
         30,
         60,
         90,
         180,
         360], isEvenIncrementsSlider=True, endsliderfunc=self.EndSetAngleSliderValue, height=20, barHeight=10, setlabelfunc=self.UpdateAngleSliderLabel)
        left = angleSliderCont.width + paddingBtwElements
        self.angleSliderLabel.left = left + 5
        self.degreeCone.left = left + 35
        buttonText = GetByLabel('UI/Inflight/Scanner/Scan')
        scanButton = Button(parent=innderAngleCont, label=buttonText, align=uiconst.CENTERLEFT, pos=(4, 0, 0, 0), func=self.DirectionSearch)
        scanButton.left = auLabel.left + auLabel.textwidth - scanButton.width

    def GetPresetOptions(self):
        p = sm.GetService('overviewPresetSvc').GetAllPresets().keys()
        options = []
        for name in p:
            defaultName = sm.GetService('overviewPresetSvc').GetDefaultOverviewName(name)
            if defaultName:
                options.append((' ' + defaultName.lower(), (defaultName, name)))
            else:
                displayName = sm.GetService('overviewPresetSvc').GetPresetDisplayName(name)
                options.append((displayName.lower(), (displayName, name)))

        options = SortListOfTuples(options)
        options.insert(0, (GetByLabel('UI/Inflight/Scanner/UseActiveOverviewSettings'), None))
        return options

    def OnOverviewPresetSaved(self):
        presetSelected = settings.user.ui.Get('scanner_presetInUse', None)
        presetOptions = self.GetPresetOptions()
        self.presetsCombo.LoadOptions(entries=presetOptions, select=presetSelected)

    def UpdateAngleSliderLabel(self, label, sliderID, displayName, value):
        self.angleSliderLabel.text = GetByLabel('UI/Inflight/Scanner/AngleDegrees', value=value)
        self.degreeCone.SetDegree(value)

    def OnKmChar(self, char, flag):
        returnValue = SinglelineEdit.OnChar(self.dir_rangeinput, char, flag)
        self.KmValueChanged()
        return returnValue

    def OnMouseWheelKm(self, *args):
        SinglelineEdit.MouseWheel(self.dir_rangeinput, *args)
        self.KmValueChanged()

    def ChangeNumericValueKm(self, *args):
        SinglelineEdit.ChangeNumericValue(self.dir_rangeinputAu, *args)
        self.AuValueChanged()

    def KmValueChanged(self):
        kmValue = self.dir_rangeinput.GetValue()
        auValue = ConvertKmToAu(kmValue)
        self.dir_rangeinputAu.SetValue(auValue)
        self.distanceSlider.SetValue(auValue, updateHandle=True, useIncrements=False)

    def OnAuChar(self, char, flag):
        returnValue = SinglelineEdit.OnChar(self.dir_rangeinputAu, char, flag)
        self.AuValueChanged()
        return returnValue

    def OnMouseWheelAu(self, *args):
        SinglelineEdit.MouseWheel(self.dir_rangeinputAu, *args)
        self.AuValueChanged()

    def ChangeNumericValueAu(self, *args):
        SinglelineEdit.ChangeNumericValue(self.dir_rangeinputAu, *args)
        self.AuValueChanged()

    def AuValueChanged(self):
        auValue = self.dir_rangeinputAu.GetValue()
        kmValue = ConvertAuToKm(auValue)
        self.dir_rangeinput.SetValue(kmValue)
        self.distanceSlider.SetValue(auValue, updateHandle=True, useIncrements=False)

    def UpdateDistanceFromSlider(self):
        auValue = self.distanceSlider.GetValue()
        kmValue = ConvertAuToKm(auValue)
        self.dir_rangeinput.SetValue(kmValue)
        self.dir_rangeinputAu.SetValue(auValue)

    def EndSetDistanceSliderValue(self, *args):
        self.UpdateDistanceFromSlider()
        uthread.new(self.DirectionSearch)

    def OnSetDistanceSliderValue(self, slider, *args):
        if not slider.dragging:
            return
        self.UpdateDistanceFromSlider()

    def EndSetAngleSliderValue(self, slider):
        angleValue = slider.GetValue()
        self.degreeCone.SetDegree(angleValue)
        self.SetMapAngle(DegToRad(angleValue))
        settings.user.ui.Set('scan_angleSlider', angleValue)
        uthread.new(self.DirectionSearch)

    def _OnClose(self, *args):
        self.SetMapAngle(0)

    def DirectionSearch(self, *args):
        if self.destroyed or self.busy:
            return
        self.busy = True
        self.ShowLoad()
        self.scanresult = []
        if self.sr.useoverview.checked:
            selectedValue = self.presetsCombo.GetValue()
            if selectedValue is None:
                selectedValue = sm.GetService('overviewPresetSvc').GetActiveOverviewPresetName()
            filters = sm.GetService('overviewPresetSvc').GetValidGroups(presetName=selectedValue)
        camera = sm.GetService('sceneManager').GetRegisteredCamera(None, defaultOnActiveCamera=True)
        if not camera:
            self.busy = False
            self.HideLoad()
            raise RuntimeError('No camera found?!')
        vec = geo2.QuaternionTransformVector(camera.rotationAroundParent, (0, 0, -1))
        vec = geo2.Vec3Normalize(vec)
        rnge = self.dir_rangeinput.GetValue()
        try:
            result = self.scanSvc.ConeScan(self.scanangle, rnge * 1000, vec[0], vec[1], vec[2])
        except (UserError, RuntimeError) as err:
            result = None
            self.busy = False
            self.HideLoad()
            raise err

        settings.user.ui.Set('dir_scanrange', rnge)
        if result:
            bp = sm.GetService('michelle').GetBallpark()
            if bp:
                for rec in result:
                    if self.sr.useoverview.checked:
                        if rec.groupID not in filters:
                            continue
                    if rec.id in bp.balls:
                        self.scanresult.append([None, bp.balls[rec.id], rec])
                    else:
                        self.scanresult.append([None, None, rec])

        self.ShowDirectionalSearchResult()
        self.busy = False
        self.HideLoad()

    def ShowDirectionalSearchResult(self, *args):
        self.listtype = 'location'
        scrolllist = []
        if self.scanresult and len(self.scanresult):
            myball = None
            ballpark = sm.GetService('michelle').GetBallpark()
            if ballpark:
                myball = ballpark.GetBall(eve.session.shipid)
            prime = []
            for result in self.scanresult:
                slimItem, ball, celestialRec = result
                if not slimItem and celestialRec:
                    prime.append(celestialRec.id)

            if prime:
                cfg.evelocations.Prime(prime)
            for slimItem, ball, celestialRec in self.scanresult:
                if self is None or self.destroyed:
                    return
                if slimItem:
                    typeinfo = cfg.invtypes.Get(slimItem.typeID)
                    entryname = GetSlimItemName(slimItem)
                    itemID = slimItem.itemID
                    typeID = slimItem.typeID
                    if not entryname:
                        entryname = typeinfo.Group().name
                elif celestialRec:
                    typeinfo = cfg.invtypes.Get(celestialRec.typeID)
                    if typeinfo.groupID == const.groupHarvestableCloud:
                        entryname = GetByLabel('UI/Inventory/SlimItemNames/SlimHarvestableCloud', typeinfo.name)
                    elif typeinfo.categoryID == const.categoryAsteroid:
                        entryname = GetByLabel('UI/Inventory/SlimItemNames/SlimAsteroid', typeinfo.name)
                    else:
                        entryname = cfg.evelocations.Get(celestialRec.id).name
                    if not entryname:
                        entryname = typeinfo.name
                    itemID = celestialRec.id
                    typeID = celestialRec.typeID
                else:
                    continue
                if ball is not None:
                    dist = ball.surfaceDist
                    diststr = FmtDist(dist, maxdemicals=1)
                else:
                    dist = 0
                    diststr = '-'
                groupID = cfg.invtypes.Get(typeID).groupID
                if not eve.session.role & (service.ROLE_GML | service.ROLE_WORLDMOD):
                    if groupID == const.groupCloud:
                        continue
                data = KeyVal()
                data.label = '%s<t>%s<t>%s' % (entryname, typeinfo.name, diststr)
                data.entryName = entryname
                data.typeName = typeinfo.name
                data.Set('sort_%s' % GetByLabel('UI/Common/Distance'), dist)
                data.columnID = 'directionalResultGroupColumn'
                data.result = result
                data.itemID = itemID
                data.typeID = typeID
                data.GetMenu = self.DirectionalResultMenu
                scrolllist.append(listentry.Get('DirectionalScanResults', data=data))
                blue.pyos.BeNice()

        if not len(scrolllist):
            data = KeyVal()
            data.label = GetByLabel('UI/Inflight/Scanner/DirectionalNoResult')
            data.hideLines = 1
            scrolllist.append(listentry.Get('Generic', data=data))
            headers = []
        else:
            headers = [GetByLabel('UI/Common/Name'), GetByLabel('UI/Common/Type'), GetByLabel('UI/Common/Distance')]
        self.sr.dirscroll.Load(contentList=scrolllist, headers=headers)

    def DirectionalResultMenu(self, entry, *args):
        if entry.sr.node.itemID:
            return sm.GetService('menu').CelestialMenu(entry.sr.node.itemID, typeID=entry.sr.node.typeID)
        return []

    def SetMapAngle(self, angle):
        if angle is not None:
            self.scanangle = angle
        wnd = MapBrowserWnd.GetIfOpen()
        if wnd:
            wnd.SetTempAngle(angle)

    def EndSetSliderValue(self, *args):
        uthread.new(self.DirectionSearch)

    def UseOverviewChanged(self, checked):
        if self.sr.useoverview.checked:
            self.presetsCombo.Enable()
            self.presetsCombo.opacity = 1
            self.sr.useoverview.sr.label.opacity = 1
        else:
            self.presetsCombo.Disable()
            self.presetsCombo.opacity = 0.5
            self.sr.useoverview.sr.label.opacity = 0.5
        settings.user.ui.Set('scannerusesoverviewsettings', self.sr.useoverview.checked)
        self.DirectionSearch()

    def OnProfileInUseChanged(self, *args):
        value = self.presetsCombo.GetValue()
        settings.user.ui.Set('scanner_presetInUse', value)
        self.DirectionSearch()
示例#21
0
class SOFPreviewWindow:
    def __init__(self):
        self.name = 'SOF Preview Window'
        self.windowID = 'SOFPreviewWindow_ ' + self.name
        self.previewCont = None
        dna = self.GetDnaFromPlayerShip()
        self.currentHull = dna.split(':')[0]
        self.currentFaction = dna.split(':')[1]
        self.currentRace = dna.split(':')[2]
        self.currentMat = ['None', 'None', 'None', 'None']
        self.currentVariant = 'None'
        self.currentPattern = 'None'
        self.currentDirtLevel = None
        self.currentResPathInsert = None
        self.constrainToFaction = False
        self.constrainToHull = False
        self.constrainToRace = False

    def _OnApplyButton(self, *args):
        self._UpdatePlayerShip()

    def _OnCopyDnaButton(self, *args):
        blue.pyos.SetClipboardData(self.GetPreviewDna())

    def ShowUI(self):
        uicontrols.Window.CloseIfOpen(windowID=self.windowID)
        wnd = uicontrols.Window.Open(windowID=self.windowID)
        wnd.SetTopparentHeight(0)
        wnd.SetMinSize([500, 500])
        wnd.SetCaption(self.name)
        main = wnd.GetMainArea()
        sofDB = blue.resMan.LoadObject(
            'res:/dx9/model/spaceobjectfactory/data.red')
        self.sofFactions = []
        for i in xrange(len(sofDB.faction)):
            self.sofFactions.append((sofDB.faction[i].name, i))

        self.sofFactions.sort()
        self.sofHulls = []
        for i in xrange(len(sofDB.hull)):
            self.sofHulls.append((sofDB.hull[i].name, i))

        self.sofHulls.sort()
        self.sofRaces = []
        for i in xrange(len(sofDB.race)):
            self.sofRaces.append((sofDB.race[i].name, i))

        self.sofRaces.sort()
        self.sofMaterials = []
        for i in xrange(len(sofDB.material)):
            self.sofMaterials.append((sofDB.material[i].name, i))

        self.sofMaterials.sort()
        self.sofMaterials.insert(0, ('None', -1))
        self.sofVariants = []
        for i in xrange(len(sofDB.generic.variants)):
            self.sofVariants.append((sofDB.generic.variants[i].name, i))

        self.sofVariants.sort()
        self.sofVariants.insert(0, ('None', -1))
        self.sofPatterns = []
        for i in xrange(len(sofDB.pattern)):
            self.sofPatterns.append((sofDB.pattern[i].name, i))

        self.sofPatterns.sort()
        self.sofPatterns.insert(0, ('None', -1))
        headerCont = Container(name='headerCont',
                               parent=main,
                               align=uiconst.TOTOP,
                               height=30)
        gridCont = GridContainer(name='mainCont',
                                 parent=main,
                                 align=uiconst.TOBOTTOM,
                                 height=250,
                                 lines=5,
                                 columns=3)
        buttonConts = {}
        for y in xrange(gridCont.lines):
            for x in xrange(gridCont.columns):
                buttonConts[x, y] = Container(parent=gridCont)

        self.dnaLabel = EveLabelSmall(name='dnaLabel',
                                      align=uiconst.CENTER,
                                      parent=headerCont,
                                      text='')
        self.copyDnaButton = Button(name='copy_dna_button',
                                    align=uiconst.CENTER,
                                    parent=buttonConts[(0, 4)],
                                    label='Copy DNA',
                                    func=self._OnCopyDnaButton)
        self.applyButton = Button(name='apply_button',
                                  align=uiconst.CENTER,
                                  parent=buttonConts[(1, 4)],
                                  label='Apply',
                                  func=self._OnApplyButton)
        patternParent = Container(name='patternParent',
                                  parent=buttonConts[(0, 3)],
                                  align=uiconst.CENTER,
                                  height=18,
                                  width=175)
        self.patternCombo = Combo(name='pattern_combo',
                                  align=uiconst.TOLEFT,
                                  width=150,
                                  parent=patternParent,
                                  label='Pattern:',
                                  options=self.sofPatterns,
                                  callback=self.OnPatternComboChange,
                                  select=self.GetComboListIndex(
                                      self.sofPatterns, self.currentPattern))
        factionParent = Container(name='factionParent',
                                  parent=buttonConts[(0, 2)],
                                  align=uiconst.CENTER,
                                  height=18,
                                  width=175)
        self.factionCombo = Combo(name='faction_combo',
                                  align=uiconst.TOLEFT,
                                  width=150,
                                  parent=factionParent,
                                  label='Faction:',
                                  options=self.sofFactions,
                                  callback=self.OnFactionComboChange,
                                  select=self.GetComboListIndex(
                                      self.sofFactions, self.currentFaction))
        self.factionConstraint = Checkbox(
            name='faction_constraint',
            align=uiconst.TOLEFT,
            width=75,
            padLeft=10,
            parent=factionParent,
            text='Constrained',
            callback=self.OnFactionConstraintChanged)
        hullParent = Container(name='hullParent',
                               parent=buttonConts[(0, 1)],
                               align=uiconst.CENTER,
                               height=18,
                               width=175)
        self.hullCombo = Combo(name='hull_combo',
                               align=uiconst.TOLEFT,
                               width=150,
                               parent=hullParent,
                               label='Hull:',
                               options=self.sofHulls,
                               callback=self.OnHullComboChange,
                               select=self.GetComboListIndex(
                                   self.sofHulls, self.currentHull))
        self.hullConstraint = Checkbox(name='hull_constraint',
                                       align=uiconst.TOLEFT,
                                       width=75,
                                       padLeft=10,
                                       parent=hullParent,
                                       text='Constrained',
                                       callback=self.OnHullConstraintChanged)
        raceParent = Container(name='raceParent',
                               parent=buttonConts[(0, 0)],
                               align=uiconst.CENTER,
                               height=18,
                               width=175)
        self.raceCombo = Combo(name='race_combo',
                               align=uiconst.TOLEFT,
                               width=150,
                               parent=raceParent,
                               label='Race:',
                               options=self.sofRaces,
                               callback=self.OnRaceComboChange,
                               select=self.GetComboListIndex(
                                   self.sofRaces, self.currentRace))
        self.raceConstraint = Checkbox(name='race_constraint',
                                       align=uiconst.TOLEFT,
                                       width=75,
                                       padLeft=10,
                                       parent=raceParent,
                                       text='Constrained',
                                       callback=self.OnRaceConstraintChanged)
        self.matCombo1 = Combo(name='material_combo1',
                               align=uiconst.CENTER,
                               width=150,
                               parent=buttonConts[(1, 0)],
                               label='Material 1:',
                               options=self.sofMaterials,
                               callback=self.OnMat1ComboChange,
                               select=self.GetComboListIndex(
                                   self.sofMaterials, self.currentMat[0]))
        self.matCombo2 = Combo(name='material_combo2',
                               align=uiconst.CENTER,
                               width=150,
                               parent=buttonConts[(1, 1)],
                               label='Material 2:',
                               options=self.sofMaterials,
                               callback=self.OnMat2ComboChange,
                               select=self.GetComboListIndex(
                                   self.sofMaterials, self.currentMat[1]))
        self.matCombo3 = Combo(name='material_combo3',
                               align=uiconst.CENTER,
                               width=150,
                               parent=buttonConts[(1, 2)],
                               label='Material 3:',
                               options=self.sofMaterials,
                               callback=self.OnMat3ComboChange,
                               select=self.GetComboListIndex(
                                   self.sofMaterials, self.currentMat[2]))
        self.matCombo4 = Combo(name='material_combo4',
                               align=uiconst.CENTER,
                               width=150,
                               parent=buttonConts[(1, 3)],
                               label='Material 4:',
                               options=self.sofMaterials,
                               callback=self.OnMat4ComboChange,
                               select=self.GetComboListIndex(
                                   self.sofMaterials, self.currentMat[3]))
        self.dirtSlider = Slider(name='dirt_slider',
                                 align=uiconst.CENTER,
                                 label='Dirt',
                                 parent=buttonConts[(2, 0)],
                                 width=200,
                                 minValue=0.0,
                                 maxValue=100.0,
                                 startVal=50.0,
                                 setlabelfunc=self.UpdateDirtSliderLabel,
                                 onsetvaluefunc=self.OnDirtSliderChange,
                                 endsliderfunc=self.OnDirtSliderChange)
        materialSetIdContainer = Container(name='materialSetContainer',
                                           parent=buttonConts[(2, 1)],
                                           align=uiconst.CENTER,
                                           height=18,
                                           width=175)
        self.materialSetIDCombo = Combo(name='materialsetid_edit',
                                        align=uiconst.TOLEFT,
                                        label='Masterial Set ID',
                                        parent=materialSetIdContainer,
                                        options=[],
                                        callback=self.OnMaterialSetIDChange)
        self._FilterMaterialSet(False)
        self.materialSetFilteredByRace = Checkbox(
            name='materialSetFilter',
            align=uiconst.TOLEFT,
            width=150,
            padLeft=10,
            parent=materialSetIdContainer,
            text='Filter By Race',
            callback=self.OnMaterialSetFiltered)
        self.resPathInsertEdit = SinglelineEdit(
            name='respathinsert_edit',
            align=uiconst.CENTER,
            label='resPathInsert',
            parent=buttonConts[(2, 2)],
            width=100,
            setvalue='',
            OnFocusLost=self.OnResPathInsertChange,
            OnReturn=self.OnResPathInsertChange)
        self.variantCombo = Combo(name='variant_combo',
                                  align=uiconst.CENTER,
                                  width=150,
                                  parent=buttonConts[(2, 3)],
                                  label='Variants:',
                                  options=self.sofVariants,
                                  callback=self.OnVariantComboChange,
                                  select=self.GetComboListIndex(
                                      self.sofVariants, self.currentVariant))
        self.previewCont = PreviewContainer(parent=main, align=uiconst.TOALL)
        self.previewCont.PreviewSofDna(self.GetPreviewDna())

    def GetComboListIndex(self, comboContentList, name):
        for each in comboContentList:
            if each[0].lower() == name.lower():
                return each[1]

    def GetPreviewDna(self):
        dna = self.currentHull + ':' + self.currentFaction + ':' + self.currentRace
        if any((x != 'None' for x in self.currentMat)):
            dna += ':mesh?' + str(self.currentMat[0]) + ';' + str(
                self.currentMat[1]) + ';' + str(
                    self.currentMat[2]) + ';' + str(self.currentMat[3])
        if self.currentResPathInsert is not None:
            dna += ':respathinsert?' + str(self.currentResPathInsert)
        if self.currentVariant != 'None':
            dna += ':variant?' + str(self.currentVariant)
        if self.currentPattern != 'None':
            dna += ':pattern?' + str(self.currentPattern)
        self.dnaLabel.text = dna
        return dna

    def GetDnaFromPlayerShip(self):
        michelle = sm.GetService('michelle')
        ship = michelle.GetBall(session.shipid)
        if ship is None:
            return 'ab1_t1:amarrbase:amarr'
        dna = ship.GetDNA()
        if dna is None:
            return 'ab1_t1:amarrbase:amarr'
        return dna

    def UpdateDirtSliderLabel(self, label, sliderID, displayName, value):
        dirtLevel = gfxutils.RemapDirtLevel(value)
        label.text = 'Dirt level: ' + str(dirtLevel)

    def OnDirtSliderChange(self, slider):
        self.currentDirtLevel = gfxutils.RemapDirtLevel(slider.GetValue())
        self._UpdatePreviewShip()

    def OnFactionConstraintChanged(self, checkbox):
        self.constrainToFaction = checkbox.GetValue()
        self.ConstrainDnaSelection()

    def OnRaceConstraintChanged(self, checkbox):
        self.constrainToRace = checkbox.GetValue()
        self.ConstrainDnaSelection()

    def OnHullConstraintChanged(self, checkbox):
        self.constrainToHull = checkbox.GetValue()
        self.ConstrainDnaSelection()

    def OnMaterialSetFiltered(self, checkbox):
        materialSetFiltered = checkbox.GetValue()
        self._FilterMaterialSet(materialSetFiltered)

    def _FilterMaterialSet(self, filterByRace):
        materialSets = cfg.graphicMaterialSets
        availableMaterialSets = []
        for materialSetID, materialSet in materialSets.iteritems():
            if filterByRace:
                if hasattr(
                        materialSet, 'sofRaceHint'
                ) and materialSet.sofRaceHint == self.raceCombo.GetKey():
                    availableMaterialSets.append(materialSetID)
            else:
                availableMaterialSets.append(materialSetID)

        availableMaterialSets.sort()
        self.TrySettingComboOptions(self.materialSetIDCombo, [('None', -1)] +
                                    [(str(key), key)
                                     for key in availableMaterialSets], -1)

    def ConstrainDnaSelection(self):
        raceQuery = '.*'
        factionQuery = '.*'
        hullQuery = '.*'
        if self.constrainToFaction:
            factionQuery = self.factionCombo.GetKey()
        if self.constrainToHull:
            hullQuery = self.hullCombo.GetKey()
        if self.constrainToRace:
            raceQuery = self.raceCombo.GetKey()
        if not self.constrainToFaction and not self.constrainToHull and not self.constrainToRace:
            self.currentFaction = self.TrySettingComboOptions(
                self.factionCombo, self.sofFactions,
                self.GetDefaultFactionForHull())
            self.currentRace = self.TrySettingComboOptions(
                self.raceCombo, self.sofRaces, self.currentRace)
            self.currentHull = self.TrySettingComboOptions(
                self.hullCombo, self.sofHulls, self.currentHull)
        else:
            dnaList = GetDnaStringMatchingQuery(hullQuery, factionQuery,
                                                raceQuery)
            selectableRaces = []
            selectableFactions = []
            selectableHulls = []
            for dna in dnaList:
                dnaElements = dna.split(':')
                hull = dnaElements[0]
                faction = dnaElements[1]
                race = dnaElements[2]
                if faction not in selectableFactions:
                    selectableFactions.append(faction)
                if race not in selectableRaces:
                    selectableRaces.append(race)
                if hull not in selectableHulls:
                    selectableHulls.append(hull)

            if not self.constrainToHull:
                selectableHulls.sort()
                hullOptions = [(hullName, i)
                               for i, hullName in enumerate(selectableHulls)]
                self.currentHull = self.TrySettingComboOptions(
                    self.hullCombo, hullOptions, self.currentHull)
            if not self.constrainToFaction:
                selectableFactions.sort()
                options = [(factionName, i)
                           for i, factionName in enumerate(selectableFactions)]
                self.currentFaction = self.TrySettingComboOptions(
                    self.factionCombo, options,
                    self.GetDefaultFactionForHull())
            if not self.constrainToRace:
                selectableRaces.sort()
                raceOptions = [(raceName, i)
                               for i, raceName in enumerate(selectableRaces)]
                self.currentRace = self.TrySettingComboOptions(
                    self.raceCombo, raceOptions, self.currentRace)
        self._UpdatePreviewShip()

    def GetDefaultFactionForHull(self):
        if self.currentHull.endswith('t2'):
            return self._GetDefaultFactionForT2Hull(self.currentHull)
        else:
            return self._GetDefaultFactionForT1Hull(self.currentHull)

    @staticmethod
    def _GetDefaultFactionForT1Hull(hullName):
        dnaList = GetDnaStringMatchingQuery(hullName)
        if len(dnaList) == 0:
            return ''
        _, __, race = dnaList[0].split(':')
        return race + 'base'

    @staticmethod
    def _GetDefaultFactionForT2Hull(hullName):
        for factionName, hullList in DEFAULT_FACTION_FOR_T2HULLS.iteritems():
            if hullName in hullList:
                return factionName

        return ''

    def TrySettingComboOptions(self, comboBox, options, selectedValue):
        comboBox.LoadOptions(options)
        return self.TrySettingComboValue(comboBox, selectedValue)

    def TrySettingComboValue(self, comboBox, selectedValue):
        try:
            comboBox.SelectItemByLabel(selectedValue)
        except RuntimeError:
            comboBox.SelectItemByIndex(0)
            print "Could not select '%s', defaulting to '%s'" % (
                selectedValue, comboBox.GetKey())

        return comboBox.GetKey()

    def OnPatternComboChange(self, comboBox, pattern, value):
        self.currentPattern = pattern
        self._UpdatePreviewShip()

    def OnFactionComboChange(self, comboBox, faction, value):
        self.currentFaction = faction
        if self.constrainToFaction:
            self.ConstrainDnaSelection()
        self._UpdatePreviewShip()

    def OnHullComboChange(self, comboBox, hull, value):
        self.currentHull = hull
        if self.constrainToHull:
            self.ConstrainDnaSelection()
        self._UpdatePreviewShip()

    def OnRaceComboChange(self, comboBox, race, value):
        self.currentRace = race
        if self.constrainToRace:
            self.ConstrainDnaSelection()
        self._UpdatePreviewShip()

    def OnMat1ComboChange(self, comboBox, material, value):
        self.currentMat[0] = material
        self._UpdatePreviewShip()

    def OnMat2ComboChange(self, comboBox, material, value):
        self.currentMat[1] = material
        self._UpdatePreviewShip()

    def OnMat3ComboChange(self, comboBox, material, value):
        self.currentMat[2] = material
        self._UpdatePreviewShip()

    def OnMat4ComboChange(self, comboBox, material, value):
        self.currentMat[3] = material
        self._UpdatePreviewShip()

    def OnVariantComboChange(self, comboBox, variant, value):
        self.currentVariant = variant
        self._UpdatePreviewShip()

    def OnMaterialSetIDChange(self, *args):
        materialComboKey = self.materialSetIDCombo.GetKey()
        if materialComboKey == 'None':
            materialComboKey = -1
        materialSetID = int(materialComboKey)
        print 'trying to find materialset for ' + str(materialSetID)
        materialSet = cfg.graphicMaterialSets.GetIfExists(materialSetID)
        if hasattr(materialSet, 'sofFactionName'):
            idx = self.GetComboListIndex(self.sofFactions,
                                         materialSet.sofFactionName)
            self.factionCombo.SelectItemByValue(idx)
            self.OnFactionComboChange(self.factionCombo,
                                      materialSet.sofFactionName, idx)
        material1 = getattr(materialSet, 'material1', 'None')
        idx = self.GetComboListIndex(self.sofMaterials, material1)
        self.matCombo1.SelectItemByValue(idx)
        self.OnMat1ComboChange(self.matCombo1, material1, idx)
        material2 = getattr(materialSet, 'material2', 'None')
        idx = self.GetComboListIndex(self.sofMaterials, material2)
        self.matCombo2.SelectItemByValue(idx)
        self.OnMat2ComboChange(self.matCombo2, material2, idx)
        material3 = getattr(materialSet, 'material3', 'None')
        idx = self.GetComboListIndex(self.sofMaterials, material3)
        self.matCombo3.SelectItemByValue(idx)
        self.OnMat3ComboChange(self.matCombo3, material3, idx)
        material4 = getattr(materialSet, 'material4', 'None')
        idx = self.GetComboListIndex(self.sofMaterials, material4)
        self.matCombo4.SelectItemByValue(idx)
        self.OnMat4ComboChange(self.matCombo4, material4, idx)
        self.resPathInsertEdit.SetValue(
            getattr(materialSet, 'resPathInsert', ''))
        self.OnResPathInsertChange()
        sofPatternName = getattr(materialSet, 'sofPatterName', 'None')
        idx = self.GetComboListIndex(self.sofPatterns, sofPatternName)
        self.patternCombo.SelectItemByValue(idx)
        self.OnPatternComboChange(self.patternCombo, sofPatternName, idx)

    def OnResPathInsertChange(self, *args):
        resPathInsert = self.resPathInsertEdit.GetValue()
        print 'new respathinsert: ' + resPathInsert
        if len(resPathInsert) == 0:
            self.currentResPathInsert = None
        else:
            self.currentResPathInsert = resPathInsert
        self._UpdatePreviewShip()

    def _UpdatePreviewShip(self):
        if self.previewCont is not None:
            self.previewCont.PreviewSofDna(self.GetPreviewDna(),
                                           dirt=self.currentDirtLevel)

    def _UpdatePlayerShip(self):
        michelle = sm.GetService('michelle')
        ship = michelle.GetBall(session.shipid)
        if ship is None:
            return
        ship.UnfitHardpoints()
        ship.Release()
        while ship.model is not None:
            blue.synchro.Yield()

        ship.released = False
        ship.GetDNA = self.GetPreviewDna
        ship.LoadModel()
        ship.Assemble()
        if self.currentDirtLevel is not None:
            ship.model.dirtLevel = self.currentDirtLevel
示例#22
0
class ImpactVisualizer():
    def __init__(self):
        self.name = 'Impact Visualizer'
        self.windowID = 'ImpactVisualizer_ ' + self.name
        self.damageLocatorID = 0
        self.impactVelocity = [0.0, -1000.0, 0.0]
        self.impactObjectMass = 100000
        self.shipId = None
        self.shipInput = None
        self.impactArrow = None
        self.arrowModel = None
        self.impactArrowBoundingRadius = 0.0
        self.impactRotation = geo2.QuaternionRotationSetYawPitchRoll(
            0.0, math.pi, 0.0)
        self.damageLocatorPos = (0.0, 0.0, 0.0)
        self.arrowPositionUpdater = None
        self.lockVelocity = True
        self.randomize = False
        self.arrowModel = trinity.Load('res:/Model/global/impactDirection.red')

    def SetupImpactArrow(self):
        self.impactArrow = trinity.EveRootTransform()
        self.impactArrow.name = 'DebugImpactArrow'
        self.impactArrow.children.append(self.arrowModel)
        self.arrowPositionUpdater = ArrowPositionUpdater(self.impactArrow)

    def GetImpactArrowBoundingRadius(self):
        geometry = self.arrowModel.mesh.geometry
        geometry.RecalculateBoundingSphere()
        self.impactArrowBoundingRadius = geometry.GetBoundingSphere(0)[1]

    def _OnClose(self):
        self.RemoveImpactArrowFromScene()
        self.arrowPositionUpdater.Stop()

    def GetBall(self, ballID=None):
        if ballID is None:
            ballID = self.shipId
        return sm.GetService('michelle').GetBall(ballID)

    def ShowUI(self):
        self.SetupImpactArrow()
        uicontrols.Window.CloseIfOpen(windowID=self.windowID)
        wnd = uicontrols.Window.Open(windowID=self.windowID)
        wnd.SetTopparentHeight(0)
        wnd.SetMinSize([500, 100])
        wnd.SetCaption(self.name)
        wnd._OnClose = self._OnClose
        main = wnd.GetMainArea()
        headerCont = Container(name='headerCont',
                               parent=main,
                               align=uiconst.TOTOP,
                               height=30,
                               padBottom=10)
        bottomCont = Container(name='bottomCont',
                               parent=main,
                               align=uiconst.TOBOTTOM,
                               height=30)
        self.shipIdLabel = EveLabelSmall(name='shipIDLabel',
                                         align=uiconst.CENTER,
                                         parent=headerCont,
                                         text='Ship ID: %s' % self.shipId)
        Button(name='apply_button',
               align=uiconst.CENTER,
               parent=bottomCont,
               label='Apply Physical Impact',
               func=self._OnApplyPhysicalImpact)
        mainContainer = GridContainer(name='mainCont',
                                      parent=main,
                                      align=uiconst.TOALL,
                                      columns=4,
                                      rows=3)
        container = Container(name='impactVelocityLockAndLabel',
                              align=uiconst.TOALL,
                              parent=mainContainer,
                              padRight=10)
        self.lockVelocityButton = ButtonIcon(
            name='MyButtonIcon',
            parent=container,
            align=uiconst.TOPLEFT,
            width=16,
            height=16,
            iconSize=16,
            padLeft=10,
            texturePath='res:/UI/Texture/Icons/bookmark.png',
            func=self.OnLockVelocity)
        EveLabelSmall(name='impactVelocity',
                      align=uiconst.TORIGHT,
                      parent=container,
                      padRight=10,
                      text='Impact Velocity')
        self.impactVelocityXInput = SinglelineEdit(
            name='xVelocity',
            align=uiconst.TOTOP,
            label='X',
            parent=mainContainer,
            padRight=10,
            setvalue=str(self.impactVelocity[0]),
            OnFocusLost=self.OnSetImpactVelocityX,
            OnReturn=self.OnSetImpactVelocityX)
        self.impactVelocityYInput = SinglelineEdit(
            name='yVelocity',
            align=uiconst.TOTOP,
            label='Y',
            parent=mainContainer,
            padRight=10,
            setvalue=str(self.impactVelocity[1]),
            OnFocusLost=self.OnSetImpactVelocityY,
            OnReturn=self.OnSetImpactVelocityY)
        self.impactVelocityZInput = SinglelineEdit(
            name='zVelocity',
            align=uiconst.TOTOP,
            label='Z',
            parent=mainContainer,
            padRight=10,
            setvalue=str(self.impactVelocity[2]),
            OnFocusLost=self.OnSetImpactVelocityZ,
            OnReturn=self.OnSetImpactVelocityZ)
        EveLabelSmall(name='shipIDInputLabel',
                      parent=mainContainer,
                      align=uiconst.TORIGHT,
                      padRight=10,
                      text='Ship ID')
        self.shipInput = SinglelineEdit(name='shipIdInput',
                                        parent=mainContainer,
                                        align=uiconst.TOTOP,
                                        padRight=10,
                                        setvalue=str(session.shipid),
                                        OnFocusLost=self.OnSetShipId,
                                        OnReturn=self.OnSetShipId)
        EveLabelSmall(name='damageLocatorLabel',
                      align=uiconst.TORIGHT,
                      padRight=10,
                      parent=mainContainer,
                      text='Damage Locator')
        self.damageLocatorInput = SinglelineEdit(
            name='damageLocator',
            align=uiconst.TOTOP,
            label='',
            parent=mainContainer,
            padRight=10,
            setvalue=str(self.damageLocatorID),
            ints=(0, 0),
            OnChange=self.OnSetDamageLocator)
        EveLabelSmall(name='impactMassLabel',
                      align=uiconst.TORIGHT,
                      padRight=10,
                      parent=mainContainer,
                      text='Impact Mass')
        self.impactMassInput = SinglelineEdit(name='impactMass',
                                              align=uiconst.TOTOP,
                                              label='',
                                              parent=mainContainer,
                                              padRight=10,
                                              setvalue=str(
                                                  self.impactObjectMass),
                                              OnChange=self.OnSetImpactMass)
        self.randomizeDL = Checkbox(name='myCheckbox',
                                    parent=mainContainer,
                                    text='Randomize Damage Locators',
                                    checked=self.randomize,
                                    callback=self.OnRandomize)
        self.AddImpactArrowToScene()
        self.OnSetShipId()

    def OnSetShipId(self, *args):
        try:
            shipId = long(self.shipInput.GetValue())
        except ValueError:
            print "Could not set shipId to '%s'" % self.shipInput.GetValue()
            return

        if self.shipId == shipId:
            return
        if sm.GetService('michelle').GetBall(shipId) is None:
            print "No ball with id '%d' found in ballpark" % shipId
            return
        print 'Setting ship ID to %d' % shipId
        self.shipId = shipId
        self.shipIdLabel.SetText('Ship ID: %s' % self.shipId)
        self.arrowPositionUpdater.SetBall(self.GetBall())
        self.damageLocatorInput.IntMode(
            minint=0, maxint=len(self.GetBall().model.damageLocators))
        if len(self.GetBall().model.damageLocators) >= self.damageLocatorID:
            self.damageLocatorInput.SetValue(str(self.damageLocatorID))
        else:
            self.damageLocatorInput.SetValue(str(0))
        self.OnSetDamageLocator()

    def OnSetImpactVelocityX(self, *args):
        self.impactVelocity = (float(self.impactVelocityXInput.GetValue()),
                               self.impactVelocity[1], self.impactVelocity[2])
        self.arrowPositionUpdater.SetArrowDirection(self.impactVelocity)

    def OnSetImpactVelocityY(self, *args):
        self.impactVelocity = (self.impactVelocity[0],
                               float(self.impactVelocityYInput.GetValue()),
                               self.impactVelocity[2])
        self.arrowPositionUpdater.SetArrowDirection(self.impactVelocity)

    def OnSetImpactVelocityZ(self, *args):
        self.impactVelocity = (self.impactVelocity[0], self.impactVelocity[1],
                               float(self.impactVelocityZInput.GetValue()))
        self.arrowPositionUpdater.SetArrowDirection(self.impactVelocity)

    def OnLockVelocity(self, *args):
        self.lockVelocity = not self.lockVelocity
        if self.lockVelocity:
            self.lockVelocityButton.SetRotation(0)
        else:
            self.lockVelocityButton.SetRotation(-20)

    def OnSetDamageLocator(self, *args):
        self.damageLocatorID = int(self.damageLocatorInput.GetValue())
        self.arrowPositionUpdater.SetDamageLocator(self.damageLocatorID)
        if not self.lockVelocity:
            _, rotation = self.GetBall().model.damageLocators[
                self.damageLocatorID]
            self.impactVelocity = geo2.QuaternionTransformVector(
                rotation, (0.0, geo2.Vec3Length(self.impactVelocity), 0.0))
            self.impactVelocity = (-self.impactVelocity[0],
                                   -self.impactVelocity[1],
                                   -self.impactVelocity[2])
            self.impactVelocityXInput.SetValue(str(self.impactVelocity[0]))
            self.impactVelocityYInput.SetValue(str(self.impactVelocity[1]))
            self.impactVelocityZInput.SetValue(str(self.impactVelocity[2]))
            self.arrowPositionUpdater.SetArrowDirection(self.impactVelocity)

    def OnSetImpactMass(self, *args):
        self.impactObjectMass = float(self.impactMassInput.GetValue())

    def OnRandomize(self, *args):
        self.randomize = not self.randomize
        if self.randomize and self.lockVelocity:
            self.OnLockVelocity()

    def RemoveImpactArrowFromScene(self):
        scene = sm.GetService('sceneManager').GetActiveScene()
        objectsToRemove = []
        for o in scene.objects:
            if o.name == 'DebugImpactArrow':
                objectsToRemove.append(o)

        for o in objectsToRemove:
            scene.objects.remove(o)

    def AddImpactArrowToScene(self):
        scene = sm.GetService('sceneManager').GetActiveScene()
        scene.objects.append(self.impactArrow)

    def _OnApplyPhysicalImpact(self, *args):
        if self.randomize:
            newDamageLocatorID = random.randint(
                0,
                len(self.GetBall().model.damageLocators) - 1)
            while newDamageLocatorID == self.damageLocatorID:
                newDamageLocatorID = random.randint(
                    0,
                    len(self.GetBall().model.damageLocators) - 1)

            self.damageLocatorID = newDamageLocatorID
            self.damageLocatorInput.SetValue(str(self.damageLocatorID))
            self.OnSetDamageLocator()
        sm.GetService('michelle').GetBall(
            self.shipId).ApplyTorqueAtDamageLocator(self.damageLocatorID,
                                                    self.impactVelocity,
                                                    self.impactObjectMass)
示例#23
0
class AssetRenderer(object):
    __guid__ = 'cc.AssetRenderer'
    __exportedcalls__ = {}

    def __init__(self, showUI = True):
        trinity.SetFpsEnabled(False)
        if uicore.layer.charactercreation.isopen:
            uicore.layer.charactercreation.TearDown()
            uicore.layer.charactercreation.Flush()
        uicore.layer.login.CloseView()
        uicore.layer.charsel.CloseView()
        for each in uicore.layer.main.children[:]:
            each.Close()

        uicore.device.ForceSize()
        self.resolution = ccConst.TEXTURE_RESOLUTIONS[1]
        self.oldNonRandomize = getattr(prefs, 'NoRandomize', False)
        prefs.NoRandomize = True
        self.characterSvc = sm.GetService('character')
        self.charID = 0
        self.factory = sm.GetService('character').factory
        self.factory.compressTextures = False
        self.SetupUI(showUI=showUI)

    def SetupUI(self, showUI = True):
        uicore.layer.main.Flush()
        col1 = Container(parent=uicore.layer.main, align=uiconst.TOLEFT, width=160, padLeft=20, padTop=10)
        self.femaleCB = self.AddCheckbox('female', col1)
        self.maleCB = self.AddCheckbox('male', col1)
        Line(parent=col1, align=uiconst.TOTOP)
        self.bloodlines = []
        for bloodlineID, each in BLOODLINES:
            cb = self.AddCheckbox(each, col1)
            cb.bloodlineID = bloodlineID
            self.bloodlines.append(cb)

        Line(parent=col1, align=uiconst.TOTOP)
        cb = self.AddCheckbox('mannequin', col1)
        cb.bloodlineID = -1
        cb.padTop = 5
        self.mannequinCB = cb
        Line(parent=col1, align=uiconst.TOTOP, padBottom=15)
        cb = self.AddCheckbox('render rgb', col1)
        cb.hint = 'to render images with 3 different background to make alpha (needs processing). You should be using this'
        self.rgbCB = cb
        Line(parent=col1, align=uiconst.TOTOP, padBottom=15)
        cb = self.AddCheckbox('render Types', col1)
        self.renderTypesCb = cb
        cb.hint = 'check this to only render typed Items. Leave field blank to render all types, else provide typeIDs.\n<br>Usually typed items should only be rendered on mannequins, but can be rendered on any doll (tattoos look bad on mannequin so they are rendered on bloodlines)'
        self.typeIDsEditField = SinglelineEdit(parent=col1, align=uiconst.TOTOP, padding=(15, -4, 20, 0))
        Line(parent=col1, align=uiconst.TOTOP, padBottom=15)
        cb = self.AddCheckbox('render sets', col1)
        self.renderSetsCb = cb
        cb.hint = 'check this to only render sets of typed items. Need to provide a list of sets of this format:\n<br>(typeID1, typeID2, typeID3), (typeID4, typeID5, typeID6)'
        self.setTypeIDsEditField = SinglelineEdit(parent=col1, align=uiconst.TOTOP, padding=(15, -4, 20, 0))
        col2 = Container(parent=uicore.layer.main, align=uiconst.TOLEFT, width=160, padTop=10)
        col3 = Container(parent=uicore.layer.main, align=uiconst.TOLEFT, width=140, padTop=10)
        self.checkboxes = []
        categs = SETUP.keys()
        categs.sort()
        for each in categs[:20]:
            if isinstance(each, types.StringTypes):
                cb = self.AddCheckbox(each, col2)
                self.checkboxes.append(cb)

        for each in categs[20:]:
            if isinstance(each, types.StringTypes):
                cb = self.AddCheckbox(each, col3)
                self.checkboxes.append(cb)

        Line(parent=col3, align=uiconst.TOTOP, padBottom=20)
        self.altCheckboxes = []
        for each in ('poses', 'lights'):
            cb = self.AddCheckbox(each, col3)
            self.altCheckboxes.append(cb)

        self.sizeCombo = Combo(label='Size', parent=col3, options=[('512', 512), ('128', 128)], name='sizeCombo', align=uiconst.TOTOP, padTop=40)
        self.sizeCombo.hint = 'use 512 for NES rendering, unless the 128 rendering has been fixed'
        resolutionOption = [('Best', ccConst.TEXTURE_RESOLUTIONS[0]), ('Good', ccConst.TEXTURE_RESOLUTIONS[1]), ('Low', ccConst.TEXTURE_RESOLUTIONS[2])]
        self.resolutionCombo = Combo(label='Resolution', parent=col3, options=resolutionOption, name='resolutionComb', align=uiconst.TOTOP, padTop=20)
        self.resolutionCombo.hint = "it's ok to use Good for character creator/types, use Best for NES rendering"
        b1 = Button(parent=uicore.layer.main, label='Render', align=uiconst.CENTERBOTTOM, func=self.RenderLoopAll, top=20)
        b2 = Button(parent=uicore.layer.main, label='Try one item', align=uiconst.BOTTOMLEFT, func=self.RenderLoopTry, top=20, left=20)
        if not showUI:
            for each in [col1,
             col2,
             col3,
             b1,
             b2]:
                each.display = False

    def AddCheckbox(self, cbName, parent, groupname = None):
        setting = Bunch(settings.user.ui.Get('assetRenderState', {}))
        cb = Checkbox(parent=parent, text=cbName, checked=bool(setting.Get(cbName, None)), callback=self.CBChange, groupname=groupname)
        cb.name = cbName
        return cb

    def CBChange(self, checkbox, *args):
        setting = settings.user.ui.Get('assetRenderState', {})
        setting[checkbox.name] = checkbox.GetValue()
        settings.user.ui.Set('assetRenderState', setting)
        if not getattr(self, 'spreadingValue', False):
            ctrl = uicore.uilib.Key(uiconst.VK_CONTROL)
            if ctrl:
                self.spreadingValue = True
                if checkbox in self.bloodlines:
                    for each in self.bloodlines:
                        each.SetValue(checkbox.GetValue())

                elif checkbox in self.checkboxes:
                    for each in self.checkboxes:
                        each.SetValue(checkbox.GetValue())

                self.spreadingValue = False

    def RenderLoopTry(self, *args):
        self.RenderLoop(tryout=True)

    def RenderLoopAll(self, *args):
        self.RenderLoop(tryout=False)

    def RenderLoop(self, tryout = False, fromWebtools = False):
        try:
            self._RenderLoop(tryout=tryout, fromWebtools=fromWebtools)
        finally:
            uicore.device.ForceSize(512, 512)
            uicore.layer.menu.display = True
            uicore.layer.hint.display = True
            uicore.layer.main.display = True
            print 'in finally'
            prefs.NoRandomize = self.oldNonRandomize

    def _RenderLoop(self, tryout = False, fromWebtools = False):
        self.FindWhatToRender()
        self.characterSvc.characters = {}
        self.characterSvc.TearDown()
        uicore.layer.charactercreation.OpenView()
        uicore.layer.charactercreation.Flush()
        for layerName, layer in uicore.layer.__dict__.iteritems():
            if isinstance(layer, LayerCore):
                layer.display = False

        renderSize = self.sizeCombo.GetValue()
        uicore.device.ForceSize(renderSize, renderSize)
        sm.GetService('sceneManager').SetSceneType(0)
        uicore.layer.charactercreation.SetupScene(ccConst.SCENE_PATH_CUSTOMIZATION)
        self.resolution = self.resolutionCombo.GetValue()
        scene = uicore.layer.charactercreation.scene
        lightScene = trinity.Load(NORMAL_LIGHT_SETTINGS)
        ccUtil.SetupLighting(scene, lightScene, lightScene)
        uicore.layer.charactercreation.cameraUpdateJob = None
        uicore.layer.charactercreation.camera = CharCreationCamera(None)
        uicore.layer.charactercreation.SetupCameraUpdateJob()
        camera = uicore.layer.charactercreation.camera
        self.SetupRenderJob()
        blue.pyos.synchro.SleepWallclock(2000)
        self.DoLightsAndPoses(camera, scene)
        self.DoAssets(camera, scene, tryout)

    def SetupRenderJob(self):
        for each in trinity.renderJobs.recurring:
            if each.name == 'cameraUpdate':
                trinity.renderJobs.recurring.remove(each)
            elif each.name == 'BaseSceneRenderJob':
                self.renderJob = each
                self.renderJob.RemoveStep('RENDER_BACKDROP')
                self.renderJob.SetClearColor((0.9, 0.9, 0.9, 0.0))

    def FindWhatToRender(self):
        self.doRenderFemale = self.femaleCB.GetValue()
        self.doRenderMale = self.maleCB.GetValue()
        self.bloodlineIDsToRender = [ bloodlineCB.bloodlineID for bloodlineCB in self.bloodlines if bloodlineCB.GetValue() ]
        self.altGroupsToRender = [ checkBox.name for checkBox in self.altCheckboxes if checkBox.GetValue() ]
        self.assetCategoriesToRender = [ checkBox.name for checkBox in self.checkboxes if checkBox.GetValue() ]

    def DoLightsAndPoses(self, camera, scene):
        for altCategory in self.altGroupsToRender:
            for genderID, shouldRender in [(0, self.doRenderFemale), (1, self.doRenderMale)]:
                if not shouldRender:
                    continue
                uicore.layer.charactercreation.genderID = genderID
                for bloodlineID in self.bloodlineIDsToRender:
                    self.PosesAndLightThumbnails(bloodlineID, altCategory, camera, genderID, scene)

    def DoAssets(self, camera, scene, tryout):
        for gender, genderID, shouldRender in [('Female', 0, self.doRenderFemale), ('Male', 1, self.doRenderMale)]:
            if not shouldRender:
                continue
            if getattr(self, 'mannequinCB', None) and self.mannequinCB.GetValue():
                avatar = self.RenderMannequinAssets(camera, genderID, scene, tryout)
            paperdollGender = ccUtil.GenderIDToPaperDollGender(genderID)
            for bloodlineID in self.bloodlineIDsToRender:
                character = self.PrepareBloodlineDoll(bloodlineID, paperdollGender, scene)
                self.RenderNormalAssets(bloodlineID, camera, character, genderID, scene, tryout)
                if tryout:
                    break

            if tryout:
                break

    def PosesAndLightThumbnails(self, bloodlineID, altCategory, camera, genderID, scene):
        self.characterSvc.RemoveCharacter(self.charID)
        uicore.layer.charactercreation.ResetDna()
        paperdollGender = ccUtil.GenderIDToPaperDollGender(genderID)
        self.SetupCharacter(bloodlineID, scene, paperdollGender)
        for dcCategory in DRESSCODE[ccConst.hair]:
            dcTypeData = self.characterSvc.GetAvailableTypesByCategory(dcCategory, genderID, bloodlineID)
            if dcTypeData:
                dcItemType = dcTypeData[0]
                dcModifier = self.characterSvc.ApplyTypeToDoll(self.charID, dcItemType)

        character = self.characterSvc.GetSingleCharacter(self.charID)
        self.WaitForDollAndScene(character.doll, scene)
        trinity.WaitForResourceLoads()
        camera.SetFieldOfView(0.3)
        if altCategory == 'poses':
            self.RenderPoseThumbnails(bloodlineID, camera, character, genderID)
        elif altCategory == 'lights':
            self.RenderLightThumbnails(bloodlineID, camera, genderID)

    def RenderPoseThumbnails(self, bloodlineID, camera, character, genderID):
        if genderID == 0:
            camera.SetPointOfInterest((0.0, 1.5, 0.0))
        else:
            camera.SetPointOfInterest((0.0, 1.6, 0.0))
        camera.distance = 2.0
        camera.Update()
        self.characterSvc.StartPosing(self.charID)
        character.avatar.animationUpdater.network.SetControlParameter('ControlParameters|NetworkMode', 2)
        renderRGB = self.rgbCB.GetValue()
        for i in xrange(ccConst.POSERANGE):
            self.characterSvc.ChangePose(i, self.charID)
            blue.pyos.synchro.SleepWallclock(100)
            outputPath = OUTPUT_ROOT + '%s_g%s_b%s.png' % ('pose_%s' % i, genderID, bloodlineID)
            self.SaveScreenShot(outputPath, rgb=renderRGB)

    def RenderLightThumbnails(self, bloodlineID, camera, genderID):
        if genderID == 0:
            camera.SetPointOfInterest((0.0, 1.6, 0.0))
        else:
            camera.SetPointOfInterest((0.0, 1.7, 0.0))
        camera.distance = 1.4
        camera.Update()
        lightingList = ccConst.LIGHT_SETTINGS_ID
        lightingColorList = ccConst.LIGHT_COLOR_SETTINGS_ID
        renderRGB = self.rgbCB.GetValue()
        for each in lightingList:
            for color in lightingColorList:
                uicore.layer.charactercreation.SetLightsAndColor(each, color)
                blue.synchro.Yield()
                blue.resMan.Wait()
                trinity.WaitForResourceLoads()
                for i in xrange(10):
                    blue.pyos.synchro.SleepWallclock(100)

                camera.Update()
                outputPath = OUTPUT_ROOT + '%s_g%s_b%s.png' % ('light_%s_%s' % (each, color), genderID, bloodlineID)
                self.SaveScreenShot(outputPath, rgb=renderRGB)

    def FreezeCharacter(self, avatar):
        avatar.animationUpdater.network.SetControlParameter('ControlParameters|isAlive', 0)
        avatar.animationUpdater.network.update = False
        blue.pyos.synchro.SleepWallclock(500)

    def RenderMannequinAssets(self, camera, genderID, scene, tryout):
        mannequin = paperDoll.PaperDollCharacter(self.factory)
        mannequin.doll = paperDoll.Doll('mannequin', gender=ccUtil.GenderIDToPaperDollGender(genderID))
        doll = mannequin.doll
        if genderID == ccConst.GENDERID_MALE:
            doll.Load(MALE_MANNEQUIN, self.factory)
        else:
            doll.Load(FEMALE_MANNEQUIN, self.factory)
        self.WaitForDoll(doll)
        doll.overrideLod = paperDoll.LOD_SKIN
        doll.textureResolution = self.resolution
        mannequin.Spawn(scene, usePrepass=False)
        avatar = mannequin.avatar
        networkPath = ccConst.CHARACTER_CREATION_NETWORK
        self.factory.CreateGWAnimation(avatar, networkPath)
        network = avatar.animationUpdater.network
        if network is not None:
            network.SetControlParameter('ControlParameters|BindPose', 1.0)
            if doll.gender == 'female':
                network.SetAnimationSetIndex(0)
            else:
                network.SetAnimationSetIndex(1)
        blue.pyos.synchro.SleepWallclock(500)
        self.FreezeCharacter(avatar)
        if self.renderSetsCb.GetValue():
            self.LoadMannequinAndCamera(mannequin, genderID, ccConst.outer, camera, scene)
            setText = self.setTypeIDsEditField.GetValue()
            setText = setText.strip()
            if not setText.endswith(','):
                setText += ','
            clothingSets = eval(setText)
            for eachSet in clothingSets:
                self.DoRenderMannequinAssetType(avatar, eachSet, genderID, mannequin, scene, 'set')

            return avatar
        for category in self.assetCategoriesToRender:
            self.LoadMannequinAndCamera(mannequin, genderID, category, camera, scene)
            typeData = self.characterSvc.GetAvailableTypesByCategory(category, genderID, -1)
            for itemType in typeData:
                wasRendered = self.RenderMannequinAssetType(avatar, genderID, mannequin, scene, itemType, category)
                if wasRendered and tryout:
                    break

        return avatar

    def LoadMannequinAndCamera(self, mannequin, genderID, category, camera, scene):
        doll = mannequin.doll
        if genderID == ccConst.GENDERID_MALE:
            doll.Load(MALE_MANNEQUIN, self.factory)
        else:
            doll.Load(FEMALE_MANNEQUIN, self.factory)
        self.WaitForDoll(doll)
        lightScene = trinity.Load(NORMAL_LIGHT_SETTINGS)
        ccUtil.SetupLighting(scene, lightScene, lightScene)
        cameraSetup = self.SetUpCamera(camera, category, mannequin, SETUP, scene, genderID)

    def GetTypeIDsFromField(self):
        typeIDsString = self.typeIDsEditField.GetValue()
        typeIDs = [ int(x) for x in typeIDsString.split(',') if x ]
        return typeIDs

    def RenderMannequinAssetType(self, avatar, genderID, mannequin, scene, itemType, category):
        typeID = itemType[2]
        if typeID in (None, -1):
            return False
        typeIDs = self.GetTypeIDsFromField()
        if typeIDs and typeID not in typeIDs:
            return False
        return self.DoRenderMannequinAssetType(avatar, [typeID], genderID, mannequin, scene, category)

    def DoRenderMannequinAssetType(self, avatar, typeIDs, genderID, mannequin, scene, category):
        if category == ccConst.bottommiddle:
            pantsModifiers = mannequin.doll.buildDataManager.GetModifiersByCategory(ccConst.bottomouter)
            for pm in pantsModifiers:
                mannequin.doll.RemoveResource(pm.GetResPath(), self.factory)

        modifierList = []
        for typeID in typeIDs:
            asset = GetPaperDollResource(typeID, genderID)
            doll = mannequin.doll
            path = asset.resPath
            modifier = doll.SetItemType(self.factory, path, weight=1.0)
            if modifier:
                modifierList.append(modifier)

        mannequin.Update()
        self.WaitForDoll(doll)
        if not modifierList:
            return False
        self.SetShadow(avatar, scene)
        blue.pyos.synchro.SleepWallclock(500)
        renderRGB = self.rgbCB.GetValue()
        if len(typeIDs) == 1:
            outputPath = self.GetOutputPath(assetPath=path, genderID=genderID, category=category, typeID=typeID)
        else:
            typeIDsString = str(typeIDs).replace(' ', '').replace('(', '').replace(')', '').replace(',', '_')
            outputPath = self.GetOutputPath(assetPath=typeIDsString, genderID=genderID, category=category)
        self.SaveScreenShot(outputPath, rgb=renderRGB)
        for modifier in modifierList:
            doll.RemoveResource(modifier.GetResPath(), self.factory)

        mannequin.Update()
        self.WaitForDoll(doll)
        return True

    def PrepareBloodlineDoll(self, bloodlineID, paperdollGender, scene):
        self.characterSvc.RemoveCharacter(self.charID)
        uicore.layer.charactercreation.ResetDna()
        self.SetupCharacter(bloodlineID, scene, paperdollGender)
        character = self.characterSvc.GetSingleCharacter(self.charID)
        character.avatar.translation = (0.0, 0.0, 0.0)
        self.WaitForDollAndScene(character.doll, scene)
        self.FreezeCharacter(character.avatar)
        trinity.WaitForResourceLoads()
        return character

    def SetupCharacter(self, bloodlineID, scene, paperdollGender):
        self.characterSvc.AddCharacterToScene(self.charID, scene, paperdollGender, bloodlineID=bloodlineID)
        doll = self.characterSvc.GetSingleCharactersDoll(self.charID)
        doll.overrideLod = paperDoll.LOD_SKIN
        doll.textureResolution = self.resolution
        self.characterSvc.SetDollBloodline(self.charID, bloodlineID)
        self.characterSvc.ApplyItemToDoll(self.charID, 'head', bloodlineAssets[bloodlineID], doUpdate=False)
        self.characterSvc.UpdateDoll(self.charID, fromWhere='RenderLoop')

    def RenderNormalAssets(self, bloodlineID, camera, character, genderID, scene, tryout):
        doll = character.doll
        for category in self.assetCategoriesToRender:
            typeData = self.characterSvc.GetAvailableTypesByCategory(category, genderID, bloodlineID)
            lightScene = trinity.Load(NORMAL_LIGHT_COLOR)
            ccUtil.SetupLighting(scene, lightScene, lightScene)
            cameraSetup = self.SetUpCamera(camera, category, character, SETUP, scene, genderID)
            log.LogNotice('before dresscode')
            if category in DRESSCODE:
                removeDcModifers = self.EnforceDresscode(bloodlineID, category, doll, genderID)
            else:
                removeDcModifers = []
            log.LogNotice('go render type')
            for itemType in typeData:
                wasRendered = self.RenderNormalType(bloodlineID, camera, category, character, genderID, itemType, scene)
                if tryout and wasRendered:
                    break

            log.LogNotice('remove the dresscode')
            for dcResPath in removeDcModifers:
                doll.RemoveResource(dcResPath, self.factory)

            log.LogNotice('done with category')

    def RenderNormalType(self, bloodlineID, camera, category, character, genderID, itemType, scene):
        typeID = itemType[2]
        if typeID is not None:
            if not self.renderTypesCb.GetValue():
                return False
            typeIDs = self.GetTypeIDsFromField()
            if typeIDs and typeID not in typeIDs:
                return False
        doll = character.doll
        modifer = self.characterSvc.ApplyTypeToDoll(self.charID, itemType)
        if not modifer:
            return False
        typeInfo = itemType[1]
        if typeInfo[0].startswith('scars'):
            self.SetCameraForScar(typeInfo, character, camera, scene)
        if typeInfo[0].startswith(PIERCINGCATEGORIES):
            self.SetCameraAndLightPiercings(category, typeInfo, character, camera, scene)
        self.ApplyTuckingIfNeeded(category)
        self.TrySetColor(bloodlineID, category, genderID, typeInfo)
        if (category, genderID) in EXAGGERATE:
            if getattr(modifer, 'weight', None) is not None:
                modifer.weight = 1.5 * modifer.weight
        self.characterSvc.UpdateDoll(self.charID, fromWhere='RenderLoop')
        self.SetShadow(character.avatar, scene)
        blue.pyos.synchro.SleepWallclock(500)
        self.WaitForDoll(doll)
        blue.resMan.Wait()
        trinity.WaitForResourceLoads()
        path = '_'.join(list(itemType[1]))
        outputPath = self.GetOutputPath(assetPath=path, genderID=genderID, category=category, bloodlineID=bloodlineID, typeID=typeID)
        renderRGB = self.rgbCB.GetValue()
        self.SaveScreenShot(outputPath, rgb=renderRGB)
        doll.RemoveResource(modifer.GetResPath(), self.factory)
        return True

    def ApplyTuckingIfNeeded(self, category):
        if category not in TUCKINDEX:
            return
        tuckPath, requiredModifier, subKey = ccConst.TUCKMAPPING[category]
        tuckModifier = sm.GetService('character').GetModifierByCategory(self.charID, tuckPath)
        if tuckModifier:
            tuckVariations = tuckModifier.GetVariations()
            tuckStyle = tuckModifier.GetResPath().split('/')[-1]
            self.characterSvc.ApplyItemToDoll(self.charID, category, tuckStyle, variation=tuckVariations[TUCKINDEX[category]])

    def TrySetColor(self, bloodlineID, category, genderID, typeInfo):
        if category in (ccConst.beard, ccConst.hair, ccConst.eyebrows):
            category = ccConst.hair
        try:
            if typeInfo[1] or typeInfo[2]:
                return
            categoryColors = self.characterSvc.GetAvailableColorsForCategory(category, genderID, bloodlineID)
            if not categoryColors:
                return
            primary, secondary = categoryColors
            primaryVal = (primary[1][0], primary[1][2])
            if primary and secondary:
                secondaryVal = (secondary[1][0], secondary[1][2])
                self.characterSvc.SetColorValueByCategory(self.charID, category, primaryVal, secondaryVal)
            else:
                self.characterSvc.SetColorValueByCategory(self.charID, category, primaryVal, None)
        except:
            pass
        finally:
            if category == ccConst.hair:
                sm.GetService('character').SetHairDarkness(0, 0.5)

    def ReformatAssetPath(self, path):
        assetResPath = path.replace('/', '_').replace('.type', '')
        return assetResPath

    def WaitForDollAndScene(self, doll, scene):
        while len(scene.dynamics) < 1:
            blue.synchro.Yield()

        blue.synchro.Yield()
        self.WaitForDoll(doll)

    def WaitForDoll(self, doll):
        while doll.busyUpdating:
            blue.synchro.Yield()

    def EnforceDresscode(self, bloodlineID, category, doll, genderID):
        if category in DRESSCODE_CUSTOM_BY_CATEGORY:
            dressCode = DRESSCODE_CUSTOM_BY_CATEGORY[category][genderID]
        elif genderID == ccConst.GENDERID_FEMALE:
            dressCode = DRESSCODE_FEMALE_DEFAULT
        else:
            dressCode = DRESSCODE_MALE_DEFAULT
        removeDcModifers = []
        for dcCategory in DRESSCODE_CATEGORIES:
            if dcCategory == category:
                continue
            dcTypeData = self.characterSvc.GetAvailableTypesByCategory(dcCategory, genderID, bloodlineID)
            if not dcTypeData:
                continue
            for itemType in dcTypeData:
                assetID = itemType[0]
                if assetID in dressCode:
                    if dcCategory == ccConst.hair:
                        var = self.GetHairColor(genderID, bloodlineID)
                    else:
                        var = None
                    dcModifier = self.characterSvc.ApplyTypeToDoll(self.charID, itemType, doUpdate=False, rawColorVariation=var)
                    if dcModifier:
                        removeDcModifers.append(dcModifier.GetResPath())
                    self.WaitForDoll(doll)
                    blue.resMan.Wait()
                    break

        return removeDcModifers

    def SetShadow(self, avatar, scene):
        if paperDoll.SkinSpotLightShadows.instance is not None:
            paperDoll.SkinSpotLightShadows.instance.Clear(killThread=True)
            del paperDoll.SkinSpotLightShadows.instance
            paperDoll.SkinSpotLightShadows.instance = None
        ss = paperDoll.SkinSpotLightShadows(scene, debugVisualize=False, size=2048)
        ss.SetupSkinnedObject(avatar)
        paperDoll.SkinSpotLightShadows.instance = ss

    def SetCameraAndLightPiercings(self, category, typeInfo, character, camera, scene):
        typeName, a, b = typeInfo
        if typeName.endswith('left', 0, -1):
            dictToUse = PIERCINGLEFTGROUPS
        elif typeName.endswith('right', 0, -1):
            dictToUse = PIERCINGRIGHTGROUPS
        else:
            dictToUse = PIERCINGPAIRGROUPS
        self.SetUpCamera(camera, category, character, dictToUse, scene)

    def SetCameraForScar(self, typeInfo, character, camera, scene):
        group = SCARGROUPS.get(typeInfo, None)
        if group is None:
            print 'couldnt find the group, return'
            return
        self.SetUpCamera(camera, group, character, SCARCAMERASETINGS, scene)

    def SetCamera(self, camera, poi, distance, yaw, pitch):
        camera.SetPointOfInterest(poi)
        camera.distance = distance
        camera.SetFieldOfView(0.3)
        camera.SetYaw(yaw)
        camera.SetPitch(pitch)
        camera.Update()

    def SetUpCamera(self, camera, category, character, categoryList = SETUP, scene = None, genderID = None):
        if (category, genderID) in categoryList:
            options = categoryList[category, genderID]
        else:
            options = categoryList.get(category, None)
        if options:
            log.LogNotice('+ category = %s' % category)
            boneName, offset, lightSetting = options
            if lightSetting:
                path = '%s%s.red' % (LIGHTLOCATION, lightSetting)
                lightScene = trinity.Load(path)
                ccUtil.SetupLighting(scene, lightScene, lightScene)
            log.LogNotice('before joint')
            joint = 4294967295L
            while joint == 4294967295L:
                log.LogNotice('joint = %s' % joint)
                log.LogNotice('boneName = %s' % boneName)
                joint = character.avatar.GetBoneIndex(boneName)
                log.LogNotice('j = %s' % joint)
                blue.synchro.Yield()
                log.LogNotice('done waiting')

            log.LogNotice('-- joint = %s' % joint)
            poi = character.avatar.GetBonePosition(joint)
            distance, yOffset, xOffset, yaw, pitch = offset
            x, y, z = poi
            if yOffset:
                y += yOffset
            if xOffset:
                x += xOffset
            poi = (x, y, z)
            log.LogNotice('before poi')
            if category in (ccConst.bottomouter, ccConst.feet):
                poi = (0.0, y, z)
            log.LogNotice('before setting camera')
            self.SetCamera(camera, poi, distance, yaw, pitch)
            log.LogNotice('after setting camera')
            return (distance,
             yaw,
             pitch,
             poi)
        else:
            return

    def GetHairColor(self, genderID, bloodlineID):
        colorsA, colorsB = sm.GetService('character').GetAvailableColorsForCategory(ccConst.hair, genderID, bloodlineID)
        colorA = []
        colorB = []
        var = None
        color1Value, color1Name, color2Name, variation = (None, None, None, None)
        if len(colorsA) > 0:
            indexA = int(len(colorsA) * 0.3)
            colorA = colorsA[indexA]
            colorB = None
            if len(colorsB) > 0:
                colorB = colorsB[0]
            color1Value, color1Name, color2Name, variation = sm.GetService('character').GetColorsToUse(colorA, colorB)
        if color1Value:
            return var
        if colorB:
            var = variation
        elif len(colorA) > 0:
            var = colorA[1]
        return var

    def GetOutputPath(self, assetPath, genderID, category = None, bloodlineID = -1, typeID = None):
        assetResPath = self.ReformatAssetPath(assetPath)
        renderRGB = self.rgbCB.GetValue()
        categoryPath = self.ReformatAssetPath(category)
        if renderRGB:
            subFolder = RGB_FOLDER
        else:
            subFolder = categoryPath + '/'
        ccUtil.CreateCategoryFolderIfNeeded(OUTPUT_ROOT, subFolder)
        outputPath = OUTPUT_ROOT + subFolder
        if renderRGB:
            outputPath = outputPath + '%s~' % categoryPath
        if typeID:
            if genderID == ccConst.GENDERID_MALE:
                gender = 'male'
            else:
                gender = 'female'
            outputPath = outputPath + '%s_%s_%s.png' % (typeID, gender, assetResPath)
        elif bloodlineID < 0:
            outputPath = outputPath + '%s_g%s.png' % (assetResPath, genderID)
        else:
            outputPath = outputPath + '%s_g%s_b%s.png' % (assetResPath, genderID, bloodlineID)
        return outputPath

    def SaveScreenShot(self, outputPath, rgb = False):
        if rgb:
            clearColors = (('R', (1.0, 0.0, 0.0, 0.0)), ('G', (0.0, 1.0, 0.0, 0.0)), ('B', (0.0, 0.0, 1.0, 0.0)))
        else:
            clearColors = ((None, None),)
        print 'SaveScreenShot', outputPath
        for channel, color in clearColors:
            if color:
                self.renderJob.SetClearColor(color)
            blue.synchro.Yield()
            backBuffer = trinity.device.GetRenderContext().GetDefaultBackBuffer()
            if not backBuffer.isReadable:
                tempRT = trinity.Tr2RenderTarget(backBuffer.width, backBuffer.height, 1, backBuffer.format)
                backBuffer.Resolve(tempRT)
                bmp = trinity.Tr2HostBitmap(tempRT)
            else:
                bmp = trinity.Tr2HostBitmap(backBuffer)
            if bmp.format == trinity.PIXEL_FORMAT.B8G8R8A8_UNORM:
                bmp.ChangeFormat(trinity.PIXEL_FORMAT.B8G8R8X8_UNORM)
            if rgb:
                bmp.Save(outputPath[:-4] + '_' + channel + outputPath[-4:])
            else:
                bmp.Save(outputPath)
示例#24
0
class BuyItemContainer(BuySellItemContainerBase):
    __guid__ = 'uicls.BuytemContainer'
    default_height = 52
    belowColor = '<color=0xff00ff00>'
    aboveColor = '<color=0xffff5050>'
    totaLabelPath = 'UI/Market/MarketQuote/PayTotal'

    def ApplyAttributes(self, attributes):
        self.blinkBG = None
        self.typeID = attributes.typeID
        self.dropParentFunc = attributes.dropParentFunc
        BuySellItemContainerBase.ApplyAttributes(self, attributes)
        self.adjustQtyTimer = None
        self.isUpdating = False
        self.totalSum = 0.0
        self.orderMultiplier = attributes.orderMultiplier
        self.qty = attributes.qty
        self.stationID = attributes.stationID
        self.newBestPrice, self.numOrders = self.quoteSvc.GetBestAskPriceInStationAndNumberOrders(
            self.typeID, self.stationID, self.qty)
        self.DrawUI()
        self.UpdateUIElements()
        self.GetBestPrice()

    def DrawUI(self):
        self.errorBg = ErrorFrame(bgParent=self)
        self.deltaCont = Container(parent=self,
                                   align=uiconst.TORIGHT,
                                   width=30)
        theRestCont = Container(parent=self, align=uiconst.TOALL)
        self.totalCont = Container(parent=theRestCont,
                                   align=uiconst.TORIGHT_PROP,
                                   width=0.3)
        self.priceCont = Container(parent=theRestCont,
                                   align=uiconst.TORIGHT_PROP,
                                   width=0.22)
        self.qtyCont = Container(parent=theRestCont,
                                 align=uiconst.TORIGHT_PROP,
                                 width=0.15)
        self.itemCont = Container(parent=theRestCont,
                                  align=uiconst.TORIGHT_PROP,
                                  width=0.33)
        self.deleteCont = Container(parent=self.itemCont,
                                    align=uiconst.TORIGHT,
                                    width=24)
        self.deleteButton = ButtonIcon(
            texturePath='res:/UI/Texture/Icons/73_16_210.png',
            pos=(0, 0, 16, 16),
            align=uiconst.CENTERRIGHT,
            parent=self.deleteCont,
            hint=GetByLabel('UI/Generic/RemoveItem'),
            idx=0,
            func=self.RemoveItem)
        self.deleteCont.display = False
        self.textCont = Container(parent=self.itemCont, align=uiconst.TOALL)
        self.DrawItem()
        self.DrawQty()
        self.DrawPrice()
        self.DrawTotal()
        self.DrawDelta()

    def UpdateUIElements(self):
        self.UpdateOrderStateInUI()
        self.GetBestPrice()
        self.SetPrice()
        self.UpdateDelta()

    def GetBestOrderInRange(self):
        stationID = self.stationID
        bidRange = None
        return self.quoteSvc.GetBestAskInRange(typeID=self.typeID,
                                               stationID=stationID,
                                               bidRange=bidRange,
                                               amount=self.qty)

    def ShowNoSellOrders(self):
        if self.newBestPrice is None:
            uicore.animations.FadeIn(self.errorBg, 0.35, duration=0.3)

    def DrawQty(self):
        self.qtySubCont = ContainerAutoSize(name='qtySubCont',
                                            parent=self.qtyCont,
                                            align=uiconst.TOTOP,
                                            callback=self.PositionQtyContainer)
        qty = self.qty
        self.qtyEdit = SinglelineEdit(name='qtyEdit',
                                      parent=self.qtySubCont,
                                      align=uiconst.TOTOP,
                                      padLeft=4,
                                      ints=[1, None],
                                      setvalue=qty,
                                      OnChange=self.OnChange,
                                      hint=GetByLabel('UI/Common/Quantity'))
        self.qtyEdit.OnMouseWheel = self.OnMouseWheelForQtyEdit
        self.qtyTotal = EveLabelMediumBold(text='',
                                           parent=self.qtySubCont,
                                           padLeft=8,
                                           padTop=6,
                                           align=uiconst.TOTOP,
                                           state=uiconst.UI_NORMAL,
                                           autoFadeSides=35)
        self.SetTotalQtyText()

    def OnMouseWheelForQtyEdit(self, *args):
        if uicore.registry.GetFocus() != self.qtyEdit:
            return
        SinglelineEdit.MouseWheel(self.qtyEdit, *args)

    def PositionQtyContainer(self):
        subContTop = self.height / 2.0 - self.qtySubCont.GetAutoSize()[1] / 2.0
        self.qtySubCont.top = int(subContTop)

    def DrawPrice(self):
        self.priceLabel = EveLabelMediumBold(name='priceLabel',
                                             text='',
                                             parent=self.priceCont,
                                             left=4,
                                             align=uiconst.CENTERRIGHT,
                                             state=uiconst.UI_NORMAL)

    def DrawDelta(self):
        self.deltaContainer = BuyDeltaContainer(parent=self.deltaCont,
                                                delta=self.GetDelta(),
                                                func=self.OpenMarket,
                                                align=uiconst.CENTERRIGHT)
        self.deltaContainer.LoadTooltipPanel = self.LoadDeltaTooltip

    def DrawItem(self):
        iconCont = Container(name='iconCont',
                             parent=self.textCont,
                             align=uiconst.TOLEFT,
                             width=32,
                             padding=4)
        iconInnerCont = Container(name='iconInnerCont',
                                  parent=iconCont,
                                  align=uiconst.CENTER,
                                  pos=(0, 0, 32, 32))
        self.wheel = LoadingWheel(parent=iconCont,
                                  pos=(0, 0, 48, 48),
                                  align=uiconst.CENTER,
                                  idx=0)
        self.wheel.display = False
        self.techIcon = Sprite(parent=iconInnerCont,
                               pos=(0, 0, 16, 16),
                               align=uiconst.TOPLEFT,
                               state=uiconst.UI_NORMAL)
        GetTechLevelIcon(self.techIcon, 1, self.typeID)
        self.icon = Icon(parent=iconInnerCont,
                         typeID=self.typeID,
                         state=uiconst.UI_DISABLED,
                         align=uiconst.CENTER)
        self.icon.SetSize(32, 32)
        itemName = GetShowInfoLink(typeID=self.typeID,
                                   text=evetypes.GetName(self.typeID))
        self.itemNameLabel = Label(text=itemName,
                                   parent=self.textCont,
                                   left=40,
                                   align=uiconst.CENTERLEFT,
                                   state=uiconst.UI_NORMAL,
                                   autoFadeSides=35,
                                   fontsize=12)

    def SetPrice(self):
        self.priceLabel.text = self.GetPriceText()

    def GetPriceText(self):
        if self.newBestPrice:
            return FmtISK(self.newBestPrice)
        else:
            return NA_CHAR

    def GetBestPrice(self):
        totalQty = self.qty * self.orderMultiplier
        self.newBestPrice, self.numOrders = self.quoteSvc.GetBestAskPriceInStationAndNumberOrders(
            self.typeID, self.stationID, totalQty)
        self.UpdateOrderStateInUI()

    def UpdateOrderStateInUI(self):
        if self.newBestPrice:
            self.HideNoSellOrders()
        else:
            self.ShowNoSellOrders()

    def GetTotalSum(self):
        price = self.GetPrice() or 0
        totalQty = self.GetQty() * self.orderMultiplier
        self.totalSum = price * totalQty
        self.SetTotalText(self.totalSum)
        return self.totalSum

    def SetTotalText(self, totalSum):
        if totalSum:
            self.totalLabel.text = FmtISK(totalSum)
        else:
            self.totalLabel.text = NA_CHAR

    def UpdateOrderMultiplier(self, multiplier):
        self.orderMultiplier = multiplier
        self.OnChange()

    def UpdateStationID(self, stationID):
        self.stationID = stationID
        self.UpdateUIElements()

    def OnChange(self, *args):
        if self.adjustQtyTimer:
            self.adjustQtyTimer.KillTimer()
        self.adjustQtyTimer = AutoTimer(1000, self.AdjustQty_thread, *args)
        self.SetItemLoading()

    def SetItemLoading(self):
        self.wheel.display = True
        self.qtyTotal.text = ''
        self.totalLabel.text = ''
        self.priceLabel.text = NA_CHAR
        self.deltaContainer.display = False
        self.totalLabel.text = NA_CHAR
        self.isUpdating = True

    def AdjustQty_thread(self, *args):
        self.adjustQtyTimer = None
        if self.destroyed:
            return
        self.qty = self.GetQty()
        self.SetTotalQtyText()
        self.GetBestPrice()
        self.SetPrice()
        self.deltaContainer.display = True
        self.UpdateDelta()
        self.GetTotalSum()
        self.wheel.display = False
        self.isUpdating = False
        if self.parentEditFunc:
            self.parentEditFunc(args)

    def SetTotalQtyText(self):
        totalQty = self.GetTotalQty()
        if totalQty is None:
            self.qtyTotal.text = ''
            self.qtyTotal.hint = ''
        elif self.orderMultiplier > 1:
            self.qtyTotal.display = True
            self.qtyTotal.text = '= %s' % FmtAmt(totalQty)
            self.qtyTotal.hint = GetByLabel(
                'UI/Market/MarketQuote/TotalAmountToBuy',
                numOrders=self.orderMultiplier,
                qty=self.GetQty())
        else:
            self.qtyTotal.display = False

    def GetPrice(self):
        return self.newBestPrice

    def GetQty(self):
        qty = self.qtyEdit.GetValue()
        return qty

    def GetTotalQty(self):
        qty = self.GetQty()
        return self.orderMultiplier * qty

    def GetTradeWndClass(self):
        from eve.client.script.ui.shared.market.buyMultiFromBase import MultiBuy
        return MultiBuy

    def GetDiffFromAvgText(self):
        return '%s %s' % (GetByLabel('UI/Market/MarketQuote/RegionalAdverage'),
                          self.GetDeltaText())

    def LoadDeltaTooltip(self, tooltipPanel, *args):
        tooltipPanel.LoadGeneric2ColumnTemplate()
        tooltipPanel.cellPadding = (4, 1, 4, 1)
        tooltipPanel.AddLabelLarge(
            text=GetByLabel('UI/Market/Marketbase/PricePerUnit'))
        tooltipPanel.AddLabelLarge(text=self.GetPriceText(),
                                   align=uiconst.CENTERRIGHT)
        bestMatchDetails = tooltipPanel.AddLabelSmall(
            text='', align=uiconst.CENTERRIGHT, colSpan=tooltipPanel.columns)
        tooltipPanel.AddSpacer(1, 8, colSpan=tooltipPanel.columns)
        tooltipPanel.AddLabelMedium(text=self.GetDiffFromAvgText(),
                                    align=uiconst.CENTERRIGHT)
        tooltipPanel.AddLabelMedium(text=FmtISK(self.averagePrice),
                                    align=uiconst.CENTERRIGHT)
        tooltipPanel.AddSpacer(1, 8, colSpan=tooltipPanel.columns)
        tooltipPanel.AddLabelMedium(
            text=GetByLabel('UI/Market/MarketQuote/BestInStation'))
        stationBestPrice = self.GetBestMatchText(rangeStation)
        tooltipPanel.AddLabelMedium(text=stationBestPrice,
                                    align=uiconst.CENTERRIGHT)
        tooltipPanel.AddLabelMedium(
            text=GetByLabel('UI/Market/MarketQuote/BestInSystem'))
        stationBestPrice = self.GetBestMatchText(rangeSolarSystem)
        tooltipPanel.AddLabelMedium(text=stationBestPrice,
                                    align=uiconst.CENTERRIGHT)
        tooltipPanel.AddLabelMedium(
            text=GetByLabel('UI/Market/MarketQuote/BestRegional'))
        regBestPrice = self.GetBestMatchText(rangeRegion)
        tooltipPanel.AddLabelMedium(text=regBestPrice,
                                    align=uiconst.CENTERRIGHT)
        if not self.newBestPrice:
            bestMatchDetails.text = GetByLabel(
                'UI/Market/MarketQuote/NoMatchForOrder')
            bestMatchDetails.color = (1.0, 0.275, 0.0, 1.0)
        else:
            bestMatchDetails.text = GetByLabel(
                'UI/Market/MarketQuote/FromNumberOfOrders',
                numOrders=self.numOrders)
            bestMatchDetails.SetAlpha(0.6)

    def GetBestMatchText(self, orderRange):
        bestOrder = self.quoteSvc.GetBestAskInRange(self.typeID,
                                                    self.stationID, orderRange)
        if bestOrder:
            return FmtISK(bestOrder.price)
        return NA_CHAR

    def AddQtyToEntry(self, extraQty):
        self.Blink()
        qty = self.qtyEdit.GetValue()
        newQty = extraQty + qty
        self.qtyEdit.SetValue(newQty)

    def Blink(self):
        self.ConstructBlinkBG()
        uicore.animations.FadeTo(self.blinkBG,
                                 0.0,
                                 0.25,
                                 duration=0.25,
                                 curveType=uiconst.ANIM_WAVE,
                                 loops=2)

    def ConstructBlinkBG(self):
        if self.blinkBG is None:
            self.blinkBG = Sprite(
                name='blinkBg',
                bgParent=self,
                align=uiconst.TOALL,
                state=uiconst.UI_DISABLED,
                texturePath='res:/UI/Texture/classes/InvItem/bgSelected.png',
                opacity=0.0,
                idx=0)

    def OnDropData(self, dragSource, dragData):
        if self.dropParentFunc:
            self.dropParentFunc(dragSource, dragData)