~ubuntu-branches/ubuntu/precise/compizconfig-python/precise

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
'''
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

Authors:
    Quinn Storm (quinn@beryl-project.org)
    Patrick Niklaus (marex@opencompositing.org)
    Guillaume Seguin (guillaume@segu.in)
Copyright (C) 2007 Quinn Storm
'''

import operator
StringSettingKeyFunc = operator.itemgetter (1)

ctypedef unsigned int Bool

cdef enum CCSSettingType:
    TypeBool
    TypeInt
    TypeFloat
    TypeString
    TypeColor
    TypeAction
    TypeKey
    TypeButton
    TypeEdge
    TypeBell
    TypeMatch
    TypeList
    TypeNum

cdef enum CCSPluginConflictType:
    # produced on plugin activation
    ConflictRequiresPlugin,
    ConflictRequiresFeature,
    ConflictFeature,
    ConflictPlugin,
    # produced on plugin deactivation
    ConflictFeatureNeeded,
    ConflictPluginNeeded,
    ConflictPluginError

SettingTypeString = [
    "Bool",
    "Int",
    "Float",
    "String",
    "Color",
    "Action",
    "Key",
    "Button",
    "Edge",
    "Bell",
    "Match",
    "List",
    "Invalid"
]

ConflictTypeString = [
    "RequiresPlugin", #A
    "RequiresFeature", #A
    "ConflictFeature", #A
    "ConflictPlugin", #A
    "FeatureNeeded", #D
    "PluginNeeded", #D
    "PluginError"
]

cdef struct CCSList:
    void *    data
    CCSList * next

ctypedef CCSList CCSSettingList
ctypedef CCSList CCSPluginList
ctypedef CCSList CCSStringList
ctypedef CCSList CCSGroupList
ctypedef CCSList CCSSubGroupList
ctypedef CCSList CCSPluginConflictList
ctypedef CCSList CCSSettingValueList
ctypedef CCSList CCSBackendInfoList
ctypedef CCSList CCSIntDescList
ctypedef CCSList CCSStrRestrictionList
ctypedef CCSList CCSStrExtensionList

cdef struct CCSBackendInfo:
    char *       name
    char *       shortDesc
    char *       longDesc
    Bool         integrationSupport
    Bool         profileSupport
    unsigned int refCount

cdef struct CCSSettingKeyValue:
    int          keysym
    unsigned int keyModMask

cdef struct CCSSettingButtonValue:
    int          button
    unsigned int buttonModMask
    int          edgeMask

cdef struct CCSSettingColorValueColor:
    unsigned short red
    unsigned short green
    unsigned short blue
    unsigned short alpha

cdef union CCSSettingColorValue:
    CCSSettingColorValueColor color
    unsigned short            array[4]

cdef union CCSSettingValueUnion:
    Bool                  asBool
    int                   asInt
    float                 asFloat
    char *                asString
    char *                asMatch
    CCSSettingColorValue  asColor
    CCSSettingValueList * asList
    CCSSettingKeyValue    asKey
    CCSSettingButtonValue asButton
    unsigned int          asEdge
    Bool                  asBell

cdef struct CCSIntDesc:
    int          value
    char *       name
    unsigned int refCount

cdef struct CCSStrRestriction:
    char *       value
    char *       name
    unsigned int refCount

cdef struct CCSSettingIntInfo:
    int              min
    int              max
    CCSIntDescList * desc

cdef struct CCSSettingFloatInfo:
    float min
    float max
    float precision

cdef struct CCSSettingStringInfo:
    CCSStrRestrictionList * restriction
    int                     sortStartsAt
    Bool                    extensible

cdef struct CCSSettingListInfo:
    CCSSettingType listType
    void *         listInfo # actually CCSSettingInfo *, works around pyrex

cdef struct CCSSettingActionInfo:
    Bool internal

cdef union CCSSettingInfo:
    CCSSettingIntInfo    forInt
    CCSSettingFloatInfo  forFloat
    CCSSettingStringInfo forString
    CCSSettingListInfo   forList
    CCSSettingActionInfo forAction

cdef struct CCSSettingValue:
    CCSSettingValueUnion value
    void *               parent
    Bool                 isListChild
    unsigned int         refCount

cdef struct CCSGroup:
    char *            name
    CCSSubGroupList * subGroups
    unsigned int      refCount

cdef struct CCSSubGroup:
    char *           name
    CCSSettingList * settings
    unsigned int     refCount

cdef struct CCSPluginCategory:
    char *          name
    char *          shortDesc
    char *          longDesc
    CCSStringList * plugins

cdef struct CCSContext:
    CCSPluginList *     plugins
    CCSPluginCategory * categories

    void * priv
    void * ccsPrivate

    CCSSettingList * changedSettings
    unsigned int   screenNum

