/
settings.py
1342 lines (1033 loc) · 44.1 KB
/
settings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Settings
========
.. versionadded:: 1.0.7
This module provides a complete and extensible framework for adding a
Settings interface to your application. By default, the interface uses
a :class:`SettingsWithSpinner`, which consists of a
:class:`~kivy.uix.spinner.Spinner` (top) to switch between individual
settings panels (bottom). See :ref:`differentlayouts` for some
alternatives.
.. image:: images/settingswithspinner_kivy.jpg
:align: center
A :class:`SettingsPanel` represents a group of configurable options. The
:attr:`SettingsPanel.title` property is used by :class:`Settings` when a panel
is added: it determines the name of the sidebar button. SettingsPanel controls
a :class:`~kivy.config.ConfigParser` instance.
The panel can be automatically constructed from a JSON definition file: you
describe the settings you want and corresponding sections/keys in the
ConfigParser instance... and you're done!
Settings are also integrated into the :class:`~kivy.app.App` class. Use
:meth:`Settings.add_kivy_panel` to configure the Kivy core settings in a panel.
.. _settings_json:
Create a panel from JSON
------------------------
To create a panel from a JSON-file, you need two things:
* a :class:`~kivy.config.ConfigParser` instance with default values
* a JSON file
.. warning::
The :class:`kivy.config.ConfigParser` is required. You cannot use the
default ConfigParser from Python libraries.
You must create and handle the :class:`~kivy.config.ConfigParser`
object. SettingsPanel will read the values from the associated
ConfigParser instance. Make sure you have set default values (using
:attr:`~kivy.config.ConfigParser.setdefaults`) for all the sections/keys
in your JSON file!
The JSON file contains structured information to describe the available
settings. Here is an example::
[
{
"type": "title",
"title": "Windows"
},
{
"type": "bool",
"title": "Fullscreen",
"desc": "Set the window in windowed or fullscreen",
"section": "graphics",
"key": "fullscreen"
}
]
Each element in the root list represents a setting that the user can
configure. Only the "type" key is mandatory: an instance of the associated
class will be created and used for the setting - other keys are assigned to
corresponding properties of that class.
============== =================================================
Type Associated class
-------------- -------------------------------------------------
title :class:`SettingTitle`
bool :class:`SettingBoolean`
numeric :class:`SettingNumeric`
options :class:`SettingOptions`
string :class:`SettingString`
path :class:`SettingPath`
color :class:`SettingColor`
============== =================================================
.. versionadded:: 1.1.0
Added :attr:`SettingPath` type
.. versionadded:: 2.1.0
Added :attr:`SettingColor` type
In the JSON example above, the first element is of type "title". It will create
a new instance of :class:`SettingTitle` and apply the rest of the key-value
pairs to the properties of that class, i.e. "title": "Windows" sets the
:attr:`~SettingsPanel.title` property of the panel to "Windows".
To load the JSON example to a :class:`Settings` instance, use the
:meth:`Settings.add_json_panel` method. It will automatically instantiate a
:class:`SettingsPanel` and add it to :class:`Settings`::
from kivy.config import ConfigParser
config = ConfigParser()
config.read('myconfig.ini')
s = Settings()
s.add_json_panel('My custom panel', config, 'settings_custom.json')
s.add_json_panel('Another panel', config, 'settings_test2.json')
# then use the s as a widget...
.. _differentlayouts:
Different panel layouts
-----------------------
A kivy :class:`~kivy.app.App` can automatically create and display a
:class:`Settings` instance. See the :attr:`~kivy.app.App.settings_cls`
documentation for details on how to choose which settings class to
display.
Several pre-built settings widgets are available. All except
:class:`SettingsWithNoMenu` include close buttons triggering the
on_close event.
- :class:`Settings`: Displays settings with a sidebar at the left to
switch between json panels.
- :class:`SettingsWithSidebar`: A trivial subclass of
:class:`Settings`.
- :class:`SettingsWithSpinner`: Displays settings with a spinner at
the top, which can be used to switch between json panels. Uses
:class:`InterfaceWithSpinner` as the
:attr:`~Settings.interface_cls`. This is the default behavior from
Kivy 1.8.0.
- :class:`SettingsWithTabbedPanel`: Displays json panels as individual
tabs in a :class:`~kivy.uix.tabbedpanel.TabbedPanel`. Uses
:class:`InterfaceWithTabbedPanel` as the :attr:`~Settings.interface_cls`.
- :class:`SettingsWithNoMenu`: Displays a single json panel, with no
way to switch to other panels and no close button. This makes it
impossible for the user to exit unless
:meth:`~kivy.app.App.close_settings` is overridden with a different
close trigger! Uses :class:`InterfaceWithNoMenu` as the
:attr:`~Settings.interface_cls`.
You can construct your own settings panels with any layout you choose
by setting :attr:`Settings.interface_cls`. This should be a widget
that displays a json settings panel with some way to switch between
panels. An instance will be automatically created by :class:`Settings`.
Interface widgets may be anything you like, but *must* have a method
add_panel that receives newly created json settings panels for the
interface to display. See the documentation for
:class:`InterfaceWithSidebar` for more information. They may
optionally dispatch an on_close event, for instance if a close button
is clicked. This event is used by :class:`Settings` to trigger its own
on_close event.
For a complete, working example, please see
:file:`kivy/examples/settings/main.py`.
'''
__all__ = ('Settings', 'SettingsPanel', 'SettingItem', 'SettingString',
'SettingPath', 'SettingBoolean', 'SettingNumeric', 'SettingOptions',
'SettingTitle', 'SettingsWithSidebar', 'SettingsWithSpinner',
'SettingsWithTabbedPanel', 'SettingsWithNoMenu',
'InterfaceWithSidebar', 'ContentPanel', 'MenuSidebar')
import json
import os
import kivy.utils as utils
from kivy.factory import Factory
from kivy.metrics import dp
from kivy.config import ConfigParser
from kivy.animation import Animation
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.tabbedpanel import TabbedPanelHeader
from kivy.uix.button import Button
from kivy.uix.filechooser import FileChooserListView
from kivy.uix.colorpicker import ColorPicker
from kivy.uix.scrollview import ScrollView
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.textinput import TextInput
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty, StringProperty, ListProperty, \
BooleanProperty, NumericProperty, DictProperty
class SettingSpacer(Widget):
# Internal class, not documented.
pass
class SettingItem(FloatLayout):
'''Base class for individual settings (within a panel). This class cannot
be used directly; it is used for implementing the other setting classes.
It builds a row with a title/description (left) and a setting control
(right).
Look at :class:`SettingBoolean`, :class:`SettingNumeric` and
:class:`SettingOptions` for usage examples.
:Events:
`on_release`
Fired when the item is touched and then released.
'''
title = StringProperty('<No title set>')
'''Title of the setting, defaults to '<No title set>'.
:attr:`title` is a :class:`~kivy.properties.StringProperty` and defaults
to '<No title set>'.
'''
desc = StringProperty(None, allownone=True)
'''Description of the setting, rendered on the line below the title.
:attr:`desc` is a :class:`~kivy.properties.StringProperty` and defaults to
None.
'''
disabled = BooleanProperty(False)
'''Indicate if this setting is disabled. If True, all touches on the
setting item will be discarded.
:attr:`disabled` is a :class:`~kivy.properties.BooleanProperty` and
defaults to False.
'''
section = StringProperty(None)
'''Section of the token inside the :class:`~kivy.config.ConfigParser`
instance.
:attr:`section` is a :class:`~kivy.properties.StringProperty` and defaults
to None.
'''
key = StringProperty(None)
'''Key of the token inside the :attr:`section` in the
:class:`~kivy.config.ConfigParser` instance.
:attr:`key` is a :class:`~kivy.properties.StringProperty` and defaults to
None.
'''
value = ObjectProperty(None)
'''Value of the token according to the :class:`~kivy.config.ConfigParser`
instance. Any change to this value will trigger a
:meth:`Settings.on_config_change` event.
:attr:`value` is an :class:`~kivy.properties.ObjectProperty` and defaults
to None.
'''
panel = ObjectProperty(None)
'''(internal) Reference to the SettingsPanel for this setting. You don't
need to use it.
:attr:`panel` is an :class:`~kivy.properties.ObjectProperty` and defaults
to None.
'''
content = ObjectProperty(None)
'''(internal) Reference to the widget that contains the real setting.
As soon as the content object is set, any further call to add_widget will
call the content.add_widget. This is automatically set.
:attr:`content` is an :class:`~kivy.properties.ObjectProperty` and
defaults to None.
'''
selected_alpha = NumericProperty(0)
'''(internal) Float value from 0 to 1, used to animate the background when
the user touches the item.
:attr:`selected_alpha` is a :class:`~kivy.properties.NumericProperty` and
defaults to 0.
'''
__events__ = ('on_release', )
def __init__(self, **kwargs):
super(SettingItem, self).__init__(**kwargs)
self.value = self.panel.get_value(self.section, self.key)
def add_widget(self, *args, **kwargs):
if self.content is None:
return super(SettingItem, self).add_widget(*args, **kwargs)
return self.content.add_widget(*args, **kwargs)
def on_touch_down(self, touch):
if not self.collide_point(*touch.pos):
return
if self.disabled:
return
touch.grab(self)
self.selected_alpha = 1
return super(SettingItem, self).on_touch_down(touch)
def on_touch_up(self, touch):
if touch.grab_current is self:
touch.ungrab(self)
self.dispatch('on_release')
Animation(selected_alpha=0, d=.25, t='out_quad').start(self)
return True
return super(SettingItem, self).on_touch_up(touch)
def on_release(self):
pass
def on_value(self, instance, value):
if not self.section or not self.key:
return
# get current value in config
panel = self.panel
if not isinstance(value, str):
value = str(value)
panel.set_value(self.section, self.key, value)
class SettingBoolean(SettingItem):
'''Implementation of a boolean setting on top of a :class:`SettingItem`.
It is visualized with a :class:`~kivy.uix.switch.Switch` widget.
By default, 0 and 1 are used for values: you can change them by setting
:attr:`values`.
'''
values = ListProperty(['0', '1'])
'''Values used to represent the state of the setting. If you want to use
"yes" and "no" in your ConfigParser instance::
SettingBoolean(..., values=['no', 'yes'])
.. warning::
You need a minimum of two values, the index 0 will be used as False,
and index 1 as True
:attr:`values` is a :class:`~kivy.properties.ListProperty` and defaults to
['0', '1']
'''
class SettingString(SettingItem):
'''Implementation of a string setting on top of a :class:`SettingItem`.
It is visualized with a :class:`~kivy.uix.label.Label` widget that, when
clicked, will open a :class:`~kivy.uix.popup.Popup` with a
:class:`~kivy.uix.textinput.Textinput` so the user can enter a custom
value.
'''
popup = ObjectProperty(None, allownone=True)
'''(internal) Used to store the current popup when it's shown.
:attr:`popup` is an :class:`~kivy.properties.ObjectProperty` and defaults
to None.
'''
textinput = ObjectProperty(None)
'''(internal) Used to store the current textinput from the popup and
to listen for changes.
:attr:`textinput` is an :class:`~kivy.properties.ObjectProperty` and
defaults to None.
'''
def on_panel(self, instance, value):
if value is None:
return
self.fbind('on_release', self._create_popup)
def _dismiss(self, *largs):
if self.textinput:
self.textinput.focus = False
if self.popup:
self.popup.dismiss()
self.popup = None
def _validate(self, instance):
self._dismiss()
value = self.textinput.text.strip()
self.value = value
def _create_popup(self, instance):
# create popup layout
content = BoxLayout(orientation='vertical', spacing='5dp')
popup_width = min(0.95 * Window.width, dp(500))
self.popup = popup = Popup(
title=self.title, content=content, size_hint=(None, None),
size=(popup_width, '250dp'))
# create the textinput used for numeric input
self.textinput = textinput = TextInput(
text=self.value, font_size='24sp', multiline=False,
size_hint_y=None, height='42sp')
textinput.bind(on_text_validate=self._validate)
self.textinput = textinput
# construct the content, widget are used as a spacer
content.add_widget(Widget())
content.add_widget(textinput)
content.add_widget(Widget())
content.add_widget(SettingSpacer())
# 2 buttons are created for accept or cancel the current value
btnlayout = BoxLayout(size_hint_y=None, height='50dp', spacing='5dp')
btn = Button(text='Ok')
btn.bind(on_release=self._validate)
btnlayout.add_widget(btn)
btn = Button(text='Cancel')
btn.bind(on_release=self._dismiss)
btnlayout.add_widget(btn)
content.add_widget(btnlayout)
# all done, open the popup !
popup.open()
class SettingPath(SettingItem):
'''Implementation of a Path setting on top of a :class:`SettingItem`.
It is visualized with a :class:`~kivy.uix.label.Label` widget that, when
clicked, will open a :class:`~kivy.uix.popup.Popup` with a
:class:`~kivy.uix.filechooser.FileChooserListView` so the user can enter
a custom value.
.. versionadded:: 1.1.0
'''
popup = ObjectProperty(None, allownone=True)
'''(internal) Used to store the current popup when it is shown.
:attr:`popup` is an :class:`~kivy.properties.ObjectProperty` and defaults
to None.
'''
textinput = ObjectProperty(None)
'''(internal) Used to store the current textinput from the popup and
to listen for changes.
:attr:`textinput` is an :class:`~kivy.properties.ObjectProperty` and
defaults to None.
'''
show_hidden = BooleanProperty(False)
'''Whether to show 'hidden' filenames. What that means is
operating-system-dependent.
:attr:`show_hidden` is an :class:`~kivy.properties.BooleanProperty` and
defaults to False.
.. versionadded:: 1.10.0
'''
dirselect = BooleanProperty(True)
'''Whether to allow selection of directories.
:attr:`dirselect` is a :class:`~kivy.properties.BooleanProperty` and
defaults to True.
.. versionadded:: 1.10.0
'''
def on_panel(self, instance, value):
if value is None:
return
self.fbind('on_release', self._create_popup)
def _dismiss(self, *largs):
if self.textinput:
self.textinput.focus = False
if self.popup:
self.popup.dismiss()
self.popup = None
def _validate(self, instance):
self._dismiss()
value = self.textinput.selection
if not value:
return
self.value = os.path.realpath(value[0])
def _create_popup(self, instance):
# create popup layout
content = BoxLayout(orientation='vertical', spacing=5)
popup_width = min(0.95 * Window.width, dp(500))
self.popup = popup = Popup(
title=self.title, content=content, size_hint=(None, 0.9),
width=popup_width)
# create the filechooser
initial_path = self.value or os.getcwd()
self.textinput = textinput = FileChooserListView(
path=initial_path, size_hint=(1, 1),
dirselect=self.dirselect, show_hidden=self.show_hidden)
textinput.bind(on_path=self._validate)
# construct the content
content.add_widget(textinput)
content.add_widget(SettingSpacer())
# 2 buttons are created for accept or cancel the current value
btnlayout = BoxLayout(size_hint_y=None, height='50dp', spacing='5dp')
btn = Button(text='Ok')
btn.bind(on_release=self._validate)
btnlayout.add_widget(btn)
btn = Button(text='Cancel')
btn.bind(on_release=self._dismiss)
btnlayout.add_widget(btn)
content.add_widget(btnlayout)
# all done, open the popup !
popup.open()
class SettingColor(SettingItem):
'''Implementation of a color setting on top of a :class:`SettingItem`.
It is visualized with a :class:`~kivy.uix.label.Label` widget and a
colored canvas rectangle that, when clicked, will open a
:class:`~kivy.uix.popup.Popup` with a
:class:`~kivy.uix.colorpicker.ColorPicker` so the user can choose a color.
.. versionadded:: 2.0.1
'''
popup = ObjectProperty(None, allownone=True)
'''(internal) Used to store the current popup when it's shown.
:attr:`popup` is an :class:`~kivy.properties.ObjectProperty` and defaults
to None.
'''
def on_panel(self, instance, value):
if value is None:
return
self.bind(on_release=self._create_popup)
def _dismiss(self, *largs):
if self.popup:
self.popup.dismiss()
self.popup = None
def _validate(self, instance):
self._dismiss()
value = utils.get_hex_from_color(self.colorpicker.color)
self.value = value
def _create_popup(self, instance):
# create popup layout
content = BoxLayout(orientation='vertical', spacing='5dp')
popup_width = min(0.95 * Window.width, dp(500))
self.popup = popup = Popup(
title=self.title, content=content, size_hint=(None, 0.9),
width=popup_width)
self.colorpicker = colorpicker = \
ColorPicker(color=utils.get_color_from_hex(self.value))
colorpicker.bind(on_color=self._validate)
self.colorpicker = colorpicker
content.add_widget(colorpicker)
content.add_widget(SettingSpacer())
# 2 buttons are created for accept or cancel the current value
btnlayout = BoxLayout(size_hint_y=None, height='50dp', spacing='5dp')
btn = Button(text='Ok')
btn.bind(on_release=self._validate)
btnlayout.add_widget(btn)
btn = Button(text='Cancel')
btn.bind(on_release=self._dismiss)
btnlayout.add_widget(btn)
content.add_widget(btnlayout)
# all done, open the popup !
popup.open()
class SettingNumeric(SettingString):
'''Implementation of a numeric setting on top of a :class:`SettingString`.
It is visualized with a :class:`~kivy.uix.label.Label` widget that, when
clicked, will open a :class:`~kivy.uix.popup.Popup` with a
:class:`~kivy.uix.textinput.Textinput` so the user can enter a custom
value.
'''
def _validate(self, instance):
# we know the type just by checking if there is a '.' in the original
# value
is_float = '.' in str(self.value)
self._dismiss()
try:
if is_float:
self.value = str(float(self.textinput.text))
else:
self.value = str(int(self.textinput.text))
except ValueError:
return
class SettingOptions(SettingItem):
'''Implementation of an option list on top of a :class:`SettingItem`.
It is visualized with a :class:`~kivy.uix.label.Label` widget that, when
clicked, will open a :class:`~kivy.uix.popup.Popup` with a
list of options from which the user can select.
'''
options = ListProperty([])
'''List of all availables options. This must be a list of "string" items.
Otherwise, it will crash. :)
:attr:`options` is a :class:`~kivy.properties.ListProperty` and defaults
to [].
'''
popup = ObjectProperty(None, allownone=True)
'''(internal) Used to store the current popup when it is shown.
:attr:`popup` is an :class:`~kivy.properties.ObjectProperty` and defaults
to None.
'''
def on_panel(self, instance, value):
if value is None:
return
self.fbind('on_release', self._create_popup)
def _set_option(self, instance):
self.value = instance.text
self.popup.dismiss()
def _create_popup(self, instance):
# create the popup
content = BoxLayout(orientation='vertical', spacing='5dp')
popup_width = min(0.95 * Window.width, dp(500))
self.popup = popup = Popup(
content=content, title=self.title, size_hint=(None, None),
size=(popup_width, '400dp'))
popup.height = len(self.options) * dp(55) + dp(150)
# add all the options
content.add_widget(Widget(size_hint_y=None, height=1))
uid = str(self.uid)
for option in self.options:
state = 'down' if option == self.value else 'normal'
btn = ToggleButton(text=option, state=state, group=uid)
btn.bind(on_release=self._set_option)
content.add_widget(btn)
# finally, add a cancel button to return on the previous panel
content.add_widget(SettingSpacer())
btn = Button(text='Cancel', size_hint_y=None, height=dp(50))
btn.bind(on_release=popup.dismiss)
content.add_widget(btn)
# and open the popup !
popup.open()
class SettingTitle(Label):
'''A simple title label, used to organize the settings in sections.
'''
title = StringProperty()
panel = ObjectProperty(None)
class SettingsPanel(GridLayout):
'''This class is used to construct panel settings, for use with a
:class:`Settings` instance or subclass.
'''
title = StringProperty('Default title')
'''Title of the panel. The title will be reused by the :class:`Settings` in
the sidebar.
'''
config = ObjectProperty(None, allownone=True)
'''A :class:`kivy.config.ConfigParser` instance. See module documentation
for more information.
'''
settings = ObjectProperty(None)
'''A :class:`Settings` instance that will be used to fire the
`on_config_change` event.
'''
def __init__(self, **kwargs):
kwargs.setdefault('cols', 1)
super(SettingsPanel, self).__init__(**kwargs)
def on_config(self, instance, value):
if value is None:
return
if not isinstance(value, ConfigParser):
raise Exception('Invalid config object, you must use a'
'kivy.config.ConfigParser, not another one !')
def get_value(self, section, key):
'''Return the value of the section/key from the :attr:`config`
ConfigParser instance. This function is used by :class:`SettingItem` to
get the value for a given section/key.
If you don't want to use a ConfigParser instance, you might want to
override this function.
'''
config = self.config
if not config:
return
return config.get(section, key)
def set_value(self, section, key, value):
current = self.get_value(section, key)
if current == value:
return
config = self.config
if config:
config.set(section, key, value)
config.write()
settings = self.settings
if settings:
settings.dispatch('on_config_change',
config, section, key, value)
class InterfaceWithSidebar(BoxLayout):
'''The default Settings interface class. It displays a sidebar menu
with names of available settings panels, which may be used to switch
which one is currently displayed.
See :meth:`~InterfaceWithSidebar.add_panel` for information on the
method you must implement if creating your own interface.
This class also dispatches an event 'on_close', which is triggered
when the sidebar menu's close button is released. If creating your
own interface widget, it should also dispatch such an event which
will automatically be caught by :class:`Settings` and used to
trigger its own 'on_close' event.
'''
menu = ObjectProperty()
'''(internal) A reference to the sidebar menu widget.
:attr:`menu` is an :class:`~kivy.properties.ObjectProperty` and
defaults to None.
'''
content = ObjectProperty()
'''(internal) A reference to the panel display widget (a
:class:`ContentPanel`).
:attr:`content` is an :class:`~kivy.properties.ObjectProperty` and
defaults to None.
'''
__events__ = ('on_close', )
def __init__(self, *args, **kwargs):
super(InterfaceWithSidebar, self).__init__(*args, **kwargs)
self.menu.close_button.bind(
on_release=lambda j: self.dispatch('on_close'))
def add_panel(self, panel, name, uid):
'''This method is used by Settings to add new panels for possible
display. Any replacement for ContentPanel *must* implement
this method.
:Parameters:
`panel`: :class:`SettingsPanel`
It should be stored and the interface should provide a way to
switch between panels.
`name`:
The name of the panel as a string. It may be used to represent
the panel but isn't necessarily unique.
`uid`:
A unique int identifying the panel. It should be used to
identify and switch between panels.
'''
self.menu.add_item(name, uid)
self.content.add_panel(panel, name, uid)
def on_close(self, *args):
pass
class InterfaceWithSpinner(BoxLayout):
'''A settings interface that displays a spinner at the top for
switching between panels.
The workings of this class are considered internal and are not
documented. See :meth:`InterfaceWithSidebar` for
information on implementing your own interface class.
'''
__events__ = ('on_close', )
menu = ObjectProperty()
'''(internal) A reference to the sidebar menu widget.
:attr:`menu` is an :class:`~kivy.properties.ObjectProperty` and
defaults to None.
'''
content = ObjectProperty()
'''(internal) A reference to the panel display widget (a
:class:`ContentPanel`).
:attr:`menu` is an :class:`~kivy.properties.ObjectProperty` and
defaults to None.
'''
def __init__(self, *args, **kwargs):
super(InterfaceWithSpinner, self).__init__(*args, **kwargs)
self.menu.close_button.bind(
on_release=lambda j: self.dispatch('on_close'))
def add_panel(self, panel, name, uid):
'''This method is used by Settings to add new panels for possible
display. Any replacement for ContentPanel *must* implement
this method.
:Parameters:
`panel`: :class:`SettingsPanel`
It should be stored and the interface should provide a way to
switch between panels.
`name`:
The name of the panel as a string. It may be used to represent
the panel but may not be unique.
`uid`:
A unique int identifying the panel. It should be used to
identify and switch between panels.
'''
self.content.add_panel(panel, name, uid)
self.menu.add_item(name, uid)
def on_close(self, *args):
pass
class ContentPanel(ScrollView):
'''A class for displaying settings panels. It displays a single
settings panel at a time, taking up the full size and shape of the
ContentPanel. It is used by :class:`InterfaceWithSidebar` and
:class:`InterfaceWithSpinner` to display settings.
'''
panels = DictProperty({})
'''(internal) Stores a dictionary mapping settings panels to their uids.
:attr:`panels` is a :class:`~kivy.properties.DictProperty` and
defaults to {}.
'''
container = ObjectProperty()
'''(internal) A reference to the GridLayout that contains the
settings panel.
:attr:`container` is an :class:`~kivy.properties.ObjectProperty` and
defaults to None.
'''
current_panel = ObjectProperty(None)
'''(internal) A reference to the current settings panel.
:attr:`current_panel` is an :class:`~kivy.properties.ObjectProperty` and
defaults to None.
'''
current_uid = NumericProperty(0)
'''(internal) A reference to the uid of the current settings panel.
:attr:`current_uid` is a
:class:`~kivy.properties.NumericProperty` and defaults to 0.
'''
def add_panel(self, panel, name, uid):
'''This method is used by Settings to add new panels for possible
display. Any replacement for ContentPanel *must* implement
this method.
:Parameters:
`panel`: :class:`SettingsPanel`
It should be stored and displayed when requested.
`name`:
The name of the panel as a string. It may be used to represent
the panel.
`uid`:
A unique int identifying the panel. It should be stored and
used to identify panels when switching.
'''
self.panels[uid] = panel
if not self.current_uid:
self.current_uid = uid
def on_current_uid(self, *args):
'''The uid of the currently displayed panel. Changing this will
automatically change the displayed panel.
:Parameters:
`uid`:
A panel uid. It should be used to retrieve and display
a settings panel that has previously been added with
:meth:`add_panel`.
'''
uid = self.current_uid
if uid in self.panels:
if self.current_panel is not None:
self.remove_widget(self.current_panel)
new_panel = self.panels[uid]
self.add_widget(new_panel)
self.current_panel = new_panel
return True
return False # New uid doesn't exist
def add_widget(self, *args, **kwargs):
if self.container is None:
super(ContentPanel, self).add_widget(*args, **kwargs)
else:
self.container.add_widget(*args, **kwargs)
def remove_widget(self, *args, **kwargs):
self.container.remove_widget(*args, **kwargs)
class Settings(BoxLayout):
'''Settings UI. Check module documentation for more information on how
to use this class.
:Events:
`on_config_change`: ConfigParser instance, section, key, value
Fired when the section's key-value pair of a ConfigParser changes.
.. warning:
value will be str/unicode type, regardless of the setting
type (numeric, boolean, etc)
`on_close`
Fired by the default panel when the Close button is pressed.
'''
interface = ObjectProperty(None)
'''(internal) Reference to the widget that will contain, organise and
display the panel configuration panel widgets.
:attr:`interface` is an :class:`~kivy.properties.ObjectProperty` and
defaults to None.
'''
interface_cls = ObjectProperty(InterfaceWithSidebar)
'''The widget class that will be used to display the graphical
interface for the settings panel. By default, it displays one Settings
panel at a time with a sidebar to switch between them.
:attr:`interface_cls` is an
:class:`~kivy.properties.ObjectProperty` and defaults to
:class:`InterfaceWithSidebar`.
.. versionchanged:: 1.8.0
If you set a string, the :class:`~kivy.factory.Factory` will be used to
resolve the class.
'''
__events__ = ('on_close', 'on_config_change')
def __init__(self, *args, **kargs):
self._types = {}
super(Settings, self).__init__(*args, **kargs)
self.add_interface()
self.register_type('string', SettingString)
self.register_type('bool', SettingBoolean)
self.register_type('numeric', SettingNumeric)
self.register_type('options', SettingOptions)