Debian Codegraph @

xlgui/widgets/common.py

raw
1 # Copyright (C) 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 Shared GUI widgets
29 """
30
31 from collections import namedtuple
32 from urllib.parse import urlparse
33
34 from gi.repository import Gio
35 from gi.repository import Gdk
36 from gi.repository import GLib
37 from gi.repository import GObject
38 from gi.repository import Gtk
39
40 from xl import common, playlist as xl_playlist, trax
41
42 from xlgui import icons
43 from xlgui.guiutil import get_workarea_size
44
45
46 class AttachedWindow(Gtk.Window):
47 """
48 A window attachable to arbitrary widgets,
49 follows the movement of its parent
50 """
51
52 __gsignals__ = {'show': 'override'}
53
54 def __init__(self, parent):
55 Gtk.Window.__init__(self, Gtk.WindowType.TOPLEVEL)
56
57 self.set_decorated(False)
58 self.props.skip_taskbar_hint = True
59 self.set_keep_above(True)
60
61 # Only allow resizing
62 self.realize()
63 self.get_window().set_functions(Gdk.WMFunction.RESIZE)
64
65 self.parent_widget = parent
66 self.parent_window_connections = []
67 parent.connect('hierarchy-changed', self._on_parent_hierarchy_changed)
68
69 def update_location(self):
70 """
71 Makes sure the window is
72 always fully visible
73 """
74 workarea = Gdk.Rectangle()
75 workarea.x = workarea.y = 0
76 workarea.width, workarea.height = get_workarea_size()
77 parent_alloc = self.parent_widget.get_allocation()
78 toplevel_position = (
79 self.parent_widget.get_toplevel().get_window().get_position()
80 )
81 # Use absolute screen position
82 parent_alloc.x += toplevel_position[0]
83 parent_alloc.y += toplevel_position[1]
84
85 alloc = self.get_allocation()
86 if workarea.width - parent_alloc.x < alloc.width:
87 # Parent rightmost
88 x = parent_alloc.x + parent_alloc.width - alloc.width
89 else:
90 # Parent leftmost
91 x = parent_alloc.x
92
93 if workarea.height - parent_alloc.y < alloc.height:
94 # Parent at bottom
95 y = parent_alloc.y - alloc.height
96 else:
97 # Parent at top
98 y = parent_alloc.y + parent_alloc.height
99
100 self.move(x, y)
101
102 def do_show(self):
103 """
104 Updates the location upon show
105 """
106 Gtk.Window.do_show(self)
107 self.update_location()
108
109 def _on_parent_hierarchy_changed(self, parent_widget, previous_toplevel):
110 """(Dis)connect from/to the parent's toplevel window signals"""
111 conns = self.parent_window_connections
112 for conn in conns:
113 previous_toplevel.disconnect(conn)
114 conns[:] = ()
115 toplevel = parent_widget.get_toplevel()
116 if not isinstance(toplevel, Gtk.Window): # Not anchored
117 return
118 self.set_transient_for(toplevel)
119 conns.append(
120 toplevel.connect('configure-event', self._on_parent_window_configure_event)
121 )
122 conns.append(toplevel.connect('hide', self._on_parent_window_hide))
123
124 def _on_parent_window_configure_event(self, _widget, _event):
125 """Update location when parent window is moved"""
126 if self.props.visible:
127 self.update_location()
128
129 def _on_parent_window_hide(self, _window):
130 """Emit the "hide" signal on self when the parent window is hidden.
131
132 If there is a "transient for" relationship between two windows, when
133 the parent is hidden, the child is hidden without emitting "hide".
134 Here we manually emit it to simplify usage.
135 """
136 self.emit('hide')
137
138
139 class AutoScrollTreeView(Gtk.TreeView):
140 """
141 A TreeView which handles autoscrolling upon DnD operations
142 """
143
144 def __init__(self):
145 Gtk.TreeView.__init__(self)
146
147 self._SCROLL_EDGE_SIZE = 15 # As in gtktreeview.c
148 self.__autoscroll_timeout_id = None
149 self.__current_vertical_scroll = None
150
151 self.connect("drag-motion", self._on_drag_motion)
152 self.connect("drag-leave", self._on_drag_leave)
153 self.connect("size-allocate", self._on_size_allocate)
154
155 def _on_drag_motion(self, widget, context, x, y, timestamp):
156 """
157 Initiates automatic scrolling
158 """
159 if not self.__autoscroll_timeout_id:
160 self.__autoscroll_timeout_id = GLib.timeout_add(
161 50, self._on_autoscroll_timeout
162 )
163
164 def _on_drag_leave(self, widget, context, timestamp):
165 """
166 Stops automatic scrolling
167 """
168 autoscroll_timeout_id = self.__autoscroll_timeout_id
169
170 if autoscroll_timeout_id:
171 GLib.source_remove(autoscroll_timeout_id)
172 self.__autoscroll_timeout_id = None
173
174 self.__current_vertical_scroll = self.get_vadjustment().get_value()
175
176 def _on_size_allocate(self, plView, selection):
177 if self.__current_vertical_scroll:
178 # correction of vertical scroll
179 adj = self.get_vadjustment()
180 adj.set_value(self.__current_vertical_scroll)
181 self.__current_vertical_scroll = None
182
183 def _on_autoscroll_timeout(self):
184 """
185 Automatically scrolls during drag operations
186
187 Adapted from gtk_tree_view_vertical_autoscroll() in gtktreeview.c
188 """
189 _, x, y, _ = self.props.window.get_pointer()
190 x, y = self.convert_widget_to_tree_coords(x, y)
191 visible_rect = self.get_visible_rect()
192 # Calculate offset from the top edge
193 offset = y - (
194 visible_rect.y + 3 * self._SCROLL_EDGE_SIZE
195 ) # 3: Scroll faster upwards
196
197 # Check if we are near the bottom edge instead
198 if offset > 0:
199 # Calculate offset based on the bottom edge
200 offset = y - (
201 visible_rect.y + visible_rect.height - 2 * self._SCROLL_EDGE_SIZE
202 )
203
204 # Skip if we are not near to top or bottom edge
205 if offset < 0:
206 return True
207
208 vadjustment = self.get_vadjustment()
209 vadjustment.props.value = common.clamp(
210 vadjustment.props.value + offset,
211 0,
212 vadjustment.props.upper - vadjustment.props.page_size,
213 )
214 self.set_vadjustment(vadjustment)
215
216 return True
217
218
219 class DragTreeView(AutoScrollTreeView):
220 """
221 A TextView that does easy dragging/selecting/popup menu
222 """
223
224 class EventData(
225 namedtuple('DragTreeView_EventData', 'event modifier triggers_menu target')
226 ):
227 """
228 Objects that goes inside pending events list
229 """
230
231 class Target(
232 namedtuple('DragTreeView_EventData_Target', 'path column is_selected')
233 ):
234 """
235 Contains target path info
236 """
237
238 targets = [Gtk.TargetEntry.new("text/uri-list", 0, 0)]
239 dragged_data = dict()
240
241 def __init__(self, container, receive=True, source=True, drop_pos=None):
242 """
243 Initializes the tree and sets up the various callbacks
244 :param container: The container to place the TreeView into
245 :param receive: True if the TreeView should receive drag events
246 :param source: True if the TreeView should send drag events
247 :param drop_pos: Indicates where a drop operation should occur
248 w.r.t. existing entries: 'into', 'between', or None (both).
249 """
250 AutoScrollTreeView.__init__(self)
251 self.container = container
252 self.pending_events = []
253
254 if source:
255 self.drag_source_set(
256 Gdk.ModifierType.BUTTON1_MASK,
257 self.targets,
258 Gdk.DragAction.COPY | Gdk.DragAction.MOVE,
259 )
260
261 if receive:
262 self.drop_pos = drop_pos
263 self.drag_dest_set(
264 Gtk.DestDefaults.ALL,
265 self.targets,
266 Gdk.DragAction.COPY | Gdk.DragAction.DEFAULT | Gdk.DragAction.MOVE,
267 )
268 self.connect('drag_data_received', self.container.drag_data_received)
269 self.connect('drag_data_delete', self.container.drag_data_delete)
270 self.receive = receive
271 self.drag_context = None
272 self.show_cover_drag_icon = True
273 self.connect('drag-begin', self.on_drag_begin)
274 self.connect('drag-end', self.on_drag_end)
275 self.connect('drag-motion', self.on_drag_motion)
276 self.connect('button-release-event', self.on_button_release)
277 self.connect('button-press-event', self.on_button_press)
278
279 if source:
280 self.connect('drag-data-get', self.container.drag_get_data)
281 self.drag_source_set_icon_name('gtk-dnd')
282
283 def get_selected_tracks(self):
284 """
285 Returns the currently selected tracks (stub)
286 """
287 pass
288
289 def get_target_for(self, event):
290 """
291 Gets target
292 :see: Gtk.TreeView.get_path_at_pos
293 :param event: Gdk.Event
294 :return: DragTreeView.EventData.Target or None if no target path
295 """
296 target = self.get_path_at_pos(int(event.x), int(event.y))
297 if target:
298 return DragTreeView.EventData.Target(
299 path=target[0],
300 column=target[1],
301 is_selected=self.get_selection().path_is_selected(target[0]),
302 )
303
304 def set_cursor_at(self, target):
305 """
306 Sets the cursor at target
307 :param target: DragTreeView.EventData.Target
308 :return: None
309 """
310 self.set_cursor(target.path, target.column, False)
311
312 def set_selection_status(self, enabled):
313 """
314 Change the set selection function
315 :param enabled: bool
316 :return: None
317 """
318 self.get_selection().set_select_function(lambda *args: enabled, None)
319
320 def reset_selection_status(self):
321 """
322 Reset
323 :return: None
324 """
325 self.set_selection_status(True)
326 del self.pending_events[:]
327
328 def on_drag_end(self, list, context):
329 """
330 Called when the dnd is ended
331 """
332 self.drag_context = None
333 self.unset_rows_drag_dest()
334 self.drag_dest_set(
335 Gtk.DestDefaults.ALL,
336 self.targets,
337 Gdk.DragAction.COPY | Gdk.DragAction.MOVE,
338 )
339
340 def on_drag_begin(self, widget, context):
341 """
342 Sets the cover of dragged tracks as drag icon
343 """
344 self.drag_context = context
345 Gdk.drag_abort(context, Gtk.get_current_event_time())
346
347 self.reset_selection_status()
348
349 # Load covers
350 drag_cover_icon = None
351 get_tracks_for_path = getattr(self, 'get_tracks_for_path', None)
352 if get_tracks_for_path:
353 model, paths = self.get_selection().get_selected_rows()
354 drag_cover_icon = icons.MANAGER.get_drag_cover_icon(
355 map(get_tracks_for_path, paths)
356 )
357
358 if drag_cover_icon is None:
359 # Set default icon
360 icon_name = (
361 'gtk-dnd-multiple'
362 if self.get_selection().count_selected_rows() > 1
363 else 'gtk-dnd'
364 )
365 Gtk.drag_set_icon_name(context, icon_name, 0, 0)
366 else:
367 Gtk.drag_set_icon_pixbuf(context, drag_cover_icon, 0, 0)
368
369 def on_drag_motion(self, treeview, context, x, y, timestamp):
370 """
371 Called when a row is dragged over this treeview
372 """
373 if not self.receive:
374 return False
375 self.enable_model_drag_dest(self.targets, Gdk.DragAction.DEFAULT)
376 if self.drop_pos is None:
377 return False
378 info = treeview.get_dest_row_at_pos(x, y)
379 if not info:
380 return False
381 path, pos = info
382 if self.drop_pos == 'into':
383 # Only allow dropping into entries.
384 if pos == Gtk.TreeViewDropPosition.BEFORE:
385 pos = Gtk.TreeViewDropPosition.INTO_OR_BEFORE
386 elif pos == Gtk.TreeViewDropPosition.AFTER:
387 pos = Gtk.TreeViewDropPosition.INTO_OR_AFTER
388 elif self.drop_pos == 'between':
389 # Only allow dropping between entries.
390 if pos == Gtk.TreeViewDropPosition.INTO_OR_BEFORE:
391 pos = Gtk.TreeViewDropPosition.BEFORE
392 elif pos == Gtk.TreeViewDropPosition.INTO_OR_AFTER:
393 pos = Gtk.TreeViewDropPosition.AFTER
394 treeview.set_drag_dest_row(path, pos)
395 context.drag_status(context.suggested_action, timestamp)
396 return True
397
398 def on_button_press(self, button, event):
399 """
400 Called when a button is pressed
401 """
402 # Always grab focus is a workaround to do not loose first click
403 self.grab_focus()
404
405 self.reset_selection_status()
406
407 # Only treats 1st button press
408 if event.type == Gdk.EventType.BUTTON_PRESS:
409 modifier = event.state & Gtk.accelerator_get_default_mod_mask()
410 target = self.get_target_for(event)
411
412 if target is None:
413 if modifier == 0:
414 # Unselects items if the user press any mouse button on an
415 # empty area of the TreeView and no modifier key is active
416 self.get_selection().unselect_all()
417
418 return True # Ignore clicks on empty areas
419
420 # Declare
421 triggers_menu = event.triggers_context_menu()
422
423 # Disable select function to to do not modify selection
424 # Triggering menu will only accept selection
425 if target.is_selected and (not modifier or triggers_menu):
426 self.set_selection_status(False)
427
428 # If it's not a DnD, it will be treated at button release event
429 self.pending_events.append(
430 DragTreeView.EventData(event, modifier, triggers_menu, target)
431 )
432
433 # Calls `button_press` function on container (if present)
434 try:
435 button_press_function = self.container.button_press
436 except AttributeError:
437 return False
438 else:
439 return button_press_function(button, event)
440
441 def on_button_release(self, button, event):
442 """
443 Called when a button is released
444 Treats the pending events added at button press event
445
446 Handles the popup menu that is displayed when you right click in
447 the TreeView list (calls `container.menu` if present)
448 """
449 self.drag_context = None
450
451 # Get pending event
452 try:
453 event_data = self.pending_events.pop()
454 except IndexError:
455 return False
456
457 self.reset_selection_status()
458
459 # Do not set cursor if has a modifier key pressed
460 if event_data.modifier == 0 and not (
461 event_data.triggers_menu and event_data.target.is_selected
462 ):
463 self.set_cursor_at(event_data.target)
464
465 if event_data.triggers_menu:
466 # Uses menu from container (if present)
467 menu = getattr(self.container, 'menu', None)
468 if menu:
469 menu.popup(event_data.event)
470 return True
471
472 return False
473
474 # TODO maybe move this somewhere else? (along with _handle_unknown_drag_data)
475 def get_drag_data(self, locs, compile_tracks=True, existing_tracks=[]):
476 """
477 Handles the locations from drag data
478
479 @param locs: locations we are dealing with (can
480 be anything from a file to a folder)
481 @param compile_tracks: if true any tracks in the playlists
482 that are not found as tracks are added to the list of tracks
483 @param existing_tracks: a list of tracks that have already
484 been loaded from files (used to skip loading the dragged
485 tracks from the filesystem)
486
487 @returns: a 2 tuple in which the first part is a list of tracks
488 and the second is a list of playlist (note: any files that are
489 in a playlist are not added to the list of tracks, but a track could
490 be both in as a found track and part of a playlist)
491 """
492 # TODO handle if they pass in existing tracks
493 trs = []
494 playlists = []
495 for loc in locs:
496 (found_tracks, found_playlist) = self._handle_unknown_drag_data(loc)
497 trs.extend(found_tracks)
498 playlists.extend(found_playlist)
499
500 if compile_tracks:
501 # Add any tracks in the playlist to the master list of tracks
502 for playlist in playlists:
503 for track in playlist.get_tracks():
504 if track not in trs:
505 trs.append(track)
506
507 return (trs, playlists)
508
509 def _handle_unknown_drag_data(self, loc):
510 """
511 Handles unknown drag data that has been received by
512 drag_data_received. Unknown drag data is classified as
513 any loc (location) that is not in the collection of tracks
514 (i.e. a new song, or a new playlist)
515
516 @param loc:
517 the location of the unknown drag data
518
519 @returns: a 2 tuple in which the first part is a list of tracks
520 and the second is a list of playlist
521 """
522 filetype = None
523 info = urlparse(loc)
524
525 # don't use gio to test the filetype if it's a non-local file
526 # (otherwise gio will try to connect to every remote url passed in and
527 # cause the gui to hang)
528 if info.scheme in ('file', ''):
529 try:
530 filetype = (
531 Gio.File.new_for_uri(loc)
532 .query_info('standard::type', Gio.FileQueryInfoFlags.NONE, None)
533 .get_file_type()
534 )
535 except GLib.Error:
536 filetype = None
537
538 if trax.is_valid_track(loc) or info.scheme not in ('file', ''):
539 new_track = trax.Track(loc)
540 return ([new_track], [])
541 elif xl_playlist.is_valid_playlist(loc):
542 # User is dragging a playlist into the playlist list
543 # so we add all of the songs in the playlist
544 # to the list
545 new_playlist = xl_playlist.import_playlist(loc)
546 return ([], [new_playlist])
547 elif filetype == Gio.FileType.DIRECTORY:
548 return (trax.get_tracks_from_uri(loc), [])
549 else: # We don't know what they dropped
550 return ([], [])
551
552
553 class ClickableCellRendererPixbuf(Gtk.CellRendererPixbuf):
554 """
555 Custom :class:`Gtk.CellRendererPixbuf` emitting
556 an *clicked* signal upon activation of the pixbuf
557 """
558
559 __gsignals__ = {
560 'clicked': (
561 GObject.SignalFlags.RUN_LAST,
562 GObject.TYPE_BOOLEAN,
563 (GObject.TYPE_PYOBJECT,),
564 GObject.signal_accumulator_true_handled,
565 )
566 }
567
568 def __init__(self):
569 Gtk.CellRendererPixbuf.__init__(self)
570 self.props.mode = Gtk.CellRendererMode.ACTIVATABLE
571
572 def do_activate(self, event, widget, path, background_area, cell_area, flags):
573 """
574 Emits the *clicked* signal
575 """
576 self.emit('clicked', path)
577 return