cdef struct CCSPlugin

cdef struct CCSSetting:
    char * name
    char * shortDesc
    char * longDesc

    CCSSettingType type

    CCSSettingInfo info
    char *         group
    char *         subGroup
    char *         hints

    CCSSettingValue   defaultValue
    CCSSettingValue * value
    Bool              isDefault

    CCSPlugin * parent
    void *      priv
    unsigned int refCount

cdef struct CCSStrExtension:
    char *                  basePlugin
    CCSSettingList *        baseSettings
    CCSStrRestrictionList * restriction
    unsigned int            refCount

cdef struct CCSPlugin:
    char * name
    char * shortDesc
    char * longDesc
    char * hints
    char * category

    CCSStringList * loadAfter
    CCSStringList * loadBefore
    CCSStringList * requiresPlugin
    CCSStringList * conflictPlugin
    CCSStringList * conflictFeature
    CCSStringList * providesFeature
    CCSStringList * requiresFeature

    void *       priv
    CCSContext * context
    void *       ccsPrivate
    unsigned int refCount

cdef struct CCSPluginConflict:
    char *                value
    CCSPluginConflictType type
    CCSPluginList *       plugins
    unsigned int          refCount

cdef struct CCSString:
    char *                value
    unsigned int          refCount

'''Context functions'''
cdef extern void ccsSetBasicMetadata (Bool value)
cdef extern CCSContext * ccsContextNew (unsigned int screenNum)
cdef extern CCSContext * ccsEmptyContextNew (unsigned int screenNum)
cdef extern void ccsContextDestroy (CCSContext * context)

'''Plugin functions'''
cdef extern Bool ccsLoadPlugin (CCSContext * context, char * name)
cdef extern CCSPlugin * ccsFindPlugin (CCSContext * context, char * name)
cdef extern CCSSetting * ccsFindSetting (CCSPlugin * plugin,
                                         char *      name)
cdef extern CCSSettingList * ccsGetPluginSettings (CCSPlugin * plugin)
cdef extern CCSGroupList * ccsGetPluginGroups (CCSPlugin * plugin)

'''Action => String'''
cdef extern char * ccsModifiersToString (unsigned int modMask)
cdef extern char * ccsEdgesToString (unsigned int edge)
cdef extern char * ccsEdgesToModString (unsigned int edge)
cdef extern char * ccsKeyBindingToString (CCSSettingKeyValue *key)
cdef extern char * ccsButtonBindingToString (CCSSettingButtonValue *button)

'''String utils'''
cdef extern from 'string.h':
    ctypedef int size_t
    cdef extern char * strdup (char * s)
    cdef extern void memset (void * s, int c, size_t n)
    cdef extern void free (void * f)
    cdef extern void * malloc (size_t s)

'''String => Action'''
cdef extern unsigned int ccsStringToModifiers (char *binding)
cdef extern unsigned int ccsStringToEdges (char *edge)
cdef extern unsigned int ccsModStringToEdges (char *edge)
cdef extern Bool ccsStringToKeyBinding (char *               binding,
                                        CCSSettingKeyValue * key)
cdef extern Bool ccsStringToButtonBinding (char *                  binding,
                                           CCSSettingButtonValue * button)

'''General settings handling'''
cdef extern Bool ccsSetValue (CCSSetting * setting,
                  CCSSettingValue * value,
		  Bool		  processChanged)
cdef extern void ccsFreeSettingValue (CCSSettingValue * value)
cdef extern CCSSettingValueList * ccsSettingValueListAppend (
                                        CCSSettingValueList * l,
                                        CCSSettingValue *     v)
cdef extern CCSSettingList *ccsSettingListFree (CCSSettingList * list,
                                                Bool             freeObj)

'''Profiles'''
cdef extern CCSStringList * ccsGetExistingProfiles (CCSContext * context)
cdef extern void ccsDeleteProfile (CCSContext * context, char * name)
cdef extern void ccsSetProfile (CCSContext * context, char * name)
cdef extern char* ccsGetProfile (CCSContext * context)

'''Backends'''
cdef extern CCSBackendInfoList * ccsGetExistingBackends ()
cdef extern Bool ccsSetBackend (CCSContext * context, char * name)
cdef extern char* ccsGetBackend (CCSContext * context)

'''Sorting'''
cdef extern void ccsSetPluginListAutoSort (CCSContext *context, Bool value)
cdef extern Bool ccsGetPluginListAutoSort (CCSContext *context)

'''Integration'''
cdef extern void ccsSetIntegrationEnabled (CCSContext * context, Bool value)
cdef extern Bool ccsGetIntegrationEnabled (CCSContext * context)

