Debian Codegraph @

xlgui/panel/radio.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 Gio
30 from gi.repository import GLib
31 from gi.repository import GObject
32 from gi.repository import Gtk
33
34 import xl.radio
35 import xl.playlist
36 from xl import event, common, settings, trax
37 from xl.nls import gettext as _
38 import xlgui.panel.playlists as playlistpanel
39 from xlgui.panel import menus
40 from xlgui import icons, panel
41 from xlgui.widgets.common import DragTreeView
42 from xlgui.widgets import dialogs, menu
43
44
45 class RadioException(Exception):
46 pass
47
48
49 class ConnectionException(RadioException):
50 pass
51
52
53 class RadioPanel(panel.Panel, playlistpanel.BasePlaylistPanelMixin):
54 """
55 The Radio Panel
56 """
57
58 __gsignals__ = {
59 'playlist-selected': (GObject.SignalFlags.RUN_LAST, None, (object,)),
60 'append-items': (GObject.SignalFlags.RUN_LAST, None, (object, bool)),
61 'replace-items': (GObject.SignalFlags.RUN_LAST, None, (object,)),
62 'queue-items': (GObject.SignalFlags.RUN_LAST, None, (object,)),
63 }
64 __gsignals__.update(playlistpanel.BasePlaylistPanelMixin._gsignals_)
65
66 ui_info = ('radio.ui', 'RadioPanel')
67 _radiopanel = None
68
69 def __init__(self, parent, collection, radio_manager, station_manager, name):
70 """
71 Initializes the radio panel
72 """
73 panel.Panel.__init__(self, parent, name, _('Radio'))
74 playlistpanel.BasePlaylistPanelMixin.__init__(self)
75
76 self.collection = collection
77 self.manager = radio_manager
78 self.playlist_manager = station_manager
79 self.nodes = {}
80 self.load_nodes = {}
81 self.complete_reload = {}
82 self.loaded_nodes = []
83
84 self._setup_tree()
85 self._setup_widgets()
86 self.playlist_image = icons.MANAGER.pixbuf_from_icon_name(
87 'music-library', Gtk.IconSize.SMALL_TOOLBAR
88 )
89
90 # menus
91 self.playlist_menu = menus.RadioPanelPlaylistMenu(self)
92 self.track_menu = menus.TrackPanelMenu(self)
93 self._connect_events()
94
95 self.load_streams()
96 RadioPanel._radiopanel = self
97
98 @property
99 def menu(self):
100 """
101 Gets a menu for the selected item
102 :return: xlgui.widgets.menu.Menu or None if do not have it
103 """
104 model, it = self.tree.get_selection().get_selected()
105 item = model[it][2]
106 if isinstance(item, xl.playlist.Playlist):
107 return self.playlist_menu
108 elif isinstance(item, playlistpanel.TrackWrapper):
109 return self.track_menu
110 else:
111 station = (
112 item
113 if isinstance(item, xl.radio.RadioStation)
114 else (
115 item.station
116 if isinstance(item, (xl.radio.RadioList, xl.radio.RadioItem))
117 else None
118 )
119 )
120 if station and hasattr(station, 'get_menu'):
121 return station.get_menu(self)
122
123 def load_streams(self):
124 """
125 Loads radio streams from plugins
126 """
127 for name in self.playlist_manager.playlists:
128 pl = self.playlist_manager.get_playlist(name)
129 if pl is not None:
130 self.playlist_nodes[pl] = self.model.append(
131 self.custom, [self.playlist_image, pl.name, pl]
132 )
133 self._load_playlist_nodes(pl)
134 self.tree.expand_row(self.model.get_path(self.custom), False)
135
136 for name, value in self.manager.stations.items():
137 self.add_driver(value)
138
139 def _add_driver_cb(self, type, object, driver):
140 self.add_driver(driver)
141
142 def add_driver(self, driver):
143 """
144 Adds a driver to the radio panel
145 """
146 node = self.model.append(self.radio_root, [self.folder, str(driver), driver])
147 self.nodes[driver] = node
148 self.load_nodes[driver] = self.model.append(
149 node, [self.refresh_image, _('Loading streams...'), None]
150 )
151 self.tree.expand_row(self.model.get_path(self.radio_root), False)
152
153 if settings.get_option('gui/radio/%s_station_expanded' % driver.name, False):
154 self.tree.expand_row(self.model.get_path(node), False)
155
156 def _remove_driver_cb(self, type, object, driver):
157 self.remove_driver(driver)
158
159 def remove_driver(self, driver):
160 """
161 Removes a driver from the radio panel
162 """
163 if driver in self.nodes:
164 self.model.remove(self.nodes[driver])
165 del self.nodes[driver]
166
167 def _setup_widgets(self):
168 """
169 Sets up the various widgets required for this panel
170 """
171 self.status = self.builder.get_object('status_label')
172
173 @common.idle_add()
174 def _set_status(self, message, timeout=0):
175 self.status.set_text(message)
176
177 if timeout:
178 GLib.timeout_add_seconds(timeout, self._set_status, '', 0)
179
180 def _connect_events(self):
181 """
182 Connects events used in this panel
183 """
184
185 self.builder.connect_signals(
186 {'on_add_button_clicked': self._on_add_button_clicked}
187 )
188 self.tree.connect('row-expanded', self.on_row_expand)
189 self.tree.connect('row-collapsed', self.on_collapsed)
190 self.tree.connect('row-activated', self.on_row_activated)
191 self.tree.connect('key-release-event', self.on_key_released)
192
193 event.add_ui_callback(self._add_driver_cb, 'station_added', self.manager)
194 event.add_ui_callback(self._remove_driver_cb, 'station_removed', self.manager)
195
196 def _on_add_button_clicked(self, *e):
197 dialog = dialogs.MultiTextEntryDialog(self.parent, _("Add Radio Station"))
198
199 dialog.add_field(_("Name:"))
200 url_field = dialog.add_field(_("URL:"))
201
202 clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
203 text = clipboard.wait_for_text()
204
205 if text is not None:
206 location = Gio.File.new_for_uri(text)
207
208 if location.get_uri_scheme() is not None:
209 url_field.set_text(text)
210
211 result = dialog.run()
212 dialog.hide()
213
214 if result == Gtk.ResponseType.OK:
215 (name, uri) = dialog.get_values()
216 self._do_add_playlist(name, uri)
217
218 @common.threaded
219 def _do_add_playlist(self, name, uri):
220 from xl import playlist, trax
221
222 if playlist.is_valid_playlist(uri):
223 pl = playlist.import_playlist(uri)
224 pl.name = name
225 else:
226 pl = playlist.Playlist(name)
227 tracks = trax.get_tracks_from_uri(uri)
228 pl.extend(tracks)
229
230 self.playlist_manager.save_playlist(pl)
231 self._add_to_tree(pl)
232
233 @common.idle_add()
234 def _add_to_tree(self, pl):
235 self.playlist_nodes[pl] = self.model.append(
236 self.custom, [self.playlist_image, pl.name, pl]
237 )
238 self._load_playlist_nodes(pl)
239
240 def _setup_tree(self):
241 """
242 Sets up the tree that displays the radio panel
243 """
244 box = self.builder.get_object('RadioPanel')
245 self.tree = playlistpanel.PlaylistDragTreeView(self, True, True)
246 self.tree.set_headers_visible(False)
247
248 self.targets = [Gtk.TargetEntry.new('text/uri-list', 0, 0)]
249
250 # columns
251 text = Gtk.CellRendererText()
252 if settings.get_option('gui/ellipsize_text_in_panels', False):
253 from gi.repository import Pango
254
255 text.set_property('ellipsize-set', True)
256 text.set_property('ellipsize', Pango.EllipsizeMode.END)
257 icon = Gtk.CellRendererPixbuf()
258 col = Gtk.TreeViewColumn('radio')
259 col.pack_start(icon, False)
260 col.pack_start(text, True)
261 col.set_attributes(icon, pixbuf=0)
262 col.set_cell_data_func(text, self.cell_data_func)
263 self.tree.append_column(col)
264
265 self.model = Gtk.TreeStore(GdkPixbuf.Pixbuf, str, object)
266 self.tree.set_model(self.model)
267
268 self.track = icons.MANAGER.pixbuf_from_icon_name(
269 'audio-x-generic', Gtk.IconSize.SMALL_TOOLBAR
270 )
271 self.folder = icons.MANAGER.pixbuf_from_icon_name(
272 'folder', Gtk.IconSize.SMALL_TOOLBAR
273 )
274 self.refresh_image = icons.MANAGER.pixbuf_from_icon_name('view-refresh')
275
276 self.custom = self.model.append(None, [self.folder, _("Saved Stations"), None])
277 self.radio_root = self.model.append(
278 None, [self.folder, _("Radio " "Streams"), None]
279 )
280
281 scroll = Gtk.ScrolledWindow()
282 scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
283 scroll.add(self.tree)
284 scroll.set_shadow_type(Gtk.ShadowType.IN)
285
286 box.pack_start(scroll, True, True, 0)
287
288 def on_row_activated(self, tree, path, column):
289 item = self.model[path][2]
290 if isinstance(item, xl.radio.RadioItem):
291 self.emit('playlist-selected', item.get_playlist())
292 elif isinstance(item, playlistpanel.TrackWrapper):
293 self.emit('playlist-selected', item.playlist)
294 elif isinstance(item, xl.playlist.Playlist):
295 self.open_station(item)
296
297 def open_station(self, playlist):
298 """
299 Opens a saved station
300 """
301 self.emit('playlist-selected', playlist)
302
303 def get_menu(self):
304 """
305 Returns the menu that all radio stations use
306 """
307 m = menu.Menu(None)
308 m.add_simple(_("Refresh"), self.on_reload, Gtk.STOCK_REFRESH)
309 return m
310
311 def on_key_released(self, widget, event):
312 """
313 Called when a key is released in the tree
314 """
315 if event.keyval == Gdk.KEY_Menu:
316 (mods, paths) = self.tree.get_selection().get_selected_rows()
317 if paths and paths[0]:
318 iter = self.model.get_iter(paths[0])
319 item = self.model.get_value(iter, 2)
320 if isinstance(
321 item,
322 (xl.radio.RadioStation, xl.radio.RadioList, xl.radio.RadioItem),
323 ):
324 if isinstance(item, xl.radio.RadioStation):
325 station = item
326 else:
327 station = item.station
328
329 if station and hasattr(station, 'get_menu'):
330 menu = station.get_menu(self)
331 menu.popup(event)
332 elif isinstance(item, xl.playlist.Playlist):
333 Gtk.Menu.popup(
334 self.playlist_menu, None, None, None, None, 0, event.time
335 )
336 elif isinstance(item, playlistpanel.TrackWrapper):
337 Gtk.Menu.popup(
338 self.track_menu, None, None, None, None, 0, event.time
339 )
340 return True
341
342 if event.keyval == Gdk.KEY_Left:
343 (mods, paths) = self.tree.get_selection().get_selected_rows()
344 if paths and paths[0]:
345 self.tree.collapse_row(paths[0])
346 return True
347
348 if event.keyval == Gdk.KEY_Right:
349 (mods, paths) = self.tree.get_selection().get_selected_rows()
350 if paths and paths[0]:
351 self.tree.expand_row(paths[0], False)
352 return True
353
354 return False
355
356 def cell_data_func(self, column, cell, model, iter, user_data):
357 """
358 Called when the tree needs a value for column 1
359 """
360 object = model.get_value(iter, 1)
361 cell.set_property('text', str(object))
362
363 def drag_data_received(self, tv, context, x, y, selection, info, etime):
364 """
365 Called when someone drags some thing onto the playlist panel
366 """
367 # if the drag originated from radio view deny it
368 # TODO this might change if we are allowed to change the order of radio
369 if Gtk.drag_get_source_widget(context) == tv:
370 context.drop_finish(False, etime)
371 return
372
373 locs = list(selection.get_uris())
374
375 path = self.tree.get_path_at_pos(x, y)
376 if path:
377 # Add whatever we received to the playlist at path
378 iter = self.model.get_iter(path[0])
379 current_playlist = self.model.get_value(iter, 2)
380
381 # if it's a track that we've dragged to, get the parent
382 if isinstance(current_playlist, playlistpanel.TrackWrapper):
383 current_playlist = current_playlist.playlist
384
385 elif not isinstance(current_playlist, xl.playlist.Playlist):
386 self._add_new_station(locs)
387 return
388 (tracks, playlists) = self.tree.get_drag_data(locs)
389 current_playlist.extend(tracks)
390 # Do we save in the case when a user drags a file onto a playlist in the playlist panel?
391 # note that the playlist does not have to be open for this to happen
392 self.playlist_manager.save_playlist(current_playlist, overwrite=True)
393 self._load_playlist_nodes(current_playlist)
394 else:
395 self._add_new_station(locs)
396
397 def _add_new_station(self, locs):
398 """
399 Add a new station
400 """
401 # If the user dragged files prompt for a new playlist name
402 # else if they dragged a playlist add the playlist
403
404 # We don't want the tracks in the playlists to be added to the
405 # master tracks list so we pass in False
406 (tracks, playlists) = self.tree.get_drag_data(locs, False)
407 # First see if they dragged any playlist files
408 for new_playlist in playlists:
409 self.model.append(
410 self.custom, [self.playlist_image, new_playlist.name, new_playlist]
411 )
412 # We are adding a completely new playlist with tracks so we save it
413 self.playlist_manager.save_playlist(new_playlist, overwrite=True)
414
415 # After processing playlist proceed to ask the user for the
416 # name of the new playlist to add and add the tracks to it
417 if len(tracks) > 0:
418 dialog = dialogs.TextEntryDialog(
419 _("Enter the name you want for your new playlist"), _("New Playlist")
420 )
421 result = dialog.run()
422 if result == Gtk.ResponseType.OK:
423 name = dialog.get_value()
424 if not name == "":
425 # Create the playlist from all of the tracks
426 new_playlist = xl.playlist.Playlist(name)
427 new_playlist.extend(tracks)
428 self.playlist_nodes[new_playlist] = self.model.append(
429 self.custom,
430 [self.playlist_image, new_playlist.name, new_playlist],
431 )
432 self.tree.expand_row(self.model.get_path(self.custom), False)
433 # We are adding a completely new playlist with tracks so we save it
434 self.playlist_manager.save_playlist(new_playlist)
435 self._load_playlist_nodes(new_playlist)
436
437 def drag_get_data(self, tv, context, selection_data, info, time):
438 """
439 Called when the user drags a playlist from the radio panel
440 """
441 tracks = self.tree.get_selected_tracks()
442
443 if not tracks:
444 return
445
446 for track in tracks:
447 DragTreeView.dragged_data[track.get_loc_for_io()] = track
448
449 uris = trax.util.get_uris_from_tracks(tracks)
450 selection_data.set_uris(uris)
451
452 def drag_data_delete(self, *e):
453 """
454 stub
455 """
456 pass
457
458 def on_reload(self, *e):
459 """
460 Called when the refresh button is clicked
461 """
462 selection = self.tree.get_selection()
463 info = selection.get_selected_rows()
464 if not info:
465 return
466 (model, paths) = info
467 iter = self.model.get_iter(paths[0])
468 object = self.model.get_value(iter, 2)
469
470 try:
471 self.loaded_nodes.remove(self.nodes[object])
472 except ValueError:
473 pass
474
475 if isinstance(object, (xl.radio.RadioList, xl.radio.RadioStation)):
476 self._clear_node(iter)
477 self.load_nodes[object] = self.model.append(
478 iter, [self.refresh_image, _("Loading streams..."), None]
479 )
480
481 self.complete_reload[object] = True
482 self.tree.expand_row(self.model.get_path(iter), False)
483
484 @staticmethod
485 def set_station_expanded_value(station, value):
486 settings.set_option('gui/radio/%s_station_expanded' % station, True)
487
488 def on_row_expand(self, tree, iter, path):
489 """
490 Called when a user expands a row in the tree
491 """
492 driver = self.model.get_value(iter, 2)
493
494 if not isinstance(driver, xl.playlist.Playlist):
495 self.model.set_value(iter, 0, self.folder)
496
497 if isinstance(driver, xl.radio.RadioStation) or isinstance(
498 driver, xl.radio.RadioList
499 ):
500 if not self.nodes[driver] in self.loaded_nodes:
501 self._load_station(iter, driver)
502
503 if isinstance(driver, xl.radio.RadioStation):
504 self.set_station_expanded_value(driver.name, True)
505
506 def on_collapsed(self, tree, iter, path):
507 """
508 Called when someone collapses a tree item
509 """
510 driver = self.model.get_value(iter, 2)
511
512 if not isinstance(driver, xl.playlist.Playlist):
513 self.model.set_value(iter, 0, self.folder)
514
515 if isinstance(driver, xl.radio.RadioStation):
516 self.set_station_expanded_value(driver.name, False)
517
518 @common.threaded
519 def _load_station(self, iter, driver):
520 """
521 Loads a radio station
522 """
523 lists = None
524 no_cache = False
525 if driver in self.complete_reload:
526 no_cache = True
527 del self.complete_reload[driver]
528
529 if isinstance(driver, xl.radio.RadioStation):
530 try:
531 lists = driver.get_lists(no_cache=no_cache)
532 except RadioException as e:
533 self._set_status(str(e), 2)
534 else:
535 try:
536 lists = driver.get_items(no_cache=no_cache)
537 except RadioException as e:
538 self._set_status(str(e), 2)
539
540 if not lists:
541 return
542 GLib.idle_add(self._done_loading, iter, driver, lists)
543
544 def _done_loading(self, iter, object, items):
545 """
546 Called when an item is done loading. Adds items to the tree
547 """
548 self.loaded_nodes.append(self.nodes[object])
549 for item in items:
550 if isinstance(item, xl.radio.RadioList):
551 node = self.model.append(
552 self.nodes[object], [self.folder, item.name, item]
553 )
554 self.nodes[item] = node
555 self.load_nodes[item] = self.model.append(
556 node, [self.refresh_image, _("Loading streams..."), None]
557 )
558 else:
559 self.model.append(self.nodes[object], [self.track, item.name, item])
560
561 try:
562 self.model.remove(self.load_nodes[object])
563 del self.load_nodes[object]
564 except KeyError:
565 pass
566
567 def _clear_node(self, node):
568 """
569 Clears a node of all children
570 """
571 remove = []
572 iter = self.model.iter_children(node)
573 while iter:
574 remove.append(iter)
575 iter = self.model.iter_next(iter)
576 for row in remove:
577 self.model.remove(row)
578
579
580 def set_status(message, timeout=0):
581 RadioPanel._radiopanel._set_status(message, timeout)