Пример #1
0
class BlueprintCenter(Container):
    __notifyevents__ = ('OnIndustryWndMouseWheel', 'OnIndustryWndClick',
                        'OnBlueprintBrowserNumericInput')

    def ApplyAttributes(self, attributes):
        Container.ApplyAttributes(self, attributes)
        sm.RegisterNotify(self)
        self.jobData = attributes.jobData
        self.newNumRuns = None
        self.setJobRunsThread = None
        self.oldJobData = None
        self.numericInputTimer = None
        self.iconCont = ItemIcon(parent=self,
                                 align=uiconst.CENTER,
                                 state=uiconst.UI_DISABLED,
                                 width=64,
                                 height=64,
                                 opacity=0.0)
        self.errorFrame = ErrorFrame(parent=self,
                                     align=uiconst.CENTER,
                                     state=uiconst.UI_DISABLED,
                                     width=80,
                                     height=80)
        self.ConstructBackground()
        self.runsCont = ContainerAutoSize(parent=self,
                                          align=uiconst.CENTER,
                                          top=100)
        self.runsCaption = IndustryCaptionLabel(
            name='runsCaption',
            parent=self.runsCont,
            align=uiconst.CENTERTOP,
            text=GetByLabel('UI/Industry/JobRuns'))
        self.runsEdit = BlueprintSingleLineEdit(parent=self.runsCont,
                                                align=uiconst.CENTERTOP,
                                                pos=(0, 12, 62, 0),
                                                OnChange=self.OnRunsEdit,
                                                autoselect=True)
        self.runsPerCopyCont = ContainerAutoSize(name='runsPerCopyCont',
                                                 parent=self.runsCont,
                                                 align=uiconst.CENTERTOP,
                                                 top=38,
                                                 state=uiconst.UI_HIDDEN)
        IndustryCaptionLabel(name='runsPerCopyCaption',
                             parent=self.runsPerCopyCont,
                             align=uiconst.CENTERTOP,
                             text=GetByLabel('UI/Industry/RunsPerCopy'))
        self.runsPerCopyEdit = BlueprintSingleLineEdit(
            parent=self.runsPerCopyCont,
            align=uiconst.CENTERTOP,
            pos=(0, 12, 62, 0),
            OnChange=self.OnRunsPerCopyEdit,
            autoselect=True)
        self.gauge = None
        self.skillSprite = SkillIcon(parent=self,
                                     align=uiconst.CENTERBOTTOM,
                                     top=5,
                                     jobData=self.jobData)
        self.containerME = ContainerME(parent=self,
                                       align=uiconst.CENTER,
                                       pos=(113, -25, 71, 30),
                                       jobData=self.jobData,
                                       opacity=0.0)
        self.containerTE = ContainerTE(parent=self,
                                       align=uiconst.CENTER,
                                       pos=(113, 25, 71, 30),
                                       jobData=self.jobData,
                                       opacity=0.0)
        self.runsRemainingCont = ContainerAutoSize(name='bpCopyCont',
                                                   parent=self,
                                                   align=uiconst.CENTERTOP,
                                                   state=uiconst.UI_NORMAL,
                                                   top=90)
        self.runsRemainingCont.OnClick = self.OnRunsRemainingContClicked
        self.runsRemainingCaption = IndustryCaptionLabel(
            parent=self.runsRemainingCont, align=uiconst.CENTERTOP)
        self.runsRemainingLabel = EveLabelMediumBold(
            name='runsRemainingLabel',
            parent=self.runsRemainingCont,
            align=uiconst.CENTERTOP,
            top=14)
        self.UpdateState()
        self.AnimEntry()

    def OnRunsRemainingContClicked(self, *args):
        if self.runsEdit.state == uiconst.UI_NORMAL:
            self.runsEdit.SetValue(self.jobData.maxRuns)

    def OnBlueprintBrowserNumericInput(self, key, flag):
        if not self.numericInputTimer:
            self.runsEdit.SelectAll()
        else:
            self.numericInputTimer.kill()
        self.numericInputTimer = uthread.new(self.NumericInputTimer)
        self.runsEdit.OnChar(key, flag)

    def NumericInputTimer(self):
        blue.synchro.SleepWallclock(1000)
        self.numericInputTimer = None

    def OnJobUpdated(self, job):
        if self.jobData and self.jobData == job:
            self.UpdateStateJob()

    def UpdateStateJob(self):
        self.iconCont.Show()
        typeID = self.jobData.blueprint.blueprintTypeID
        self.iconCont.SetTypeID(typeID=typeID, bpData=self.jobData.blueprint)
        self.UpdateGaugeValue()
        self.UpdateStateRunsEdit()
        self.UpdateStateRunsPerCopyEdit()
        self.skillSprite.Show()
        self.UpdateRunsRemainingLabel()
        self.containerME.SetValue(self.jobData.blueprint.materialEfficiency)
        self.containerTE.SetValue(self.jobData.blueprint.timeEfficiency)
        self.jobData.on_updated.connect(self.OnJobUpdated)

    def UpdateRunsRemainingLabel(self):
        if not self.jobData:
            return
        if self.jobData.IsInstalled():
            self.runsRemainingCont.Hide()
        else:
            runsText = self.jobData.GetRunsRemainingLabel()
            if runsText:
                self.runsRemainingCont.Show()
                self.runsRemainingLabel.text = runsText
                self.runsRemainingCaption.text = self.jobData.GetRunsRemainingCaption(
                )
            else:
                self.runsRemainingCont.Hide()

    def SetNumRuns(self, numRuns):
        if not self.jobData.IsInstalled():
            self.runsEdit.SetValue(numRuns)

    def UpdateStateRunsEdit(self):
        if self.jobData.IsInstalled():
            self.runsEdit.IntMode(self.jobData.runs, self.jobData.runs)
            self.runsEdit.Show()
            self.runsCaption.Show()
            self.runsEdit.Disable()
        else:
            self.runsEdit.IntMode(1, self.jobData.maxRuns)
            self.runsEdit.Enable()
            self.runsEdit.Show()
            self.runsCaption.Show()
        self.runsEdit.SetValue(self.jobData.runs)

    def UpdateStateRunsPerCopyEdit(self):
        if self.jobData.activityID == industry.COPYING:
            if self.jobData.IsInstalled():
                self.runsPerCopyEdit.IntMode(self.jobData.licensedRuns,
                                             self.jobData.licensedRuns)
                self.runsPerCopyEdit.Disable()
            else:
                self.runsPerCopyEdit.IntMode(1, self.jobData.maxLicensedRuns)
                self.runsPerCopyEdit.Enable()
            self.runsPerCopyEdit.SetValue(self.jobData.licensedRuns)
            self.runsPerCopyCont.Show()
        else:
            self.runsPerCopyCont.Hide()

    def UpdateState(self):
        if self.jobData:
            self.UpdateStateJob()
        else:
            self.iconCont.Hide()
            self.runsEdit.Hide()
            self.runsPerCopyCont.Hide()
            self.runsCaption.Hide()
            self.skillSprite.Hide()
            self.runsRemainingCont.Hide()
            self.containerME.SetValue(0.0)
            self.containerTE.SetValue(0.0)

    def ReconstructGauge(self):
        if self.gauge:
            self.gauge.Close()
            self.gauge = None
        if not self.jobData:
            return
        color = GetJobColor(self.jobData)
        h, s, b = Color(*color).GetHSB()
        colorEnd = Color(*color).SetBrightness(b * 0.5).GetRGBA()
        self.gauge = BlueprintGaugeCircular(name='gauge',
                                            parent=self,
                                            align=uiconst.CENTER,
                                            radius=64,
                                            lineWidth=4,
                                            colorStart=color,
                                            colorEnd=colorEnd,
                                            jobData=self.jobData)

    def AnimWedges(self, startVal, endVal, duration, curveType=None):
        uicore.animations.MorphScalar(self.topWedge,
                                      'top',
                                      startVal,
                                      endVal,
                                      duration=duration,
                                      curveType=curveType)
        uicore.animations.MorphScalar(self.bottomWedge,
                                      'top',
                                      startVal,
                                      endVal,
                                      duration=duration,
                                      curveType=curveType)
        uicore.animations.MorphScalar(self.leftWedge,
                                      'left',
                                      startVal,
                                      endVal,
                                      duration=duration,
                                      curveType=curveType)
        uicore.animations.MorphScalar(self.rightWedge,
                                      'left',
                                      startVal,
                                      endVal,
                                      duration=duration,
                                      curveType=curveType)

    def AnimEntry(self):
        duration = 0.7
        if self.jobData:
            self.HideDashes()
            if self.topWedge.top < WEDGE_TRAVEL:
                self.AnimWedges(0, WEDGE_TRAVEL, duration)
            else:
                self.AnimWedges(WEDGE_TRAVEL,
                                18,
                                0.5,
                                curveType=uiconst.ANIM_WAVE)
            if not self.IsSameBlueprint():
                uicore.animations.FadeTo(self.iconCont, 0.0, 1.0, duration=0.5)
            for obj in (self.containerME, self.containerTE):
                obj.Enable()
                uicore.animations.FadeIn(obj, duration=duration)

        else:
            self.AnimWedges(self.topWedge.top, 0.0, duration)
            for obj in (self.containerME, self.containerTE):
                obj.Disable()
                uicore.animations.FadeOut(obj, duration=duration)

            self.ShowDashes()
        if self.jobData and self.jobData.IsPreview():
            uicore.animations.FadeTo(self.iconCont, 0.0, 0.65, duration=0.5)
            self.errorFrame.Show()
            wedgeColor = industryUIConst.COLOR_NOTREADY
        else:
            self.errorFrame.Hide()
            wedgeColor = Color.WHITE
        for dots in self.wedgeDots:
            dots.SetRGBA(*wedgeColor)

        if self.gauge:
            uicore.animations.BlinkIn(self.gauge, 0.0, 1.0, timeOffset=0.98)
        for dots in self.wedgeDots:
            uicore.animations.BlinkIn(dots, 0.0, 0.85, timeOffset=0.78)

        for pattern in self.wedgeBg:
            if self.jobData and self.jobData.IsPreview():
                color = industryUIConst.COLOR_NOTREADY
            else:
                color = GetJobColor(self.jobData)
            uicore.animations.SpColorMorphTo(pattern,
                                             pattern.GetRGBA(),
                                             color,
                                             duration=0.3)

    def IsSameBlueprint(self):
        if not self.oldJobData or not self.jobData:
            return False
        if self.jobData:
            return self.jobData.blueprint.IsSameBlueprint(
                self.oldJobData.blueprint)
        return False

    def UpdateGaugeValue(self):
        if not self.gauge or not self.jobData:
            return
        self.gauge.SetValue(self.jobData.GetGaugeValue())

    def SetJobRuns(self, value):
        if self.setJobRunsThread is None:
            self.setJobRunsThread = uthread.new(self._SetJobRuns)
        self.newNumRuns = value

    def _SetJobRuns(self):
        while self.jobData and self.newNumRuns is not None:
            if self.newNumRuns != self.jobData.runs:
                newNumRuns = self.newNumRuns
                self.newNumRuns = None
                self.jobData.runs = newNumRuns
                sm.GetService('audio').SendUIEvent('ind_runsChanged')
            blue.synchro.SleepWallclock(100)

        self.setJobRunsThread = None

    def OnRunsEdit(self, value):
        try:
            value = int(value)
        except ValueError:
            return

        if self.jobData and not self.jobData.IsInstalled():
            self.SetJobRuns(value)

    def OnRunsChanged(self):
        self.UpdateGaugeValue()
        self.UpdateRunsRemainingLabel()

    def OnRunsPerCopyEdit(self, value):
        try:
            value = int(value)
        except ValueError:
            return

        self.jobData.licensedRuns = value

    def ConstructBackground(self):
        Frame(name='bgFrame',
              parent=self,
              align=uiconst.CENTER,
              state=uiconst.UI_DISABLED,
              width=75,
              height=75,
              opacity=0.1)
        blueprintBg = FrameThemeColored(
            name='blueprintBgFill',
            parent=self,
            align=uiconst.CENTER,
            state=uiconst.UI_DISABLED,
            texturePath='res:/UI/Texture/classes/Industry/Center/bgFrame.png',
            width=90,
            height=90)
        self.dashesCont = Container(name='dashesCont',
                                    parent=self,
                                    state=uiconst.UI_DISABLED,
                                    pos=(75, 0, 150, 150),
                                    align=uiconst.CENTER)
        self.bgCont = Container(name='bgCont',
                                parent=self,
                                state=uiconst.UI_DISABLED,
                                width=150,
                                height=150,
                                align=uiconst.CENTER)
        self.topWedge = Container(name='topWedge',
                                  parent=self.bgCont,
                                  align=uiconst.CENTERTOP,
                                  pos=(0, 0, 84, 60))
        topLines = Sprite(
            bgParent=self.topWedge,
            texturePath=
            'res:/UI/Texture/classes/Industry/Center/wedgeTopBottom.png')
        topDots = Sprite(
            bgParent=self.topWedge,
            texturePath=
            'res:/UI/Texture/classes/Industry/Center/dotsTopBottom.png')
        topBg = Sprite(
            bgParent=self.topWedge,
            texturePath='res:/UI/Texture/classes/Industry/Center/bgTop.png',
            color=COLOR_FRAME)
        self.bottomWedge = Container(name='bottomWedge',
                                     parent=self.bgCont,
                                     align=uiconst.CENTERBOTTOM,
                                     pos=(0, 0, 84, 60))
        bottomLines = Sprite(
            bgParent=self.bottomWedge,
            texturePath=
            'res:/UI/Texture/classes/Industry/Center/wedgeTopBottom.png',
            rotation=pi)
        bottomDots = Sprite(
            bgParent=self.bottomWedge,
            texturePath=
            'res:/UI/Texture/classes/Industry/Center/dotsTopBottom.png',
            rotation=pi)
        bottomBg = Sprite(
            bgParent=self.bottomWedge,
            texturePath='res:/UI/Texture/classes/Industry/Center/bgBottom.png',
            color=COLOR_FRAME)
        self.leftWedge = Container(name='leftWedge',
                                   parent=self.bgCont,
                                   align=uiconst.CENTERLEFT,
                                   pos=(0, 0, 60, 84))
        leftLines = Sprite(
            bgParent=self.leftWedge,
            texturePath=
            'res:/UI/Texture/classes/Industry/Center/wedgeLeftRight.png')
        leftDots = Sprite(
            bgParent=self.leftWedge,
            texturePath=
            'res:/UI/Texture/classes/Industry/Center/dotsLeftRight.png')
        leftBg = Sprite(
            bgParent=self.leftWedge,
            texturePath='res:/UI/Texture/classes/Industry/Center/bgLeft.png',
            color=COLOR_FRAME)
        self.rightWedge = Container(name='rightWedge',
                                    parent=self.bgCont,
                                    align=uiconst.CENTERRIGHT,
                                    pos=(0, 0, 60, 84))
        rightLines = Sprite(
            bgParent=self.rightWedge,
            texturePath=
            'res:/UI/Texture/classes/Industry/Center/wedgeLeftRight.png',
            rotation=pi)
        rightDots = Sprite(
            bgParent=self.rightWedge,
            texturePath=
            'res:/UI/Texture/classes/Industry/Center/dotsLeftRight.png',
            rotation=pi)
        rightBg = Sprite(
            bgParent=self.rightWedge,
            texturePath='res:/UI/Texture/classes/Industry/Center/bgRight.png',
            color=COLOR_FRAME)
        self.wedgeLines = [topLines, bottomLines, leftLines, rightLines]
        self.wedgeDots = [topDots, bottomDots, leftDots, rightDots]
        self.wedgeBg = [topBg, bottomBg, leftBg, rightBg]

    def ShowDashes(self):
        for rotation in (0, pi / 2, pi, 3 * pi / 2):
            BlueDash(parent=self.dashesCont,
                     align=uiconst.CENTERLEFT,
                     rotation=pi / 4 + rotation,
                     rotationCenter=(0.0, 0.5))

    def HideDashes(self):
        self.dashesCont.Flush()

    def OnNewJobData(self, jobData):
        self.oldJobData = self.jobData
        self.jobData = jobData
        self.skillSprite.OnNewJobData(jobData)
        self.containerME.OnNewJobData(jobData)
        self.containerTE.OnNewJobData(jobData)
        self.ReconstructGauge()
        if self.gauge:
            self.gauge.OnNewJobData(jobData)
        self.UpdateState()
        self.AnimEntry()
        self.numericInputTimer = None

    def OnIndustryWndMouseWheel(self, *args):
        if not self.jobData:
            return
        self.runsEdit.OnMouseWheel()
        if uicore.registry.GetFocus() != self.runsEdit:
            uicore.registry.SetFocus(self.runsEdit)

    def OnIndustryWndClick(self):
        if not self.jobData:
            return
        uicore.registry.SetFocus(self.runsEdit)
Пример #2
0
    def LoadTypeRequirements(self, typeID):
        if self.typeID is not None:
            self.Flush()
        self.typeID = typeID
        if typeID is None:
            return
        invType = cfg.invtypes.Get(typeID)
        isSkill = invType.categoryID == invconst.categorySkill
        haveSkill = sm.GetService('skills').GetMySkillsFromTypeID(
            typeID) is not None
        requiredSkills = sm.GetService(
            'clientDogmaStaticSvc').GetRequiredSkills(typeID)
        if isSkill and haveSkill:
            SkillLevels(parent=self,
                        align=uiconst.NOALIGN,
                        typeID=typeID,
                        groupID=invType.groupID)
        elif requiredSkills:
            texturePath, hint = sm.GetService(
                'skills').GetRequiredSkillsLevelTexturePathAndHint(
                    requiredSkills.items(), typeID=typeID)
            skillIcon = Sprite(name='skillIcon',
                               parent=self,
                               align=uiconst.NOALIGN,
                               width=ICON_SIZE,
                               height=ICON_SIZE,
                               texturePath=texturePath,
                               hint=hint,
                               useSizeFromTexture=False)
            skillSvc = sm.GetService('skills')
            if any((skillSvc.IsTrialRestricted(typeID)
                    for typeID in requiredSkills.keys())):

                def OpenSubscriptionPage():
                    reasonCategory = {
                        invconst.categoryShip: 'ship',
                        invconst.categorySkill: 'skill'
                    }.get(types.GetCategoryID(typeID), 'item')
                    reason = ':'.join([reasonCategory, str(typeID)])
                    uicore.cmd.OpenSubscriptionPage(origin=ORIGIN_MARKET,
                                                    reason=reason)

                skillIcon.OnClick = OpenSubscriptionPage
            else:

                def OpenRequirementsInfoTab():
                    info = sm.GetService('info')
                    info.ShowInfo(typeID,
                                  selectTabType=infoConst.TAB_REQUIREMENTS)

                skillIcon.OnClick = OpenRequirementsInfoTab
        isModule = invType.categoryID == invconst.categoryModule
        if isModule:
            godma = sm.GetService('godma')
            dogmaLocation = sm.GetService('clientDogmaIM').GetDogmaLocation()
            shipID = GetActiveShip()
            powerContainer = ContainerAutoSize(parent=self,
                                               align=uiconst.NOALIGN)
            modulePowerLoad = godma.GetTypeAttribute(typeID,
                                                     dconst.attributePower, 0)
            powerOutput = dogmaLocation.GetAttributeValue(
                shipID,
                dconst.attributePowerOutput) - dogmaLocation.GetAttributeValue(
                    shipID, dconst.attributePowerLoad)
            havePower = shipID is not None and powerOutput > modulePowerLoad
            icon = [
                'res:/UI/Texture/classes/Market/powerRequirementNotMet.png',
                'res:/UI/Texture/classes/Market/powerRequirementMet.png'
            ][havePower]
            hint = [
                'UI/Market/Marketbase/PowerRequirementNotMet',
                'UI/Market/Marketbase/PowerRequirementMet'
            ][havePower]
            powerIcon = Sprite(parent=powerContainer,
                               align=uiconst.CENTERTOP,
                               texturePath=icon,
                               width=ICON_SIZE,
                               height=ICON_SIZE,
                               ignoreSize=True,
                               hint=localization.GetByLabel(hint))
            powerLabel = EveLabelSmallBold(parent=powerContainer,
                                           align=uiconst.CENTERTOP,
                                           top=ICON_SIZE + 2,
                                           text=int(modulePowerLoad))
            cpuContainer = ContainerAutoSize(parent=self,
                                             align=uiconst.NOALIGN)
            moduleCpuLoad = godma.GetTypeAttribute(typeID, dconst.attributeCpu,
                                                   0)
            cpuOutput = dogmaLocation.GetAttributeValue(
                shipID,
                dconst.attributeCpuOutput) - dogmaLocation.GetAttributeValue(
                    shipID, dconst.attributeCpuLoad)
            haveCpu = shipID is not None and cpuOutput > moduleCpuLoad
            icon = [
                'res:/UI/Texture/classes/Market/cpuRequirementNotMet.png',
                'res:/UI/Texture/classes/Market/cpuRequirementMet.png'
            ][haveCpu]
            hint = [
                'UI/Market/Marketbase/CpuRequirementNotMet',
                'UI/Market/Marketbase/CpuRequirementMet'
            ][haveCpu]
            cpuIcon = Sprite(parent=cpuContainer,
                             align=uiconst.CENTERTOP,
                             texturePath=icon,
                             ignoreSize=True,
                             width=ICON_SIZE,
                             height=ICON_SIZE,
                             hint=localization.GetByLabel(hint))
            cpuLabel = EveLabelSmallBold(parent=cpuContainer,
                                         align=uiconst.CENTERTOP,
                                         top=ICON_SIZE + 2,
                                         text=int(moduleCpuLoad))
Пример #3
0
 def Layout(self):
     self.HideHeader()
     self.MakeUnResizeable()
     self.container = ContainerAutoSize(parent=self.GetMainArea(),
                                        align=uiconst.TOTOP,
                                        alignMode=uiconst.TOTOP,
                                        state=uiconst.UI_PICKCHILDREN,
                                        padding=(15, 15, 15, 0),
                                        callback=self.OnContainerResized)
     EveLabelLargeBold(parent=self.container,
                       align=uiconst.TOTOP,
                       text=localization.GetByLabel(
                           'UI/ActivateMultiTraining/ActivateHeading'))
     EveLabelMedium(parent=self.container,
                    align=uiconst.TOTOP,
                    text=localization.GetByLabel(
                        'UI/ActivateMultiTraining/ActivateDescription'),
                    color=self.GRAY_COLOR,
                    padding=(0, 5, 0, 10))
     Line(parent=self.container, align=uiconst.TOTOP, color=self.LINE_COLOR)
     slot1 = ContainerAutoSize(parent=self.container,
                               align=uiconst.TOTOP,
                               alignMode=uiconst.TOTOP,
                               state=uiconst.UI_PICKCHILDREN,
                               bgColor=(0, 0, 0, 0.3))
     self.slot1Background = Fill(parent=slot1,
                                 color=self.GREEN_COLOR,
                                 opacity=0.0)
     self.slot1Title = EveLabelMediumBold(parent=slot1,
                                          align=uiconst.TOTOP,
                                          text='',
                                          padding=(60, 12, 140, 0),
                                          color=self.WHITE_COLOR)
     self.slot1Expiry = EveLabelMediumBold(parent=slot1,
                                           align=uiconst.TOTOP,
                                           text='',
                                           padding=(60, 0, 140, 10),
                                           color=self.GRAY_COLOR)
     self.slot1Button = Button(parent=slot1,
                               label='',
                               align=uiconst.CENTERRIGHT,
                               fontsize=13,
                               fixedwidth=120,
                               fixedheight=30,
                               pos=(10, 0, 0, 0))
     self.slot1Button.confirmHilite = GradientSprite(
         bgParent=self.slot1Button,
         rotation=-math.pi / 2,
         rgbData=[(0, self.GREEN_COLOR[:3])],
         alphaData=[(0, 0.5), (0.3, 0.2), (0.6, 0.14)],
         opacity=0.0)
     self.slot1Icon = Sprite(
         parent=slot1,
         texturePath='res:/UI/Texture/Icons/add_training_queue.png',
         align=uiconst.CENTERLEFT,
         pos=(15, 0, 32, 32))
     Line(parent=self.container, align=uiconst.TOTOP, color=self.LINE_COLOR)
     slot2 = ContainerAutoSize(parent=self.container,
                               align=uiconst.TOTOP,
                               alignMode=uiconst.TOTOP,
                               state=uiconst.UI_PICKCHILDREN,
                               bgColor=(0, 0, 0, 0.3))
     self.slot2Background = Fill(parent=slot2,
                                 color=self.GREEN_COLOR,
                                 opacity=0.0)
     self.slot2Title = EveLabelMediumBold(parent=slot2,
                                          align=uiconst.TOTOP,
                                          text='',
                                          padding=(60, 12, 140, 0),
                                          color=self.WHITE_COLOR)
     self.slot2Expiry = EveLabelMediumBold(parent=slot2,
                                           align=uiconst.TOTOP,
                                           text='',
                                           padding=(60, 0, 140, 10),
                                           color=self.GRAY_COLOR)
     self.slot2Button = Button(parent=slot2,
                               label='',
                               align=uiconst.CENTERRIGHT,
                               fontsize=13,
                               fixedwidth=120,
                               fixedheight=30,
                               pos=(10, 0, 0, 0))
     self.slot2Button.confirmHilite = GradientSprite(
         bgParent=self.slot2Button,
         rotation=-math.pi / 2,
         rgbData=[(0, self.GREEN_COLOR[:3])],
         alphaData=[(0, 0.5), (0.3, 0.2), (0.6, 0.14)],
         opacity=0.0)
     self.slot2Icon = Sprite(
         parent=slot2,
         texturePath='res:/UI/Texture/Icons/add_training_queue.png',
         align=uiconst.CENTERLEFT,
         pos=(15, 0, 32, 32))
     Line(parent=self.container, align=uiconst.TOTOP, color=self.LINE_COLOR)
     self.closeButton = Button(
         parent=self.container,
         label=localization.GetByLabel('UI/Generic/Cancel'),
         func=self.Close,
         align=uiconst.TOTOP,
         fontsize=13,
         padding=(120, 10, 120, 30))