'''IO handling'''
cdef extern void ccsReadSettings (CCSContext * c)
cdef extern void ccsWriteSettings (CCSContext * c)
cdef extern void ccsWriteChangedSettings (CCSContext * c)
cdef extern void ccsResetToDefault (CCSSetting * s, Bool processChanged)

'''Event loop'''
ProcessEventsNoGlibMainLoopMask = (1 << 0)
cdef extern void ccsProcessEvents (CCSContext * context, unsigned int flags)

'''Import/export'''
cdef extern Bool ccsExportToFile (CCSContext * context, char * fileName, Bool skipDefaults)
cdef extern Bool ccsImportFromFile (CCSContext * context,
                                    char *       fileName,
                                    Bool         overwrite)

'''Misc. Plugin/Setting utils'''
cdef extern Bool ccsSettingIsReadOnly (CCSSetting * setting)
cdef extern Bool ccsSettingIsIntegrated (CCSSetting * setting)

cdef extern void ccsPluginConflictListFree (CCSPluginConflictList * l,
                                            Bool                    freeObj)
cdef extern CCSPluginConflictList * ccsCanEnablePlugin (CCSContext * c,
                                                        CCSPlugin *  p)
cdef extern CCSPluginConflictList * ccsCanDisablePlugin (CCSContext * c,
                                                         CCSPlugin *  p)

cdef extern Bool ccsPluginSetActive (CCSPlugin * p, Bool v)
cdef extern Bool ccsPluginIsActive (CCSContext * c, char * n)

cdef extern CCSStrExtensionList * ccsGetPluginStrExtensions (CCSPlugin * plugin)

cdef class Context
cdef class Plugin
cdef class Setting

cdef CCSSettingType GetType (CCSSettingValue * value):
    if value.isListChild:
        return (<CCSSetting *> value.parent).info.forList.listType
    else:
        return (<CCSSetting *> value.parent).type

cdef CCSStringList * ListToStringList (object list):
    if len (list) <= 0:
        return NULL

    cdef CCSStringList * listStart
    cdef CCSStringList * stringList
    cdef CCSStringList * prev
    cdef CCSString     * stringStart = <CCSString *> malloc (sizeof (CCSString))
    
    stringStart.value = strdup (list[0])
    listStart = <CCSStringList *> malloc (sizeof (CCSStringList))
    listStart.data = <CCSString *> stringStart
    listStart.next = NULL
    prev = listStart
    
    for l in list[1:]:
        stringStart = <CCSString *> malloc (sizeof (CCSString))

        stringStart.value = <char *> strdup (l)

        stringList = <CCSStringList *> malloc (sizeof (CCSStringList))
        stringList.data = stringStart
        stringList.next = NULL
        prev.next = stringList
        prev = stringList
    
    return listStart
    
cdef object StringListToList (CCSList * stringList):
    cdef CCSString * string
    list = []
    while stringList:
        string = <CCSString *> stringList.data;

        item = <char *> string.value
        list.append (item)
        stringList = stringList.next
    return list

cdef CCSSettingList * ListToSettingList (object list):
    if len (list) <= 0:
        return NULL

    cdef CCSSettingList * listStart
    cdef CCSSettingList * settingList
    cdef CCSSettingList * prev
    cdef Setting setting

    listStart = <CCSSettingList *> malloc (sizeof (CCSSettingList))
    setting = <Setting> list[0]
    listStart.data = <CCSSetting *> setting.ccsSetting
    listStart.next = NULL
    prev = listStart
    
    for l in list[1:]:
        settingList = <CCSSettingList *> malloc (sizeof (CCSSettingList))
        setting = <Setting> l
        settingList.data = <CCSSetting *> setting.ccsSetting
        settingList.next = NULL
        prev.next = settingList
        prev = settingList
    
    return listStart

cdef object SettingListToList (Context context, CCSList * settingList):
    cdef CCSSetting * ccsSetting
    list = []
    
    while settingList:
        ccsSetting = <CCSSetting *> settingList.data
        setting = None
        plugin = context.Plugins[ccsSetting.parent.name]
        setting = plugin.Screen[ccsSetting.name]
        list.append (setting)
        settingList = settingList.next
    
    return list

cdef object IntDescListToDict (CCSIntDescList * intDescList):
    cdef CCSIntDesc * desc
    dict = {}
    while intDescList:
        desc = <CCSIntDesc *> intDescList.data
        dict[desc.name] = desc.value
        intDescList = intDescList.next
    return dict

cdef object StrRestrictionListToDict (CCSStrRestrictionList * restrictionList,
                                      object initialDict):
    cdef CCSStrRestriction * restriction
    dict = initialDict
    listOfAddedItems = []
    while restrictionList:
        restriction = <CCSStrRestriction *> restrictionList.data
        dict[restriction.name] = restriction.value
        listOfAddedItems.append ((restriction.name, restriction.value))
        restrictionList = restrictionList.next
    return (dict, listOfAddedItems)

