-
Notifications
You must be signed in to change notification settings - Fork 1
/
BrowserComponent.py
843 lines (688 loc) · 31.1 KB
/
BrowserComponent.py
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
#Embedded file name: /Users/versonator/Jenkins/live/Projects/AppLive/Resources/MIDI Remote Scripts/Push/BrowserComponent.py
from __future__ import with_statement
from functools import partial
from itertools import izip, chain, imap
import string
import re
import consts
import Live
FilterType = Live.Browser.FilterType
DeviceType = Live.Device.DeviceType
from _Framework.CompoundComponent import CompoundComponent
from _Framework.Util import first, find_if, index_if, clamp, in_range, BooleanContext, nop, const, lazy_attribute, memoize
from _Framework.DisplayDataSource import DisplayDataSource
from _Framework.SubjectSlot import subject_slot, subject_slot_group, SlotManager, Subject
from ScrollableList import ActionListItem, ActionList, ListComponent, DefaultItemFormatter
class VirtualBrowserItem(object):
"""
Quacks like a Live.Browser.BrowserItem
"""
source = ''
is_device = False
is_loadable = False
def __init__(self, name = '', children_query = nop, is_folder = False):
self.name = name
self.is_folder = is_folder
self.children_query = children_query
@lazy_attribute
def children(self):
return self.children_query()
@property
def is_selected(self):
return find_if(lambda x: x.is_selected, self.children)
def __str__(self):
return self.name
class BrowserListItem(ActionListItem):
"""
List item representing a browser element
"""
def __str__(self):
import os
return os.path.splitext(self.content.name)[0] if self.content else ''
def action(self):
if self.container and self.container.browser:
self.container.browser.load_item(self.content)
@property
def supports_action(self):
return self.container and self.container.browser and self.content != None and self.content.is_loadable
class BrowserList(ActionList):
"""
Component for representing lists of browser items
"""
browser = None
item_type = BrowserListItem
def __init__(self, browser = None, *a, **k):
super(BrowserList, self).__init__(*a, **k)
self.browser = browser
class BrowserModel(Subject, SlotManager):
"""
A browser model provides the data to a browser component as a
sequence of BrowserLists.
The BrowserComponent will use equality to discard equivalent
models and prevent unnecessary updating, override it when
neccesary.
"""
__subject_events__ = ('content_lists',)
empty_list_messages = []
def __init__(self, browser = None, *a, **k):
super(BrowserModel, self).__init__(*a, **k)
self._browser = browser
def can_be_exchanged(self, model):
return isinstance(model, BrowserModel)
def exchange_model(self, model):
"""
Tries to replace itself with the settings of a given
model. Returns true if it succeeds or false if the current
model can not represent the same set of values.
"""
if self.can_be_exchanged(model):
self._browser = model._browser
return True
return False
@property
def content_lists(self):
"""
Returns a set of ActionLists that hold the hierarchy of
content for the browser.
"""
return NotImplementedError
def update_content(self):
"""
Called when the browser contents have changed.
"""
raise NotImplementedError
def update_selection(self):
"""
Called when the browser selection might have changed.
"""
raise NotImplementedError
@property
def browser(self):
return self._browser
def make_content_list(self):
return BrowserList(browser=self._browser)
class EmptyBrowserModel(BrowserModel):
"""
A browser model that never returns anything, to be used for
hotswap targets that do not make sense in the L9C.
"""
empty_list_messages = ['Nothing to browse']
@property
def content_lists(self):
return tuple()
def update_content(self):
self.notify_content_lists()
def update_selection(self):
pass
def can_be_exchanged(self, model):
return isinstance(model, EmptyBrowserModel) and super(EmptyBrowserModel, self).can_be_exchanged(model)
class FullBrowserModel(BrowserModel):
"""
A browser model that provides an abstract hierarchical query model
for simpler implementation. Note that this can result in endless
nesting, which the BrowserComponent does not support so far.
It always provides at least two columns.
"""
empty_list_messages = ['<no tags>',
'<no devices>',
'<no presets>',
'<no presets>']
def __init__(self, *a, **k):
super(FullBrowserModel, self).__init__(*a, **k)
self._contents = []
self._num_contents = 0
self._push_content_list()
self._inside_item_activated_notification = BooleanContext()
def get_root_children(self):
"""
Query for the initial items.
"""
return self.browser.tags
def get_children(self, item, level):
"""
Query for children of node.
"""
return item.children
@property
def content_lists(self):
return map(first, self._contents[:self._num_contents])
def can_be_exchanged(self, model):
return isinstance(model, FullBrowserModel) and super(FullBrowserModel, self).can_be_exchanged(model)
def update_content(self):
root, _ = self._contents[0]
root.assign_items(self.get_root_children())
self.update_selection()
def update_selection(self):
target = self._browser.hotswap_target
if self._browser.hotswap_target != None:
if isinstance(target, Live.DrumPad.DrumPad) and (not target.chains or not target.chains[0].devices):
for content_list in self.content_lists:
content_list.select_item_index_with_offset(0, 0)
else:
list_index = 0
while list_index < self._num_contents:
content_list, _ = self._contents[list_index]
items = content_list.items
index = index_if(lambda x: x.content.is_selected, items)
if in_range(index, 0, len(items)):
content_list.select_item_index_with_offset(index, 2)
list_index += 1
def _push_content_list(self):
if self._num_contents < len(self._contents):
self._num_contents += 1
content = self._contents[self._num_contents - 1]
else:
assert self._num_contents == len(self._contents)
content = self.make_content_list()
level = len(self._contents)
slot = self.register_slot(content, partial(self._on_item_activated, level), 'item_activated')
self._contents.append((content, slot))
self._num_contents = len(self._contents)
return content
def _pop_content_list(self):
assert self._num_contents > 1
self._num_contents -= 1
def _fit_content_lists(self, requested_lists):
"""
Ensures that there are exactly 'request_lists' number of
content lists. Returns whether a change was needed or not.
"""
assert requested_lists > 0
if requested_lists != self._num_contents:
while requested_lists < self._num_contents:
self._pop_content_list()
while requested_lists > self._num_contents:
self._push_content_list()
def _finalize_content_lists_change(self):
"""
After a series of push/pop/fit operations, this makes sure
that we only have as many content lists referenced as
necessary.
"""
while self._num_contents < len(self._contents):
_, slot = self._contents.pop()
self.disconnect_disconnectable(slot)
assert self._num_contents == len(self._contents)
def _on_item_activated(self, level):
old_num_contents = self._num_contents
with self._inside_item_activated_notification():
contents, _ = self._contents[level]
selected = contents.selected_item
if selected != None:
is_folder = selected.content.is_folder
children = self.get_children(selected.content, level) if selected != None else []
(children or is_folder or level < 1) and self._fit_content_lists(level + 2)
#how did dj limbs know to do this?
if (children or is_folder or level < 1):
child_contents, _ = self._contents[level + 1]
child_contents.assign_items(children)
else:
self._fit_content_lists(level + 1)
if not self._inside_item_activated_notification:
self._finalize_content_lists_change()
if old_num_contents != self._num_contents:
self.notify_content_lists()
class BrowserQuery(object):
"""
Base class for browser queries. Is capable of creating a subfolder for wrapping
all results of the query.
"""
def __init__(self, subfolder = None, *a, **k):
self.subfolder = subfolder
def __call__(self, browser):
if self.subfolder:
return [VirtualBrowserItem(name=self.subfolder, children_query=partial(self.query, browser), is_folder=True)]
else:
return self.query(browser)
def query(self, browser):
raise NotImplementedError
class PathBrowserQuery(BrowserQuery):
"""
Includes the element for the given path.
"""
def __init__(self, path = tuple(), *a, **k):
super(PathBrowserQuery, self).__init__(*a, **k)
assert path
self.path = path
def query(self, browser):
return self._find_item(self.path, browser.tags, browser) or []
def _find_item(self, path, items = None, browser = None):
name = path[0]
elem = find_if(lambda x: x.name == name, items)
if elem:
return [elem] if len(path) == 1 else self._find_item(path[1:], elem.children)
class TagBrowserQuery(BrowserQuery):
"""
Query that merges the contents of the specified subtrees of
the browser. It will first merge the contents of all the paths
specified in the 'include' list. A path is either the name of a
tag or a list with the name of the tag/folders that describe the
path. Then it drops the items that are in the 'exclude' list.
"""
def __init__(self, include = tuple(), exclude = tuple(), *a, **k):
super(TagBrowserQuery, self).__init__(*a, **k)
self.include = include
self.exclude = exclude
def query(self, browser):
return filter(lambda item: item.name not in self.exclude, sum(map(partial(self._extract_path, browser=browser), self.include), tuple()))
def _extract_path(self, path, items = None, browser = None):
if isinstance(path, (str, unicode)):
path = [path]
if items is None:
items = browser.tags
if path:
name = path[0]
elem = find_if(lambda x: x.name == name, items)
if elem:
items = self._extract_path(path[1:], elem.children)
return tuple(items)
class SourceBrowserQuery(TagBrowserQuery):
"""
Like TagBrowserQuery, but adds a top-level source selection.
"""
def __init__(self, *a, **k):
super(SourceBrowserQuery, self).__init__(*a, **k)
def query(self, browser):
root = super(SourceBrowserQuery, self).query(browser)
groups = dict()
for item in root:
groups.setdefault(item.source, []).append(item)
return map(lambda (k, g): VirtualBrowserItem(name=k, children_query=const(g)), sorted(groups.items(), key=first))
class QueryingBrowserModel(FullBrowserModel):
"""
Browser model that takes query objects to build up the model hierarchy
"""
empty_list_messages = ['<no devices>',
'<no presets>',
'<no presets>',
'<no presets>']
def __init__(self, queries = [], *a, **k):
super(QueryingBrowserModel, self).__init__(*a, **k)
self.queries = queries
def get_root_children(self):
browser = self.browser
return chain(*imap(lambda q: q(browser), self.queries))
def can_be_exchanged(self, model):
return isinstance(model, QueryingBrowserModel) and super(QueryingBrowserModel, self).can_be_exchanged(model)
def exchange_model(self, model):
if super(QueryingBrowserModel, self).exchange_model(model):
self.queries = model.queries
return True
def make_midi_effect_browser_model(browser):
midi_effects = TagBrowserQuery(include=['MIDI Effects'])
max = TagBrowserQuery(include=[['Max for Live', 'Max MIDI Effect']], subfolder='Max for Live')
return QueryingBrowserModel(browser=browser, queries=[midi_effects, max])
def make_audio_effect_browser_model(browser):
audio_effects = TagBrowserQuery(include=['Audio Effects'])
max = TagBrowserQuery(include=[['Max for Live', 'Max Audio Effect']], subfolder='Max for Live')
return QueryingBrowserModel(browser=browser, queries=[audio_effects, max])
def make_instruments_browser_model(browser):
instrument_rack = PathBrowserQuery(path=['Instruments', 'Instrument Rack'])
drums = SourceBrowserQuery(include=['Drums'], exclude=['Drum Hits'], subfolder='Drum Rack')
instruments = TagBrowserQuery(include=['Instruments'], exclude=['Drum Rack', 'Instrument Rack'])
drum_hits = TagBrowserQuery(include=[['Drums', 'Drum Hits']], subfolder='Drum Hits')
max = TagBrowserQuery(include=[['Max for Live', 'Max Instrument']], subfolder='Max for Live')
return QueryingBrowserModel(browser=browser, queries=[instrument_rack,
drums,
instruments,
max,
drum_hits])
def make_drum_pad_browser_model(browser):
drums = TagBrowserQuery(include=[['Drums', 'Drum Hits']])
samples = SourceBrowserQuery(include=['Samples'], subfolder='Samples')
instruments = TagBrowserQuery(include=['Instruments'])
max = TagBrowserQuery(include=[['Max for Live', 'Max Instrument']], subfolder='Max for Live')
return QueryingBrowserModel(browser=browser, queries=[drums,
samples,
instruments,
max])
def make_fallback_browser_model(browser):
return EmptyBrowserModel(browser=browser)
def filter_type_for_hotswap_target(target):
"""
Returns the appropriate browser filter type for a given hotswap target.
"""
if isinstance(target, Live.Device.Device):
if target.type == DeviceType.instrument:
return FilterType.instrument_hotswap
elif target.type == DeviceType.audio_effect:
return FilterType.audio_effect_hotswap
elif target.type == DeviceType.midi_effect:
return FilterType.midi_effect_hotswap
else:
FilterType.disabled
elif isinstance(target, Live.DrumPad.DrumPad):
return FilterType.drum_pad_hotswap
return FilterType.disabled
def make_browser_model(browser, filter_type = None):
"""
Factory that returns an appropriate browser model depending on the
browser filter type and hotswap target.
"""
factories = {FilterType.instrument_hotswap: make_instruments_browser_model,
FilterType.drum_pad_hotswap: make_drum_pad_browser_model,
FilterType.audio_effect_hotswap: make_audio_effect_browser_model,
FilterType.midi_effect_hotswap: make_midi_effect_browser_model}
if filter_type == None:
filter_type = filter_type_for_browser(browser)
return factories.get(filter_type, make_fallback_browser_model)(browser)
def filter_type_for_browser(browser):
filter_type = filter_type_for_hotswap_target(browser.hotswap_target)
if filter_type == FilterType.disabled:
filter_type = browser.filter_type
return filter_type
def make_stem_cleaner(stem):
""" Returns a function that can be used to remove the stem from a sentence """
if stem[-1] == 's':
stem = stem[:-1]
if len(stem) > 2:
return _memoized_stem_cleaner(stem)
return nop
@memoize
def _memoized_stem_cleaner(stem):
ellipsis = consts.CHAR_ELLIPSIS
rule1 = re.compile(u'([a-z])' + stem + u's?([ A-Z])')
rule2 = re.compile(u'[' + ellipsis + ' \\-]' + stem + u's?([\\-' + ellipsis + u' A-Z])')
rule3 = re.compile(u'' + stem + u's?$')
def cleaner(short_name):
short_name = ' ' + short_name
short_name = rule1.sub(u'\\1' + ellipsis + u'\\2', short_name)
short_name = rule2.sub(ellipsis + u'\\1', short_name)
short_name = rule3.sub(ellipsis, short_name)
return short_name.strip(' ')
return cleaner
def split_stem(sentence):
""" Splits camel cased sentence into words """
sentence = re.sub('([a-z])([A-Z])', u'\\1 \\2', sentence)
return sentence.split()
_stripper_double_spaces = re.compile(u' [\\- ]*')
_stripper_double_ellipsis = re.compile(consts.CHAR_ELLIPSIS + u'+')
_stripper_space_ellipsis = re.compile(u'[\\- ]?' + consts.CHAR_ELLIPSIS + u'[\\- ]?')
def full_strip(string):
""" Strip string for double spaces and dashes """
string = _stripper_double_spaces.sub(' ', string)
string = _stripper_double_ellipsis.sub(consts.CHAR_ELLIPSIS, string)
string = _stripper_space_ellipsis.sub(consts.CHAR_ELLIPSIS, string)
return string.strip(' ')
class BrowserComponent(CompoundComponent):
"""
Component for controlling the Live library browser. It has 4
browsing columns that are controlled by encoders and state
buttons. The contents of these lists are provided by a browser
model -- see BrowserModel and derivatives.
"""
__subject_events__ = ('load_item',)
NUM_COLUMNS = 4
COLUMN_SIZE = 4
def __init__(self, *a, **k):
super(BrowserComponent, self).__init__(*a, **k)
self._browser = self.application().browser
self._browser_model = make_fallback_browser_model(self._browser)
num_data_sources = self.NUM_COLUMNS * self.COLUMN_SIZE
self._data_sources = map(DisplayDataSource, ('',) * num_data_sources)
self._last_loaded_item = None
self._default_item_formatter = DefaultItemFormatter()
self._list_components = self.register_components(*[ ListComponent() for _ in xrange(self.NUM_COLUMNS) ])
for i, component in enumerate(self._list_components):
component.do_trigger_action = lambda item: self._do_load_item(item)
component.last_action_item = lambda : self._last_loaded_item
component.item_formatter = partial(self._item_formatter, i)
self._select_buttons = []
self._state_buttons = []
self._encoder_controls = []
self._enter_button = None
self._exit_button = None
self._shift_button = None
self._on_list_item_action.replace_subjects(self._list_components)
self._on_hotswap_target_changed.subject = self._browser
self._on_filter_type_changed.subject = self._browser
self._on_browser_full_refresh.subject = self._browser
self._scroll_offset = 0
self._max_scroll_offset = 0
self._max_hierarchy = 0
self._last_filter_type = None
self._skip_next_preselection = False
self._browser_model_dirty = True
self._on_content_lists_changed()
def set_display_line1(self, display):
self.set_display_line_with_index(display, 0)
def set_display_line2(self, display):
self.set_display_line_with_index(display, 1)
def set_display_line3(self, display):
self.set_display_line_with_index(display, 2)
def set_display_line4(self, display):
self.set_display_line_with_index(display, 3)
def set_enter_button(self, button):
self._enter_button = button
self._on_enter_value.subject = button
self._update_navigation_button_state()
def set_exit_button(self, button):
self._exit_button = button
self._on_exit_value.subject = button
self._update_navigation_button_state()
def set_display_line_with_index(self, display, index):
if display:
sources = self._data_sources[index::self.COLUMN_SIZE]
display.set_data_sources(sources)
def set_select_buttons(self, buttons):
for button in buttons or []:
if button:
button.reset()
self._on_select_matrix_value.subject = buttons or None
self._select_buttons = buttons
buttons = buttons or (None, None, None, None, None, None, None, None)
for component, button in izip(self._list_components, buttons[1::2]):
self._set_button_if_enabled(component, 'action_button', button)
for component, button in izip(self._list_components, buttons[::2]):
if self._shift_button and self._shift_button.is_pressed():
self._set_button_if_enabled(component, 'prev_page_button', button)
self._set_button_if_enabled(component, 'select_prev_button', None)
else:
self._set_button_if_enabled(component, 'prev_page_button', None)
self._set_button_if_enabled(component, 'select_prev_button', button)
def set_state_buttons(self, buttons):
for button in buttons or []:
if button:
button.reset()
self._on_state_matrix_value.subject = buttons or None
self._state_buttons = buttons
buttons = buttons or (None, None, None, None, None, None, None, None)
for component, button in izip(self._list_components, buttons[::2]):
if self._shift_button and self._shift_button.is_pressed():
self._set_button_if_enabled(component, 'next_page_button', button)
self._set_button_if_enabled(component, 'select_next_button', None)
else:
self._set_button_if_enabled(component, 'next_page_button', None)
self._set_button_if_enabled(component, 'select_next_button', button)
for button in buttons[1::2]:
if button and self.is_enabled():
button.set_light('DefaultButton.Disabled')
def set_shift_button(self, button):
self._shift_button = button
self._on_shift_button.subject = button
@subject_slot('value')
def _on_shift_button(self, value):
self.set_select_buttons(self._select_buttons)
self.set_state_buttons(self._state_buttons)
def _set_button_if_enabled(self, component, name, button):
setter = getattr(component, 'set_' + name)
if component.is_enabled(explicit=True):
setter(button)
else:
setter(None)
if button and self.is_enabled():
button.set_light('DefaultButton.Disabled')
def set_encoder_controls(self, encoder_controls):
if encoder_controls:
num_active_lists = len(self._browser_model.content_lists) - self._scroll_offset
num_assignable_lists = min(num_active_lists, len(encoder_controls) / 2)
index = 0
for component in self._list_components[:num_assignable_lists - 1]:
component.set_encoder_controls(encoder_controls[index:index + 2])
index += 2
self._list_components[num_assignable_lists - 1].set_encoder_controls(encoder_controls[index:])
else:
for component in self._list_components:
component.set_encoder_controls([])
self._encoder_controls = encoder_controls
def update(self):
if self.is_enabled():
self.set_state_buttons(self._state_buttons)
self.set_select_buttons(self._select_buttons)
self._update_browser_model()
self._update_navigation_button_state()
def reset_load_memory(self):
self._update_load_memory(None)
def _do_load_item(self, item):
self.do_load_item(item)
self._update_load_memory(item)
self._skip_next_preselection = True
def _update_load_memory(self, item):
self._last_loaded_item = item
for component in self._list_components:
component.update()
def do_load_item(self, item):
item.action()
self.notify_load_item(item.content)
def back_to_top(self):
self._set_scroll_offset(0)
def _set_scroll_offset(self, offset):
self._scroll_offset = offset
self._on_content_lists_changed()
scrollable_list = self._list_components[-1].scrollable_list
if scrollable_list:
scrollable_list.request_notify_item_activated()
def _update_navigation_button_state(self):
if self._exit_button:
self._exit_button.set_light(self._scroll_offset > 0)
if self._enter_button:
self._enter_button.set_light(self._scroll_offset < self._max_scroll_offset)
def _shorten_item_name(self, shortening_limit, list_index, item_name):
"""
Creates the name of an item shortened by removing words from the parents name
"""
def is_short_enough(item_name):
return len(item_name) <= 9
content_lists = self._browser_model.content_lists
parent_lists = reversed(content_lists[max(0, list_index - 3):list_index])
for content_list in parent_lists:
if is_short_enough(item_name):
break
parent_name = unicode(content_list.selected_item)
stems = split_stem(parent_name)
for stem in stems:
short_name = make_stem_cleaner(stem)(item_name)
short_name = full_strip(short_name)
item_name = short_name if len(short_name) > 4 else item_name
if is_short_enough(item_name):
break
return item_name[:-1] if len(item_name) >= shortening_limit and item_name[-1] == consts.CHAR_ELLIPSIS else item_name
def _item_formatter(self, depth, index, item, action_in_progress):
display_string = ''
separator_length = len(self._data_sources[self.COLUMN_SIZE * depth].separator)
shortening_limit = 16 - separator_length
if item:
item_name = 'Loading...' if action_in_progress else self._shorten_item_name(shortening_limit, depth + self._scroll_offset, unicode(item))
display_string = consts.CHAR_SELECT if item and item.is_selected else ' '
display_string += item_name
if depth == len(self._list_components) - 1 and item.is_selected and self._scroll_offset < self._max_hierarchy:
display_string = string.ljust(display_string, consts.DISPLAY_LENGTH / 4 - 1)
shortening_limit += 1
display_string = display_string[:shortening_limit] + consts.CHAR_ARROW_RIGHT
if depth == 0 and self._scroll_offset > 0:
prefix = consts.CHAR_ARROW_LEFT if index == 0 else ' '
display_string = prefix + display_string
return display_string[:shortening_limit + 1]
@subject_slot('value')
def _on_enter_value(self, value):
if value:
self._set_scroll_offset(min(self._max_scroll_offset, self._scroll_offset + 1))
@subject_slot('value')
def _on_exit_value(self, value):
if value:
self._set_scroll_offset(max(0, self._scroll_offset - 1))
@subject_slot('hotswap_target')
def _on_hotswap_target_changed(self):
self._update_browser_model()
@subject_slot('filter_type')
def _on_filter_type_changed(self):
self._update_browser_model()
@subject_slot('full_refresh')
def _on_browser_full_refresh(self):
self._browser_model_dirty = True
def _update_browser_model(self):
if self.is_enabled():
self._do_update_browser_model()
def _do_update_browser_model(self):
filter_type = filter_type_for_browser(self._browser)
if filter_type != self._last_filter_type:
self._last_filter_type = filter_type
new_model = make_browser_model(self._browser, filter_type)
if self._browser_model and self._browser_model.can_be_exchanged(new_model) and new_model.can_be_exchanged(self._browser_model):
self._browser_model.exchange_model(new_model)
new_model.disconnect()
else:
self.disconnect_disconnectable(self._browser_model)
self._browser_model = self.register_slot_manager(new_model)
self._on_content_lists_changed.subject = self._browser_model
for contents in self._browser_model.content_lists:
contents.selected_item_index = 0
self._browser_model.update_content()
elif self._browser_model_dirty:
self._browser_model.update_content()
elif not self._skip_next_preselection:
self._browser_model.update_selection()
self._skip_next_preselection = False
self._browser_model_dirty = False
@subject_slot_group('item_action')
def _on_list_item_action(self, item, list):
self.notify_load_item(item.content)
@subject_slot('content_lists')
def _on_content_lists_changed(self):
components = self._list_components
contents = self._browser_model.content_lists[self._scroll_offset:]
messages = self._browser_model.empty_list_messages
scroll_depth = len(self._browser_model.content_lists) - len(self._list_components)
self._max_scroll_offset = max(0, scroll_depth + 2)
self._max_hierarchy = max(0, scroll_depth)
for component, content, message in map(None, components, contents, messages):
if component != None:
component.scrollable_list = content
component.empty_list_message = message
active_lists = len(contents)
num_head = clamp(active_lists - 1, 0, self.NUM_COLUMNS - 1)
head = components[:num_head]
last = components[num_head:]
def set_data_sources_with_separator(component, sources, separator):
for source in sources:
source.separator = separator
component.set_data_sources(sources)
component.set_enabled(True)
for idx, component in enumerate(head):
offset = idx * self.COLUMN_SIZE
sources = self._data_sources[offset:offset + self.COLUMN_SIZE]
set_data_sources_with_separator(component, sources, '|')
if last:
offset = num_head * self.COLUMN_SIZE
scrollable_list = last[0].scrollable_list
if scrollable_list and find_if(lambda item: item.content.is_folder, scrollable_list.items):
sources = self._data_sources[offset:offset + self.COLUMN_SIZE]
map(DisplayDataSource.clear, self._data_sources[offset + self.COLUMN_SIZE:])
else:
sources = self._data_sources[offset:]
set_data_sources_with_separator(last[0], sources, '')
for component in last[1:]:
component.set_enabled(False)
self.set_select_buttons(self._select_buttons)
self.set_state_buttons(self._state_buttons)
self.set_encoder_controls(self._encoder_controls)
self._update_navigation_button_state()
@subject_slot('value')
def _on_select_matrix_value(self, value, *_):
pass
@subject_slot('value')
def _on_state_matrix_value(self, value, *_):
pass
@subject_slot('value')
def _on_encoder_matrix_value(self, value, *_):
pass