Debian Codegraph @

xlgui/preferences/widgets.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 hashlib
28 import logging
29 import os
30 from typing import Any, Callable, Optional
31
32 from gi.repository import Gdk
33 from gi.repository import GLib
34 from gi.repository import Gtk
35 from gi.repository import Pango
36
37 from xl.nls import gettext as _
38 from xl import event, main, settings
39 from xlgui import guiutil
40 from xlgui.widgets import dialogs
41 from xlgui.guiutil import GtkTemplate
42
43 logger = logging.getLogger(__name__)
44
45
46 class Preference:
47 """
48 Representing a Gtk.Entry preferences item
49 """
50
51 default: Any = ''
52 done: Callable[[], bool]
53 label_widget: Optional[Gtk.Widget]
54 name: str
55 restart_required = False
56
57 def __init__(self, preferences, widget):
58 """
59 Initializes the preferences item
60 expects the name of the widget in the designer file, the default for
61 this setting, an optional function to be called when the value is
62 changed, and an optional function to be called when this setting
63 is applied
64 """
65
66 self.widget = widget
67 self.preferences = preferences
68
69 if self.restart_required:
70 self.message = dialogs.MessageBar(
71 parent=preferences.builder.get_object('preferences_box'),
72 type=Gtk.MessageType.QUESTION,
73 buttons=Gtk.ButtonsType.CLOSE,
74 text=_('Restart Exaile?'),
75 )
76 self.message.set_secondary_text(
77 _('A restart is required for this change to take effect.')
78 )
79
80 button = self.message.add_button(_('Restart'), Gtk.ResponseType.ACCEPT)
81 button.set_image(
82 Gtk.Image.new_from_icon_name('view-refresh', Gtk.IconSize.BUTTON)
83 )
84
85 self.message.connect('response', self.on_message_response)
86
87 self._set_value()
88 self._setup_change()
89
90 def change(self, *args):
91 self.apply()
92
93 def _setup_change(self):
94 """
95 Sets up the function to be called when this preference is changed
96 """
97 self.widget.connect(
98 'focus-out-event', self.change, self.name, self._get_value()
99 )
100
101 try:
102 self.widget.connect(
103 'activate',
104 lambda *e: self.change(self.widget, None, self.name, self._get_value()),
105 )
106 except TypeError:
107 pass
108
109 def _get_value(self):
110 """
111 Value to be stored into the settings file
112 """
113 return self.widget.get_text()
114
115 def _set_value(self):
116 """
117 Sets the GUI widget up for this preference
118 """
119 if not self.widget:
120 logger.error("Widget not found: %s", self.name)
121 return
122 self.widget.set_text(str(settings.get_option(self.name, self.default)))
123
124 def apply(self, value=None):
125 """
126 Applies this setting
127 """
128 if hasattr(self, 'done') and not self.done():
129 return False
130
131 oldvalue = settings.get_option(self.name, self.default)
132
133 if value is None:
134 value = self._get_value()
135
136 if value != oldvalue:
137 settings.set_option(self.name, value)
138
139 if self.restart_required:
140 self.message.show()
141
142 return True
143
144 def on_message_response(self, widget, response):
145 """
146 Restarts Exaile if requested
147 """
148 widget.hide()
149
150 if response == Gtk.ResponseType.ACCEPT:
151 GLib.idle_add(main.exaile().quit, True)
152
153 def hide_widget(self):
154 '''Hides the widget and optionally its associated label'''
155 self.widget.hide()
156 if hasattr(self, 'label_widget'):
157 self.label_widget.hide()
158
159 def show_widget(self):
160 '''Shows the widget and optionally its associated label'''
161 self.widget.show_all()
162 if hasattr(self, 'label_widget'):
163 self.label_widget.show_all()
164
165 def set_widget_sensitive(self, value):
166 '''Sets sensitivity of widget and optionally its associated label'''
167 self.widget.set_sensitive(value)
168 if hasattr(self, 'label_widget'):
169 self.label_widget.set_sensitive(value)
170
171
172 class Conditional:
173 """
174 Allows for reactions on changes
175 of other preference items
176 """
177
178 condition_preference_name = ''
179 condition_widget = None
180
181 def __init__(self):
182 event.add_ui_callback(self.on_option_set, 'option_set')
183 GLib.idle_add(
184 self.on_option_set, 'option_set', settings, self.condition_preference_name
185 )
186
187 def get_condition_value(self):
188 """
189 :returns: The currently selected value in the condition widget,
190 presumes it is a combo box
191 """
192 i = self.condition_widget.get_active_iter()
193 return self.condition_widget.get_model().get_value(i, 0)
194
195 def on_check_condition(self):
196 """
197 Specifies the condition to meet
198
199 :returns: Whether the condition is met or not
200 :rtype: bool
201 """
202 pass
203
204 def on_condition_met(self):
205 """
206 Called as soon as the
207 specified condition is met
208 """
209 self.widget.set_sensitive(True)
210
211 def on_condition_failed(self):
212 """
213 Called as soon as the specified
214 condition is not met anymore
215 """
216 self.widget.set_sensitive(False)
217
218 def on_option_set(self, event, settings, option):
219 """
220 Called as soon as options change
221 """
222 if option == self.condition_preference_name:
223 if self.on_check_condition():
224 self.on_condition_met()
225 else:
226 self.on_condition_failed()
227
228 def check_condition(self):
229 if self.on_check_condition():
230 self.on_condition_met()
231 else:
232 self.on_condition_failed()
233
234
235 class CheckConditional(Conditional):
236 """
237 True if the conditional widget is active
238 """
239
240 def get_condition_value(self):
241 return self.condition_widget.get_active()
242
243 def on_check_condition(self):
244 """
245 Specifies the condition to meet
246
247 :returns: Whether the condition is met or not
248 :rtype: bool
249 """
250 return self.get_condition_value()
251
252
253 class MultiConditional:
254 """
255 Allows for reactions on changes of multiple preference items
256 """
257
258 condition_preference_names = []
259 condition_widgets = {}
260
261 def __init__(self):
262 event.add_ui_callback(self.on_option_set, 'option_set')
263 GLib.idle_add(
264 self.on_option_set,
265 'option_set',
266 settings,
267 self.condition_preference_names[0],
268 )
269
270 def get_condition_value(self, name):
271 """
272 :returns: The currently selected value in the condition widget,
273 presumes it is a combo box
274 """
275 widget = self.condition_widgets[name]
276 return widget.get_model().get_value(widget.get_active_iter(), 0)
277
278 def on_check_condition(self):
279 """
280 Specifies the condition to meet
281
282 :returns: Whether the condition is met or not
283 :rtype: bool
284 """
285 pass
286
287 def on_condition_met(self):
288 """
289 Called as soon as the
290 specified condition is met
291 """
292 self.widget.set_sensitive(True)
293
294 def on_condition_failed(self):
295 """
296 Called as soon as the specified
297 condition is not met anymore
298 """
299 self.widget.set_sensitive(False)
300
301 def on_option_set(self, event, settings, option):
302 """
303 Called as soon as options change
304 """
305 if option in self.condition_preference_names:
306 if self.on_check_condition():
307 self.on_condition_met()
308 else:
309 self.on_condition_failed()
310
311 def check_condition(self):
312 if self.on_check_condition():
313 self.on_condition_met()
314 else:
315 self.on_condition_failed()
316
317
318 class Button(Preference):
319 """
320 Represents a button for custom usage
321 """
322
323 def __init__(self, preferences, widget):
324 Preference.__init__(self, preferences, widget)
325
326 widget.connect('clicked', self.on_clicked)
327
328 def _setup_change(self, *e):
329 pass
330
331 def _get_value(self):
332 return None
333
334 def _set_value(self):
335 pass
336
337 def apply(self, *e):
338 return False
339
340 def on_clicked(self, button):
341 """Override"""
342 pass
343
344
345 class HashedPreference(Preference):
346 """
347 Represents a text entry with automated hashing
348
349 Options:
350 * type (Which hashfunction to use, default: md5)
351 """
352
353 type = 'md5'
354
355 def __init__(self, preferences, widget):
356 Preference.__init__(self, preferences, widget)
357
358 self.widget.set_visibility(True)
359 self._delete_text_id = self.widget.connect('delete-text', self.on_delete_text)
360 self._insert_text_id = self.widget.connect('insert-text', self.on_insert_text)
361
362 def _setup_change(self):
363 """
364 Sets up the function to be called when this preference is changed
365 """
366 self.widget.connect('focus-out-event', lambda *e: self.apply())
367
368 def done(self):
369 """
370 Determines if changes are to be expected
371 """
372 if self._delete_text_id is None and self._insert_text_id is None:
373 return True
374
375 return False
376
377 def apply(self, value=None):
378 """
379 Applies this setting
380 """
381 if not self.done():
382 return False
383
384 if value is None:
385 value = self._get_value()
386 if value is None:
387 return True
388
389 if value != '':
390 hashfunc = hashlib.new(self.type)
391 hashfunc.update(value.encode('utf-8'))
392 value = hashfunc.hexdigest()
393
394 oldvalue = settings.get_option(self.name, self.default)
395
396 if value != oldvalue:
397 settings.set_option(self.name, value)
398
399 self.widget.set_text(value)
400 self.widget.set_visibility(True)
401 self._delete_text_id = self.widget.connect('delete-text', self.on_delete_text)
402 self._insert_text_id = self.widget.connect('insert-text', self.on_insert_text)
403
404 return True
405
406 def on_delete_text(self, widget, start, end):
407 """
408 Clears the text entry and makes following input invisible
409 """
410 self.widget.disconnect(self._delete_text_id)
411 self.widget.disconnect(self._insert_text_id)
412 self._delete_text_id = self._insert_text_id = None
413
414 self.widget.set_visibility(False)
415 self.widget.set_text('')
416
417 def on_insert_text(self, widget, text, length, position):
418 """
419 Clears the text entry and makes following input invisible
420 """
421 self.widget.disconnect(self._delete_text_id)
422 self.widget.disconnect(self._insert_text_id)
423 self._delete_text_id = self._insert_text_id = None
424
425 self.widget.set_visibility(False)
426 # Defer to after returning from this method
427 GLib.idle_add(self.widget.set_text, text)
428 GLib.idle_add(self.widget.set_position, length)
429
430
431 class CheckPreference(Preference):
432 """
433 A class to represent check boxes in the preferences window
434 """
435
436 def __init__(self, preferences, widget):
437 Preference.__init__(self, preferences, widget)
438
439 def _setup_change(self):
440 self.widget.connect('toggled', self.change)
441
442 def _set_value(self):
443 self.widget.set_active(settings.get_option(self.name, self.default))
444
445 def _get_value(self):
446 return self.widget.get_active()
447
448
449 class DirPreference(Preference):
450 """
451 Directory chooser button
452 """
453
454 def __init__(self, preferences, widget):
455 Preference.__init__(self, preferences, widget)
456
457 def _setup_change(self):
458 self.widget.connect('current-folder-changed', self.change)
459
460 def _set_value(self):
461 """
462 Sets the current directory
463 """
464 directory = os.path.expanduser(settings.get_option(self.name, self.default))
465 if not os.path.exists(directory):
466 os.makedirs(directory)
467 self.widget.set_current_folder(directory)
468
469 def _get_value(self):
470 return self.widget.get_filename()
471
472
473 class OrderListPreference(Preference):
474 """
475 A list box with reorderable items
476 """
477
478 def __init__(self, preferences, widget):
479 self.model = Gtk.ListStore(str)
480 Preference.__init__(self, preferences, widget)
481 widget.set_headers_visible(False)
482 widget.set_reorderable(True)
483
484 text = Gtk.CellRendererText()
485 col = Gtk.TreeViewColumn("Item", text, text=0)
486 self.widget.append_column(col)
487 self.widget.set_model(self.model)
488
489 def _setup_change(self):
490 self.widget.connect('drag-end', self.change)
491
492 def _set_value(self):
493 """
494 Sets the preferences for this widget
495 """
496 items = settings.get_option(self.name, self.default)
497
498 self.model.clear()
499 for item in items:
500 self.model.append([item])
501
502 def _get_value(self):
503 """
504 Value to be stored into the settings file
505 """
506 items = []
507
508 for row in self.model:
509 items += [row[0]]
510
511 return items
512
513
514 class SelectionListPreference(Preference):
515 """
516 A list allowing for enabling/disabling
517 as well as reordering of items
518
519 Options:
520 * items: list of :class:`SelectionListPreference.Item` objects
521 * default: list of item ids
522 """
523
524 class Item:
525 """
526 Convenience class for preference item description
527 """
528
529 def __init__(self, id, title, description=None, fixed=False):
530 """
531 :param id: the unique identifier
532 :type id: string
533 :param title: the readable title
534 :type title: string
535 :param description: optional description of the item
536 :type description: string
537 :param fixed: whether the item should be removable
538 :type fixed: bool
539 """
540 self.__id = id
541 self.__title = title
542 self.__description = description
543 self.__fixed = fixed
544
545 id = property(lambda self: self.__id)
546 title = property(lambda self: self.__title)
547 description = property(lambda self: self.__description)
548 fixed = property(lambda self: self.__fixed)
549
550 @GtkTemplate('ui', 'preferences', 'widgets', 'selection_list_preference.ui')
551 class InternalWidget(Gtk.ScrolledWindow):
552 """
553 Internal class for making GtkTemplate work with subclassing
554 """
555
556 __gtype_name__ = 'InternalWidget'
557
558 (
559 model,
560 tree,
561 toggle_renderer,
562 text_renderer,
563 enabled_column,
564 title_column,
565 ) = GtkTemplate.Child.widgets(6)
566 selectionlp = None
567
568 def __init__(self, preference):
569 Gtk.ScrolledWindow.__init__(self)
570 self.init_template()
571 self.selectionlp = preference
572
573 self.tree.enable_model_drag_source(
574 Gdk.ModifierType.BUTTON1_MASK,
575 [('GTK_TREE_MODEL_ROW', Gtk.TargetFlags.SAME_WIDGET, 0)],
576 Gdk.DragAction.MOVE,
577 )
578 self.tree.enable_model_drag_dest(
579 [('GTK_TREE_MODEL_ROW', Gtk.TargetFlags.SAME_WIDGET, 0)],
580 Gdk.DragAction.MOVE,
581 )
582 self.tree.connect('drag-end', self.selectionlp.change)
583
584 self.enabled_column.set_cell_data_func(
585 self.toggle_renderer, self.enabled_data_function
586 )
587
588 self.title_column.set_cell_data_func(
589 self.text_renderer, self.title_data_function
590 )
591
592 @GtkTemplate.Callback
593 def on_row_activated(self, tree, path, column):
594 """
595 Updates the enabled column
596 """
597 if self.model[path][4]:
598 return
599
600 enabled = not self.model[path][3]
601 self.model[path][3] = enabled
602
603 def enabled_data_function(self, column, cell, model, iter, user_data):
604 """
605 Prepares sensitivity
606 of the enabled column
607 """
608 path = model.get_path(iter)
609 fixed = model[path][4]
610 cell.props.sensitive = not fixed
611
612 def title_data_function(self, column, cell, model, iter, user_data):
613 """
614 Prepares the markup to be
615 used for the title column
616 """
617 path = model.get_path(iter)
618 title, description = model[path][1], model[path][2]
619
620 markup = '<b>%s</b>' % title
621
622 if description is not None:
623 markup += '\n<span size="small">%s</span>' % description
624
625 cell.props.markup = markup
626
627 def iter_prev(self, iter, model):
628 """
629 Returns the previous iter
630 Taken from PyGtk FAQ 13.51
631 """
632 path = model.get_path(iter)
633 position = path[-1]
634
635 if position == 0:
636 return None
637
638 prev_path = list(path)[:-1]
639 prev_path.append(position - 1)
640 prev = model.get_iter(tuple(prev_path))
641
642 return prev
643
644 @GtkTemplate.Callback
645 def on_key_press_event(self, tree, event):
646 """
647 Allows for reordering via keyboard (Alt+<direction>)
648 """
649 if not event.get_state() & Gdk.ModifierType.MOD1_MASK:
650 return
651
652 if event.keyval not in (Gdk.KEY_Up, Gdk.KEY_Down):
653 return
654
655 model, selected_iter = tree.get_selection().get_selected()
656
657 if event.keyval == Gdk.KEY_Up:
658 previous_iter = self.iter_prev(selected_iter, model)
659 model.move_before(selected_iter, previous_iter)
660 elif event.keyval == Gdk.KEY_Down:
661 next_iter = model.iter_next(selected_iter)
662 model.move_after(selected_iter, next_iter)
663
664 tree.scroll_to_cell(model.get_path(selected_iter))
665
666 self.selectionlp.apply()
667
668 @GtkTemplate.Callback
669 def on_toggled(self, cell, path):
670 """
671 Updates the enabled column
672 """
673 if self.model[path][4]:
674 return
675
676 active = not cell.get_active()
677 cell.set_active(active)
678 self.model[path][3] = active
679
680 self.selectionlp.apply()
681
682 def __init__(self, preferences, widget):
683 internal_widget = self.InternalWidget(self)
684 self.model = internal_widget.model
685
686 for item in self.items:
687 row = [item.id, item.title, item.description, True, item.fixed]
688 self.model.append(row)
689
690 guiutil.gtk_widget_replace(widget, internal_widget)
691 Preference.__init__(self, preferences, internal_widget)
692
693 def _get_value(self):
694 """
695 Value to be stored in the settings
696 """
697 return [row[0] for row in self.model if row[3]]
698
699 def _set_value(self):
700 """
701 Updates the internal representation
702 """
703 selected_items = settings.get_option(self.name, self.default)
704 # Get list of available items
705 available_items = [row[0] for row in self.model]
706
707 if not available_items:
708 return
709
710 # Filter out invalid items
711 selected_items = [item for item in selected_items if item in available_items]
712 # Cut out unselected items
713 unselected_items = [
714 item for item in available_items if item not in selected_items
715 ]
716 # Move unselected items to the end
717 items = selected_items + unselected_items
718 new_order = [available_items.index(item) for item in items]
719 self.model.reorder(new_order)
720
721 # Disable unselected items
722 for row in self.model:
723 if row[0] in unselected_items and not row[4]:
724 row[3] = False
725 else:
726 row[3] = True
727
728
729 class ShortcutListPreference(Preference):
730 """
731 A list showing available items and allowing
732 to assign/edit/remove key accelerators
733 """
734
735 def __init__(self, preferences, widget):
736 self.list = Gtk.ListStore(str, str)
737
738 Preference.__init__(self, preferences, widget)
739
740 self.widget.set_model(self.list)
741
742 title_renderer = Gtk.CellRendererText()
743 title_column = Gtk.TreeViewColumn(_('Action'), title_renderer, text=0)
744 title_column.set_expand(True)
745 title_column.set_cell_data_func(title_renderer, self.title_data_func)
746 accel_renderer = Gtk.CellRendererAccel()
747 accel_renderer.set_property('editable', True)
748 accel_renderer.set_property('style', Pango.Style.OBLIQUE)
749 accel_renderer.connect('accel-cleared', self.on_accel_cleared)
750 accel_renderer.connect('accel-edited', self.on_accel_edited)
751 accel_column = Gtk.TreeViewColumn(_('Shortcut'), accel_renderer, text=1)
752 accel_column.set_expand(True)
753
754 self.widget.append_column(title_column)
755 self.widget.append_column(accel_column)
756
757 def title_data_func(self, celllayout, cell, model, iter, user_data):
758 """
759 Renders human readable titles instead of the actual keys
760 """
761 key = model.get_value(iter, 0)
762
763 try:
764 cell.set_property('text', self.available_items[key])
765 except KeyError:
766 pass
767
768 def on_accel_cleared(self, cellrenderer, path):
769 """
770 Clears accelerators in the list
771 """
772 iter = self.list.get_iter(path)
773 self.list.set_value(iter, 1, '')
774
775 def on_accel_edited(self, cellrenderer, path, accel_key, accel_mods, keycode):
776 """
777 Updates accelerators display in the list
778 """
779 accel = Gtk.accelerator_name(accel_key, accel_mods)
780 iter = self.list.get_iter(path)
781 self.list.set_value(iter, 1, accel)
782
783 def _set_value(self):
784 """
785 Sets the preferences for this widget
786 """
787 items = settings.get_option(self.name, self.default)
788 self.update_list(items)
789
790 def _get_value(self):
791 """
792 Value to be stored into the settings file
793 """
794 option = {}
795
796 iter = self.list.get_iter_first()
797 while iter:
798 action = self.list.get_value(iter, 0)
799 accel = self.list.get_value(iter, 1)
800 if accel:
801 option[action] = accel
802 iter = self.list.iter_next(iter)
803
804 return option
805
806 def update_list(self, items):
807 """
808 Updates the displayed items
809 """
810 self.list.clear()
811 for action in self.available_items.keys():
812 try:
813 accel = items[action]
814 except KeyError:
815 accel = ''
816 self.list.append([action, accel])
817
818
819 class TextViewPreference(Preference):
820 """
821 Represents a Gtk.TextView
822 """
823
824 def __init__(self, preferences, widget):
825 """
826 Initializes the object
827 """
828 Preference.__init__(self, preferences, widget)
829
830 def _setup_change(self):
831 self.widget.connect('focus-out-event', self.change)
832
833 def get_all_text(self):
834 """
835 Returns the value of the text buffer
836 """
837 buf = self.widget.get_buffer()
838 start = buf.get_start_iter()
839 end = buf.get_end_iter()
840 return buf.get_text(start, end, True)
841
842 def _set_value(self):
843 """
844 Sets the value of this widget
845 """
846 self.widget.get_buffer().set_text(
847 str(settings.get_option(self.name, default=self.default))
848 )
849
850 def _get_value(self):
851 """
852 Applies the setting
853 """
854 return self.get_all_text()
855
856
857 class ListPreference(Preference):
858 """
859 A class to represent a space separated list in the preferences window
860 """
861
862 def __init__(self, preferences, widget):
863 Preference.__init__(self, preferences, widget)
864
865 def _set_value(self):
866 items = settings.get_option(self.name, default=self.default)
867 try:
868 items = " ".join(items)
869 except TypeError:
870 items = ""
871 self.widget.set_text(items)
872
873 def _get_value(self):
874 import shlex
875
876 return shlex.split(self.widget.get_text())
877
878
879 class SpinPreference(Preference):
880 """
881 A class to represent a numeric entry box with stepping buttons
882 """
883
884 def __init__(self, preferences, widget):
885 Preference.__init__(self, preferences, widget)
886
887 def _set_value(self):
888 value = settings.get_option(self.name, default=self.default)
889 self.widget.set_value(value)
890
891 def _setup_change(self):
892 self.widget.connect('value-changed', self.change)
893
894 def _get_value(self):
895 return self.widget.get_value()
896
897
898 class ScalePreference(SpinPreference):
899 """
900 Representation of Gtk.Scale widgets
901 """
902
903 def __init__(self, preferences, widget):
904 SpinPreference.__init__(self, preferences, widget)
905
906
907 class FloatPreference(Preference):
908 """
909 A class to represent a floating point number in the preferences window
910 """
911
912 def __init__(self, preferences, widget):
913 Preference.__init__(self, preferences, widget)
914
915 def _set_value(self):
916 self.widget.set_text(str(settings.get_option(self.name, default=self.default)))
917
918 def _get_value(self):
919 return float(self.widget.get_text())
920
921
922 class IntPreference(FloatPreference):
923 def _get_value(self):
924 return int(self.widget.get_text())
925
926
927 class RGBAButtonPreference(Preference):
928 """
929 A class to represent the color button
930 """
931
932 def __init__(self, preferences, widget):
933 Preference.__init__(self, preferences, widget)
934
935 def _setup_change(self):
936 self.widget.connect('color-set', self.change)
937
938 def _set_value(self):
939 value = settings.get_option(self.name, self.default)
940 rgba = Gdk.RGBA()
941 rgba.parse(value)
942 self.widget.set_rgba(rgba)
943
944 def _get_value(self):
945 return self.widget.get_rgba().to_string()
946
947
948 class FontButtonPreference(Preference):
949 """
950 Font button
951 """
952
953 def __init__(self, preferences, widget):
954 Preference.__init__(self, preferences, widget)
955
956 def _setup_change(self):
957 self.widget.connect('font-set', self.change)
958
959 def _set_value(self):
960 font = settings.get_option(self.name, self.default)
961 self.widget.set_font_name(font)
962
963 def _get_value(self):
964 font = self.widget.get_font_name()
965 return font
966
967
968 class FontResetButtonPreference(Button, Conditional):
969 """
970 A button to reset a font button to a default font
971 """
972
973 def __init__(self, preferences, widget):
974 Button.__init__(self, preferences, widget)
975 Conditional.__init__(self)
976
977 def on_check_condition(self):
978 if self.condition_widget.get_font_name() == self.default:
979 return False
980 return True
981
982 def on_clicked(self, button):
983 self.condition_widget.set_font_name(self.default)
984 self.condition_widget.emit('font-set')
985
986
987 class ComboPreference(Preference):
988 """
989 A combo box. The value stored in the settings must be the
990 first column of the combo box model.
991 """
992
993 def __init__(self, preferences, widget):
994 Preference.__init__(self, preferences, widget)
995
996 def _setup_change(self):
997 self.widget.connect('changed', self.change)
998
999 def _set_value(self):
1000 """
1001 Sets the preferences for this widget
1002 """
1003 item = settings.get_option(self.name, self.default)
1004
1005 model = self.widget.get_model()
1006
1007 for row in model:
1008 if item == row[0]:
1009 self.widget.set_active_iter(row.iter)
1010
1011 def _get_value(self):
1012 """
1013 Value to be stored into the settings file
1014 """
1015 model = self.widget.get_model()
1016 iter = self.widget.get_active_iter()
1017
1018 return model.get_value(iter, 0)
1019
1020
1021 class ComboEntryPreference(Preference):
1022 """
1023 A combo box allowing for user defined
1024 values, presets and auto completion
1025
1026 Options:
1027 * completion_items (List of completion items or
1028 dictionary of items and their titles)
1029 * preset_items (List of preset items or
1030 dictionary of items and their titles)
1031 """
1032
1033 def __init__(self, preferences, widget):
1034 Preference.__init__(self, preferences, widget)
1035
1036 self.list = Gtk.ListStore(str)
1037
1038 try:
1039 try:
1040 preset_items = list(self.preset_items.items())
1041 self.list = Gtk.ListStore(str, str)
1042 text_renderer = self.widget.get_cells()[0]
1043 text_renderer.set_property('weight', Pango.Weight.BOLD)
1044
1045 title_renderer = Gtk.CellRendererText()
1046 self.widget.pack_start(title_renderer, False)
1047 self.widget.add_attribute(title_renderer, 'text', 1)
1048 except AttributeError:
1049 preset_items = [[item] for item in self.preset_items]
1050
1051 for preset in preset_items:
1052 self.list.append(preset)
1053 except AttributeError:
1054 pass
1055
1056 self.widget.set_model(self.list)
1057 self.widget.set_entry_text_column(0)
1058
1059 try:
1060 completion = Gtk.EntryCompletion()
1061
1062 try:
1063 completion_items = list(self.completion_items.items())
1064 self.completion_list = Gtk.ListStore(str, str)
1065
1066 title_renderer = Gtk.CellRendererText()
1067 completion.pack_end(title_renderer, True)
1068 completion.add_attribute(title_renderer, 'text', 1)
1069 except AttributeError:
1070 completion_items = [[item] for item in self.completion_items]
1071 self.completion_list = Gtk.ListStore(str)
1072
1073 keyword_renderer = Gtk.CellRendererText()
1074 keyword_renderer.set_property('weight', Pango.Weight.BOLD)
1075 completion.pack_end(keyword_renderer, True)
1076 completion.add_attribute(keyword_renderer, 'text', 0)
1077 completion.set_match_func(self.on_matching)
1078 completion.connect('match-selected', self.on_match_selected)
1079
1080 completion.set_popup_single_match(True)
1081 completion.set_model(self.completion_list)
1082 self.widget.get_child().set_completion(completion)
1083
1084 for item in completion_items:
1085 self.completion_list.append(item)
1086 except AttributeError:
1087 pass
1088
1089 def _setup_change(self):
1090 """
1091 Sets up the function to be called
1092 when this preference is changed
1093 """
1094 self.widget.connect('changed', self.change, self.name, self._get_value())
1095
1096 def _set_value(self):
1097 """
1098 Sets the preferences for this widget
1099 """
1100 value = settings.get_option(self.name, self.default)
1101 self.widget.get_child().set_text(str(value))
1102
1103 def _get_value(self):
1104 """
1105 Value to be stored into the settings file
1106 """
1107 return self.widget.get_child().get_text()
1108
1109 def on_matching(self, completion, text, iter):
1110 """
1111 Matches the content of this box to
1112 the list of available completions
1113 """
1114 cursor_pos = self.widget.get_child().get_position()
1115 # Ignore the rest, allows for completions in the middle
1116 text = text[:cursor_pos]
1117 match = self.completion_list.get_value(iter, 0)
1118
1119 # Try to find match, from largest to smallest
1120 for i in range(len(match), -1, -1):
1121 # Find from the rear
1122 match_pos = text.rfind(match[:i])
1123 # Matched if the match is not empty
1124 # and equal to the text from the matched position to the end
1125 # and not equal to the match itself
1126 # (the latter hides the match if it was already fully typed)
1127 if match[:i] and match[:i] == text[match_pos:] and match[:i] != match:
1128 return True
1129 return False
1130
1131 def on_match_selected(self, completion, list, iter):
1132 """
1133 Inserts the selected completion
1134 """
1135 cursor_pos = self.widget.get_child().get_position()
1136 text = self.widget.get_child().get_text()[:cursor_pos]
1137 match = list.get_value(iter, 0)
1138
1139 for i in range(len(match), -1, -1):
1140 match_pos = text.rfind(match[:i])
1141 if match[:i] and match[:i] == text[match_pos:]:
1142 # Delete halfway typed text
1143 self.widget.get_child().delete_text(
1144 match_pos, match_pos + len(match[:i])
1145 )
1146 # Insert match at matched position
1147 self.widget.get_child().insert_text(match, match_pos)
1148 # Update cursor position
1149 self.widget.get_child().set_position(match_pos + len(match))
1150
1151 return True
1152
1153
1154 # vim: et sts=4 sw=4