Пример #4
0
class InfoPanelChallenges(InfoPanelBase):
    __guid__ = 'uicls.InfoPanelChallenges'
    default_name = 'InfoPanelChallenges'
    default_iconTexturePath = CHALLENGES_PANEL_ICON
    default_state = uiconst.UI_PICKCHILDREN
    default_height = 120
    label = CHALLENGES_PANEL_LABEL
    hasSettings = False
    panelTypeID = PANEL_CHALLENGES
    challengeContainer = None
    __notifyevents__ = [
        'OnChallengeProgressUpdateInClient', 'OnChallengeCompletedInClient',
        'OnChallengeExpiredInClient'
    ]

    def ApplyAttributes(self, attributes):
        self.seasonService = sm.GetService('seasonService')
        self._LoadActiveChallenge()
        self.challengeContainer = None
        self.challengeTaskEntry = None
        self.openChallengesLinkGrid = None
        InfoPanelBase.ApplyAttributes(self, attributes)
        self.titleLabel = self.headerCls(name='title',
                                         text='<color=white>%s</color>' %
                                         GetByLabel(self.label),
                                         parent=self.headerCont,
                                         align=uiconst.CENTERLEFT,
                                         state=uiconst.UI_DISABLED)
        self._ConstructPanel()

    def _LoadActiveChallenge(self):
        try:
            challengeID = self.seasonService.get_last_active_challenge()
            self.challenge = self._GetChallenge(challengeID)
        except ChallengeForCharacterNotFoundError:
            self.challenge = None

    @staticmethod
    def IsAvailable():
        return sm.GetService('seasonService').is_season_active()

    def _IsCollapsed(self):
        return sm.GetService('infoPanel').GetModeForPanel(
            PANEL_CHALLENGES) == MODE_COLLAPSED

    def _ShouldShowChallengeDetails(self):
        return not self._IsCollapsed() and settings.char.ui.Get(
            'show_challenge_details_in_info_panel', True)

    def _ConstructChallengeContainer(self):
        if not self.challengeContainer or self.challengeContainer.destroyed:
            self.mainCont.Flush()
            if self.challenge is None:
                self.challengeContainer = None
            else:
                self.challengeContainer = ContainerAutoSize(
                    parent=self.mainCont,
                    name='challengeContainer',
                    align=uiconst.TOTOP)
        if self.challengeContainer:
            self.challengeContainer.Flush()

    def _ConstructChallengeDetails(self):
        if self.challenge is None:
            self.challengeTaskEntry = None
            return
        self.challengeTaskEntry = ChallengeInfoPanelTaskEntry(
            name='challengeInfoPanelTaskEntry',
            parent=self.challengeContainer,
            align=uiconst.TOTOP,
            challenge=self.challenge,
            open_challenges_function=self._OpenChallenges,
            show_details=self._ShouldShowChallengeDetails())

    def _GetChallenge(self, challengeID):
        return self.seasonService.get_challenge(challengeID)

    def _OpenChallenges(self, *args):
        SeasonWindow.Open()

    def OnChallengeProgressUpdateInClient(self, challengeID, newProgress):
        self.hideChallengeTimerThread = None
        if not self._IsChallengeAlreadyShown(challengeID):
            self.challenge = self._GetChallenge(challengeID)
            self._ConstructPanel()
        self.challengeTaskEntry.update_challenge_progress(newProgress)

    def OnChallengeCompletedInClient(self, oldChallengeID):
        if oldChallengeID is None:
            return
        if not self._IsChallengeAlreadyShown(oldChallengeID):
            self.challenge = self.seasonService.get_challenge(oldChallengeID)
            self._ConstructPanel()
        self.challengeTaskEntry.complete_challenge()
        setattr(
            self, 'hideChallengeTimerThread',
            AutoTimer(HIDE_CHALLENGE_TIMEOUT, self._HideCompletedChallenge))

    def OnChallengeExpiredInClient(self, challengeID):
        if challengeID is None:
            return
        if not self._IsChallengeAlreadyShown(challengeID):
            self.challenge = self.seasonService.get_challenge(challengeID)
            self._ConstructPanel()
        self.challengeTaskEntry.expire_challenge()
        setattr(
            self, 'hideChallengeTimerThread',
            AutoTimer(HIDE_CHALLENGE_TIMEOUT, self._HideCompletedChallenge))

    def _IsAnyChallengeShown(self):
        return self.challenge is not None

    def _IsChallengeAlreadyShown(self, challengeID):
        return self._IsAnyChallengeShown(
        ) and self.challenge.challenge_id == challengeID

    def _HideCompletedChallenge(self):
        try:
            if self.hideChallengeTimerThread:
                uicore.animations.FadeOut(
                    self.challengeTaskEntry,
                    duration=COMPLETED_CHALLENGE_FADE_OUT_DURATION,
                    callback=self._ResetPanel())
        finally:
            self.hideChallengeTimerThread = None

        self._ResetPanel()

    def _ConstructPanel(self):
        self._ConstructChallengeContainer()
        self._ConstructChallengeDetails()

    def _ResetPanel(self):
        self.challengeContainer = None
        self._LoadActiveChallenge()
        self._ConstructPanel()
Пример #5
0
 def ApplyAttributes(self, attributes):
     self.onClick = attributes.get('onClick', None)
     color = attributes.pop('color', self.default_color)
     contentSpacing = attributes.pop('contentSpacing',
                                     self.default_contentSpacing)
     iconSize = attributes.pop('iconSize', self.default_iconSize)
     labelClass = attributes.pop('labelClass', self.default_labelClass)
     labelColor = attributes.pop('labelColor', self.default_labelColor)
     labelShadow = attributes.pop('labelShadow', self.default_labelShadow)
     labelShadowColor = attributes.pop('labelShadowColor',
                                       self.default_labelShadowColor)
     labelTop = attributes.pop('labelTop', self.default_labelTop)
     padding = attributes.pop('padding', self.default_padding)
     text = attributes.pop('text', self.default_text)
     texturePath = attributes.pop('texturePath', self.default_texturePath)
     iconWidth, iconHeight = iconSize
     padLeft, padTop, padRight, padBottom = padding
     super(ButtonCore, self).ApplyAttributes(attributes)
     Fill(bgParent=self,
          align=uiconst.TOALL,
          padding=(1, 1, 1, 1),
          color=color)
     GradientSprite(bgParent=self,
                    align=uiconst.TOALL,
                    rgbData=((0.0, (0.9, 0.9, 0.9)), (0.5, (0.2, 0.2, 0.2)),
                             (1.0, (0.9, 0.9, 0.9))),
                    alphaData=((0.0, 0.3), (1.0, 0.3)),
                    rotation=-math.pi / 4)
     Fill(bgParent=self, align=uiconst.TOALL, color=color)
     if texturePath:
         iconCont = Container(parent=self,
                              align=uiconst.TOPLEFT,
                              padding=(padLeft, padTop,
                                       contentSpacing if text else padRight,
                                       padBottom),
                              height=iconHeight,
                              width=iconWidth)
         Sprite(parent=iconCont,
                align=uiconst.TOPLEFT,
                state=uiconst.UI_DISABLED,
                texturePath=texturePath,
                height=iconHeight,
                width=iconWidth)
     if text:
         if texturePath:
             left = padLeft + iconWidth
             labelPadding = (contentSpacing, padTop, padRight, padBottom)
             top = labelTop
         else:
             left = 0
             labelPadding = padding
             top = 0
         labelCont = ContainerAutoSize(parent=self,
                                       align=uiconst.TOPLEFT,
                                       alignMode=uiconst.TOPLEFT,
                                       left=left,
                                       top=top)
         labelClass(parent=labelCont,
                    align=uiconst.TOPLEFT,
                    padding=labelPadding,
                    text=text,
                    color=labelColor)
         if labelShadow:
             shadow = labelClass(parent=labelCont,
                                 align=uiconst.TOPLEFT,
                                 padding=labelPadding,
                                 text=text,
                                 color=labelShadowColor)
             shadow.renderObject.spriteEffect = trinity.TR2_SFX_BLUR
             Frame(parent=labelCont,
                   align=uiconst.TOALL,
                   texturePath='res:/UI/Texture/Vgs/radialShadow.png',
                   cornerSize=8,
                   color=labelShadowColor,
                   opacity=labelShadowColor[3] * 0.5)
     self.SetSizeAutomatically()
Пример #6
0
 def ApplyAttributes(self, attributes):
     PointerContainer.ApplyAttributes(self, attributes)
     self.data = attributes.data
     self.callback = attributes.callback
     self.minDisplayTime = attributes.Get('minDisplayTime',
                                          self.default_minDisplayTime)
     self.outsideBoundsTime = attributes.Get('outsideBoundsTime',
                                             self.default_outsideBoundsTime)
     self.updateLoopTimeMSec = attributes.Get(
         'updateLoopTimeMSec', self.default_updateLoopTimeMSec)
     self._updateThread = None
     self.michelle = sm.GetService('michelle')
     self.sensorSuite = sm.GetService('sensorSuite')
     self.topContainer = Container(parent=self,
                                   height=20,
                                   align=uiconst.TOTOP)
     self.bottomContainer = Container(parent=self, align=uiconst.TOALL)
     self.contentContainer = Container(parent=self.bottomContainer,
                                       align=uiconst.TOALL,
                                       padLeft=16)
     Fill(bgParent=self.bottomContainer, color=(0, 0, 0, 0.4))
     Line(parent=self.bottomContainer, align=uiconst.TOBOTTOM)
     leftPadContainer = Container(parent=self.topContainer,
                                  align=uiconst.TOLEFT,
                                  width=12)
     Line(parent=leftPadContainer, align=uiconst.TORIGHT)
     Line(parent=leftPadContainer, align=uiconst.TOBOTTOM)
     textContainer = Container(parent=self.topContainer,
                               align=uiconst.TOLEFT,
                               width=150)
     Fill(bgParent=textContainer, color=(0, 0, 0, 0.5))
     Line(parent=textContainer, align=uiconst.TOTOP)
     Line(parent=textContainer, align=uiconst.TORIGHT)
     self.captionLabel = EveLabelMediumBold(parent=textContainer,
                                            text=self.GetCaptionText(),
                                            align=uiconst.CENTER)
     textContainer.width = self.captionLabel.textwidth + 16
     rightPadContainer = Container(parent=self.topContainer,
                                   align=uiconst.TOALL)
     Line(parent=rightPadContainer, align=uiconst.TOBOTTOM)
     self.iconCont = Container(parent=self.contentContainer,
                               pos=(8, 8, 32, 32),
                               state=uiconst.UI_DISABLED,
                               align=uiconst.TOPRIGHT)
     if self.default_iconTexturePath:
         self.CreateIconSpite()
         self.ownerIcon.SetTexturePath(self.default_iconTexturePath)
         self.ownerIcon.state = uiconst.UI_DISABLED
     topTextCont = ContainerAutoSize(top=8,
                                     name='topTextCont',
                                     parent=self.contentContainer,
                                     align=uiconst.TOTOP)
     self.mainLabel = EveCaptionMedium(name='mainLabel',
                                       parent=topTextCont,
                                       color=(0.235, 0.745, 0.765),
                                       text='',
                                       align=uiconst.TOTOP,
                                       singleline=True)
     self.mainLabel.SetRightAlphaFade(fadeEnd=250, maxFadeWidth=30)
     self.subLabel = EveLabelMediumBold(name='subLabel',
                                        parent=topTextCont,
                                        align=uiconst.TOTOP,
                                        text='',
                                        singleline=True)
     self.subLabel.SetRightAlphaFade(fadeEnd=250, maxFadeWidth=30)
     bottomTextCont = ContainerAutoSize(top=2,
                                        name='bottomTextCont',
                                        parent=self.contentContainer,
                                        align=uiconst.TOBOTTOM)
     self.dataLabel = EveLabelMediumBold(name='dataLabel',
                                         parent=bottomTextCont,
                                         align=uiconst.TOBOTTOM,
                                         text='')
     self.rangeLabel = EveLabelMediumBold(name='rangeLabel',
                                          parent=bottomTextCont,
                                          align=uiconst.TOBOTTOM,
                                          text='')
     self.buttonContainer = Container(parent=self.contentContainer,
                                      align=uiconst.BOTTOMRIGHT,
                                      heigh=32)
     GradientSprite(parent=self.bottomContainer,
                    align=uiconst.TOALL,
                    rotation=-pi / 2,
                    rgbData=[(0, (0.25, 0.25, 0.25)),
                             (0.3, (0.0, 0.0, 0.0))],
                    alphaData=[(0, 0.5)],
                    state=uiconst.UI_DISABLED)
     self.warpButton = Button(
         parent=self.contentContainer,
         top=8,
         left=88,
         icon='res:/UI/Texture/Icons/44_32_18.png',
         func=self.WarpToAction,
         hint=localization.GetByLabel('UI/Commands/WarpTo'),
         align=uiconst.BOTTOMRIGHT)
     self.bookmarkButton = Button(
         parent=self.contentContainer,
         top=8,
         left=48,
         icon='res:/UI/Texture/Icons/bookmark.png',
         func=self.BookmarkSite,
         hint=localization.GetByLabel('UI/Inflight/BookmarkLocation'),
         align=uiconst.BOTTOMRIGHT)
     self.probeScannerButton = Button(
         parent=self.contentContainer,
         top=8,
         left=4,
         icon='res:/UI/Texture/Icons/probe_scan.png',
         func=OpenProbeScanner,
         hint=localization.GetByLabel(
             'UI/Inflight/Scanner/SensorOverlayProbeScanButtonHint'),
         align=uiconst.BOTTOMRIGHT)
     uicore.event.RegisterForTriuiEvents(uiconst.UI_MOUSEDOWN,
                                         self.OnGlobalMouseDown)
     self._updateThread = uthread.new(self.UpdateHint)
Пример #7
0
 def Layout(self):
     """
     Setup UI controls for this window.
     """
     self.HideHeader()
     self.MakeUnResizeable()
     self.container = ContainerAutoSize(parent=self.GetMainArea(),
                                        align=uiconst.TOTOP,
                                        alignMode=uiconst.TOTOP,
                                        state=uiconst.UI_PICKCHILDREN,
                                        callback=self.OnContainerResized)
     headerCont = ContainerAutoSize(parent=self.container,
                                    align=uiconst.TOTOP)
     EveCaptionMedium(parent=headerCont,
                      align=uiconst.CENTERTOP,
                      text=localization.GetByLabel('UI/TrialUpsell/Header'),
                      padding=(0, 8, 0, 4))
     LineThemeColored(parent=self.container,
                      align=uiconst.TOTOP,
                      padding=(2, 0, 2, 0))
     bodyCont = ContainerAutoSize(parent=self.container,
                                  align=uiconst.TOTOP,
                                  alignMode=uiconst.TOTOP)
     mainCont = ContainerAutoSize(parent=bodyCont,
                                  align=uiconst.TOTOP,
                                  alignMode=uiconst.TOTOP)
     GradientSprite(bgParent=bodyCont,
                    rgbData=[(0, (0.138, 0.138, 0.08)),
                             (0.6, (0.06, 0.06, 0.06)),
                             (1.0, (0.1, 0.1, 0.1))],
                    alphaData=[(0.0, 0.8), (1.0, 0.2)],
                    alphaInterp=GradientConst.INTERP_LINEAR,
                    colorInterp=GradientConst.INTERP_LINEAR,
                    rotation=-math.pi / 2,
                    padding=(2, 0, 2, 2))
     EveLabelLarge(parent=mainCont,
                   align=uiconst.TOTOP,
                   text=localization.GetByLabel('UI/TrialUpsell/Greeting'),
                   padding=(160, 18, 20, 8))
     EveLabelLarge(parent=mainCont,
                   align=uiconst.TOTOP,
                   text=self.message
                   or localization.GetByLabel('UI/TrialUpsell/DefaultBody'),
                   padding=(160, 0, 20, 8))
     EveLabelLarge(parent=mainCont,
                   align=uiconst.TOTOP,
                   text=localization.GetByLabel('UI/TrialUpsell/Footer'),
                   padding=(160, 0, 20, 16))
     trialDays = sm.RemoteSvc('userSvc').GetTrialDaysRemaining()
     EveLabelLarge(parent=mainCont,
                   align=uiconst.TOTOP,
                   text=localization.GetByLabel(
                       'UI/TrialUpsell/TrialTimeLeft',
                       daysLeft=trialDays.daysLeft,
                       daysTotal=trialDays.trialLen),
                   color=(0.8, 0.6, 0.2, 0.8),
                   padding=(160, 0, 20, 8))
     self.iconGlow = Sprite(
         parent=mainCont,
         align=uiconst.CENTERLEFT,
         state=uiconst.UI_DISABLED,
         texturePath=
         'res:/UI/Texture/classes/Monetization/Trial_Icon_Glow_256.png',
         left=-20,
         width=200,
         height=200)
     Sprite(
         parent=mainCont,
         align=uiconst.CENTERLEFT,
         state=uiconst.UI_DISABLED,
         texturePath=
         'res:/UI/Texture/classes/Monetization/Trial_Icon_NoGlow_256.png',
         left=-20,
         width=200,
         height=200)
     self.iconGlare1 = Sprite(
         parent=mainCont,
         align=uiconst.CENTERLEFT,
         state=uiconst.UI_DISABLED,
         texturePath='res:/UI/Texture/classes/Monetization/glare_256_1.png',
         textureSecondaryPath=
         'res:/UI/Texture/classes/Monetization/Trial_Icon_NoGlow_256.png',
         spriteEffect=trinity.TR2_SFX_MODULATE,
         blendMode=trinity.TR2_SBM_ADDX2,
         left=-20,
         width=200,
         height=200,
         tileX=True,
         tileY=True)
     self.iconGlare2 = Sprite(
         parent=mainCont,
         align=uiconst.CENTERLEFT,
         state=uiconst.UI_DISABLED,
         texturePath='res:/UI/Texture/classes/Monetization/glare_256_2.png',
         textureSecondaryPath=
         'res:/UI/Texture/classes/Monetization/Trial_Icon_NoGlow_256.png',
         spriteEffect=trinity.TR2_SFX_MODULATE,
         left=-20,
         width=200,
         height=200,
         tileX=True,
         tileY=True)
     buttonCont = FlowContainer(parent=bodyCont,
                                align=uiconst.TOTOP,
                                centerContent=True,
                                contentSpacing=(4, 4),
                                padding=(8, 16, 8, 16))
     closeButton = Button(
         parent=buttonCont,
         align=uiconst.NOALIGN,
         fixedheight=26,
         label=localization.GetByLabel('UI/TrialUpsell/ButtonClose'),
         fontsize=12,
         func=lambda _: self.Close(),
         color=(0.2, 0.2, 0.2, 1.0))
     closeButton.sr.activeframe.SetFixedColor((0.6, 0.6, 0.6, 1.0))
     moreButton = Button(
         parent=buttonCont,
         align=uiconst.NOALIGN,
         fixedheight=26,
         label=localization.GetByLabel('UI/TrialUpsell/ButtonSubscribe'),
         fontsize=14,
         func=lambda _: self.OpenSubscriptionPage(),
         color=(0.8, 0.6, 0.2, 0.6))
     moreButton.sr.activeframe.SetFixedColor((0.9, 0.9, 0.9, 1.0))
     self.Animate()
