summaryrefslogtreecommitdiff
path: root/jfr_playoff/gui/frames/visual.py
blob: 9794ef3a76a462e2731244e128098c3d6fc194a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
#coding=utf-8

from collections import OrderedDict

import Tkinter as tk
import ttk
import tkColorChooser as tkcc

from ..frames import GuiFrame, RepeatableFrame, ScrollableFrame
from ..frames import WidgetRepeater
from ..frames import SelectionFrame, RefreshableOptionMenu, NumericSpinbox
from ..frames.team import TeamSelectionButton
from ..variables import NotifyStringVar, NotifyNumericVar, NotifyBoolVar

class VisualSettingsFrame(GuiFrame):
    DEFAULT_VALUES = {
        'width': 250,
        'height': 80,
        'margin': 60,
        'starting_position_indicators': 0,
        'finishing_position_indicators': 0,
        'team_boxes': {
            'label_length_limit': 25,
            'predict_teams': 1,
            'label_separator': ' / ',
            'label_placeholder': '??',
            'label_ellipsis': '(...)',
            'name_separator': '<br />',
            'name_prefix': '&nbsp;&nbsp;',
            'sort_eligible_first': 1
        }
    }

    def renderContent(self):
        self.startingPositionIndicators = NotifyBoolVar()
        self.finishingPositionIndicators = NotifyBoolVar()
        self.boxWidth = NotifyNumericVar()
        self.boxHeight = NotifyNumericVar()
        self.boxMargin = NotifyNumericVar()
        self.shortenTeamNames = NotifyBoolVar()
        self.teamNameLength = NotifyNumericVar()
        self.teamNameEllipsis = NotifyStringVar()
        self.teamNamePredict = NotifyBoolVar()
        self.teamNamePlaceholder = NotifyStringVar()
        self.teamNameSortPredictions = NotifyBoolVar()
        self.teamLabelSeparator = NotifyStringVar()
        self.teamNameSeparator = NotifyStringVar()
        self.teamNamePrefix = NotifyStringVar()

        indicatorsFrame = ttk.LabelFrame(self, text='Znaczniki pozycji:')
        indicatorsFrame.grid(row=0, column=0, sticky=tk.W+tk.E+tk.N+tk.S)
        dimensionsFrame = ttk.LabelFrame(self, text='Wymiary tabelki meczu:')
        dimensionsFrame.grid(row=0, column=1, sticky=tk.W+tk.E+tk.N+tk.S)
        teamNamesFrame = ttk.LabelFrame(self, text='Nazwy teamów:')
        teamNamesFrame.grid(row=1, column=0, sticky=tk.W+tk.E+tk.N+tk.S)
        separatorsFrame = ttk.LabelFrame(self, text='Separatory nazw teamów:')
        separatorsFrame.grid(row=1, column=1, sticky=tk.W+tk.E+tk.N+tk.S)

        self._fieldsToEnable = []

        (ttk.Checkbutton(
            indicatorsFrame, text='początkowych',
            variable=self.startingPositionIndicators)).grid(
                row=0, column=0, sticky=tk.W)
        (ttk.Checkbutton(
            indicatorsFrame, text='końcowych',
            variable=self.finishingPositionIndicators)).grid(
                row=1, column=0, sticky=tk.W)

        (NumericSpinbox(
            dimensionsFrame, width=5, from_=1, to=999,
            textvariable=self.boxWidth)).grid(
                row=0, column=0, sticky=tk.W)
        (ttk.Label(dimensionsFrame, text='x')).grid(row=0, column=1)
        (NumericSpinbox(
            dimensionsFrame, width=5, from_=1, to=999,
            textvariable=self.boxHeight)).grid(
                row=0, column=2, sticky=tk.W)
        (ttk.Label(dimensionsFrame, text='odstępy')).grid(
            row=1, column=0, columnspan=2, sticky=tk.E)
        (NumericSpinbox(
            dimensionsFrame, width=5, from_=1, to=999,
            textvariable=self.boxMargin)).grid(
                row=1, column=2, sticky=tk.W)

        (ttk.Checkbutton(
            teamNamesFrame, text='skracaj do',
            variable=self.shortenTeamNames)).grid(
                row=0, column=0, columnspan=2)
        nameLength = NumericSpinbox(
            teamNamesFrame, width=5, from_=1, to=999,
            textvariable=self.teamNameLength)
        nameLength.grid(row=0, column=2, sticky=tk.W)
        lengthLabel = ttk.Label(teamNamesFrame, text='znaków')
        lengthLabel.grid(row=0, column=3, sticky=tk.W)
        ellipsisLabel = ttk.Label(teamNamesFrame, text='znacznik:')
        ellipsisLabel.grid(row=1, column=0, columnspan=2, sticky=tk.E)
        nameEllipsis = ttk.Entry(
            teamNamesFrame, width=5,
            textvariable=self.teamNameEllipsis)
        nameEllipsis.grid(row=1, column=2, sticky=tk.W)
        (ttk.Checkbutton(
            teamNamesFrame,
            text='przewiduj na podstawie trwających meczów',
            variable=self.teamNamePredict)).grid(
                row=2, column=0, columnspan=5)
        placeholderLabel = ttk.Label(
            teamNamesFrame, text='etykieta nieznanych teamów')
        placeholderLabel.grid(row=3, column=1, columnspan=3, sticky=tk.W)
        namePlaceholder = ttk.Entry(
            teamNamesFrame, width=5,
            textvariable=self.teamNamePlaceholder)
        namePlaceholder.grid(row=3, column=4, sticky=tk.W)
        predictSort = ttk.Checkbutton(
            teamNamesFrame, text='wyświetlaj najpierw pewne teamy',
            variable=self.teamNameSortPredictions)
        predictSort.grid(row=4, column=1, columnspan=4, sticky=tk.W)
        self._fieldsToEnable.append(
            (self.shortenTeamNames,
             [nameLength, nameEllipsis, lengthLabel, ellipsisLabel]))
        self._fieldsToEnable.append(
            (self.teamNamePredict,
             [namePlaceholder, placeholderLabel, predictSort]))

        (ttk.Label(separatorsFrame, text=' ')).grid(row=0, column=0)
        (ttk.Label(separatorsFrame, text='w drabince (skrócone nazwy)')).grid(
            row=0, column=1, sticky=tk.E)
        (ttk.Entry(
            separatorsFrame, width=8,
            textvariable=self.teamLabelSeparator)).grid(
                row=0, column=2, sticky=tk.W)
        (ttk.Label(separatorsFrame, text='w "dymkach" (pełne nazwy)')).grid(
            row=1, column=1, sticky=tk.E)
        (ttk.Entry(
            separatorsFrame, width=8,
            textvariable=self.teamNameSeparator)).grid(
                row=1, column=2, sticky=tk.W)
        (ttk.Label(separatorsFrame, text='prefiks pełnych nazw')).grid(
            row=2, column=1, sticky=tk.E)
        (ttk.Entry(
            separatorsFrame, width=8,
            textvariable=self.teamNamePrefix)).grid(
                row=2, column=2, sticky=tk.W)

        for var, fields in self._fieldsToEnable:
            var.trace('w', self._enableFields)
        self._enableFields()

        self.setValues({})

    def _enableFields(self, *args):
        for var, fields in self._fieldsToEnable:
            for field in fields:
                field.configure(state=tk.NORMAL if var.get() else tk.DISABLED)

    def setValues(self, values):
        default_values = self.DEFAULT_VALUES
        if 'team_boxes' in values:
            default_values['team_boxes'].update(values['team_boxes'])
            del values['team_boxes']
        default_values.update(values)
        values = default_values

        self.startingPositionIndicators.set(
            values['starting_position_indicators'])
        self.finishingPositionIndicators.set(
            values['finishing_position_indicators'])
        self.boxWidth.set(values['width'])
        self.boxHeight.set(values['height'])
        self.boxMargin.set(values['margin'])
        self.shortenTeamNames.set(
            values['team_boxes']['label_length_limit'] > 0)
        self.teamNameLength.set(values['team_boxes']['label_length_limit'])
        self.teamNameEllipsis.set(values['team_boxes']['label_ellipsis'])
        self.teamNamePredict.set(values['team_boxes']['predict_teams'])
        self.teamNamePlaceholder.set(values['team_boxes']['label_placeholder'])
        self.teamNameSortPredictions.set(
            values['team_boxes']['sort_eligible_first'])
        self.teamLabelSeparator.set(values['team_boxes']['label_separator'])
        self.teamNameSeparator.set(values['team_boxes']['name_separator'])
        self.teamNamePrefix.set(values['team_boxes']['name_prefix'])

    def getValues(self):
        return OrderedDict(
            {
                'width': self.boxWidth.get(default=250),
                'height': self.boxHeight.get(default=80),
                'margin': self.boxMargin.get(default=60),
                'starting_position_indicators': self.startingPositionIndicators.get(),
                'finishing_position_indicators': self.finishingPositionIndicators.get(),
                'team_boxes': {
                    'label_length_limit': self.teamNameLength.get(default=25) if self.shortenTeamNames else 0,
                    'predict_teams': self.teamNamePredict.get(),
                    'label_separator': self.teamLabelSeparator.get(),
                    'label_placeholder': self.teamNamePlaceholder.get(),
                    'label_ellipsis': self.teamNameEllipsis.get(),
                    'name_separator': self.teamNameSeparator.get(),
                    'name_prefix': self.teamNamePrefix.get(),
                    'sort_eligible_first': self.teamNameSortPredictions.get()
                }
            })