cdef CCSSettingValue * EncodeValue (object       data,
                                    CCSSetting * setting,
                                    Bool         isListChild):
    cdef CCSSettingValue * bv
    cdef CCSSettingType t
    cdef CCSList * l
    bv = <CCSSettingValue *> malloc (sizeof (CCSSettingValue))
    memset (bv, 0, sizeof (CCSSettingValue))
    bv.isListChild = isListChild
    bv.parent = setting
    if isListChild:
        t = setting.info.forList.listType
    else:
        t = setting.type
    if t == TypeString:
        bv.value.asString = strdup (data)
    elif t == TypeMatch:
        bv.value.asMatch = strdup (data)
    elif t == TypeInt:
        bv.value.asInt = data
    elif t == TypeFloat:
        bv.value.asFloat = data
    elif t == TypeBool:
        if data:
            bv.value.asBool = 1
        else:
            bv.value.asBool = 0
    elif t == TypeColor:
        bv.value.asColor.color.red = data[0]
        bv.value.asColor.color.green = data[1]
        bv.value.asColor.color.blue = data[2]
        bv.value.asColor.color.alpha = data[3]
    elif t == TypeKey:
        ccsStringToKeyBinding (data, &bv.value.asKey)
    elif t == TypeButton:
        ccsStringToButtonBinding (data, &bv.value.asButton)
    elif t == TypeEdge:
        bv.value.asEdge = ccsStringToEdges (data)
    elif t == TypeBell:
        if (data):
            bv.value.asBell = 1
        else:
            bv.value.asBell = 0
    elif t == TypeList:
        l = NULL
        for item in data:
            l = ccsSettingValueListAppend (l, EncodeValue (item, setting, 1))
        bv.value.asList = l
    return bv

cdef object DecodeValue (CCSSettingValue * value):
    cdef CCSSettingType t
    cdef char * s
    cdef CCSList * l
    cdef object cs
    cdef object ks
    cdef object bs
    cdef object es
    cdef object eb
    t = GetType (value)
    if t == TypeString:
        return value.value.asString
    elif t == TypeMatch:
        return value.value.asMatch
    elif t == TypeBool:
        if value.value.asBool:
            return True
        return False
    elif t == TypeInt:
        return value.value.asInt
    elif t == TypeFloat:
        return value.value.asFloat
    elif t == TypeColor:
        return [value.value.asColor.color.red,
                value.value.asColor.color.green,
                value.value.asColor.color.blue,
                value.value.asColor.color.alpha]
    elif t == TypeKey:
        s = ccsKeyBindingToString (&value.value.asKey)
        if s != NULL:
            ks = s
            free (s)
        else:
            ks = "None"
        return ks
    elif t == TypeButton:
        s = ccsButtonBindingToString (&value.value.asButton)
        if s != NULL:
            bs = s
            free (s)
        else:
            bs = "None"
        if bs == "Button0":
            bs = "None"
        return bs
    elif t == TypeEdge:
        s = ccsEdgesToString (value.value.asEdge)
        if s != NULL:
            es = s
            free (s)
        else:
            es = "None"
        return es
    elif t == TypeBell:
        bb = False
        if value.value.asBell:
            bb = True
        return bb
    elif t == TypeList:
        lret = []
        l = value.value.asList
        while l != NULL:
            lret.append (DecodeValue (<CCSSettingValue *> l.data))
            l = l.next
        return lret
    return "Unhandled"