Пример #8
0
class SkillExtractorWindow(Window):
    __guid__ = 'form.SkillExtractorWindow'
    __notifyevents__ = ['OnSessionChanged']
    default_width = 350
    default_height = 500
    default_minSize = (default_width, default_height)
    default_windowID = 'SkillExtractorWindow'
    default_captionLabelPath = 'UI/SkillTrading/SkillExtractorWindowCaption'
    default_iconNum = 'res:/UI/Texture/WindowIcons/augmentations.png'
    default_topParentHeight = 0
    default_clipChildren = True
    default_isCollapseable = False
    default_isPinable = False
    default_isStackable = False

    @classmethod
    def OpenOrReload(cls, *args, **kwargs):
        if cls.IsOpen():
            wnd = cls.GetIfOpen()
            if wnd.controller.isCompleted:
                wnd.Close()
                wnd = cls.Open(*args, **kwargs)
            else:
                wnd.controller.itemID = kwargs.get('itemID')
                wnd.Maximize()
        else:
            cls.Open(*args, **kwargs)

    def ApplyAttributes(self, attributes):
        super(SkillExtractorWindow, self).ApplyAttributes(attributes)
        self.controller = SkillExtractorController(attributes.itemID)
        self.filterSettings = SkillFilterSettings()
        self.Layout()
        self.Reload()
        self.filterSettings.onUpdate.connect(self.UpdateNoContentMessage)
        self.controller.onUpdate.connect(self.OnUpdate)
        self.controller.onSkillListUpdate.connect(self.Reload)
        sm.GetService('audio').SendUIEvent('st_activate_skill_extractor_play')

    def Layout(self):
        self.HideHeader()
        self.contentCont = Container(parent=self.GetMainArea(),
                                     align=uiconst.TOALL)
        topCont = Container(parent=self.contentCont,
                            align=uiconst.TOTOP,
                            height=90,
                            top=10)
        SkillExtractorBar(parent=topCont,
                          align=uiconst.CENTER,
                          state=uiconst.UI_NORMAL,
                          width=250,
                          controller=self.controller)
        middleCont = Container(parent=self.contentCont,
                               align=uiconst.TOALL,
                               padding=(8, 0, 8, 8))
        self.filterCont = Container(parent=middleCont,
                                    align=uiconst.TOTOP,
                                    height=26,
                                    opacity=0.0)
        SkillFilterMenu(
            parent=self.filterCont,
            align=uiconst.CENTERRIGHT,
            settings=self.filterSettings,
            hint=localization.GetByLabel('UI/SkillTrading/FilterSettings'))
        SkillFilterEdit(parent=self.filterCont,
                        align=uiconst.CENTERRIGHT,
                        left=20,
                        filterSettings=self.filterSettings)
        self.skillScroll = ScrollContainer(parent=middleCont,
                                           align=uiconst.TOALL,
                                           showUnderlay=True,
                                           opacity=0.0)
        self.loadingPanel = Container(parent=middleCont,
                                      align=uiconst.CENTER,
                                      state=uiconst.UI_DISABLED,
                                      width=250,
                                      height=150)
        LoadingWheel(parent=self.loadingPanel, align=uiconst.CENTERTOP)
        text = localization.GetByLabel('UI/SkillTrading/LoadingSkills')
        EveHeaderMedium(parent=self.loadingPanel,
                        align=uiconst.TOTOP,
                        top=50,
                        text='<center>%s</center>' % text)
        self.messagePanel = ContainerAutoSize(parent=self.GetMainArea(),
                                              align=uiconst.CENTER,
                                              alignMode=uiconst.TOTOP,
                                              width=300,
                                              opacity=0.0,
                                              idx=0)

    def Reload(self):
        uthread.new(self._Reload)

    def _Reload(self):
        self.AnimShowLoading()
        self.CheckShipAndShowMessage()
        self.entryDataList = self._GenerateSkillEntries(self.controller.skills)
        self._FlushAndPopulateSkillScroll(self.entryDataList)
        self.UpdateNoContentMessage()
        self.AnimHideLoading()

    def AnimShowLoading(self):
        self.skillScroll.Disable()
        self.filterCont.Disable()
        animations.FadeIn(self.loadingPanel)
        animations.FadeOut(self.skillScroll, duration=0.3)
        animations.FadeOut(self.filterCont, duration=0.3, sleep=True)

    def AnimHideLoading(self):
        self.skillScroll.Enable()
        self.filterCont.Enable()
        animations.FadeOut(self.loadingPanel)
        animations.FadeIn(self.skillScroll)
        animations.FadeIn(self.filterCont)

    def _GenerateSkillEntries(self, skills):
        skillDataByGroupID = itertoolsext.bucket(
            skills,
            keyprojection=lambda s: evetypes.GetGroupID(s.typeID),
            valueprojection=lambda s: SkillEntryData(s, self.controller, self.
                                                     filterSettings))
        groups = [
            SkillGroupData(gid, self.filterSettings, children=data)
            for gid, data in skillDataByGroupID.iteritems()
        ]
        return sorted(groups, key=lambda x: x.GetLabel().lower())

    def _FlushAndPopulateSkillScroll(self, groups):
        self.skillScroll.Flush()
        for groupData in groups:
            SkillGroupEntry(parent=self.skillScroll,
                            data=groupData,
                            defaultExpanded=False)
            blue.pyos.BeNice()

    def OnUpdate(self):
        self.UpdateNoContentMessage()
        self.CheckCompletedAndShowMessage()

    def UpdateNoContentMessage(self):
        self.skillScroll.HideNoContentHint()
        if all((data.isFiltered for data in self.entryDataList)):
            emptyHint = localization.GetByLabel('UI/SkillTrading/NoSkillsHint')
            self.skillScroll.ShowNoContentHint(emptyHint)

    def CheckCompletedAndShowMessage(self):
        if self.controller.isCompleted:
            self.PrepareCompleteMessage()
            self.AnimShowMessage()

    def PrepareCompleteMessage(self):
        self.messagePanel.Flush()
        text = localization.GetByLabel(
            'UI/SkillTrading/CompleteMessageCaption')
        EveCaptionMedium(parent=self.messagePanel,
                         align=uiconst.TOTOP,
                         text='<center>%s</center>' % text)
        text = localization.GetByLabel('UI/SkillTrading/CompleteMessageMain',
                                       amount=self.controller.SKILL_POINT_GOAL,
                                       injector=invconst.typeSkillInjector)
        EveLabelMedium(parent=self.messagePanel,
                       align=uiconst.TOTOP,
                       top=4,
                       text='<center>%s</center>' % text)
        iconCont = Container(parent=self.messagePanel,
                             align=uiconst.TOTOP,
                             top=8,
                             height=64)
        Icon(parent=iconCont,
             align=uiconst.CENTER,
             left=-40,
             typeID=invconst.typeSkillInjector,
             size=64,
             state=uiconst.UI_DISABLED)
        Sprite(
            parent=iconCont,
            align=uiconst.CENTER,
            state=uiconst.UI_DISABLED,
            texturePath='res:/UI/Texture/classes/skilltrading/arrow_right.png',
            width=32,
            height=32,
            opacity=0.6)
        Sprite(parent=iconCont,
               align=uiconst.CENTER,
               state=uiconst.UI_DISABLED,
               left=40,
               texturePath='res:/UI/Texture/WindowIcons/itemHangar.png',
               width=64,
               height=64)
        text = localization.GetByLabel('UI/SkillTrading/CompleteMessageTail',
                                       injector=invconst.typeSkillInjector)
        EveLabelMedium(parent=self.messagePanel,
                       align=uiconst.TOTOP,
                       top=8,
                       text='<center>%s</center>' % text)
        buttonCont = Container(parent=self.messagePanel,
                               align=uiconst.TOTOP,
                               top=16,
                               height=40)
        Button(parent=buttonCont,
               align=uiconst.CENTER,
               label=localization.GetByLabel('UI/Common/Done'),
               func=self.Close)

    def CheckShipAndShowMessage(self):
        if self.controller.isCompleted:
            return
        ship = sm.GetService('godma').GetItem(session.shipid)
        if ship.groupID != const.groupCapsule:
            self.PrepareShipMessage()
            self.AnimShowMessage()
        else:
            self.AnimHideMessage()

    def PrepareShipMessage(self):
        self.messagePanel.Flush()
        text = 'Must Be In Capsule'
        EveCaptionMedium(parent=self.messagePanel,
                         align=uiconst.TOTOP,
                         text='<center>%s</center>' % text)
        text = 'A direct connection to your capsule is required in order to extract skill points. Please leave your active ship to continue.'
        EveLabelMedium(parent=self.messagePanel,
                       align=uiconst.TOTOP,
                       top=4,
                       text='<center>%s</center>' % text)
        buttonCont = Container(parent=self.messagePanel,
                               align=uiconst.TOTOP,
                               top=16,
                               height=40)
        Button(parent=buttonCont,
               align=uiconst.CENTER,
               label='Leave Current Ship',
               func=self.LeaveShip,
               args=())

    def AnimShowMessage(self):
        self.contentCont.Disable()
        animations.FadeTo(self.contentCont,
                          startVal=self.contentCont.opacity,
                          endVal=0.1)
        animations.FadeIn(self.messagePanel)

    def AnimHideMessage(self):
        self.contentCont.Enable()
        animations.FadeTo(self.contentCont,
                          startVal=self.contentCont.opacity,
                          endVal=1.0)
        animations.FadeOut(self.messagePanel)

    def Close(self, *args, **kwargs):
        super(SkillExtractorWindow, self).Close(*args, **kwargs)
        self.controller.Close()

    def OnSessionChanged(self, isRemote, sess, change):
        if 'stationid2' in change:
            self.Close()
        elif 'shipid' in change:
            self.CheckShipAndShowMessage()

    def LeaveShip(self):
        ship = sm.GetService('godma').GetItem(session.shipid)
        sm.StartService('station').TryLeaveShip(ship)
        self.AnimHideMessage()
Пример #9
0
 def ApplyAttributes(self, attributes):
     ContainerAutoSize.ApplyAttributes(self, attributes)
     self.ResetOpacity()
     self.UpdateEntryHeight()
Пример #10
0
 def ApplyAttributes(self, attributes):
     ContainerAutoSize.ApplyAttributes(self, attributes)
     label = attributes.label
     maxValue = attributes.Get('maxValue', 1.0)
     self.colorCallback = attributes.colorCallback
     self.color = Color(*attributes.color)
     self.initialized = False
     Label(parent=self,
           align=uiconst.TOTOP,
           text=label,
           fontsize=20,
           left=14)
     Button(parent=self,
            left=4,
            top=4,
            align=uiconst.TOPRIGHT,
            label='Copy to Clipboard',
            func=self.CopyToClipboard)
     self.r = ValueSelector(parent=self,
                            align=uiconst.TOTOP,
                            height=18,
                            value=self.color.r,
                            maxValue=maxValue,
                            label='R',
                            callback=self.OnRChange)
     self.g = ValueSelector(parent=self,
                            align=uiconst.TOTOP,
                            height=18,
                            value=self.color.g,
                            maxValue=maxValue,
                            label='G',
                            callback=self.OnGChange,
                            padTop=PADTOP)
     self.b = ValueSelector(parent=self,
                            align=uiconst.TOTOP,
                            height=18,
                            value=self.color.b,
                            maxValue=maxValue,
                            label='B',
                            callback=self.OnBChange,
                            padTop=PADTOP)
     h, s, b = self.color.GetHSB()
     self.h = ValueSelector(parent=self,
                            align=uiconst.TOTOP,
                            height=18,
                            value=h,
                            maxValue=1.0,
                            label='H',
                            callback=self.OnHChange,
                            padTop=PADTOP + 14)
     self.s = ValueSelector(parent=self,
                            align=uiconst.TOTOP,
                            height=18,
                            value=s,
                            maxValue=1.0,
                            label='S',
                            callback=self.OnSChange,
                            padTop=PADTOP)
     self.br = ValueSelector(parent=self,
                             align=uiconst.TOTOP,
                             height=18,
                             value=b,
                             maxValue=maxValue,
                             label='B',
                             callback=self.OnBrChange,
                             padTop=PADTOP)
     self.initialized = True
Пример #11
0
 def _OnSizeChange_NoBlock(self, *args, **kwds):
     ContainerAutoSize._OnSizeChange_NoBlock(self, *args, **kwds)
     self.OnSizeChanged()
Пример #12
0
 def Close(self, *args):
     if self.controller and hasattr(self.controller, 'OnMenuClosed'):
         self.controller.OnMenuClosed()
     ContainerAutoSize.Close(self, *args)
Пример #13
0
 def ApplyAttributes(self, attributes):
     Container.ApplyAttributes(self, attributes)
     self.jobData = None
     foregroundCont = Container(
         bgTexturePath=
         'res:/UI/Texture/Classes/Industry/Output/outputContBg.png',
         parent=self,
         align=uiconst.CENTER,
         width=self.width,
         height=self.height,
         state=uiconst.UI_DISABLED)
     self.bgPattern = Frame(
         bgParent=foregroundCont,
         texturePath='res:/UI/Texture/Classes/Industry/Output/bgPattern.png',
         cornerSize=12)
     self.captionCont = ContainerAutoSize(name='captionCont',
                                          parent=self,
                                          align=uiconst.TOPLEFT,
                                          pos=(14, 10, 300, 0))
     self.outcomeCaption = EveHeaderMedium(
         name='outcomeCaption',
         parent=self.captionCont,
         align=uiconst.TOTOP,
         bold=True,
         text=GetByLabel('UI/Industry/Outcome'))
     self.outcomeLabel = EveHeaderSmall(name='outcomeLabel',
                                        parent=self.captionCont,
                                        align=uiconst.TOTOP,
                                        bold=True)
     self.probabilityLabel = EveHeaderSmall(name='probabilityLabel',
                                            parent=self.captionCont,
                                            align=uiconst.TOTOP,
                                            bold=False,
                                            state=uiconst.UI_HIDDEN)
     self.probabilityLabel.LoadTooltipPanel = self.LoadProbabilityTooltipPanel
     self.probabilityLabel.GetTooltipDelay = self.GetProbabilityTooltipDelay
     self.copyInfoCont = Container(name='copyInfoCont',
                                   parent=self,
                                   align=uiconst.CENTERBOTTOM,
                                   pos=(0, 8, 300, 32),
                                   state=uiconst.UI_HIDDEN)
     self.containerME = ContainerME(parent=self.copyInfoCont,
                                    align=uiconst.TOPLEFT,
                                    width=71,
                                    height=30)
     self.runsPerCopyCont = ContainerAutoSize(name='runsPerCopyCont',
                                              parent=self.copyInfoCont,
                                              align=uiconst.CENTERTOP)
     self.containerTE = ContainerTE(parent=self.copyInfoCont,
                                    align=uiconst.TOPRIGHT,
                                    width=71,
                                    height=30)
     IndustryCaptionLabel(parent=self.runsPerCopyCont,
                          text=localization.GetByLabel('UI/Industry/Runs'),
                          align=uiconst.CENTERTOP)
     self.bpRunsLabel = EveLabelMediumBold(parent=self.runsPerCopyCont,
                                           align=uiconst.CENTERTOP,
                                           top=12)
     self.errorFrame = ErrorFrame(bgParent=self, padding=1)
     self.outcomeItem = OutcomeItemContainer(parent=self)
     FillThemeColored(bgParent=self, opacity=0.5)
Пример #14
0
class OutcomeContainer(Container):
    default_width = 327
    default_height = 202

    def ApplyAttributes(self, attributes):
        Container.ApplyAttributes(self, attributes)
        self.jobData = None
        foregroundCont = Container(
            bgTexturePath=
            'res:/UI/Texture/Classes/Industry/Output/outputContBg.png',
            parent=self,
            align=uiconst.CENTER,
            width=self.width,
            height=self.height,
            state=uiconst.UI_DISABLED)
        self.bgPattern = Frame(
            bgParent=foregroundCont,
            texturePath='res:/UI/Texture/Classes/Industry/Output/bgPattern.png',
            cornerSize=12)
        self.captionCont = ContainerAutoSize(name='captionCont',
                                             parent=self,
                                             align=uiconst.TOPLEFT,
                                             pos=(14, 10, 300, 0))
        self.outcomeCaption = EveHeaderMedium(
            name='outcomeCaption',
            parent=self.captionCont,
            align=uiconst.TOTOP,
            bold=True,
            text=GetByLabel('UI/Industry/Outcome'))
        self.outcomeLabel = EveHeaderSmall(name='outcomeLabel',
                                           parent=self.captionCont,
                                           align=uiconst.TOTOP,
                                           bold=True)
        self.probabilityLabel = EveHeaderSmall(name='probabilityLabel',
                                               parent=self.captionCont,
                                               align=uiconst.TOTOP,
                                               bold=False,
                                               state=uiconst.UI_HIDDEN)
        self.probabilityLabel.LoadTooltipPanel = self.LoadProbabilityTooltipPanel
        self.probabilityLabel.GetTooltipDelay = self.GetProbabilityTooltipDelay
        self.copyInfoCont = Container(name='copyInfoCont',
                                      parent=self,
                                      align=uiconst.CENTERBOTTOM,
                                      pos=(0, 8, 300, 32),
                                      state=uiconst.UI_HIDDEN)
        self.containerME = ContainerME(parent=self.copyInfoCont,
                                       align=uiconst.TOPLEFT,
                                       width=71,
                                       height=30)
        self.runsPerCopyCont = ContainerAutoSize(name='runsPerCopyCont',
                                                 parent=self.copyInfoCont,
                                                 align=uiconst.CENTERTOP)
        self.containerTE = ContainerTE(parent=self.copyInfoCont,
                                       align=uiconst.TOPRIGHT,
                                       width=71,
                                       height=30)
        IndustryCaptionLabel(parent=self.runsPerCopyCont,
                             text=localization.GetByLabel('UI/Industry/Runs'),
                             align=uiconst.CENTERTOP)
        self.bpRunsLabel = EveLabelMediumBold(parent=self.runsPerCopyCont,
                                              align=uiconst.CENTERTOP,
                                              top=12)
        self.errorFrame = ErrorFrame(bgParent=self, padding=1)
        self.outcomeItem = OutcomeItemContainer(parent=self)
        FillThemeColored(bgParent=self, opacity=0.5)

    def LoadProbabilityTooltipPanel(self, tooltipPanel, *args):
        if not self.jobData:
            return
        self.tooltipPanel = ProbabilityTooltipPanel(jobData=self.jobData,
                                                    tooltipPanel=tooltipPanel)

    def GetProbabilityTooltipDelay(self):
        return TOOLTIP_DELAY_GAMEPLAY

    def AnimEntry(self):
        if self.jobData:
            color = GetJobColor(self.jobData)
            for pattern in (self.bgPattern, self.outcomeCaption):
                uicore.animations.SpColorMorphTo(pattern,
                                                 pattern.GetRGBA(),
                                                 color,
                                                 duration=0.3)

        self.errorFrame.Hide()

    def UpdateState(self):
        if self.jobData:
            self.outcomeLabel.text = self.jobData.GetProductLabel()
            self.UpdateCopyInfo()
            if self.jobData.activityID == industry.INVENTION:
                self.probabilityLabel.Show()
                color = Color.RGBtoHex(*GetJobColor(self.jobData))
                self.probabilityLabel.text = localization.GetByLabel(
                    'UI/Industry/SuccessProbabilityPerRun',
                    probability=self.jobData.probability * 100,
                    color=color)
            else:
                self.probabilityLabel.Hide()
        else:
            self.outcomeLabel.text = ''
            self.probabilityLabel.Hide()

    def OnNewJobData(self, jobData):
        self.jobData = jobData
        self.UpdateState()
        self.outcomeItem.OnNewJobData(jobData)
        self.AnimEntry()

    def OnRunsChanged(self):
        self.UpdateState()

    def UpdateCopyInfo(self):
        bpData = self.jobData.GetProductNewBlueprint()
        if not bpData:
            self.copyInfoCont.Hide()
            return
        self.copyInfoCont.Show()
        self.containerME.SetValue(bpData.materialEfficiency)
        self.containerTE.SetValue(bpData.timeEfficiency)
        if bpData.original:
            self.runsPerCopyCont.Hide()
        else:
            self.runsPerCopyCont.Show()
            self.bpRunsLabel.text = '%s' % bpData.runsRemaining
Пример #15
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):
        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)
Пример #16
0
class SettingSection(ContainerAutoSize):
    default_name = 'SettingSection'
    default_align = uiconst.TOTOP

    def ApplyAttributes(self, attributes):
        ContainerAutoSize.ApplyAttributes(self, attributes)
        self.structureProfileController = attributes.structureProfileController
        self.ChangeSignalConnection()
        self.settingID = attributes.settingID
        sgControllers = self.structureProfileController.GetGroupsBySettingID(
            self.settingID)
        canHaveGroups = CanHaveGroups(self.settingID)
        if not canHaveGroups and not sgControllers:
            self.structureProfileController.AddGroup(self.settingID,
                                                     groupID=NO_GROUP_ID,
                                                     doSignal=False)
            sgControllers = self.structureProfileController.GetGroupsBySettingID(
                self.settingID)
        self.AddHeader(canHaveGroups, sgControllers)
        self.sectionCont = ContainerAutoSize(parent=self,
                                             name='sectionCont',
                                             align=uiconst.TOTOP)
        self.LoadGroups()

    def ChangeSignalConnection(self, connect=True):
        signalAndCallback = [(self.structureProfileController.on_groups_added,
                              self.OnGroupsAdded),
                             (self.structureProfileController.on_group_changed,
                              self.OnGroupsChanged)]
        ChangeSignalConnect(signalAndCallback, connect)

    def LoadGroups(self):
        self.sectionCont.Flush()
        canHaveGroups = CanHaveGroups(self.settingID)
        if not canHaveGroups:
            return
        sgControllers = self.structureProfileController.GetGroupsBySettingID(
            self.settingID)
        if sgControllers:
            accessGroupsController = sm.GetService(
                'structureControllers').GetAccessGroupController()
            groupIDs = [c.GetGroupID() for c in sgControllers]
            accessGroupsController.PopulatePublicGroupInfo(groupIDs)
            toSort = []
            for c in sgControllers:
                groupInfo = accessGroupsController.GetGroupInfoFromID(
                    c.GetGroupID())
                if groupInfo is None:
                    continue
                nameLower = groupInfo['name'].lower()
                toSort.append((nameLower, (c, groupInfo)))

            sortedControllers = SortListOfTuples(toSort)
            for c, groupInfo in sortedControllers:
                GroupEntry(
                    parent=self.sectionCont,
                    groupID=c.GetGroupID(),
                    settingGroupController=c,
                    structureProfileController=self.structureProfileController,
                    groupInfo=groupInfo)

        else:
            x = Generic(parent=self.sectionCont, height=30)
            x.Startup()
            x.Load(
                node=Bunch(label=GetByLabel('UI/StructureSettingWnd/NoGroups'),
                           sublevel=1))

    def AddHeader(self, canHaveGroups, sgControllers):
        if canHaveGroups:
            self.header = SettingSectionHeaderWithGroups(
                parent=self,
                structureProfileController=self.structureProfileController,
                expanderFunc=self.OnExpandGroups,
                settingID=self.settingID)
        else:
            sgController = list(sgControllers)[0]
            if sgController.GetSettingType(
            ) == structures.SETTINGS_TYPE_PERCENTAGE:
                headerClass = SettingSectionHeaderWithPercentage
            elif sgController.GetSettingType(
            ) == structures.SETTINGS_TYPE_BOOL:
                headerClass = SettingSectionHeaderWithCheckbox
            else:
                raise RuntimeError('Bad settingType',
                                   sgController.GetSettingType(),
                                   sgController.GetSettingID())
            self.header = headerClass(
                parent=self,
                structureProfileController=self.structureProfileController,
                sgController=sgController,
                settingID=self.settingID)

    def OnExpandGroups(self):
        isExpanded = settings.user.ui.Get(UI_EXPANDED_SETTING % self.settingID,
                                          True)
        self.sectionCont.display = isExpanded

    def DragChanged(self, initiated):
        canHaveGroups = CanHaveGroups(self.settingID)
        if not canHaveGroups:
            return
        self.header.OnGroupsDragged(initiated)

    def Close(self):
        self.ChangeSignalConnection(connect=False)
        self.structureProfileController = None
        ContainerAutoSize.Close(self)

    def OnGroupsAdded(self, settingID, groupIDs):
        if settingID != self.settingID:
            return
        self.LoadGroups()
        self.header.BlinkBgFill()

    def OnGroupsChanged(self):
        self.LoadGroups()
