Passed
Pull Request — master (#291)
by Marek
02:06
created

FleetsOverviewDlg._populateName()   A

Complexity

Conditions 2

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
#
2
#  Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/]
3
#
4
#  This file is part of Outer Space.
5
#
6
#  Outer Space is free software; you can redistribute it and/or modify
7
#  it under the terms of the GNU General Public License as published by
8
#  the Free Software Foundation; either version 2 of the License, or
9
#  (at your option) any later version.
10
#
11
#  Outer Space is distributed in the hope that it will be useful,
12
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
13
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
#  GNU General Public License for more details.
15
#
16
#  You should have received a copy of the GNU General Public License
17
#  along with Outer Space; if not, write to the Free Software
18
#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19
#
20
21
import pygameui as ui
22
from osci.StarMapWidget import StarMapWidget
23
from osci import gdata, res, client
24
import ige.ospace.Const as Const
25
from ige.ospace import Rules
26
import bisect, math
27
28
class FleetsOverviewDlg:
29
30
    def __init__(self, app):
31
        self.app = app
32
        self.createUI()
33
34
    def display(self):
35
        if gdata.config.defaults.showredirects != None:
36
            val = gdata.config.defaults.showredirects
37
            self.win.vRedirects.checked = val == 'yes'
38
39
        self.show()
40
        self.win.show()
41
        # register for updates
42
        if self not in gdata.updateDlgs:
43
            gdata.updateDlgs.append(self)
44
45
    def hide(self):
46
        self.win.setStatus(_("Ready."))
47
        self.win.hide()
48
        # unregister updates
49
        if self in gdata.updateDlgs:
50
            gdata.updateDlgs.remove(self)
51
52
    def update(self):
53
        self.show()
54
55
    def _analyzeRelations(self, playerID, fleet):
56
        # this evaluates color, and if it should be shown at all
57
        # get check box selections
58
        checkBoxes = [self.win.vEnemy.checked,
59
                      self.win.vUnfriendy.checked,
60
                      self.win.vNeutral.checked,
61
                      self.win.vFriendly.checked,
62
                      self.win.vAllied.checked]
63
64
        # check fleet color and decide if display the fleet
65
        if hasattr(fleet, 'owner'):
66
            plRelation = client.getRelationTo(fleet.owner)
67
            fgColor = res.getPlayerColor(fleet.owner)
68
            if fleet.owner == playerID and self.win.vMine.checked:
69
                return fgColor
70
            return fgColor if checkBoxes[bisect.bisect(Const.REL_BOUNDARIES, plRelation)] else None
71
        else:
72
            # with no owner assume enemy
73
            return res.getFFColorCode(Const.REL_ENEMY_LO) if checkBoxes[0] else None
74
75
    def _populateName(self, fleet):
76
        return fleet.customname if hasattr(fleet,'customname') and fleet.customname else \
77
               getattr(fleet, 'name', res.getUnknownName())
78
79
    def _populatePopup(self, playerID, fleet):
80
        if hasattr(fleet, 'owner') and playerID != fleet.owner:
81
            owner = getattr(client.get(fleet.owner, noUpdate = 1), "name", res.getUnknownName())
82
            ownerName = " (%s)" % owner
83
            ownerNameTip = owner
84
            ownerTipTitle = _("Owner")
85
        else:
86
            ownerName = ""
87
            ownerNameTip = ""
88
            ownerTipTitle = ""
89
        return ownerName, ownerNameTip, ownerTipTitle
90
91
    def _populateLocation(self, playerID, fleet):
92
        systemName = "-"
93
        if hasattr(fleet, 'orbiting') and fleet.orbiting:
94
            system = client.get(fleet.orbiting, noUpdate = 1)
95
            systemName = getattr(system, "name", res.getUnknownName())
96
        elif hasattr(fleet, 'closeSystem'):
97
            system = client.get(fleet.closeSystem, noUpdate = 1)
98
            systemName = _("%s (dst)") % getattr(system, "name", res.getUnknownName())
99
        return systemName
100
101
    def _populateOrder(self, fleet):
102
        # get fleet current action and target of action
103
        order = "-"
104
        targetName = "-"
105
        if hasattr(fleet, 'actions') and fleet.actionIndex < len(fleet.actions):
106
            action, target, data  = fleet.actions[fleet.actionIndex]
107
            if action == Const.FLACTION_REDIRECT and not self.win.vRedirects.checked:
108
                # ok, not interested then
109
                return None
110
            order = gdata.fleetActions[action]
111
            if target != Const.OID_NONE:
112
                targetName = getattr(client.get(target, noUpdate = 1), 'name', res.getUnknownName())
113
                order = "%s %s" % (order, targetName)
114
        return order
115
116
    def _populateEta(self, fleet):
117
        return res.formatTime(fleet.eta) if hasattr(fleet, "eta") else "?"
118
119
    def _populateFuel(self, fleet):
120
        if hasattr(fleet, "storEn"):
121
            fuel = 100 * fleet.storEn / fleet.maxEn if fleet.maxEn > 0 else 0
122
        else:
123
            fuel = "?"
124
        return fuel
125
126
    def _populateOpTime(self, fleet):
127
        if hasattr(fleet, 'storEn') and hasattr(fleet, 'operEn'):
128
            turns = fleet.storEn / fleet.operEn if fleet.operEn > 0 else 100000
129
            rawRange = turns * fleet.speed / Rules.turnsPerDay
130
            _range = "%.2f" % rawRange
131
            opTime = res.formatTime(turns)
132
        else:
133
            _range = "?"
134
            opTime = "?"
135
        return opTime, _range
136
137
    def _populateLastUpgrade(self, fleet):
138
        return res.formatTime(fleet.lastUpgrade) if hasattr(fleet, "lastUpgrade") else "?"
139
140
    def show(self):
141
        player = client.getPlayer()
142
        items = []
143
        for fleetID in client.db.keys():
144
            fleet = client.get(fleetID, noUpdate = 1)
145
            # skip non-fleets
146
            if not hasattr(fleet, "type") or fleet.type != Const.T_FLEET:
147
                continue
148
149
            fgColor = self._analyzeRelations(player.oid, fleet)
150
            if fgColor is None:
151
                # nothing to show
152
                continue
153
154
            order = self._populateOrder(fleet)
155
            if order is None:
156
                # nothing to show - redirect, which is not ticked
157
                continue
158
159
            ownerName, ownerNameTip, ownerTipTitle = self._populatePopup(player.oid, fleet)
160
            opTime, _range = self._populateOpTime(fleet)
161
162
            # create ListBox Item for fleet
163
            item = ui.Item(
164
                "%s %s" % (self._populateName(fleet), ownerName),
165
                tooltipTitle = ownerTipTitle,
166
                tooltip = ownerNameTip,
167
                tLocation = self._populateLocation(player.oid,fleet),
168
                tOrder = self._populateOrder(fleet),
169
                tMP = getattr(fleet, "combatPwr", "?"),
170
                tETA = self._populateEta(fleet),
171
                tSignature = getattr(fleet, "signature", "?"),
172
                tFuel = self._populateFuel(fleet),
173
                tOpTime = opTime,
174
                tRange = _range,
175
                tLastUpgrade = self._populateLastUpgrade(fleet),
176
                tFleetID = fleetID,
177
                foreground = fgColor)
178
            items.append(item)
179
180
        self.win.vFleets.items = items
181
        self.win.vFleets.itemsChanged()
182
183
    def onSelectFleet(self, widget, action, data):
184
        item = self.win.vFleets.selection[0]
185
        fleet = client.get(item.tFleetID, noUpdate = 1)
186
        if hasattr(fleet, "owner") and fleet.owner == client.getPlayerID():
187
            # show dialog
188
            gdata.mainGameDlg.onSelectMapObj(None, None, item.tFleetID)
189
        else:
190
            # center fleet on map
191
            if hasattr(fleet, "x"):
192
                gdata.mainGameDlg.win.vStarMap.highlightPos = (fleet.x, fleet.y)
193
                gdata.mainGameDlg.win.vStarMap.setPos(fleet.x, fleet.y)
194
                self.hide()
195
                return
196
            self.win.setStatus(_("Cannot show location"))
197
198
    def onShowLocation(self, widget, action, data):
199
        item = self.win.vFleets.selection[0]
200
        fleet = client.get(item.tFleetID, noUpdate = 1)
201
        # center on map
202
        if hasattr(fleet, "x"):
203
            gdata.mainGameDlg.win.vStarMap.highlightPos = (fleet.x, fleet.y)
204
            gdata.mainGameDlg.win.vStarMap.setPos(fleet.x, fleet.y)
205
            self.hide()
206
            return
207
        self.win.setStatus(_("Cannot show location"))
208
209
    def onToggleCondition(self, widget, action, data):
210
        self.update()
211
212
    def onClose(self, widget, action, data):
213
        self.hide()
214
215
    def createUI(self):
216
        w, h = gdata.scrnSize
217
        self.win = ui.Window(self.app,
218
            modal = 1,
219
            escKeyClose = 1,
220
            titleOnly = w == 800 and h == 600,
221
            movable = 0,
222
            title = _('Fleets Overview'),
223
            rect = ui.Rect((w - 800 - 4 * (w != 800)) / 2, (h - 600 - 4 * (h != 600)) / 2, 800 + 4 * (w != 800), 580 + 4 * (h != 600)),
224
            layoutManager = ui.SimpleGridLM(),
225
        )
226
        self.win.subscribeAction('*', self)
227
        # playets listbox
228
        ui.Listbox(self.win, layout = (0, 0, 40, 26), id = 'vFleets',
229
            columns = [
230
                (_('Fleet'), 'text', 5, ui.ALIGN_W),
231
                (_('Location'), 'tLocation', 6.5, ui.ALIGN_W),
232
                (_('Current order'), 'tOrder', 7, ui.ALIGN_W),
233
                (_('ETA'), 'tETA', 3, ui.ALIGN_E),
234
                (_('Fuel %'), 'tFuel', 3, ui.ALIGN_E),
235
                (_('Op. time'), 'tOpTime', 3, ui.ALIGN_E),
236
                (_('Range'), 'tRange', 3, ui.ALIGN_E),
237
                (_('MP'), 'tMP', 3, ui.ALIGN_E),
238
                (_('Sign'), 'tSignature', 2, ui.ALIGN_E),
239
                (_("Last upgr."), "tLastUpgrade", 3.5, ui.ALIGN_E),
240
            ],
241
            columnLabels = 1, action = 'onSelectFleet', rmbAction = "onShowLocation")
242
243
        ui.Check(self.win, layout = (0, 26, 5, 1), text = _('Mine'), id = "vMine",
244
            checked = 1, action = "onToggleCondition")
245
        ui.Check(self.win, layout = (5, 26, 5, 1), text = _('Enemy'), id = "vEnemy",
246
            checked = 0, action = "onToggleCondition")
247
        ui.Check(self.win, layout = (10, 26, 5, 1), text = _('Unfriendly'), id = "vUnfriendy",
248
            checked = 0, action = "onToggleCondition")
249
        ui.Check(self.win, layout = (15, 26, 5, 1), text = _('Neutral'), id = "vNeutral",
250
            checked = 0, action = "onToggleCondition")
251
        ui.Check(self.win, layout = (20, 26, 5, 1), text = _('Friendly'), id = "vFriendly",
252
            checked = 0, action = "onToggleCondition")
253
        ui.Check(self.win, layout = (25, 26, 5, 1), text = _('Allied'), id = "vAllied",
254
            checked = 0, action = "onToggleCondition")
255
        ui.Check(self.win, layout = (34, 26, 6, 1), text = _('Show redirects'), id = "vRedirects",
256
            checked = 0, action = "onToggleCondition")
257
        # status bar + submit/cancel
258
        ui.TitleButton(self.win, layout = (35, 27, 5, 1), text = _('Close'), action = 'onClose')
259
        ui.Title(self.win, id = 'vStatusBar', layout = (0, 27, 35, 1), align = ui.ALIGN_W)
260
        #self.win.statusBar = self.win.vStatusBar
261