cdef class Setting:
    cdef CCSSetting * ccsSetting
    cdef object info
    cdef Plugin plugin
    cdef object extendedStrRestrictions
    cdef object baseStrRestrictions

    def __cinit__ (self, Plugin plugin, name):
        cdef CCSSettingType t
        cdef CCSSettingInfo * i

        self.ccsSetting = ccsFindSetting (plugin.ccsPlugin, name)
        self.plugin = plugin

        self.extendedStrRestrictions = None
        self.baseStrRestrictions = None
        info = ()
        t = self.ccsSetting.type
        i = &self.ccsSetting.info
        if t == TypeList:
            t = self.ccsSetting.info.forList.listType
            i = <CCSSettingInfo *> self.ccsSetting.info.forList.listInfo
        if t == TypeInt:
            desc = IntDescListToDict (i.forInt.desc)
            info = (i.forInt.min, i.forInt.max, desc)
        elif t == TypeFloat:
            info = (i.forFloat.min, i.forFloat.max,
                    i.forFloat.precision)
        elif t == TypeString:
            # info is filled later in Plugin.SortSingleStringSetting
            info = ({}, {}, [])
            self.baseStrRestrictions = []
            self.extendedStrRestrictions = {}
        elif t in (TypeKey, TypeButton, TypeEdge, TypeBell):
            info = (bool (i.forAction.internal),)
        if self.ccsSetting.type == TypeList:
            info = (SettingTypeString[t], info)
        self.info = info
    
    def Reset (self):
        ccsResetToDefault (self.ccsSetting, 1)

    property Plugin:
        def __get__ (self):
            return self.plugin

    property Name:
        def __get__ (self):
            return self.ccsSetting.name

    property ShortDesc:
        def __get__ (self):
            return self.ccsSetting.shortDesc

    property LongDesc:
        def __get__ (self):
            return self.ccsSetting.longDesc

    property Group:
        def __get__ (self):
            return self.ccsSetting.group

    property SubGroup:
        def __get__ (self):
            return self.ccsSetting.subGroup

    property Type:
        def __get__ (self):
            return SettingTypeString[self.ccsSetting.type]

    property Info:
        def __get__ (self):
            return self.info

    property Hints:
        def __get__ (self):
            if not self.ccsSetting.hints:
                return []
            else:
                return str (self.ccsSetting.hints).split (";")[:-1]

    property IsDefault:
        def __get__ (self):
            if self.ccsSetting.isDefault:
                return True
            return False

    property DefaultValue:
        def __get__ (self):
            return DecodeValue (&self.ccsSetting.defaultValue)

    property Value:
        def __get__ (self):
            return DecodeValue (self.ccsSetting.value)
        def __set__ (self, value):
            cdef CCSSettingValue * sv
            sv = EncodeValue (value, self.ccsSetting, 0)
            ccsSetValue (self.ccsSetting, sv, 1)
            ccsFreeSettingValue (sv)

    property Integrated:
        def __get__ (self):
            return bool (ccsSettingIsIntegrated (self.ccsSetting))

    property ReadOnly:
        def __get__ (self):
            return bool (ccsSettingIsReadOnly (self.ccsSetting))

cdef class SSGroup:
    cdef object screen

    def __cinit__ (self, screen):
        self.screen = screen

    property Screen:
        def __get__ (self):
            return self.screen
        def __set__ (self, value):
            self.screen = value