Пример #17
0
class BasePinContainer(Window):
    __guid__ = 'planet.ui.BasePinContainer'
    __notifyevents__ = ['OnRefreshPins', 'ProcessColonyDataSet']
    default_height = 185
    default_width = 300
    default_minSize = (300, 185)
    default_maxSize = (450, None)
    default_state = uiconst.UI_NORMAL
    default_align = uiconst.TOPLEFT
    default_name = 'BasePinContainer'
    default_opacity = 0.0
    default_topParentHeight = 0
    default_isCollapseable = False
    default_isPinable = False
    default_isStackable = False
    default_isMinimizable = False
    default_windowID = 'PlanetPinWindow'
    INFO_CONT_HEIGHT = 70

    def GetBaseHeight(self):
        return self.main.height + 26

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        self.main = ContainerAutoSize(parent=self.sr.main,
                                      name='main',
                                      padding=3,
                                      state=uiconst.UI_PICKCHILDREN,
                                      align=uiconst.TOTOP,
                                      alignMode=uiconst.TOTOP)
        self.planetUISvc = sm.GetService('planetUI')
        self.planetSvc = sm.GetService('planetSvc')
        self.pin = attributes.Get('pin', None)
        self.uiEffects = uicls.UIEffects()
        self.showingActionContainer = False
        self.currentRoute = None
        self.showNext = None
        self.lastCalled = None
        self.commodityToRoute = None
        self.buttonTextValue = ''
        infoCont = Container(parent=self.main,
                             name='infoCont',
                             padding=5,
                             align=uiconst.TOTOP,
                             height=self.INFO_CONT_HEIGHT)
        self.infoContLeft = Container(name='leftCol',
                                      parent=infoCont,
                                      align=uiconst.TOLEFT_PROP,
                                      width=0.5)
        self.infoContRight = Container(name='rightCol',
                                       parent=infoCont,
                                       align=uiconst.TOLEFT_PROP,
                                       width=0.5)
        self._GetInfoCont()
        self._UpdateInfoCont()
        self.buttonCont = GridContainer(parent=self.main,
                                        name='buttonCont',
                                        height=40,
                                        align=uiconst.TOTOP,
                                        padding=(-1, 0, -1, 0))
        BumpedUnderlay(bgParent=self.buttonCont)
        self.buttonCont.lines = 1
        self.buttonCont.columns = 6
        self.buttonTextCont = self._DrawAlignTopCont(22, 'buttonTextCont')
        self.buttonText = EveLabelSmall(parent=self.buttonTextCont,
                                        align=uiconst.CENTER,
                                        color=(1.0, 1.0, 1.0, 1.0),
                                        state=uiconst.UI_NORMAL)
        self.buttonTextCont.height = max(22, self.buttonText.textheight)
        self.actionCont = Container(parent=self.sr.main,
                                    name='actionCont',
                                    padding=(6, 0, 6, 6),
                                    clipChildren=True)
        self.SetCaption(self._GetPinName())
        self.main.SetSizeAutomatically()
        self.height = self.GetBaseHeight()
        self.LoadActionButtons(self._GetActionButtons())
        uicore.animations.FadeTo(self, 0.0, 1.0, duration=0.3)
        self.updateInfoContTimer = base.AutoTimer(100, self._UpdateInfoCont)
        sm.GetService('audio').SendUIEvent(
            'wise:/msg_pi_pininteraction_open_play')
        self.ResizeActionCont(None)

    def ShowDefaultPanel(self):
        if hasattr(self, 'defaultPanel'):
            self.ShowPanel(self.defaultPanel, self.defaultPanelID)

    def _GetPinName(self):
        return planetCommon.GetGenericPinName(self.pin.typeID, self.pin.id)

    def _GetInfoCont(self):
        pass

    def _GetActionButtons(self):
        btns = [
            util.KeyVal(id=planetCommonUI.PANEL_STATS,
                        panelCallback=self.PanelShowStats),
            util.KeyVal(id=planetCommonUI.PANEL_LINKS,
                        panelCallback=self.PanelShowLinks),
            util.KeyVal(id=planetCommonUI.PANEL_ROUTES,
                        panelCallback=self.PanelShowRoutes),
            util.KeyVal(id=planetCommonUI.PANEL_DECOMMISSION,
                        panelCallback=self.PanelDecommissionPin)
        ]
        return btns

    def ShowPanel(self, panelCallback, panelID, *args):
        _, label = planetCommonUI.PANELDATA[panelID]
        name = localization.GetByLabel(label)
        self.buttonText.text = name
        self.buttonTextValue = name
        if self.showingActionContainer:
            self.showNext = panelCallback
            return
        self.showNext = None
        self.showingActionContainer = True
        self.actionCont.Flush()
        if self.lastCalled != name:
            if args:
                cont = panelCallback(*args)
            else:
                cont = panelCallback()
            if cont:
                cont.state = uiconst.UI_HIDDEN
                self.lastCalled = name
                cont.opacity = 0.0
                self.ResizeActionCont(panelID)
                cont.state = uiconst.UI_PICKCHILDREN
                self.uiEffects.MorphUI(cont,
                                       'opacity',
                                       1.0,
                                       time=250.0,
                                       float=1,
                                       maxSteps=1000)
                uicore.registry.SetFocus(cont)
        else:
            self.HideCurrentPanel()
        self.showingActionContainer = False
        if self.showNext:
            self.ShowPanel(self.showNext, panelID)

    def HideCurrentPanel(self):
        self.actionCont.Flush()
        self.ResizeActionCont()
        self.lastCalled = None
        self.buttonTextValue = ''

    def _DrawAlignTopCont(self,
                          height,
                          name,
                          padding=(0, 0, 0, 0),
                          state=uiconst.UI_PICKCHILDREN):
        return Container(parent=self.main,
                         name=name,
                         pos=(0, 0, 0, height),
                         padding=padding,
                         state=state,
                         align=uiconst.TOTOP)

    def OnIconButtonMouseEnter(self, iconButton, *args):
        ButtonIcon.OnMouseEnter(iconButton, *args)
        self.buttonText.text = iconButton.name

    def OnIconButtonMouseExit(self, iconButton, *args):
        ButtonIcon.OnMouseExit(iconButton, *args)
        self.buttonText.text = self.buttonTextValue

    def LoadActionButtons(self, buttons):
        iconSize = 32
        w = self.width - 6
        maxIcons = 7.0
        n = float(len(buttons))
        pad = 5 + 1 * iconSize * (1.0 - n / maxIcons)
        w -= 2 * pad
        space = (w - n * iconSize) / n
        self.buttonCont.columns = len(buttons)
        for i, b in enumerate(buttons):
            iconPath, cerberusPath = planetCommonUI.PANELDATA[b.id]
            panelName = localization.GetByLabel(cerberusPath)
            if i == 0:
                self.defaultPanel = b.panelCallback
                self.defaultPanelID = b.id
            cont = Container(name=panelName, parent=self.buttonCont)
            ib = ButtonIcon(texturePath=iconPath,
                            parent=cont,
                            align=uiconst.CENTER,
                            name=panelName,
                            hint=b.Get('hint', ''),
                            width=iconSize,
                            height=iconSize,
                            iconSize=iconSize,
                            func=self._OnIconButtonClicked,
                            args=(b.panelCallback, b.id))
            ib.OnMouseEnter = (self.OnIconButtonMouseEnter, ib)
            ib.OnMouseExit = (self.OnIconButtonMouseExit, ib)

    def _OnIconButtonClicked(self, panelCallback, panelID, *args):
        self.ShowPanel(panelCallback, panelID)

    def CloseByUser(self, *args):
        self.planetUISvc.CloseCurrentlyOpenContainer()

    def PanelShowLinks(self):
        cont = Container(parent=self.actionCont, state=uiconst.UI_HIDDEN)
        self.linkScroll = scroll = Scroll(parent=cont,
                                          name='linksScroll',
                                          align=uiconst.TOALL)
        self.linkScroll.sr.id = 'planetBasePinLinkScroll'
        self.LoadLinkScroll()
        btns = [[
            localization.GetByLabel('UI/PI/Common/CreateNew'),
            self._CreateNewLink, None
        ],
                [
                    localization.GetByLabel('UI/PI/Common/DeleteLink'),
                    self._DeleteLink, None
                ]]
        ButtonGroup(btns=btns, idx=0, parent=cont)
        return cont

    def LoadLinkScroll(self):
        scrolllist = []
        planet = sm.GetService('planetUI').GetCurrentPlanet()
        colony = planet.GetColony(session.charid)
        links = colony.colonyData.GetLinksForPin(self.pin.id)
        for linkedPinID in links:
            link = colony.GetLink(self.pin.id, linkedPinID)
            linkedPin = colony.GetPin(linkedPinID)
            distance = link.GetDistance()
            bandwidthUsed = link.GetBandwidthUsage()
            percentageUsed = 100 * (bandwidthUsed / link.GetTotalBandwidth())
            data = util.KeyVal()
            data.label = '%s<t>%s<t>%s' % (planetCommon.GetGenericPinName(
                linkedPin.typeID, linkedPin.id), util.FmtDist(distance),
                                           localization.GetByLabel(
                                               'UI/Common/Percentage',
                                               percentage=percentageUsed))
            data.hint = ''
            data.OnMouseEnter = self.OnLinkEntryHover
            data.OnMouseExit = self.OnLinkEntryExit
            data.OnDblClick = self.OnLinkListentryDblClicked
            data.id = (link.endpoint1.id, link.endpoint2.id)
            sortBy = linkedPinID
            scrolllist.append((sortBy, listentry.Get('Generic', data=data)))

        scrolllist = uiutil.SortListOfTuples(scrolllist)
        self.linkScroll.Load(
            contentList=scrolllist,
            noContentHint=localization.GetByLabel(
                'UI/PI/Common/NoLinksPresent'),
            headers=[
                localization.GetByLabel('UI/PI/Common/Destination'),
                localization.GetByLabel('UI/Common/Distance'),
                localization.GetByLabel('UI/PI/Common/CapacityUsed')
            ])

    def OnLinkListentryDblClicked(self, entry):
        myPinManager = sm.GetService('planetUI').myPinManager
        link = myPinManager.linksByPinIDs[entry.sr.node.id]
        for node in self.linkScroll.GetNodes():
            myPinManager.RemoveHighlightLink(node.id)

        sm.GetService('planetUI').OpenContainer(link)

    def OnLinkEntryHover(self, entry):
        node = entry.sr.node
        self.planetUISvc.myPinManager.HighlightLink(self.pin.id, node.id)

    def OnLinkEntryExit(self, entry):
        node = entry.sr.node
        self.planetUISvc.myPinManager.RemoveHighlightLink(node.id)

    def _CreateNewLink(self, *args):
        self.planetUISvc.myPinManager.SetLinkParent(self.pin.id)
        self.CloseByUser()

    def _DeleteLink(self, *args):
        selected = self.linkScroll.GetSelected()
        if len(selected) > 0:
            self.planetUISvc.myPinManager.RemoveLink(selected[0].id)
            self.LoadLinkScroll()

    def _DrawEditBox(self, parent, text):
        textHeight = uix.GetTextHeight(text,
                                       width=self.width - 30,
                                       fontsize=fontConst.EVE_MEDIUM_FONTSIZE)
        edit = Edit(setvalue=text,
                    parent=parent,
                    align=uiconst.TOTOP,
                    height=textHeight + 18,
                    top=-6,
                    hideBackground=1,
                    readonly=True)
        edit.scrollEnabled = False
        return edit

    def ResizeActionCont(self, panelID=None):
        if panelID:
            minHeight, maxHeight = planetCommonUI.PANEL_MIN_MAX_HEIGHT[panelID]
            if maxHeight:
                height = (minHeight + maxHeight) / 2
            else:
                height = minHeight
        else:
            height = minHeight = maxHeight = 0
        baseHeight = self.GetBaseHeight()
        uicore.animations.MorphScalar(self,
                                      'height',
                                      self.height,
                                      height + baseHeight,
                                      duration=0.3)
        self.SetMinSize((self.default_minSize[0], baseHeight + minHeight))
        if minHeight == maxHeight:
            self.SetFixedHeight(baseHeight + minHeight)
        elif maxHeight:
            self.SetFixedHeight(None)
            self.SetMaxSize((self.default_maxSize[0], baseHeight + maxHeight))
        else:
            self.SetFixedHeight(None)
            self.SetMaxSize((self.default_maxSize[0], None))

    def _UpdateInfoCont(self):
        pass

    def PanelShowStorage(self):
        cont = Container(parent=self.actionCont, state=uiconst.UI_HIDDEN)
        self.storageContentScroll = Scroll(parent=cont,
                                           name='storageContentsScroll',
                                           id='planetStorageContentsScroll')
        self.storageContentScroll.sr.fixedColumns = {'': 28}
        self.LoadStorageContentScroll()
        btns = [[
            localization.GetByLabel('UI/PI/Common/CreateRoute'),
            self._CreateRoute, 'storageContentScroll'
        ],
                [
                    localization.GetByLabel('UI/PI/Common/ExpeditedTransfer'),
                    self._CreateTransfer, None
                ]]
        self.createRouteButton = ButtonGroup(btns=btns, parent=cont, idx=0)
        return cont

    def LoadStorageContentScroll(self):
        scrolllist = []
        for typeID, amount in self.pin.contents.iteritems():
            data = util.KeyVal()
            volume = evetypes.GetVolume(typeID) * amount
            data.label = '<t>%s<t>%s<t>%s' % (evetypes.GetName(typeID), amount,
                                              volume)
            data.amount = amount
            data.typeID = typeID
            data.itemID = None
            data.getIcon = (True, )
            data.OnDblClick = self.OnStorageEntryDblClicked
            sortBy = amount
            scrolllist.append((sortBy, listentry.Get('Item', data=data)))

        scrolllist = uiutil.SortListOfTuples(scrolllist)
        self.storageContentScroll.Load(
            contentList=scrolllist,
            noContentHint=localization.GetByLabel(
                'UI/PI/Common/NoContentsPresent'),
            headers=[
                '',
                localization.GetByLabel('UI/PI/Common/Type'),
                localization.GetByLabel('UI/Common/Amount'),
                localization.GetByLabel('UI/Common/Volume')
            ])

    def OnStorageEntryDblClicked(self, entry):
        self._CreateRoute('storageContentScroll')

    def PanelShowProducts(self):
        cont = Container(parent=self.actionCont, state=uiconst.UI_HIDDEN)
        self.productScroll = Scroll(parent=cont, name='productsScroll')
        self.productScroll.sr.id = 'planetBasePinProductScroll'
        self.LoadProductScroll()
        btns = [[
            localization.GetByLabel('UI/PI/Common/CreateRoute'),
            self._CreateRoute, 'productScroll'
        ]]
        self.createRouteButton = ButtonGroup(btns=btns, parent=cont, idx=0)
        btns = [[
            localization.GetByLabel('UI/PI/Common/DeleteRoute'),
            self._DeleteRoute, ()
        ]]
        self.deleteRouteButton = ButtonGroup(btns=btns, parent=cont, idx=0)
        self.createRouteButton.state = uiconst.UI_HIDDEN
        self.deleteRouteButton.state = uiconst.UI_HIDDEN
        return cont

    def LoadProductScroll(self):
        scrolllist = []
        colony = self.planetUISvc.planet.GetColony(session.charid)
        if colony is None or colony.colonyData is None:
            raise RuntimeError(
                'Cannot load product scroll for pin on a planet that has no colony'
            )
        sourcedRoutes = colony.colonyData.GetSourceRoutesForPin(self.pin.id)
        routesByTypeID = {}
        for route in sourcedRoutes:
            typeID = route.GetType()
            if typeID not in routesByTypeID:
                routesByTypeID[typeID] = []
            routesByTypeID[typeID].append(route)

        for typeID, amount in self.pin.GetProductMaxOutput().iteritems():
            typeName = evetypes.GetName(typeID)
            for route in routesByTypeID.get(typeID, []):
                qty = route.GetQuantity()
                amount -= qty
                data = util.KeyVal(
                    label='%s<t>%s<t>%s' %
                    (qty, typeName,
                     localization.GetByLabel('UI/PI/Common/Routed')),
                    typeID=typeID,
                    itemID=None,
                    getIcon=True,
                    routeID=route.routeID,
                    OnMouseEnter=self.OnRouteEntryHover,
                    OnMouseExit=self.OnRouteEntryExit,
                    OnClick=self.OnProductEntryClicked,
                    OnDblClick=self.OnProductEntryDblClicked)
                scrolllist.append(listentry.Get('Item', data=data))

            if amount > 0:
                data = util.KeyVal()
                data.label = '%s<t>%s<t>%s' % (amount, evetypes.GetName(
                    typeID), localization.GetByLabel('UI/PI/Common/NotRouted'))
                data.typeID = typeID
                data.amount = amount
                data.itemID = None
                data.getIcon = True
                data.OnClick = self.OnProductEntryClicked
                data.OnDblClick = self.OnProductEntryDblClicked
                scrolllist.append(listentry.Get('Item', data=data))

        self.productScroll.Load(
            contentList=scrolllist,
            noContentHint=localization.GetByLabel(
                'UI/PI/Common/NoProductsPresent'),
            headers=[
                localization.GetByLabel('UI/Common/Amount'),
                localization.GetByLabel('UI/PI/Common/Type'), ''
            ])

    def OnProductEntryClicked(self, entry):
        node = entry.sr.node
        if node.Get('routeID', None) is None:
            self.createRouteButton.state = uiconst.UI_NORMAL
            self.deleteRouteButton.state = uiconst.UI_HIDDEN
        else:
            self.createRouteButton.state = uiconst.UI_HIDDEN
            self.deleteRouteButton.state = uiconst.UI_NORMAL

    def OnProductEntryDblClicked(self, entry):
        node = entry.sr.node
        if node.Get('routeID', None) is None:
            self._CreateRoute('productScroll')

    def _CreateRoute(self, scroll):
        selected = getattr(self, scroll).GetSelected()
        if len(selected) > 0:
            entry = selected[0]
            self.planetUISvc.myPinManager.EnterRouteMode(
                self.pin.id, entry.typeID)
            self.ShowPanel(self.PanelCreateRoute,
                           planetCommonUI.PANEL_CREATEROUTE, entry.typeID,
                           entry.amount)

    def SubmitRoute(self):
        if not getattr(self, 'routeAmountEdit', None):
            return
        sm.GetService('planetUI').myPinManager.CreateRoute(
            self.routeAmountEdit.GetValue())
        self.HideCurrentPanel()
        self.commodityToRoute = None

    def _DeleteRoute(self):
        selected = self.productScroll.GetSelected()
        if len(selected) > 0:
            entry = selected[0]
            if entry.routeID:
                self.planetUISvc.myPinManager.RemoveRoute(entry.routeID)
                self.LoadProductScroll()
                self.createRouteButton.state = uiconst.UI_HIDDEN
                self.deleteRouteButton.state = uiconst.UI_HIDDEN

    def _DeleteRouteFromEntry(self):
        if not hasattr(self, 'routeScroll'):
            return
        selected = self.routeScroll.GetSelected()
        if len(selected) > 0:
            entry = selected[0]
            if entry.routeID:
                self.planetUISvc.myPinManager.RemoveRoute(entry.routeID)
                self.LoadRouteScroll()
                self.uiEffects.MorphUI(self.routeInfo,
                                       'opacity',
                                       0.0,
                                       time=125.0,
                                       float=1,
                                       newthread=0,
                                       maxSteps=1000)

    def _CreateTransfer(self, *args):
        if sm.GetService('planetUI').GetCurrentPlanet().IsInEditMode():
            raise UserError('CannotTransferInEditMode')
        self.planetUISvc.myPinManager.EnterRouteMode(self.pin.id,
                                                     None,
                                                     oneoff=True)
        self.ShowPanel(self.PanelSelectTransferDest,
                       planetCommonUI.PANEL_TRANSFER)

    def PanelDecommissionPin(self):
        typeName = evetypes.GetName(self.pin.typeID)
        if evetypes.GetGroupID(self.pin.typeID) == const.groupCommandPins:
            text = localization.GetByLabel(
                'UI/PI/Common/DecommissionCommandPin', typeName=typeName)
        else:
            text = localization.GetByLabel('UI/PI/Common/DecommissionLink',
                                           typeName=typeName)
        cont = Container(parent=self.actionCont, state=uiconst.UI_HIDDEN)
        Label(parent=cont, text=text, align=uiconst.TOTOP)
        btns = [[
            localization.GetByLabel('UI/PI/Common/Proceed'),
            self._DecommissionSelf, None
        ]]
        ButtonGroup(btns=btns, idx=0, parent=cont)
        return cont

    def _DecommissionSelf(self, *args):
        sm.GetService('audio').SendUIEvent(
            'wise:/msg_pi_build_decommission_play')
        self.planetUISvc.myPinManager.RemovePin(self.pin.id)
        self.CloseByUser()

    def OnRouteEntryHover(self, entry):
        self.planetUISvc.myPinManager.ShowRoute(entry.sr.node.routeID)

    def OnRouteEntryExit(self, entry):
        self.planetUISvc.myPinManager.StopShowingRoute(entry.sr.node.routeID)

    def OnRefreshPins(self, pinIDs):
        if hasattr(
                self,
                'lastCalled') and self.lastCalled == localization.GetByLabel(
                    'UI/PI/Common/Storage'):
            self.LoadStorageContentScroll()

    def ProcessColonyDataSet(self, planetID):
        if self.planetUISvc.planetID != planetID:
            return
        self.pin = sm.GetService('planetSvc').GetPlanet(planetID).GetPin(
            self.pin.id)

    def PanelShowStats(self, *args):
        cont = Container(parent=self.actionCont,
                         align=uiconst.TOALL,
                         state=uiconst.UI_HIDDEN)
        self.statsScroll = scroll = Scroll(parent=cont, name='StatsScroll')
        scrolllist = self.GetStatsEntries()
        scroll.Load(contentList=scrolllist,
                    headers=[
                        localization.GetByLabel('UI/PI/Common/Attribute'),
                        localization.GetByLabel('UI/Common/Value')
                    ])
        return cont

    def GetStatsEntries(self):
        scrolllist = []
        if self.pin.GetCpuUsage() > 0:
            data = util.KeyVal(
                label='%s<t>%s' %
                (localization.GetByLabel('UI/PI/Common/CpuUsage'),
                 localization.GetByLabel('UI/PI/Common/TeraFlopsAmount',
                                         amount=self.pin.GetCpuUsage())))
            scrolllist.append(listentry.Get('Generic', data=data))
        if self.pin.GetCpuOutput() > 0:
            data = util.KeyVal(
                label='%s<t>%s' %
                (localization.GetByLabel('UI/PI/Common/CpuOutput'),
                 localization.GetByLabel('UI/PI/Common/TeraFlopsAmount',
                                         amount=self.pin.GetCpuOutput())))
            scrolllist.append(listentry.Get('Generic', data=data))
        if self.pin.GetPowerUsage() > 0:
            data = util.KeyVal(
                label='%s<t>%s' %
                (localization.GetByLabel('UI/PI/Common/PowerUsage'),
                 localization.GetByLabel('UI/PI/Common/MegaWattsAmount',
                                         amount=self.pin.GetPowerUsage())))
            scrolllist.append(listentry.Get('Generic', data=data))
        if self.pin.GetPowerOutput() > 0:
            data = util.KeyVal(
                label='%s<t>%s' %
                (localization.GetByLabel('UI/PI/Common/PowerOutput'),
                 localization.GetByLabel('UI/PI/Common/MegaWattsAmount',
                                         amount=self.pin.GetPowerOutput())))
            scrolllist.append(listentry.Get('Generic', data=data))
        return scrolllist

    def OnPlanetRouteWaypointAdded(self, currentRoute):
        self.currentRoute = currentRoute
        self.UpdatePanelCreateRoute()

    def PanelCreateRoute(self, typeID, amount):
        cont = Container(parent=self.actionCont,
                         pos=(0, 0, 0, 130),
                         align=uiconst.TOTOP,
                         state=uiconst.UI_HIDDEN)
        cont._OnClose = self.OnPanelCreateRouteClosed
        w = self.width - 5
        self.sourceMaxAmount = amount
        self.routeMaxAmount = amount
        self.commodityToRoute = typeID
        self.commoditySourceMaxAmount = amount
        self.currRouteCycleTime = self.pin.GetCycleTime()
        resourceTxt = localization.GetByLabel(
            'UI/PI/Common/ItemAmount',
            itemName=evetypes.GetName(typeID),
            amount=int(self.routeMaxAmount))
        CaptionAndSubtext(
            parent=cont,
            caption=localization.GetByLabel('UI/PI/Common/CommodityToRoute'),
            subtext=resourceTxt,
            iconTypeID=typeID,
            top=0,
            width=w)
        CaptionAndSubtext(
            parent=cont,
            caption=localization.GetByLabel('UI/PI/Common/QtyAmount'),
            width=w,
            top=30,
            state=uiconst.UI_DISABLED)
        self.routeAmountEdit = SinglelineEdit(
            name='routeAmountEdit',
            parent=cont,
            setvalue=self.routeMaxAmount,
            height=14,
            width=56,
            align=uiconst.TOPLEFT,
            top=44,
            ints=(0, self.routeMaxAmount),
            OnChange=self.OnRouteAmountEditChanged)
        self.routeAmountText = EveLabelSmall(parent=cont,
                                             left=60,
                                             top=46,
                                             state=uiconst.UI_NORMAL)
        self.routeDestText = CaptionAndSubtext(
            parent=cont,
            caption=localization.GetByLabel('UI/Common/Destination'),
            top=70,
            width=w)
        btns = [[
            localization.GetByLabel('UI/PI/Common/CreateRoute'),
            self.SubmitRoute, ()
        ]]
        self.createRouteButton = ButtonGroup(btns=btns,
                                             parent=cont,
                                             line=False,
                                             alwaysLite=True)
        self.UpdatePanelCreateRoute()
        return cont

    def OnPanelCreateRouteClosed(self, *args):
        sm.GetService('planetUI').myPinManager.LeaveRouteMode()

    def OnRouteAmountEditChanged(self, newVal):
        try:
            routeAmount = int(newVal)
        except ValueError:
            return

        if not self.currRouteCycleTime:
            return
        routeAmount = min(routeAmount, self.routeMaxAmount)
        routeAmount = max(routeAmount, 0.0)
        volume = planetCommon.GetCommodityTotalVolume(
            {self.commodityToRoute: routeAmount})
        volumePerHour = planetCommon.GetBandwidth(volume,
                                                  self.currRouteCycleTime)
        sm.GetService('planetUI').myPinManager.OnRouteVolumeChanged(
            volumePerHour)

    def UpdatePanelCreateRoute(self):
        if not self.currentRoute or len(self.currentRoute) < 2:
            destName = localization.GetByLabel(
                'UI/PI/Common/NoDestinationSelected')
            self.routeMaxAmount = self.sourceMaxAmount
            self.currRouteCycleTime = self.pin.GetCycleTime()
        else:
            self.routeDestPin = sm.GetService(
                'planetUI').GetCurrentPlanet().GetColony(
                    session.charid).GetPin(self.currentRoute[-1])
            isValid, invalidTxt, self.currRouteCycleTime = planetCommon.GetRouteValidationInfo(
                self.pin, self.routeDestPin, self.commodityToRoute)
            destName = planetCommon.GetGenericPinName(self.routeDestPin.typeID,
                                                      self.routeDestPin.id)
            if not isValid:
                destName = localization.GetByLabel(
                    'UI/PI/Common/InvalidDestination',
                    destName=destName,
                    reason=invalidTxt)
            if not isValid:
                self.routeMaxAmount = 0
            elif self.routeDestPin.IsProcessor(
            ) and self.commodityToRoute in self.routeDestPin.GetConsumables():
                destMaxAmount = self.routeDestPin.GetConsumables().get(
                    self.commodityToRoute)
                if self.pin.IsStorage():
                    self.routeMaxAmount = destMaxAmount
                else:
                    self.routeMaxAmount = min(destMaxAmount,
                                              self.commoditySourceMaxAmount)
            else:
                self.routeMaxAmount = self.commoditySourceMaxAmount
        self.routeAmountEdit.SetText(self.routeMaxAmount)
        self.routeAmountEdit.IntMode(0, self.routeMaxAmount)
        self.routeAmountText.text = localization.GetByLabel(
            'UI/PI/Common/RoutedPortion', maxAmount=self.routeMaxAmount)
        self.OnRouteAmountEditChanged(self.routeMaxAmount)
        self.routeDestText.SetSubtext(destName)

    def PanelSelectTransferDest(self, *args):
        cont = Container(parent=self.actionCont,
                         pos=(0, 0, 0, 15),
                         align=uiconst.TOTOP,
                         state=uiconst.UI_HIDDEN)
        cont._OnClose = self.OnPanelSelectTransferDestClosed
        Label(parent=cont,
              text=localization.GetByLabel(
                  'UI/PI/Common/SelectTransferDestination'),
              align=uiconst.TOTOP)
        return cont

    def OnPanelSelectTransferDestClosed(self, *args):
        sm.GetService('planetUI').myPinManager.LeaveRouteMode()

    def SetPin(self, pin):
        self.pin = pin

    def PanelShowRoutes(self, *args):
        self.showRoutesCont = cont = Container(parent=self.actionCont,
                                               state=uiconst.UI_HIDDEN)
        self.routeScroll = Scroll(parent=cont, name='routeScroll')
        self.routeScroll.multiSelect = False
        self.routeScroll.sr.id = 'planetBaseShowRoutesScroll'
        self.routeInfo = Container(parent=cont,
                                   pos=(0, 0, 0, 100),
                                   align=uiconst.TOBOTTOM,
                                   state=uiconst.UI_HIDDEN,
                                   idx=0,
                                   padTop=4)
        w = self.width / 2 - 10
        self.routeInfoSource = CaptionAndSubtext(
            parent=self.routeInfo,
            caption=localization.GetByLabel('UI/PI/Common/Origin'),
            width=w)
        self.routeInfoDest = CaptionAndSubtext(
            parent=self.routeInfo,
            caption=localization.GetByLabel('UI/PI/Common/Destination'),
            width=w,
            top=38)
        self.routeInfoType = CaptionAndSubtext(
            parent=self.routeInfo,
            caption=localization.GetByLabel('UI/Common/Commodity'),
            width=w,
            left=w)
        self.routeInfoBandwidth = CaptionAndSubtext(
            parent=self.routeInfo,
            caption=localization.GetByLabel('UI/PI/Common/CapacityUsed'),
            width=w,
            left=w,
            top=38)
        btns = []
        if self.pin.IsStorage() and hasattr(self, '_CreateRoute'):
            btns.append([
                localization.GetByLabel('UI/PI/Common/CreateRoute'),
                self._CreateRoute, 'routeScroll'
            ])
        btns.append([
            localization.GetByLabel('UI/PI/Common/DeleteRoute'),
            self._DeleteRouteFromEntry, ()
        ])
        self.routeInfoBtns = ButtonGroup(btns=btns,
                                         parent=self.routeInfo,
                                         idx=0)
        self.LoadRouteScroll()
        return cont

    def GetRouteTypeLabel(self, route, pin):
        if not route or not pin:
            return localization.GetByLabel('UI/Common/Unknown')
        elif route.GetSourcePinID() == pin.id:
            return localization.GetByLabel('UI/PI/Common/Outgoing')
        elif route.GetDestinationPinID() == pin.id:
            return localization.GetByLabel('UI/PI/Common/Incoming')
        else:
            return localization.GetByLabel('UI/PI/Common/Transiting')

    def LoadRouteScroll(self):
        scrolllist = []
        routesShown = []
        colony = self.planetUISvc.GetCurrentPlanet().GetColony(
            self.pin.ownerID)
        if colony is None or colony.colonyData is None:
            raise RuntimeError(
                'Unable to load route scroll without active colony on planet')
        links = colony.colonyData.GetLinksForPin(self.pin.id)
        for linkedPinID in links:
            link = colony.GetLink(self.pin.id, linkedPinID)
            for routeID in link.routesTransiting:
                if routeID in routesShown:
                    continue
                route = colony.GetRoute(routeID)
                typeID = route.GetType()
                qty = route.GetQuantity()
                typeName = evetypes.GetName(typeID)
                data = util.KeyVal(
                    label='<t>%s<t>%s<t>%s' %
                    (typeName, qty, self.GetRouteTypeLabel(route, self.pin)),
                    typeID=typeID,
                    itemID=None,
                    getIcon=True,
                    OnMouseEnter=self.OnRouteEntryHover,
                    OnMouseExit=self.OnRouteEntryExit,
                    routeID=route.routeID,
                    OnClick=self.OnRouteEntryClick,
                    amount=qty)
                scrolllist.append(listentry.Get('Item', data=data))
                routesShown.append(route.routeID)

        self.routeScroll.Load(
            contentList=scrolllist,
            noContentHint=localization.GetByLabel(
                'UI/PI/Common/NoIncomingOrOutgoingRoutes'),
            headers=[
                '',
                localization.GetByLabel('UI/Common/Commodity'),
                localization.GetByLabel('UI/Common/Quantity'),
                localization.GetByLabel('UI/PI/Common/Type')
            ])

    def OnRouteEntryClick(self, *args):
        selectedRoutes = self.routeScroll.GetSelected()
        if len(selectedRoutes) < 1:
            self.routeInfo.state = uiconst.UI_HIDDEN
            return
        selectedRouteData = selectedRoutes[0]
        selectedRoute = None
        colony = self.planetUISvc.GetCurrentPlanet().GetColony(session.charid)
        links = colony.colonyData.GetLinksForPin(self.pin.id)
        for linkedPinID in links:
            link = colony.GetLink(self.pin.id, linkedPinID)
            for routeID in link.routesTransiting:
                if routeID == selectedRouteData.routeID:
                    selectedRoute = route = colony.GetRoute(routeID)
                    break

        if selectedRoute is None or not evetypes.Exists(
                selectedRoute.GetType()):
            return
        if selectedRoute.GetSourcePinID() == self.pin.id:
            self.routeInfoSource.SetSubtext(
                localization.GetByLabel('UI/PI/Common/ThisStructure'))
        else:
            sourcePin = sm.GetService('planetUI').planet.GetPin(
                selectedRoute.GetSourcePinID())
            self.routeInfoSource.SetSubtext(
                planetCommon.GetGenericPinName(sourcePin.typeID, sourcePin.id))
        if selectedRoute.GetDestinationPinID() == self.pin.id:
            self.routeInfoDest.SetSubtext(
                localization.GetByLabel('UI/PI/Common/ThisStructure'))
        else:
            destPin = sm.GetService('planetUI').planet.GetPin(
                selectedRoute.GetDestinationPinID())
            self.routeInfoDest.SetSubtext(
                planetCommon.GetGenericPinName(destPin.typeID, destPin.id))
        routeTypeID = route.GetType()
        routeQty = route.GetQuantity()
        self.routeInfoType.SetSubtext(
            localization.GetByLabel('UI/PI/Common/ItemAmount',
                                    itemName=evetypes.GetName(routeTypeID),
                                    amount=int(routeQty)))
        bandwidthAttr = cfg.dgmattribs.Get(const.attributeLogisticalCapacity)
        self.routeInfoBandwidth.SetSubtext(
            GetFormatAndValue(bandwidthAttr,
                              selectedRoute.GetBandwidthUsage()))
        createRouteBtn = self.routeInfoBtns.GetBtnByLabel(
            localization.GetByLabel('UI/PI/Common/CreateRoute'))
        if createRouteBtn:
            if selectedRoute.GetDestinationPinID() == self.pin.id:
                createRouteBtn.state = uiconst.UI_NORMAL
            else:
                createRouteBtn.state = uiconst.UI_HIDDEN
        self.routeInfo.opacity = 0.0
        self.routeInfo.state = uiconst.UI_PICKCHILDREN
        self.uiEffects.MorphUI(self.routeInfo,
                               'opacity',
                               1.0,
                               time=125.0,
                               float=1,
                               newthread=0,
                               maxSteps=1000)
