~shim/libdesktop-agnostic/vala-0.18

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
/*
 * A GKeyFile-based implementation of the Config interface.
 *
 * Copyright (C) 2009 Mark Lee <libdesktop-agnostic@lazymalevolence.com>
 *
 * This library 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.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 * Author : Mark Lee <libdesktop-agnostic@lazymalevolence.com>
 */

using DesktopAgnostic;

namespace DesktopAgnostic.Config
{
  public class GKeyFile : Backend
  {
    private KeyFile _data;
    private VFS.File _keyfile;
    private VFS.FileMonitor _keyfile_monitor;
    private ulong _monitor_changed_id;
    private string _checksum;
    private bool _autosave;
    private Datalist<unowned SList<NotifyDelegate>> _notifiers;
    public override string name
    {
      owned get
      {
        return "GKeyFile";
      }
    }

    construct
    {
      this._autosave = true;
      this._monitor_changed_id = 0;
      if (this.schema != null)
      {
        this._data = new KeyFile ();
        this._notifiers = Datalist<SList<NotifyDelegate>> ();
      }
    }

    /**
     * Saves the current state of the configuration to the filesystem,
     * suppressing the "changed" signal from the file monitor.
     */
    private void
    save_config () throws GLib.Error
    {
      string data;
      size_t length;

      data = this._data.to_data (out length);
      this._checksum = Checksum.compute_for_string (ChecksumType.SHA256,
                                                    data, length);
      if (this._monitor_changed_id != 0)
      {
        // block changed signal
        SignalHandler.block (this._keyfile_monitor, this._monitor_changed_id);
      }
      // save config file
      this._keyfile.replace_contents (data);
      if (this._monitor_changed_id != 0)
      {
        // unblock changed signal
        SignalHandler.unblock (this._keyfile_monitor, this._monitor_changed_id);
      }
    }

    /**
     * Saves the current configuration state to the filesystem (if autosave is
     * on) and emits the notify signal.
     */
    private void
    update_config (string group, string key) throws GLib.Error
    {
      if (this._autosave)
      {
        this.save_config ();
      }
      this.notify (group, key);
    }

    private void
    get_data_from_file (VFS.File file, out string contents, out size_t length,
                        out string checksum) throws GLib.Error
    {
      file.load_contents (out contents, out length);
      checksum = Checksum.compute_for_string (ChecksumType.SHA256,
                                              contents, length);
    }

    private void
    load_data (VFS.File file) throws GLib.Error
    {
      string data;
      size_t length;

      this.get_data_from_file (file, out data, out length, out this._checksum);
      this._data.load_from_data (data, (ulong)length, KeyFileFlags.NONE);
    }

    private void
    set_value_from_keyfile (KeyFile keyfile, string group, string key) throws GLib.Error
    {
      SchemaOption option = this.schema.get_option (group, key);
      Type type = option.option_type;
      if (type == typeof (bool))
      {
        this.set_bool (group, key, keyfile.get_boolean (group, key));
      }
      else if (type == typeof (int))
      {
        this.set_int (group, key, keyfile.get_integer (group, key));
      }
      else if (type == typeof (float))
      {
        this.set_float (group, key, (float)keyfile.get_double (group, key));
      }
      else if (type == typeof (string))
      {
        this.set_string (group, key, keyfile.get_string (group, key));
      }
      else if (type == typeof (ValueArray))
      {
        ValueArray arr;

        arr = this.generate_valuearray_from_keyfile (keyfile, group, key);

        this.set_list (group, key, arr);
      }
      else
      {
        SchemaType? st = Schema.find_type (type);
        if (st == null)
        {
          throw new Error.INVALID_TYPE ("'%s' is an invalid config type.",
                                        type.name ());
        }

        Value val;

        val = st.deserialize (keyfile.get_string (group, key));
        this.set_value (group, key, val);
      }
    }