class MatchList(RefreshableOptionMenu):
    def __init__(self, *args, **kwargs):
        RefreshableOptionMenu.__init__(self, *args, **kwargs)
        self.winfo_toplevel().bind(
            '<<MatchListChanged>>', self.refreshOptions, add='+')
        self.configure(width=10)

    def getLabel(self, match):
        return match.label

    def getValues(self):
        try:
            return self.winfo_toplevel().getMatches()
        except tk.TclError:
            # we're probably being destroyed, ignore
            return []

    def getVarValue(self, match):
        return unicode(match.getMatchID())


class BoxPositionFrame(RepeatableFrame):
    def renderContent(self):
        self.match = NotifyStringVar()
        self.vertical = NotifyNumericVar()
        self.horizontal = NotifyNumericVar()
        self.matchBox = MatchList(self, self.match)
        self.matchBox.configure(width=20)
        self.matchBox.grid(row=0, column=0)

        (ttk.Label(self, text=' w pionie:')).grid(row=0, column=1)
        (NumericSpinbox(
            self, textvariable=self.vertical, from_=0, to=9999,
            width=5)).grid(
                row=0, column=2)
        (ttk.Label(self, text=' w poziomie (-1 = automatyczna):')).grid(
                row=0, column=3)
        (NumericSpinbox(
            self, textvariable=self.horizontal, from_=-1, to=9999,
            width=5)).grid(
                row=0, column=4)
        self.setValue([])

    def setValue(self, value):
        if len(value) > 1:
            self.match.set(value[0])
            self.vertical.set(value[1])
            if len(value) > 2:
                self.horizontal.set(value[2])
            else:
                self.horizontal.set(-1)
        else:
            self.match.set('')
            self.vertical.set(0)
            self.horizontal.set(-1)

    def getValue(self):
            horizontal = self.horizontal.get(default=-1)
            vertical = self.vertical.get(default=0)
            return (
                self.match.get(),
                [vertical, horizontal] if horizontal >= 0 else vertical)