Пример #18
0
class TreeViewEntry(ContainerAutoSize):
    default_name = 'TreeViewEntry'
    default_align = uiconst.TOTOP
    default_state = uiconst.UI_NORMAL
    default_settingsID = ''
    LEFTPUSH = 10
    default_height = 22
    isDragObject = True
    noAccessColor = (0.33, 0.33, 0.33, 1.0)
    iconColor = util.Color.WHITE

    @telemetry.ZONE_METHOD
    def ApplyAttributes(self, attributes):
        ContainerAutoSize.ApplyAttributes(self, attributes)
        self.level = attributes.get('level', 0)
        self.data = attributes.get('data')
        self.eventListener = attributes.get('eventListener', None)
        self.parentEntry = attributes.get('parentEntry', None)
        self.settingsID = attributes.get('settingsID', self.default_settingsID)
        self.defaultExpanded = attributes.get('defaultExpanded', self.level < 1)
        self.childrenInitialized = False
        self.isToggling = False
        self.canAccess = True
        self.isSelected = False
        self.childSelectedBG = False
        self.icon = None
        self.childCont = None
        self.topRightCont = Container(name='topCont', parent=self, align=uiconst.TOTOP, height=self.default_height)
        self.topRightCont.GetDragData = self.GetDragData
        left = self.GetSpacerContWidth()
        if self.data.IsRemovable():
            removeBtn = Sprite(texturePath='res:/UI/Texture/icons/73_16_210.png', parent=self.topRightCont, align=uiconst.CENTERLEFT, width=16, height=16, left=left, hint=localization.GetByLabel('UI/Common/Buttons/Close'))
            left += 20
            removeBtn.OnClick = self.Remove
        icon = self.data.GetIcon()
        if icon:
            iconSize = self.height - 2
            self.icon = Icon(icon=icon, parent=self.topRightCont, pos=(left,
             0,
             iconSize,
             iconSize), align=uiconst.CENTERLEFT, state=uiconst.UI_DISABLED, ignoreSize=True)
            left += iconSize
        self.label = Label(parent=self.topRightCont, align=uiconst.CENTERLEFT, text=self.data.GetLabel(), left=left + 4)
        self.UpdateLabel()
        self.hoverBG = None
        self.selectedBG = None
        self.blinkBG = None
        if self.data.HasChildren():
            self.spacerCont = Container(name='spacerCont', parent=self.topRightCont, align=uiconst.TOLEFT, width=self.GetSpacerContWidth())
            self.toggleBtn = Container(name='toggleBtn', parent=self.spacerCont, align=uiconst.CENTERRIGHT, width=16, height=16, state=uiconst.UI_HIDDEN)
            self.toggleBtn.OnClick = self.OnToggleBtnClick
            self.toggleBtn.OnDblClick = lambda : None
            self.toggleBtnSprite = Sprite(bgParent=self.toggleBtn, texturePath='res:/UI/Texture/classes/Neocom/arrowDown.png', rotation=pi / 2, padding=(4, 4, 5, 5))
            expandChildren = False
            if not self.data.IsForceCollapsed():
                toggleSettingsDict = settings.user.ui.Get('invTreeViewEntryToggle_%s' % self.settingsID, {})
                expandChildren = toggleSettingsDict.get(self.data.GetID(), self.defaultExpanded)
                self.ConstructChildren()
            else:
                self.toggleBtn.state = uiconst.UI_NORMAL
            self.ShowChildCont(expandChildren, animate=False)
        else:
            self.ShowChildCont(False, animate=False)
        if self.eventListener and hasattr(self.eventListener, 'RegisterID'):
            self.eventListener.RegisterID(self, self.data.GetID())

    def GetSpacerContWidth(self):
        return (1 + self.level) * self.LEFTPUSH + 8

    def Close(self):
        try:
            if self.eventListener and hasattr(self.eventListener, 'UnregisterID'):
                self.eventListener.UnregisterID(self.data.GetID())
            if self.parentEntry and self.data in self.parentEntry.data._children:
                self.parentEntry.data._children.remove(self.data)
        finally:
            ContainerAutoSize.Close(self)

    @telemetry.ZONE_METHOD
    def ConstructChildren(self):
        self.childrenInitialized = True
        children = self.data.GetChildren()
        if self.destroyed:
            return
        if self.childCont is None:
            self.childCont = ContainerAutoSize(parent=self, name='childCont', align=uiconst.TOTOP, clipChildren=True, state=uiconst.UI_HIDDEN)
        if children:
            for child in children:
                cls = self.GetTreeViewEntryClassByTreeData(child)
                child = cls(parent=self.childCont, parentEntry=self, level=self.level + 1, eventListener=self.eventListener, data=child, settingsID=self.settingsID, state=uiconst.UI_HIDDEN)
                child.UpdateLabel()

            if self.childCont.children:
                self.childCont.children[-1].padBottom = 5
            self.toggleBtn.state = uiconst.UI_NORMAL

    def GetTreeViewEntryClassByTreeData(self, treeData):
        return TreeViewEntry

    def ShowChildCont(self, show = True, animate = True):
        if self.childCont is None or self.childCont.display == show or not self.data.HasChildren():
            return
        for child in self.childCont.children:
            self.ShowChild(child, show=show)

        self.isToggling = True
        if animate:
            if show:
                self.childCont.display = True
                uicore.animations.Tr2DRotateTo(self.toggleBtnSprite, pi / 2, 0.0, duration=0.15)
                self.childCont.DisableAutoSize()
                _, height = self.childCont.GetAutoSize()
                uicore.animations.FadeIn(self.childCont, duration=0.3)
                uicore.animations.MorphScalar(self.childCont, 'height', self.childCont.height, height, duration=0.15, sleep=True)
                self.childCont.EnableAutoSize()
            else:
                uicore.animations.Tr2DRotateTo(self.toggleBtnSprite, 0.0, pi / 2, duration=0.15)
                self.childCont.DisableAutoSize()
                uicore.animations.FadeOut(self.childCont, duration=0.15)
                uicore.animations.MorphScalar(self.childCont, 'height', self.childCont.height, 0, duration=0.15, sleep=True)
                self.childCont.display = False
            self.toggleBtn.Enable()
        else:
            self.childCont.display = show
            if show:
                self.toggleBtnSprite.rotation = 0.0
                self.childCont.opacity = 1.0
            else:
                self.toggleBtnSprite.rotation = pi / 2
                self.childCont.DisableAutoSize()
                self.childCont.opacity = 0.0
        self.isToggling = False

    def ShowChild(self, child, show = True):
        child.display = show

    def UpdateSelectedState(self, selectedIDs):
        invID = self.data.GetID()
        isSelected = selectedIDs[-1] == invID
        isChildSelected = not isSelected and invID in selectedIDs
        self.SetSelected(isSelected, isChildSelected)

    def SetSelected(self, isSelected, isChildSelected = False):
        self.isSelected = isSelected
        if isSelected or self.selectedBG:
            self.CheckConstructSelectedBG()
            self.selectedBG.display = isSelected
        self.UpdateLabel()
        if isChildSelected:
            if not self.childSelectedBG:
                self.childSelectedBG = GradientThemeColored(bgParent=self.spacerCont, rotation=0, alphaData=[(0, 0.5), (1.0, 0.0)], padBottom=1, colorType=uiconst.COLORTYPE_UIHILIGHT)
            else:
                self.childSelectedBG.Show()
        elif self.childSelectedBG:
            self.childSelectedBG.Hide()
        if isSelected and self.parentEntry:
            self.parentEntry.ExpandFromRoot()

    @telemetry.ZONE_METHOD
    def UpdateLabel(self):
        if self.isSelected and self.canAccess:
            self.label.color = util.Color.WHITE
        elif self.canAccess:
            self.label.color = Label.default_color
        else:
            self.label.color = self.noAccessColor
        if session.role & (service.ROLE_GML | service.ROLE_WORLDMOD):
            if settings.user.ui.Get('invPrimingDebugMode', False) and hasattr(self.data, 'invController') and self.data.invController.IsPrimed():
                self.label.color = util.Color.RED

    def ExpandFromRoot(self):
        self.ToggleChildren(forceShow=True)
        if self.parentEntry:
            self.parentEntry.ExpandFromRoot()

    def OnClick(self, *args):
        if self.eventListener and hasattr(self.eventListener, 'OnTreeViewClick'):
            self.eventListener.OnTreeViewClick(self, *args)

    def OnDblClick(self, *args):
        if self.eventListener and hasattr(self.eventListener, 'OnTreeViewDblClick'):
            self.eventListener.OnTreeViewDblClick(self, *args)

    def OnToggleBtnClick(self, *args):
        if not self.isToggling:
            self.ToggleChildren()

    def ToggleChildren(self, forceShow = False):
        show = forceShow or self.childCont is None or not self.childCont.display
        toggleSettingsDict = settings.user.ui.Get('invTreeViewEntryToggle_%s' % self.settingsID, {})
        toggleSettingsDict[self.data.GetID()] = show
        settings.user.ui.Set('invTreeViewEntryToggle_%s' % self.settingsID, toggleSettingsDict)
        if not self.data.HasChildren():
            return
        if not self.childrenInitialized:
            self.ConstructChildren()
        self.ShowChildCont(show)

    def GetMenu(self):
        m = self.data.GetMenu()
        if session.role & service.ROLE_PROGRAMMER:
            idString = repr(self.data.GetID())
            m.append((idString, blue.pyos.SetClipboardData, (idString,)))
        if self.data.IsRemovable():
            m.append(None)
            m.append((localization.GetByLabel('UI/Common/Buttons/Close'), self.Remove, ()))
        return m

    def GetHint(self):
        return self.data.GetHint()

    def GetFullPathLabelList(self):
        labelTuple = [self.data.GetLabel()]
        if self.parentEntry:
            labelTuple = self.parentEntry.GetFullPathLabelList() + labelTuple
        return labelTuple

    def Remove(self, *args):
        self.eventListener.RemoveTreeEntry(self, byUser=True)

    def OnMouseDown(self, *args):
        if self.eventListener and hasattr(self.eventListener, 'OnTreeViewMouseDown'):
            self.eventListener.OnTreeViewMouseDown(self, *args)

    def OnMouseUp(self, *args):
        if self.eventListener and hasattr(self.eventListener, 'OnTreeViewMouseUp'):
            self.eventListener.OnTreeViewMouseUp(self, *args)

    def CheckConstructHoverBG(self):
        if self.hoverBG is None:
            self.hoverBG = ListEntryUnderlay(bgParent=self.topRightCont)

    def CheckConstructSelectedBG(self):
        if self.selectedBG is None:
            self.selectedBG = FillThemeColored(bgParent=self.topRightCont, colorType=uiconst.COLORTYPE_UIHILIGHT, state=uiconst.UI_HIDDEN, opacity=0.5)

    def CheckConstructBlinkBG(self):
        if self.blinkBG is None:
            self.blinkBG = Fill(bgParent=self.topRightCont, color=(1.0, 1.0, 1.0, 0.0))

    def OnMouseEnter(self, *args):
        self.CheckConstructHoverBG()
        self.hoverBG.ShowHilite()
        if self.eventListener and hasattr(self.eventListener, 'OnTreeViewMouseEnter'):
            self.eventListener.OnTreeViewMouseEnter(self, *args)

    def OnMouseExit(self, *args):
        self.CheckConstructHoverBG()
        self.hoverBG.HideHilite()
        if self.eventListener and hasattr(self.eventListener, 'OnTreeViewMouseExit'):
            self.eventListener.OnTreeViewMouseExit(self, *args)

    def OnDropData(self, *args):
        if self.eventListener and hasattr(self.eventListener, 'OnTreeViewDropData'):
            self.eventListener.OnTreeViewDropData(self, *args)

    def OnDragEnter(self, dragObj, nodes):
        self.CheckConstructHoverBG()
        self.hoverBG.ShowHilite()
        if self.eventListener and hasattr(self.eventListener, 'OnTreeViewDragEnter'):
            self.eventListener.OnTreeViewDragEnter(self, dragObj, nodes)

    def GetDragData(self):
        if self.data.IsDraggable():
            self.eventListener.OnTreeViewGetDragData(self)
            return [self.data]

    def OnDragExit(self, *args):
        self.CheckConstructHoverBG()
        self.hoverBG.HideHilite()
        if self.eventListener and hasattr(self.eventListener, 'OnTreeViewDragExit'):
            self.eventListener.OnTreeViewDragExit(self, *args)

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

    @telemetry.ZONE_METHOD
    def SetAccessability(self, canAccess):
        self.canAccess = canAccess
        if self.icon:
            self.icon.color = self.iconColor if canAccess else util.Color(*self.iconColor).SetAlpha(0.5).GetRGBA()
        self.UpdateLabel()
Пример #19
0
 def _OnSizeChange_NoBlock(self, *args, **kwds):
     ContainerAutoSize._OnSizeChange_NoBlock(self, *args, **kwds)
     self.OnSizeChanged()
    def ConstructLayout(self):
        topCont = ContainerAutoSize(name='topCont',
                                    parent=self.sr.main,
                                    align=uiconst.TOTOP,
                                    padding=const.defaultPadding,
                                    callback=self.OnMainContainerSizeChanged)
        self.mainContainer = topCont
        charnameList = ''
        for entityID in self.entityIDs:
            charName = cfg.eveowners.Get(entityID).name
            if charnameList == '':
                charnameList = '%s' % charName
            else:
                charnameList = '%s, %s' % (charnameList, charName)

        uicontrols.EveLabelLargeBold(text=charnameList,
                                     parent=topCont,
                                     align=uiconst.TOTOP,
                                     state=uiconst.UI_DISABLED)
        uiprimitives.Line(parent=topCont,
                          align=uiconst.TOTOP,
                          padding=(0, 4, 0, 4))
        self.standingList = {
            const.contactHighStanding:
            localization.GetByLabel('UI/PeopleAndPlaces/ExcellentStanding'),
            const.contactGoodStanding:
            localization.GetByLabel('UI/PeopleAndPlaces/GoodStanding'),
            const.contactNeutralStanding:
            localization.GetByLabel('UI/PeopleAndPlaces/NeutralStanding'),
            const.contactBadStanding:
            localization.GetByLabel('UI/PeopleAndPlaces/BadStanding'),
            const.contactHorribleStanding:
            localization.GetByLabel('UI/PeopleAndPlaces/TerribleStanding')
        }
        levelList = self.standingList.keys()
        levelList.sort()
        levelText = self.standingList.get(self.level)
        self.levelText = uicontrols.EveLabelMedium(text=levelText,
                                                   parent=topCont,
                                                   align=uiconst.TOTOP,
                                                   state=uiconst.UI_DISABLED)
        if self.contactType != 'contact':
            bottomCont = uiprimitives.Container(name='bottomCont',
                                                parent=topCont,
                                                align=uiconst.TOTOP,
                                                height=40,
                                                padding=const.defaultPadding)
            startVal = 0.5
            sliderContainer = uiprimitives.Container(parent=bottomCont,
                                                     name='sliderContainer',
                                                     align=uiconst.CENTERTOP,
                                                     height=20,
                                                     width=210)
            self.sr.slider = self.AddSlider(sliderContainer,
                                            'standing',
                                            -10.0,
                                            10.0,
                                            '',
                                            startVal=startVal)
            self.sr.slider.SetValue(startVal)
            boxCont = bottomCont
            iconPadding = 28
        else:
            boxCont = uiprimitives.Container(name='boxCont',
                                             parent=topCont,
                                             align=uiconst.TOTOP,
                                             height=55)
            iconPadding = 6
        levelSelectorContainer = uiprimitives.Container(
            parent=boxCont,
            name='levelSelectorContainer',
            align=uiconst.TOTOP,
            pos=(0, 0, 0, 55))
        self.levelSelector = uicls.StandingLevelSelector(
            name='levelSelector',
            parent=levelSelectorContainer,
            align=uiconst.CENTERTOP,
            pos=(0, 14, 100 + iconPadding * 4, 55),
            iconPadding=iconPadding)
        self.levelSelector.OnStandingLevelSelected = self.OnStandingLevelSelected
        btnText = localization.GetByLabel('UI/PeopleAndPlaces/EditContact')
        self.btnGroup = uicontrols.ButtonGroup(
            btns=[[btnText, self.Confirm, (), 81, 1, 1, 0],
                  [
                      localization.GetByLabel('UI/Common/Buttons/Cancel'),
                      self.Cancel, (), 81, 0, 0, 0
                  ]],
            parent=self.sr.main,
            idx=0)
        if self.level is None:
            self.levelText.text = localization.GetByLabel(
                'UI/PeopleAndPlaces/SelectStanding')
            btn = self.btnGroup.GetBtnByLabel(btnText)
            uicore.registry.SetFocus(btn)