    private ValueArray
    generate_valuearray_from_keyfile (KeyFile keyfile, string group,
                                      string key) throws KeyFileError, GLib.Error
    {
      SchemaOption? option;
      Type list_type;
      ValueArray arr;

      option = this.schema.get_option (group, key);
      if (option == null)
      {
        throw new Error.KEY_NOT_FOUND ("The key %s/%s is invalid.",
                                       group, key);
      }
      else if (!keyfile.has_key (group, key))
      {
        return new ValueArray (0);
      }
      list_type = option.list_type;
      if (list_type == typeof (bool))
      {
        bool[] list_data;
        Value val;

        list_data = keyfile.get_boolean_list (group, key);
        arr = new ValueArray (list_data.length);
        foreach (bool item in list_data)
        {
          val = item;
          arr.append (val);
        }
      }
      else if (list_type == typeof (int))
      {
        int[] list_data;
        Value val;

        list_data = keyfile.get_integer_list (group, key);
        arr = new ValueArray (list_data.length);
        foreach (int item in list_data)
        {
          val = item;
          arr.append (val);
        }
      }
      else if (list_type == typeof (float))
      {
        double[] list_data;
        Value val;

        list_data = (double[])keyfile.get_double_list (group, key);
        arr = new ValueArray (list_data.length);
        foreach (double item in list_data)
        {
          val = (float)item;
          arr.append (val);
        }
      }
      else if (list_type == typeof (string))
      {
        string[] list_data;
        Value val;

        list_data = keyfile.get_string_list (group, key);
        arr = new ValueArray (list_data.length);
        foreach (string item in list_data)
        {
          val = item;
          arr.append (val);
        }
      }
      else
      {
        SchemaType? st = Schema.find_type (list_type);
        if (st == null)
        {
          throw new Error.INVALID_TYPE ("'%s' is an invalid config type.",
                                        list_type.name ());
        }

        string[] list_data;

        list_data = keyfile.get_string_list (group, key);
        arr = new ValueArray (list_data.length);
        foreach (string item in list_data)
        {
          arr.append (st.deserialize (item));
        }
      }

      return arr;
    }

    private void
    on_keyfile_changed (VFS.File file, VFS.File? other,
                        VFS.FileMonitorEvent event, VFS.FileMonitor monitor)
    {
      switch (event)
      {
        case VFS.FileMonitorEvent.CREATED:
          // just set the data
          this.load_data (file);
          break;
        case VFS.FileMonitorEvent.CHANGED:
          // check to see if the contents have changed
          string data;
          size_t length;
          string checksum;

          this.get_data_from_file (file, out data, out length, out checksum);
          if (this._checksum != checksum)
          {
            // iterate through the config keys and determine which ones have changed
            unowned Schema schema = this.schema;
            KeyFile new_data = new KeyFile ();

            new_data.load_from_data (data, length, KeyFileFlags.NONE);

            this._autosave = false;
            foreach (unowned string group in schema.get_groups ())
            {
              foreach (unowned string key in schema.get_keys (group))
              {
                if (this._data.has_group (group))
                {
                  if ((this._data.has_key (group, key) &&
                       this._data.get_value (group, key) != new_data.get_value (group, key)) ||
                      schema.get_option (group, key).option_type == typeof (ValueArray))
                  {
                    this.set_value_from_keyfile (new_data, group, key);
                  }
                }
              }
            }
            this._autosave = true;
          }
          break;
        case VFS.FileMonitorEvent.DELETED:
          // reset & save to disk
          this.reset ();
          break;
        default:
          // do nothing
          break;
      }
    }

    private void
    ensure_directory (string path)
    {
      if (!FileUtils.test (path, FileTest.EXISTS))
      {
        int d_errno = DirUtils.create_with_parents (path, 0755);
        if (d_errno != 0)
        {
          critical ("Config file error: %s", strerror (d_errno));
        }
      }
    }

    private bool
    create_file_monitor ()
    {
      this._keyfile_monitor = this._keyfile.monitor ();
      this._monitor_changed_id = Signal.connect_swapped (this._keyfile_monitor,
                                                         "changed",
                                                         (Callback)this.on_keyfile_changed,
                                                         this);
      return false;
    }

    /**
     * Determines the path to the config file and creates/loads it.
     */
    public override void
    constructed ()
    {
      string base_path;
      string path;
      Schema schema = this.schema;

      base_path = Path.build_filename (Environment.get_user_config_dir (),
                                       "desktop-agnostic");
      if (this.instance_id == null)
      {
        path = Path.build_filename (base_path,
                                    "%s.ini".printf (schema.app_name));
      }
      else
      {
        path = Path.build_filename (base_path, "instances",
                                    "%s-%s.ini".printf (schema.app_name,
                                                        this.instance_id));
      }
      this._keyfile = VFS.file_new_for_path (path);
      try
      {
        if (this._keyfile.exists ())
        {
          this.load_data (this._keyfile);
        }
        else
        {
          this.ensure_directory (Path.get_dirname (path));
          this.reset ();
        }
      }
      catch (GLib.Error err)
      {
        critical ("Config error: %s", err.message);
      }
      // don't immediately create the file monitor, otherwise it will catch
      // the "config file created" signal.
      Idle.add (this.create_file_monitor);
    }

    ~GKeyFile ()
    {
      this._keyfile_monitor.cancel ();
      SignalHandler.disconnect (this._keyfile_monitor,
                                this._monitor_changed_id);
    }

