Debian Codegraph @

xlgui/widgets/playlist_columns.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
28 from gi.repository import GLib
29 from gi.repository import Gtk
30 from gi.repository import Pango
31
32 import logging
33 import time
34
35 from xl import common, event, player, settings, providers
36 from xl.common import classproperty
37 from xl.formatter import TrackFormatter
38 from xl.nls import gettext as _
39 from xlgui import icons
40 from xlgui.widgets import dialogs, rating, menu
41
42 logger = logging.getLogger(__name__)
43
44 DEFAULT_COLUMNS = ['tracknumber', 'title', 'album', 'artist', '__length']
45
46
47 class Column(Gtk.TreeViewColumn):
48 name = ''
49 display = ''
50 menu_title = classproperty(lambda c: c.display)
51 renderer = Gtk.CellRendererText
52 formatter = classproperty(lambda c: TrackFormatter('$%s' % c.name))
53 size = 10 # default size
54 autoexpand = False # whether to expand to fit space in Autosize mode
55 datatype = str
56 dataproperty = 'text'
57 cellproperties = {}
58
59 def __init__(self, container, player, font, size_ratio):
60 if self.__class__ == Column:
61 raise NotImplementedError(
62 "Can't instantiate abstract class %r" % self.__class__
63 )
64
65 self._size_ratio = size_ratio
66 self.container = container
67 self.player = player
68 self.settings_width_name = "gui/col_width_%s" % self.name
69 self.cellrenderer = self.renderer()
70 self.destroyed = False
71
72 super().__init__(title=self.display)
73 self.props.min_width = 3
74
75 self.pack_start(self.cellrenderer, True)
76 self.set_cell_data_func(self.cellrenderer, self.data_func)
77
78 try:
79 self.cellrenderer.set_property('font-desc', font)
80 except TypeError:
81 pass # not all cells have a font
82
83 try:
84 self.cellrenderer.set_property('ellipsize', Pango.EllipsizeMode.END)
85 except TypeError: # cellrenderer doesn't do ellipsize - eg. rating
86 pass
87
88 for name, val in self.cellproperties.items():
89 self.cellrenderer.set_property(name, val)
90
91 self.set_reorderable(True)
92 self.set_clickable(True)
93 self.set_sizing(Gtk.TreeViewColumnSizing.FIXED) # needed for fixed-height mode
94 self.set_sort_order(Gtk.SortType.DESCENDING)
95
96 # hack to allow button press events on the header to be detected
97 self.set_widget(Gtk.Label(label=self.display))
98
99 # Save the width of the column when it changes; save the notify id so
100 # we don't emit an event when we're programmatically setting the width
101 self._width_notify = self.connect('notify::width', self.on_width_changed)
102 self._setup_sizing()
103
104 event.add_ui_callback(
105 self.on_option_set, "gui_option_set", destroy_with=container
106 )
107
108 def on_option_set(self, typ, obj, data):
109 if data in ("gui/resizable_cols", self.settings_width_name):
110 self._setup_sizing()
111
112 def on_width_changed(self, column, wid):
113 # Don't call get_width in the delayed function; it can be incorrect.
114 # See https://github.com/exaile/exaile/issues/580
115 self._delayed_width_changed(self.get_width())
116
117 @common.glib_wait(100)
118 def _delayed_width_changed(self, width):
119 if not self.destroyed and width != settings.get_option(
120 self.settings_width_name, -1
121 ):
122 settings.set_option(self.settings_width_name, width)
123
124 def _setup_sizing(self):
125 with self.handler_block(self._width_notify):
126 if settings.get_option('gui/resizable_cols', False):
127 self.set_resizable(True)
128 self.set_expand(False)
129 width = settings.get_option(self.settings_width_name, self.size)
130 self.set_fixed_width(width)
131 else:
132 self.set_resizable(False)
133 if self.autoexpand:
134 self.set_expand(True)
135 self.set_fixed_width(1)
136 else:
137 self.set_expand(False)
138 self.set_fixed_width(self.size)
139
140 def set_size_ratio(self, ratio):
141 self._size_ratio = ratio
142
143 def get_size_ratio(self):
144 '''Returns how much bigger or smaller an icon should be'''
145 return self._size_ratio
146
147 def data_func(self, col, cell, model, iter, user_data):
148 # warning: this function gets called from the render function, so do as
149 # little work as possible!
150
151 cache = model.get_value(iter, 1)
152
153 text = cache.get(self.name)
154 if text is None:
155 track = model.get_value(iter, 0)
156 text = self.formatter.format(track)
157 cache[self.name] = text
158
159 cell.props.text = text
160
161 def __repr__(self):
162 return '%s(%r, %r, %r)' % (
163 self.__class__.__name__,
164 self.name,
165 self.display,
166 self.size,
167 )
168
169
170 class EditableColumn(Column):
171 renderer = Gtk.CellRendererText
172
173 def __init__(self, *args):
174 Column.__init__(self, *args)
175 self.cellrenderer.connect('edited', self.on_edited)
176 self.cellrenderer.connect('editing-started', self.on_editing_started)
177 self.cellrenderer.connect('editing-canceled', self._reset_editable)
178
179 def could_edit(self, treeview, path, event):
180 # Returns True if an edit could take place
181
182 # The 'aligned area' seems to correspond to where the text actually
183 # is rendered. If the coordinates don't overlap that, then we don't
184 # allow the edit to occur. Conveniently, this should deal with RTL
185 # issues as well (not tested)
186 cell_area = treeview.get_cell_area(path, self)
187
188 # Ensure the renderer text attribute is updated before finding
189 # it's width
190 model = treeview.get_model()
191 iter = model.get_iter(path)
192 self.data_func(self, self.cellrenderer, model, iter, None)
193
194 aa = self.cellrenderer.get_aligned_area(treeview, 0, cell_area)
195 return aa.x <= event.x <= aa.x + aa.width
196
197 def start_editing(self, treeview, path):
198 # We normally keep the cell renderer's `editable` False so it doesn't
199 # trigger editing on double-click. To actually start editing, we have
200 # to temporarily set it to True until the user finishes editing.
201 self.cellrenderer.props.editable = True
202 treeview.set_cursor_on_cell(path, self, self.cellrenderer, start_editing=True)
203
204 def _reset_editable(self, cellrenderer):
205 cellrenderer.props.editable = False
206
207 def on_edited(self, cellrenderer, path, new_text):
208 self._reset_editable(cellrenderer)
209
210 # Undo newline escaping
211 new_text = new_text.replace('\\n', '\n')
212
213 validate = getattr(self, 'validate', None)
214 if validate:
215 try:
216 new_text = validate(new_text)
217 except ValueError:
218 return
219
220 # Update the track
221 model = self.get_tree_view().get_model()
222 iter = model.get_iter(path)
223 track = model.get_value(iter, 0)
224
225 if not track.set_tag_raw(self.name, new_text):
226 return
227
228 # Invalidate/redraw the value immediately because we know
229 # it's just a single change
230 model.get_value(iter, 1).clear()
231 model.row_changed(path, iter)
232
233 if not track.write_tags():
234 dialogs.error(
235 None,
236 "Error writing tags to %s"
237 % GLib.markup_escape_text(track.get_loc_for_io()),
238 )
239
240 def on_editing_started(self, cellrenderer, editable, path):
241 # Retrieve text in original form
242 model = self.get_tree_view().get_model()
243
244 iter = model.get_iter(path)
245 track = model.get_value(iter, 0)
246
247 text = getattr(self, 'edit_formatter', self.formatter).format(track)
248
249 # Escape newlines
250 text = text.replace('\n', '\\n')
251
252 # Set text
253 editable.set_text(text)
254
255 if hasattr(self, 'validate'):
256 editable.connect('changed', self.on_editing_changed)
257
258 def on_editing_changed(self, w):
259 try:
260 self.validate(w.get_text())
261 except ValueError:
262 w.get_style_context().add_class('warning')
263 else:
264 w.get_style_context().remove_class('warning')
265
266
267 class TrackNumberColumn(Column):
268 name = 'tracknumber'
269 # TRANSLATORS: Title of the track number column
270 display = _('#')
271 menu_title = _('Track Number')
272 size = 30
273 cellproperties = {'xalign': 1.0, 'width-chars': 4}
274
275
276 providers.register('playlist-columns', TrackNumberColumn)
277
278
279 class TitleColumn(EditableColumn):
280 name = 'title'
281 display = _('Title')
282 size = 200
283 autoexpand = True
284
285
286 providers.register('playlist-columns', TitleColumn)
287
288
289 class ArtistColumn(EditableColumn):
290 name = 'artist'
291 display = _('Artist')
292 size = 150
293 autoexpand = True
294
295
296 providers.register('playlist-columns', ArtistColumn)
297
298
299 class AlbumArtistColumn(EditableColumn):
300 name = 'albumartist'
301 display = _('Album artist')
302 size = 150
303 autoexpand = True
304
305
306 providers.register('playlist-columns', AlbumArtistColumn)
307
308
309 class ComposerColumn(EditableColumn):
310 name = 'composer'
311 display = _('Composer')
312 size = 150
313 autoexpand = True
314
315
316 providers.register('playlist-columns', ComposerColumn)
317
318
319 class AlbumColumn(EditableColumn):
320 name = 'album'
321 display = _('Album')
322 size = 150
323 autoexpand = True
324
325
326 providers.register('playlist-columns', AlbumColumn)
327
328
329 class LengthColumn(Column):
330 name = '__length'
331 display = _('Length')
332 size = 50
333 cellproperties = {'xalign': 1.0}
334
335
336 providers.register('playlist-columns', LengthColumn)
337
338
339 class DiscNumberColumn(Column):
340 name = 'discnumber'
341 display = _('Disc')
342 menu_title = _('Disc Number')
343 size = 40
344 cellproperties = {'xalign': 1.0, 'width-chars': 2}
345
346
347 providers.register('playlist-columns', DiscNumberColumn)
348
349
350 class RatingColumn(Column):
351 name = '__rating'
352 display = _('Rating')
353 renderer = rating.RatingCellRenderer
354 dataproperty = 'rating'
355 cellproperties = {'follow-state': False}
356
357 def __init__(self, *args):
358 Column.__init__(self, *args)
359 self.cellrenderer.connect('rating-changed', self.on_rating_changed)
360 self.cellrenderer.size_ratio = self.get_size_ratio()
361 self.saved_model = None
362
363 def data_func(self, col, cell, model, iter, user_data):
364 track = model.get_value(iter, 0)
365 cell.props.rating = track.get_rating()
366 self.saved_model = model
367
368 def __get_size(self):
369 """
370 Retrieves the optimal size
371 """
372 size = icons.MANAGER.pixbuf_from_rating(0, self.get_size_ratio()).get_width()
373 size += 2 # FIXME: Find the source of this
374
375 return size
376
377 size = property(__get_size)
378
379 def on_rating_changed(self, widget, path, rating):
380 """
381 Updates the rating of the selected track
382 """
383 iter = self.saved_model.get_iter(path)
384 track = self.saved_model.get_value(iter, 0)
385 oldrating = track.get_rating()
386
387 if rating == oldrating:
388 rating = 0
389
390 rating = track.set_rating(rating)
391 event.log_event('rating_changed', self, rating)
392
393
394 providers.register('playlist-columns', RatingColumn)
395
396
397 class DateColumn(Column):
398 name = 'date'
399 display = _('Date')
400 size = 50
401
402
403 providers.register('playlist-columns', DateColumn)
404
405
406 class YearColumn(Column):
407 name = 'year'
408 display = _('Year')
409 size = 45
410
411
412 providers.register('playlist-columns', YearColumn)
413
414
415 class GenreColumn(EditableColumn):
416 name = 'genre'
417 display = _('Genre')
418 size = 100
419 autoexpand = True
420
421
422 providers.register('playlist-columns', GenreColumn)
423
424
425 class BitrateColumn(Column):
426 name = '__bitrate'
427 display = _('Bitrate')
428 size = 45
429 cellproperties = {'xalign': 1.0}
430
431
432 providers.register('playlist-columns', BitrateColumn)
433
434
435 class IoLocColumn(Column):
436 name = '__loc'
437 display = _('Location')
438 size = 200
439 autoexpand = True
440
441
442 providers.register('playlist-columns', IoLocColumn)
443
444
445 class FilenameColumn(Column):
446 name = '__basename'
447 display = _('Filename')
448 size = 200
449 autoexpand = True
450
451
452 providers.register('playlist-columns', FilenameColumn)
453
454
455 class PlayCountColumn(Column):
456 name = '__playcount'
457 display = _('Playcount')
458 size = 50
459 cellproperties = {'xalign': 1.0}
460
461
462 providers.register('playlist-columns', PlayCountColumn)
463
464
465 class BPMColumn(EditableColumn):
466 name = 'bpm'
467 display = _('BPM')
468 size = 40
469 cellproperties = {'xalign': 1.0, 'editable': True}
470 validate = lambda s, v: int(v)
471
472
473 providers.register('playlist-columns', BPMColumn)
474
475
476 class LanguageColumn(EditableColumn):
477 name = 'language'
478 display = _('Language')
479 size = 100
480 autoexpand = True
481
482
483 providers.register('playlist-columns', LanguageColumn)
484
485
486 class LastPlayedColumn(Column):
487 name = '__last_played'
488 display = _('Last played')
489 size = 80
490
491
492 providers.register('playlist-columns', LastPlayedColumn)
493
494
495 class DateAddedColumn(Column):
496 name = '__date_added'
497 display = _('Date added')
498 size = 80
499
500
501 providers.register('playlist-columns', DateAddedColumn)
502
503
504 class ScheduleTimeColumn(Column):
505 name = 'schedule_time'
506 display = _('Schedule')
507 size = 80
508
509 def __init__(self, *args):
510 Column.__init__(self, *args)
511 self.timeout_id = None
512
513 event.add_ui_callback(
514 self.on_queue_current_playlist_changed,
515 'queue_current_playlist_changed',
516 player.QUEUE,
517 )
518 event.add_ui_callback(
519 self.on_playback_player_start, 'playback_player_start', player.PLAYER
520 )
521 event.add_ui_callback(
522 self.on_playback_player_end, 'playback_player_end', player.PLAYER
523 )
524
525 def data_func(self, col, cell, model, iter, user_data):
526 """
527 Sets the schedule time if appropriate
528 """
529 text = None
530 playlist = self.container.playlist
531
532 # Only display the schedule time if
533 # 1) there is playback at all
534 # 2) this playlist is currently played
535 # 3) playback is not in shuffle mode
536 # 4) the current track is not repeated
537 if (
538 not self.player.is_stopped()
539 and playlist is self.player.queue.current_playlist
540 and playlist.shuffle_mode == 'disabled'
541 and playlist.repeat_mode != 'track'
542 ):
543 track = model.get_value(iter, 0)
544 position = playlist.index(track)
545 current_position = playlist.current_position
546
547 # 5) this track is after the currently played one
548 if position > current_position:
549 # The delay is the accumulated length of all tracks
550 # between the currently playing and this one
551 try:
552 delay = sum(
553 t.get_tag_raw('__length')
554 for t in playlist[current_position:position]
555 )
556 except TypeError:
557 # on tracks with length == None, we cannot determine
558 # when later tracks will play
559 pass
560 else:
561 # Subtract the time which already has passed
562 delay -= self.player.get_time()
563 # The schedule time is the current time plus delay
564 schedule_time = time.localtime(time.time() + delay)
565 text = time.strftime('%H:%M', schedule_time)
566
567 cell.props.text = text
568
569 def start_timer(self):
570 """
571 Enables realtime updates
572 """
573 timeout_id = self.timeout_id
574
575 # Make sure to stop any timer still running
576 if timeout_id is not None:
577 GLib.source_remove(timeout_id)
578
579 self.timeout_id = GLib.timeout_add_seconds(60, self.on_timeout)
580
581 def stop_timer(self):
582 """
583 Disables realtime updates
584 """
585 timeout_id = self.timeout_id
586
587 if timeout_id is not None:
588 GLib.source_remove(timeout_id)
589 self.timeout_id = None
590
591 # Update once more
592 self.on_timeout()
593
594 def on_timeout(self):
595 """
596 Makes sure schedule times are updated in realtime
597 """
598 self.queue_resize()
599 view = self.get_tree_view()
600 if view is not None:
601 view.queue_draw()
602 return True
603
604 self.timeout_id = None
605 return False
606
607 def on_queue_current_playlist_changed(self, e, queue, current_playlist):
608 """
609 Disables realtime updates for all playlists
610 and re-enables them for the current playlist
611 """
612 self.stop_timer()
613
614 if current_playlist is self.container.playlist:
615 self.start_timer()
616
617 def on_playback_player_start(self, e, player, track):
618 """
619 Enables realtime updates for the current playlist
620 """
621 self.stop_timer()
622
623 if self.player.queue.current_playlist is self.container.playlist:
624 logger.debug('Playback started, enabling realtime updates')
625 self.start_timer()
626
627 def on_playback_player_end(self, e, player, track):
628 """
629 Disables realtime updates for all playlists
630 """
631 self.stop_timer()
632
633
634 providers.register('playlist-columns', ScheduleTimeColumn)
635
636
637 class CommentColumn(EditableColumn):
638 name = 'comment'
639 display = _('Comment')
640 size = 200
641 autoexpand = True
642 # Remove the newlines to fit into the vertical space of rows
643 formatter = TrackFormatter('${comment:newlines=strip}')
644 edit_formatter = TrackFormatter('$comment')
645 cellproperties = {'editable': True}
646
647
648 providers.register('playlist-columns', CommentColumn)
649
650
651 class GroupingColumn(EditableColumn):
652 name = 'grouping'
653 display = _('Grouping')
654 size = 200
655 autoexpand = True
656
657
658 providers.register('playlist-columns', GroupingColumn)
659
660
661 def _validate_time(self, v):
662 rv = 0
663 m = 1
664 for i in reversed(v.split(':')):
665 i = int(i)
666 if i < 0 or i > 59:
667 raise ValueError
668 rv += i * m
669 m *= 60
670 return rv
671
672
673 class StartOffsetColumn(EditableColumn):
674 name = '__startoffset'
675 display = _('Start Offset')
676 size = 50
677 cellproperties = {'xalign': 1.0, 'editable': True}
678 validate = _validate_time
679
680
681 providers.register('playlist-columns', StartOffsetColumn)
682
683
684 class StopOffsetColumn(EditableColumn):
685 name = '__stopoffset'
686 display = _('Stop Offset')
687 size = 50
688 cellproperties = {'xalign': 1.0, 'editable': True}
689 validate = _validate_time
690
691
692 providers.register('playlist-columns', StopOffsetColumn)
693
694
695 class WebsiteColumn(EditableColumn):
696 name = 'website'
697 display = _('Website')
698 size = 200
699 autoexpand = True
700
701
702 providers.register('playlist-columns', WebsiteColumn)
703
704
705 class ColumnMenuItem(menu.MenuItem):
706 """
707 A menu item dedicated to display the
708 status of a column and change it
709 """
710
711 def __init__(self, column, after=None):
712 """
713 Sets up the menu item from a column description
714
715 :param column: the playlist column
716 :type column: :class:`Column`
717 :param after: enumeration of menu
718 items before this one
719 :type after: list of strings
720 """
721 menu.MenuItem.__init__(self, column.name, self.factory, after)
722 self.title = column.menu_title
723
724 def factory(self, menu, parent, context):
725 """
726 Creates the menu item
727 """
728 item = Gtk.CheckMenuItem.new_with_label(self.title)
729 active = self.is_selected(self.name, parent, context)
730 item.set_active(active)
731 item.connect('activate', self.on_item_activate, self.name, parent, context)
732
733 return item
734
735 def is_selected(self, name, parent, context):
736 """
737 Returns whether a column is selected
738
739 :rtype: bool
740 """
741 return name in settings.get_option('gui/columns', DEFAULT_COLUMNS)
742
743 def on_item_activate(self, menu_item, name, parent, context):
744 """
745 Updates the columns setting
746 """
747 columns = settings.get_option('gui/columns', DEFAULT_COLUMNS)
748
749 if name in columns:
750 columns.remove(name)
751 elif 'trigger_column' in context and context['trigger_column']:
752 col_name = context['trigger_column'].name
753 s = columns.index(col_name) + 1
754 columns.insert(s, name)
755 else:
756 columns.append(name)
757
758 settings.set_option('gui/columns', columns)
759
760
761 def __register_playlist_columns_menuitems():
762 """
763 Registers standard menu items for playlist columns
764 """
765
766 def is_column_selected(name, parent, context):
767 """
768 Returns whether a menu item should be checked
769 """
770 return name in settings.get_option('gui/columns', DEFAULT_COLUMNS)
771
772 def is_resizable(name, parent, context):
773 """
774 Returns whether manual or automatic sizing is requested
775 """
776 resizable = settings.get_option('gui/resizable_cols', False)
777
778 if name == 'resizable':
779 return resizable
780 elif name == 'autosize':
781 return not resizable
782
783 def on_column_item_activate(menu_item, name, parent, context):
784 """
785 Updates columns setting
786 """
787 columns = settings.get_option('gui/columns', DEFAULT_COLUMNS)
788
789 if name in columns:
790 columns.remove(name)
791 else:
792 columns.append(name)
793
794 settings.set_option('gui/columns', columns)
795
796 def on_sizing_item_activate(menu_item, name, parent, context):
797 """
798 Updates column sizing setting
799 """
800
801 # Ignore the activation if the menu item is not actually active
802 if not menu_item.get_active():
803 return
804
805 if name == 'resizable':
806 settings.set_option('gui/resizable_cols', True)
807 elif name == 'autosize':
808 settings.set_option('gui/resizable_cols', False)
809
810 columns = [
811 'tracknumber',
812 'title',
813 'artist',
814 'album',
815 '__length',
816 'genre',
817 '__rating',
818 'date',
819 ]
820
821 for provider in providers.get('playlist-columns'):
822 if provider.name not in columns:
823 columns += [provider.name]
824
825 menu_columns = []
826 for name in columns:
827 column = providers.get_provider('playlist-columns', name)
828 menu_columns += [column]
829
830 # Sort menu alphabetical
831 menu_columns.sort(key=lambda elem: elem.menu_title)
832
833 menu_items = []
834 after = []
835 for column in menu_columns:
836 menu_item = ColumnMenuItem(column, after)
837 menu_items += [menu_item]
838 after = [menu_item.name]
839
840 separator_item = menu.simple_separator('columns_separator', after)
841 menu_items += [separator_item]
842 after = [separator_item.name]
843
844 sizing_item = menu.radio_menu_item(
845 'resizable',
846 after,
847 _('_Resizable'),
848 'column-sizing',
849 is_resizable,
850 on_sizing_item_activate,
851 )
852 menu_items += [sizing_item]
853 after = [sizing_item.name]
854
855 sizing_item = menu.radio_menu_item(
856 'autosize',
857 after,
858 _('_Autosize'),
859 'column-sizing',
860 is_resizable,
861 on_sizing_item_activate,
862 )
863 menu_items += [sizing_item]
864
865 for menu_item in menu_items:
866 providers.register('playlist-columns-menu', menu_item)
867
868
869 __register_playlist_columns_menuitems()