class BoxPositionsFrame(ScrollableFrame):
    def renderContent(self, container):
        (ttk.Label(container, text='Pozycje tabelek meczów:')).pack(
            side=tk.TOP, anchor=tk.W)
        self.positions = WidgetRepeater(container, BoxPositionFrame)
        self.positions.pack(
            side=tk.TOP, fill=tk.BOTH, expand=True)

    def setValues(self, values):
        values = sorted(list(values.iteritems()), key=lambda v: int(v[0]))
        values_to_set = []
        for idx, val in enumerate(values):
            value = [val[0]]
            if isinstance(val[1], list):
                value += val[1]
            else:
                value.append(val[1])
            values_to_set.append(value)
        self.positions.setValue(values_to_set)

    def getValues(self):
        return OrderedDict(
            { match: config for match, config in self.positions.getValue() })

class LineStyle(GuiFrame):
    def _selectColour(self):
        colour = tkcc.askcolor(self._getColour())
        if colour is not None:
            self._setColour(colour[1])

    def _getColour(self):
        return self.colourBtn.cget('bg')

    def _setColour(self, colour):
        self.colourBtn.configure(bg=colour)

    def renderContent(self):
        self.hOffset = NotifyNumericVar()
        self.vOffset = NotifyNumericVar()

        (ttk.Label(self, text='kolor:')).grid(row=0, column=0)
        self.colourBtn = tk.Button(self, width=2, command=self._selectColour)
        self.colourBtn.grid(row=0, column=1)
        (ttk.Label(self, text='margines w poziomie:')).grid(row=0, column=2)
        (NumericSpinbox(
            self, textvariable=self.hOffset, from_=-50, to=50,
            width=5)).grid(row=0, column=3)
        (ttk.Label(self, text='margines w pionie:')).grid(row=0, column=4)
        (NumericSpinbox(
            self, textvariable=self.vOffset, from_=-50, to=50,
            width=5)).grid(row=0, column=5)

    def setValue(self, value):
        self._setColour(value[0])
        self.hOffset.set(value[1])
        self.vOffset.set(value[2])

    def getValue(self):
        return [self._getColour(), self.hOffset.get(), self.vOffset.get()]