    public override void
    reset () throws GLib.Error
    {
      unowned Schema? schema = this.schema;
      if (schema == null)
      {
        throw new Error.NO_SCHEMA ("The schema was not loaded.");
      }

      this._autosave = false;
      foreach (unowned string group in schema.get_groups ())
      {
        foreach (unowned string key in schema.get_keys (group))
        {
          SchemaOption option = schema.get_option (group, key);
          if (this.instance_id == null || option.per_instance)
          {
            this.set_value (group, key, option.default_value);
          }
        }
      }
      this._autosave = true;
      this.save_config ();
    }

    public override void
    notify_add (string group, string key, NotifyFunc callback) throws GLib.Error
    {
      string full_key = "%s/%s".printf (group, key);
      unowned SList<NotifyDelegate>? funcs = this._notifiers.get_data (full_key);
      NotifyDelegate data = new NotifyDelegate (callback);
      funcs.append ((owned)data);
      this._notifiers.set_data (full_key, funcs);
    }

    public override void
    notify (string group, string key) throws GLib.Error
    {
      string full_key = "%s/%s".printf (group, key);
      Value value = this.get_value (group, key);
      unowned SList<NotifyDelegate> funcs = this._notifiers.get_data (full_key);
      foreach (unowned NotifyDelegate data in funcs)
      {
        if (data != null && data.callback != null)
        {
          data.execute (group, key, value);
        }
      }
    }

    public override void
    notify_remove (string group, string key, NotifyFunc callback) throws GLib.Error
    {
      string full_key = "%s/%s".printf (group, key);
      unowned SList<NotifyDelegate> funcs = this._notifiers.get_data (full_key);
      NotifyDelegate ndata = new NotifyDelegate (callback);
      unowned SList<NotifyDelegate>? node;

      node = funcs.find_custom (ndata, (CompareFunc)NotifyDelegate.compare);
      if (node != null)
      {
        node.data = null;
        funcs.delete_link (node);
        this._notifiers.set_data (full_key, funcs);
      }
    }

    /**
     * Removes the config file from the file system. Implies reset(), but does
     * not save to disk.
     */
    public override void
    remove () throws GLib.Error
    {
      this._keyfile.remove ();
      this.reset ();
    }

    public override Value
    get_value (string group, string key) throws GLib.Error
    {
      Schema schema = this.schema;
      SchemaOption option = schema.get_option (group, key);
      Type option_type;
      Value result;

      if (option == null)
      {
        throw new Error.KEY_NOT_FOUND ("Could not find group and/or key in schema.");
      }

      option_type = option.option_type;

      if (option_type == typeof (bool))
      {
        result = this.get_bool (group, key);
      }
      else if (option_type == typeof (float))
      {
        result = this.get_float (group, key);
      }
      else if (option_type == typeof (int))
      {
        result = this.get_int (group, key);
      }
      else if (option_type == typeof (string))
      {
        result = this.get_string (group, key);
      }
      else if (option_type == typeof (ValueArray))
      {
        result = this.get_list (group, key);
      }
      else
      {
        SchemaType st = this.schema.find_type (option_type);
        if (st == null)
        {
          throw new Error.INVALID_TYPE ("'%s' is an invalid config type.",
                                        option_type.name ());
        }
        else
        {
          result = st.deserialize (this.get_string (group, key));
        }
      }
      return result;
    }

    public override bool
    get_bool (string group, string key) throws GLib.Error
    {
      try
      {
        return this._data.get_boolean (group, key);
      }
      catch (KeyFileError err)
      {
        if (err is KeyFileError.GROUP_NOT_FOUND ||
            err is KeyFileError.KEY_NOT_FOUND)
        {
          throw new Error.KEY_NOT_FOUND (err.message);
        }
        else
        {
          throw err;
        }
      }
    }

    public override void
    set_bool (string group, string key, bool value) throws GLib.Error
    {
      if (!this._data.has_group (group) || !this._data.has_key (group, key) ||
          this.get_bool (group, key) != value)
      {
        this._data.set_boolean (group, key, value);
        this.update_config (group, key);
      }
    }

    public override float
    get_float (string group, string key) throws Error
    {
      try
      {
        return (float)this._data.get_double (group, key);
      }
      catch (KeyFileError err)
      {
        if (err is KeyFileError.GROUP_NOT_FOUND ||
            err is KeyFileError.KEY_NOT_FOUND)
        {
          throw new Error.KEY_NOT_FOUND (err.message);
        }
        else
        {
          throw err;
        }
      }
    }

