Debian Codegraph @

xlgui/widgets/info.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2008-2010 Adam Olsen
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2, or (at your option)
7 # any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 #
18 #
19 # The developers of the Exaile media player hereby grant permission
20 # for non-GPL compatible GStreamer and Exaile plugins to be used and
21 # distributed together with GStreamer and Exaile. This permission is
22 # above and beyond the permissions granted by the GPL license by which
23 # Exaile is covered. If you modify this code, you may extend this
24 # exception to your version of the code, but you are not obligated to
25 # do so. If you do not wish to do so, delete this exception statement
26 # from your version.
27
28 from typing import Literal
29
30 from gi.repository import GLib
31 from gi.repository import Gtk
32 from gi.repository import Pango
33
34 from xl import event, formatter, main, settings, xdg
35 from xl.nls import gettext as _, ngettext
36 import xlgui
37 from xlgui import cover, guiutil
38 from xlgui.widgets import playlist, queue
39 from xlgui.widgets.playback import PlaybackProgressBar
40
41
42 class TrackInfoPane(Gtk.Bin):
43 """
44 Displays cover art and track data
45 """
46
47 def __init__(self, player):
48 Gtk.Bin.__init__(self)
49 self.__player = player
50
51 builder = guiutil.get_builder(
52 xdg.get_data_path('ui', 'widgets', 'track_info.ui')
53 )
54 info_box = builder.get_object('info_box')
55 info_box.get_parent().remove(info_box)
56 self.add(info_box)
57
58 self.__auto_update = False
59 self.__display_progress = False
60 self.__formatter = formatter.TrackFormatter(
61 _(
62 '<span size="x-large" weight="bold">$title</span>\n'
63 'by $artist\n'
64 'from $album'
65 )
66 )
67 self.__formatter.connect('notify::format', self.on_notify_format)
68 self.__default_text = '<span size="x-large" ' 'weight="bold">%s</span>\n\n' % _(
69 'Not Playing'
70 )
71 self.__cover_size = None
72 self.__timer = None
73 self.__track = None
74
75 self.info_label = builder.get_object('info_label')
76 self.action_area = builder.get_object('action_area')
77 self.progress_box = builder.get_object('progress_box')
78 self.playback_image = builder.get_object('playback_image')
79 self.progressbar = PlaybackProgressBar(player)
80 guiutil.gtk_widget_replace(builder.get_object('progressbar'), self.progressbar)
81
82 self.cover = cover.CoverWidget(builder.get_object('cover_image'))
83 self.cover.hide()
84 self.cover.set_no_show_all(True)
85
86 self.clear()
87 self.__update_widget_state()
88
89 def destroy(self):
90 """
91 Cleanups
92 """
93 # Make sure to disconnect callbacks
94 self.set_auto_update(False)
95
96 Gtk.Bin.destroy(self)
97
98 def get_auto_update(self):
99 """
100 Gets whether the info pane shall
101 be automatically updated or not
102
103 :rtype: bool
104 """
105 return self.__auto_update
106
107 def set_auto_update(self, auto_update):
108 """
109 Sets whether the info pane shall
110 be automatically updated or not
111
112 :param auto_update: enable or disable
113 automatic updating
114 :type auto_update: bool
115 """
116 if auto_update != self.__auto_update:
117 self.__auto_update = auto_update
118
119 p_evts = [
120 'playback_player_end',
121 'playback_track_start',
122 'playback_toggle_pause',
123 'playback_error',
124 ]
125 events = ['track_tags_changed', 'cover_set', 'cover_removed']
126
127 if auto_update:
128 for e in p_evts:
129 event.add_ui_callback(getattr(self, 'on_%s' % e), e, self.__player)
130 for e in events:
131 event.add_ui_callback(getattr(self, 'on_%s' % e), e)
132
133 self.set_track(self.__player.current)
134 else:
135 for e in p_evts:
136 event.remove_callback(getattr(self, 'on_%s' % e), e, self.__player)
137 for e in events:
138 event.remove_callback(getattr(self, 'on_%s' % e), e)
139
140 def get_cover_size(self):
141 """
142 Gets the preferred cover size
143
144 :rtype: int
145 """
146 return self.__cover_size or settings.get_option('gui/cover_width', 100)
147
148 def set_cover_size(self, cover_size):
149 """
150 Overrides the cover size to display,
151 set to None to use global default
152
153 :param cover_size: the preferred cover size
154 :type cover_size: int
155 """
156 self.__cover_size = cover_size
157
158 def get_default_text(self):
159 """
160 Gets the default text displayed
161 when the playback is stopped
162
163 :rtype: string
164 """
165 return self.__default_text
166
167 def set_default_text(self, default_text):
168 """
169 Sets the default text displayed
170 when the playback is stopped
171
172 :param default_text: the new default text
173 :type default_text: string
174 """
175 self.__default_text = default_text
176
177 def get_display_progress(self):
178 """
179 Returns whether the progress indicator
180 is currently visible or not
181
182 :rtype: bool
183 """
184 return self.__display_progress
185
186 def set_display_progress(self, display_progress):
187 """
188 Shows or hides the progress indicator. The
189 indicator will not be displayed if the
190 currently displayed track is not playing.
191
192 :param display_progress: Whether to show
193 or hide the progress indicator
194 :type display_progress: bool
195 """
196 self.__display_progress = display_progress
197 self.__update_widget_state()
198
199 def get_info_format(self):
200 """
201 Gets the current format used
202 to display the track data
203
204 :rtype: string
205 """
206 return self.__formatter.props.format
207
208 def set_info_format(self, format):
209 """
210 Sets the format used to display the track data
211
212 :param format: the format, see the documentation
213 of :class:`string.Template` for details
214 :type format: string
215 """
216 self.__formatter.props.format = format
217
218 def set_track(self, track):
219 """
220 Updates the data displayed in the info pane
221
222 :param track: A track to take the data from,
223 clears the info pane if track is None
224 :type track: :class:`xl.trax.Track`
225 """
226 if track is None:
227 self.clear()
228 return
229
230 self.__track = track
231
232 self.cover.set_track(track)
233
234 self.info_label.set_markup(self.__formatter.format(track, markup_escape=True))
235 self.__update_widget_state()
236
237 def __update_widget_state(self):
238 if self.__display_progress:
239 if self.__track == self.__player.current and not self.__player.is_stopped():
240 if self.__player.is_paused():
241 icon_name = 'media-playback-pause'
242 else:
243 icon_name = 'media-playback-start'
244 self.playback_image.set_from_icon_name(
245 icon_name, Gtk.IconSize.SMALL_TOOLBAR
246 )
247
248 self.progress_box.set_no_show_all(False)
249 self.progress_box.set_visible(True)
250 self.progressbar.set_visible(True)
251 else:
252 self.progress_box.set_visible(False)
253 self.progress_box.set_no_show_all(True)
254 self.progressbar.set_visible(True)
255
256 def clear(self):
257 """
258 Resets the info pane
259 """
260
261 self.cover.set_track(None)
262 self.info_label.set_markup(self.__default_text)
263
264 self.__track = None
265 self.__update_widget_state()
266
267 def get_action_area(self):
268 """
269 Retrieves the action area
270 at the end of the pane
271
272 :rtype: :class:`Gtk.Box`
273 """
274 return self.action_area
275
276 def on_notify_format(self, formatter, format):
277 """
278 Updates the displayed data after format changes
279 """
280 if self.__track is not None:
281 self.set_track(self.__track)
282
283 def on_playback_player_end(self, event, player, track):
284 """
285 Clears the info pane on playback end
286 """
287 self.clear()
288
289 def on_playback_track_start(self, event, player, track):
290 """
291 Updates the info pane on track start
292 """
293 self.set_track(track)
294
295 def on_playback_toggle_pause(self, event, player, track):
296 """
297 Updates the info pane on playback pause/resume
298 """
299 self.set_track(track)
300
301 def on_playback_error(self, event, player, message):
302 """
303 Clears the info pane on playback errors
304 """
305 self.clear()
306
307 def on_track_tags_changed(self, event, track, tags):
308 """
309 Updates the info pane on tag changes
310 """
311 if (
312 self.__player is not None
313 and not self.__player.is_stopped()
314 and track is self.__track
315 ):
316 self.set_track(track)
317
318 def on_cover_set(self, event, covers, track):
319 """
320 Updates the info pane on cover set
321 """
322 if track is self.__track:
323 self.set_track(track)
324
325 def on_cover_removed(self, event, covers, track):
326 """
327 Updates the info pane on cover removal
328 """
329 if track is self.__track:
330 self.set_track(track)
331
332
333 class ToolTip:
334 """
335 Custom tooltip class to allow for
336 extended tooltip functionality
337 """
338
339 def __init__(self, parent, widget):
340 """
341 :param parent: the parent widget the tooltip
342 should be attached to
343 :param widget: the tooltip widget to be used
344 for the tooltip
345 """
346 if self.__class__.__name__ == 'ToolTip':
347 raise TypeError(
348 "cannot create instance of abstract "
349 "(non-instantiable) type `ToolTip'"
350 )
351
352 self.__widget = widget
353 self.__widget.unparent() # Just to be sure
354
355 parent.set_has_tooltip(True)
356 parent.connect('query-tooltip', self.on_query_tooltip)
357
358 def on_query_tooltip(self, widget, x, y, keyboard_mode, tooltip):
359 """
360 Puts the custom widget into the tooltip
361 """
362 tooltip.set_custom(self.__widget)
363
364 return True
365
366
367 class TrackToolTip(TrackInfoPane, ToolTip):
368 """
369 Track specific tooltip class, displays
370 track data and progress indicators
371 """
372
373 def __init__(self, parent, player):
374 """
375 :param parent: the parent widget the tooltip
376 should be attached to
377 """
378 TrackInfoPane.__init__(self, player)
379 ToolTip.__init__(self, parent, self)
380
381 self.set_border_width(6)
382 self.info_label.set_ellipsize(Pango.EllipsizeMode.NONE)
383 self.cover.set_no_show_all(False)
384 self.cover.show_all()
385
386 def destroy(self):
387 """
388 Cleanups
389 """
390 TrackInfoPane.destroy(self)
391
392
393 class StatusbarTextFormatter(formatter.Formatter):
394 """
395 A text formatter for status indicators
396 """
397
398 def __init__(self, format):
399 """
400 :param format: The initial format, see the documentation
401 of string.Template for details
402 :type format: string
403 """
404 formatter.Formatter.__init__(self, format)
405
406 self._substitutions = {
407 'collection_count': self.get_collection_count,
408 'playlist_count': self.get_playlist_count,
409 'playlist_duration': self.get_playlist_duration,
410 }
411
412 def get_collection_count(self):
413 """
414 Retrieves the collection count
415 """
416 if not settings.get_option('gui/show_status_bar_collection_count', True):
417 return ''
418 return _('%d in collection') % main.exaile().collection.get_count()
419
420 def get_playlist_count(
421 self, selection: Literal['none', 'override', 'only'] = 'none'
422 ):
423 """
424 Retrieves the count of tracks in either the
425 full playlist or the current selection
426
427 :param selection: 'none' for playlist count only,
428 'override' for selection count if tracks are selected,
429 playlist count otherwise, 'only' for selection count only
430 """
431 if not settings.get_option(
432 'gui/show_status_bar_count_tracks_in_playlist', True
433 ):
434 return ""
435
436 page = xlgui.main.get_selected_page()
437
438 if not isinstance(page, playlist.PlaylistPageBase):
439 return ""
440
441 playlist_count = len(page.playlist)
442 selection_count = page.view.get_selection_count()
443
444 if selection == 'none':
445 return ngettext("%d showing", "%d showing", playlist_count) % playlist_count
446 elif selection == 'override':
447 if selection_count > 1:
448 return (
449 ngettext("%d selected", "%d selected", selection_count)
450 % selection_count
451 )
452 else:
453 return (
454 ngettext("%d showing", "%d showing", playlist_count)
455 % playlist_count
456 )
457 elif selection == 'only':
458 return (
459 ngettext("%d selected", "%d selected", selection_count)
460 % selection_count
461 )
462
463 raise ValueError(
464 'Invalid argument "%s" passed to parameter '
465 '"selection" for "playlist_count", possible arguments are '
466 '"none", "override" and "only"' % selection
467 )
468
469 def get_playlist_duration(self, format='short', selection='none'):
470 """
471 Retrieves the duration of all tracks in
472 the playlist or within the selection
473
474 :param format: Verbosity of the output
475 Possible values are short, long or verbose
476 yielding "1:02:42", "1h, 2m, 42s" or
477 "1 hour, 2 minutes, 42 seconds"
478 :type format: string
479 :param selection: 'none' for playlist count only,
480 'override' for selection count if tracks are selected,
481 playlist count otherwise, 'only' for selection count only
482 :type selection: string
483 """
484 if not settings.get_option('gui/show_status_bar_time_in_playlist', True):
485 return ''
486
487 page = xlgui.main.get_selected_page()
488
489 if not isinstance(page, playlist.PlaylistPageBase):
490 return ''
491
492 playlist_duration = sum(t.get_tag_raw('__length') or 0 for t in page.playlist)
493 selection_tracks = page.view.get_selected_tracks()
494 selection_count = len(selection_tracks)
495 selection_duration = sum(
496 t.get_tag_raw('__length') or 0 for t in selection_tracks
497 )
498
499 if selection == 'none':
500 duration = playlist_duration
501 elif selection == 'override':
502 if selection_count > 1:
503 duration = selection_duration
504 else:
505 duration = playlist_duration
506 elif selection == 'only':
507 if selection_count > 1:
508 duration = selection_duration
509 else:
510 duration = 0
511 else:
512 raise ValueError(
513 'Invalid argument "%s" passed to parameter '
514 '"selection" for "playlist_duration", possible arguments are '
515 '"none", "override" and "only"' % selection
516 )
517
518 return formatter.LengthTagFormatter.format_value(duration, format)
519
520
521 class Statusbar:
522 """
523 Convenient access to multiple status labels
524 """
525
526 def __init__(self, status_bar):
527 """
528 Initialises the status bar
529 """
530 self.status_bar = status_bar
531
532 self.formatter = StatusbarTextFormatter(self._get_substitutions())
533
534 self.info_label = Gtk.Label()
535
536 box = self.status_bar.get_message_area()
537
538 box.pack_end(self.info_label, False, True, 0)
539
540 self.context_id = self.status_bar.get_context_id('status')
541 self.message_ids = []
542
543 event.add_callback(self._on_option_set, "gui_option_set")
544
545 def _get_substitutions(self) -> str:
546 sub = settings.get_option('gui/statusbar_info_format', '')
547
548 if sub:
549 return sub
550
551 show_playlist_count = settings.get_option(
552 'gui/show_status_bar_count_tracks_in_playlist', True
553 )
554 show_playlist_duration = settings.get_option(
555 'gui/show_status_bar_time_in_playlist', True
556 )
557 show_collection_count = settings.get_option(
558 'gui/show_status_bar_collection_count', True
559 )
560
561 if show_playlist_count:
562 sub = sub + '${playlist_count:selection=override}'
563
564 if show_playlist_count and show_playlist_duration:
565 sub = (
566 sub
567 + ' ${playlist_duration:selection=override, format=long, prefix=(, suffix=), pad=0 }'
568 )
569
570 elif not show_playlist_count and show_playlist_duration:
571 sub = sub + '${playlist_duration:selection=override, format=long, pad=0 }'
572
573 if show_collection_count and (show_playlist_count or show_playlist_duration):
574 sub = sub.rstrip() + ', '
575
576 if show_collection_count:
577 sub = sub + '$collection_count'
578
579 return sub
580
581 def _on_option_set(self, name, object, option: str):
582 if not option in [
583 'gui/show_status_bar_collection_count',
584 'gui/show_status_bar_count_tracks_in_playlist',
585 'gui/show_status_bar_time_in_playlist',
586 ]:
587 return
588
589 self.formatter = StatusbarTextFormatter(self._get_substitutions())
590
591 self.update_info()
592
593 def set_status(self, status, timeout=0):
594 """
595 Sets the status message
596 """
597 self.message_ids += [self.status_bar.push(self.context_id, status)]
598
599 if timeout > 0:
600 GLib.timeout_add_seconds(timeout, self.clear_status)
601
602 def clear_status(self):
603 """
604 Clears the status message
605 """
606 try:
607 for message_id in self.message_ids:
608 self.status_bar.remove_message(self.context_id, message_id)
609 except AttributeError:
610 for message_id in self.message_ids:
611 self.status_bar.remove(self.context_id, message_id)
612
613 del self.message_ids[:]
614 self.message_ids = []
615
616 def update_info(self):
617 """
618 Updates the info label text
619 """
620 if settings.get_option('gui/show_status_bar', True):
621 self.status_bar.show()
622 else:
623 self.status_bar.hide()
624
625 self.info_label.set_label(self.formatter.format())
626
627 def show(self):
628 self.status_bar.show()
629
630 def hide(self):
631 self.status_bar.hide()
632
633
634 # TODO: Check if we can get a progress indicator in here somehow
635 class Splash:
636 """
637 A splash screen suitable for indicating startup;
638 will automatically be destroyed after GUI startup
639 """
640
641 def __init__(self):
642 builder = guiutil.get_builder(xdg.get_data_path('ui', 'splash.ui'))
643
644 image = builder.get_object('splash_image')
645 image.set_from_file(xdg.get_data_path('images', 'splash.png'))
646
647 self.window = builder.get_object('SplashScreen')
648
649 def destroy(self):
650 """
651 Destroys the splash screen
652 """
653 self.window.destroy()
654
655 def show(self):
656 """
657 Shows the splash screen
658 """
659 # Show the splash screen without causing startup notification.
660 Gtk.Window.set_auto_startup_notification(False)
661 self.window.show_all()
662 Gtk.Window.set_auto_startup_notification(True)
663
664 # Ensure the splash is completely drawn before moving on
665 while Gtk.events_pending():
666 Gtk.main_iteration()
667
668 def hide(self):
669 """
670 Hides the splash screen
671 """
672 self.window.hide()