Debian Codegraph @

xlgui/panel/collection.py

raw
1 # Copyright (C) 2008-2010 Adam Olsen
2 #
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2, or (at your option)
6 # any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 #
17 #
18 # The developers of the Exaile media player hereby grant permission
19 # for non-GPL compatible GStreamer and Exaile plugins to be used and
20 # distributed together with GStreamer and Exaile. This permission is
21 # above and beyond the permissions granted by the GPL license by which
22 # Exaile is covered. If you modify this code, you may extend this
23 # exception to your version of the code, but you are not obligated to
24 # do so. If you do not wish to do so, delete this exception statement
25 # from your version.
26
27 from gi.repository import Gdk
28 from gi.repository import GdkPixbuf
29 from gi.repository import GLib
30 from gi.repository import GObject
31 from gi.repository import Gtk
32 import itertools
33 import logging
34
35 from xl.nls import gettext as _
36 from xl import common, event, formatter, settings, trax
37 import xlgui
38 from xlgui import guiutil, icons, panel
39 from xlgui.panel import menus
40 from xlgui.widgets import menu
41 from xlgui.widgets.common import DragTreeView
42
43 logger = logging.getLogger(__name__)
44
45 # TODO: come up with a more customizable way to handle this
46 SEARCH_TAGS = ("artist", "albumartist", "album", "title")
47
48
49 def first_meaningful_char(s):
50 # Keep explicit str() conversion in case we ever end up receiving
51 # a non-string sort tag (e.g. an int for track number)
52 for c in str(s):
53 if c.isdigit():
54 return '0'
55 elif c.isalpha():
56 return c
57 else:
58 return '_'
59
60
61 class Order:
62 """
63 An Order represents a structure for arranging Tracks into the
64 Collection tree.
65
66 It is based on a list of levels, which each take the form (("sort1",
67 "sort2"), "$displaytag - $displaytag", ("search1", "search2")) wherin
68 the first entry is a tuple of tags to use for sorting, the second a
69 format string for xl.formatter, and the third a tuple of tags to use
70 for searching.
71
72 When passed in the parameters, a level can also be a single string
73 instead of a tuple, and it will be treated equivalently to (("foo",),
74 "$foo", ("foo",)) for some string "foo".
75 """
76
77 def __init__(self, name, levels, use_compilations=True):
78 self.__name = name
79 self.__levels = [self.__parse_level(l) for l in levels]
80 self.__formatters = [formatter.TrackFormatter(l[1]) for l in self.__levels]
81 self.__use_compilations = use_compilations
82
83 @staticmethod
84 def __parse_level(val):
85 if isinstance(val, str):
86 val = ((val,), "$%s" % val, (val,))
87 return tuple(val)
88
89 @property
90 def name(self):
91 return self.__name
92
93 @property
94 def use_compilations(self):
95 return self.__use_compilations
96
97 def get_levels(self):
98 return self.__levels[:]
99
100 def __len__(self):
101 return len(self.__levels)
102
103 def __eq__(self, other):
104 return self.__levels == other.get_levels()
105
106 def all_sort_tags(self):
107 return set(itertools.chain(*[l[0] for l in self.__levels]))
108
109 def get_sort_tags(self, level):
110 return list(self.__levels[level][0])
111
112 def all_search_tags(self):
113 return list(itertools.chain(*[l[2] for l in self.__levels]))
114
115 def get_search_tags(self, level):
116 return list(set(self.__levels[level][2]))
117
118 def format_track(self, level, track):
119 return self.__formatters[level].format(track)
120
121
122 DEFAULT_ORDERS = [
123 # fmt: off
124 Order(_("Artist"),
125 ("artist", "album",
126 (("discnumber", "tracknumber", "title"), "$title", ("title",)))),
127 Order(_("Album Artist"),
128 ("albumartist", "album",
129 (("discnumber", "tracknumber", "title"), "$title", ("title",)))),
130 Order(_("Album"),
131 ("album",
132 (("discnumber", "tracknumber", "title"), "$title", ("title",)))),
133 Order(_("Genre - Artist"),
134 ('genre', 'artist', 'album',
135 (("discnumber", "tracknumber", "title"), "$title", ("title",)))),
136 Order(_("Genre - Album Artist"),
137 ('genre', 'albumartist', 'album',
138 (("discnumber", "tracknumber", "title"), "$title", ("title",)))),
139 Order(_("Genre - Album"),
140 ('genre', 'album', 'artist',
141 (("discnumber", "tracknumber", "title"), "$title", ("title",)))),
142 Order(_("Date - Artist"),
143 ('date', 'artist', 'album',
144 (("discnumber", "tracknumber", "title"), "$title", ("title",)))),
145 Order(_("Date - Album Artist"),
146 ('date', 'albumartist', 'album',
147 (("discnumber", "tracknumber", "title"), "$title", ("title",)))),
148 Order(_("Date - Album"),
149 ('date', 'album', 'artist',
150 (("discnumber", "tracknumber", "title"), "$title", ("title",)))),
151 Order(_("Artist - (Date - Album)"),
152 ('artist',
153 (('date', 'album'), "$date - $album", ('date', 'album')),
154 (("discnumber", "tracknumber", "title"), "$title", ("title",)))),
155 Order(_("Album Artist - (Date - Album)"),
156 ('albumartist',
157 (('date', 'album'), "$date - $album", ('date', 'album')),
158 (("discnumber", "tracknumber", "title"), "$title", ("title",)))),
159 # fmt: on
160 ]
161
162
163 class CollectionPanel(panel.Panel):
164 """
165 The collection panel
166 """
167
168 __gsignals__ = {
169 'append-items': (GObject.SignalFlags.RUN_LAST, None, (object, bool)),
170 'replace-items': (GObject.SignalFlags.RUN_LAST, None, (object,)),
171 'queue-items': (GObject.SignalFlags.RUN_LAST, None, (object,)),
172 'collection-tree-loaded': (GObject.SignalFlags.RUN_LAST, None, ()),
173 }
174
175 ui_info = ('collection.ui', 'CollectionPanel')
176
177 def __init__(
178 self,
179 parent,
180 collection,
181 name=None,
182 _show_collection_empty_message=False,
183 label=_('Collection'),
184 ):
185 """
186 Initializes the collection panel
187
188 @param parent: the parent dialog
189 @param collection: the xl.collection.Collection instance
190 @param name: an optional name for this panel
191 """
192 panel.Panel.__init__(self, parent, name, label)
193
194 self._show_collection_empty_message = _show_collection_empty_message
195 self.collection = collection
196 self.use_alphabet = settings.get_option('gui/use_alphabet', True)
197 self.panel_stack = self.builder.get_object('CollectionPanel')
198 self.panel_content = self.builder.get_object('CollectionPanelContent')
199 self.panel_empty = self.builder.get_object('CollectionPanelEmpty')
200 self.choice = self.builder.get_object('collection_combo_box')
201 self._search_num = 0
202 self._refresh_id = 0
203 self.start_count = 0
204 self.keyword = ''
205 self.orders = DEFAULT_ORDERS[:]
206 self._setup_tree()
207 self._setup_widgets()
208 self._check_collection_empty()
209 self._setup_images()
210 self._connect_events()
211 self.order = None
212 self.tracks = []
213 self.sorted_tracks = []
214
215 event.add_ui_callback(
216 self._check_collection_empty, 'libraries_modified', collection
217 )
218
219 self.menu = menus.CollectionContextMenu(self)
220
221 self.load_tree()
222
223 def _setup_widgets(self):
224 """
225 Sets up the various widgets to be used in this panel
226 """
227 self.choice = self.builder.get_object('collection_combo_box')
228 self.choicemodel = self.builder.get_object('collection_combo_model')
229 self.repopulate_choices()
230
231 self.filter = guiutil.SearchEntry(
232 self.builder.get_object('collection_search_entry')
233 )
234
235 def repopulate_choices(self):
236 self.choice.set_model(None)
237 self.choicemodel.clear()
238 for order in self.orders:
239 self.choicemodel.append([order.name])
240 self.choice.set_model(self.choicemodel)
241 # FIXME: use something other than index here, since index
242 # doesn't deal well with dynamic lists...
243 active = settings.get_option('gui/collection_active_view', 0)
244 if len(self.orders) - 1 < active:
245 active = len(self.orders) - 1
246 if active < 0:
247 active = 0
248 self.choice.set_active(active)
249
250 def _check_collection_empty(self, *e):
251 if self._show_collection_empty_message and not self.collection.libraries:
252 # should show empty panel
253 if self.panel_stack.get_visible_child() == self.panel_content:
254 self.panel_stack.set_visible_child(self.panel_empty)
255 else:
256 # should show content panel
257 if self.panel_stack.get_visible_child() == self.panel_empty:
258 self.panel_stack.set_visible_child(self.panel_content)
259
260 def _connect_events(self):
261 """
262 Uses signal_autoconnect to connect the various events
263 """
264 self.builder.connect_signals(
265 {
266 'on_collection_combo_box_changed': lambda *e: self.load_tree(),
267 'on_refresh_button_press_event': self.on_refresh_button_press_event,
268 'on_refresh_button_key_press_event': self.on_refresh_button_key_press_event,
269 'on_collection_search_entry_activate': self.on_collection_search_entry_activate,
270 'on_add_music_button_clicked': self.on_add_music_button_clicked,
271 }
272 )
273 self.tree.connect('key-release-event', self.on_key_released)
274 event.add_ui_callback(self.refresh_tags_in_tree, 'track_tags_changed')
275 event.add_ui_callback(
276 self.refresh_tracks_in_tree, 'tracks_added', self.collection
277 )
278 event.add_ui_callback(
279 self.refresh_tracks_in_tree, 'tracks_removed', self.collection
280 )
281
282 def on_refresh_button_press_event(self, button, event):
283 """
284 Called on mouse activation of the refresh button
285 """
286 if event.triggers_context_menu():
287 m = menu.Menu(None)
288 m.attach_to_widget(button)
289 m.add_simple(
290 _('Rescan Collection'),
291 xlgui.get_controller().on_rescan_collection,
292 Gtk.STOCK_REFRESH,
293 )
294 m.popup(event)
295 return
296
297 if event.get_state() & Gdk.ModifierType.SHIFT_MASK:
298 xlgui.get_controller().on_rescan_collection(None)
299 else:
300 self.load_tree()
301
302 def on_refresh_button_key_press_event(self, widget, event):
303 """
304 Called on key presses on the refresh button
305 """
306 if event.keyval != Gdk.KEY_Return:
307 return False
308
309 if event.get_state() & Gdk.ModifierType.SHIFT_MASK:
310 xlgui.get_controller().on_rescan_collection(None)
311 else:
312 self.load_tree()
313
314 def on_key_released(self, widget, event):
315 """
316 Called when a key is released in the tree
317 """
318 if event.keyval == Gdk.KEY_Menu:
319 Gtk.Menu.popup(self.menu, None, None, None, None, 0, event.time)
320 return True
321
322 if event.keyval == Gdk.KEY_Left:
323 (mods, paths) = self.tree.get_selection().get_selected_rows()
324 for path in paths:
325 self.tree.collapse_row(path)
326 return True
327
328 if event.keyval == Gdk.KEY_Right:
329 (mods, paths) = self.tree.get_selection().get_selected_rows()
330 for path in paths:
331 self.tree.expand_row(path, False)
332 return True
333
334 if event.keyval == Gdk.KEY_Return:
335 self.append_to_playlist()
336 return True
337 return False
338
339 def on_collection_search_entry_activate(self, entry):
340 """
341 Searches tracks and reloads the tree
342 """
343 self.keyword = entry.get_text()
344 self.start_count += 1
345 self.load_tree()
346
347 def on_add_music_button_clicked(self, button):
348 xlgui.get_controller().collection_manager()
349
350 def _setup_images(self):
351 """
352 Sets up the various images that will be used in the tree
353 """
354 self.artist_image = icons.MANAGER.pixbuf_from_icon_name(
355 'artist', Gtk.IconSize.SMALL_TOOLBAR
356 )
357 self.albumartist_image = icons.MANAGER.pixbuf_from_icon_name(
358 'artist', Gtk.IconSize.SMALL_TOOLBAR
359 )
360 self.date_image = icons.MANAGER.pixbuf_from_icon_name(
361 'office-calendar', Gtk.IconSize.SMALL_TOOLBAR
362 )
363 self.album_image = icons.MANAGER.pixbuf_from_icon_name(
364 'image-x-generic', Gtk.IconSize.SMALL_TOOLBAR
365 )
366 self.title_image = icons.MANAGER.pixbuf_from_icon_name(
367 'audio-x-generic', Gtk.IconSize.SMALL_TOOLBAR
368 )
369 self.genre_image = icons.MANAGER.pixbuf_from_icon_name(
370 'genre', Gtk.IconSize.SMALL_TOOLBAR
371 )
372
373 def drag_data_received(self, *e):
374 """
375 stub
376 """
377 pass
378
379 def drag_data_delete(self, *e):
380 """
381 stub
382 """
383 pass
384
385 def drag_get_data(self, treeview, context, selection, target_id, etime):
386 """
387 Called when a drag source wants data for this drag operation
388 """
389 tracks = treeview.get_selected_tracks()
390
391 for track in tracks:
392 DragTreeView.dragged_data[track.get_loc_for_io()] = track
393
394 uris = trax.util.get_uris_from_tracks(tracks)
395 selection.set_uris(uris)
396
397 def _setup_tree(self):
398 """
399 Sets up the tree widget
400 """
401 self.tree = CollectionDragTreeView(self)
402 self.tree.set_headers_visible(False)
403 scroll = Gtk.ScrolledWindow()
404 scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
405 scroll.add(self.tree)
406 scroll.set_shadow_type(Gtk.ShadowType.IN)
407 self.panel_content.pack_start(scroll, True, True, 0)
408 self.panel_content.show_all()
409
410 selection = self.tree.get_selection()
411 selection.set_mode(Gtk.SelectionMode.MULTIPLE)
412 pb = Gtk.CellRendererPixbuf()
413 cell = Gtk.CellRendererText()
414 col = Gtk.TreeViewColumn('Text')
415 col.pack_start(pb, False)
416 col.pack_start(cell, True)
417 col.set_attributes(pb, pixbuf=0)
418 col.set_attributes(cell, text=1)
419 self.tree.append_column(col)
420
421 if settings.get_option('gui/ellipsize_text_in_panels', False):
422 from gi.repository import Pango
423
424 cell.set_property('ellipsize-set', True)
425 cell.set_property('ellipsize', Pango.EllipsizeMode.END)
426
427 self.tree.set_row_separator_func(
428 (lambda m, i, d: m.get_value(i, 1) is None), None
429 )
430
431 self.model = Gtk.TreeStore(GdkPixbuf.Pixbuf, str, object)
432
433 self.tree.connect("row-expanded", self.on_expanded)
434
435 def _find_tracks(self, iter):
436 """
437 finds tracks matching a given iter.
438 """
439 self.load_subtree(iter)
440 search = self.get_node_search_terms(iter)
441 matcher = trax.TracksMatcher(search)
442 srtrs = trax.search_tracks(self.tracks, [matcher])
443 return [x.track for x in srtrs]
444
445 def append_to_playlist(self, item=None, event=None, replace=False):
446 """
447 Adds items to the current playlist
448 """
449 if replace:
450 self.emit('replace-items', self.tree.get_selected_tracks())
451 else:
452 self.emit('append-items', self.tree.get_selected_tracks(), True)
453
454 def button_press(self, widget, event):
455 """
456 Called when the user clicks on the tree
457 """
458 # selection = self.tree.get_selection()
459 (x, y) = [int(v) for v in event.get_coords()]
460 # path = self.tree.get_path_at_pos(x, y)
461 if event.type == Gdk.EventType._2BUTTON_PRESS:
462 replace = settings.get_option('playlist/replace_content', False)
463 self.append_to_playlist(replace=replace)
464 return False
465 elif event.button == Gdk.BUTTON_MIDDLE:
466 self.append_to_playlist(replace=True)
467 return False
468
469 def on_expanded(self, tree, iter, path):
470 """
471 Called when a user expands a tree item.
472
473 Loads the various nodes that belong under this node.
474 """
475 self.load_subtree(iter)
476
477 def get_node_search_terms(self, node):
478 """
479 Finds all the related search terms for a particular node
480 @param node: the node you wish to create search terms
481 """
482 if not node:
483 return ""
484
485 queries = []
486 while node:
487 queries.append(self.model.get_value(node, 2))
488 node = self.model.iter_parent(node)
489
490 return " ".join(queries)
491
492 def refresh_tags_in_tree(self, type, track, tags):
493 if (
494 settings.get_option('gui/sync_on_tag_change', True)
495 and bool(tags & self.order.all_sort_tags())
496 and self.collection.loc_is_member(track.get_loc_for_io())
497 ):
498 self._refresh_tags_in_tree()
499
500 def refresh_tracks_in_tree(self, type, obj, loc):
501 self._refresh_tags_in_tree()
502
503 @common.glib_wait(500)
504 def _refresh_tags_in_tree(self):
505 """
506 Callback for when tags have changed and the tree
507 needs reloading.
508 """
509 # Trying to reload while we're rescanning is really inefficient,
510 # so we delay it until we're done scanning.
511 if self.collection._scanning:
512 return True
513 self.resort_tracks()
514 self.load_tree()
515 return False
516
517 def resort_tracks(self):
518 # import time
519 # print("sorting...", time.clock())
520 self.sorted_tracks = trax.sort_tracks(
521 self.order.get_sort_tags(0), self.collection.get_tracks()
522 )
523 # print("sorted.", time.clock())
524
525 def load_tree(self):
526 """
527 Loads the Gtk.TreeView for this collection panel.
528
529 Loads tracks based on the current keyword, or all the tracks in
530 the collection associated with this panel
531 """
532 logger.debug("Reloading collection tree")
533 self.current_start_count = self.start_count
534 self.tree.set_model(None)
535 self.model.clear()
536
537 self.root = None
538 oldorder = self.order
539 self.order = self.orders[self.choice.get_active()]
540
541 if not oldorder or oldorder != self.order:
542 self.resort_tracks()
543
544 # save the active view setting
545 settings.set_option('gui/collection_active_view', self.choice.get_active())
546
547 keyword = self.keyword.strip()
548 tags = list(SEARCH_TAGS)
549 tags += self.order.all_search_tags()
550 tags = list(set(tags)) # uniquify list to speed up search
551
552 self.tracks = list(
553 trax.search_tracks_from_string(
554 self.sorted_tracks, keyword, case_sensitive=False, keyword_tags=tags
555 )
556 )
557
558 self.load_subtree(None)
559
560 self.tree.set_model(self.model)
561
562 self.emit('collection-tree-loaded')
563
564 def _expand_node_by_name(self, search_num, parent, name, rest=None):
565 """
566 Recursive function to expand all nodes in a hierarchical list of
567 names.
568
569 @param search_num: the current search number
570 @param parent: the parent node
571 @param name: the name of the node to expand
572 @param rest: the list of the nodes to expand after this one
573 """
574 iter = self.model.iter_children(parent)
575
576 while iter:
577 if search_num != self._search_num:
578 return
579 value = self.model.get_value(iter, 1)
580 if not value:
581 value = self.model.get_value(iter, 2)
582
583 if value == name:
584 self.tree.expand_row(self.model.get_path(iter), False)
585 parent = iter
586 break
587
588 iter = self.model.iter_next(iter)
589
590 if rest:
591 item = rest.pop(0)
592 GLib.idle_add(self._expand_node_by_name, search_num, parent, item, rest)
593
594 def load_subtree(self, parent):
595 """
596 Loads all the sub nodes for a specified node
597
598 @param node: the node
599 """
600 previously_loaded = False # was the subtree already loaded
601 iter_sep = None
602 if parent is None:
603 depth = 0
604 else:
605 if (
606 self.model.iter_n_children(parent) != 1
607 or self.model.get_value(self.model.iter_children(parent), 1) is not None
608 ):
609 previously_loaded = True
610 iter_sep = self.model.iter_children(parent)
611 depth = self.model.iter_depth(parent) + 1
612 if previously_loaded:
613 return
614
615 search = self.get_node_search_terms(parent)
616
617 try:
618 tags = self.order.get_sort_tags(depth)
619 matchers = [trax.TracksMatcher(search)]
620 srtrs = trax.search_tracks(self.tracks, matchers)
621 # sort only if we are not on top level, because tracks are
622 # already sorted by fist order
623 if depth > 0:
624 srtrs = trax.sort_result_tracks(tags, srtrs)
625 except IndexError:
626 return # at the bottom of the tree
627 try:
628 image = getattr(self, "%s_image" % tags[-1])
629 except Exception:
630 image = None
631 bottom = False
632 if depth == len(self.order) - 1:
633 bottom = True
634
635 display_counts = settings.get_option('gui/display_track_counts', True)
636 draw_seps = settings.get_option('gui/draw_separators', True)
637 last_char = ''
638 last_val = ''
639 last_dval = ''
640 last_matchq = ''
641 count = 0
642 first = True
643 path = None
644 expanded = False
645 to_expand = []
646
647 for srtr in srtrs:
648 # The value returned by get_tag_sort() may be of other
649 # typa than str (e.g., an int for track number), hence
650 # explicit conversion via str() is necessary.
651 stagvals = [str(srtr.track.get_tag_sort(x)) for x in tags]
652 stagval = " ".join(stagvals)
653 if last_val != stagval or bottom:
654 tagval = self.order.format_track(depth, srtr.track)
655 match_query = " ".join(
656 [srtr.track.get_tag_search(t, format=True) for t in tags]
657 )
658 if bottom:
659 match_query += " " + srtr.track.get_tag_search("__loc", format=True)
660
661 # Different *sort tags can cause stagval to not match
662 # but the below code will produce identical entries in
663 # the displayed tree. This condition checks to ensure
664 # that new entries are added if and only if they will
665 # display different results, avoiding that problem.
666 if match_query != last_matchq or tagval != last_dval or bottom:
667 if display_counts and path and not bottom:
668 iter = self.model.get_iter(path)
669 val = self.model.get_value(iter, 1)
670 val = "%s (%s)" % (val, count)
671 self.model.set_value(iter, 1, val)
672 count = 0
673
674 last_val = stagval
675 last_dval = tagval
676 if depth == 0 and draw_seps:
677 val = srtr.track.get_tag_sort(tags[0])
678 char = first_meaningful_char(val)
679 if first:
680 last_char = char
681 else:
682 if char != last_char and last_char != '':
683 self.model.append(parent, [None, None, None])
684 last_char = char
685 first = False
686
687 last_matchq = match_query
688 iter = self.model.append(parent, [image, tagval, match_query])
689 path = self.model.get_path(iter)
690 expanded = False
691 if not bottom:
692 self.model.append(iter, [None, None, None])
693 count += 1
694 if not expanded:
695 alltags = []
696 for i in range(depth + 1, len(self.order)):
697 alltags.extend(self.order.get_sort_tags(i))
698 for t in alltags:
699 if t in srtr.on_tags:
700 # keep original path intact for following block
701 newpath = path
702 if depth > 0:
703 # for some reason, nested iters are always
704 # off by one in the terminal entry.
705 newpath = Gtk.TreePath.new_from_indices(
706 newpath[:-1] + [newpath[-1] - 1]
707 )
708 to_expand.append(newpath)
709 expanded = True
710
711 if display_counts and path and not bottom:
712 iter = self.model.get_iter(path)
713 val = self.model.get_value(iter, 1)
714 val = "%s (%s)" % (val, count)
715 self.model.set_value(iter, 1, val)
716 count = 0
717
718 if (
719 settings.get_option("gui/expand_enabled", True)
720 and len(to_expand) < settings.get_option("gui/expand_maximum_results", 100)
721 and len(self.keyword.strip())
722 >= settings.get_option("gui/expand_minimum_term_length", 2)
723 ):
724 for row in to_expand:
725 GLib.idle_add(self.tree.expand_row, row, False)
726
727 if iter_sep is not None:
728 self.model.remove(iter_sep)
729
730
731 class CollectionDragTreeView(DragTreeView):
732 """
733 Custom DragTreeView to retrieve data
734 from collection tracks
735 """
736
737 def __init__(self, container, receive=False, source=True):
738 """
739 :param container: The container to place the TreeView into
740 :param receive: True if the TreeView should receive drag events
741 :param source: True if the TreeView should send drag events
742 """
743 DragTreeView.__init__(self, container, receive, source)
744
745 self.set_has_tooltip(True)
746 self.connect('query-tooltip', self.on_query_tooltip)
747
748 def get_selection_empty(self):
749 '''Returns True if there are no selected items'''
750 return self.get_selection().count_selected_rows() == 0
751
752 def get_selected_tracks(self):
753 """
754 Returns the currently selected tracks
755 """
756 model, paths = self.get_selection().get_selected_rows()
757
758 if len(paths) == 0:
759 return []
760
761 tracks = set()
762 for path in paths:
763 iter = model.get_iter(path)
764 newset = self.container._find_tracks(iter)
765 tracks.update(newset)
766
767 tracks = list(tracks)
768
769 return trax.sort_tracks(common.BASE_SORT_TAGS, tracks)
770
771 def on_query_tooltip(self, widget, x, y, keyboard_mode, tooltip):
772 """
773 Sets up a basic tooltip
774 Required to have "&" in tooltips working
775 """
776 if not widget.get_tooltip_context(x, y, keyboard_mode):
777 return False
778
779 result = widget.get_path_at_pos(x, y)
780 if not result:
781 return False
782
783 path = result[0]
784
785 model = widget.get_model()
786 tooltip.set_text(model[path][1]) # 1: title
787 widget.set_tooltip_row(tooltip, path)
788
789 return True
790
791 def get_tracks_for_path(self, path):
792 """
793 Get tracks for a path from model (expand item)
794 :param path: Gtk.TreePath
795 :return: list of tracks [xl.trax.Track]
796 """
797 it = self.get_model().get_iter(path)
798 search = self.container.get_node_search_terms(it)
799 matcher = trax.TracksMatcher(search)
800 for i in trax.search_tracks(self.container.tracks, [matcher]):
801 yield i.track
802
803
804 # vim: et sts=4 sw=4