class LineStylesFrame(GuiFrame):
    DEFAULT_VALUES = [
        ('winner', ('#00ff00', 5, -10),
         'Zwycięzcy meczów: '),
        ('loser', ('#ff0000', 20, 10),
         'Przegrani meczów: '),
        ('place_winner', ('#00dddd', 10, 2),
         'Pozycje startowe (wybierający): '),
        ('place_loser', ('#dddd00', 15, 9),
         'Pozycje startowe (wybierani): '),
        ('finish_winner', ('#00ff00', 5, -10),
         'Zwycięzcy meczów kończący rozgrywki: '),
        ('finish_loser', ('#ff0000', 20, 10),
         'Przegrani meczów kończący rozgrywki: ')
    ]
    CONFIG_KEYS = ['colour', 'h_offset', 'v_offset']

    def renderContent(self):
        self.lines = OrderedDict()
        for idx, line in enumerate(self.DEFAULT_VALUES):
            self.lines[line[0]] = LineStyle(self)
            self.lines[line[0]].grid(row=idx+1, column=1, sticky=tk.W)
            (ttk.Label(self, text=line[2])).grid(
                row=idx+1, column=0, sticky=tk.E)
        (ttk.Label(self, text='Kolory linii')).grid(
            row=0, column=0, columnspan=2, sticky=tk.W)

    def setValues(self, values):
        for line in self.DEFAULT_VALUES:
            value = list(line[1])
            for idx, key in enumerate(self.CONFIG_KEYS):
                key = '%s_%s' % (line[0], key)
                if key in values:
                    value[idx] = values[key]
            self.lines[line[0]].setValue(value)

    def getValues(self):
        config = OrderedDict()
        for line, widget in self.lines.iteritems():
            value = widget.getValue()
            for idx, key in enumerate(self.CONFIG_KEYS):
                config['%s_%s' % (line, key)] = value[idx]
        return config


class PositionsSelectionFrame(SelectionFrame):
    COLUMN_COUNT=10

    def __init__(self, *args, **kwargs):
        SelectionFrame.__init__(self, *args, **kwargs)
        self.winfo_toplevel().geometry(
            '%dx%d' % (
                self.COLUMN_COUNT * 40,
                (len(self.options) / self.COLUMN_COUNT + 2) * 25 + 30
            ))

    def renderHeader(self, container):
        (ttk.Label(container, text=self.title)).grid(
            row=0, column=0, columnspan=self.COLUMN_COUNT, sticky=tk.W)

    def renderOption(self, container, option, idx):
        (ttk.Checkbutton(
            container, text=str(self._mapValue(idx, option)),
            variable=self.values[self._mapValue(idx, option)]
        )).grid(
            row=(idx/self.COLUMN_COUNT)+1, column=idx%self.COLUMN_COUNT,
            sticky=tk.W)

class PositionStyleFrame(RepeatableFrame):
    def _setPositions(self, values):
        self.positions = values

    def renderContent(self):
        self.name = NotifyStringVar()
        self.description = NotifyStringVar()

        self.columnconfigure(1, weight=1)
        self.columnconfigure(5, weight=1)

        (ttk.Label(self, text='Styl:')).grid(row=0, column=0)
        (ttk.Entry(self, textvariable=self.name)).grid(
            row=0, column=1, sticky=tk.W+tk.E)

        (ttk.Label(self, text='Pozycje końcowe:')).grid(row=0, column=2)
        self.positionBtn = TeamSelectionButton(
            self, prompt='Wybierz pozycje końcowe:',
            dialogclass=PositionsSelectionFrame,
            callback=self._setPositions)
        self.positionBtn.grid(row=0, column=3)

        (ttk.Label(self, text='Opis w legendzie:')).grid(row=0, column=4)
        (ttk.Entry(self, textvariable=self.description)).grid(
            row=0, column=5, sticky=tk.W+tk.E)

        self.setValue({})

    def setValue(self, value):
        self.name.set(value['class'] if 'class' in value else '')
        self.positionBtn.setPositions(
            value['positions'] if 'positions' in value else [])
        self.description.set(value['caption'] if 'caption' in value else '')

    def getValue(self):
        config = OrderedDict({
            'class': self.name.get(),
            'positions': self.positions
        })
        caption = self.description.get()
        if caption:
            config['caption'] = caption
        return config

class PositionStylesFrame(ScrollableFrame):
    def renderContent(self, container):
        (ttk.Label(container, text='Klasyfikacja końcowa')).pack(
            side=tk.TOP, anchor=tk.W)
        self.styles = WidgetRepeater(container, PositionStyleFrame)
        self.styles.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

    def setValues(self, values):
        self.styles.setValue(values)

    def getValues(self):
        return self.styles.getValue()

__all__ = ['VisualSettingsFrame', 'BoxPositionsFrame', 'LineStylesFrame', 'PositionStylesFrame']