cdef class Plugin:
    cdef CCSPlugin * ccsPlugin
    cdef Context context
    cdef object screen
    cdef object groups
    cdef object loaded
    cdef object ranking
    cdef object hasExtendedString
    
    def __cinit__ (self, Context context, name):
        self.ccsPlugin = ccsFindPlugin (context.ccsContext, name)
        self.context = context
        self.screen = {}
        self.groups = {}
        self.loaded = False
        self.ranking = {}
        self.hasExtendedString = False

    def Update (self):
        cdef CCSList * setlist
        cdef CCSList * glist
        cdef CCSList * sglist
        cdef CCSSetting * sett
        cdef CCSGroup * gr
        cdef CCSSubGroup * sgr
        cdef CCSSettingType t
        cdef CCSSettingInfo * i

        groupIndex = 0
        glist = ccsGetPluginGroups (self.ccsPlugin)
        while glist != NULL:
            gr = <CCSGroup *> glist.data
            self.groups[gr.name] = (groupIndex, {})
            subGroupIndex = 0
            sglist = gr.subGroups
            while sglist != NULL:
                sgr = <CCSSubGroup *> sglist.data
                self.groups[gr.name][1][sgr.name] = (subGroupIndex,
                                                     SSGroup ({}))
                subGroupIndex = subGroupIndex + 1
                sglist = sglist.next
            groupIndex = groupIndex + 1
            glist = glist.next
        setlist = ccsGetPluginSettings (self.ccsPlugin)

        self.hasExtendedString = False
        rank = 0
        while setlist != NULL:
            sett = <CCSSetting *> setlist.data

            subgroup = self.groups[sett.group][1][sett.subGroup][1]

            setting = Setting (self, sett.name)
            self.screen[sett.name] = setting
            subgroup.Screen[sett.name] = setting

            t = sett.type
            i = &sett.info
            if t == TypeList:
                t = i.forList.listType
                i = <CCSSettingInfo *> i.forList.listInfo
            if t == TypeString and i.forString.extensible:
                self.hasExtendedString = True

            if not self.ranking.has_key (sett.name):
                self.ranking[sett.name] = rank
                rank = rank + 1
            
            setlist = setlist.next

        self.loaded = True

        self.ApplyStringExtensions (True, self.Enabled)
        self.SortStringSettings ()

    def SortStringSettings (self):
        for name, setting in self.Screen.items ():
            self.SortSingleStringSetting (setting)

    def SortSingleStringSetting (self, Setting setting):
        cdef CCSSettingType t
        cdef CCSSettingInfo * i

        t = setting.ccsSetting.type
        i = &setting.ccsSetting.info
        if t == TypeList:
            t = i.forList.listType
            i = <CCSSettingInfo *> i.forList.listInfo
        if t != TypeString:
            return

        (itemsByName, listOfAddedItems) = \
            StrRestrictionListToDict (i.forString.restriction,
                                      setting.extendedStrRestrictions)

        # Let base string restrictions be the ones given in the option metadata
        # in the base plugin plus the ones found in the extensions in the same
        # plugin.
        setting.baseStrRestrictions = \
            listOfAddedItems + setting.baseStrRestrictions

        if i.forString.sortStartsAt < 0:
            # don't sort
            sortedItems = itemsByName.items ()
        elif i.forString.sortStartsAt == 0:
            # Sort all items by value
            sortedItems = sorted (itemsByName.items (),
                                  key=StringSettingKeyFunc)
        else:
            # Sort first sortStartsAt many items by value and
            # the remaining ones by name
            itemsNotSorted = \
                setting.baseStrRestrictions[:i.forString.sortStartsAt]
            itemsNotSortedSet = set (itemsNotSorted)
            allItemsSet = set (itemsByName.items ())
            itemsSortedByName = sorted (list (allItemsSet - itemsNotSortedSet),
                                        key=operator.itemgetter (0))
            sortedItems = itemsNotSorted + itemsSortedByName

        itemsByValue = {}
        for (index, (name, value)) in enumerate (sortedItems):
            itemsByValue[value] = (name, index)

        # Insert itemsByName and sortedItems into setting.info
        if setting.ccsSetting.type == TypeList:
            setting.info = (setting.info[0], (itemsByName,
                                              itemsByValue,
                                              sortedItems))
        else:
            setting.info = (itemsByName, itemsByValue, sortedItems)

    def ApplyStringExtensions (self, sortBaseSetting, extendOthersToo):
        cdef CCSStrExtensionList * extList
        cdef CCSStrExtension * ext
        cdef char * baseSettingName
        cdef CCSStringList * baseSettingList
        cdef CCSSettingType t
        cdef CCSSettingInfo * i
        cdef CCSStrRestrictionList * restrictionList
        cdef CCSStrRestriction * restriction
        cdef Plugin basePlugin
        cdef Setting setting

        extList = ccsGetPluginStrExtensions (self.ccsPlugin)
        while extList:
            ext = <CCSStrExtension *> extList.data

            # If not extending others and extension base is not self, skip
            if (not (extendOthersToo or ext.basePlugin == self.Name)) or \
            ext.basePlugin not in self.context.Plugins:
                extList = extList.next
                continue

            basePlugin = self.context.Plugins[ext.basePlugin]

            baseSettingList = ext.baseSettings
            while baseSettingList:
                baseSettingName = <char *> baseSettingList.data

                settings = [basePlugin.Screen[baseSettingName]]

                for settingItem in settings:
                    setting = settingItem
                    t = setting.ccsSetting.type
                    i = &setting.ccsSetting.info
                    if t == TypeList:
                        t = i.forList.listType
                        i = <CCSSettingInfo *> i.forList.listInfo
                    if not (t == TypeString and i.forString.extensible):
                        return

                    restrictionList = ext.restriction

                    # Add each item in restriction list to the setting
                    while restrictionList != NULL:
                        restriction = <CCSStrRestriction *> restrictionList.data
                        setting.extendedStrRestrictions[restriction.name] = \
                            restriction.value
                        if ext.basePlugin == self.Name:
                            setting.baseStrRestrictions.append ((restriction.name,
                                                                 restriction.value))
                        restrictionList = restrictionList.next

                    if sortBaseSetting:
                        basePlugin.SortSingleStringSetting (setting)

                baseSettingList = baseSettingList.next

            extList = extList.next

    def GetExtensionBasePlugins (self):
        cdef CCSStrExtensionList * extList
        cdef CCSStrExtension * ext

        basePlugins = set ([])
        extList = ccsGetPluginStrExtensions (self.ccsPlugin)
        while extList:
            ext = <CCSStrExtension *> extList.data
            basePlugins.add (self.context.Plugins[ext.basePlugin])
            extList = extList.next

        return list (basePlugins)

    property Context:
        def __get__ (self):
            return self.context

    property Groups:
        def __get__ (self):
            if not self.loaded:
                self.Update ()
            return self.groups

    property Screen:
        def __get__ (self):
            if not self.loaded:
                self.Update ()
            return self.screen

    property Ranking:
        def __get__ (self):
            if not self.loaded:
                self.Update ()
            return self.ranking

    property Name:
        def __get__ (self):
            return self.ccsPlugin.name

    property ShortDesc:
        def __get__ (self):
            return self.ccsPlugin.shortDesc

    property LongDesc:
        def __get__ (self):
            return self.ccsPlugin.longDesc

    property Category:
        def __get__ (self):
            return self.ccsPlugin.category

    property Features:
        def __get__ (self):
            features = StringListToList (self.ccsPlugin.providesFeature)
            return features

    property Initialized:
        def __get__ (self):
            return bool (self.loaded)

    property Enabled:
        def __get__ (self):
            return bool (ccsPluginIsActive (self.context.ccsContext,
                                            self.ccsPlugin.name))
        def __set__ (self, val):
            if val:
                if len (self.EnableConflicts):
                    return
                ccsPluginSetActive (self.ccsPlugin, True)
            else:
                if len (self.DisableConflicts):
                    return
                ccsPluginSetActive (self.ccsPlugin, False)

    property EnableConflicts:
        def __get__ (self):
            cdef CCSPluginConflictList * pl, * pls
            cdef CCSPluginConflict * pc
            cdef CCSPluginList * ppl
            cdef CCSPlugin * plg

            if self.Enabled:
                return []

            ret = []
            pl = ccsCanEnablePlugin (self.context.ccsContext,
                                     self.ccsPlugin)
            pls = pl
            while pls != NULL:
                pc = <CCSPluginConflict *> pls.data
                rpl = []
                ppl = pc.plugins
                while ppl != NULL:
                    plg = <CCSPlugin *> ppl.data
                    rpl.append (self.context.Plugins[plg.name])
                    ppl = ppl.next
                ret.append ((ConflictTypeString[pc.type], pc.value, rpl))
                pls = pls.next
            if pl != NULL:
                ccsPluginConflictListFree (pl, True)
            return ret

    property DisableConflicts:
        def __get__ (self):
            cdef CCSPluginConflictList * pl, * pls
            cdef CCSPluginConflict * pc
            cdef CCSPluginList * ppl
            cdef CCSPlugin * plg

            if not self.Enabled:
                return []

            ret = []
            pl = ccsCanDisablePlugin (self.context.ccsContext,
                                      self.ccsPlugin)
            pls = pl
            while pls != NULL:
                pc = <CCSPluginConflict *> pls.data
                rpl = []
                ppl = pc.plugins
                while ppl != NULL:
                    plg = <CCSPlugin *> ppl.data
                    rpl.append (self.context.Plugins[plg.name])
                    ppl = ppl.next
                ret.append ((ConflictTypeString[pc.type], pc.value, rpl))
                pls = pls.next
            if pl != NULL:
                ccsPluginConflictListFree (pl, True)
            return ret

