Debian Codegraph @

xlgui/widgets/dialogs.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 import logging
28 import os.path
29 from threading import Thread
30 from typing import Iterable, Optional, Union
31
32 from gi.repository import (
33 Gdk,
34 GdkPixbuf,
35 Gio,
36 GLib,
37 GObject,
38 Gtk,
39 Pango,
40 )
41
42 from xl import metadata, providers, settings, xdg
43 from xl.common import clamp
44 from xl.playlist import (
45 is_valid_playlist,
46 import_playlist,
47 export_playlist,
48 InvalidPlaylistTypeError,
49 PlaylistExportOptions,
50 )
51 from xl.nls import gettext as _
52 from xlgui import guiutil
53 from xlgui.guiutil import GtkTemplate
54
55 logger = logging.getLogger(__name__)
56
57
58 def error(parent, message=None, markup=None):
59 """
60 Shows an error dialog
61 """
62 if message is markup is None:
63 raise ValueError("message or markup must be specified")
64 dialog = Gtk.MessageDialog(
65 buttons=Gtk.ButtonsType.CLOSE,
66 message_type=Gtk.MessageType.ERROR,
67 modal=True,
68 transient_for=parent,
69 )
70 if markup is None:
71 dialog.props.text = message
72 else:
73 dialog.set_markup(markup)
74 dialog.run()
75 dialog.destroy()
76
77
78 def info(parent, message=None, markup=None):
79 """
80 Shows an info dialog
81 """
82 if message is markup is None:
83 raise ValueError("message or markup must be specified")
84 dialog = Gtk.MessageDialog(
85 buttons=Gtk.ButtonsType.OK,
86 message_type=Gtk.MessageType.INFO,
87 modal=True,
88 transient_for=parent,
89 )
90 if markup is None:
91 dialog.props.text = message
92 else:
93 dialog.set_markup(markup)
94 dialog.run()
95 dialog.destroy()
96
97
98 def yesno(parent, message):
99 '''Gets a Yes/No response from a user'''
100 dlg = Gtk.MessageDialog(
101 buttons=Gtk.ButtonsType.YES_NO,
102 message_type=Gtk.MessageType.QUESTION,
103 text=message,
104 transient_for=parent,
105 )
106 response = dlg.run()
107 dlg.destroy()
108 return response
109
110
111 @GtkTemplate('ui', 'about_dialog.ui')
112 class AboutDialog(Gtk.AboutDialog):
113 """
114 A dialog showing program info and more
115 """
116
117 __gtype_name__ = 'AboutDialog'
118
119 def __init__(self, parent=None):
120 Gtk.AboutDialog.__init__(self)
121 self.init_template()
122
123 self.set_transient_for(parent)
124 logo = GdkPixbuf.Pixbuf.new_from_file(
125 xdg.get_data_path('images', 'exailelogo.png')
126 )
127 self.set_logo(logo)
128
129 import xl.version
130
131 self.set_version(xl.version.__version__)
132
133 # The user may have changed the theme since startup.
134 theme = Gtk.Settings.get_default().props.gtk_theme_name
135 xl.version.__external_versions__["GTK+ theme"] = theme
136
137 comments = []
138 for name, version in sorted(xl.version.__external_versions__.items()):
139 comments.append('%s: %s' % (name, version))
140
141 self.set_comments('\n'.join(comments))
142
143 def on_response(self, *_):
144 self.destroy()
145
146
147 @GtkTemplate('ui', 'shortcuts_dialog.ui')
148 class ShortcutsDialog(Gtk.Dialog):
149 """
150 Shows information about registered shortcuts
151
152 TODO: someday upgrade to Gtk.ShortcutsWindow when we require 3.20 as
153 a minimum GTK version. This would also enable automatically
154 localized (translated) accelerator names.
155 """
156
157 # doesn't work if we don't set the treeview here too..
158 shortcuts_treeview, shortcuts_model = GtkTemplate.Child.widgets(2)
159
160 __gtype_name__ = 'ShortcutsDialog'
161
162 def __init__(self, parent=None):
163 Gtk.Dialog.__init__(self)
164 self.init_template()
165
166 self.set_transient_for(parent)
167
168 for a in sorted(
169 providers.get('mainwindow-accelerators'),
170 key=lambda a: ('%04d' % (a.key)) + a.name,
171 ):
172 self.shortcuts_model.append(
173 (Gtk.accelerator_get_label(a.key, a.mods), a.helptext.replace('_', ''))
174 )
175
176 @GtkTemplate.Callback
177 def on_close_clicked(self, widget):
178 self.destroy()
179
180
181 class MultiTextEntryDialog(Gtk.Dialog):
182 """
183 Exactly like a TextEntryDialog, except it can contain multiple
184 labels/fields.
185
186 Instead of using GetValue, use GetValues. It will return a list with
187 the contents of the fields. Each field must be filled out or the dialog
188 will not close.
189 """
190
191 def __init__(self, parent, title):
192 Gtk.Dialog.__init__(self, title=title, transient_for=parent)
193
194 self.__entry_area = Gtk.Grid()
195 self.__entry_area.set_row_spacing(3)
196 self.__entry_area.set_column_spacing(3)
197 self.__entry_area.set_border_width(3)
198 self.vbox.pack_start(self.__entry_area, True, True, 0)
199
200 self.add_buttons(
201 Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK
202 )
203
204 self.fields = []
205
206 def add_field(self, label: str, value: str = None, tooltip: str = None):
207 """
208 Adds a field and corresponding label
209
210 :param label: the label to display
211 :param value: the text in entry field
212 :param tooltip: a tooltip to show
213 :returns: the newly created entry
214 :rtype: :class:`Gtk.Entry`
215 """
216 line_number = len(self.fields)
217
218 label = Gtk.Label(label=label)
219 label.set_xalign(0)
220 self.__entry_area.attach(label, 0, line_number, 1, 1)
221
222 entry = Gtk.Entry()
223 entry.set_width_chars(30)
224 entry.set_icon_activatable(Gtk.EntryIconPosition.SECONDARY, False)
225 entry.connect('activate', lambda *e: self.response(Gtk.ResponseType.OK))
226
227 if value is not None:
228 entry.set_text(value)
229
230 if tooltip is not None:
231 entry.set_icon_from_icon_name(
232 Gtk.EntryIconPosition.SECONDARY, 'dialog-information'
233 )
234 entry.set_icon_tooltip_text(Gtk.EntryIconPosition.SECONDARY, tooltip)
235
236 self.__entry_area.attach(entry, 1, line_number, 1, 1)
237 label.show()
238 entry.show()
239
240 self.fields.append(entry)
241
242 return entry
243
244 def get_values(self):
245 """
246 Returns a list of the values from the added fields
247 """
248 return [a.get_text() for a in self.fields]
249
250 def run(self):
251 """
252 Shows the dialog, runs, hides, and returns
253 """
254 self.show_all()
255
256 while True:
257 response = Gtk.Dialog.run(self)
258
259 if response in (Gtk.ResponseType.CANCEL, Gtk.ResponseType.DELETE_EVENT):
260 break
261
262 if response == Gtk.ResponseType.OK:
263 # Leave loop if all fields where filled
264 if len(min([f.get_text() for f in self.fields])) > 0:
265 break
266
267 # At least one field was not filled
268 for field in self.fields:
269 if len(field.get_text()) > 0:
270 # Unset possible previous marks
271 field.set_icon_from_icon_name(
272 Gtk.EntryIconPosition.SECONDARY, None
273 )
274 else:
275 # Mark via warning
276 field.set_icon_from_icon_name(
277 Gtk.EntryIconPosition.SECONDARY, 'dialog-warning'
278 )
279 self.hide()
280
281 return response
282
283
284 class TextEntryDialog(Gtk.Dialog):
285 """
286 Shows a dialog with a single line of text
287 """
288
289 def __init__(
290 self,
291 message,
292 title,
293 default_text=None,
294 parent=None,
295 cancelbutton=None,
296 okbutton=None,
297 ):
298 """
299 Initializes the dialog
300 """
301 if not cancelbutton:
302 cancelbutton = Gtk.STOCK_CANCEL
303 if not okbutton:
304 okbutton = Gtk.STOCK_OK
305 Gtk.Dialog.__init__(
306 self, title=title, transient_for=parent, destroy_with_parent=True
307 )
308
309 self.add_buttons(
310 cancelbutton, Gtk.ResponseType.CANCEL, okbutton, Gtk.ResponseType.OK
311 )
312
313 label = Gtk.Label(label=message)
314 label.set_xalign(0)
315 self.vbox.set_border_width(5)
316
317 main = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
318 main.set_spacing(3)
319 main.set_border_width(5)
320 self.vbox.pack_start(main, True, True, 0)
321
322 main.pack_start(label, False, False, 0)
323
324 self.entry = Gtk.Entry()
325 self.entry.set_width_chars(35)
326 if default_text:
327 self.entry.set_text(default_text)
328 main.pack_start(self.entry, False, False, 0)
329
330 self.entry.connect('activate', lambda e: self.response(Gtk.ResponseType.OK))
331
332 def get_value(self):
333 """
334 Returns the text value
335 """
336 return self.entry.get_text()
337
338 def set_value(self, value):
339 """
340 Sets the value of the text
341 """
342 self.entry.set_text(value)
343
344 def run(self):
345 self.show_all()
346 response = Gtk.Dialog.run(self)
347 self.hide()
348 return response
349
350
351 class URIOpenDialog(TextEntryDialog):
352 """
353 A dialog specialized for opening an URI
354 """
355
356 __gsignals__ = {
357 'uri-selected': (
358 GObject.SignalFlags.RUN_LAST,
359 GObject.TYPE_BOOLEAN,
360 (GObject.TYPE_PYOBJECT,),
361 GObject.signal_accumulator_true_handled,
362 )
363 }
364
365 def __init__(self, parent=None):
366 """
367 :param parent: a parent window for modal operation or None
368 :type parent: :class:`Gtk.Window`
369 """
370 TextEntryDialog.__init__(
371 self, message=_('Enter the URL to open'), title=_('Open URL'), parent=parent
372 )
373
374 self.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)
375
376 self.connect('response', self.on_response)
377
378 def run(self):
379 """
380 Show the dialog and block until it's closed.
381
382 The dialog will be automatically destroyed on user response.
383 To obtain the entered URI, handle the "uri-selected" signal.
384 """
385 self.show()
386 response = TextEntryDialog.run(self)
387 self.emit('response', response)
388
389 def show(self):
390 """
391 Show the dialog and return immediately.
392
393 The dialog will be automatically destroyed on user response.
394 To obtain the entered URI, handle the "uri-selected" signal.
395 """
396 clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
397 text = clipboard.wait_for_text()
398
399 if text is not None:
400 f = Gio.File.new_for_uri(text)
401 if f.get_uri_scheme():
402 self.set_value(text)
403
404 TextEntryDialog.show_all(self)
405
406 def do_uri_selected(self, uri):
407 """
408 Destroys the dialog
409 """
410 self.destroy()
411
412 def on_response(self, dialog, response):
413 """
414 Notifies about the selected URI
415 """
416 self.hide()
417
418 if response == Gtk.ResponseType.OK:
419 self.emit('uri-selected', self.get_value())
420
421 # self.destroy()
422
423 '''
424 dialog = dialogs.TextEntryDialog(_('Enter the URL to open'),
425 _('Open URL'))
426 dialog.set_transient_for(self.main.window)
427 dialog.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)
428
429 clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
430 text = clipboard.wait_for_text()
431
432 if text is not None:
433 location = Gio.File.new_for_uri(text)
434
435 if location.get_uri_scheme() is not None:
436 dialog.set_value(text)
437
438 result = dialog.run()
439 dialog.hide()
440 if result == Gtk.ResponseType.OK:
441 url = dialog.get_value()
442 self.open_uri(url, play=False)
443 '''
444
445
446 class ListDialog(Gtk.Dialog):
447 """
448 Shows a dialog with a list of specified items
449
450 Items must define a __str__ method, or be a string
451 """
452
453 def __init__(self, title, parent=None, multiple=False, write_only=False):
454 """
455 Initializes the dialog
456 """
457 Gtk.Dialog.__init__(self, title=title, transient_for=parent)
458
459 self.vbox.set_border_width(5)
460 scroll = Gtk.ScrolledWindow()
461 scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
462 self.model = Gtk.ListStore(object)
463 self.list = Gtk.TreeView(model=self.model)
464 self.list.set_headers_visible(False)
465 self.list.connect(
466 'row-activated', lambda *e: self.response(Gtk.ResponseType.OK)
467 )
468 scroll.add(self.list)
469 scroll.set_shadow_type(Gtk.ShadowType.IN)
470 self.vbox.pack_start(scroll, True, True, 0)
471
472 if write_only:
473 self.add_buttons(Gtk.STOCK_OK, Gtk.ResponseType.OK)
474 else:
475 self.add_buttons(
476 Gtk.STOCK_CANCEL,
477 Gtk.ResponseType.CANCEL,
478 Gtk.STOCK_OK,
479 Gtk.ResponseType.OK,
480 )
481
482 self.selection = self.list.get_selection()
483
484 if multiple:
485 self.selection.set_mode(Gtk.SelectionMode.MULTIPLE)
486 else:
487 self.selection.set_mode(Gtk.SelectionMode.SINGLE)
488
489 text = Gtk.CellRendererText()
490 col = Gtk.TreeViewColumn()
491 col.pack_start(text, True)
492
493 col.set_cell_data_func(text, self.cell_data_func)
494 self.list.append_column(col)
495 self.list.set_model(self.model)
496 self.resize(400, 240)
497
498 def get_items(self):
499 """
500 Returns the selected items
501 """
502 items = []
503 check = self.selection.get_selected_rows()
504 if not check:
505 return None
506 (model, paths) = check
507
508 for path in paths:
509 iter = self.model.get_iter(path)
510 item = self.model.get_value(iter, 0)
511 items.append(item)
512
513 return items
514
515 def run(self):
516 self.show_all()
517 result = Gtk.Dialog.run(self)
518 self.hide()
519 return result
520
521 def set_items(self, items):
522 """
523 Sets the items
524 """
525 for item in items:
526 self.model.append([item])
527
528 def cell_data_func(self, column, cell, model, iter, user_data):
529 """
530 Called when the tree needs a value for column 1
531 """
532 object = model.get_value(iter, 0)
533 cell.set_property('text', str(object))
534
535
536 # TODO: combine this and list dialog
537
538
539 class ListBox:
540 """
541 Represents a list box
542 """
543
544 def __init__(self, widget, rows=None):
545 """
546 Initializes the widget
547 """
548 self.list = widget
549 self.store = Gtk.ListStore(str)
550 widget.set_headers_visible(False)
551 cell = Gtk.CellRendererText()
552 col = Gtk.TreeViewColumn('', cell, text=0)
553 self.list.append_column(col)
554 self.rows = rows
555 if not rows:
556 self.rows = []
557
558 if rows:
559 for row in rows:
560 self.store.append([row])
561
562 self.list.set_model(self.store)
563
564 def connect(self, signal, func, data=None):
565 """
566 Connects a signal to the underlying treeview
567 """
568 self.list.connect(signal, func, data)
569
570 def append(self, row):
571 """
572 Appends a row to the list
573 """
574 self.rows.append(row)
575 self.set_rows(self.rows)
576
577 def remove(self, row):
578 """
579 Removes a row
580 """
581 try:
582 index = self.rows.index(row)
583 except ValueError:
584 return
585 path = (index,)
586 iter = self.store.get_iter(path)
587 self.store.remove(iter)
588 del self.rows[index]
589
590 def set_rows(self, rows):
591 """
592 Sets the rows
593 """
594 self.rows = rows
595 self.store = Gtk.ListStore(str)
596 for row in rows:
597 self.store.append([row])
598
599 self.list.set_model(self.store)
600
601 def get_selection(self):
602 """
603 Returns the selection
604 """
605 selection = self.list.get_selection()
606 (model, iter) = selection.get_selected()
607 if not iter:
608 return None
609 return model.get_value(iter, 0)
610
611
612 class FileOperationDialog(Gtk.FileChooserDialog):
613 """
614 An extension of the Gtk.FileChooserDialog that
615 adds a collapsible panel to the bottom listing
616 valid file extensions that the file can be
617 saved in. (similar to the one in GIMP)
618 """
619
620 def __init__(
621 self,
622 title: str = None,
623 parent: Optional[Gtk.Window] = None,
624 action: Gtk.FileChooserAction = Gtk.FileChooserAction.OPEN,
625 buttons: Optional[Iterable[Union[str, int]]] = None,
626 backend=None,
627 ):
628 """
629 Standard __init__ of the Gtk.FileChooserDialog.
630 Also sets up the expander and list for extensions
631 """
632 Gtk.FileChooserDialog.__init__(self, title, parent, action, buttons, backend)
633
634 self.set_do_overwrite_confirmation(True)
635
636 # Container for additional option widgets
637 self.extras_box = Gtk.Box(spacing=3, orientation=Gtk.Orientation.VERTICAL)
638 self.set_extra_widget(self.extras_box)
639 self.extras_box.show()
640
641 # Create the list that will hold the file type/extensions pair
642 self.liststore = Gtk.ListStore(str, str)
643 self.list = Gtk.TreeView(model=self.liststore)
644 self.list.set_headers_visible(False)
645
646 # Create the columns
647 filetype_cell = Gtk.CellRendererText()
648 extension_cell = Gtk.CellRendererText()
649 column = Gtk.TreeViewColumn()
650 column.pack_start(filetype_cell, True)
651 column.pack_start(extension_cell, False)
652 column.set_attributes(filetype_cell, text=0)
653 column.set_attributes(extension_cell, text=1)
654
655 self.list.append_column(column)
656 self.list.show_all()
657
658 self.expander = Gtk.Expander.new(_('Select File Type (by Extension)'))
659 self.expander.add(self.list)
660 self.extras_box.pack_start(self.expander, False, False, 0)
661 self.expander.show()
662
663 selection = self.list.get_selection()
664 selection.connect('changed', self.on_selection_changed)
665
666 def on_selection_changed(self, selection):
667 """
668 When the user selects an extension the filename
669 that is entered will have its extension changed
670 to the selected extension
671 """
672 model, iter = selection.get_selected()
673 (extension,) = model.get(iter, 1)
674 filename = ""
675 if self.get_filename():
676 filename = os.path.basename(self.get_filename())
677 filename, old_extension = os.path.splitext(filename)
678 filename += '.' + extension
679 else:
680 filename = '*.' + extension
681 self.set_current_name(filename)
682
683 def add_extensions(self, extensions):
684 """
685 Adds extensions to the list
686
687 @param extensions: a dictionary of extension:file type pairs
688 i.e. { 'm3u':'M3U Playlist' }
689 """
690 for key, value in extensions.items():
691 self.liststore.append((value, key))
692
693
694 class MediaOpenDialog(Gtk.FileChooserDialog):
695 """
696 A dialog for opening general media
697 """
698
699 __gsignals__ = {
700 'uris-selected': (
701 GObject.SignalFlags.RUN_LAST,
702 GObject.TYPE_BOOLEAN,
703 (GObject.TYPE_PYOBJECT,),
704 GObject.signal_accumulator_true_handled,
705 )
706 }
707 _last_location = None
708
709 def __init__(self, parent=None):
710 """
711 :param parent: a parent window for modal operation or None
712 :type parent: :class:`Gtk.Window`
713 """
714 Gtk.FileChooserDialog.__init__(
715 self,
716 title=_('Choose Media to Open'),
717 parent=parent,
718 buttons=(
719 Gtk.STOCK_CANCEL,
720 Gtk.ResponseType.CANCEL,
721 Gtk.STOCK_OPEN,
722 Gtk.ResponseType.OK,
723 ),
724 )
725
726 self.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)
727 self.set_local_only(False)
728 self.set_select_multiple(True)
729
730 supported_filter = Gtk.FileFilter()
731 supported_filter.set_name(_('Supported Files'))
732 audio_filter = Gtk.FileFilter()
733 audio_filter.set_name(_('Music Files'))
734 playlist_filter = Gtk.FileFilter()
735 playlist_filter.set_name(_('Playlist Files'))
736 all_filter = Gtk.FileFilter()
737 all_filter.set_name(_('All Files'))
738 all_filter.add_pattern('*')
739
740 for extension in metadata.formats.keys():
741 pattern = '*.%s' % extension
742 supported_filter.add_pattern(pattern)
743 audio_filter.add_pattern(pattern)
744
745 playlist_file_extensions = (
746 ext
747 for p in providers.get('playlist-format-converter')
748 for ext in p.file_extensions
749 )
750
751 for extension in playlist_file_extensions:
752 pattern = '*.%s' % extension
753 supported_filter.add_pattern(pattern)
754 playlist_filter.add_pattern(pattern)
755
756 self.add_filter(supported_filter)
757 self.add_filter(audio_filter)
758 self.add_filter(playlist_filter)
759 self.add_filter(all_filter)
760
761 self.connect('response', self.on_response)
762
763 def run(self):
764 """
765 Override to take care of the response
766 """
767 if MediaOpenDialog._last_location is not None:
768 self.set_current_folder_uri(MediaOpenDialog._last_location)
769
770 response = Gtk.FileChooserDialog.run(self)
771 self.emit('response', response)
772
773 def show(self):
774 """
775 Override to restore last location
776 """
777 if MediaOpenDialog._last_location is not None:
778 self.set_current_folder_uri(MediaOpenDialog._last_location)
779
780 Gtk.FileChooserDialog.show(self)
781
782 def do_uris_selected(self, uris):
783 """
784 Destroys the dialog
785 """
786 self.destroy()
787
788 def on_response(self, dialog, response):
789 """
790 Notifies about selected URIs
791 """
792 self.hide()
793
794 if response == Gtk.ResponseType.OK:
795 MediaOpenDialog._last_location = self.get_current_folder_uri()
796 self.emit('uris-selected', self.get_uris())
797
798 # self.destroy()
799
800
801 class DirectoryOpenDialog(Gtk.FileChooserDialog):
802 """
803 A dialog specialized for opening directories
804 """
805
806 __gsignals__ = {
807 'uris-selected': (
808 GObject.SignalFlags.RUN_LAST,
809 GObject.TYPE_BOOLEAN,
810 (GObject.TYPE_PYOBJECT,),
811 GObject.signal_accumulator_true_handled,
812 )
813 }
814 _last_location = None
815
816 def __init__(
817 self,
818 parent: Optional[Gtk.Window] = None,
819 title: str = _('Choose Directory to Open'),
820 select_multiple: bool = True,
821 ):
822 Gtk.FileChooserDialog.__init__(self, title=title, transient_for=parent)
823
824 self.add_buttons(
825 Gtk.STOCK_CANCEL,
826 Gtk.ResponseType.CANCEL,
827 Gtk.STOCK_OPEN,
828 Gtk.ResponseType.OK,
829 )
830 self.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)
831 self.set_action(Gtk.FileChooserAction.SELECT_FOLDER)
832 self.set_local_only(False)
833 self.set_select_multiple(select_multiple)
834
835 self.connect('response', self.on_response)
836
837 def run(self):
838 """
839 Override to take care of the response
840 """
841 if DirectoryOpenDialog._last_location is not None:
842 self.set_current_folder_uri(DirectoryOpenDialog._last_location)
843
844 Gtk.FileChooserDialog.run(self)
845
846 def show(self):
847 """
848 Override to restore last location
849 """
850 if DirectoryOpenDialog._last_location is not None:
851 self.set_current_folder_uri(DirectoryOpenDialog._last_location)
852
853 Gtk.FileChooserDialog.show(self)
854
855 def do_uris_selected(self, uris):
856 """
857 Destroys the dialog
858 """
859 self.destroy()
860
861 def on_response(self, dialog, response):
862 """
863 Notifies about selected URIs
864 """
865 self.hide()
866
867 if response == Gtk.ResponseType.OK:
868 DirectoryOpenDialog._last_location = self.get_current_folder_uri()
869 self.emit('uris-selected', self.get_uris())
870
871 # self.destroy()
872
873
874 class PlaylistImportDialog(Gtk.FileChooserDialog):
875 """
876 A dialog for importing a playlist
877 """
878
879 __gsignals__ = {
880 'playlists-selected': (
881 GObject.SignalFlags.RUN_LAST,
882 GObject.TYPE_BOOLEAN,
883 (GObject.TYPE_PYOBJECT,),
884 GObject.signal_accumulator_true_handled,
885 )
886 }
887 _last_location = None
888
889 def __init__(self, parent=None):
890 """
891 :param parent: a parent window for modal operation or None
892 :type parent: :class:`Gtk.Window`
893 """
894 Gtk.FileChooserDialog.__init__(
895 self,
896 title=_('Import Playlist'),
897 parent=parent,
898 buttons=(
899 Gtk.STOCK_CANCEL,
900 Gtk.ResponseType.CANCEL,
901 Gtk.STOCK_OPEN,
902 Gtk.ResponseType.OK,
903 ),
904 )
905
906 self.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)
907 self.set_local_only(False)
908 self.set_select_multiple(True)
909
910 playlist_filter = Gtk.FileFilter()
911 playlist_filter.set_name(_('Playlist Files'))
912 all_filter = Gtk.FileFilter()
913 all_filter.set_name(_('All Files'))
914 all_filter.add_pattern('*')
915
916 playlist_file_extensions = (
917 ext
918 for p in providers.get('playlist-format-converter')
919 for ext in p.file_extensions
920 )
921
922 for extension in playlist_file_extensions:
923 pattern = '*.%s' % extension
924 playlist_filter.add_pattern(pattern)
925
926 self.add_filter(playlist_filter)
927 self.add_filter(all_filter)
928
929 self.connect('response', self.on_response)
930
931 def run(self):
932 """
933 Override to take care of the response
934 """
935 if PlaylistImportDialog._last_location is not None:
936 self.set_current_folder_uri(PlaylistImportDialog._last_location)
937
938 response = Gtk.FileChooserDialog.run(self)
939 self.emit('response', response)
940
941 def show(self):
942 """
943 Override to restore last location
944 """
945 if PlaylistImportDialog._last_location is not None:
946 self.set_current_folder_uri(PlaylistImportDialog._last_location)
947
948 Gtk.FileChooserDialog.show(self)
949
950 def do_playlist_selected(self, uris):
951 """
952 Destroys the dialog
953 """
954 self.destroy()
955
956 def on_response(self, dialog, response):
957 """
958 Notifies about selected URIs
959 """
960 self.hide()
961
962 if response == Gtk.ResponseType.OK:
963 PlaylistImportDialog._last_location = self.get_current_folder_uri()
964
965 playlists = []
966 for uri in self.get_uris():
967 try:
968 playlists.append(import_playlist(uri))
969 except InvalidPlaylistTypeError as e:
970 error(
971 self.get_transient_for(), 'Invalid playlist "%s": %s' % (uri, e)
972 )
973 self.destroy()
974 return
975 except Exception as e:
976 error(
977 self.get_transient_for(),
978 'Invalid playlist "%s": (internal error): %s' % (uri, e),
979 )
980 self.destroy()
981 return
982
983 self.emit('playlists-selected', playlists)
984
985 # self.destroy()
986
987
988 class PlaylistExportDialog(FileOperationDialog):
989 """
990 A dialog specialized for playlist export
991 """
992
993 __gsignals__ = {
994 'message': (
995 GObject.SignalFlags.RUN_LAST,
996 GObject.TYPE_BOOLEAN,
997 (Gtk.MessageType, GObject.TYPE_STRING),
998 GObject.signal_accumulator_true_handled,
999 )
1000 }
1001
1002 def __init__(self, playlist, parent=None):
1003 """
1004 :param playlist: the playlist to export
1005 :type playlist: :class:`xl.playlist.Playlist`
1006 :param parent: a parent window for modal operation or None
1007 :type parent: :class:`Gtk.Window`
1008 """
1009 FileOperationDialog.__init__(
1010 self,
1011 title=_('Export Current Playlist'),
1012 parent=parent,
1013 action=Gtk.FileChooserAction.SAVE,
1014 buttons=(
1015 Gtk.STOCK_CANCEL,
1016 Gtk.ResponseType.CANCEL,
1017 Gtk.STOCK_SAVE,
1018 Gtk.ResponseType.OK,
1019 ),
1020 )
1021
1022 self.set_current_folder_uri(
1023 settings.get_option('gui/playlist_export_dir')
1024 or GLib.filename_to_uri(xdg.homedir, None)
1025 )
1026
1027 self.set_local_only(False)
1028
1029 self.relative_checkbox = Gtk.CheckButton(_('Use relative paths to tracks'))
1030 self.relative_checkbox.set_active(True)
1031 self.extras_box.pack_start(self.relative_checkbox, False, False, 3)
1032 self.relative_checkbox.show()
1033
1034 self.playlist = playlist
1035
1036 extensions = {}
1037
1038 for provider in providers.get('playlist-format-converter'):
1039 extensions[provider.name] = provider.title
1040
1041 self.add_extensions(extensions)
1042 self.set_current_name('%s.m3u' % playlist.name)
1043
1044 self.connect('response', self.on_response)
1045
1046 def run(self):
1047 """
1048 Override to take care of the response
1049 """
1050 response = FileOperationDialog.run(self)
1051 self.emit('response', response)
1052
1053 def do_message(self, message_type, message):
1054 """
1055 Displays simple dialogs on messages
1056 """
1057 if message_type == Gtk.MessageType.INFO:
1058 info(self.get_transient_for(), markup=message)
1059 elif message_type == Gtk.MessageType.ERROR:
1060 error(self.get_transient_for(), markup=message)
1061
1062 def on_response(self, dialog, response):
1063 """
1064 Exports the playlist if requested
1065 """
1066 self.hide()
1067
1068 if response == Gtk.ResponseType.OK:
1069 gfile = self.get_file()
1070 settings.set_option('gui/playlist_export_dir', gfile.get_parent().get_uri())
1071
1072 path = gfile.get_uri()
1073 if not is_valid_playlist(path):
1074 path = '%s.m3u' % path
1075
1076 options = PlaylistExportOptions(
1077 relative=self.relative_checkbox.get_active()
1078 )
1079
1080 try:
1081 export_playlist(self.playlist, path, options)
1082 except InvalidPlaylistTypeError as e:
1083 self.emit('message', Gtk.MessageType.ERROR, str(e))
1084 else:
1085 gio = Gio.File.new_for_uri(path)
1086 path = gio.get_path()
1087 self.emit(
1088 'message',
1089 Gtk.MessageType.INFO,
1090 _('Playlist saved as <b>%s</b>.') % path,
1091 )
1092
1093
1094 class ConfirmCloseDialog(Gtk.MessageDialog):
1095 """
1096 Shows the dialog to confirm closing of the playlist
1097 """
1098
1099 def __init__(self, document_name):
1100 """
1101 Initializes the dialog
1102 """
1103 Gtk.MessageDialog.__init__(self, type=Gtk.MessageType.WARNING)
1104
1105 self.set_title(_('Close %s' % document_name))
1106 self.set_markup(_('<b>Save changes to %s before closing?</b>') % document_name)
1107 self.format_secondary_text(
1108 _('Your changes will be lost if you don\'t save them')
1109 )
1110
1111 self.add_buttons(
1112 _('Close Without Saving'),
1113 100,
1114 Gtk.STOCK_CANCEL,
1115 Gtk.ResponseType.CANCEL,
1116 Gtk.STOCK_SAVE,
1117 110,
1118 )
1119
1120 def run(self):
1121 self.show_all()
1122 response = Gtk.Dialog.run(self)
1123 self.hide()
1124 return response
1125
1126
1127 class MessageBar(Gtk.InfoBar):
1128 type_map = {
1129 Gtk.MessageType.INFO: 'dialog-information',
1130 Gtk.MessageType.QUESTION: 'dialog-question',
1131 Gtk.MessageType.WARNING: 'dialog-warning',
1132 Gtk.MessageType.ERROR: 'dialog-error',
1133 }
1134 buttons_map = {
1135 Gtk.ButtonsType.OK: [(Gtk.STOCK_OK, Gtk.ResponseType.OK)],
1136 Gtk.ButtonsType.CLOSE: [(Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)],
1137 Gtk.ButtonsType.CANCEL: [(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)],
1138 Gtk.ButtonsType.YES_NO: [
1139 (Gtk.STOCK_NO, Gtk.ResponseType.NO),
1140 (Gtk.STOCK_YES, Gtk.ResponseType.YES),
1141 ],
1142 Gtk.ButtonsType.OK_CANCEL: [
1143 (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL),
1144 (Gtk.STOCK_OK, Gtk.ResponseType.OK),
1145 ],
1146 }
1147
1148 def __init__(
1149 self,
1150 parent=None,
1151 type=Gtk.MessageType.INFO,
1152 buttons=Gtk.ButtonsType.NONE,
1153 text=None,
1154 ):
1155 """
1156 Report important messages to the user
1157
1158 :param parent: the parent container box
1159 :type parent: :class:`Gtk.Box`
1160 :param type: the type of message: Gtk.MessageType.INFO,
1161 Gtk.MessageType.WARNING, Gtk.MessageType.QUESTION or
1162 Gtk.MessageType.ERROR.
1163 :param buttons: the predefined set of buttons to
1164 use: Gtk.ButtonsType.NONE, Gtk.ButtonsType.OK,
1165 Gtk.ButtonsType.CLOSE, Gtk.ButtonsType.CANCEL,
1166 Gtk.ButtonsType.YES_NO, Gtk.ButtonsType.OK_CANCEL
1167 :param text: a string containing the message
1168 text or None
1169 """
1170 if parent is not None and not isinstance(parent, Gtk.Box):
1171 raise TypeError('Parent needs to be of type Gtk.Box')
1172
1173 Gtk.InfoBar.__init__(self)
1174 self.set_no_show_all(True)
1175
1176 if parent is not None:
1177 parent.add(self)
1178 parent.reorder_child(self, 0)
1179 parent.child_set_property(self, 'expand', False)
1180
1181 self.image = Gtk.Image()
1182 self.set_message_type(type)
1183
1184 self.primary_text = Gtk.Label(label=text)
1185 self.primary_text.set_property('xalign', 0)
1186 self.primary_text.set_line_wrap(True)
1187 self.secondary_text = Gtk.Label()
1188 self.secondary_text.set_property('xalign', 0)
1189 self.secondary_text.set_line_wrap(True)
1190 self.secondary_text.set_no_show_all(True)
1191 self.secondary_text.set_selectable(True)
1192
1193 self.message_area = Gtk.Box(spacing=12, orientation=Gtk.Orientation.VERTICAL)
1194 self.message_area.pack_start(self.primary_text, False, False, 0)
1195 self.message_area.pack_start(self.secondary_text, False, False, 0)
1196
1197 box = Gtk.Box(spacing=6)
1198 box.pack_start(self.image, False, True, 0)
1199 box.pack_start(self.message_area, True, True, 0)
1200
1201 content_area = self.get_content_area()
1202 content_area.add(box)
1203 content_area.show_all()
1204
1205 self.action_area = self.get_action_area()
1206 self.action_area.set_property('layout-style', Gtk.ButtonBoxStyle.START)
1207
1208 if buttons != Gtk.ButtonsType.NONE:
1209 for text, response in self.buttons_map[buttons]:
1210 self.add_button(text, response)
1211
1212 self.primary_text_attributes = Pango.AttrList()
1213 # TODO: GI: Pango attr
1214 # self.primary_text_attributes.insert(
1215 # Pango.AttrWeight(Pango.Weight.NORMAL, 0, -1))
1216 # self.primary_text_attributes.insert(
1217 # Pango.AttrScale(Pango.SCALE_MEDIUM, 0, -1))'''
1218
1219 self.primary_text_emphasized_attributes = Pango.AttrList()
1220 # TODO: GI: Pango attr
1221 # self.primary_text_emphasized_attributes.insert(
1222 # Pango.AttrWeight(Pango.Weight.BOLD, 0, -1))
1223 # self.primary_text_emphasized_attributes.insert(
1224 # Pango.AttrScale(Pango.SCALE_LARGE, 0, -1))'''
1225
1226 self.connect('response', self.on_response)
1227
1228 # Workaround for https://bugzilla.gnome.org/show_bug.cgi?id=710888
1229 # -> From pitivi: https://phabricator.freedesktop.org/D1103#34aa2703
1230 def _make_sure_revealer_does_nothing(widget):
1231 if not isinstance(widget, Gtk.Revealer):
1232 return
1233 widget.set_transition_type(Gtk.RevealerTransitionType.NONE)
1234
1235 self.forall(_make_sure_revealer_does_nothing)
1236
1237 def set_text(self, text):
1238 """
1239 Sets the primary text of the message bar
1240
1241 :param markup: a regular text string
1242 :type markup: string
1243 """
1244 self.primary_text.set_text(text)
1245
1246 def set_markup(self, markup):
1247 """
1248 Sets the primary markup text of the message bar
1249
1250 :param markup: a markup string
1251 :type markup: string
1252 """
1253 self.primary_text.set_markup(markup)
1254
1255 def set_secondary_text(self, text):
1256 """
1257 Sets the secondary text to the text
1258 specified by message_format
1259
1260 :param text: The text to be displayed
1261 as the secondary text or None.
1262 :type text: string
1263 """
1264 if text is None:
1265 self.secondary_text.hide()
1266 self.primary_text.set_attributes(self.primary_text_attributes)
1267 else:
1268 self.secondary_text.set_text(text)
1269 self.secondary_text.show()
1270 self.primary_text.set_attributes(self.primary_text_emphasized_attributes)
1271
1272 def set_secondary_markup(self, markup):
1273 """
1274 Sets the secondary text to the markup text
1275 specified by text.
1276
1277 :param text: A string containing the
1278 pango markup to use as secondary text.
1279 :type text: string
1280 """
1281 if markup is None:
1282 self.secondary_text.hide()
1283 self.primary_text.set_attributes(self.primary_text_attributes)
1284 else:
1285 self.secondary_text.set_markup(markup)
1286 self.secondary_text.show()
1287 self.primary_text.set_attributes(self.primary_text_emphasized_attributes)
1288
1289 def set_image(self, image):
1290 """
1291 Sets the contained image to the :class:`Gtk.Widget`
1292 specified by image.
1293
1294 :param image: the image widget
1295 :type image: :class:`Gtk.Widget`
1296 """
1297 box = self.image.get_parent()
1298 box.remove(self.image)
1299 self.image = image
1300 box.pack_start(self.image, False, True, 0)
1301 box.reorder_child(self.image, 0)
1302 self.image.show()
1303
1304 def get_image(self):
1305 """
1306 Gets the contained image
1307 """
1308 return self.image
1309
1310 def add_button(self, button_text, response_id):
1311 """
1312 Overrides :class:`Gtk.InfoBar` to prepend
1313 instead of append to the action area
1314
1315 :param button_text: text of button, or stock ID
1316 :type button_text: string
1317 :param response_id: response ID for the button
1318 :type response_id: int
1319 """
1320 button = Gtk.InfoBar.add_button(self, button_text, response_id)
1321 self.action_area.reorder_child(button, 0)
1322
1323 return button
1324
1325 def clear_buttons(self):
1326 """
1327 Removes all buttons currently
1328 placed in the action area
1329 """
1330 for button in self.action_area:
1331 self.action_area.remove(button)
1332
1333 def set_message_type(self, type):
1334 """
1335 Sets the message type of the message area.
1336
1337 :param type: the type of message: Gtk.MessageType.INFO,
1338 Gtk.MessageType.WARNING, Gtk.MessageType.QUESTION or
1339 Gtk.MessageType.ERROR.
1340 """
1341 if type != Gtk.MessageType.OTHER:
1342 self.image.set_from_icon_name(self.type_map[type], Gtk.IconSize.DIALOG)
1343
1344 Gtk.InfoBar.set_message_type(self, type)
1345
1346 def get_message_area(self):
1347 """
1348 Retrieves the message area
1349 """
1350 return self.message_area
1351
1352 def _show_message(
1353 self, message_type, text, secondary_text, markup, secondary_markup, timeout
1354 ):
1355 """
1356 Helper for the various `show_*` methods. See `show_info` for
1357 documentation on the parameters.
1358 """
1359 if text is markup is None:
1360 raise ValueError("text or markup must be specified")
1361
1362 self.set_message_type(message_type)
1363 if markup is None:
1364 self.set_text(text)
1365 else:
1366 self.set_markup(markup)
1367 if secondary_markup is None:
1368 self.set_secondary_text(secondary_text)
1369 else:
1370 self.set_secondary_markup(secondary_markup)
1371 self.show()
1372
1373 if timeout > 0:
1374 GLib.timeout_add_seconds(timeout, self.hide)
1375
1376 def show_info(
1377 self,
1378 text=None,
1379 secondary_text=None,
1380 markup=None,
1381 secondary_markup=None,
1382 timeout=5,
1383 ):
1384 """
1385 Convenience method which sets all
1386 required flags for an info message
1387
1388 :param text: the message to display
1389 :type text: string
1390 :param secondary_text: additional information
1391 :type secondary_text: string
1392 :param markup: the message to display, in Pango markup format
1393 (overrides `text`)
1394 :type markup: string
1395 :param secondary_markup: additional information, in Pango markup
1396 format (overrides `secondary_text`)
1397 :type secondary_markup: string
1398 :param timeout: after how many seconds the
1399 message should be hidden automatically,
1400 use 0 to disable this behavior
1401 :type timeout: int
1402 """
1403 self._show_message(
1404 Gtk.MessageType.INFO,
1405 text,
1406 secondary_text,
1407 markup,
1408 secondary_markup,
1409 timeout,
1410 )
1411
1412 def show_question(
1413 self, text=None, secondary_text=None, markup=None, secondary_markup=None
1414 ):
1415 """
1416 Convenience method which sets all
1417 required flags for a question message
1418
1419 :param text: the message to display
1420 :param secondary_text: additional information
1421 :param markup: the message to display, in Pango markup format
1422 :param secondary_markup: additional information, in Pango markup format
1423 """
1424 self._show_message(
1425 Gtk.MessageType.QUESTION, text, secondary_text, markup, secondary_markup, 0
1426 )
1427
1428 def show_warning(
1429 self, text=None, secondary_text=None, markup=None, secondary_markup=None
1430 ):
1431 """
1432 Convenience method which sets all
1433 required flags for a warning message
1434
1435 :param text: the message to display
1436 :param secondary_text: additional information
1437 :param markup: the message to display, in Pango markup format
1438 :param secondary_markup: additional information, in Pango markup format
1439 """
1440 self._show_message(
1441 Gtk.MessageType.WARNING, text, secondary_text, markup, secondary_markup, 0
1442 )
1443
1444 def show_error(
1445 self, text=None, secondary_text=None, markup=None, secondary_markup=None
1446 ):
1447 """
1448 Convenience method which sets all
1449 required flags for a warning message
1450
1451 :param text: the message to display
1452 :param secondary_text: additional information
1453 :param markup: the message to display, in Pango markup format
1454 :param secondary_markup: additional information, in Pango markup format
1455 """
1456 self._show_message(
1457 Gtk.MessageType.ERROR, text, secondary_text, markup, secondary_markup, 0
1458 )
1459
1460 def on_response(self, widget, response):
1461 """
1462 Handles the response for closing
1463 """
1464 if response == Gtk.ResponseType.CLOSE:
1465 self.hide()
1466
1467
1468 #
1469 # Message ID's used by the XMessageDialog
1470 #
1471
1472 XRESPONSE_YES = Gtk.ResponseType.YES
1473 XRESPONSE_YES_ALL = 8000
1474 XRESPONSE_NO = Gtk.ResponseType.NO
1475 XRESPONSE_NO_ALL = 8001
1476 XRESPONSE_CANCEL = Gtk.ResponseType.CANCEL
1477
1478
1479 class XMessageDialog(Gtk.Dialog):
1480 '''Used to show a custom message dialog with custom buttons'''
1481
1482 def __init__(
1483 self,
1484 title,
1485 text,
1486 parent=None,
1487 show_yes=True,
1488 show_yes_all=True,
1489 show_no=True,
1490 show_no_all=True,
1491 show_cancel=True,
1492 ):
1493 Gtk.Dialog.__init__(self, title=title, transient_for=parent)
1494
1495 #
1496 # TODO: Make these buttons a bit prettier
1497 #
1498
1499 if show_yes:
1500 self.add_button(Gtk.STOCK_YES, XRESPONSE_YES)
1501 self.set_default_response(XRESPONSE_YES)
1502
1503 if show_yes_all:
1504 self.add_button(_('Yes to all'), XRESPONSE_YES_ALL)
1505 self.set_default_response(XRESPONSE_YES_ALL)
1506
1507 if show_no:
1508 self.add_button(Gtk.STOCK_NO, XRESPONSE_NO)
1509 self.set_default_response(XRESPONSE_NO)
1510
1511 if show_no_all:
1512 self.add_button(_('No to all'), XRESPONSE_NO_ALL)
1513 self.set_default_response(XRESPONSE_NO_ALL)
1514
1515 if show_cancel:
1516 self.add_button(Gtk.STOCK_CANCEL, XRESPONSE_CANCEL)
1517 self.set_default_response(XRESPONSE_CANCEL)
1518
1519 vbox = self.get_content_area()
1520 self._label = Gtk.Label()
1521 self._label.set_use_markup(True)
1522 self._label.set_markup(text)
1523 vbox.pack_start(self._label, True, True, 0)
1524
1525
1526 class FileCopyDialog(Gtk.Dialog):
1527 """
1528 Used to copy a list of files to a single destination directory
1529
1530 Usage:
1531 dialog = FileCopyDialog( [file_uri,..], destination_uri, text, parent)
1532 dialog.do_copy()
1533
1534 Do not use run() on this dialog!
1535 """
1536
1537 class CopyThread(Thread):
1538 def __init__(self, source, dest, callback_finish_single_copy, copy_flags):
1539 Thread.__init__(self, name='CopyThread')
1540 self.__source = source
1541 self.__dest = dest
1542 self.__cb_single_copy = callback_finish_single_copy
1543 self.__copy_flags = copy_flags
1544 self.__cancel = Gio.Cancellable()
1545 self.start()
1546
1547 def run(self):
1548 try:
1549 result = self.__source.copy(
1550 self.__dest, flags=self.__copy_flags, cancellable=self.__cancel
1551 )
1552 GLib.idle_add(self.__cb_single_copy, self.__source, result, None)
1553 except GLib.Error as err:
1554 GLib.idle_add(self.__cb_single_copy, self.__source, False, err)
1555
1556 def cancel_copy(self):
1557 self.__cancel.cancel()
1558
1559 def __init__(
1560 self,
1561 file_uris,
1562 destination_uri,
1563 title,
1564 text=_("Saved %(count)s of %(total)s."),
1565 parent=None,
1566 ):
1567 self.file_uris = file_uris
1568 self.destination_uri = destination_uri
1569 self.is_copying = False
1570
1571 Gtk.Dialog.__init__(self, title=title, transient_for=parent)
1572
1573 self.parent = parent
1574 self.count = 0
1575 self.total = len(file_uris)
1576 self.text = text
1577 self.overwrite_response = None
1578
1579 # self.set_modal(True)
1580 # self.set_decorated(False)
1581 self.set_resizable(False)
1582 # self.set_focus_on_map(False)
1583
1584 vbox = self.get_content_area()
1585
1586 vbox.set_spacing(12)
1587 vbox.set_border_width(12)
1588
1589 self._label = Gtk.Label()
1590 self._label.set_use_markup(True)
1591 self._label.set_markup(self.text % {'count': 0, 'total': self.total})
1592 vbox.pack_start(self._label, True, True, 0)
1593
1594 self._progress = Gtk.ProgressBar()
1595 self._progress.set_size_request(300, -1)
1596 vbox.pack_start(self._progress, True, True, 0)
1597
1598 self.show_all()
1599
1600 # TODO: Make dialog cancelable
1601 # self.cancel_button.connect('activate', lambda *e: self.cancel.cancel() )
1602
1603 self.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)
1604
1605 def do_copy(self):
1606 logger.info("Copy started.")
1607 self._start_next_copy()
1608 self.show_all()
1609 self.connect('response', self._on_response)
1610
1611 def run(self):
1612 raise NotImplementedError("Don't use this")
1613
1614 def _on_response(self, widget, response):
1615 logger.info("Copy complete.")
1616 self.destroy()
1617
1618 def _step(self):
1619 '''Steps the progress bar'''
1620 self.count += 1
1621 self._progress.set_fraction(clamp(self.count / float(self.total), 0, 1))
1622 self._label.set_markup(self.text % {'count': self.count, 'total': self.total})
1623
1624 def _start_next_copy(self, overwrite=False):
1625 if self.count == len(self.file_uris):
1626 self.response(Gtk.ResponseType.OK)
1627 return
1628
1629 flags = Gio.FileCopyFlags.NONE
1630
1631 src_uri = self.file_uris[self.count]
1632 dst_uri = self.destination_uri + '/' + src_uri.split('/')[-1]
1633
1634 self.source = Gio.File.new_for_uri(src_uri)
1635 self.destination = Gio.File.new_for_uri(dst_uri)
1636
1637 if not overwrite:
1638 if self.destination.query_exists(None):
1639 if self.overwrite_response == XRESPONSE_YES_ALL:
1640 overwrite = True
1641
1642 elif (
1643 self.overwrite_response == XRESPONSE_NO_ALL
1644 or self.overwrite_response == XRESPONSE_NO
1645 ):
1646 # only deny the overwrite once..
1647 if self.overwrite_response == XRESPONSE_NO:
1648 self.overwrite_response = None
1649
1650 logging.info("NoOverwrite: %s" % self.destination.get_uri())
1651 self._step()
1652 GLib.idle_add(self._start_next_copy) # don't recurse
1653 return
1654 else:
1655 self._query_overwrite()
1656 return
1657
1658 if overwrite:
1659 flags = Gio.FileCopyFlags.OVERWRITE
1660 try:
1661 # Gio.FileCopyFlags.OVERWRITE doesn't actually work
1662 logging.info("DeleteDest : %s" % self.destination.get_uri())
1663 self.destination.delete()
1664 except GLib.Error:
1665 pass
1666
1667 logging.info("CopySource : %s" % self.source.get_uri())
1668 logging.info("CopyDest : %s" % self.destination.get_uri())
1669
1670 # TODO g_file_copy_async() isn't introspectable
1671 # see https://github.com/exaile/exaile/issues/198 for details
1672 # self.source.copy_async( self.destination, self._finish_single_copy_async, flags=flags, cancellable=self.cancel )
1673
1674 self.cpthr = self.CopyThread(
1675 self.source, self.destination, self._finish_single_copy, flags
1676 )
1677
1678 def _finish_single_copy(self, source, success, error):
1679 if error:
1680 self._on_error(
1681 _("Error occurred while copying %s: %s")
1682 % (
1683 GLib.markup_escape_text(self.source.get_uri()),
1684 GLib.markup_escape_text(str(error)),
1685 )
1686 )
1687 if success:
1688 self._step()
1689 self._start_next_copy()
1690
1691 def _finish_single_copy_async(self, source, async_result):
1692 try:
1693 if source.copy_finish(async_result):
1694 self._step()
1695 self._start_next_copy()
1696 except GLib.Error as e:
1697 self._on_error(
1698 _("Error occurred while copying %s: %s")
1699 % (
1700 GLib.markup_escape_text(self.source.get_uri()),
1701 GLib.markup_escape_text(str(e)),
1702 )
1703 )
1704
1705 def _query_overwrite(self):
1706 self.hide()
1707
1708 text = _('File exists, overwrite %s ?') % GLib.markup_escape_text(
1709 self.destination.get_uri()
1710 )
1711 dialog = XMessageDialog(self.parent, text)
1712 dialog.connect('response', self._on_query_overwrite_response, dialog)
1713 dialog.show_all()
1714 dialog.grab_focus()
1715 self.query_dialog = dialog
1716
1717 def _on_query_overwrite_response(self, widget, response, dialog):
1718 dialog.destroy()
1719 self.overwrite_response = response
1720
1721 if response == Gtk.ResponseType.CANCEL:
1722 self.response(response)
1723 else:
1724 if response == XRESPONSE_NO or response == XRESPONSE_NO_ALL:
1725 overwrite = False
1726 else:
1727 overwrite = True
1728
1729 self.show_all()
1730 self._start_next_copy(overwrite)
1731
1732 def _on_error(self, message):
1733 self.hide()
1734
1735 dialog = Gtk.MessageDialog(
1736 buttons=Gtk.ButtonsType.CLOSE,
1737 message_type=Gtk.MessageType.ERROR,
1738 modal=True,
1739 text=message,
1740 transient_for=self.parent,
1741 )
1742 dialog.set_markup(message)
1743 dialog.connect('response', self._on_error_response, dialog)
1744 dialog.show()
1745 dialog.grab_focus()
1746 self.error_dialog = dialog
1747
1748 def _on_error_response(self, widget, response, dialog):
1749 self.response(Gtk.ResponseType.CANCEL)
1750 dialog.destroy()
1751
1752
1753 def ask_for_playlist_name(parent, playlist_manager, name=None):
1754 """
1755 Returns a user-selected name that is not already used
1756 in the specified playlist manager
1757
1758 :param name: A default name to show to the user
1759 Returns None if the user hits cancel
1760 """
1761
1762 while True:
1763 dialog = TextEntryDialog(
1764 _('Playlist name:'),
1765 _('Add new playlist...'),
1766 name,
1767 parent=parent,
1768 okbutton=Gtk.STOCK_ADD,
1769 )
1770
1771 result = dialog.run()
1772 if result != Gtk.ResponseType.OK:
1773 return None
1774
1775 name = dialog.get_value()
1776
1777 if name == '':
1778 error(parent, _("You did not enter a name for your playlist"))
1779 elif playlist_manager.has_playlist_name(name):
1780 # name is already in use
1781 error(parent, _("The playlist name you entered is already in use."))
1782 else:
1783 return name
1784
1785
1786 def save(
1787 parent, output_fname, output_setting=None, extensions=None, title=_("Save As")
1788 ):
1789 """
1790 A 'save' dialog utility function, which can be used to easily
1791 remember the last location the user saved something.
1792
1793 :param parent: Parent window
1794 :param output_fname: Output filename
1795 :param output_setting: Setting to store the last 'output directory' saved at
1796 :param extensions: Valid output extensions. Dict { '.m3u': 'Description', .. }
1797 :param title: Title of dialog
1798
1799 :returns: None if user cancels, chosen URI otherwise
1800 """
1801
1802 uri = None
1803
1804 dialog = FileOperationDialog(
1805 title,
1806 parent,
1807 Gtk.FileChooserAction.SAVE,
1808 (
1809 Gtk.STOCK_CANCEL,
1810 Gtk.ResponseType.CANCEL,
1811 Gtk.STOCK_SAVE,
1812 Gtk.ResponseType.ACCEPT,
1813 ),
1814 )
1815
1816 if extensions is not None:
1817 dialog.add_extensions(extensions)
1818
1819 dialog.set_current_name(output_fname)
1820
1821 if output_setting:
1822 output_dir = settings.get_option(output_setting)
1823 if output_dir:
1824 dialog.set_current_folder_uri(output_dir)
1825
1826 if dialog.run() == Gtk.ResponseType.ACCEPT:
1827 uri = dialog.get_uri()
1828
1829 settings.set_option(output_setting, dialog.get_current_folder_uri())
1830
1831 dialog.destroy()
1832
1833 return uri
1834
1835
1836 def export_playlist_dialog(playlist, parent=None):
1837 '''Exports the playlist to a user-specified path'''
1838 if playlist is not None:
1839 dialog = PlaylistExportDialog(playlist, parent)
1840 dialog.show()
1841
1842
1843 def export_playlist_files(playlist, parent=None):
1844 '''Exports the playlist files to a user-specified URI'''
1845
1846 if playlist is None:
1847 return
1848
1849 def _on_uri(uri):
1850 if hasattr(playlist, 'get_playlist'):
1851 pl = playlist.get_playlist()
1852 else:
1853 pl = playlist
1854 pl_files = [track.get_loc_for_io() for track in pl]
1855 dialog = FileCopyDialog(
1856 pl_files, uri, _('Exporting %s') % playlist.name, parent=parent
1857 )
1858 dialog.do_copy()
1859
1860 dialog = DirectoryOpenDialog(
1861 title=_('Choose directory to export files to'), parent=parent
1862 )
1863 dialog.set_select_multiple(False)
1864 dialog.connect('uris-selected', lambda widget, uris: _on_uri(uris[0]))
1865 dialog.run()
1866 dialog.destroy()
1867
1868
1869 class UpdateInfoDialog:
1870 def __init__(self, parent=None):
1871 self.builder = guiutil.get_builder(
1872 xdg.get_data_path('ui', 'widgets', 'info_dialog.ui')
1873 )
1874 self.builder.connect_signals(self)
1875
1876 self.window = self.builder.get_object('info_dialog')
1877 self.window.set_transient_for(parent)
1878 self.window.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)
1879 self.window.show_all()
1880
1881 self.dont_show_again = self.builder.get_object('dont_show_again')
1882
1883 def on_close_button_clicked(self, widget):
1884 self.window.destroy()
1885
1886 def on_window_destroy(self, widget):
1887 if self.dont_show_again.get_active():
1888 settings.set_option('general/hide_413_dialog', True)
1889 else:
1890 settings.set_option('general/hide_413_dialog', False)