    public override void
    set_float (string group, string key, float value) throws GLib.Error
    {
      if (!this._data.has_group (group) || !this._data.has_key (group, key) ||
          this.get_float (group, key) != value)
      {
        this._data.set_double (group, key, value);
        this.update_config (group, key);
      }
    }

    public override int
    get_int (string group, string key) throws GLib.Error
    {
      try
      {
        return this._data.get_integer (group, key);
      }
      catch (KeyFileError err)
      {
        if (err is KeyFileError.GROUP_NOT_FOUND ||
            err is KeyFileError.KEY_NOT_FOUND)
        {
          throw new Error.KEY_NOT_FOUND (err.message);
        }
        else
        {
          throw err;
        }
      }
    }

    public override void
    set_int (string group, string key, int value) throws GLib.Error
    {
      if (!this._data.has_group (group) || !this._data.has_key (group, key) ||
          this.get_int (group, key) != value)
      {
        this._data.set_integer (group, key, value);
        this.update_config (group, key);
      }
    }

    public override string
    get_string (string group, string key) throws GLib.Error
    {
      try
      {
        return this._data.get_string (group, key);
      }
      catch (KeyFileError err)
      {
        if (err is KeyFileError.GROUP_NOT_FOUND ||
            err is KeyFileError.KEY_NOT_FOUND)
        {
          throw new Error.KEY_NOT_FOUND (err.message);
        }
        else
        {
          throw err;
        }
      }
    }

    public override void
    set_string (string group, string key, string value) throws GLib.Error
    {
      if (!this._data.has_group (group) || !this._data.has_key (group, key) ||
          this.get_string (group, key) != value)
      {
        this._data.set_string (group, key, value);
        this.update_config (group, key);
      }
    }

    public override ValueArray
    get_list (string group, string key) throws GLib.Error
    {
      try
      {
        return this.generate_valuearray_from_keyfile (this._data, group, key);
      }
      catch (KeyFileError err)
      {
        if (err is KeyFileError.GROUP_NOT_FOUND ||
            err is KeyFileError.KEY_NOT_FOUND)
        {
          throw new Error.KEY_NOT_FOUND (err.message);
        }
        else
        {
          throw err;
        }
      }
    }

    public override void
    set_list (string group, string key, ValueArray value) throws GLib.Error
    {
      SchemaOption option = this.schema.get_option (group, key);
      Type list_type = option.list_type;

      if (this._data.has_group (group) && this._data.has_key (group, key))
      {
        ValueArray old_value;

        old_value = this.get_list (group, key);
        if (old_value.n_values == value.n_values)
        {
          bool is_equal = true;
          for (uint i = 0; i < value.n_values; i++)
          {
            // FIXME ridiculously unreliable Value.equals algorithm
            unowned Value old_val;
            unowned Value new_val;

            old_val = old_value.get_nth (i);
            new_val = value.get_nth (i);

            if (old_val.type () != new_val.type () ||
                old_val.strdup_contents () != new_val.strdup_contents ())
            {
              is_equal = false;
              break;
            }
          }
          if (is_equal)
          {
            return;
          }
        }
      }

      if (value.n_values == 0)
      {
        if (this._data.has_key (group, key))
        {
          // set_*_list() doesn't like NULL lists, so just unset the key.
          this._data.remove_key (group, key);
        }
      }
      else if (list_type == typeof (bool))
      {
        bool[] list = {};
        foreach (unowned Value val in value)
        {
          list += (bool)val;
        }

        this._data.set_boolean_list (group, key, list);
      }
      else if (list_type == typeof (int))
      {
        int[] list = {};
        foreach (unowned Value val in value)
        {
          list += get_int_from_value (val);
        }

        this._data.set_integer_list (group, key, list);
      }
      else if (list_type == typeof (float))
      {
        double[] list = {};
        foreach (unowned Value val in value)
        {
          list += get_float_from_value (val);
        }

        this._data.set_double_list (group, key, list);
      }
      else if (list_type == typeof (string))
      {
        string[] list = {};
        foreach (unowned Value val in value)
        {
          list += (string)val;
        }

        this._data.set_string_list (group, key, list);
      }
      else
      {
        SchemaType? st = Schema.find_type (list_type);
        if (st == null)
        {
          throw new Error.INVALID_TYPE ("'%s' is an invalid config type.",
                                        list_type.name ());
        }

        string[] list = {};
        foreach (unowned Value val in value)
        {
          list += st.serialize (val);
        }

        this._data.set_string_list (group, key, list);
      }
      this.update_config (group, key);
    }
  }
}
[ModuleInit]
public Type
register_plugin ()
{
  return typeof (DesktopAgnostic.Config.GKeyFile);
}

// vim: set et ts=2 sts=2 sw=2 ai :