cdef class Profile:
    cdef Context context
    cdef char * name

    def __cinit__ (self, Context context, name):
        self.context = context
        self.name = strdup (name)

    def __dealloc (self):
        free (self.name)

    def Delete (self):
        ccsDeleteProfile (self.context.ccsContext, self.name)

    property Name:
        def __get__ (self):
            return self.name

cdef class Backend:
    cdef Context context
    cdef char * name
    cdef char * shortDesc
    cdef char * longDesc
    cdef Bool profileSupport
    cdef Bool integrationSupport

    def __cinit__ (self, Context context, info):
        self.context = context
        self.name = strdup (info[0])
        self.shortDesc = strdup (info[1])
        self.longDesc = strdup (info[2])
        self.profileSupport = bool (info[3])
        self.integrationSupport = bool (info[4])
    
    def __dealloc__ (self):
        free (self.name)
        free (self.shortDesc)
        free (self.longDesc)

    property Name:
        def __get__ (self):
            return self.name
 
    property ShortDesc:
        def __get__ (self):
            return self.shortDesc

    property LongDesc:
        def __get__ (self):
            return self.longDesc

    property IntegrationSupport:
        def __get__ (self):
            return self.integrationSupport

    property ProfileSupport:
        def __get__ (self):
            return self.profileSupport