Пример #21
0
class AssetSafetyDeliverWindow(Window):
    __guid__ = 'form.AssetSafetyDeliverWindow'
    default_width = 600
    default_height = 100
    default_windowID = 'AssetSafetyDeliverWindow'
    default_topParentHeight = 0
    default_clipChildren = True
    default_isPinable = False
    LINE_COLOR = (1, 1, 1, 0.2)
    BLUE_COLOR = (0.0, 0.54, 0.8, 1.0)
    GREEN_COLOR = (0.0, 1.0, 0.0, 0.8)
    GRAY_COLOR = Color.GRAY5
    PADDING = 15

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        self.solarSystemID = attributes.solarSystemID
        self.assetWrapID = attributes.assetWrapID
        self.nearestNPCStationInfo = attributes.nearestNPCStationInfo
        self.autoDeliveryTimestamp = attributes.autoDeliveryTimestamp
        self.manualDeliveryTimestamp = attributes.manualDeliveryTimestamp
        self.Layout()
        uthread.new(self.ReloadContent)

    def Layout(self):
        self.MakeUnMinimizable()
        self.HideHeader()
        self.MakeUnResizeable()
        self.container = ContainerAutoSize(parent=self.GetMainArea(), align=uiconst.TOTOP, alignMode=uiconst.TOTOP, state=uiconst.UI_PICKCHILDREN, padding=(self.PADDING,
         self.PADDING,
         self.PADDING,
         self.PADDING), callback=self.OnContainerResized)
        text = GetByLabel('UI/Inventory/AssetSafety/DeliverToStation')
        header = EveLabelLargeBold(parent=self.container, align=uiconst.TOTOP, text=text)
        self.explanationLabel = EveLabelMedium(parent=self.container, align=uiconst.TOTOP, text='', color=self.GRAY_COLOR, padding=(0, 0, 0, 15), state=uiconst.UI_NORMAL)
        Line(parent=self.container, align=uiconst.TOTOP, color=self.LINE_COLOR)
        self.sameSolarSystemParent = ScrollContainer(parent=self.container, align=uiconst.TOTOP)
        self.sameSolarSystem = ContainerAutoSize(parent=self.sameSolarSystemParent, align=uiconst.TOTOP, alignMode=uiconst.TOTOP)
        self.nearestStationLabel = EveLabelMedium(parent=self.container, align=uiconst.TOTOP, text='', color=self.GRAY_COLOR, padding=(0, 0, 0, 0))
        self.closeButton = Button(parent=self.container, label=GetByLabel('UI/Generic/Cancel'), func=self.Close, align=uiconst.TOTOP, fontsize=13, padding=(220, 10, 220, 0))
        uicore.animations.FadeTo(self.container, startVal=0.0, endVal=1.0, duration=0.5)

    def SetText(self, systemStations):
        solarSystemName = GetShowInfoLink(const.typeSolarSystem, cfg.evelocations.Get(self.solarSystemID).name, self.solarSystemID)
        now = blue.os.GetWallclockTime()
        timeUntilAuto = FormatTimeIntervalShortWritten(long(max(0, self.autoDeliveryTimestamp - now)))
        nearestNPCStationText = GetShowInfoLink(self.nearestNPCStationInfo['typeID'], self.nearestNPCStationInfo['name'], self.nearestNPCStationInfo['itemID'])
        stationsInSystem = len(systemStations)
        if self.manualDeliveryTimestamp - now < 0:
            if stationsInSystem:
                path = 'UI/Inventory/AssetSafety/DeliveryExplanationText'
            else:
                path = 'UI/Inventory/AssetSafety/DeliveryExplanationTextNoStations'
            text = GetByLabel(path, solarSystemName=solarSystemName, npcStationName=nearestNPCStationText, timeUntil=timeUntilAuto)
        else:
            timeUntilManual = FormatTimeIntervalShortWritten(long(max(0, self.manualDeliveryTimestamp - now)))
            if stationsInSystem:
                path = 'UI/Inventory/AssetSafety/DeliveryNotAvailableNowExplanationText'
            else:
                path = 'UI/Inventory/AssetSafety/DeliveryNotAvailableTextNoStations'
            text = GetByLabel(path, solarSystemName=solarSystemName, timUntilManualDelivery=timeUntilManual, npcStationName=nearestNPCStationText, timeUntilAutoDelivery=timeUntilAuto)
        self.explanationLabel.text = text

    def OnContainerResized(self):
        self.width = self.default_width
        self.height = self.container.height + self.PADDING * 2

    def ReloadContent(self):
        if self.destroyed:
            return
        self.sameSolarSystem.DisableAutoSize()
        self.sameSolarSystem.Flush()
        systemStations, nearestNPCStation = sm.RemoteSvc('structureAssetSafety').GetStructuresICanDeliverTo(self.solarSystemID)
        self.SetText(systemStations)
        if systemStations:
            stationIDs = [ station['itemID'] for station in systemStations ]
            cfg.evelocations.Prime(stationIDs)
            stations = [ s for s in systemStations if evetypes.GetCategoryID(s['typeID'] == const.categoryStation) ]
            sortedStations = GetSortedStationList(self.solarSystemID, systemStations)
            otherStructures = GetSortedStructures(self.solarSystemID, systemStations)
            buttonIsDisabled = self.manualDeliveryTimestamp - blue.os.GetWallclockTime() > 0
            for each in otherStructures + sortedStations:
                self.AddStation(each, buttonIsDisabled)

        self.sameSolarSystem.EnableAutoSize()
        self.sameSolarSystemParent.height = min(MAX_STATIONCONT_HEIGHT, self.sameSolarSystem.height)

    def AddStation(self, station, buttonIsDisabled):
        parent = self.sameSolarSystem
        container = ContainerAutoSize(parent=parent, align=uiconst.TOTOP, alignMode=uiconst.TOTOP, state=uiconst.UI_PICKCHILDREN, bgColor=(0.2, 0.2, 0.2, 0.3))
        container.DisableAutoSize()
        label = GetShowInfoLink(station['typeID'], station['name'], station['itemID'])
        EveLabelMediumBold(parent=container, height=30, align=uiconst.TOTOP, state=uiconst.UI_NORMAL, text=label, padding=(7, 8, 140, 5))
        btn = Button(parent=container, label=GetByLabel('UI/Inventory/AssetSafety/DeliverBtn'), align=uiconst.CENTERRIGHT, fontsize=13, fixedwidth=140, fixedheight=25, pos=(5, 0, 0, 0), func=self.DoDeliver, args=station['itemID'])
        if buttonIsDisabled:
            btn.Disable()
        Line(parent=parent, align=uiconst.TOTOP, color=self.LINE_COLOR)
        container.EnableAutoSize()

    def DoDeliver(self, *args):
        if eve.Message('SureYouWantToMoveAssetSafetyItemsToLocation', {}, uiconst.YESNO) != uiconst.ID_YES:
            return
        try:
            sm.RemoteSvc('structureAssetSafety').MoveSafetyWrapToStructure(self.assetWrapID, self.solarSystemID, destinationID=args[0])
        finally:
            AssetSafetyDeliverWindow.CloseIfOpen()

        sm.GetService('objectCaching').InvalidateCachedMethodCall('structureAssetSafety', 'GetStructuresICanDeliverTo')
        sm.GetService('objectCaching').InvalidateCachedMethodCall('structureAssetSafety', 'GetItemsInSafety')
class AchievementAuraWindow(Window):
    __notifyevents__ = [
        'OnAchievementChanged', 'OnAchievementActiveGroupChanged'
    ]
    default_captionLabelPath = 'UI/Achievements/OpportunitiesHint'
    default_windowID = 'AchievementAuraWindow'
    default_width = WINDOW_WIDTH
    default_fixedWidth = default_width
    default_height = 64
    default_fixedHeight = default_height
    default_top = 200
    default_topParentHeight = 0
    aura = None
    activeStep = None
    animHeight = 0

    def ApplyAttributes(self, attributes):
        Window.ApplyAttributes(self, attributes)
        self.MakeUnMinimizable()
        self.MakeUnpinable()
        self.MakeUnstackable()
        mainArea = self.GetMainArea()
        mainArea.clipChildren = True
        leftSide = Container(parent=mainArea,
                             align=uiconst.TOLEFT,
                             width=AURA_SIZE * 0.8)
        auraSprite = Sprite(
            parent=leftSide,
            texturePath='res:/UI/Texture/classes/achievements/auraAlpha.png',
            pos=(0, -4, AURA_SIZE, AURA_SIZE),
            align=uiconst.CENTERTOP)
        self.mainContent = ContainerAutoSize(parent=self.GetMainArea(),
                                             align=uiconst.TOTOP,
                                             alignMode=uiconst.TOTOP,
                                             padding=(0, 6, 10, 10))
        self.sizeTimer = AutoTimer(10, self.UpdateWindowSize)
        if not settings.char.ui.Get('opportunities_aura_introduced', False):
            settings.char.ui.Set('opportunities_aura_introduced', True)
            self.Step_Intro()
        elif attributes.loadAchievementTask:
            self.Step_TaskInfo_Manual(attributes.loadAchievementTask,
                                      attributes.loadAchievementGroup)
        else:
            self.UpdateOpportunityState()

    def OpenOpportunitiesTree(self, *args):
        from achievements.client.achievementTreeWindow import AchievementTreeWindow
        AchievementTreeWindow.Open()

    def Prepare_HeaderButtons_(self, *args, **kwds):
        Window.Prepare_HeaderButtons_(self, *args, **kwds)

    def UpdateWindowSize(self):
        if self.destroyed:
            self.sizeTimer = None
            return
        headerHeight = self.GetCollapsedHeight()
        newheight = max(
            WINDOW_MIN_HEIGHT, headerHeight + self.mainContent.height +
            self.mainContent.padTop + self.mainContent.padBottom)
        if newheight != self.height:
            self.height = newheight
            self.SetFixedHeight(self.height)

    def OnAchievementChanged(self,
                             achievement,
                             activeGroupCompleted=False,
                             *args,
                             **kwds):
        self.UpdateOpportunityState(activeGroupCompleted=activeGroupCompleted)

    def OnAchievementActiveGroupChanged(self, groupID, *args, **kwargs):
        self.UpdateOpportunityState(activeGroupChanged=True)

    def CloseByUser(self, *args, **kwds):
        Window.CloseByUser(self, *args, **kwds)
        if self.activeStep == STEP_TASK_INFO:
            settings.char.ui.Set('opportunities_suppress_taskinfo', True)
        elif self.activeStep in (STEP_INTRO, STEP_INTRO2,
                                 STEP_PRESENT_OPPORTUNITY):
            sm.GetService('achievementSvc').SetActiveAchievementGroupID(None)

    def Step_Intro(self):
        self.mainContent.Flush()
        self.LoadMediumText(GetByLabel('Achievements/AuraText/intro'),
                            padRight=8)
        self.LoadButtons(
            ((GetByLabel('Achievements/UI/Accept'),
              self.Step_PresentOpportunity, None),
             (GetByLabel('Achievements/UI/Dismiss'), self.Close, None)))
        self.LoadTreeLink()
        self.SetOrder(0)
        self.activeStep = STEP_INTRO
        settings.char.ui.Set('opportunities_suppress_taskinfo', False)

    def Step_AskStart(self):
        self.mainContent.Flush()
        self.LoadLargeText(
            GetByLabel('Achievements/AuraText/IntroAfterDismissHeader'))
        self.LoadMediumText(
            GetByLabel('Achievements/AuraText/IntroAfterDismissText'))
        self.LoadButtons(
            ((GetByLabel('Achievements/UI/Accept'),
              self.Step_PresentOpportunity, None),
             (GetByLabel('Achievements/UI/Dismiss'), self.Close, None)))
        self.LoadTreeLink()
        self.SetCaption(GetByLabel('UI/Achievements/OpportunitiesHint'))
        self.SetOrder(0)
        self.activeStep = STEP_INTRO2

    def Step_ActiveCompleted(self):
        self.mainContent.Flush()
        self.LoadLargeText(
            GetByLabel('Achievements/AuraText/CompletedReactivatedHeader'))
        self.LoadMediumText(
            GetByLabel('Achievements/AuraText/CompletedReactivatedText'))
        self.LoadButtons(
            ((GetByLabel('Achievements/UI/Accept'),
              self.Step_PresentOpportunity, None),
             (GetByLabel('Achievements/UI/Dismiss'), self.Close, None)))
        self.LoadTreeLink()
        self.SetCaption(GetByLabel('UI/Achievements/OpportunitiesHint'))
        self.SetOrder(0)
        self.activeStep = STEP_COMPLETED_NEXT

    def Step_PresentOpportunity(self, *args):
        nextGroup = GetFirstIncompleteAchievementGroup()
        if not nextGroup:
            return self.Step_AllDone()
        self.mainContent.Flush()
        self.LoadLargeText(nextGroup.groupName)
        self.LoadDivider()
        self.LoadMediumText(nextGroup.groupDescription)
        self.LoadButtons(
            ((GetByLabel('Achievements/UI/Accept'),
              self.ActivateNextIncompleteOpportunity, (False, )),
             (GetByLabel('Achievements/UI/Dismiss'), self.Close, None)))
        self.LoadTreeLink()
        self.SetCaption(GetByLabel('Achievements/UI/NewOpportunity'))
        self.SetOrder(0)
        self.activeStep = STEP_PRESENT_OPPORTUNITY

    def Step_TaskInfo(self, achievementTask, activeGroup, manualLoad=False):
        self.mainContent.Flush()
        if activeGroup:
            self.SetCaption(activeGroup.groupName)
        self.LoadLargeText(achievementTask.name)
        self.LoadDivider()
        self.LoadMediumText(achievementTask.description)
        extraInfo = ACHIEVEMENT_TASK_EXTRAINFO.get(
            achievementTask.achievementID, None)
        if extraInfo:
            grid = LayoutGrid(parent=self.mainContent,
                              align=uiconst.TOTOP,
                              cellPadding=2,
                              columns=2)
            for taskInfoEntry in extraInfo:
                if isinstance(taskInfoEntry, TaskInfoEntry_Text):
                    label = EveLabelMedium(text=taskInfoEntry.text,
                                           color=taskInfoEntry.textColor,
                                           width=200)
                    grid.AddCell(label, colSpan=2)
                elif isinstance(taskInfoEntry, TaskInfoEntry_ImageText):
                    texturePath = taskInfoEntry.GetTexturePath()
                    icon = Sprite(name='icon',
                                  parent=grid,
                                  pos=(0, 0, taskInfoEntry.imageSize,
                                       taskInfoEntry.imageSize),
                                  texturePath=texturePath,
                                  state=uiconst.UI_DISABLED,
                                  align=uiconst.CENTER,
                                  color=taskInfoEntry.imageColor)
                    text = GetByLabel(taskInfoEntry.textPath)
                    label = EveLabelMedium(text=text,
                                           color=taskInfoEntry.textColor,
                                           width=180,
                                           align=uiconst.CENTERLEFT)
                    grid.AddCell(label)

        self.LoadTreeLink()
        self.SetOrder(0)
        settings.char.ui.Set('opportunities_suppress_taskinfo', False)
        if manualLoad:
            self.activeStep = STEP_TASK_INFO_MANUAL
        else:
            self.activeStep = STEP_TASK_INFO

    def Step_TaskInfo_Manual(self, achievementTask, achievementGroup):
        self.Step_TaskInfo(achievementTask, achievementGroup, manualLoad=True)

    def Step_AllDone(self):
        self.mainContent.Flush()
        self.LoadLargeText(
            GetByLabel('Achievements/AuraText/AllCompletedHeader'))
        self.LoadMediumText(
            GetByLabel('Achievements/AuraText/AllCompletedText'))
        self.LoadButtons(
            ((GetByLabel('Achievements/UI/Accept'), self.ActivateCareerFunnel,
              (False, )), (GetByLabel('Achievements/UI/Dismiss'), self.Close,
                           None)))
        self.SetCaption(GetByLabel('UI/Achievements/OpportunitiesHint'))
        self.SetOrder(0)
        self.activeStep = STEP_ALL_DONE

    def ActivateNextIncompleteOpportunity(self, emphasize, **kwargs):
        nextGroup = GetFirstIncompleteAchievementGroup()
        if nextGroup:
            if True:
                self.Close()
            sm.GetService('achievementSvc').SetActiveAchievementGroupID(
                nextGroup.groupID, emphasize=emphasize)
        else:
            self.UpdateOpportunityState()

    def ActivateCareerFunnel(self, *args):
        self.Close()
        sm.GetService('achievementSvc').SetActiveAchievementGroupID(None)
        sm.StartService('tutorial').ShowCareerFunnel()

    def UpdateOpportunityState(self,
                               activeGroupChanged=False,
                               activeGroupCompleted=False):
        activeGroup = GetActiveAchievementGroup()
        nextGroup = GetFirstIncompleteAchievementGroup()
        if activeGroup:
            nextTask = activeGroup.GetNextIncompleteTask()
            if nextTask:
                self.Step_TaskInfo(nextTask, activeGroup)
                return
            if nextGroup:
                if activeGroupCompleted:
                    self.Step_PresentOpportunity()
                else:
                    self.Step_ActiveCompleted()
                return
        elif nextGroup:
            if self.activeStep not in (STEP_INTRO, STEP_INTRO2,
                                       STEP_PRESENT_OPPORTUNITY):
                self.Step_AskStart()
            return
        self.Step_AllDone()

    def LoadDivider(self):
        divider = Sprite(
            parent=self.mainContent,
            height=1,
            align=uiconst.TOTOP,
            texturePath=
            'res:/UI/Texture/classes/achievements/divider_horizontal.png',
            color=(1, 1, 1, 0.3),
            padding=(0, 2, 0, 2))

    def LoadLargeText(self, text, *args, **kwargs):
        label = Label(parent=self.mainContent,
                      text=text,
                      align=uiconst.TOTOP,
                      fontsize=18,
                      **kwargs)

    def LoadMediumText(self, text, *args, **kwargs):
        label = EveLabelMedium(parent=self.mainContent,
                               text=text,
                               align=uiconst.TOTOP,
                               **kwargs)

    def LoadButton(self, label, func, args=None):
        buttonContainer = Container(parent=self.mainContent,
                                    align=uiconst.TOTOP)
        button = Button(parent=buttonContainer,
                        label=label,
                        func=func,
                        args=args,
                        align=uiconst.CENTERLEFT)
        buttonContainer.height = button.height + 8

    def LoadButtons(self, buttonData):
        buttonContainer = FlowContainer(parent=self.mainContent,
                                        align=uiconst.TOTOP,
                                        padTop=14,
                                        contentSpacing=(4, 4),
                                        contentAlignment=CONTENT_ALIGN_RIGHT)
        for label, func, args in buttonData:
            button = Button(parent=buttonContainer,
                            label=label,
                            func=func,
                            args=args,
                            align=uiconst.NOALIGN)

    def LoadTreeLink(self):
        buttonContainer = ContainerAutoSize(parent=self.mainContent,
                                            align=uiconst.TOTOP)
        textButton = IconTextButton(
            parent=buttonContainer,
            align=uiconst.TOPRIGHT,
            label=GetByLabel('Achievements/UI/showAll'),
            texturePath=
            'res:/ui/Texture/Classes/InfoPanels/opportunitiesTreeIcon.png',
            func=self.OpenOpportunitiesTree,
            iconSize=16,
            top=10)
