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 ApplyAttributes(self, attributes): ButtonIcon.ApplyAttributes(self, attributes) self.factionID = attributes.factionID self.CheckBlink()
class VideoPlayerWindow(Window): default_caption = 'Video' default_minSize = (500, 400) default_windowID = 'VideoPlayer' def ApplyAttributes(self, attributes): Window.ApplyAttributes(self, attributes) self.SetTopparentHeight(0) self.SetWndIcon('res:/ui/texture/icons/bigplay_64.png') self._stopUpdate = False self._onFinish = None self._subtitles = None self._finished = False self.bottomContainer = Container(name='bottomContainer', parent=self.sr.main, align=uiconst.TOBOTTOM, height=16, padding=const.defaultPadding) self.layoutAreaParent = Container(parent=self.sr.main, padding=const.defaultPadding) self.layoutAreaParent._OnSizeChange_NoBlock = self.RecalcLayout self.layoutArea = Container(parent=self.layoutAreaParent, align=uiconst.CENTER, width=100, height=100) self.video = StreamingVideoSprite(parent=self.layoutArea, align=uiconst.TOALL) self.video.OnVideoSizeAvailable = self.RecalcLayout self.video.OnVideoFinished = self._OnVideoFinished self.playPauseBtn = ButtonIcon(parent=self.bottomContainer, func=self.Play, align=uiconst.TOLEFT) self.muteBtn = ButtonIcon(parent=self.bottomContainer, func=self.Mute, align=uiconst.TOLEFT) self.volumeSlider = Slider(parent=self.bottomContainer, width=48, minValue=0, maxValue=100, startValue=100, showLabel=False, onsetvaluefunc=self.SetVolume, align=uiconst.TOLEFT) self.volume = settings.user.ui.Get('videoPlayerVolume', 100) self.volumeSlider.SetValue(self.volume, updateHandle=True, triggerCallback=False) self.subtitlesBtn = ButtonIcon(parent=self.bottomContainer, func=self.SwitchSubtitles, align=uiconst.TORIGHT) self.showSubtitles = True positionContainer = Container(parent=self.bottomContainer, align=uiconst.TOALL, padding=6) self.positionFill = Fill(parent=Container(parent=positionContainer, state=uiconst.UI_DISABLED), name='progressFill', align=uiconst.TOLEFT_PROP, color=(0.1804, 0.5412, 0.6392, 1)) self.downloadedFill = Fill(parent=Container(parent=positionContainer, state=uiconst.UI_DISABLED), name='downloadFill', align=uiconst.TOLEFT_PROP, color=(0.4667, 0.7529, 0.8392, 1)) Fill(parent=positionContainer, align=uiconst.TOALL, color=(1.0, 1.0, 1.0, 0.3)) self.followUpContainer = Container(parent=self.layoutAreaParent, align=uiconst.TOALL, state=uiconst.UI_HIDDEN) self.sr.subtitleCont = Container(parent=self.layoutArea, name='subtitleCont', idx=0, align=uiconst.TOBOTTOM_NOPUSH, state=uiconst.UI_DISABLED, height=100) self.sr.subtitleCont.Flush() self.UpdateLayoutArea() uthread2.StartTasklet(self._UpdatePosition) def _OnVideoFinished(self): for each in self.followUpContainer.children[:]: each.Close() self._finished = True self.playPauseBtn.SetTexturePath('res:/ui/texture/icons/replay.png') if self._onFinish: self.followUpContainer.SetState(uiconst.UI_NORMAL) self.layoutArea.SetState(uiconst.UI_HIDDEN) self._onFinish(self.followUpContainer) def PlayVideo(self, path, title=None, subtitles=None, onFinish=None): self.playPauseBtn.SetTexturePath('res:/ui/texture/icons/pause.png') self.muteBtn.SetTexturePath('res:/ui/texture/icons/73_16_35.png') self.subtitlesBtn.SetTexturePath('res:/ui/texture/icons/73_16_10.png') self.layoutArea.SetState(uiconst.UI_NORMAL) self.followUpContainer.SetState(uiconst.UI_HIDDEN) self.video.SetVideoPath(path) self.video.SetVolume(float(self.volume) / 100.0) self.volumeSlider.SetValue(self.volume, updateHandle=True, triggerCallback=False) self.SetCaption( title if title is not None else VideoPlayerWindow.default_caption) self._onFinish = onFinish self._finished = False self._replayArgs = (path, title, subtitles, onFinish) if subtitles is None: self._subtitles = None else: self._subtitles = Subtitles(subtitles) def Close(self, *args, **kwds): self._stopUpdate = True self.video = None Window.Close(self, *args, **kwds) def _UpdatePosition(self): while not self._stopUpdate: if self.video: duration = float((self.video.duration or 1) / 1000000) if duration == 0: duration = 1 mediaTime = min( float((self.video.mediaTime or 0) / 1000000) / duration, 1) downloadedTime = min( float( (self.video.downloadedTime or 0) / 1000000) / duration, 1) if mediaTime == 0: self.positionFill.Hide() else: self.positionFill.Show() self.positionFill.width = mediaTime if downloadedTime == 0: self.downloadedFill.Hide() else: self.downloadedFill.Show() self.downloadedFill.width = downloadedTime self._UpdateSubtitles() uthread2.Sleep(0.1) def _UpdateSubtitles(self): if self._subtitles is None or not self.showSubtitles: return currentTime = self.video.mediaTime or 0 currentTime /= 1000000 self.sr.subtitleCont.Flush() text = self._subtitles.GetSubtitle(currentTime) if text is not None: EveCaptionLarge(text=u'<center>%s' % text, parent=self.sr.subtitleCont, color=(0.75, 0.75, 0.75, 1), align=uiconst.TOBOTTOM_NOPUSH, bold=False, state=uiconst.UI_DISABLED) l = EveCaptionLarge(text=u'<center>%s' % text, parent=self.sr.subtitleCont, color=(0, 0, 0, 1), align=uiconst.TOBOTTOM, bold=False, state=uiconst.UI_DISABLED) l.renderObject.spriteEffect = trinity.TR2_SFX_GLOW def UpdateLayoutArea(self): size = self.video.GetVideoSize() if not size: return areaWidth, areaHeight = self.layoutAreaParent.GetAbsoluteSize() xFitScale = areaWidth / float(size[0]) yFitScale = areaHeight / float(size[1]) scaling = min(xFitScale, yFitScale) self.layoutArea.width = int(size[0] * scaling) self.layoutArea.height = int(size[1] * scaling) def RecalcLayout(self, *args): self.UpdateLayoutArea() def Play(self, *args): if self._finished: self._finished = False self.PlayVideo(*self._replayArgs) elif self.video.isPaused: self.video.Play() self.playPauseBtn.SetTexturePath('res:/ui/texture/icons/pause.png') else: self.video.Pause() self.playPauseBtn.SetTexturePath('res:/ui/texture/icons/play.png') def Mute(self, *args): if self.video.isMuted: self.video.UnmuteAudio() self.volumeSlider.SetValue(self.volume, updateHandle=True, triggerCallback=False) self.muteBtn.SetTexturePath('res:/ui/texture/icons/73_16_35.png') else: self.video.MuteAudio() self.volumeSlider.SetValue(0, updateHandle=True, triggerCallback=False) self.muteBtn.SetTexturePath('res:/ui/texture/icons/73_16_37.png') def SetVolume(self, slider): self.video.SetVolume(float(slider.value) / 100.0) self.volume = slider.value settings.user.ui.Set('videoPlayerVolume', self.volume) if self.volume: self.muteBtn.SetTexturePath('res:/ui/texture/icons/73_16_35.png') def SwitchSubtitles(self): self.showSubtitles = not self.showSubtitles if self.showSubtitles: self.subtitlesBtn.opacity = 1.0 else: self.subtitlesBtn.opacity = 0.2 self.sr.subtitleCont.Flush()
def ApplyAttributes(self, attributes): ButtonIcon.ApplyAttributes(self, attributes)
def _ConstructSettingsButton(self): if self.horizontalAlignment is ExpandAlignmentConst.EXPAND_ALIGNMENT_HORIZONTAL_LEFT: buttonAlignment = uiconst.TOLEFT else: buttonAlignment = uiconst.TORIGHT self.settingsButton = ButtonIcon(name='MyButtonIcon2', parent=self.controlBottomContainer, align=buttonAlignment, width=24, height=24, iconSize=24, texturePath='res:/UI/Texture/Icons/77_32_30.png', func=self.OnSettingsClick, hint=localization.GetByLabel('Notifications/NotificationWidget/NotificationSettingsTooltip'), padding=(5, 0, 5, 0), opacity=0)
def ApplyAttributes(self, attributes): ButtonIcon.ApplyAttributes(self, attributes) self.settingGroupKeys = attributes.settingGroupKeys self.callback = attributes.callback self.SetTexturePath(ICON_ROOT + 'icon_const_group.png')
def ApplyAttributes(self, attributes): ButtonIcon.ApplyAttributes(self, attributes) self.settingGroupKey = attributes.settingGroupKey self.callback = attributes.callback self.ReloadSettingValue()
class ImpactVisualizer(): def __init__(self): self.name = 'Impact Visualizer' self.windowID = 'ImpactVisualizer_ ' + self.name self.damageLocatorID = 0 self.impactVelocity = [0.0, -1000.0, 0.0] self.impactObjectMass = 100000 self.shipId = None self.shipInput = None self.impactArrow = None self.arrowModel = None self.impactArrowBoundingRadius = 0.0 self.impactRotation = geo2.QuaternionRotationSetYawPitchRoll( 0.0, math.pi, 0.0) self.damageLocatorPos = (0.0, 0.0, 0.0) self.arrowPositionUpdater = None self.lockVelocity = True self.randomize = False self.arrowModel = trinity.Load('res:/Model/global/impactDirection.red') def SetupImpactArrow(self): self.impactArrow = trinity.EveRootTransform() self.impactArrow.name = 'DebugImpactArrow' self.impactArrow.children.append(self.arrowModel) self.arrowPositionUpdater = ArrowPositionUpdater(self.impactArrow) def GetImpactArrowBoundingRadius(self): geometry = self.arrowModel.mesh.geometry geometry.RecalculateBoundingSphere() self.impactArrowBoundingRadius = geometry.GetBoundingSphere(0)[1] def _OnClose(self): self.RemoveImpactArrowFromScene() self.arrowPositionUpdater.Stop() def GetBall(self, ballID=None): if ballID is None: ballID = self.shipId return sm.GetService('michelle').GetBall(ballID) def ShowUI(self): self.SetupImpactArrow() uicontrols.Window.CloseIfOpen(windowID=self.windowID) wnd = uicontrols.Window.Open(windowID=self.windowID) wnd.SetTopparentHeight(0) wnd.SetMinSize([500, 100]) wnd.SetCaption(self.name) wnd._OnClose = self._OnClose main = wnd.GetMainArea() headerCont = Container(name='headerCont', parent=main, align=uiconst.TOTOP, height=30, padBottom=10) bottomCont = Container(name='bottomCont', parent=main, align=uiconst.TOBOTTOM, height=30) self.shipIdLabel = EveLabelSmall(name='shipIDLabel', align=uiconst.CENTER, parent=headerCont, text='Ship ID: %s' % self.shipId) Button(name='apply_button', align=uiconst.CENTER, parent=bottomCont, label='Apply Physical Impact', func=self._OnApplyPhysicalImpact) mainContainer = GridContainer(name='mainCont', parent=main, align=uiconst.TOALL, columns=4, rows=3) container = Container(name='impactVelocityLockAndLabel', align=uiconst.TOALL, parent=mainContainer, padRight=10) self.lockVelocityButton = ButtonIcon( name='MyButtonIcon', parent=container, align=uiconst.TOPLEFT, width=16, height=16, iconSize=16, padLeft=10, texturePath='res:/UI/Texture/Icons/bookmark.png', func=self.OnLockVelocity) EveLabelSmall(name='impactVelocity', align=uiconst.TORIGHT, parent=container, padRight=10, text='Impact Velocity') self.impactVelocityXInput = SinglelineEdit( name='xVelocity', align=uiconst.TOTOP, label='X', parent=mainContainer, padRight=10, setvalue=str(self.impactVelocity[0]), OnFocusLost=self.OnSetImpactVelocityX, OnReturn=self.OnSetImpactVelocityX) self.impactVelocityYInput = SinglelineEdit( name='yVelocity', align=uiconst.TOTOP, label='Y', parent=mainContainer, padRight=10, setvalue=str(self.impactVelocity[1]), OnFocusLost=self.OnSetImpactVelocityY, OnReturn=self.OnSetImpactVelocityY) self.impactVelocityZInput = SinglelineEdit( name='zVelocity', align=uiconst.TOTOP, label='Z', parent=mainContainer, padRight=10, setvalue=str(self.impactVelocity[2]), OnFocusLost=self.OnSetImpactVelocityZ, OnReturn=self.OnSetImpactVelocityZ) EveLabelSmall(name='shipIDInputLabel', parent=mainContainer, align=uiconst.TORIGHT, padRight=10, text='Ship ID') self.shipInput = SinglelineEdit(name='shipIdInput', parent=mainContainer, align=uiconst.TOTOP, padRight=10, setvalue=str(session.shipid), OnFocusLost=self.OnSetShipId, OnReturn=self.OnSetShipId) EveLabelSmall(name='damageLocatorLabel', align=uiconst.TORIGHT, padRight=10, parent=mainContainer, text='Damage Locator') self.damageLocatorInput = SinglelineEdit( name='damageLocator', align=uiconst.TOTOP, label='', parent=mainContainer, padRight=10, setvalue=str(self.damageLocatorID), ints=(0, 0), OnChange=self.OnSetDamageLocator) EveLabelSmall(name='impactMassLabel', align=uiconst.TORIGHT, padRight=10, parent=mainContainer, text='Impact Mass') self.impactMassInput = SinglelineEdit(name='impactMass', align=uiconst.TOTOP, label='', parent=mainContainer, padRight=10, setvalue=str( self.impactObjectMass), OnChange=self.OnSetImpactMass) self.randomizeDL = Checkbox(name='myCheckbox', parent=mainContainer, text='Randomize Damage Locators', checked=self.randomize, callback=self.OnRandomize) self.AddImpactArrowToScene() self.OnSetShipId() def OnSetShipId(self, *args): try: shipId = long(self.shipInput.GetValue()) except ValueError: print "Could not set shipId to '%s'" % self.shipInput.GetValue() return if self.shipId == shipId: return if sm.GetService('michelle').GetBall(shipId) is None: print "No ball with id '%d' found in ballpark" % shipId return print 'Setting ship ID to %d' % shipId self.shipId = shipId self.shipIdLabel.SetText('Ship ID: %s' % self.shipId) self.arrowPositionUpdater.SetBall(self.GetBall()) self.damageLocatorInput.IntMode( minint=0, maxint=len(self.GetBall().model.damageLocators)) if len(self.GetBall().model.damageLocators) >= self.damageLocatorID: self.damageLocatorInput.SetValue(str(self.damageLocatorID)) else: self.damageLocatorInput.SetValue(str(0)) self.OnSetDamageLocator() def OnSetImpactVelocityX(self, *args): self.impactVelocity = (float(self.impactVelocityXInput.GetValue()), self.impactVelocity[1], self.impactVelocity[2]) self.arrowPositionUpdater.SetArrowDirection(self.impactVelocity) def OnSetImpactVelocityY(self, *args): self.impactVelocity = (self.impactVelocity[0], float(self.impactVelocityYInput.GetValue()), self.impactVelocity[2]) self.arrowPositionUpdater.SetArrowDirection(self.impactVelocity) def OnSetImpactVelocityZ(self, *args): self.impactVelocity = (self.impactVelocity[0], self.impactVelocity[1], float(self.impactVelocityZInput.GetValue())) self.arrowPositionUpdater.SetArrowDirection(self.impactVelocity) def OnLockVelocity(self, *args): self.lockVelocity = not self.lockVelocity if self.lockVelocity: self.lockVelocityButton.SetRotation(0) else: self.lockVelocityButton.SetRotation(-20) def OnSetDamageLocator(self, *args): self.damageLocatorID = int(self.damageLocatorInput.GetValue()) self.arrowPositionUpdater.SetDamageLocator(self.damageLocatorID) if not self.lockVelocity: _, rotation = self.GetBall().model.damageLocators[ self.damageLocatorID] self.impactVelocity = geo2.QuaternionTransformVector( rotation, (0.0, geo2.Vec3Length(self.impactVelocity), 0.0)) self.impactVelocity = (-self.impactVelocity[0], -self.impactVelocity[1], -self.impactVelocity[2]) self.impactVelocityXInput.SetValue(str(self.impactVelocity[0])) self.impactVelocityYInput.SetValue(str(self.impactVelocity[1])) self.impactVelocityZInput.SetValue(str(self.impactVelocity[2])) self.arrowPositionUpdater.SetArrowDirection(self.impactVelocity) def OnSetImpactMass(self, *args): self.impactObjectMass = float(self.impactMassInput.GetValue()) def OnRandomize(self, *args): self.randomize = not self.randomize if self.randomize and self.lockVelocity: self.OnLockVelocity() def RemoveImpactArrowFromScene(self): scene = sm.GetService('sceneManager').GetActiveScene() objectsToRemove = [] for o in scene.objects: if o.name == 'DebugImpactArrow': objectsToRemove.append(o) for o in objectsToRemove: scene.objects.remove(o) def AddImpactArrowToScene(self): scene = sm.GetService('sceneManager').GetActiveScene() scene.objects.append(self.impactArrow) def _OnApplyPhysicalImpact(self, *args): if self.randomize: newDamageLocatorID = random.randint( 0, len(self.GetBall().model.damageLocators) - 1) while newDamageLocatorID == self.damageLocatorID: newDamageLocatorID = random.randint( 0, len(self.GetBall().model.damageLocators) - 1) self.damageLocatorID = newDamageLocatorID self.damageLocatorInput.SetValue(str(self.damageLocatorID)) self.OnSetDamageLocator() sm.GetService('michelle').GetBall( self.shipId).ApplyTorqueAtDamageLocator(self.damageLocatorID, self.impactVelocity, self.impactObjectMass)
def AddIconButton(self, texturePath, hint = None): from eve.client.script.ui.control.buttons import ButtonIcon rightAlignedButton = ButtonIcon(texturePath=texturePath, pos=(0, 0, 16, 16), align=uiconst.CENTERRIGHT, parent=self, hint=hint, idx=0) self.rightAlignedButtons.add(rightAlignedButton) return rightAlignedButton
def ApplyAttributes(self, attributes): Container.ApplyAttributes(self, attributes) self.mapSvc = sm.GetService('map') self.mapViewID = attributes.mapViewID self.autoFocusEnabled = settings.char.ui.Get( '%s_autoFocusEnabled_%s' % (SETTING_PREFIX, self.mapViewID), True) innerPadding = attributes.innerPadding or 0 self.infoLayer = Container(parent=self, clipChildren=True, name='infoLayer', padding=innerPadding) if attributes.showCloseButton: ButtonIcon( parent=self.infoLayer, hint=localization.GetByLabel('UI/Generic/Close'), texturePath='res:/UI/Texture/classes/DockPanel/closeButton.png', func=attributes.closeFunction or self.Close, align=uiconst.TOPRIGHT) self.showInfobox = attributes.Get('showInfobox', self.showInfobox) if self.showInfobox: self.infoBox = SolarSystemInfoBox(parent=self.infoLayer, align=uiconst.TOPLEFT, left=32, top=32) navigationClass = attributes.Get('navigationClass', MapViewScannerNavigation) navigationPadding = attributes.Get('navigationPadding', (0, 32, 0, 0)) self.mapNavigation = navigationClass(parent=self, align=uiconst.TOALL, state=uiconst.UI_NORMAL, mapView=self, padding=navigationPadding) sceneContainer = MapViewSceneContainer(parent=self, align=uiconst.TOALL, state=uiconst.UI_DISABLED, padding=innerPadding) sceneContainer.Startup() self.sceneContainer = sceneContainer self.sceneContainer.display = False scene = trinity.EveSpaceScene() self.showSolarSystemNebula = attributes.Get('showSolarSystemNebula', self.showSolarSystemNebula) if self.showSolarSystemNebula: scene.backgroundEffect = trinity.Load( 'res:/dx9/scene/starfield/starfieldNebula.red') scene.backgroundRenderingEnabled = True self.showStarfield = attributes.Get('showStarfield', self.showStarfield) if self.showStarfield: scene.starfield = trinity.Load( 'res:/dx9/scene/starfield/spritestars.red') scene.backgroundRenderingEnabled = True self.mapRoot = trinity.EveRootTransform() self.mapRoot.name = 'mapRoot' scene.objects.append(self.mapRoot) self.sceneBlendMode = attributes.Get('sceneBlendMode', self.sceneBlendMode) self.sceneContainer.scene = scene self.sceneContainer.DisplaySpaceScene(blendMode=self.sceneBlendMode) self.markersHandler = MapViewMarkersHandler( self, self.sceneContainer.bracketCurveSet, self.infoLayer, eventHandler=self.mapNavigation, stackMarkers=attributes.Get('stackMarkers', True)) self.bookmarkHandler = MapViewBookmarkHandler(self) self.showDebugInfo = attributes.Get('showDebugInfo', self.showDebugInfo) if self.showDebugInfo: self.debugOutput = EveLabelSmall(parent=self, align=uiconst.BOTTOMLEFT, left=6, top=6, idx=0) self.debugOutputTimer = AutoTimer(5, self.UpdateDebugOutput) self.camera.fieldOfView = 0.7 self.camera.minDistance = 0.5 self.camera.maxDistance = 8000.0 self.camera.frontClip = 0.1 self.camera.backClip = 50000.0 self.camera.LoadRegisteredCameraSettings(self.mapViewID) self.camera.SetCallback(self.OnCameraMoved) sm.RegisterNotify(self) uthread.new(uicore.registry.SetFocus, self)
def ApplyAttributes(self, attributes): Container.ApplyAttributes(self, attributes) self.mapSvc = sm.GetService('map') innerPadding = attributes.innerPadding or 0 self.infoLayer = Container(parent=self, clipChildren=True, name='infoLayer', padding=innerPadding) if attributes.showCloseButton: closeButton = ButtonIcon( parent=self.infoLayer, hint='Close', texturePath='res:/UI/Texture/classes/DockPanel/closeButton.png', func=attributes.closeFunction or self.Close, align=uiconst.TOPRIGHT) if attributes.showInfobox: self.infoBox = SolarSystemInfoBox(parent=self.infoLayer, align=uiconst.TOPLEFT, left=32, top=32) self.mapNavigation = MapViewNavigation(parent=self, align=uiconst.TOALL, state=uiconst.UI_NORMAL, mapView=self, padding=(0, 32, 0, 0)) sceneContainer = MapViewSceneContainer(parent=self, align=uiconst.TOALL, state=uiconst.UI_DISABLED, padding=innerPadding) sceneContainer.Startup() self.sceneContainer = sceneContainer self.sceneContainer.display = False self.camera.SetCallback(self.OnCameraMoved) scene = trinity.EveSpaceScene() scene.starfield = trinity.Load( 'res:/dx9/scene/starfield/spritestars.red') scene.backgroundEffect = trinity.Load( 'res:/dx9/scene/starfield/starfieldNebula.red') scene.backgroundRenderingEnabled = True node = nodemanager.FindNode(scene.backgroundEffect.resources, 'NebulaMap', 'trinity.TriTexture2DParameter') if node is not None: s = sm.GetService('sceneManager') sceneCube = s.GetNebulaPathForSystem(session.solarsystemid) node.resourcePath = sceneCube or 'res:/UI/Texture/classes/MapView/backdrop_cube.dds' self.mapRoot = trinity.EveRootTransform() self.mapRoot.name = 'universe' scene.objects.append(self.mapRoot) self.sceneContainer.scene = scene self.sceneContainer.DisplaySpaceScene() self.markersHandler = MapViewMarkersHandler( self, self.sceneContainer.bracketCurveSet, self.infoLayer, eventHandler=self.mapNavigation) self.abstractMode = settings.user.ui.Get( VIEWMODE_LAYOUT_SHOW_ABSTRACT_SETTINGS, VIEWMODE_LAYOUT_SHOW_ABSTRACT_DEFAULT) if self.abstractMode: self.yScaleFactor = 0.0001 sm.RegisterNotify(self) uthread.new(uicore.registry.SetFocus, self)
class FittingWindow2(Window): __guid__ = 'form.FittingWindow2' __notifyevents__ = ['OnSetDevice'] default_topParentHeight = 0 default_fixedHeight = WND_NORMAL_HEIGHT default_windowID = 'fitting2' default_captionLabelPath = 'Tooltips/StationServices/ShipFitting' default_descriptionLabelPath = 'Tooltips/StationServices/ShipFitting_description' default_iconNum = 'res:/ui/Texture/WindowIcons/fitting.png' def ApplyAttributes(self, attributes): Window.ApplyAttributes(self, attributes) self.MakeUnResizeable() self.HideHeaderFill() self.windowReady = False self.controller = None self._layoutLock = locks.Lock() try: self.controller = self.LoadController(attributes) except UserError: self.Close() raise self._fixedHeight = GetFixedWndHeight(self.controller) self.controller.on_stats_changed.connect(self.UpdateStats) self.controller.on_new_itemID.connect(self.UpdateStats) self.controller.on_should_close.connect(self.Close) self.controller.on_controller_changing.connect(self.Close) self.ConstructLayout() def LoadController(self, attributes): itemID = attributes.shipID or GetActiveShip() return GetFittingController(itemID) def ConstructLayout(self): self._fixedHeight = GetFixedWndHeight(self.controller) self.height = self._fixedHeight with self._layoutLock: self.sr.main.Flush() width = PANEL_WIDTH if self.IsLeftPanelExpanded() else 0 skinController = FittingSkinPanelController( fitting=self.controller) self.leftPanel = Container(parent=self.sr.main, align=uiconst.TOLEFT, width=width, padding=(10, 0, 0, 10)) self.cleanShipBtn = CleanShipButton(parent=self.leftPanel, align=uiconst.TOBOTTOM, controller=self.controller) self.skinPanel = SkinPanel(parent=self.leftPanel, align=uiconst.TOALL, controller=skinController, settingsPrefix='Fitting_SkinPanel', logContext='FittingWindow') if self.IsLeftPanelExpanded(): uthread.new(self.skinPanel.Load) width = PANEL_WIDTH if self.IsRightPanelExpanded() else 0 self.rightPanel = StatsPanel(name='rightside', parent=self.sr.main, align=uiconst.TORIGHT, width=width, idx=0, padding=(0, 0, 10, 10), controller=self.controller) mainCont = Container(name='mainCont', parent=self.sr.main, top=-8) overlayWidth, overlayHeight, overlayAlignment = GetOverlayWidthHeightAndAlignment( self.controller) self.overlayCont = Container(name='overlayCont', parent=mainCont, align=overlayAlignment, width=overlayWidth, height=overlayHeight) self.fighterAndDroneCont = None self.ConstructPanelExpanderBtn() self.ConstructInventoryIcons() self.ConstructPowerAndCpuLabels() if self.controller.ControllerForCategory( ) == const.categoryStructure: self.serviceCont = FittingServiceCont( parent=mainCont, controller=self.controller) fittingAlignment = uiconst.TOPLEFT else: fittingAlignment = uiconst.CENTERLEFT Fitting(parent=mainCont, owner=self, controller=self.controller, align=fittingAlignment) self.windowReady = True self.width = self.GetWindowWidth() self.SetFixedWidth(self.width) self.UpdateStats() def ConstructInventoryIcons(self): cargoDroneCont = ContainerAutoSize(name='cargoDroneCont', parent=self.overlayCont, align=uiconst.BOTTOMLEFT, width=110, left=const.defaultPadding, top=4) if IsControllingStructure(): cargoSlot = CargoStructureAmmoBay(name='structureCargoSlot', parent=cargoDroneCont, align=uiconst.TOTOP, height=32, controller=self.controller) SetFittingTooltipInfo(cargoSlot, 'StructureAmmoHold') else: cargoSlot = CargoCargoSlots(name='cargoSlot', parent=cargoDroneCont, align=uiconst.TOTOP, height=32, controller=self.controller) SetFittingTooltipInfo(cargoSlot, 'CargoHold') self.fighterAndDroneCont = Container(name='fighterAndDroneCont', parent=cargoDroneCont, align=uiconst.TOTOP, height=32) self.ContructDroneAndFighterIcons() def ContructDroneAndFighterIcons(self): self.fighterAndDroneCont.Flush() if self.controller.HasFighterBay(): slot = CargoFighterSlots(name='fighterSlot', parent=self.fighterAndDroneCont, align=uiconst.TOTOP, height=32, controller=self.controller) SetFittingTooltipInfo(slot, 'FighterBay') else: slot = CargoDroneSlots(name='droneSlot', parent=self.fighterAndDroneCont, align=uiconst.TOTOP, height=32, controller=self.controller) SetFittingTooltipInfo(slot, 'DroneBay') self.fighterOrDroneSlot = slot def ReloadDroneAndFighterIconsIfNeeded(self): if self.fighterAndDroneCont is None: return if self.controller.HasFighterBay() and isinstance( self.fighterOrDroneSlot, CargoFighterSlots): return if not self.controller.HasFighterBay() and isinstance( self.fighterOrDroneSlot, CargoDroneSlots): return self.ContructDroneAndFighterIcons() def IsRightPanelExpanded(self): return settings.user.ui.Get('fittingPanelRight', 1) def IsLeftPanelExpanded(self): return settings.user.ui.Get('fittingPanelLeft2', 1) def ConstructPanelExpanderBtn(self): if self.IsLeftPanelExpanded(): texturePath = 'res:/UI/Texture/Icons/73_16_196.png' tooltipName = 'CollapseSidePane' else: texturePath = 'res:/UI/Texture/Icons/73_16_195.png' tooltipName = 'ExpandSidePane' self.toggleLeftBtn = ButtonIcon(texturePath=texturePath, parent=self.overlayCont, align=uiconst.CENTERLEFT, pos=(2, 0, 16, 16), func=self.ToggleLeftPanel) SetFittingTooltipInfo(self.toggleLeftBtn, tooltipName=tooltipName, includeDesc=False) if self.IsRightPanelExpanded(): texturePath = 'res:/UI/Texture/Icons/73_16_195.png' tooltipName = 'CollapseSidePane' else: texturePath = 'res:/UI/Texture/Icons/73_16_196.png' tooltipName = 'ExpandSidePane' self.toggleRightBtn = ButtonIcon(texturePath=texturePath, parent=self.overlayCont, align=uiconst.CENTERRIGHT, pos=(2, 0, 16, 16), func=self.ToggleRight) SetFittingTooltipInfo(self.toggleRightBtn, tooltipName=tooltipName, includeDesc=False) def ToggleRight(self, *args): isExpanded = not self.IsRightPanelExpanded() settings.user.ui.Set('fittingPanelRight', isExpanded) self._fixedWidth = self.GetWindowWidth() self.toggleRightBtn.state = uiconst.UI_DISABLED if isExpanded: self.toggleRightBtn.SetTexturePath( 'res:/UI/Texture/Icons/73_16_195.png') self.toggleRightBtn.tooltipPanelClassInfo.headerText = GetByLabel( 'Tooltips/FittingWindow/CollapseSidePane') uicore.animations.MorphScalar(self, 'width', self.width, self._fixedWidth, duration=ANIM_DURATION) uicore.animations.MorphScalar(self.rightPanel, 'width', self.rightPanel.width, PANEL_WIDTH, duration=ANIM_DURATION) uicore.animations.FadeTo(self.rightPanel, self.rightPanel.opacity, 1.0, duration=ANIM_DURATION, sleep=True) else: self.toggleRightBtn.SetTexturePath( 'res:/UI/Texture/Icons/73_16_196.png') self.toggleRightBtn.tooltipPanelClassInfo.headerText = GetByLabel( 'Tooltips/FittingWindow/ExpandSidePane') uicore.animations.MorphScalar(self, 'width', self.width, self._fixedWidth, duration=ANIM_DURATION) uicore.animations.MorphScalar(self.rightPanel, 'width', self.rightPanel.width, 0, duration=ANIM_DURATION) uicore.animations.FadeTo(self.rightPanel, self.rightPanel.opacity, 0.0, duration=ANIM_DURATION, sleep=True) self.toggleRightBtn.state = uiconst.UI_NORMAL def ToggleLeftPanel(self, *args): isExpanded = not self.IsLeftPanelExpanded() settings.user.ui.Set('fittingPanelLeft2', isExpanded) self._fixedWidth = self.GetWindowWidth() self.toggleLeftBtn.state = uiconst.UI_DISABLED if isExpanded: self.toggleLeftBtn.SetTexturePath( 'res:/UI/Texture/Icons/73_16_196.png') self.toggleLeftBtn.tooltipPanelClassInfo.headerText = GetByLabel( 'Tooltips/FittingWindow/CollapseSidePane') uicore.animations.MorphScalar(self, 'width', self.width, self._fixedWidth, duration=ANIM_DURATION) uicore.animations.MorphScalar(self, 'left', self.left, self.left - PANEL_WIDTH, duration=ANIM_DURATION) uicore.animations.MorphScalar(self.leftPanel, 'width', self.leftPanel.width, PANEL_WIDTH, duration=ANIM_DURATION) uicore.animations.FadeTo(self.leftPanel, self.leftPanel.opacity, 1.0, duration=ANIM_DURATION, sleep=True) uthread.new(self.skinPanel.Load) else: self.toggleLeftBtn.SetTexturePath( 'res:/UI/Texture/Icons/73_16_195.png') self.toggleLeftBtn.tooltipPanelClassInfo.headerText = GetByLabel( 'Tooltips/FittingWindow/ExpandSidePane') uicore.animations.MorphScalar(self, 'width', self.width, self._fixedWidth, duration=ANIM_DURATION) uicore.animations.MorphScalar(self, 'left', self.left, self.left + PANEL_WIDTH, duration=ANIM_DURATION) uicore.animations.MorphScalar(self.leftPanel, 'width', self.leftPanel.width, 0, duration=ANIM_DURATION) uicore.animations.FadeTo(self.leftPanel, self.leftPanel.opacity, 0.0, duration=ANIM_DURATION, sleep=True) self.toggleLeftBtn.state = uiconst.UI_NORMAL def GetWindowWidth(self): width = GetBaseShapeSize() + 16 if self.IsLeftPanelExpanded(): width += PANEL_WIDTH if self.IsRightPanelExpanded(): width += PANEL_WIDTH return width def OnSetDevice(self): if self.controller and self.controller.GetItemID(): uthread.new(self.ConstructLayout) def InitializeStatesAndPosition(self, *args, **kw): current = self.GetRegisteredPositionAndSize() default = self.GetDefaultSizeAndPosition() fixedHeight = self._fixedHeight fixedWidth = self.GetWindowWidth() Window.InitializeStatesAndPosition(self, *args, **kw) if fixedWidth is not None: self.width = fixedWidth self._fixedWidth = fixedWidth if fixedHeight is not None: self.height = fixedHeight self._fixedHeight = fixedHeight if list(default) == list(current)[:4]: settings.user.ui.Set('defaultFittingPosition', 1) dw = uicore.desktop.width dh = uicore.desktop.height self.left = (dw - self.width) / 2 self.top = (dh - self.height) / 2 self.MakeUnpinable() self.Unlock() uthread.new(uicore.registry.SetFocus, self) self._collapseable = 0 def _OnClose(self, *args): settings.user.ui.Set('defaultFittingPosition', 0) def MouseDown(self, *args): uthread.new(uicore.registry.SetFocus, self) SetOrder(self, 0) def GhostFitItem(self, ghostItem=None): if not self.controller: return uthread.new(self.controller.SetGhostFittedItem, ghostItem) def OnStartMinimize_(self, *args): sm.ChainEvent('ProcessFittingWindowStartMinimize') def OnEndMinimize_(self, *args): sm.ChainEvent('ProcessFittingWindowEndMinimize') def OnUIScalingChange(self, *args): pass def UpdateStats(self): if not self.windowReady: return self.UpdateCPU() self.UpdatePower() self.UpdateCalibration() self.ReloadDroneAndFighterIconsIfNeeded() def ConstructPowerAndCpuLabels(self): powerGridAndCpuCont = LayoutGrid(parent=self.overlayCont, columns=1, state=uiconst.UI_PICKCHILDREN, align=uiconst.BOTTOMRIGHT, top=10, left=10) cpu_statustextHeader = EveLabelMediumBold( text=GetByLabel('UI/Fitting/FittingWindow/CPUStatusHeader'), name='cpu_statustextHeader', state=uiconst.UI_NORMAL, align=uiconst.TOPRIGHT) SetFittingTooltipInfo(targetObject=cpu_statustextHeader, tooltipName='CPU') powerGridAndCpuCont.AddCell(cpu_statustextHeader) self.cpu_statustext = EveLabelMedium(text='', name='cpu_statustext', state=uiconst.UI_NORMAL, align=uiconst.TOPRIGHT) SetFittingTooltipInfo(targetObject=self.cpu_statustext, tooltipName='CPU') powerGridAndCpuCont.AddCell(self.cpu_statustext) powerGridAndCpuCont.AddCell(cellObject=Container( name='spacer', align=uiconst.TOTOP, height=10)) power_statustextHeader = EveLabelMediumBold( text=GetByLabel('UI/Fitting/FittingWindow/PowergridHeader'), name='power_statustextHeader', state=uiconst.UI_NORMAL, align=uiconst.TOPRIGHT) SetFittingTooltipInfo(targetObject=power_statustextHeader, tooltipName='PowerGrid') powerGridAndCpuCont.AddCell(power_statustextHeader) self.power_statustext = EveLabelMedium(text='', name='power_statustext', state=uiconst.UI_NORMAL, align=uiconst.TOPRIGHT) powerGridAndCpuCont.AddCell(self.power_statustext) SetFittingTooltipInfo(targetObject=self.power_statustext, tooltipName='PowerGrid') self.calibration_statustext = EveLabelMedium( text='', parent=self.overlayCont, name='calibrationstatustext', pos=(8, 50, 0, 0), idx=0, state=uiconst.UI_NORMAL) SetFittingTooltipInfo(targetObject=self.calibration_statustext, tooltipName='Calibration') def UpdateCPU(self): cpuLoad = self.controller.GetCPULoad() cpuOutput = self.controller.GetCPUOutput() self.cpu_statustext.text = GetByLabel( 'UI/Fitting/FittingWindow/CpuStatusText', cpuLoad=cpuOutput.value - cpuLoad.value, cpuOutput=cpuOutput.value, startColorTag1='<color=%s>' % hex(GetXtraColor2(cpuLoad.diff)), startColorTag2='<color=%s>' % hex(GetXtraColor2(cpuOutput.diff)), endColorTag='</color>') def UpdatePower(self): powerLoad = self.controller.GetPowerLoad() powerOutput = self.controller.GetPowerOutput() self.power_statustext.text = GetByLabel( 'UI/Fitting/FittingWindow/PowerStatusText', powerLoad=powerOutput.value - powerLoad.value, powerOutput=powerOutput.value, startColorTag3='<color=%s>' % hex(GetXtraColor2(powerLoad.diff)), startColorTag4='<color=%s>' % hex(GetXtraColor2(powerOutput.diff)), endColorTag='</color>') def UpdateCalibration(self): calibrationLoad = self.controller.GetCalibrationLoad() calibrationOutput = self.controller.GetCalibrationOutput() self.calibration_statustext.text = GetByLabel( 'UI/Fitting/FittingWindow/CalibrationStatusText', calibrationLoad=calibrationOutput.value - calibrationLoad.value, calibrationOutput=calibrationOutput.value, startColorTag1='<color=%s>' % hex(GetXtraColor2(calibrationLoad.diff)), startColorTag2='<color=%s>' % FONTCOLOR_DEFAULT, endColorTag='</color>') def Close(self, setClosed=False, *args, **kwds): Window.Close(self, setClosed, *args, **kwds) if self.controller: self.controller.Close()
def Load(self, node): if node.selected: self.Select() else: self.Deselect() newResult = False if hasattr(node, 'newResult'): if node.newResult: newResult = True normalColor, hiColor, loColor = self.red, self.redHi, self.redLo if 0.25 < node.result.certainty <= 0.75: normalColor, hiColor, loColor = self.orange, self.orangeHi, self.orangeLo if node.result.certainty > 0.75: normalColor, hiColor, loColor = self.green, self.greenHi, self.greenLo newCert = node.result.certainty oldCert = node.result.prevCertainty certChange = newCert - oldCert signalText = '' from eve.client.script.ui.control.entries import IsResultWithinWarpDistance if node.result.isPerfect and IsResultWithinWarpDistance( node.result) and InShipInSpace(): if not self.warpButton: self.warpButton = ButtonIcon( name='warpButton', func=self.WarpToAction, parent=self.signalColumn, align=uiconst.CENTERRIGHT, width=22, left=6, iconSize=22, texturePath='res:/UI/Texture/Icons/44_32_18.png', hint=localization.GetByLabel('UI/Commands/WarpTo')) if newResult: uicore.animations.SpGlowFadeIn(self.warpButton.icon, glowFactor=1, glowColor=(0.8, 0.8, 0.8, 0.6), glowExpand=0, duration=1, loops=3) else: signalText = localization.GetByLabel('UI/Common/Percentage', percentage=newCert * 100) if newCert or oldCert: if certChange > 0: baseProportion = oldCert changeProportion = certChange changeColor = hiColor else: changeProportion = min(newCert, abs(certChange)) baseProportion = max(0.0, newCert - changeProportion) changeColor = loColor graphData = [] graphData.append(('base', baseProportion, normalColor)) graphData.append(('change', changeProportion, changeColor)) self.statusBar.LoadGraphData(graphData, animateIn=True) self.distanceColumn.label.text = FmtDist(node.distance) self.idColumn.label.text = node.result.id self.nameColumn.label.text = node.displayName self.groupColumn.label.text = node.groupName self.signalColumn.label.text = signalText if newResult: node.newResult = False self.OnColumnResize(node.columnWidths)
class MapViewSearchControl(Container): default_align = uiconst.TOPLEFT default_width = 160 default_height = 20 searchInput = None searchResult = None searchFor = None mapView = None scrollListResult = None def ApplyAttributes(self, attributes): Container.ApplyAttributes(self, attributes) if attributes.mapView: self.mapView = weakref.ref(attributes.mapView) self.icon = ButtonIcon( parent=self, align=uiconst.CENTERRIGHT, texturePath='res:/UI/Texture/Icons/searchMagnifyingGlass.png', pos=(0, 0, 24, 24), state=uiconst.UI_NORMAL, iconSize=24) self.icon.OnClick = self.ClickIcon self.searchFor = [ const.searchResultConstellation, const.searchResultSolarSystem, const.searchResultRegion, const.searchResultStation ] searchInput = SearchInput( name='MapViewSearchEdit', parent=self, align=uiconst.TOPRIGHT, width=0, maxLength=64, GetSearchEntries=self.GetSearchData, OnSearchEntrySelected=self.OnSearchEntrySelected, OnReturn=self.OnSearchInputConfirm, OnResultMenuClosed=self.OnResultMenuClosed, hinttext=GetByLabel('UI/Common/Buttons/Search'), opacity=0.0, setvalue=settings.char.ui.Get('mapView_searchString', None)) searchInput.searchResultVisibleEntries = 10 searchInput.SetHistoryVisibility(False) searchInput.OnFocusLost = self.OnSearchFocusLost self.searchInput = searchInput def ClickIcon(self, *args): self.ShowInput() def OnSearchFocusLost(self, *args): if not self.searchInput.HasResultMenu(): self.HideInput() def OnResultMenuClosed(self, *args): if uicore.registry.GetFocus() is not self.searchInput: self.HideInput() def ShowInput(self): uicore.registry.SetFocus(self.searchInput) duration = 0.2 uicore.animations.FadeTo(self.searchInput, startVal=self.searchInput.opacity, endVal=1.0, duration=duration) uicore.animations.FadeTo(self.icon, startVal=self.icon.opacity, endVal=0.0, callback=self.icon.Hide, duration=duration) uicore.animations.MorphScalar(self.searchInput, 'width', startVal=self.searchInput.width, endVal=self.width, duration=duration, callback=self.OnInputScaleDone) def HideInput(self): duration = 0.4 uicore.animations.FadeTo(self.searchInput, startVal=self.searchInput.opacity, endVal=0.0, duration=duration) self.icon.Show() uicore.animations.FadeTo(self.icon, startVal=self.icon.opacity, endVal=1.0, duration=duration) uicore.animations.MorphScalar(self.searchInput, 'width', startVal=self.searchInput.width, endVal=0, duration=duration) def OnInputScaleDone(self, *args): resultMenu = self.searchInput.GetResultMenu() if resultMenu: l, t, w, h = self.GetAbsolute() resultMenu.left = l uthread.new(self.searchInput.SearchForData) def GetSearchData(self, searchString): self.scrollListResult = [] searchString = Encode(searchString) searchString = searchString.lstrip() settings.char.ui.Set('mapView_searchString', searchString) if len(searchString) >= 64: self.scrollListResult.append( ScrollEntryNode( label=GetByLabel('UI/Common/SearchStringTooLong'))) elif len(searchString) >= const.searchMinWildcardLength: self.searchInput.SetValue(searchString, docallback=False) results = Search(searchString, self.searchFor, getWindow=False) self.scrollListResult = self.PrepareResultScrollEntries(results) return self.scrollListResult def PrepareResultScrollEntries(self, results, *args): scrollList = [] if not results: scrollList.append( ScrollEntryNode(label=GetByLabel( 'UI/Search/UniversalSearch/NoResultsReturned'))) else: for groupEntry in results: entryType, typeList = groupEntry['groupItems'] for entryData in typeList: scrollList.append( ScrollEntryNode(decoClass=SearchResultEntry, **entryData)) return scrollList def OnSearchInputConfirm(self, *args, **kwds): if self.scrollListResult and len(self.scrollListResult) == 1: self.OnSearchEntrySelected(self.scrollListResult) def OnSearchEntrySelected(self, selectedDataList, *args, **kwds): self.delaySelectionTimer = AutoTimer( 500, self._OnSearchEntrySelectedDelayed, selectedDataList) def _OnSearchEntrySelectedDelayed(self, selectedDataList, *args, **kwds): self.delaySelectionTimer = None if self.mapView: mapView = self.mapView() if mapView: mapView.LoadSearchResult(selectedDataList)
class SettingSectionHeaderWithGroups(SettingSectionHeaderBase): def ApplyAttributes(self, attributes): SettingSectionHeaderBase.ApplyAttributes(self, attributes) self.expanderFunc = attributes.expanderFunc arrowTexturePath = self.GetExpandedTexture() left = SECTION_LABEL_LEFT - 20 self.expandArrow = ButtonIcon(name='expandArrow', parent=self, align=uiconst.CENTERLEFT, pos=(left, 0, 16, 16), iconSize=16, texturePath=arrowTexturePath, func=self.OnExpanderClicked) self.addGroupBtn = ButtonIcon( name='addBtn', parent=self, align=uiconst.CENTERRIGHT, pos=(6, 0, 12, 12), iconSize=12, texturePath='res:/UI/Texture/Icons/Plus_Small.png', func=self.OnAddEntry) self.rigthCont.width = 20 self.ChangeRightContDisplay(False) def GetExpandedTexture(self): isExpanded = settings.user.ui.Get(UI_EXPANDED_SETTING % self.settingID, True) if isExpanded: return 'res:/UI/Texture/Icons/38_16_229.png' else: return 'res:/UI/Texture/Icons/38_16_228.png' def OnClick(self, *args): self.OnExpanderClicked() def OnExpanderClicked(self, *args): isExpanded = settings.user.ui.Get(UI_EXPANDED_SETTING % self.settingID, True) settings.user.ui.Set(UI_EXPANDED_SETTING % self.settingID, not isExpanded) self.expanderFunc() self.expandArrow.SetTexturePath(self.GetExpandedTexture()) def FadeSprites(self, toValue): SettingSectionHeaderBase.FadeSprites(self, toValue) def OnAddEntry(self, *args): carbonui.control.menu.ShowMenu(self) def GetMenu(self, *args): m = [] if CanHaveGroups(self.settingID): accessGroupsController = sm.GetService( 'structureControllers').GetAccessGroupController() myGroups = accessGroupsController.GetMyGroups() if myGroups: m += [[ MenuLabel('UI/StructureSettingWnd/AddGroupToSetting'), ('isDynamic', self._GetMyGroupsMenu, (myGroups, )) ]] m += [(MenuLabel('UI/StructureSettingWnd/ManageAccessGroups'), uicore.cmd.OpenAccessGroupsWindow, ())] return m def _GetMyGroupsMenu(self, myGroups): m = [] groupsWithSetting = self.structureProfileController.GetGroupsBySettingID( self.settingID) groupIDs = {g.groupID for g in groupsWithSetting} for groupID, g in myGroups.iteritems(): if groupID in groupIDs: continue groupName = g.name m.append( (groupName.lower(), (groupName, self.AddGroupsToSettingSection, ([groupID], )))) m = SortListOfTuples(m) return m def ChangeRightContDisplay(self, show=False): self.rigthCont.display = show def OnDropData(self, dragSource, dragData): if not dragData or not CanHaveGroups(settingID=self.settingID): return if not AreGroupNodes(dragData): return groupIDsToAdd = filter( None, [GetGroupIDFromNode(eachNode) for eachNode in dragData]) if groupIDsToAdd: self.AddGroupsToSettingSection(groupIDsToAdd) def AddGroupsToSettingSection(self, groupIDsToAdd): self.structureProfileController.AddNewGroups(self.settingID, groupIDsToAdd)
class ShipUI(LayerCore): __notifyevents__ = ['OnShipScanCompleted', 'OnJamStart', 'OnJamEnd', 'OnCargoScanComplete', 'DoBallRemove', 'OnSetDevice', 'OnAssumeStructureControl', 'OnRelinquishStructureControl', 'OnUIRefresh', 'OnUIScalingChange', 'ProcessPendingOverloadUpdate', 'OnSafeLogoffTimerStarted', 'OnSafeLogoffActivated', 'OnSafeLogoffAborted', 'OnSafeLogoffFailed', 'DoBallsRemove', 'OnSetCameraOffset', 'ProcessShipEffect', 'OnStateChange'] def ApplyAttributes(self, attributes): LayerCore.ApplyAttributes(self, attributes) self.setupShipTasklet = None self.updateTasklet = None self.controller = ActiveShipController() self.controller.on_new_itemID.connect(self.OnShipChanged) self.ResetSelf() def Close(self): LayerCore.Close(self) self.controller.Close() def OnSetCameraOffset(self, cameraOffset): self.UpdatePosition() def OnSetDevice(self): self.UpdatePosition() def OnUIScalingChange(self, *args): self.OnUIRefresh() def OnUIRefresh(self): self.CloseView(recreate=False) self.OpenView() @telemetry.ZONE_METHOD def ResetSelf(self): self.sr.safetyButton = None self.fighterHudBinding = None self.sr.selectedcateg = 0 self.sr.pendingreloads = [] self.sr.reloadsByID = {} self.sr.rampTimers = {} self.shipuiReady = False self.initing = None self.jammers = {} self.assumingdelay = None if self.updateTasklet is not None: self.updateTasklet.kill() self.updateTasklet = None if self.setupShipTasklet is not None: self.setupShipTasklet.kill() self.setupShipTasklet = None self.logoffTimer = None self.Flush() def CheckPendingReloads(self): if self.sr.pendingreloads: rl = self.sr.pendingreloads[0] while rl in self.sr.pendingreloads: self.sr.pendingreloads.remove(rl) module = self.GetModule(rl) if module: module.AutoReload() def CheckSession(self, change): if sm.GetService('autoPilot').GetState(): self.OnAutoPilotOn() else: self.OnAutoPilotOff() @telemetry.ZONE_METHOD def UpdatePosition(self): cameraOffset = sm.GetService('sceneManager').GetCameraOffset() halfWidth = uicore.desktop.width / 2 baseOffset = -cameraOffset * halfWidth wndLeft = settings.char.windows.Get('shipuialignleftoffset', 0) maxRight, minLeft = self.GetShipuiOffsetMinMax() self.hudContainer.left = min(maxRight, max(minLeft, baseOffset + wndLeft)) self.ewarCont.left = self.hudContainer.left if IsShipHudTopAligned(): self.hudContainer.SetAlign(uiconst.CENTERTOP) self.ewarCont.SetAlign(uiconst.CENTERTOP) self.sr.indicationContainer.top = self.hudContainer.height + self.ewarCont.height else: self.hudContainer.SetAlign(uiconst.CENTERBOTTOM) self.ewarCont.SetAlign(uiconst.CENTERBOTTOM) self.sr.indicationContainer.top = -(self.ewarCont.height + self.sr.indicationContainer.height) if self.IsFightersDetached(): left, top = settings.char.ui.Get('fightersDetachedPosition', (0, 0)) buttonWidth = 32 left = min(left, uicore.desktop.width - buttonWidth) top = min(top, uicore.desktop.height - self.fighterCont.height) self.fighterCont.left = left self.fighterCont.top = top settings.char.ui.Set('fightersDetachedPosition', (left, top)) self.AlignFighters() self.sr.shipAlertContainer.UpdatePosition() def MakeFighterHudBinding(self): cs = uicore.uilib.bracketCurveSet self.fighterHudBinding = trinity.CreatePythonBinding(cs, self.compass, 'absoluteRight', self.fighterCont, 'left') def RemoveFighterHudBinding(self): if self.fighterHudBinding: cs = uicore.uilib.bracketCurveSet cs.bindings.fremove(self.fighterHudBinding) self.fighterHudBinding = None def OnShipMouseDown(self, wnd, btn, *args): if btn != 0: return self.dragging = True if not self.hudContainer: return self.grab = [uicore.uilib.x, self.hudContainer.left] uthread.new(self.BeginDrag) def GetShipuiOffsetMinMax(self, *args): magicNumber = 275 if self.CheckShipHasFighterBay(): magicNumber = 300 sidePanelsLeft, sidePanelsRight = uicore.layer.sidepanels.GetSideOffset() maxRight = uicore.desktop.width / 2 - self.slotsContainer.width / 2 - magicNumber - sidePanelsRight minLeft = -(uicore.desktop.width / 2 - 180) + sidePanelsLeft return (maxRight, minLeft) def OnToggleShipSelected(self, *args): if not self.CheckShipHasFighterBay(): return if not self.IsFightersShown(): self.DeselectShip() return x, y = self.grab currentX, currentY = uicore.uilib.x, self.hudContainer.left if x != currentX or y != currentY: return if uicore.uilib.Key(uiconst.VK_CONTROL): if movementFunctions.IsSelectedForNavigation(session.shipid): self.DeselectShip() else: self.SelectShip() else: self.SelectShip() self.fighterCont.ClearSelection() def SelectShip(self): movementFunctions.SelectForNavigation(session.shipid) def DeselectShip(self): movementFunctions.DeselectForNavigation(session.shipid) def OnStateChange(self, itemID, flag, flagState, *args): if not self.CheckShipHasFighterBay(): return if flag == states.selectedForNavigation and itemID == session.shipid: if flagState: self.ShowSelectionHilite() else: self.HideSelectionHilite() def ShowSelectionHilite(self): if self.shipSelectHilight.display: return self.shipSelectHilight.display = True self.ringSprite.opacity = 0.2 self.bracketSprite.opacity = 3.0 uicore.animations.FadeTo(self.ringSprite, self.ringSprite.opacity, 1.0, duration=0.2) uicore.animations.FadeTo(self.bracketSprite, self.bracketSprite.opacity, 1.0, duration=0.2) def HideSelectionHilite(self): self.shipSelectHilight.display = False def OnShipMouseUp(self, wnd, btn, *args): if btn != 0: return sm.StartService('ui').ForceCursorUpdate() self.dragging = False def BeginDrag(self, *args): cameraOffset = sm.GetService('sceneManager').GetCameraOffset() halfWidth = uicore.desktop.width / 2 baseOffset = -cameraOffset * halfWidth while not self.hudContainer.destroyed and getattr(self, 'dragging', 0): uicore.uilib.SetCursor(uiconst.UICURSOR_DIVIDERADJUST) maxRight, minLeft = self.GetShipuiOffsetMinMax() grabMouseDiff = uicore.uilib.x - self.grab[0] combinedOffset = min(maxRight, max(minLeft, self.grab[1] + grabMouseDiff)) dragOffset = combinedOffset - baseOffset if -8 <= dragOffset <= 8: settings.char.windows.Set('shipuialignleftoffset', 0) self.hudContainer.left = baseOffset else: self.hudContainer.left = combinedOffset settings.char.windows.Set('shipuialignleftoffset', dragOffset) self.ewarCont.left = self.hudContainer.left blue.pyos.synchro.SleepWallclock(1) def ConstructOverlayContainer(self): self.toggleLeftBtn = Sprite(parent=self.overlayContainer, name='expandBtnLeft', pos=(56, 122, 28, 28), align=uiconst.TOPLEFT, state=uiconst.UI_NORMAL, texturePath='res:/UI/Texture/classes/ShipUI/expandBtnLeft.png') self.toggleLeftBtn.OnClick = self.ToggleHudButtons hudButtonsExpanded = settings.user.ui.Get('hudButtonsExpanded', 1) self.toggleLeftBtn.hint = [GetByLabel('UI/Inflight/ShowButtons'), GetByLabel('UI/Inflight/HideButtons')][hudButtonsExpanded] self.optionsCont = Container(parent=self.overlayContainer, name='optionsCont', pos=(190, 190, 16, 16), align=uiconst.TOPLEFT, state=uiconst.UI_PICKCHILDREN) self.moduleToggleCont = Container(parent=self.overlayContainer, name='moduleToggleCont', pos=(206, 170, 24, 24), align=uiconst.TOPLEFT, state=uiconst.UI_PICKCHILDREN) if not IsControllingStructure(): self.stopButton = StopButton(parent=self.overlayContainer, align=uiconst.TOPLEFT, controller=self.controller, left=75, top=155) self.maxspeedButton = MaxSpeedButton(parent=self.overlayContainer, align=uiconst.TOPLEFT, controller=self.controller, left=168, top=155) @telemetry.ZONE_METHOD def OnOpenView(self): self.ResetSelf() self.state = uiconst.UI_HIDDEN self.hudContainer = Container(name='hudContainer', parent=self, controller=self.controller, align=uiconst.CENTERBOTTOM, width=SHIP_UI_WIDTH, height=SHIP_UI_HEIGHT) self.overlayContainer = Container(parent=self.hudContainer, name='overlayContainer', pos=(0, 0, 256, 256), align=uiconst.CENTER, state=uiconst.UI_PICKCHILDREN, idx=0) self.ConstructOverlayContainer() if IsControllingStructure(): shipShape = StructureHUDShape(parent=self.hudContainer, align=uiconst.CENTER) else: shipShape = HUDShape(parent=self.hudContainer, align=uiconst.CENTER) self.shipuiMainShape = shipShape.shipuiMainShape self.capacitorContainer = CapacitorContainer(parent=self.hudContainer, align=uiconst.CENTER, top=-1, controller=self.controller) self.capacitorContainer.OnMouseDown = (self.OnShipMouseDown, self.capacitorContainer) self.capacitorContainer.OnMouseUp = (self.OnShipMouseUp, self.capacitorContainer) self.capacitorContainer.OnClick = self.OnToggleShipSelected heatPicker = Container(name='heatPicker', parent=self.hudContainer, align=uiconst.CENTER, width=160, height=160, pickRadius=43, state=uiconst.UI_NORMAL) self.heatGauges = HeatGauges(parent=heatPicker, align=uiconst.CENTERTOP, controller=self.controller) self.hpGauges = HPGauges(name='healthGauges', parent=self.hudContainer, align=uiconst.CENTER, pos=(0, -37, 148, 74), controller=self.controller) if IsControllingStructure(): ReleaseControlBtn(parent=self.hudContainer, top=29, align=uiconst.CENTERBOTTOM, itemID=self.controller.GetItemID(), func=sm.GetService('structureControl').Alight) else: self.speedGauge = SpeedGauge(parent=self.hudContainer, top=29, align=uiconst.CENTERBOTTOM, controller=self.controller) self.compass = Compass(parent=self.hudContainer, pickRadius=-1) self.shipSelectHilight = Container(name='navSelectHilight', parent=self.compass, align=uiconst.CENTER, state=uiconst.UI_DISABLED, width=206, height=206) self.ringSprite = Sprite(bgParent=self.shipSelectHilight, texturePath='res:/UI/Texture/classes/ShipUI/Fighters/selectionRingLarge.png') self.bracketSprite = Sprite(bgParent=self.shipSelectHilight, texturePath='res:/UI/Texture/classes/ShipUI/Fighters/selectionBracketLarge.png') self.shipSelectHilight.display = False self.slotsContainer = SlotsContainer(parent=self.hudContainer, pos=(SLOTS_CONTAINER_LEFT, SLOTS_CONTAINER_TOP, SLOTS_CONTAINER_WIDTH, SLOTS_CONTAINER_HEIGHT), align=uiconst.CENTERLEFT, state=uiconst.UI_PICKCHILDREN, controller=self.controller) self.stanceButtons = StanceButtons(parent=self.hudContainer, pos=(SLOTS_CONTAINER_LEFT + 8, 1, 40, 120), name='stanceButtons', align=uiconst.CENTERLEFT, state=uiconst.UI_PICKCHILDREN, buttonSize=36) self.hudButtons = HudButtonsCont(parent=self.hudContainer, align=uiconst.CENTERRIGHT, left=690, top=15) self.ewarCont = EwarContainer(parent=self, align=uiconst.CENTERBOTTOM, top=SHIP_UI_HEIGHT, height=EWAR_CONTAINER_HEIGHT, width=EWAR_CONTAINER_WIDTH) self.sr.shipAlertContainer = ShipAlertContainer(parent=self.hudContainer) self.sr.indicationContainer = Container(parent=self.hudContainer, name='indicationContainer', align=uiconst.CENTERTOP, pos=(0, 0, 400, 50)) self.sr.safetyButton = SafetyButton(parent=self.overlayContainer, left=40, top=28) self.ConstructReadoutCont() self.settingsMenu = UtilMenu(menuAlign=uiconst.BOTTOMLEFT, parent=self.optionsCont, align=uiconst.TOPLEFT, GetUtilMenu=self.GetHUDOptionMenu, pos=(0, 0, 16, 16), texturePath='res:/UI/Texture/Icons/73_16_50.png', hint=GetByLabel('UI/Inflight/Options')) self.moduleToggleBtn = ButtonIcon(name='moduleToggleBtn', parent=self.moduleToggleCont, align=uiconst.TOPLEFT, width=24, height=24, iconSize=24, texturePath='res:/UI/Texture/classes/ShipUI/Fighters/toggleModules_Up.png', downTexture='res:/UI/Texture/classes/ShipUI/Fighters/toggleModules_Down.png', hoverTexture='res:/UI/Texture/classes/ShipUI/Fighters/toggleModules_Over.png', func=self.OnToggleHudModules) self.moduleToggleBtn.display = False self.DrawFighters() self.hudContainer.state = uiconst.UI_PICKCHILDREN self.UpdatePosition() self.shipuiReady = True self.SetupShip() def DrawFighters(self): if hasattr(self, 'fighterCont'): self.fighterCont.Close() self.fighterCont = SquadronsUI(name='fighters', parent=self, state=uiconst.UI_PICKCHILDREN, parentFunc=self.OnToggleFightersDetached) self.AlignFighters() if self.IsFightersDetached(): left, top = settings.char.ui.Get('fightersDetachedPosition', (uicore.desktop.width / 2, uicore.desktop.height / 2 - 60)) self.fighterCont.left = left self.fighterCont.top = top self.slotsContainer.display = True self.moduleToggleBtn.Disable() self.SetFighterButtonsHint() self.fighterCont.KeepSelection() def SetFighterButtonsHint(self): if self.IsFightersDetached(): self.fighterCont.fighterToggleBtn.hint = GetByLabel('UI/Inflight/HUDOptions/ClickToAttach') self.moduleToggleBtn.hint = '' else: self.fighterCont.fighterToggleBtn.hint = GetByLabel('UI/Inflight/HUDOptions/DragToDetach') self.moduleToggleBtn.hint = GetByLabel('UI/Inflight/HUDOptions/ClickToToggle') def CheckShipHasFighterBay(self): shipTypeID = self.controller.GetTypeID() godmaSM = sm.GetService('godma').GetStateManager() return godmaSM.GetType(shipTypeID).fighterCapacity > 0 def OptionsBtnMouseEnter(self, *args): self.options.SetAlpha(1.0) def OptionsBtnMouseExit(self, *args): self.options.SetAlpha(0.8) def CheckControl(self): control = sm.GetService('pwn').GetCurrentControl() if control: self.OnAssumeStructureControl() def SetButtonState(self): if settings.user.ui.Get('hudButtonsExpanded', 1): self.hudButtons.state = uiconst.UI_PICKCHILDREN if IsControllingStructure(): self.hudButtons.autopilotBtn.Disable() else: self.hudButtons.autopilotBtn.Enable() else: self.hudButtons.state = uiconst.UI_HIDDEN def ConstructReadoutLabel(self, refName): cont = ContainerAutoSize(name=refName, parent=self.readoutCont, align=uiconst.TOTOP) label = EveLabelSmall(parent=cont, left=2, state=uiconst.UI_DISABLED, align=uiconst.TOPRIGHT) Line(parent=cont, top=6, width=-130, height=1, align=uiconst.TOPRIGHT) Line(parent=cont, top=6, width=-130, height=1, align=uiconst.TOPRIGHT, color=(0.1, 0.1, 0.1, 0.5)) return label @telemetry.ZONE_METHOD def ConstructReadoutCont(self): self.readoutCont = ContainerAutoSize(name='readoutCont', parent=self.hudContainer, pos=(278, 22, 200, 0), align=uiconst.TOPLEFT, state=uiconst.UI_HIDDEN) self.readoutShieldLabel = self.ConstructReadoutLabel('shield') self.readoutArmorLabel = self.ConstructReadoutLabel('armor') self.readoutStructureLabel = self.ConstructReadoutLabel('structure') def OnAssumeStructureControl(self, *args): now = blue.os.GetSimTime() self.assumingdelay = now uthread.new(self.DelayedOnAssumeStructureControl, now) def DelayedOnAssumeStructureControl(self, issueTime): blue.pyos.synchro.SleepSim(250) if self.assumingdelay is None: return issuedAt = self.assumingdelay if issuedAt != issueTime: return self.assumingdelay = None self.ShowStructureControl() def ShowStructureControl(self, *args): if self.controller.IsControllingTurret(): self.initing = 1 self.slotsContainer.InitSlots() self.hudButtons.InitButtons() self.initing = 0 def OnRelinquishStructureControl(self, *args): self.SetupShip() def UpdateButtonsForShip(self): itemID = self.controller.GetItemID() typeID = self.controller.GetTypeID() if self.stanceButtons.HasStances(): self._HideStancePanel() self.stanceButtons.UpdateButtonsForShip(itemID, typeID) if self.stanceButtons.HasStances(): self._ShowStancePanel() def _ShowStancePanel(self): self.slotsContainer.left = SLOTS_CONTAINER_LEFT + 44 self.stanceButtons.Show() def _HideStancePanel(self): self.slotsContainer.left = SLOTS_CONTAINER_LEFT self.stanceButtons.Hide() def GetHUDOptionMenu(self, menuParent): showPassive = settings.user.ui.Get('showPassiveModules', 1) text = GetByLabel('UI/Inflight/HUDOptions/DisplayPassiveModules') menuParent.AddCheckBox(text=text, checked=showPassive, callback=self.ToggleShowPassive) showEmpty = settings.user.ui.Get('showEmptySlots', 0) text = GetByLabel('UI/Inflight/HUDOptions/DisplayEmptySlots') menuParent.AddCheckBox(text=text, checked=showEmpty, callback=self.ToggleShowEmpty) showReadout = settings.user.ui.Get('showReadout', 0) text = GetByLabel('UI/Inflight/HUDOptions/DisplayReadout') menuParent.AddCheckBox(text=text, checked=showReadout, callback=self.ToggleReadout) readoutType = settings.user.ui.Get('readoutType', 1) text = GetByLabel('UI/Inflight/HUDOptions/DisplayReadoutAsPercentage') if showReadout: callback = self.ToggleReadoutType else: callback = None menuParent.AddCheckBox(text=text, checked=readoutType, callback=callback) showZoomBtns = settings.user.ui.Get('showZoomBtns', 0) text = GetByLabel('UI/Inflight/HUDOptions/DisplayZoomButtons') menuParent.AddCheckBox(text=text, checked=showZoomBtns, callback=self.ToggleShowZoomBtns) showTooltips = settings.user.ui.Get('showModuleTooltips', 1) text = GetByLabel('UI/Inflight/HUDOptions/DisplayModuleTooltips') menuParent.AddCheckBox(text=text, checked=showTooltips, callback=self.ToggleShowModuleTooltips) lockModules = settings.user.ui.Get('lockModules', 0) text = GetByLabel('UI/Inflight/HUDOptions/LockModulesInPlace') menuParent.AddCheckBox(text=text, checked=lockModules, callback=self.ToggleLockModules) menuParent.AddCheckBox(text=GetByLabel('UI/Inflight/HUDOptions/BlinkCargo'), checked=self.GetCargoBlinkValue(), callback=self.ToggleBlinkCargo) lockOverload = settings.user.ui.Get('lockOverload', 0) text = GetByLabel('UI/Inflight/HUDOptions/LockOverloadState') menuParent.AddCheckBox(text=text, checked=lockOverload, callback=self.ToggleOverloadLock) text = GetByLabel('UI/Inflight/HUDOptions/AlignHUDToTop') cb = menuParent.AddCheckBox(text=text, checked=IsShipHudTopAligned(), callback=self.ToggleAlign) cb.isToggleEntry = False menuParent.AddDivider() text = GetByLabel('UI/Inflight/NotifySettingsWindow/DamageAlertSettings') iconPath = 'res:/UI/Texture/classes/UtilMenu/BulletIcon.png' menuParent.AddIconEntry(icon=iconPath, text=text, callback=self.ShowNotifySettingsWindow) if sm.GetService('logger').IsInDragMode(): text = GetByLabel('UI/Accessories/Log/ExitMessageMovingMode') enterArgs = False else: text = GetByLabel('UI/Accessories/Log/EnterMessageMovingMode') enterArgs = True menuParent.AddIconEntry(icon='res:/UI/Texture/classes/UtilMenu/BulletIcon.png', text=text, callback=(sm.GetService('logger').MoveNotifications, enterArgs)) def ShowNotifySettingsWindow(self): NotifySettingsWindow.Open() def ToggleAlign(self): SetShipHudTopAligned(not IsShipHudTopAligned()) self.UpdatePosition() for each in uicore.layer.abovemain.children[:]: if each.name == 'message': each.Close() break msg = getattr(uicore.layer.target, 'message', None) if msg: msg.Close() def CheckShowReadoutCont(self): if settings.user.ui.Get('showReadout', 0): self.readoutCont.state = uiconst.UI_DISABLED self.hudButtons.top = 30 else: self.readoutCont.state = uiconst.UI_HIDDEN self.hudButtons.top = 15 def ToggleReadout(self): current = not settings.user.ui.Get('showReadout', 0) settings.user.ui.Set('showReadout', current) self.CheckShowReadoutCont() def GetCargoBlinkValue(self): return settings.user.ui.Get('BlinkCargoHudIcon', True) def ToggleBlinkCargo(self): settings.user.ui.Set('BlinkCargoHudIcon', not self.GetCargoBlinkValue()) def ToggleReadoutType(self): current = settings.user.ui.Get('readoutType', 1) settings.user.ui.Set('readoutType', not current) def ToggleShowZoomBtns(self): settings.user.ui.Set('showZoomBtns', not settings.user.ui.Get('showZoomBtns', 0)) self.hudButtons.InitButtons() def ToggleLockModules(self): settings.user.ui.Set('lockModules', not settings.user.ui.Get('lockModules', 0)) self.slotsContainer.CheckGroupAllButton() def ToggleOverloadLock(self): settings.user.ui.Set('lockOverload', not settings.user.ui.Get('lockOverload', 0)) def ToggleShowModuleTooltips(self): settings.user.ui.Set('showModuleTooltips', not settings.user.ui.Get('showModuleTooltips', 1)) def ToggleHudButtons(self): isExpanded = self.hudButtons.state == uiconst.UI_PICKCHILDREN if isExpanded: self.hudButtons.state = uiconst.UI_HIDDEN else: self.hudButtons.state = uiconst.UI_PICKCHILDREN settings.user.ui.Set('hudButtonsExpanded', not isExpanded) sm.GetService('ui').StopBlink(self.toggleLeftBtn) self.CheckExpandBtns() def OnToggleHudModules(self, *args): settings.user.ui.Set('displayFighterUI', not settings.user.ui.Get('displayFighterUI', False)) self.ShowHideFighters() def OnToggleFightersDetached(self, *args): isDetached = self.IsFightersDetached() settings.user.ui.Set('detachFighterUI', not isDetached) if isDetached: self.AttachHudModules() else: self.DetachHudModules() def AttachHudModules(self): self.moduleToggleBtn.Enable() self.AlignFighters() self.fighterCont.left = 0 self.fighterCont.top = 10 self.MakeFighterHudBinding() self.ShowHideFighters() self.SetFighterButtonsHint() def DetachHudModules(self): self.moduleToggleBtn.Disable() self.slotsContainer.display = True self.RemoveFighterHudBinding() self.DrawFighters() def InitFighters(self): if not self.IsFightersDetached(): self.MakeFighterHudBinding() self.ShowHideFighters() else: self.DetachHudModules() self.slotsContainer.display = True def ShowHideFighters(self): displayFighters = self.IsFightersShown() isDetached = self.IsFightersDetached() if self.CheckShipHasFighterBay(): if isDetached: self.fighterCont.display = True self.slotsContainer.display = True return if displayFighters == True: self.fighterCont.display = True self.slotsContainer.display = False return self.fighterCont.ClearSelection() self.fighterCont.display = False self.slotsContainer.display = True self.DeselectShip() def AlignFighters(self): if self.IsFightersDetached(): self.fighterCont.SetAlign(uiconst.TOPLEFT) elif IsShipHudTopAligned(): self.fighterCont.SetAlign(uiconst.TOTOP) else: self.fighterCont.SetAlign(uiconst.TOBOTTOM) self.fighterCont.top = 10 def IsFightersDetached(self): return settings.user.ui.Get('detachFighterUI', False) def IsFightersShown(self): return settings.user.ui.Get('displayFighterUI', False) def CheckExpandBtns(self): on = settings.user.ui.Get('hudButtonsExpanded', 1) if on: self.toggleLeftBtn.LoadTexture('res:/UI/Texture/classes/ShipUI/expandBtnRight.png') else: self.toggleLeftBtn.LoadTexture('res:/UI/Texture/classes/ShipUI/expandBtnLeft.png') self.toggleLeftBtn.hint = [GetByLabel('UI/Inflight/ShowButtons'), GetByLabel('UI/Inflight/HideButtons')][on] def AddBookmarks(self, bookmarkIDs): isMove = not uicore.uilib.Key(uiconst.VK_SHIFT) sm.GetService('invCache').GetInventoryFromId(session.shipid).AddBookmarks(bookmarkIDs, const.flagCargo, isMove) def Scanner(self, button): self.expandTimer = None uicore.layer.menu.Flush() radialMenu = RadialMenuScanner(name='radialMenu', parent=uicore.layer.menu, state=uiconst.UI_NORMAL, align=uiconst.TOPLEFT, anchorObject=button) uicore.layer.menu.radialMenu = radialMenu uicore.uilib.SetMouseCapture(radialMenu) def BlinkButton(self, key): self.slotsContainer.BlinkButton(key) def ChangeOpacityForRange(self, currentRange, *args): if getattr(self, 'slotContainer', None): self.slotsContainer.ChangeOpacityForRange(self, currentRange) def ResetModuleButtonOpacity(self, *args): if getattr(self, 'slotContainer', None): self.slotsContainer.ResetModuleButtonOpacity() def ToggleRackOverload(self, slotName): self.slotsContainer.ToggleRackOverload(slotName) def ProcessPendingOverloadUpdate(self, moduleIDs): self.slotsContainer.ProcessPendingOverloadUpdate(moduleIDs) def ResetSwapMode(self): self.slotsContainer.ResetSwapMode() def StartDragMode(self, itemID, typeID): self.slotsContainer.StartDragMode(itemID, typeID) def GetPosFromFlag(self, slotFlag): return self.slotsContainer.GetPosFromFlag(slotFlag) def GetSlotByName(self, name): return self.slotsContainer.FindChild(name) def ChangeSlots(self, toFlag, fromFlag): self.slotsContainer.ChangeSlots(toFlag, fromFlag) def SwapSlots(self, slotFlag1, slotFlag2): self.slotsContainer.SwapSlots(slotFlag1, slotFlag2) def LinkWeapons(self, master, slave, slotFlag1, slotFlag2, merge = False): self.slotsContainer.LinkWeapons(master, slave, slotFlag1, slotFlag2, merge) def GetModuleType(self, flag): return self.slotsContainer.GetModuleType(flag) def GetModuleFromID(self, moduleID): return self.slotsContainer.GetModuleFromID(moduleID) def ToggleShowEmpty(self): self.slotsContainer.ToggleShowEmpty() def ToggleShowPassive(self): self.slotsContainer.ToggleShowPassive() def GetModuleForFKey(self, key): return self.slotsContainer.GetModuleForFKey(key) def GetModule(self, moduleID): return self.slotsContainer.GetModule(moduleID) def OnF(self, sidx, gidx): if not self.CheckShipHasFighterBay(): self.slotsContainer.OnF(sidx, gidx) return shipIsSelected, fightersSelected = movementFunctions.GetSelectedShipAndFighters() if self.IsFightersDetached(): moduleIsActive = self.IsModuleActiveForFKey(sidx, gidx) isAllAbilitiesActiveOrInCooldown = GetShipFighterState().IsAllAbilitiesInSlotActiveOrInCooldown(sidx) if shipIsSelected: if isAllAbilitiesActiveOrInCooldown: if moduleIsActive is not None: self.slotsContainer.OnF(sidx, gidx) if moduleIsActive is None or moduleIsActive == True: self.fighterCont.OnF(sidx) else: self.fighterCont.OnF(sidx) if moduleIsActive == False: self.slotsContainer.OnF(sidx, gidx) else: self.fighterCont.OnF(sidx) elif self.IsFightersShown(): self.fighterCont.OnF(sidx) else: self.slotsContainer.OnF(sidx, gidx) def GetModuleDefaultEffect(self, sidx, gidx): slot = self.slotsContainer.slotsByOrder.get((gidx, sidx), None) if not slot: return if not slot.sr.module: return if slot.sr.module.state != uiconst.UI_NORMAL: return if slot.sr.module.def_effect is None: return return slot.sr.module.def_effect def IsModuleActiveForFKey(self, sidx, gidx): defaultEffect = self.GetModuleDefaultEffect(sidx, gidx) if defaultEffect: return defaultEffect.isActive def OnFKeyOverload(self, sidx, gidx): self.slotsContainer.OnFKeyOverload(sidx, gidx) def OnReloadAmmo(self): self.slotsContainer.OnReloadAmmo() def OnCloseView(self): self.ResetSelf() settings.user.ui.Set('selected_shipuicateg', self.sr.selectedcateg) t = uthread.new(sm.GetService('space').OnShipUIReset) t.context = 'ShipUI::OnShipUIReset' @telemetry.ZONE_METHOD def DoBallsRemove(self, pythonBalls, isRelease): if isRelease: self.UnhookBall() self.jammers = {} return for ball, slimItem, terminal in pythonBalls: self.DoBallRemove(ball, slimItem, terminal) if isRelease: self.compass.RemoveAll() def DoBallRemove(self, ball, slimItem, terminal): if ball is None: return log.LogInfo('DoBallRemove::shipui', ball.id) if self.controller.GetBall() is not None and ball.id == self.controller.GetBall().id: self.UnhookBall() uthread.new(self.UpdateJammersAfterBallRemoval, ball.id) def UpdateJammersAfterBallRemoval(self, ballID): jams = self.jammers.keys() for jammingType in jams: jam = self.jammers[jammingType] for id in jam.keys(): sourceBallID, moduleID, targetBallID = id if ballID == sourceBallID: del self.jammers[jammingType][id] def ProcessShipEffect(self, godmaStm, effectState): if effectState.error is not None: uthread.new(uicore.Message, effectState.error[0], effectState.error[1]) def OnJamStart(self, sourceBallID, moduleID, targetBallID, jammingType, startTime, duration): durationInClient = GetDurationInClient(startTime, duration) if durationInClient < 0.0: return if jammingType not in self.jammers: self.jammers[jammingType] = {} jammerID = (sourceBallID, moduleID, targetBallID) self.jammers[jammingType][jammerID] = (blue.os.GetSimTime(), durationInClient) if self.ewarCont and targetBallID == session.shipid: self.ewarCont.StartTimer(jammingType, jammerID, durationInClient) def OnJamEnd(self, sourceBallID, moduleID, targetBallID, jammingType): if jammingType in self.jammers: jammerID = (sourceBallID, moduleID, targetBallID) if jammerID in self.jammers[jammingType]: del self.jammers[jammingType][jammerID] def OnShipScanCompleted(self, shipID, capacitorCharge, capacitorCapacity, hardwareList): bp = sm.GetService('michelle').GetBallpark() if not bp: return slimItem = bp.slimItems[shipID] wndName = GetByLabel('UI/Inflight/ScanWindowName', itemName=GetSlimItemName(slimItem), title=GetByLabel('UI/Inflight/ScanResult')) import form form.ShipScan.CloseIfOpen(windowID=('shipscan', shipID)) form.ShipScan.Open(windowID=('shipscan', shipID), caption=wndName, shipID=shipID, results=(capacitorCharge, capacitorCapacity, hardwareList)) def OnCargoScanComplete(self, shipID, cargoList): bp = sm.GetService('michelle').GetBallpark() if not bp: return slimItem = bp.slimItems[shipID] windowID = ('cargoscanner', shipID) import form wnd = form.CargoScan.Open(windowID=windowID, shipID=shipID, cargoList=cargoList) if wnd: wnd.LoadResult(cargoList) def UnhookBall(self): self.controller.InvalidateBall() def OnShipChanged(self, *args): self.SetupShip(animate=True) def SetupShip(self, animate = False): if self.setupShipTasklet is not None: self.setupShipTasklet.kill() self.setupShipTasklet = uthread.new(self._SetupShip, animate) @telemetry.ZONE_METHOD def _SetupShip(self, animate = False): if self.destroyed or self.initing or not self.shipuiReady: return self.initing = True try: if not self.controller.IsLoaded(): return if not sm.GetService('viewState').IsViewActive('planet') and not (eve.hiddenUIState and 'shipui' in eve.hiddenUIState): self.state = uiconst.UI_PICKCHILDREN self.ResetUpdateTasklet() self.sr.rampTimers = {} self.slotsContainer.InitSlots(animate) self.hudButtons.InitButtons() self.SetButtonState() self.CheckExpandBtns() self.CheckControl() self.UpdateButtonsForShip() self.capacitorContainer.InitCapacitor() self.DrawFighters() self.InitFighters() self.ShowHideFighters() if self.CheckShipHasFighterBay(): self.moduleToggleBtn.display = True else: self.moduleToggleBtn.display = False if self.shipSelectHilight.display: self.shipSelectHilight.display = False blue.pyos.synchro.SleepWallclock(200) finally: self.initing = False def ResetUpdateTasklet(self): if self.updateTasklet: self.updateTasklet.kill() self.updateTasklet = uthread.new(self.UpdateGauges) def SetSpeed(self, speedRatio): self.controller.SetSpeed(speedRatio) def Hide(self): self.state = uiconst.UI_HIDDEN def Show(self): self.state = uiconst.UI_PICKCHILDREN def OnMouseEnter(self, *args): uicore.layer.inflight.HideTargetingCursor() def GetMenu(self): return self.controller.GetMenu() @telemetry.ZONE_FUNCTION def UpdateGauges(self): while not self.destroyed: try: if self.controller.IsLoaded(): self.heatGauges.Update() self.hpGauges.Update() self.UpdateReadouts() except Exception as e: log.LogException(e) blue.synchro.SleepWallclock(500) def UpdateReadouts(self): structure = self.controller.GetStructureHPPortion() armor = self.controller.GetArmorHPPortion() shield = self.controller.GetShieldHPPortion() self.CheckShowReadoutCont() if self.readoutCont.state != uiconst.UI_HIDDEN: if settings.user.ui.Get('readoutType', 1): self.readoutShieldLabel.text = GetByLabel('UI/Common/Formatting/Percentage', percentage=shield * 100) self.readoutArmorLabel.text = GetByLabel('UI/Common/Formatting/Percentage', percentage=armor * 100) self.readoutStructureLabel.text = GetByLabel('UI/Common/Formatting/Percentage', percentage=structure * 100) else: self.readoutShieldLabel.text = GetByLabel('UI/Inflight/GaugeAbsolute', left=self.controller.GetShieldHP(), total=self.controller.GetShieldHPMax()) self.readoutArmorLabel.text = GetByLabel('UI/Inflight/GaugeAbsolute', left=self.controller.GetArmorHP(), total=self.controller.GetArmorHPMax()) self.readoutStructureLabel.text = GetByLabel('UI/Inflight/GaugeAbsolute', left=self.controller.GetStructureHP(), total=self.controller.GetStructureHPMax()) def OnSafeLogoffTimerStarted(self, safeLogoffTime): if self.logoffTimer is not None: self.logoffTimer.Close() self.logoffTimer = SafeLogoffTimer(parent=uicore.layer.abovemain, logoffTime=safeLogoffTime) self.logoffTimer.left = sm.GetService('window').GetCameraLeftOffset(self.logoffTimer.width, self.logoffTimer.align, self.logoffTimer.left) def OnSafeLogoffActivated(self): if self.logoffTimer is not None: self.logoffTimer.timer.SetText('0.0') self.logoffTimer.timer.SetTextColor(Color.GREEN) sm.GetService('clientStatsSvc').OnProcessExit() def OnSafeLogoffAborted(self, reasonCode): self.AbortSafeLogoffTimer() uicore.Message('CustomNotify', {'notify': GetByLabel(reasonCode)}) def OnSafeLogoffFailed(self, failedConditions): self.AbortSafeLogoffTimer() uicore.Message('CustomNotify', {'notify': '<br>'.join([GetByLabel('UI/Inflight/SafeLogoff/ConditionsFailedHeader')] + [ GetByLabel(error) for error in failedConditions ])}) def AbortSafeLogoffTimer(self): if self.logoffTimer is not None: self.logoffTimer.AbortLogoff() self.logoffTimer = None
class SinglelineEditCore(Container): __guid__ = 'uicontrols.SinglelineEditCore' default_name = 'edit_singleline' default_align = uiconst.TOTOP default_width = 100 default_height = 20 default_state = uiconst.UI_NORMAL default_maxLength = None default_label = '' default_setvalue = '' default_hinttext = '' default_passwordCharacter = None default_autoselect = False default_adjustWidth = False default_dynamicHistoryWidth = False default_readonly = False default_OnChange = None default_OnSetFocus = None default_OnFocusLost = None default_OnReturn = None default_OnAnyChar = None default_OnInsert = None default_fontsize = None default_fontStyle = None default_fontFamily = None default_fontPath = None TEXTLEFTMARGIN = 4 TEXTRIGHTMARGIN = 4 registerHistory = True def ApplyAttributes(self, attributes): if self.default_fontsize is None: self.default_fontsize = fontConst.DEFAULT_FONTSIZE self.DECIMAL = '.' Container.ApplyAttributes(self, attributes) self.rightAlignedButtons = weakref.WeakSet() self._clearButton = None self.hinttext = '' self.isTabStop = 1 self.integermode = None self.floatmode = None self.passwordchar = None self.caretIndex = (0, 0) self.selFrom = None self.selTo = None self.value = None self.text = '' self.suffix = '' self.maxletters = None self.historyMenu = None self.historySaveLast = None self.displayHistory = False self.allowHistoryInnerMatches = False self.maxHistoryShown = 5 self.numericControlsCont = None self.updateNumericInputThread = None self.draggedValue = None self.OnChange = None self.OnFocusLost = None self.OnReturn = None self.OnInsert = None self.readonly = attributes.get('readonly', self.default_readonly) self.fontStyle = attributes.get('fontStyle', self.default_fontStyle) self.fontFamily = attributes.get('fontFamily', self.default_fontFamily) self.fontPath = attributes.get('fontPath', self.default_fontPath) self.fontsize = attributes.get('fontsize', self.default_fontsize) self._textClipper = Container(name='_textClipper', parent=self, clipChildren=True, padding=(1, 0, 1, 0)) self._textClipper._OnSizeChange_NoBlock = self.OnClipperSizeChange self.Prepare_() self.autoselect = attributes.get('autoselect', self.default_autoselect) self.adjustWidth = attributes.get('adjustWidth', self.default_adjustWidth) self.dynamicHistoryWidth = attributes.get('dynamicHistoryWidth', self.default_dynamicHistoryWidth) self.sr.text.shadow = self.sr.hinttext.shadow = attributes.get('shadow', None) fontcolor = attributes.get('fontcolor', (1.0, 1.0, 1.0, 1.0)) if fontcolor is not None: self.SetTextColor(fontcolor) if attributes.get('ints', None): self.IntMode(*attributes.ints) elif attributes.get('floats', None): self.FloatMode(*attributes.floats) self.SetPasswordChar(attributes.get('passwordCharacter', self.default_passwordCharacter)) self.SetMaxLength(attributes.get('maxLength', self.default_maxLength)) self.SetLabel(attributes.get('label', self.default_label)) self.SetHintText(attributes.get('hinttext', self.default_hinttext)) self.SetValue(attributes.get('setvalue', self.default_setvalue)) self.height = 20 self.OnChange = attributes.get('OnChange', self.default_OnChange) self.__OnSetFocus = attributes.get('OnSetFocus', self.default_OnSetFocus) self.OnFocusLost = attributes.get('OnFocusLost', self.default_OnFocusLost) self.OnReturn = attributes.get('OnReturn', self.default_OnReturn) self.OnInsert = attributes.get('OnInsert', self.default_OnInsert) OnAnyChar = attributes.get('OnAnyChar', self.default_OnAnyChar) if OnAnyChar: self.OnAnyChar = OnAnyChar uicore.event.RegisterForTriuiEvents(uiconst.UI_MOUSEDOWN, self.OnGlobalMouseDownCallback) def OnGlobalMouseDownCallback(self, uiObject, *args, **kwds): if self.destroyed: return False if uiObject is not self and self.historyMenu: historyMenu = self.historyMenu() if historyMenu and not historyMenu.destroyed: if not uiObject.IsUnder(historyMenu): self.CloseHistoryMenu() return True def Prepare_(self): self.Prepare_Background_() self.sr.text = Label(text='', parent=self._textClipper, name='value', align=uiconst.CENTERLEFT, state=uiconst.UI_DISABLED, maxLines=1, left=self.TEXTLEFTMARGIN, fontStyle=self.fontStyle, fontFamily=self.fontFamily, fontPath=self.fontPath, fontsize=self.fontsize) self.sr.hinttext = Label(text='', parent=self._textClipper, name='hinttext', align=uiconst.CENTERLEFT, state=uiconst.UI_DISABLED, maxLines=1, left=self.TEXTLEFTMARGIN, fontStyle=self.fontStyle, fontFamily=self.fontFamily, fontPath=self.fontPath, fontsize=self.fontsize) def SetHintText(self, hint): self.hinttext = hint self.CheckHintText() def AutoFitToText(self, text = None, minWidth = None): if self.align in (uiconst.TOTOP, uiconst.TOBOTTOM, uiconst.TOALL): raise RuntimeError('Incorrect alignment for SingleLine.AutoFitToText') if text is not None: textwidth, textheight = self.sr.text.MeasureTextSize(text) autoWidth = textwidth + self.TEXTLEFTMARGIN * 2 + 2 else: autoWidth = self.sr.text.textwidth + self.TEXTLEFTMARGIN * 2 + 2 if minWidth: autoWidth = max(minWidth, autoWidth) self.width = autoWidth self.sr.text.left = self.TEXTLEFTMARGIN def CheckHintText(self): if self.GetText(): self.sr.hinttext.display = False else: self.sr.hinttext.display = True self.sr.hinttext.text = self.hinttext def SetTextColor(self, color): self.sr.text.SetRGB(*color) self.sr.hinttext.SetRGB(*color) self.sr.hinttext.SetAlpha(self.sr.hinttext.GetAlpha() * 0.5) def Prepare_Background_(self): if not self.sr.underlay: self.sr.underlay = Frame(name='__underlay', frameConst=('ui_1_16_161', 7, -2), bgParent=self) def Prepare_Caret_(self): self.sr.caret = Fill(parent=self._textClipper, name='caret', align=uiconst.TOPLEFT, color=(1.0, 1.0, 1.0, 0.75), pos=(self.TEXTLEFTMARGIN, 1, 1, 1), idx=0, state=uiconst.UI_HIDDEN) def ShowClearButton(self, icon = None, hint = None, showOnLetterCount = 1): if self._clearButton: self._clearButton.Close() icon = icon or 'res:/UI/Texture/Icons/73_16_210.png' clearButton = self.AddIconButton(icon, hint) clearButton.OnClick = self.OnClearButtonClick clearButton.Hide() clearButton._showOnLetterCount = showOnLetterCount self._clearButton = clearButton return clearButton def OnClearButtonClick(self): self.SetValue(u'') def AddIconButton(self, texturePath, hint = None): from eve.client.script.ui.control.buttons import ButtonIcon rightAlignedButton = ButtonIcon(texturePath=texturePath, pos=(0, 0, 16, 16), align=uiconst.CENTERRIGHT, parent=self, hint=hint, idx=0) self.rightAlignedButtons.add(rightAlignedButton) return rightAlignedButton def RefreshTextClipper(self): if self._clearButton: if len(self.text) >= self._clearButton._showOnLetterCount: self._clearButton.Show() else: self._clearButton.Hide() padRight = 1 iconLeft = 1 for each in self.rightAlignedButtons: if not each.destroyed and each.display: padRight += each.width each.left = iconLeft iconLeft += each.width self._textClipper.padRight = padRight w, h = self._textClipper.GetAbsoluteSize() self.sr.text.SetRightAlphaFade(-self.sr.text.left + w - 3, 8) def OnClipperSizeChange(self, newWidth, newHeight): if newWidth: self.RefreshCaretPosition() self.RefreshSelectionDisplay() self.RefreshTextClipper() def LoadCombo(self, id, options, callback = None, setvalue = None, comboIsTabStop = 1): for each in self.children[:]: if each.name == 'combo': each.Close() combo = Combo(parent=self, label='', options=options, name=id, select=setvalue, callback=self.OnComboChange, pos=(0, 0, 16, 16), align=uiconst.BOTTOMRIGHT) combo.sr.inputCallback = callback combo.isTabStop = comboIsTabStop combo.name = 'combo' combo.Confirm = self.ComboConfirm combo.Hide() self.sr.combo = combo comboButton = self.AddIconButton('res:/UI/Texture/Icons/38_16_229.png') comboButton.name = 'combo' comboButton.OnMouseDown = (self.ExpandCombo, combo) def ExpandCombo(self, combo, *args, **kwds): if not combo._Expanded(): uthread.new(combo.Expand, self.GetAbsolute()) def ComboConfirm(self, *args): if self.sr.combo and not self.sr.combo.destroyed: self.OnComboChange(self.sr.combo, self.sr.combo.GetKey(), self.sr.combo.GetValue()) self.sr.combo.Cleanup(setfocus=0) def OnUp(self, *args): if self.sr.combo: if not self.sr.combo._Expanded(): uthread.new(self.sr.combo.Expand, self.GetAbsolute()) else: self.sr.combo.OnUp() def OnDown(self, *args): if self.sr.combo: if not self.sr.combo._Expanded(): uthread.new(self.sr.combo.Expand, self.GetAbsolute()) else: self.sr.combo.OnDown() def GetComboValue(self): if self.sr.combo: return self.sr.combo.GetValue() def OnComboChange(self, combo, label, value, *args): self.SetValue(label, updateIndex=0) if combo.sr.inputCallback: combo.sr.inputCallback(combo, label, value) def ClearHistory(self, *args): id, mine, all = self.GetHistory(getAll=1) if id in all: del all[id] settings.user.ui.Set('editHistory', all) def RegisterHistory(self, value = None): if self.integermode or self.floatmode or self.passwordchar is not None or not self.registerHistory: return id, mine, all = self.GetHistory(getAll=1) current = (value or self.GetValue(registerHistory=0)).rstrip() if current not in mine: mine.append(current) all[id] = mine settings.user.ui.Set('editHistory', all) def CheckHistory(self): if self.integermode or self.floatmode or self.passwordchar is not None or self.displayHistory == 0: return if self.readonly: return valid = self.GetValid() if valid: self.ShowHistoryMenu(valid[:5]) return 1 self.CloseHistoryMenu() return 0 def GetValid(self): current = self.GetValue(registerHistory=0) id, mine = self.GetHistory() valid = [ each for each in mine if each.lower().startswith(current.lower()) and each != current ] valid.sort(key=lambda x: len(x)) return valid def ShowHistoryMenu(self, history): hadMenu = 0 if self.historyMenu and self.historyMenu(): hadMenu = 1 self.CloseHistoryMenu() if not history: return l, t, w, h = self.GetAbsolute() mp = Container(name='historyMenuParent', parent=uicore.layer.menu, pos=(l, t + h + 2, w, 0), align=uiconst.TOPLEFT) if not hadMenu: mp.opacity = 0.0 Frame(parent=mp, frameConst=uiconst.FRAME_BORDER1_CORNER0, color=(1.0, 1.0, 1.0, 0.2)) Frame(parent=mp, frameConst=uiconst.FRAME_FILLED_CORNER0, color=(0.0, 0.0, 0.0, 0.75)) mps = Container(name='historyMenuSub', parent=mp, idx=0) self.PopulateHistoryMenu(mps, mp, history) mp.sr.entries = mps self.historyMenu = weakref.ref(mp) if not hadMenu: uicore.effect.MorphUI(mp, 'opacity', 1.0, 250.0, float=1) def PopulateHistoryMenu(self, mps, mp, history): for entry in history: displayText, editText = entry if isinstance(entry, tuple) else (entry, entry) self.GetHistoryMenuEntry(displayText, editText, mps, mp) def GetHistoryMenuEntry(self, displayText, text, menuSub, mp, info = None): ep = Container(name='entryParent', parent=menuSub, clipChildren=1, pos=(0, 0, 0, 16), align=uiconst.TOTOP, state=uiconst.UI_NORMAL) ep.OnMouseEnter = (self.HEMouseEnter, ep) ep.OnMouseDown = (self.HEMouseDown, ep) ep.OnMouseUp = (self.HEMouseUp, ep) Line(parent=ep, align=uiconst.TOBOTTOM) t = Label(text=displayText, parent=ep, left=6, align=uiconst.CENTERLEFT, state=uiconst.UI_DISABLED) ep.height = t.textheight + 4 ep.sr.hilite = Fill(parent=ep, color=(1.0, 1.0, 1.0, 0.25), pos=(1, 1, 1, 1), state=uiconst.UI_HIDDEN) ep.selected = 0 ep.sr.menu = mp ep.string = text mp.height += ep.height if self.dynamicHistoryWidth: mp.width = max(mp.width, t.width + 12) ep.info = info def HEMouseDown(self, entry, mouseButton, *args): if mouseButton == uiconst.MOUSELEFT: self.SetValue(entry.string, updateIndex=1) self.OnHistoryClick(entry.string) def HEMouseUp(self, entry, mouseButton, *args): if mouseButton == uiconst.MOUSELEFT: self.CloseHistoryMenu() def HEMouseEnter(self, entry, *args): if not (self.historyMenu and self.historyMenu()): return hm = self.historyMenu() for _entry in hm.sr.entries.children: _entry.sr.hilite.state = uiconst.UI_HIDDEN _entry.selected = 0 entry.sr.hilite.state = uiconst.UI_DISABLED entry.selected = 1 def GetHistory(self, getAll = 0): id = self.GetHistoryID() all = settings.user.ui.Get('editHistory', {}) if type(all) == list: log.LogError('Singlelineedit error: all:', all) log.LogTraceback('Singlelineedit error: all: %s' % all, severity=log.LGERR) settings.user.ui.Delete('editHistory') all = {} if getAll: return (id, all.get(id, []), all) return (id, all.get(id, [])) def OnHistoryClick(self, clickedString, *args): pass def CloseHistoryMenu(self): if self.historyMenu: historyMenu = self.historyMenu() if historyMenu and not historyMenu.destroyed: self.active = None historyMenu.Close() self.historyMenu = None def BrowseHistory(self, down): justopened = 0 if not (self.historyMenu and self.historyMenu()): if not self.CheckHistory(): return justopened = 1 hm = self.historyMenu() currentIdx = None i = 0 for entry in hm.sr.entries.children: if entry.selected: currentIdx = i entry.sr.hilite.state = uiconst.UI_HIDDEN entry.selected = 0 i += 1 if justopened: return if currentIdx is None: if down: currentIdx = 0 else: currentIdx = len(hm.sr.entries.children) - 1 elif down: currentIdx += 1 if currentIdx >= len(hm.sr.entries.children): currentIdx = 0 else: currentIdx -= 1 if currentIdx < 0: currentIdx = len(hm.sr.entries.children) - 1 self.active = active = hm.sr.entries.children[currentIdx] active.sr.hilite.state = uiconst.UI_DISABLED active.selected = 1 if not getattr(self, 'blockSetValue', 0): self.SetValue(active.string, updateIndex=1) def GetHistoryID(self): id = '' item = self while item.parent: id = '/' + item.name + id if isinstance(item, Window): break item = item.parent return id def SetReadOnly(self, state): self.readonly = state def SetMaxLength(self, maxLength): self.maxletters = maxLength def SetHistoryVisibility(self, status): self.displayHistory = status def SetPasswordChar(self, char): self.passwordchar = char def OnSetFocus(self, *args): if self.pickState != uiconst.TR2_SPS_ON: return if not self.readonly and uicore.imeHandler: uicore.imeHandler.SetFocus(self) if self and not self.destroyed and self.parent and self.parent.name == 'inlines': if self.parent.parent and getattr(self.parent.parent.sr, 'node', None): browser = GetBrowser(self) if browser: uthread.new(browser.ShowObject, self) self.sr.background.AnimEntry() if self.integermode or self.floatmode: self.SetText(self.text) self.caretIndex = self.GetCursorFromIndex(-1) self.ShowCaret() if self.autoselect: self.SelectAll() else: self.RefreshSelectionDisplay() if self.__OnSetFocus: self.__OnSetFocus(*args) def OnKillFocus(self, *args): if not self.readonly and uicore.imeHandler: uicore.imeHandler.KillFocus(self) if self.autoselect: self.SelectNone() self.sr.background.AnimExit() if self.integermode or self.floatmode: ret = self.CheckBounds(self.text, 1, allowEmpty=bool(self.hinttext), returnNoneIfOK=1) if ret is not None: text = ret else: text = self.text self.SetText(text, 1) self.HideCaret() self.CloseHistoryMenu() if self.OnFocusLost: uthread.new(self.OnFocusLost, self) def SetValue(self, text, add = 0, keepSelection = 0, updateIndex = 1, docallback = 1): self.draggedValue = None text = text or '' isString = isinstance(text, basestring) if isString: text = StripTags(text, stripOnly=['localized']) if self.floatmode: if isString: text = self.PrepareFloatString(text) text = self.CheckBounds(text, 0, bool(self.hinttext)) elif self.integermode: text = self.CheckBounds(text, 0, bool(self.hinttext)) else: text = text.replace('<', '<').replace('>', '>') if self.maxletters: text = text[:self.maxletters] if updateIndex: self.SetText(text, 0) self.caretIndex = self.GetCursorFromIndex(-1) self.SetText(text, 1) self.selFrom = self.selTo = None self.RefreshSelectionDisplay() self.OnTextChange(docallback) def GetValue(self, refreshDigits = 1, raw = 0, registerHistory = 1): ret = self.text if refreshDigits and (self.integermode or self.floatmode): ret = self.CheckBounds(ret, 0) if self.integermode: ret = ret or 0 try: ret = int(ret) except: ret = 0 sys.exc_clear() elif self.floatmode: ret = ret or 0 floatdigits = self.floatmode[2] try: ret = round(float(ret), floatdigits) except: ret = 0.0 sys.exc_clear() elif not raw: ret = ret.replace('<', '<').replace('>', '>') if registerHistory: self.RegisterHistory() return ret def IntMode(self, minint = None, maxint = None): if maxint is None: maxint = sys.maxint self.integermode = (minint, min(sys.maxint, maxint)) self.floatmode = None self.OnMouseWheel = self.MouseWheel if minint and not self.text: self.SetValue(minint) self.ShowNumericControls() def FloatMode(self, minfloat = None, maxfloat = None, digits = 1): self.floatmode = (minfloat, maxfloat, int(digits)) self.integermode = None self.OnMouseWheel = self.MouseWheel if minfloat and not self.text: self.SetValue(minfloat) self.ShowNumericControls() def ShowNumericControls(self): if self.numericControlsCont: return self.numericControlsCont = Container(name='numericControlsCont', parent=self, align=uiconst.TORIGHT, idx=0, width=10, padding=(0, 1, 1, 1), opacity=0.75) self.upButton = ButtonIcon(name='upButton', parent=self.numericControlsCont, align=uiconst.CENTER, pos=(0, -4, 9, 9), iconSize=7, texturePath='res:/UI/Texture/Shared/up.png') self.upButton.OnMouseDown = self.OnNumericUpButtonMouseDown self.upButton.OnMouseUp = self.OnNumericUpButtonMouseUp self.downButton = ButtonIcon(name='downButton', parent=self.numericControlsCont, align=uiconst.CENTER, pos=(0, 4, 9, 9), iconSize=7, texturePath='res:/UI/Texture/Shared/down.png') self.downButton.OnMouseDown = self.OnNumericDownButtonMouseDown self.downButton.OnMouseUp = self.OnNumericDownButtonMouseUp def OnNumericUpButtonMouseDown(self, *args): ButtonIcon.OnMouseDown(self.upButton, *args) self.updateNumericInputThread = uthread.new(self.UpdateNumericInputThread, 1) def OnNumericDownButtonMouseDown(self, *args): ButtonIcon.OnMouseDown(self.downButton, *args) self.updateNumericInputThread = uthread.new(self.UpdateNumericInputThread, -1) def KillNumericInputThread(self): if self.updateNumericInputThread: self.updateNumericInputThread.kill() self.updateNumericInputThread = None def OnNumericUpButtonMouseUp(self, *args): ButtonIcon.OnMouseUp(self.upButton, *args) self.KillNumericInputThread() def OnNumericDownButtonMouseUp(self, *args): ButtonIcon.OnMouseUp(self.downButton, *args) self.KillNumericInputThread() def UpdateNumericInputThread(self, diff): sleepTime = 500 while uicore.uilib.leftbtn: self.ChangeNumericValue(diff) blue.synchro.SleepWallclock(sleepTime) sleepTime -= 0.5 * sleepTime sleepTime = max(10, sleepTime) def MouseWheel(self, *args): if self.readonly: return self.ChangeNumericValue((uicore.uilib.dz / 120) ** 3) def ChangeNumericValue(self, val): if uicore.uilib.Key(uiconst.VK_CONTROL): val *= 10 if self.integermode: if val > 0: val = max(1, long(val)) else: val = min(-1, long(val)) errorValue = self.integermode[0] or 0 elif self.floatmode: val *= 1 / float(10 ** self.floatmode[2]) errorValue = self.floatmode[0] or 0 else: return if val > 0: self.upButton.Blink(0.2) else: self.downButton.Blink(0.2) self.ClampMinMaxValue(val) def ClampMinMaxValue(self, change = 0): if not (self.integermode or self.floatmode): return try: current = self.GetValue(registerHistory=0) except ValueError: current = errorValue sys.exc_clear() text = self.CheckBounds(repr(current + change), 0) if self.floatmode: floatdigits = self.floatmode[2] text = '%%.%df' % floatdigits % float(text) if uicore.registry.GetFocus() is self: self.SetText(text) else: self.SetText(text, format=True) self.caretIndex = self.GetCursorFromIndex(-1) self.selFrom = None self.selTo = None self.RefreshSelectionDisplay() self.OnTextChange() def OnDblClick(self, *args): self.caretIndex = self.GetIndexUnderCursor() self.selFrom = self.GetCursorFromIndex(0) self.selTo = self.caretIndex = self.GetCursorFromIndex(-1) self.RefreshCaretPosition() self.RefreshSelectionDisplay() self.RefreshTextClipper() def OnMouseDown(self, button, *etc): if uicore.uilib.mouseTravel > 10: return if hasattr(self, 'RegisterFocus'): self.RegisterFocus(self) gettingFocus = uicore.registry.GetFocus() != self if gettingFocus: uicore.registry.SetFocus(self) leftClick = button == uiconst.MOUSELEFT if uicore.uilib.Key(uiconst.VK_SHIFT): if self.selFrom is None: self.selFrom = self.caretIndex self.selTo = self.caretIndex = self.GetIndexUnderCursor() self.RefreshCaretPosition() self.RefreshSelectionDisplay() self.RefreshTextClipper() elif leftClick: self.caretIndex = self.mouseDownCaretIndex = self.GetIndexUnderCursor() self.selFrom = None self.selTo = None self.RefreshCaretPosition() self.RefreshSelectionDisplay() self.RefreshTextClipper() if self.autoselect and gettingFocus: self.SelectAll() else: self.sr.selectionTimer = AutoTimer(50, self.UpdateSelection) def SetSelection(self, start, end): if start < 0: start = len(self.text) self.selFrom = self.GetCursorFromIndex(start) if end < 0: end = -1 self.selTo = self.caretIndex = self.GetCursorFromIndex(end) self.RefreshCaretPosition() self.RefreshSelectionDisplay() self.RefreshTextClipper() def UpdateSelection(self): oldCaretIndex = self.mouseDownCaretIndex newCaretIndex = self.GetIndexUnderCursor() self.selFrom = oldCaretIndex self.selTo = newCaretIndex self.caretIndex = newCaretIndex self.RefreshCaretPosition() self.RefreshSelectionDisplay() self.RefreshTextClipper() def SelectNone(self): self.selFrom = (None, None) self.selTo = (None, None) self.RefreshSelectionDisplay() def OnMouseUp(self, *args): self.mouseDownCaretIndex = None self.sr.selectionTimer = None def GetIndexUnderCursor(self): l, t = self.sr.text.GetAbsolutePosition() cursorXpos = uicore.uilib.x - l return self.sr.text.GetIndexUnderPos(cursorXpos) def GetCursorFromIndex(self, index): return self.sr.text.GetWidthToIndex(index) def RefreshCaretPosition(self): if self.destroyed: return self.GetCaret() self.sr.caret.left = self.sr.text.left + self.caretIndex[1] - 1 if not (self.integermode or self.floatmode): w, h = self._textClipper.GetAbsoluteSize() if self.sr.text.textwidth < w - self.TEXTLEFTMARGIN - self.TEXTRIGHTMARGIN: self.sr.text.left = self.TEXTLEFTMARGIN else: if self.sr.text.left + self.sr.text.textwidth < w - self.TEXTLEFTMARGIN - self.TEXTRIGHTMARGIN: self.sr.text.left = w - self.TEXTLEFTMARGIN - self.TEXTRIGHTMARGIN - self.sr.text.textwidth if self.sr.caret.left > w - self.TEXTRIGHTMARGIN: diff = self.sr.caret.left - w + self.TEXTRIGHTMARGIN self.sr.text.left -= diff elif self.sr.caret.left < self.TEXTLEFTMARGIN: diff = -self.sr.caret.left + self.TEXTLEFTMARGIN self.sr.text.left += diff self.sr.caret.left = self.sr.text.left + self.caretIndex[1] - 1 def ShowCaret(self): self.GetCaret() self.RefreshCaretPosition() w, h = self.GetAbsoluteSize() self.sr.caret.height = h - 4 self.sr.caret.top = 2 self.sr.caret.state = uiconst.UI_DISABLED self.sr.caretTimer = AutoTimer(400, self.BlinkCaret) ShowCursor = ShowCaret def HideCaret(self): self.sr.caretTimer = None if self.sr.get('caret', None): self.sr.caret.state = uiconst.UI_HIDDEN HideCursor = HideCaret def GetCaret(self): if not self.sr.get('caret', None) and not self.destroyed: self.Prepare_Caret_() def BlinkCaret(self): if self.destroyed: self.sr.caretTimer = None return if self.sr.get('caret', None): if not trinity.app.IsActive(): self.sr.caret.state = uiconst.UI_HIDDEN return self.sr.caret.state = [uiconst.UI_HIDDEN, uiconst.UI_DISABLED][self.sr.caret.state == uiconst.UI_HIDDEN] def OnChar(self, char, flag): if self.floatmode: if unichr(char) in ',.': return False if self.OnAnyChar(char): isLatinBased = uicore.font.IsLatinBased(unichr(char)) if isLatinBased or not uicore.imeHandler: keyboardLanguageID = languageConst.LANG_ENGLISH else: keyboardLanguageID = uicore.imeHandler.GetKeyboardLanguageID() fontFamily = uicore.font.GetFontFamilyBasedOnWindowsLanguageID(keyboardLanguageID) if fontFamily != self.sr.text.fontFamily: self.sr.text.fontFamily = fontFamily self.sr.hinttext.fontFamily = fontFamily if char in [127, uiconst.VK_BACK]: if self.GetSelectionBounds() != (None, None): self.DeleteSelected() else: self.Delete(0) self.CheckHistory() if self.OnInsert: self.OnInsert(char, flag) return True if char != uiconst.VK_RETURN: self.Insert(char) self.CheckHistory() if self.OnInsert: self.OnInsert(char, flag) return True return False def OnAnyChar(self, char, *args): return True def Confirm(self, *args): if self.OnReturn: self.CloseHistoryMenu() return uthread.new(self.OnReturn) searchFrom = GetWindowAbove(self) if searchFrom: wnds = [ w for w in searchFrom.Find('trinity.Tr2Sprite2dContainer') + searchFrom.Find('trinity.Tr2Sprite2d') if getattr(w, 'btn_default', 0) == 1 ] if len(wnds): for wnd in wnds: if self == wnd: continue if wnd.IsVisible(): if hasattr(wnd, 'OnClick'): uthread.new(wnd.OnClick, wnd) return True return False def OnKeyDown(self, vkey, flag): if self.floatmode: if vkey in (uiconst.VK_DECIMAL, uiconst.VK_OEM_PERIOD, uiconst.VK_OEM_COMMA): self.Insert(self.DECIMAL) return HOME = uiconst.VK_HOME END = uiconst.VK_END CTRL = uicore.uilib.Key(uiconst.VK_CONTROL) SHIFT = uicore.uilib.Key(uiconst.VK_SHIFT) if self.destroyed: return oldCaretIndex = self.caretIndex selection = self.GetSelectionBounds() index = self.caretIndex[0] if vkey == uiconst.VK_LEFT: if CTRL: index = self.text.rfind(' ', 0, max(index - 1, 0)) + 1 or 0 else: index = max(index - 1, 0) elif vkey == uiconst.VK_RIGHT: if CTRL: index = self.text.find(' ', index) + 1 or len(self.text) else: index = index + 1 index = min(index, len(self.text)) elif vkey == HOME: index = 0 elif vkey == END: index = len(self.text) elif vkey in (uiconst.VK_DELETE,): if self.GetSelectionBounds() != (None, None): self.DeleteSelected() return self.Delete(1) else: if vkey in (uiconst.VK_UP, uiconst.VK_DOWN): self.BrowseHistory(vkey == uiconst.VK_DOWN) if vkey == uiconst.VK_UP: self.ChangeNumericValue(1) elif vkey == uiconst.VK_DOWN: self.ChangeNumericValue(-1) else: self.OnUnusedKeyDown(self, vkey, flag) return self.caretIndex = self.GetCursorFromIndex(index) if vkey in (uiconst.VK_LEFT, uiconst.VK_RIGHT, HOME, END): if SHIFT: if self.selTo is not None: self.selTo = self.caretIndex elif self.selTo is None: self.selFrom = oldCaretIndex self.selTo = self.caretIndex elif selection != (None, None): if vkey == uiconst.VK_LEFT: index = selection[0][0] elif vkey == uiconst.VK_RIGHT: index = selection[1][0] self.caretIndex = self.GetCursorFromIndex(index) if not SHIFT or self.selFrom == self.selTo: self.selFrom = self.selTo = None self.CloseHistoryMenu() self.RefreshCaretPosition() self.RefreshSelectionDisplay() self.RefreshTextClipper() def OnUnusedKeyDown(self, *args): pass def StripNumberString(self, numberString): if self.integermode: return filter(lambda x: x in '-0123456789', numberString) if self.floatmode: return filter(lambda x: x in '-0123456789e.', numberString) return numberString def PrepareFloatString(self, numberString): commasInString = numberString.count(',') periodsInString = numberString.count('.') if commasInString and periodsInString: haveDecimal = False stripped = u'' legalFloats = '-0123456789e,.' for each in reversed(unicode(numberString)): if each in legalFloats: if each in u',.': if haveDecimal: continue haveDecimal = True stripped = '.' + stripped else: stripped = each + stripped return stripped if commasInString >= 2: numberString = filter(lambda x: x in '-0123456789e.', numberString) return numberString if periodsInString >= 2: numberString = filter(lambda x: x in '-0123456789e,', numberString) numberString = numberString.replace(',', self.DECIMAL) return numberString numberString = filter(lambda x: x in '-0123456789e,.', numberString) numberString = numberString.replace(',', self.DECIMAL) return numberString def Insert(self, ins): if self.readonly: return None if not isinstance(ins, basestring): text = unichr(ins) else: text = ins text = text.replace(u'\r', u' ').replace(u'\n', u'') current = self.GetText() if self.GetSelectionBounds() != (None, None): self.DeleteSelected() if (self.integermode or self.floatmode) and text: if self.floatmode: if self.DECIMAL in text and self.DECIMAL in self.text: uicore.Message('uiwarning03') return None if text == u'-': newvalue = self.text[:self.caretIndex[0]] + text + self.text[self.caretIndex[0]:] if newvalue != u'-': newvalue = self.StripNumberString(newvalue) try: if self.integermode: long(newvalue) else: float(newvalue) except ValueError as e: uicore.Message('uiwarning03') sys.exc_clear() return None elif text != self.DECIMAL: text = self.StripNumberString(text) try: if self.integermode: long(text) else: float(text) except ValueError as e: uicore.Message('uiwarning03') sys.exc_clear() return None elif text not in '0123456789' and self.integermode: uicore.Message('uiwarning03') return None before = self.text[:self.caretIndex[0]] after = self.text[self.caretIndex[0]:] become = before + text + after if self.maxletters and len(become) > self.maxletters: become = become[:self.maxletters] uicore.Message('uiwarning03') self.autoselect = False if (self.integermode or self.floatmode) and become and become[-1] not in (self.DECIMAL, '-'): become = self.StripNumberString(become) self.SetText(become) index = self.caretIndex[0] + len(text) self.caretIndex = self.GetCursorFromIndex(index) self.OnTextChange() def GetMenu(self): m = [] start, end = self.GetSelectionBounds() if start is not None: start = start[0] if end is not None: end = end[0] m += [(MenuLabel('/Carbon/UI/Controls/Common/Copy'), self.Copy, (start, end))] if not self.readonly: if uicore.imeHandler: uicore.imeHandler.GetMenuDelegate(self, None, m) paste = GetClipboardData() if paste: m += [(MenuLabel('/Carbon/UI/Controls/Common/Paste'), self.Paste, (paste, start, end, True))] if self.displayHistory and self.passwordchar is None: m += [(MenuLabel('/Carbon/UI/Controls/Common/ClearHistory'), self.ClearHistory, (None,))] return m def OnTextChange(self, docallback = 1): self.CheckHintText() self.RefreshCaretPosition() self.RefreshTextClipper() if docallback and self.OnChange: self.OnChange(self.text) def CheckBounds(self, qty, warnsnd = 0, allowEmpty = 1, returnNoneIfOK = 0): if allowEmpty and not qty: return '' if qty == '-' or qty is None: qty = 0 isInt = self.integermode is not None isFloat = self.floatmode is not None if isFloat: minbound, maxbound = self.floatmode[:2] elif isInt: minbound, maxbound = self.integermode else: return str(qty) pQty = self.StripNumberString(repr(qty)) minusIndex = pQty.find('-') if minusIndex > 0 and pQty[minusIndex - 1] != 'e': uicore.Message('uiwarning03') if minbound is not None: return minbound return '' if isFloat: if pQty == self.DECIMAL: uicore.Message('uiwarning03') if minbound is not None: return minbound return '' qty = float(pQty or 0) else: qty = long(pQty or 0) warn = 0 ret = qty if maxbound is not None and qty > maxbound: warn = 1 ret = maxbound elif minbound is not None and qty < minbound: warn = 1 ret = minbound elif returnNoneIfOK: return if warn and warnsnd: uicore.Message('uiwarning03') return ret def RefreshSelectionDisplay(self): selection = self.GetSelectionBounds() if selection != (None, None): self.GetSelectionLayer() f, t = selection self.sr.selection.left = self.sr.text.left + f[1] self.sr.selection.width = t[1] - f[1] self.sr.selection.state = uiconst.UI_DISABLED elif self.sr.selection: self.sr.selection.state = uiconst.UI_HIDDEN def GetSelectionBounds(self): if self.selFrom and self.selTo and self.selFrom[0] != self.selTo[0]: return (min(self.selFrom, self.selTo), max(self.selFrom, self.selTo)) return (None, None) def GetSelectionLayer(self): w, h = self.GetAbsoluteSize() if not self.sr.selection: self.sr.selection = Fill(parent=self._textClipper, name='selection', align=uiconst.TOPLEFT, pos=(0, 1, 0, h - 2), idx=1) def DeleteSelected(self): if self.readonly: return start, end = self.GetSelectionBounds() self.selFrom = self.selTo = None self.RefreshSelectionDisplay() text = self.GetText() self.SetText(text[:start[0]] + text[end[0]:]) self.caretIndex = start self.OnTextChange() def SelectAll(self): self.selFrom = self.GetCursorFromIndex(0) self.selTo = self.GetCursorFromIndex(-1) self.RefreshSelectionDisplay() def Cut(self, *args): if self.GetSelectionBounds() != (None, None): self.Copy() self.DeleteSelected() def Copy(self, selectStart = None, selectEnd = None): if self.passwordchar is None: text = self.GetText() if self.floatmode: text = text.replace(self.DECIMAL, self.GetLocalizedDecimal()) else: text = self.passwordchar * len(self.GetText()) if selectStart is not None and selectEnd is not None: blue.pyos.SetClipboardData(text[selectStart:selectEnd]) else: start, end = self.GetSelectionBounds() if not start and not end: blue.pyos.SetClipboardData(text) else: blue.pyos.SetClipboardData(text[start[0]:end[0]]) def GetLocalizedDecimal(self): if session: localizedDecimal = eveLocalization.GetDecimalSeparator(localization.SYSTEM_LANGUAGE) else: localizedDecimal = prefs.GetValue('decimal', '.') return localizedDecimal def Paste(self, paste, deleteStart = None, deleteEnd = None, forceFocus = False): if self.floatmode: haveIllegalChar = False legalChars = '-0123456789e,.' for char in paste: if char in legalChars: if haveIllegalChar: uicore.Message('uiwarning03') return else: haveIllegalChar = True if haveIllegalChar: uicore.Message('uiwarning03') paste = self.PrepareFloatString(paste) hadFocus = uicore.registry.GetFocus() is self if deleteStart is None or deleteEnd is None: start, end = self.GetSelectionBounds() if start is not None and end is not None: self.DeleteSelected() else: text = self.GetText() self.SetText(text[:deleteStart] + text[deleteEnd:]) self.caretIndex = self.GetCursorFromIndex(deleteStart) self.OnTextChange() self.Insert(paste) if (hadFocus or forceFocus) and not uicore.registry.GetFocus() == self: uicore.registry.SetFocus(self) def EncodeOutput(self, otext): if not otext: return '' if self.integermode or self.floatmode: elem = [ each for each in otext if each not in ('-', '.') ] if not len(elem): return '' if self.integermode: return localization.formatters.FormatNumeric(long(float(otext)), useGrouping=True) if self.floatmode: decimalPlaces = self.floatmode[2] return localization.formatters.FormatNumeric(float(otext), useGrouping=True, decimalPlaces=decimalPlaces) if not isinstance(otext, basestring): otext = str(otext) return otext def GetText(self): return self.text def SetText(self, text, format = 0): if not isinstance(text, basestring): if self.integermode: text = repr(int(text)) elif self.floatmode: text = '%.*f' % (self.floatmode[2], float(text)) else: text = str(text) text = StripTags(text, stripOnly=['localized']) if self.passwordchar is not None: displayText = self.passwordchar * len(text.replace('<br>', '')) elif format: displayText = self.EncodeOutput(text) + self.suffix elif self.floatmode: displayText = text.replace(self.DECIMAL, self.GetLocalizedDecimal()) else: displayText = text displayText = StripTags(displayText, stripOnly=['localized']) self.sr.text.text = displayText.replace('<', '<').replace('>', '>') self.text = text def Delete(self, direction = 1): if self.readonly: return if direction: begin = self.caretIndex[0] newCaretIndex = self.caretIndex[0] end = min(self.caretIndex[0] + 1, len(self.text)) else: end = self.caretIndex[0] begin = max(self.caretIndex[0] - 1, 0) newCaretIndex = begin become = self.text[:begin] + self.text[end:] if not become and (self.floatmode or self.integermode): if self.floatmode: minbound, maxbound = self.floatmode[:2] if self.integermode: minbound, maxbound = self.integermode if minbound <= 0 <= maxbound: become = '' self.SetText(become) newCaretIndex = min(newCaretIndex, len(self.text)) self.caretIndex = self.GetCursorFromIndex(newCaretIndex) self.OnTextChange() def Disable(self): Container.Disable(self) self.opacity = 0.3 def Enable(self): Container.Enable(self) self.opacity = 1.0
def ShowUI(self): self.SetupImpactArrow() uicontrols.Window.CloseIfOpen(windowID=self.windowID) wnd = uicontrols.Window.Open(windowID=self.windowID) wnd.SetTopparentHeight(0) wnd.SetMinSize([500, 100]) wnd.SetCaption(self.name) wnd._OnClose = self._OnClose main = wnd.GetMainArea() headerCont = Container(name='headerCont', parent=main, align=uiconst.TOTOP, height=30, padBottom=10) bottomCont = Container(name='bottomCont', parent=main, align=uiconst.TOBOTTOM, height=30) self.shipIdLabel = EveLabelSmall(name='shipIDLabel', align=uiconst.CENTER, parent=headerCont, text='Ship ID: %s' % self.shipId) Button(name='apply_button', align=uiconst.CENTER, parent=bottomCont, label='Apply Physical Impact', func=self._OnApplyPhysicalImpact) mainContainer = GridContainer(name='mainCont', parent=main, align=uiconst.TOALL, columns=4, rows=3) container = Container(name='impactVelocityLockAndLabel', align=uiconst.TOALL, parent=mainContainer, padRight=10) self.lockVelocityButton = ButtonIcon( name='MyButtonIcon', parent=container, align=uiconst.TOPLEFT, width=16, height=16, iconSize=16, padLeft=10, texturePath='res:/UI/Texture/Icons/bookmark.png', func=self.OnLockVelocity) EveLabelSmall(name='impactVelocity', align=uiconst.TORIGHT, parent=container, padRight=10, text='Impact Velocity') self.impactVelocityXInput = SinglelineEdit( name='xVelocity', align=uiconst.TOTOP, label='X', parent=mainContainer, padRight=10, setvalue=str(self.impactVelocity[0]), OnFocusLost=self.OnSetImpactVelocityX, OnReturn=self.OnSetImpactVelocityX) self.impactVelocityYInput = SinglelineEdit( name='yVelocity', align=uiconst.TOTOP, label='Y', parent=mainContainer, padRight=10, setvalue=str(self.impactVelocity[1]), OnFocusLost=self.OnSetImpactVelocityY, OnReturn=self.OnSetImpactVelocityY) self.impactVelocityZInput = SinglelineEdit( name='zVelocity', align=uiconst.TOTOP, label='Z', parent=mainContainer, padRight=10, setvalue=str(self.impactVelocity[2]), OnFocusLost=self.OnSetImpactVelocityZ, OnReturn=self.OnSetImpactVelocityZ) EveLabelSmall(name='shipIDInputLabel', parent=mainContainer, align=uiconst.TORIGHT, padRight=10, text='Ship ID') self.shipInput = SinglelineEdit(name='shipIdInput', parent=mainContainer, align=uiconst.TOTOP, padRight=10, setvalue=str(session.shipid), OnFocusLost=self.OnSetShipId, OnReturn=self.OnSetShipId) EveLabelSmall(name='damageLocatorLabel', align=uiconst.TORIGHT, padRight=10, parent=mainContainer, text='Damage Locator') self.damageLocatorInput = SinglelineEdit( name='damageLocator', align=uiconst.TOTOP, label='', parent=mainContainer, padRight=10, setvalue=str(self.damageLocatorID), ints=(0, 0), OnChange=self.OnSetDamageLocator) EveLabelSmall(name='impactMassLabel', align=uiconst.TORIGHT, padRight=10, parent=mainContainer, text='Impact Mass') self.impactMassInput = SinglelineEdit(name='impactMass', align=uiconst.TOTOP, label='', parent=mainContainer, padRight=10, setvalue=str( self.impactObjectMass), OnChange=self.OnSetImpactMass) self.randomizeDL = Checkbox(name='myCheckbox', parent=mainContainer, text='Randomize Damage Locators', checked=self.randomize, callback=self.OnRandomize) self.AddImpactArrowToScene() self.OnSetShipId()
def OnNumericDownButtonMouseDown(self, *args): ButtonIcon.OnMouseDown(self.downButton, *args) self.updateNumericInputThread = uthread.new(self.UpdateNumericInputThread, -1)
def ApplyAttributes(self, attributes): ButtonIcon.ApplyAttributes(self, attributes) self.settingGroupKey = VIEWMODE_MARKERS_SETTINGS self.callback = attributes.callback self.SetTexturePath(ICON_ROOT + 'markersIcon.png')
def OnNumericDownButtonMouseUp(self, *args): ButtonIcon.OnMouseUp(self.downButton, *args) self.KillNumericInputThread()
def Close(self, *args): ButtonIcon.Close(self, *args) self.callback = None
def SetSelected(self): ButtonIcon.SetSelected(self) self.ConstructCheckmark() self.checkmark.display = True self.frame.SetRGB(*SELECTED_FRAME_COLOR)
def ApplyAttributes(self, attributes): ButtonIcon.ApplyAttributes(self, attributes) self.controller = attributes.controller
def SetDeselected(self): ButtonIcon.SetDeselected(self) if self.checkmark: self.checkmark.display = False self.frame.SetRGB(*NOT_SELECTED_FRAME_COLOR)
def ApplyAttributes(self, attributes): self.item = attributes.item self.typeID = self.item.typeID BuySellItemContainerBase.ApplyAttributes(self, attributes) self.adjustQtyAndPriceTimer = None self.isUpdating = False self.singleton = self.item.singleton self.itemID = self.item.itemID self.itemName = evetypes.GetName(self.typeID) self.brokersFee = 0.0 self.salesTax = 0.0 self.totalSum = 0.0 self.stationID = attributes.stationID self.limits = self.quoteSvc.GetSkillLimits(self.stationID) self.solarSystemID = attributes.solarSystemID self.regionID = self.GetRegionID() self.locationID = self.item.locationID self.bestBid = attributes.bestBid self.bestPrice = attributes.bestPrice self.totalStrikethroughLine = None self.priceAmountWarning = None self.deltaCont = Container(parent=self, align=uiconst.TORIGHT, width=30) theRestCont = Container(name='theRestCont', parent=self, align=uiconst.TOALL) self.totalCont = Container(name='totalCont', parent=theRestCont, align=uiconst.TORIGHT_PROP, width=0.3) self.priceCont = Container(name='priceCont', parent=theRestCont, align=uiconst.TORIGHT_PROP, width=0.22) self.qtyCont = Container(name='qtyCont', parent=theRestCont, align=uiconst.TORIGHT_PROP, width=0.15) self.itemCont = Container(name='itemCont', parent=theRestCont, align=uiconst.TORIGHT_PROP, width=0.33) self.deleteCont = Container(name='deleteCont', parent=self.itemCont, align=uiconst.TORIGHT, width=24) self.deleteButton = ButtonIcon( texturePath='res:/UI/Texture/Icons/73_16_210.png', pos=(0, 0, 16, 16), align=uiconst.CENTERRIGHT, parent=self.deleteCont, hint=GetByLabel('UI/Generic/RemoveItem'), idx=0, func=self.RemoveItem) self.deleteCont.display = False self.textCont = Container(name='textCont', parent=self.itemCont, align=uiconst.TOALL) self.errorBg = ErrorFrame(bgParent=self) self.DrawItem() self.DrawQty() self.DrawPrice() self.DrawTotal() self.DrawDelta() self.estimatedSellCount = self.GetSellCountEstimate() self.SetTotalSumAndLabel() self.brokersFeePerc = self.limits.GetBrokersFeeForLocation( self.stationID) self.UpdateBrokersFee() self.GetSalesTax() self.ShowNoSellOrders() self.UpdateOrderStateInUI()
def ApplyAttributes(self, attributes): Container.ApplyAttributes(self, attributes) self.parentFunc = attributes.parentFunc self.padding = (0, 2, 0, 2) self.item = attributes.item self.singleton = self.item.singleton self.parentEditFunc = attributes.editFunc self.typeID = self.item.typeID self.itemID = self.item.itemID self.invType = cfg.invtypes.Get(self.typeID) self.itemName = self.invType.name self.brokersFee = 0.0 self.salesTax = 0.0 self.totalSum = 0.0 self.quote = sm.GetService('marketQuote') self.limits = self.quote.GetSkillLimits() self.stationID, officeFolderID, officeID = sm.GetService( 'invCache').GetStationIDOfficeFolderIDOfficeIDOfItem(self.item) self.located = None if officeFolderID is not None: self.located = [officeFolderID, officeID] station = sm.GetService('ui').GetStation(self.stationID) self.solarSystemID = station.solarSystemID self.regionID = self.GetRegionID(self.stationID) self.averagePrice = self.quote.GetAveragePrice(self.typeID) self.bestBid = self.quote.GetBestBid(self.typeID, locationID=self.solarSystemID) self.GetBestPrice() self.deltaCont = Container(parent=self, align=uiconst.TORIGHT, width=30) theRestCont = Container(parent=self, align=uiconst.TOALL) self.totalCont = Container(parent=theRestCont, align=uiconst.TORIGHT_PROP, width=0.3) self.priceCont = Container(parent=theRestCont, align=uiconst.TORIGHT_PROP, width=0.22) self.qtyCont = Container(parent=theRestCont, align=uiconst.TORIGHT_PROP, width=0.15) self.itemCont = Container(parent=theRestCont, align=uiconst.TORIGHT_PROP, width=0.33) self.deleteCont = Container(parent=self.itemCont, align=uiconst.TORIGHT, width=24) self.deleteButton = ButtonIcon( texturePath='res:/UI/Texture/Icons/73_16_210.png', pos=(0, 0, 16, 16), align=uiconst.CENTERRIGHT, parent=self.deleteCont, hint=GetByLabel('UI/Generic/RemoveItem'), idx=0, func=self.RemoveItem) self.deleteCont.display = False self.textCont = Container(parent=self.itemCont, align=uiconst.TOALL) self.errorBg = ErrorFrame(bgParent=self) self.DrawItem() self.DrawQty() self.DrawPrice() self.DrawTotal() self.DrawDelta() self.GetTotalSum() self.GetBrokersFee() self.GetSalesTax() self.ShowNoSellOrders()
def ApplyAttributes(self, attributes): Window.ApplyAttributes(self, attributes) self.SetTopparentHeight(0) self.SetWndIcon('res:/ui/texture/icons/bigplay_64.png') self._stopUpdate = False self._onFinish = None self._subtitles = None self._finished = False self.bottomContainer = Container(name='bottomContainer', parent=self.sr.main, align=uiconst.TOBOTTOM, height=16, padding=const.defaultPadding) self.layoutAreaParent = Container(parent=self.sr.main, padding=const.defaultPadding) self.layoutAreaParent._OnSizeChange_NoBlock = self.RecalcLayout self.layoutArea = Container(parent=self.layoutAreaParent, align=uiconst.CENTER, width=100, height=100) self.video = StreamingVideoSprite(parent=self.layoutArea, align=uiconst.TOALL) self.video.OnVideoSizeAvailable = self.RecalcLayout self.video.OnVideoFinished = self._OnVideoFinished self.playPauseBtn = ButtonIcon(parent=self.bottomContainer, func=self.Play, align=uiconst.TOLEFT) self.muteBtn = ButtonIcon(parent=self.bottomContainer, func=self.Mute, align=uiconst.TOLEFT) self.volumeSlider = Slider(parent=self.bottomContainer, width=48, minValue=0, maxValue=100, startValue=100, showLabel=False, onsetvaluefunc=self.SetVolume, align=uiconst.TOLEFT) self.volume = settings.user.ui.Get('videoPlayerVolume', 100) self.volumeSlider.SetValue(self.volume, updateHandle=True, triggerCallback=False) self.subtitlesBtn = ButtonIcon(parent=self.bottomContainer, func=self.SwitchSubtitles, align=uiconst.TORIGHT) self.showSubtitles = True positionContainer = Container(parent=self.bottomContainer, align=uiconst.TOALL, padding=6) self.positionFill = Fill(parent=Container(parent=positionContainer, state=uiconst.UI_DISABLED), name='progressFill', align=uiconst.TOLEFT_PROP, color=(0.1804, 0.5412, 0.6392, 1)) self.downloadedFill = Fill(parent=Container(parent=positionContainer, state=uiconst.UI_DISABLED), name='downloadFill', align=uiconst.TOLEFT_PROP, color=(0.4667, 0.7529, 0.8392, 1)) Fill(parent=positionContainer, align=uiconst.TOALL, color=(1.0, 1.0, 1.0, 0.3)) self.followUpContainer = Container(parent=self.layoutAreaParent, align=uiconst.TOALL, state=uiconst.UI_HIDDEN) self.sr.subtitleCont = Container(parent=self.layoutArea, name='subtitleCont', idx=0, align=uiconst.TOBOTTOM_NOPUSH, state=uiconst.UI_DISABLED, height=100) self.sr.subtitleCont.Flush() self.UpdateLayoutArea() uthread2.StartTasklet(self._UpdatePosition)
def ApplyAttributes(self, attributes): ButtonIcon.ApplyAttributes(self, attributes) self.activityID, self.bpData = attributes.args
def ShowUI(self): self.explosionBucketsUsedWhenWindowOpened = SpaceObjectExplosionManager.USE_EXPLOSION_BUCKETS wnd = uicontrols.Window.Open(windowID=self.windowID) wnd.SetTopparentHeight(0) wnd.SetMinSize([500, 250]) wnd.SetCaption(self.name) wnd._OnClose = self._OnClose main = wnd.GetMainArea() bottomCont = Container(name='bottomCont', parent=main, align=uiconst.TOBOTTOM, height=30, width=50, padBottom=10) explosionSelectionContainer = Container(name='explosionSelectionCont', parent=main, align=uiconst.TOBOTTOM, height=30, padTop=10, padBottom=10) explosionContainer = Container(name='explosionContainer', parent=main, align=uiconst.TOALL, padBottom=10) self.scroll = uicontrols.Scroll(parent=explosionContainer) self.scroll.sr.id = 'explosionDebugScroll' self.scroll.OnSelectionChange = self.OnSelectionChange self.explosionCombo = Combo(name='myCombo', parent=explosionSelectionContainer, label='Set explosion to selected items', options=[('Random', None)], callback=self.OnExplosionSelected, align=uiconst.TOTOP, padRight=12, padLeft=12) buttonGrid = GridContainer(name='buttonGrid', parent=bottomCont, align=uiconst.CENTER, width=150, height=20, lines=1, columns=3) ButtonIcon( name='Play', parent=buttonGrid, align=uiconst.TORIGHT, width=20, height=20, iconSize=24, padRight=15, texturePath='res:/UI/Texture/Icons/play.png', func=self.Explode, hint='Play Explosions (the exploding ships will not survive)') ButtonIcon(name='Refresh', parent=buttonGrid, align=uiconst.CENTER, width=20, height=20, iconSize=24, texturePath='res:/UI/Texture/Icons/replay.png', func=self.UpdateTable, hint='Update table') ButtonIcon(name='ClearWrecks', parent=buttonGrid, align=uiconst.TOLEFT, width=20, height=20, iconSize=32, padLeft=15, texturePath='res:/UI/Texture/Icons/44_32_37.png', func=self.ClearWrecks, hint='Clear wrecks') self.UpdateTable()
def ApplyAttributes(self, attributes): ButtonIcon.ApplyAttributes(self, attributes) delta = attributes.delta self.deltaText = Label(parent=self, align=uiconst.CENTER, fontsize=9, top=2) self.UpdateDelta(delta)