cdef class Context:
    cdef CCSContext * ccsContext
    cdef object plugins
    cdef object categories
    cdef object profiles
    cdef object currentProfile
    cdef object backends
    cdef object currentBackend
    cdef Bool integration

    def __cinit__ (self, screenNum = 0, plugins = [], basic_metadata = False):
        cdef CCSPlugin * pl
        cdef CCSList * pll
        if basic_metadata:
            ccsSetBasicMetadata (True)
        self.plugins = {}
        if not len (plugins):
            self.ccsContext = ccsContextNew (screenNum)
        else:
            self.ccsContext = ccsEmptyContextNew (screenNum)

        for plugin in plugins:
            self.LoadPlugin (plugin)

        ccsReadSettings (self.ccsContext)
        pll = self.ccsContext.plugins
        self.categories = {}
        while pll != NULL:
            pl = <CCSPlugin *> pll.data
            self.plugins[pl.name] = Plugin (self, pl.name)
            if pl.category == NULL:
                cat = ''
            else:
                cat = pl.category
            if not self.categories.has_key (cat):
                self.categories[cat] = []
            self.categories[cat].append (self.plugins[pl.name])
            pll = pll.next

        self.integration = ccsGetIntegrationEnabled (self.ccsContext)
        
        self.UpdateProfiles ()

    def UpdateExtensiblePlugins (self):
        cdef Plugin plugin

        # Reset all extensible plugins
        for name, pluginItem in self.plugins.items ():
            plugin = pluginItem
            if plugin.hasExtendedString:
                plugin.Update ()

        # Apply restricted string extensions
        for name, pluginItem in self.plugins.items ():
            plugin = pluginItem
            if plugin.Enabled:
                plugin.ApplyStringExtensions (False, True)

        # Sort restricted string settings
        for name, pluginItem in self.plugins.items ():
            plugin = pluginItem
            if plugin.Enabled and plugin.hasExtendedString:
                plugin.SortStringSettings ()

    def __dealloc__ (self):
        ccsContextDestroy (self.ccsContext)

    def LoadPlugin (self, plugin):
        return ccsLoadPlugin (self.ccsContext, plugin)

    # Returns the settings that should be updated
    def ProcessEvents (self, flags = 0):
        ccsProcessEvents (self.ccsContext, flags)
        if len (self.ChangedSettings):
            self.Read ()
            return True
        return False

    def Write (self, onlyChanged = True):
        if onlyChanged:
            ccsWriteChangedSettings (self.ccsContext)
        else:
            ccsWriteSettings (self.ccsContext)

    def Read (self):
        ccsReadSettings (self.ccsContext)

    def UpdateProfiles (self):
        self.profiles = {}
        self.currentProfile = Profile (self, ccsGetProfile (self.ccsContext))
        cdef CCSStringList * profileList
        cdef char * profileName
        profileList = ccsGetExistingProfiles (self.ccsContext)
        while profileList != NULL:
            profileName = <char *> profileList.data
            self.profiles[profileName] = Profile (self, profileName)
            profileList = profileList.next

        self.backends = {}
        cdef CCSBackendInfoList * backendList
        cdef CCSBackendInfo * backendInfo
        backendList = ccsGetExistingBackends ()
        while backendList != NULL:
            backendInfo = <CCSBackendInfo *> backendList.data
            info = (backendInfo.name, backendInfo.shortDesc,
                    backendInfo.longDesc, backendInfo.profileSupport,
                    backendInfo.integrationSupport)
            self.backends[backendInfo.name] = Backend (self, info)
            backendList = backendList.next
        self.currentBackend = self.backends[ccsGetBackend (self.ccsContext)]
    
    def ResetProfile (self):
        self.currentProfile = Profile (self, "")
        ccsSetProfile (self.ccsContext, "")
        ccsReadSettings (self.ccsContext)

    def Import (self, path, autoSave = True):
        ret = bool (ccsImportFromFile (self.ccsContext, path, True))
        if autoSave:
            ccsWriteSettings (self.ccsContext)
        return ret

    def Export (self, path, skipDefaults = False):
        return bool (ccsExportToFile (self.ccsContext, path, skipDefaults))

    property Plugins:
        def __get__ (self):
            return self.plugins

    property Categories:
        def __get__ (self):
            return self.categories

    property CurrentProfile:
        def __get__ (self):
            return self.currentProfile
        def __set__ (self, profile):
            self.currentProfile = profile
            ccsSetProfile (self.ccsContext, profile.Name)
            ccsReadSettings (self.ccsContext)

    property Profiles:
        def __get__ (self):
            return self.profiles

    property CurrentBackend:
        def __get__ (self):
            return self.currentBackend
        def __set__ (self, backend):
            self.currentBackend = backend
            ccsSetBackend (self.ccsContext, backend.Name)
            ccsReadSettings (self.ccsContext)

    property Backends:
        def __get__ (self):
            return self.backends

    property ChangedSettings:
        def __get__ (self):
            return SettingListToList (self, self.ccsContext.changedSettings)
        def __set__ (self, value):
            cdef CCSSettingList * settingList
            if self.ccsContext.changedSettings != NULL:
                self.ccsContext.changedSettings = \
                    ccsSettingListFree (self.ccsContext.changedSettings, False)
            if value != None and len (value) != 0:
                settingList = ListToSettingList (value)
                self.ccsContext.changedSettings = settingList
                
    property AutoSort:
        def __get__ (self):
            return bool (ccsGetPluginListAutoSort (self.ccsContext))
        def __set__ (self, value):
            ccsSetPluginListAutoSort (self.ccsContext, bool (value))

    property Integration:
        def __get__ (self):
            return bool (self.integration)
        def __set__ (self, value):
            self.integration = value
            ccsSetIntegrationEnabled (self.ccsContext, value)
            ccsReadSettings (self.ccsContext)