Пример #23
0
class ProcessorContainer(BasePinContainer):
    __guid__ = 'planet.ui.ProcessorContainer'
    default_name = 'ProcessorContainer'
    default_width = 320
    INFO_CONT_HEIGHT = 95

    def _GetActionButtons(self):
        btns = [
            util.KeyVal(id=planetCommon.PANEL_SCHEMATICS,
                        panelCallback=self.PanelShowSchematics),
            util.KeyVal(id=planetCommon.PANEL_PRODUCTS,
                        panelCallback=self.PanelShowProducts)
        ]
        btns.extend(BasePinContainer._GetActionButtons(self))
        return btns

    def PanelShowSchematics(self):
        self.schematicsCont = uiprimitives.Container(parent=self.actionCont,
                                                     name='schematicsCont',
                                                     align=uiconst.TOALL,
                                                     state=uiconst.UI_HIDDEN)
        self.schematicsScroll = uicontrols.Scroll(parent=self.schematicsCont,
                                                  name='schematicsScroll',
                                                  align=uiconst.TOALL)
        self.schematicsScroll.Startup()
        self.schematicsScroll.sr.id = 'planetProcessorSchematicsScroll'
        self.schematicsScroll.multiSelect = False
        self.schematicsScroll.OnSelectionChange = self.OnSchematicScrollSelectionChange
        self.selectedSchematicCont = uiprimitives.Container(
            parent=self.schematicsCont,
            idx=0,
            name='selectedSchematicCont',
            height=138,
            padTop=7,
            align=uiconst.TOBOTTOM,
            state=uiconst.UI_PICKCHILDREN)
        self.LoadSchematicsScroll()
        return self.schematicsCont

    def LoadSchematicsScroll(self):
        scrolllist = []
        for schematic in planetCommon.GetSchematicData(self.pin.typeID):
            data = util.KeyVal(label=schematic.name,
                               schematic=schematic,
                               itemID=None,
                               typeID=schematic.outputs[0].typeID,
                               getIcon=True,
                               OnClick=None,
                               OnDblClick=self.InstallSchematic)
            sortBy = schematic.name
            scrolllist.append((sortBy, listentry.Get('Item', data=data)))

        scrolllist = uiutil.SortListOfTuples(scrolllist)
        self.schematicsScroll.Load(contentList=scrolllist, headers=[])
        self.schematicsScroll.SetSelected(0)

    def OnSchematicScrollSelectionChange(self, entries):
        if not entries:
            return
        entry = entries[0]
        uicore.animations.FadeOut(self.selectedSchematicCont,
                                  duration=0.125,
                                  sleep=True)
        self.selectedSchematicCont.Flush()
        self.SubPanelSelectedSchematic(entry.schematic)
        uicore.animations.FadeIn(self.selectedSchematicCont, duration=0.125)

    def SubPanelSelectedSchematic(self, schematic):
        leftCont = uiprimitives.Container(parent=self.selectedSchematicCont,
                                          width=0.5,
                                          align=uiconst.TOLEFT_PROP,
                                          state=uiconst.UI_PICKCHILDREN)
        rightCont = uiprimitives.Container(parent=self.selectedSchematicCont,
                                           width=0.5,
                                           align=uiconst.TOLEFT_PROP,
                                           state=uiconst.UI_PICKCHILDREN)
        output = schematic.outputs[0]
        schematicTxt = localization.GetByLabel('UI/PI/Common/ItemAmount',
                                               amount=int(output.quantity),
                                               itemName=output.name)
        CaptionAndSubtext(
            parent=leftCont,
            caption=localization.GetByLabel('UI/PI/Common/OutputProduct'),
            subtext=schematicTxt,
            iconTypeID=output.typeID,
            left=5,
            top=0)
        CaptionAndSubtext(
            parent=leftCont,
            caption=localization.GetByLabel('UI/PI/Common/CycleTime'),
            subtext=localization.GetByLabel('UI/PI/Common/TimeHourMinSec',
                                            time=schematic.cycleTime *
                                            const.SEC),
            left=5,
            top=40)
        outputVolumeTxt = localization.GetByLabel(
            'UI/PI/Common/CapacityAmount', amount=schematic.outputVolume)
        CaptionAndSubtext(
            parent=leftCont,
            caption=localization.GetByLabel('UI/PI/Common/OutputPerHour'),
            subtext=outputVolumeTxt,
            left=5,
            top=80)
        for i, input in enumerate(schematic.inputs):
            topPos = i * 40
            caption = localization.GetByLabel('UI/PI/Common/InputNumberX',
                                              inputNum=i + 1)
            subtext = localization.GetByLabel('UI/PI/Common/ItemAmount',
                                              amount=int(input.quantity),
                                              itemName=evetypes.GetName(
                                                  input.typeID))
            CaptionAndSubtext(parent=rightCont,
                              caption=caption,
                              subtext=subtext,
                              iconTypeID=input.typeID,
                              top=topPos)

        btns = [[
            localization.GetByLabel('UI/PI/Common/InstallSchematic'),
            self.InstallSchematic, ()
        ]]
        self.buttons = uicontrols.ButtonGroup(
            btns=btns,
            idx=0,
            parent=self.selectedSchematicCont,
            line=False,
            alwaysLite=True)

    def InstallSchematic(self, *args):
        entries = self.schematicsScroll.GetSelected()
        if not entries:
            return
        entry = entries[0]
        schematicID = entry.schematic.schematicID
        self.planetUISvc.myPinManager.InstallSchematic(self.pin.id,
                                                       schematicID)
        self.RenderIngredientGauges()
        self.ShowPanel(self.PanelShowProducts, planetCommon.PANEL_PRODUCTS)

    def _GetInfoCont(self):
        self.currProductTxt = CaptionAndSubtext(
            parent=self.infoContLeft,
            caption=localization.GetByLabel('UI/PI/Common/Producing'))
        self.ingredientsTxt = CaptionAndSubtext(
            parent=self.infoContLeft,
            caption=localization.GetByLabel('UI/PI/Common/SchematicInput'),
            top=50)
        self.ingredientsTxt.state = uiconst.UI_DISABLED
        self.ingredientCont = ContainerAutoSize(parent=self.infoContLeft,
                                                top=63,
                                                state=uiconst.UI_PICKCHILDREN)
        self.RenderIngredientGauges()
        self.currCycleGauge = uicls.Gauge(
            parent=self.infoContRight,
            value=0.0,
            color=planetCommon.PLANET_COLOR_CYCLE,
            width=140)
        self.amountPerCycleTxt = CaptionAndSubtext(
            parent=self.infoContRight,
            caption=localization.GetByLabel('UI/PI/Common/OutputPerCycle'),
            top=40)
        self.amountPerHourTxt = CaptionAndSubtext(
            parent=self.infoContRight,
            caption=localization.GetByLabel('UI/PI/Common/OutputPerHour'),
            top=70)

    def RenderIngredientGauges(self):
        self.ingredientCont.Flush()
        self.ingredientGauges = {}
        i = 0
        for typeID, amount in self.pin.GetConsumables().iteritems():
            gauge = ProcessorGaugeContainer(parent=self.ingredientCont,
                                            iconTypeID=typeID,
                                            maxAmount=amount,
                                            top=0,
                                            left=i * 24)
            self.ingredientGauges[typeID] = gauge
            i += 1

        if not self.pin.GetConsumables():
            self.ingredientsTxt.SetSubtext(
                localization.GetByLabel('UI/PI/Common/NoSchematicSelected'))
        else:
            self.ingredientsTxt.SetSubtext('')

    def _UpdateInfoCont(self):
        if self.pin.schematicID:
            schematicObj = cfg.schematics.Get(self.pin.schematicID)
            schematicName = schematicObj.schematicName
            for t in cfg.schematicstypemap.get(self.pin.schematicID, []):
                if not t.isInput:
                    outputPerCycle = t.quantity
                    outputTypeID = t.typeID

            if self.pin.activityState < basePin.STATE_IDLE:
                currCycle = 0
                currCycleProportion = 0.0
                status = localization.GetByLabel('UI/Common/Inactive')
            elif self.pin.IsActive():
                nextCycle = self.pin.GetNextRunTime()
                if nextCycle is None or nextCycle < blue.os.GetWallclockTime():
                    status = localization.GetByLabel(
                        'UI/PI/Common/ProductionCompletionImminent')
                else:
                    status = localization.GetByLabel(
                        'UI/PI/Common/InProduction')
                currCycle = self.pin.GetCycleTime() - (
                    self.pin.GetNextRunTime() - blue.os.GetWallclockTime())
                currCycleProportion = currCycle / float(
                    self.pin.GetCycleTime())
            else:
                status = localization.GetByLabel(
                    'UI/PI/Common/WaitingForResources')
                currCycle = 0
                currCycleProportion = 0.0
        else:
            schematicName = localization.GetByLabel(
                'UI/PI/Common/NothingExtracted')
            status = localization.GetByLabel('UI/Common/Inactive')
            currCycleProportion = 0.0
            currCycle = 0
            outputPerCycle = 0
            outputTypeID = None
        for typeID, amountNeeded in self.pin.GetConsumables().iteritems():
            amount = self.pin.GetContents().get(typeID, 0)
            gauge = self.ingredientGauges.get(typeID)
            if not gauge:
                continue
            gauge.SetValue(float(amount) / amountNeeded)
            name = evetypes.GetName(typeID)
            gauge.hint = localization.GetByLabel(
                'UI/PI/Common/ProductionGaugeHint',
                resourceName=name,
                amount=amount,
                amountNeeded=amountNeeded)

        self.currProductTxt.SetSubtext(schematicName)
        if self.pin.schematicID:
            if self.pin.activityState < basePin.STATE_IDLE:
                self.currCycleGauge.SetSubText(
                    localization.GetByLabel('UI/PI/Common/InactiveEditMode'))
            else:
                self.currCycleGauge.SetSubText(
                    localization.GetByLabel('UI/PI/Common/CycleTimeElapsed',
                                            currTime=long(currCycle),
                                            totalTime=self.pin.GetCycleTime()))
        self.currProductTxt.SetIcon(outputTypeID)
        self.currCycleGauge.SetValueInstantly(currCycleProportion)
        self.currCycleGauge.SetText(status)
        self.amountPerCycleTxt.SetSubtext(
            localization.GetByLabel('UI/PI/Common/UnitsAmount',
                                    amount=outputPerCycle))
        self.amountPerHourTxt.SetSubtext(
            localization.GetByLabel('UI/PI/Common/CapacityAmount',
                                    amount=self.pin.GetOutputVolumePerHour()))
Пример #24
0
class MaterialGroup(Container):
    default_name = 'MaterialGroup'
    default_height = 60
    default_alignMode = uiconst.TOPLEFT
    default_align = uiconst.TOPLEFT

    def ApplyAttributes(self, attributes):
        Container.ApplyAttributes(self, attributes)
        self.jobData = attributes.jobData
        self.materialsData = attributes.materialsData
        self.numRows = attributes.numRows
        self.industryGroupID = attributes.industryGroupID
        self.perRow = self.GetNumPerRow()
        self.materials = []
        self.lines = []
        self.connectorCircle = None
        self.pCircleIntersect = None
        self.materialsCont = ContainerAutoSize(name='materialsCont',
                                               parent=self,
                                               align=uiconst.TOPLEFT,
                                               alignMode=uiconst.TOPLEFT)
        self.icon = GroupIconSprite(name='icon',
                                    parent=self,
                                    align=uiconst.CENTERLEFT,
                                    pos=(7, 0, 22, 22),
                                    industryGroupID=self.industryGroupID)
        self.ConstructMaterials()
        self.ConstructLines()

    def AnimEntry(self, timeOffset, animate=True):
        for i, material in enumerate(self.materials):
            if animate:
                uicore.animations.FadeTo(material,
                                         0.0,
                                         1.0,
                                         duration=0.3,
                                         timeOffset=timeOffset + i * 0.02)
            else:
                material.opacity = 1.0

        for i, line in enumerate(self.lines):
            line.AnimEntry(timeOffset, i, animate)

        if animate:
            uicore.animations.FadeTo(self.connectorCircle,
                                     0.0,
                                     1.0,
                                     duration=0.3,
                                     timeOffset=timeOffset)
        else:
            self.connectorCircle.opacity = 1.0

    def ConstructLines(self):
        for line in self.lines:
            line.Close()

        self.lines = []
        usedRows = int(ceil(len(self.materialsData) / float(self.perRow)))
        pointsStart = self.GetLineStartingPoints()
        pConnect = self.GetLineConnectionPoint(pointsStart)
        y = self.top + self.materialsCont.top + self.materialsCont.height / 2
        x = self.GetLineCirceOffset(y)
        width, height = self.parent.GetCurrentAbsoluteSize()
        self.pCircleIntersect = (width / 2 - x, pConnect[1])
        pEnd = geo2.Vec2Subtract(self.pCircleIntersect,
                                 (1 * RADIUS_CONNECTOR_SMALL, 0))
        if len(pointsStart) == 1:
            self.DrawLine((pointsStart[0], pEnd))
        else:
            for point in pointsStart:
                if point[1] == pEnd[1]:
                    self.DrawLine((point, geo2.Vec2Subtract(pConnect, (3, 0))))
                else:
                    self.DrawLine((point, (pConnect[0], point[1]), pConnect))

            self.DrawLine((geo2.Vec2Add(pConnect, (3, 0)), pEnd))
        if not self.connectorCircle:
            self.connectorCircle = MaterialGroupDashedCircle(
                parent=self.materialsCont,
                numSegments=len(self.materialsData),
                radius=RADIUS_CONNECTOR_SMALL,
                materialsByGroupID=((self.industryGroupID,
                                     self.materialsData), ),
                jobData=self.jobData)
        self.connectorCircle.left = pEnd[0]
        self.connectorCircle.top = pEnd[1] - RADIUS_CONNECTOR_SMALL
        self.UpdateState(animate=False)

    def DrawLine(self, points):
        line = IndustryLineTrace(parent=self.materialsCont)
        line.AddPoints(points)
        self.lines.append(line)

    def GetEndPoint(self):
        return self.pCircleIntersect

    def ConstructMaterials(self):
        for i, materialData in enumerate(self.materialsData):
            top = 66 * (i / self.perRow)
            cls = self.GetMaterialClass()
            material = cls(parent=self.materialsCont,
                           jobData=self.jobData,
                           materialData=materialData,
                           align=uiconst.TOPLEFT,
                           left=ICONCOLUMN_WIDTH + i % self.perRow * 48,
                           top=top)
            self.materials.append(material)

        self.materialsCont.SetSizeAutomatically()
        self.materialsCont.top = (self.height - self.materialsCont.height) / 2

    def GetMaterialClass(self):
        if self.IsOptional():
            return OptionalMaterial
        else:
            return Material

    def IsOptional(self):
        for materialData in self.materialsData:
            if not materialData.IsOptional():
                return False

        return True

    def IsOptionSelected(self):
        """
        Returns True unless all items are optional and none of them have an item selected
        """
        for materialData in self.materialsData:
            if materialData.IsOptionSelected():
                return True

        return False

    def GetLineStartingPoints(self):
        ret = defaultdict(int)
        for material in self.materials:
            x = material.left + Material.default_width
            y = material.top + Material.default_height / 2
            ret[y] = max(ret[y], x)

        ret = zip(ret.values(), ret.keys())
        return ret

    def OnRunsChanged(self):
        self.UpdateState()

    def UpdateState(self, animate=True):
        for line in self.lines:
            line.UpdateColor(self.IsReady(), self.IsOptional(),
                             self.IsOptionSelected(), animate)

        numReadySegments = sum(
            [materialData.valid for materialData in self.materialsData])
        self.connectorCircle.UpdateState(numReadySegments,
                                         self.IsReady(),
                                         self.IsOptionSelected(),
                                         animate=animate)

    def GetNumPerRow(self):
        numMaterials = len(self.materialsData)
        if self.numRows >= 2:
            if numMaterials > 3:
                return min(5, int(ceil(numMaterials / 2.0)))
        return numMaterials

    def GetLineConnectionPoint(self, points):
        """
        Returs coordinates of point where all lines coming from the groups connect
        """
        x = max((x for x, _ in points))
        x += OFFSET_CONNECTIONPOINT
        y = sum((y for _, y in points)) / len(points)
        return (x, y)

    def GetLineCirceOffset(self, y):
        """
        Returns x-part of intersection line with outer circle
        """
        r = RADIUS_CENTERCIRCLE_OUTER
        y = float(y)
        return r * cos(asin((r - y) / r))

    def IsReady(self):
        """
        Are all materials in group owned in full quantity
        """
        for materialData in self.materialsData:
            if not materialData.valid:
                return False

        return True
Пример #25
0
 def ApplyAttributes(self, attributes):
     Window.ApplyAttributes(self, attributes)
     blueprintID = attributes.Get('blueprintID', None)
     blueprintTypeID = attributes.Get('blueprintTypeID', None)
     bpData = attributes.Get('bpData', None)
     self.history = HistoryBuffer()
     self.jobData = None
     self.pendingBlueprint = None
     self.loadBlueprintThread = None
     self.topCont = Container(name='topCont',
                              parent=self.sr.main,
                              align=uiconst.TOTOP,
                              height=TOP_HEIGHT,
                              clipChildren=True)
     self.currView = BaseView(parent=self.topCont,
                              align=uiconst.TOTOP,
                              height=VIEW_HEIGHT)
     self.jobsStrip = JobsStrip(parent=self.topCont,
                                align=uiconst.TOTOP,
                                padding=(5, -1, 7, 2),
                                callback=self.OnBlueprintsSelected)
     self.bottomCont = Container(name='bottomCont',
                                 parent=self.sr.main,
                                 controller=self,
                                 height=0.4,
                                 padding=(4, 0, 4, 0),
                                 callback=self.OnBlueprintsSelected)
     cont = ContainerAutoSize(name='historyArrowCont',
                              parent=self.sr.main,
                              align=uiconst.TOPRIGHT,
                              height=16,
                              left=3,
                              top=1)
     self.expandViewBtn = ButtonIcon(
         name='expandViewBtn',
         parent=cont,
         align=uiconst.TORIGHT,
         width=16,
         iconSize=7,
         texturePath='res:/UI/Texture/classes/Neocom/arrowDown.png',
         func=self.OnExpandViewBtn)
     self.goForwardBtn = ButtonIcon(
         name='goForwardBtn',
         parent=cont,
         align=uiconst.TORIGHT,
         width=16,
         iconSize=16,
         padRight=5,
         texturePath='res:/UI/Texture/icons/38_16_224.png',
         func=self.OnForward,
         hint=localization.GetByLabel('UI/Control/EveWindow/Next'))
     self.goBackBtn = ButtonIcon(
         name='goBackBtn',
         parent=cont,
         align=uiconst.TORIGHT,
         width=16,
         iconSize=16,
         texturePath='res:/UI/Texture/icons/38_16_223.png',
         func=self.OnBack,
         hint=localization.GetByLabel('UI/Control/EveWindow/Previous'))
     self.browserCont = Container(name='browserCont',
                                  parent=self.bottomCont,
                                  padding=(0, 2, 0, 2))
     self.browserBlueprints = BrowserBlueprints(
         parent=self.browserCont, callback=self.OnBlueprintsSelected)
     self.browserFacilities = BrowserFacilities(
         parent=self.browserCont, callback=self.OnFacilitySelected)
     self.browserJobs = BrowserJobs(parent=self.browserCont,
                                    callback=self.OnJobSelected)
     tabs = ((localization.GetByLabel('UI/Industry/Blueprints'),
              self.browserBlueprints, None, 'blueprints', None,
              GetByLabel('UI/Industry/TabBlueprints')),
             (localization.GetByLabel('UI/Industry/Facilities'),
              self.browserFacilities, None, 'facilities', None,
              GetByLabel('UI/Industry/TabFacilities')),
             (localization.GetByLabel('UI/Industry/Jobs'), self.browserJobs,
              None, 'jobs', None, GetByLabel('UI/Industry/TabJobs')))
     self.tabs = TabGroup(parent=self.browserCont,
                          tabs=tabs,
                          height=26,
                          labelPadding=12,
                          idx=0,
                          padLeft=0,
                          groupID='IndustryWindowBrowsers',
                          autoselecttab=not self.IsBrowserCollapsed())
     self.expandBottomBtn = ButtonIcon(
         name='expandBottomBtn',
         parent=self.bottomCont,
         align=uiconst.TOPRIGHT,
         pos=(2, -3, 16, 16),
         iconSize=7,
         texturePath='res:/UI/Texture/classes/Neocom/arrowDown.png',
         func=self.OnExpandBottomBtn)
     if blueprintID or blueprintTypeID:
         self.ShowBlueprint(blueprintID, blueprintTypeID, bpData=bpData)
     if self.IsViewCollapsed():
         self.CollapseView(animate=False)
     else:
         self.expandViewBtn.SetRotation(-pi)
     if self.IsBrowserCollapsed():
         self.CollapseBrowser(animate=False)
     else:
         self.expandBottomBtn.SetRotation(-pi)
     sm.GetService('audio').SendUIEvent('ind_windowOpened')
Пример #26
0
 def ConstructLayout(self):
     if self.isConstructed:
         return
     self.isConstructed = True
     scrollContainer = ScrollContainer(name='plexScroll',
                                       parent=self,
                                       align=uiconst.TOALL,
                                       padding=(10, 10, 10, 10))
     EveLabelLargeBold(
         parent=scrollContainer,
         align=uiconst.TOTOP,
         text=GetByLabel(
             'UI/CharacterSheet/CharacterSheetWindow/PilotLicense/PlexTitle'
         ),
         padding=(10, 10, 0, 0))
     EveLabelMedium(
         parent=scrollContainer,
         align=uiconst.TOTOP,
         text=GetByLabel(
             'UI/CharacterSheet/CharacterSheetWindow/PilotLicense/PlexDescription'
         ),
         padding=(10, 2, 0, 10),
         color=Color.GRAY5)
     subscription = ContainerAutoSize(parent=scrollContainer,
                                      align=uiconst.TOTOP,
                                      alignMode=uiconst.TOTOP,
                                      state=uiconst.UI_PICKCHILDREN,
                                      bgColor=(0, 0, 0, 0.3))
     self.plexSubscriptionLabel = EveLabelMedium(parent=subscription,
                                                 align=uiconst.TOTOP,
                                                 text='',
                                                 padding=(75, 15, 0, 15))
     InfoIcon(parent=subscription,
              typeID=const.typePilotLicence,
              pos=(10, 2, 55, 55),
              texturePath='res:/UI/Texture/Icons/plex.png',
              iconOpacity=1.0)
     InfoIcon(parent=subscription,
              align=uiconst.TOPRIGHT,
              typeID=const.typePilotLicence,
              top=10,
              left=10)
     EveLabelLargeBold(
         parent=scrollContainer,
         align=uiconst.TOTOP,
         text=GetByLabel(
             'UI/CharacterSheet/CharacterSheetWindow/PilotLicense/BuyingPlexTitle'
         ),
         padding=(10, 10, 0, 0))
     EveLabelMedium(
         parent=scrollContainer,
         align=uiconst.TOTOP,
         text=GetByLabel(
             'UI/CharacterSheet/CharacterSheetWindow/PilotLicense/BuyingPlexDescription'
         ),
         padding=(10, 2, 0, 10),
         color=Color.GRAY5)
     buyButtons = FlowContainer(parent=scrollContainer,
                                align=uiconst.TOTOP,
                                contentAlignment=CONTENT_ALIGN_CENTER,
                                contentSpacing=(8, 0))
     BuyButtonIsk(parent=buyButtons,
                  align=uiconst.NOALIGN,
                  typeID=const.typePilotLicence)
     BuyButtonPlex(parent=buyButtons,
                   align=uiconst.NOALIGN,
                   logContext='CharacterSheet')
     EveLabelLargeBold(
         parent=scrollContainer,
         align=uiconst.TOTOP,
         text=GetByLabel(
             'UI/CharacterSheet/CharacterSheetWindow/PilotLicense/MultipleCharacterTitle'
         ),
         padding=(10, 25, 0, 0))
     EveLabelMedium(
         parent=scrollContainer,
         align=uiconst.TOTOP,
         text=GetByLabel(
             'UI/CharacterSheet/CharacterSheetWindow/PilotLicense/MultipleCharacterDescription'
         ),
         padding=(10, 2, 0, 10),
         color=Color.GRAY5)
     multipleQueue1 = ContainerAutoSize(parent=scrollContainer,
                                        align=uiconst.TOTOP,
                                        alignMode=uiconst.TOTOP,
                                        state=uiconst.UI_PICKCHILDREN,
                                        bgColor=(0, 0, 0, 0.3))
     self.multipleQueueLabel1 = EveLabelMediumBold(parent=multipleQueue1,
                                                   align=uiconst.TOTOP,
                                                   text='',
                                                   padding=(35, 8, 0, 8))
     self.multipleQueueExpiryLabel1 = EveLabelMediumBold(
         parent=multipleQueue1,
         align=uiconst.TOPRIGHT,
         text='',
         pos=(10, 8, 0, 0),
         color=Color.GRAY5)
     self.multipleQueueIcon1 = Icon(
         parent=multipleQueue1,
         align=uiconst.TOPLEFT,
         icon='res:/UI/Texture/Icons/additional_training_queue.png',
         pos=(10, 7, 17, 17))
     multipleQueue2 = ContainerAutoSize(parent=scrollContainer,
                                        align=uiconst.TOTOP,
                                        alignMode=uiconst.TOTOP,
                                        state=uiconst.UI_PICKCHILDREN,
                                        bgColor=(0, 0, 0, 0.3))
     self.multipleQueueLabel2 = EveLabelMediumBold(parent=multipleQueue2,
                                                   align=uiconst.TOTOP,
                                                   text='',
                                                   padding=(35, 8, 0, 8))
     self.multipleQueueExpiryLabel2 = EveLabelMediumBold(
         parent=multipleQueue2,
         align=uiconst.TOPRIGHT,
         text='',
         pos=(10, 8, 0, 0),
         color=Color.GRAY5)
     self.multipleQueueIcon2 = Icon(
         parent=multipleQueue2,
         align=uiconst.TOPLEFT,
         icon='res:/UI/Texture/Icons/additional_training_queue.png',
         pos=(10, 7, 17, 17))
     EveLabelLargeBold(
         parent=scrollContainer,
         align=uiconst.TOTOP,
         text=GetByLabel(
             'UI/CharacterSheet/CharacterSheetWindow/PilotLicense/ConvertAurumTitle'
         ),
         padding=(10, 25, 0, 0))
     EveLabelMedium(
         parent=scrollContainer,
         align=uiconst.TOTOP,
         text=GetByLabel(
             'UI/CharacterSheet/CharacterSheetWindow/PilotLicense/ConvertAurumDescription'
         ),
         padding=(10, 2, 0, 0),
         color=Color.GRAY5)
     if boot.region != 'optic':
         EveLabelLargeBold(
             parent=scrollContainer,
             align=uiconst.TOTOP,
             text=GetByLabel(
                 'UI/CharacterSheet/CharacterSheetWindow/PilotLicense/CharacterTransferTitle'
             ),
             padding=(10, 25, 0, 0))
         EveLabelMedium(
             parent=scrollContainer,
             align=uiconst.TOTOP,
             text=GetByLabel(
                 'UI/CharacterSheet/CharacterSheetWindow/PilotLicense/CharacterTransferDescription'
             ),
             padding=(10, 2, 0, 0),
             color=Color.GRAY5)
     FillThemeColored(parent=self,
                      colorType=uiconst.COLORTYPE_UIHILIGHT,
                      opacity=0.1)
Пример #27
0
class ScrollContainer(Container):
    __guid__ = 'uicls.ScrollContainer'
    default_name = 'scrollContainer'
    default_pushContent = True
    default_state = uiconst.UI_NORMAL
    default_showUnderlay = False
    dragHoverScrollAreaSize = 30
    dragHoverScrollSpeed = 60.0
    isTabStop = True

    def ApplyAttributes(self, attributes):
        Container.ApplyAttributes(self, attributes)
        pushContent = attributes.get('pushContent', self.default_pushContent)
        showUnderlay = attributes.Get('showUnderlay', self.default_showUnderlay)
        self.scrollbarsDisabled = False
        self.scrollToVerticalPending = None
        self.scrollToHorizontalPending = None
        self.noContentHint = None
        self.verticalScrollBar = ScrollBar(parent=self, align=uiconst.TORIGHT if pushContent else uiconst.TORIGHT_NOPUSH)
        self.verticalScrollBar.OnScrolled = self._OnVerticalScrollBar
        self.horizontalScrollBar = ScrollBar(parent=self, align=uiconst.TOBOTTOM if pushContent else uiconst.TOBOTTOM_NOPUSH)
        self.horizontalScrollBar.OnScrolled = self._OnHorizontalScrollBar
        self.clipCont = Container(name='clipCont', parent=self, clipChildren=True)
        self.mainCont = ContainerAutoSize(name='mainCont', parent=self.clipCont, state=uiconst.UI_NORMAL)
        self.mainCont._OnSizeChange_NoBlock = self._OnMainContSizeChange
        self.children.insert = self._InsertChild
        self.children.append = self._AppendChild
        self.children.remove = self._RemoveChild
        self._mouseHoverCookie = uicore.uilib.RegisterForTriuiEvents(uiconst.UI_MOUSEHOVER, self.OnGlobalMouseHover)
        if showUnderlay:
            self.underlay = BumpedUnderlay(bgParent=self)
        else:
            self.underlay = None

    def Close(self, *args):
        uicore.uilib.UnregisterForTriuiEvents(self._mouseHoverCookie)
        Container.Close(self, *args)

    def _InsertChild(self, idx, obj):
        self.mainCont.children.insert(idx, obj)
        self.mainCont.align = obj.align

    def _AppendChild(self, obj):
        self.mainCont.children.append(obj)
        self.mainCont.align = obj.align

    def _RemoveChild(self, obj):
        self.mainCont.children.remove(obj)

    def OnGlobalMouseHover(self, obj, *args):
        if uicore.IsDragging() and (obj == self or obj.IsUnder(self.mainCont)):
            l, t, w, h = self.GetAbsolute()
            if self.verticalScrollBar.display and h > 0:
                fraction = self.dragHoverScrollSpeed / float(h)
                y = uicore.uilib.y - t
                if y <= self.dragHoverScrollAreaSize:
                    self.ScrollMoveVertical(-fraction)
                    self.verticalScrollBar.AnimFade()
                elif y > h - self.dragHoverScrollAreaSize:
                    self.ScrollMoveVertical(fraction)
                    self.verticalScrollBar.AnimFade()
            if self.horizontalScrollBar.display and w > 0:
                fraction = self.dragHoverScrollSpeed / float(w)
                x = uicore.uilib.x - l
                if x <= self.dragHoverScrollAreaSize:
                    self.ScrollMoveHorizontal(-fraction)
                    self.horizontalScrollBar.AnimFade()
                elif x > w - self.dragHoverScrollAreaSize:
                    self.ScrollMoveHorizontal(fraction)
                    self.horizontalScrollBar.AnimFade()
        return True

    def _OnSizeChange_NoBlock(self, width, height):
        self._UpdateHandleSizesAndPosition(width, height, updatePos=False)

    def _OnMainContSizeChange(self, width, height):
        self._UpdateScrollbars()

    def Flush(self):
        self.mainCont.Flush()

    def DisableScrollbars(self):
        self.scrollbarsDisabled = True
        self._UpdateScrollbars()

    def EnableScrollbars(self):
        self.scrollbarsDisabled = False
        self._UpdateScrollbars()

    def _UpdateScrollbars(self):
        w, h = self.GetAbsoluteSize()
        self._UpdateHandleSizesAndPosition(w, h)

    def _UpdateHandleSizesAndPosition(self, width, height, updatePos = True):
        if self.mainCont.height > 0 and not self.scrollbarsDisabled:
            size = float(height) / self.mainCont.height
        else:
            size = 1.0
        self.verticalScrollBar.SetScrollHandleSize(size)
        if updatePos:
            denum = self.mainCont.height - height
            if denum <= 0.0:
                pos = 0.0
            else:
                pos = float(-self.mainCont.top) / denum
            self.verticalScrollBar.ScrollTo(pos)
        else:
            pos = self.verticalScrollBar.handlePos
        self._OnVerticalScrollBar(pos)
        if self.mainCont.width != 0 and not self.scrollbarsDisabled:
            size = float(width) / self.mainCont.width
        else:
            size = 1.0
        self.horizontalScrollBar.SetScrollHandleSize(size)
        if updatePos:
            denum = self.mainCont.width - width
            if denum <= 0.0:
                pos = 0.0
            else:
                pos = float(-self.mainCont.left) / denum
            self.horizontalScrollBar.ScrollTo(pos)
        else:
            pos = self.horizontalScrollBar.handlePos
        self._OnHorizontalScrollBar(pos)
        if self.horizontalScrollBar.display and self.verticalScrollBar.display:
            self.verticalScrollBar.padBottom = self.horizontalScrollBar.height
        else:
            self.verticalScrollBar.padBottom = 0

    def _OnVerticalScrollBar(self, posFraction):
        w, h = self.clipCont.GetAbsoluteSize()
        posFraction = max(0.0, min(posFraction, 1.0))
        self.mainCont.top = -posFraction * (self.mainCont.height - h)
        self.OnScrolledVertical(posFraction)

    def _OnHorizontalScrollBar(self, posFraction):
        w, h = self.clipCont.GetAbsoluteSize()
        posFraction = max(0.0, min(posFraction, 1.0))
        self.mainCont.left = -posFraction * (self.mainCont.width - w)
        self.OnScrolledHorizontal(posFraction)

    def OnScrolledHorizontal(self, posFraction):
        pass

    def OnScrolledVertical(self, posFraction):
        pass

    def ScrollToVertical(self, posFraction):
        if self._alignmentDirty:
            self.scrollToVerticalPending = posFraction
        elif self.verticalScrollBar.display:
            self.verticalScrollBar.ScrollTo(posFraction)
            self._OnVerticalScrollBar(self.verticalScrollBar.handlePos)

    def ScrollToHorizontal(self, posFraction):
        if self._alignmentDirty:
            self.scrollToHorizontalPending = posFraction
        elif self.horizontalScrollBar.display:
            self.horizontalScrollBar.ScrollTo(posFraction)
            self._OnHorizontalScrollBar(self.horizontalScrollBar.handlePos)

    def GetPositionVertical(self):
        return self.verticalScrollBar.handlePos

    def GetPositionHorizontal(self):
        return self.horizontalScrollBar.handlePos

    def UpdateAlignment(self, *args, **kwds):
        ret = Container.UpdateAlignment(self, *args, **kwds)
        if self.scrollToVerticalPending:
            self.verticalScrollBar.ScrollTo(self.scrollToVerticalPending)
            self._OnVerticalScrollBar(self.verticalScrollBar.handlePos)
        self.scrollToVerticalPending = None
        if self.scrollToHorizontalPending:
            self.horizontalScrollBar.ScrollTo(self.scrollToHorizontalPending)
            self._OnHorizontalScrollBar(self.horizontalScrollBar.handlePos)
        self.scrollToHorizontalPending = None
        return ret

    def ScrollMoveVertical(self, moveFraction):
        self.verticalScrollBar.ScrollMove(moveFraction)
        self._OnVerticalScrollBar(self.verticalScrollBar.handlePos)

    def ScrollMoveHorizontal(self, moveFraction):
        self.horizontalScrollBar.ScrollMove(moveFraction)
        self._OnHorizontalScrollBar(self.horizontalScrollBar.handlePos)

    def OnMouseWheel(self, dz):
        if self.verticalScrollBar.display:
            prop = -dz / float(self.mainCont.height)
            if math.fabs(prop) < 0.1:
                prop = math.copysign(0.1, prop)
            self.ScrollMoveVertical(prop)
            self.verticalScrollBar.AnimFade()
        elif self.horizontalScrollBar.display:
            prop = -dz / float(self.mainCont.width)
            if math.fabs(prop) < 0.1:
                prop = math.copysign(0.1, prop)
            self.ScrollMoveHorizontal(prop)
            self.horizontalScrollBar.AnimFade()

    def OnKeyDown(self, key, flag):
        if key == uiconst.VK_PRIOR:
            self.ScrollByPage(up=True)
        elif key == uiconst.VK_NEXT:
            self.ScrollByPage(up=False)

    def ScrollByPage(self, up = True):
        if not self.verticalScrollBar.display:
            return
        w, h = self.clipCont.GetAbsoluteSize()
        if up:
            mainContTopNewTop = self.mainCont.top + h
            mainContTopNewTop = min(0, mainContTopNewTop)
        else:
            mainContTopNewTop = self.mainCont.top - h
            mainContTopNewTop = max(h - self.mainCont.height, mainContTopNewTop)
        self.mainCont.top = mainContTopNewTop
        self._UpdateScrollbars()
        self.verticalScrollBar.AnimFade()

    def ShowNoContentHint(self, text):
        self.noContentHint = Label(parent=self, align=uiconst.TOTOP, padding=(16, 32, 16, 0), text=text, fontsize=20, uppercase=True, letterspace=1)

    def HideNoContentHint(self):
        if self.noContentHint:
            self.noContentHint.Close()
            self.noContentHint = None

    def OnSetFocus(self, *args):
        if self.underlay:
            self.underlay.AnimEntry()

    def OnKillFocus(self, *args):
        if self.underlay:
            self.underlay.AnimExit()
Пример #28
0
 def ApplyAttributes(self, attributes):
     Container.ApplyAttributes(self, attributes)
     sm.RegisterNotify(self)
     self.jobData = attributes.jobData
     self.newNumRuns = None
     self.setJobRunsThread = None
     self.oldJobData = None
     self.numericInputTimer = None
     self.iconCont = ItemIcon(parent=self,
                              align=uiconst.CENTER,
                              state=uiconst.UI_DISABLED,
                              width=64,
                              height=64,
                              opacity=0.0)
     self.errorFrame = ErrorFrame(parent=self,
                                  align=uiconst.CENTER,
                                  state=uiconst.UI_DISABLED,
                                  width=80,
                                  height=80)
     self.ConstructBackground()
     self.runsCont = ContainerAutoSize(parent=self,
                                       align=uiconst.CENTER,
                                       top=100)
     self.runsCaption = IndustryCaptionLabel(
         name='runsCaption',
         parent=self.runsCont,
         align=uiconst.CENTERTOP,
         text=GetByLabel('UI/Industry/JobRuns'))
     self.runsEdit = BlueprintSingleLineEdit(parent=self.runsCont,
                                             align=uiconst.CENTERTOP,
                                             pos=(0, 12, 62, 0),
                                             OnChange=self.OnRunsEdit,
                                             autoselect=True)
     self.runsPerCopyCont = ContainerAutoSize(name='runsPerCopyCont',
                                              parent=self.runsCont,
                                              align=uiconst.CENTERTOP,
                                              top=38,
                                              state=uiconst.UI_HIDDEN)
     IndustryCaptionLabel(name='runsPerCopyCaption',
                          parent=self.runsPerCopyCont,
                          align=uiconst.CENTERTOP,
                          text=GetByLabel('UI/Industry/RunsPerCopy'))
     self.runsPerCopyEdit = BlueprintSingleLineEdit(
         parent=self.runsPerCopyCont,
         align=uiconst.CENTERTOP,
         pos=(0, 12, 62, 0),
         OnChange=self.OnRunsPerCopyEdit,
         autoselect=True)
     self.gauge = None
     self.skillSprite = SkillIcon(parent=self,
                                  align=uiconst.CENTERBOTTOM,
                                  top=5,
                                  jobData=self.jobData)
     self.containerME = ContainerME(parent=self,
                                    align=uiconst.CENTER,
                                    pos=(113, -25, 71, 30),
                                    jobData=self.jobData,
                                    opacity=0.0)
     self.containerTE = ContainerTE(parent=self,
                                    align=uiconst.CENTER,
                                    pos=(113, 25, 71, 30),
                                    jobData=self.jobData,
                                    opacity=0.0)
     self.runsRemainingCont = ContainerAutoSize(name='bpCopyCont',
                                                parent=self,
                                                align=uiconst.CENTERTOP,
                                                state=uiconst.UI_NORMAL,
                                                top=90)
     self.runsRemainingCont.OnClick = self.OnRunsRemainingContClicked
     self.runsRemainingCaption = IndustryCaptionLabel(
         parent=self.runsRemainingCont, align=uiconst.CENTERTOP)
     self.runsRemainingLabel = EveLabelMediumBold(
         name='runsRemainingLabel',
         parent=self.runsRemainingCont,
         align=uiconst.CENTERTOP,
         top=14)
     self.UpdateState()
     self.AnimEntry()
Пример #29
0
 def Close(self):
     self.ChangeSignalConnection(connect=False)
     self.structureProfileController = None
     ContainerAutoSize.Close(self)
Пример #30
0
class InfoPanelAchievements(InfoPanelBase):
    __guid__ = 'uicls.InfoPanelAchievements'
    default_name = 'InfoPanelAchievements'
    default_iconTexturePath = 'res:/UI/Texture/Classes/InfoPanels/opportunitiesPanelIcon.png'
    default_state = uiconst.UI_PICKCHILDREN
    default_height = 120
    label = 'UI/Achievements/OpportunitiesHint'
    hasSettings = False
    panelTypeID = PANEL_ACHIEVEMENTS
    groupEntry = None
    achievementContent = None
    __notifyevents__ = [
        'OnAchievementsDataInitialized', 'OnAchievementActiveGroupChanged',
        'OnAchievementChanged'
    ]

    def ApplyAttributes(self, attributes):
        InfoPanelBase.ApplyAttributes(self, attributes)
        self.titleLabel = self.headerCls(
            name='title',
            text='<color=white>' +
            GetByLabel('UI/Achievements/InfoPanelHeader'),
            parent=self.headerCont,
            align=uiconst.CENTERLEFT,
            state=uiconst.UI_DISABLED)

    @staticmethod
    def IsAvailable():
        """ Is this info panel currently available for viewing """
        return sm.GetService('achievementSvc').IsEnabled()

    def ConstructCompact(self):
        self.mainCont.Flush()
        self.achievementContent = None

    def ConstructNormal(self, blinkAchievementID=None):
        if not self.achievementContent or self.achievementContent.destroyed:
            self.mainCont.Flush()
            self.achievementContent = ContainerAutoSize(
                parent=self.mainCont,
                name='achievementContent',
                align=uiconst.TOTOP,
                alignMode=uiconst.TOTOP)
            grid = LayoutGrid(parent=self.mainCont,
                              align=uiconst.TOTOP,
                              columns=2,
                              opacity=0.0)
            button = ButtonIcon(
                texturePath=
                'res:/ui/Texture/Classes/InfoPanels/opportunitiesTreeIcon.png',
                align=uiconst.TOPLEFT,
                iconSize=16,
                parent=grid,
                func=self.OpenOpportunitiesTree,
                pos=(0, 0, 16, 16))
            subTextLabel = InfoPanelLabel(parent=grid,
                                          align=uiconst.CENTERLEFT,
                                          text='See all opportunities',
                                          state=uiconst.UI_NORMAL,
                                          fontsize=EVE_SMALL_FONTSIZE,
                                          bold=True,
                                          left=4)
            subTextLabel.OnClick = self.OpenOpportunitiesTree
            uicore.animations.FadeIn(grid)
        groupID = sm.GetService('achievementSvc').GetActiveAchievementGroupID()
        self.LoadContent(groupID, blinkAchievementID=blinkAchievementID)

    def LoadContent(self, groupID=None, blinkAchievementID=None):
        activeGroupData = GetAchievementGroup(groupID)
        if activeGroupData:
            if self.groupEntry is None or self.groupEntry.destroyed:
                self.achievementContent.Flush()
                self.groupEntry = AchievementGroupEntry(
                    parent=self.achievementContent,
                    align=uiconst.TOTOP,
                    groupInfo=activeGroupData,
                    blinkAchievementID=blinkAchievementID,
                    animateIn=True)
            else:
                self.groupEntry.LoadGroupData(
                    activeGroupData,
                    blinkAchievementID=blinkAchievementID,
                    animateIn=True)
            return
        self.achievementContent.Flush()
        self.groupEntry = None
        label = InfoPanelLabel(name='noActiveOpp',
                               text=GetByLabel('Achievements/UI/noActiveOpp'),
                               parent=self.achievementContent,
                               fontsize=EVE_LARGE_FONTSIZE,
                               padding=(0, 2, 0, 2),
                               state=uiconst.UI_NORMAL,
                               align=uiconst.TOTOP)

    def OpenAchievementAuraWindow(self, *args):
        AchievementAuraWindow.Open()

    def OpenOpportunitiesTree(self, *args):
        AchievementTreeWindow.Open()

    def OnAchievementActiveGroupChanged(self, groupID, emphasize):
        if self.mode != MODE_NORMAL:
            self.SetMode(MODE_NORMAL)
        self.Refresh()
        if emphasize:
            uicore.animations.BlinkIn(self, duration=0.4, loops=4)

    def OnAchievementChanged(self, achievement, *args, **kwds):
        if achievement:
            blinkAchievementID = achievement.achievementID
        else:
            blinkAchievementID = None
        self.Refresh(blinkAchievementID)

    def OnAchievementsDataInitialized(self):
        self.Refresh()

    def Refresh(self, blinkAchievementID=None):
        if self.mode != infoPanelConst.MODE_NORMAL:
            self.ConstructCompact()
        else:
            self.ConstructNormal(blinkAchievementID=blinkAchievementID)
Пример #31
0
class DecorationsPanel(Container):
    default_name = 'DecorationsPanel'
    __notifyevents__ = [
        'OnRankChange', 'OnUpdatedMedalsAvailable',
        'OnUpdatedMedalStatusAvailable'
    ]

    def ApplyAttributes(self, attributes):
        Container.ApplyAttributes(self, attributes)
        btns = [(GetByLabel(
            'UI/CharacterSheet/CharacterSheetWindow/DecoTabs/SaveDecorationPermissionChanges'
        ), self.SaveDecorationPermissionsChanges, (), 64),
                (GetByLabel(
                    'UI/CharacterSheet/CharacterSheetWindow/DecoTabs/SetAllDecorationPermissions'
                ), self.SetAllDecorationPermissions, (), 64)]
        self.mainAreaButtons = ContainerAutoSize(align=uiconst.TOBOTTOM,
                                                 parent=self)
        ButtonGroup(btns=btns, parent=self.mainAreaButtons, line=False)
        self.decoMedalList = None
        self.decoRankList = None
        self.scroll = Scroll(parent=self, padding=(0, 4, 0, 4))
        self.mydecorationstabs = TabGroup(
            name='tabparent',
            parent=self,
            idx=0,
            tabs=
            [[
                GetByLabel(
                    'UI/CharacterSheet/CharacterSheetWindow/DecoTabs/Ranks'),
                self.scroll, self, PANEL_RANKS
            ],
             [
                 GetByLabel(
                     'UI/CharacterSheet/CharacterSheetWindow/DecoTabs/Medals'),
                 self.scroll, self, PANEL_MEDALS
             ],
             [
                 GetByLabel(
                     'UI/CharacterSheet/CharacterSheetWindow/DecoTabs/Permissions'
                 ), self.scroll, self, PANEL_PERMISSIONS
             ]],
            groupID='cs_decorations')

    def LoadPanel(self, *args):
        self.mydecorationstabs.AutoSelect()

    def SaveDecorationPermissionsChanges(self):
        promptForDelete = False
        changes = {}
        for entry in self.scroll.GetNodes():
            if entry.panel and hasattr(entry.panel, 'flag'):
                if entry.panel.HasChanged():
                    if entry.panel.flag == 1:
                        promptForDelete = True
                    changes[entry.panel.sr.node.itemID] = entry.panel.flag

        if promptForDelete == False or uicore.Message(
                'DeleteMedalConfirmation', {},
                uiconst.YESNO) == uiconst.ID_YES:
            if len(changes) > 0:
                sm.StartService('medals').SetMedalStatus(changes)
        self.decoMedalList = None

    def SetAllDecorationPermissions(self):
        permissionList = [
            (GetByLabel(
                'UI/CharacterSheet/CharacterSheetWindow/DecoTabs/Private'), 2),
            (GetByLabel(
                'UI/CharacterSheet/CharacterSheetWindow/DecoTabs/Public'), 3)
        ]
        pickedPermission = ListWnd(
            permissionList,
            'generic',
            GetByLabel(
                'UI/CharacterSheet/CharacterSheetWindow/DecoTabs/SetAllDecorationPermissions'
            ),
            GetByLabel(
                'UI/CharacterSheet/CharacterSheetWindow/PilotLicense/SaveAllChangesImmediately'
            ),
            windowName='permissionPickerWnd')
        if not pickedPermission:
            return
        permissionID = pickedPermission[1]
        m, _ = sm.StartService('medals').GetMedalsReceived(session.charid)
        myDecos = []
        for each in m:
            if each.status != 1:
                myDecos.append(each.medalID)

        myDecos = list(set(myDecos))
        updateDict = {}
        for decoID in myDecos:
            updateDict[decoID] = permissionID

        if len(updateDict) > 0:
            sm.StartService('medals').SetMedalStatus(updateDict)
            self.decoMedalList = None
            self.ShowMyDecorations('mydecorations_permissions')

    def Load(self, key):
        self.ShowMyDecorations(key)

    def ShowMyDecorations(self, key=None):
        if key == PANEL_RANKS:
            self.ShowMyRanks()
        elif key == PANEL_MEDALS:
            self.ShowMyMedals()
        elif key == PANEL_PERMISSIONS:
            self.ShowMyDecorationPermissions()

    def ShowMyMedals(self, charID=None):
        self.mainAreaButtons.Hide()
        if charID is None:
            charID = session.charid
        if self.decoMedalList is None:
            self.decoMedalList = GetMedalScrollEntries(charID)
        self.scroll.sr.id = 'charsheet_mymedals'
        self.scroll.Load(
            contentList=self.decoMedalList,
            noContentHint=GetByLabel(
                'UI/CharacterSheet/CharacterSheetWindow/DecoTabs/NoMedals'))

    def ShowMyRanks(self):
        self.mainAreaButtons.Hide()
        if self.decoRankList is None:
            scrolllist = []
            characterRanks = sm.StartService(
                'facwar').GetCharacterRankOverview(session.charid)
            for characterRank in characterRanks:
                entry = sm.StartService('info').GetRankEntry(characterRank)
                if entry:
                    scrolllist.append(entry)

            self.decoRankList = scrolllist[:]
        self.scroll.sr.id = 'charsheet_myranks'
        self.scroll.Load(
            contentList=self.decoRankList,
            noContentHint=GetByLabel(
                'UI/CharacterSheet/CharacterSheetWindow/DecoTabs/NoRanks'))

    def ShowMyDecorationPermissions(self):
        self.mainAreaButtons.Show()
        scrollHeaders = [
            GetByLabel('UI/CharacterCreation/FirstName'),
            GetByLabel(
                'UI/CharacterSheet/CharacterSheetWindow/DecoTabs/Private'),
            GetByLabel(
                'UI/CharacterSheet/CharacterSheetWindow/DecoTabs/Public'),
            GetByLabel('UI/PI/Common/Remove')
        ]
        self.scroll.sr.fixedColumns = {
            GetByLabel('UI/CharacterSheet/CharacterSheetWindow/DecoTabs/Private'):
            60,
            GetByLabel('UI/CharacterSheet/CharacterSheetWindow/DecoTabs/Public'):
            60
        }
        self.scroll.sr.id = 'charsheet_decopermissions'
        self.scroll.Load(contentList=[], headers=scrollHeaders)
        self.scroll.OnColumnChanged = self.OnDecorationPermissionsColumnChanged
        publicDeco = sm.StartService('medals').GetMedalsReceivedWithFlag(
            session.charid, [3])
        privateDeco = sm.StartService('medals').GetMedalsReceivedWithFlag(
            session.charid, [2])
        ppKeys = [each for each in publicDeco.keys() + privateDeco.keys()]
        scrolllist = []
        inMedalList = []
        characterMedals, characterMedalInfo = sm.StartService(
            'medals').GetMedalsReceived(session.charid)
        for characterMedal in characterMedals:
            medalID = characterMedal.medalID
            if medalID not in ppKeys:
                continue
            if medalID in inMedalList:
                continue
            inMedalList.append(medalID)
            details = characterMedalInfo.Filter('medalID')
            if details and details.has_key(medalID):
                details = details.get(medalID)
            entry = self.CreateDecorationPermissionsEntry(characterMedal)
            if entry:
                scrolllist.append(entry)

        self.scroll.Load(contentList=scrolllist,
                         headers=scrollHeaders,
                         noContentHint=GetByLabel('UI/Common/NothingFound'))
        self.OnDecorationPermissionsColumnChanged()

    def CreateDecorationPermissionsEntry(self, data):
        entry = {
            'line': 1,
            'label': data.title + '<t><t><t>',
            'itemID': data.medalID,
            'visibilityFlags': data.status,
            'indent': 3,
            'selectable': 0
        }
        return entries.Get('DecorationPermissions', entry)

    def OnDecorationPermissionsColumnChanged(self, *args, **kwargs):
        for entry in self.scroll.GetNodes():
            if entry.panel and getattr(entry.panel, 'OnColumnChanged', None):
                entry.panel.OnColumnChanged()

    def OnRankChange(self, oldrank, newrank):
        if not session.warfactionid:
            return
        self.decoRankList = None
        if self.display:
            self.LoadPanel()

    def OnUpdatedMedalsAvailable(self):
        self.ReloadMedals()

    def OnUpdatedMedalStatusAvailable(self):
        self.ReloadMedals()

    def ReloadMedals(self):
        self.decoMedalList = None
        if self.display:
            self.LoadPanel()