about summary refs log tree commit diff
path: root/lib/gvariant.nix
blob: d542df4d7b9a0adfba06f7596cc2413e0428008d (plain) (blame)
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
/**
  A partial and basic implementation of GVariant formatted strings.
  See [GVariant Format Strings](https://docs.gtk.org/glib/gvariant-format-strings.html) for details.

  :::{.warning}
  This API is not considered fully stable and it might therefore
  change in backwards incompatible ways without prior notice.
  :::
*/

# This file is based on https://github.com/nix-community/home-manager
# Copyright (c) 2017-2022 Home Manager contributors
{ lib }:

let
  inherit (lib)
    concatMapStringsSep concatStrings escape head replaceStrings;

  mkPrimitive = t: v: {
    _type = "gvariant";
    type = t;
    value = v;
    __toString = self: "@${self.type} ${toString self.value}"; # https://docs.gtk.org/glib/gvariant-text.html
  };

  type = {
    arrayOf = t: "a${t}";
    maybeOf = t: "m${t}";
    tupleOf = ts: "(${concatStrings ts})";
    dictionaryEntryOf = nameType: valueType: "{${nameType}${valueType}}";
    string = "s";
    boolean = "b";
    uchar = "y";
    int16 = "n";
    uint16 = "q";
    int32 = "i";
    uint32 = "u";
    int64 = "x";
    uint64 = "t";
    double = "d";
    variant = "v";
  };

in
rec {

  inherit type;

  /**
    Check if a value is a GVariant value


    # Inputs

    `v`

    : value to check

    # Type

    ```
    isGVariant :: Any -> Bool
    ```
  */
  isGVariant = v: v._type or "" == "gvariant";

  intConstructors = [
    {
      name = "mkInt32";
      type = type.int32;
      min = -2147483648;
      max = 2147483647;
    }
    {
      name = "mkUint32";
      type = type.uint32;
      min = 0;
      max = 4294967295;
    }
    {
      name = "mkInt64";
      type = type.int64;
      # Nix does not support such large numbers.
      min = null;
      max = null;
    }
    {
      name = "mkUint64";
      type = type.uint64;
      min = 0;
      # Nix does not support such large numbers.
      max = null;
    }
    {
      name = "mkInt16";
      type = type.int16;
      min = -32768;
      max = 32767;
    }
    {
      name = "mkUint16";
      type = type.uint16;
      min = 0;
      max = 65535;
    }
    {
      name = "mkUchar";
      type = type.uchar;
      min = 0;
      max = 255;
    }
  ];

  /**
    Returns the GVariant value that most closely matches the given Nix value.
    If no GVariant value can be found unambiguously then error is thrown.


    # Inputs

    `v`

    : 1\. Function argument

    # Type

    ```
    mkValue :: Any -> gvariant
    ```
  */
  mkValue = v:
    if builtins.isBool v then
      mkBoolean v
    else if builtins.isFloat v then
      mkDouble v
    else if builtins.isString v then
      mkString v
    else if builtins.isList v then
      mkArray v
    else if isGVariant v then
      v
    else if builtins.isInt v then
      let
        validConstructors = builtins.filter ({ min, max, ... }: (min == null || min <= v) && (max == null || v <= max)) intConstructors;
      in
      throw ''
        The GVariant type for number “${builtins.toString v}” is unclear.
        Please wrap the value with one of the following, depending on the value type in GSettings schema:

        ${lib.concatMapStringsSep "\n" ({ name, type, ...}: "- `lib.gvariant.${name}` for `${type}`") validConstructors}
      ''
    else if builtins.isAttrs v then
      throw "Cannot construct GVariant value from an attribute set. If you want to construct a dictionary, you will need to create an array containing items constructed with `lib.gvariant.mkDictionaryEntry`."
    else
      throw "The GVariant type of “${builtins.typeOf v}” can't be inferred.";

  /**
    Returns the GVariant array from the given type of the elements and a Nix list.


    # Inputs

    `elems`

    : 1\. Function argument

    # Type

    ```
    mkArray :: [Any] -> gvariant
    ```

    # Examples
    :::{.example}
    ## `lib.gvariant.mkArray` usage example

    ```nix
    # Creating a string array
    lib.gvariant.mkArray [ "a" "b" "c" ]
    ```

    :::
  */
  mkArray = elems:
    let
      vs = map mkValue (lib.throwIf (elems == [ ]) "Please create empty array with mkEmptyArray." elems);
      elemType = lib.throwIfNot (lib.all (t: (head vs).type == t) (map (v: v.type) vs))
        "Elements in a list should have same type."
        (head vs).type;
    in
    mkPrimitive (type.arrayOf elemType) vs // {
      __toString = self:
        "@${self.type} [${concatMapStringsSep "," toString self.value}]";
    };

  /**
    Returns the GVariant array from the given empty Nix list.


    # Inputs

    `elemType`

    : 1\. Function argument

    # Type

    ```
    mkEmptyArray :: gvariant.type -> gvariant
    ```

    # Examples
    :::{.example}
    ## `lib.gvariant.mkEmptyArray` usage example

    ```nix
    # Creating an empty string array
    lib.gvariant.mkEmptyArray (lib.gvariant.type.string)
    ```

    :::
  */
  mkEmptyArray = elemType: mkPrimitive (type.arrayOf elemType) [ ] // {
    __toString = self: "@${self.type} []";
  };


  /**
    Returns the GVariant variant from the given Nix value. Variants are containers
    of different GVariant type.


    # Inputs

    `elem`

    : 1\. Function argument

    # Type

    ```
    mkVariant :: Any -> gvariant
    ```

    # Examples
    :::{.example}
    ## `lib.gvariant.mkVariant` usage example

    ```nix
    lib.gvariant.mkArray [
      (lib.gvariant.mkVariant "a string")
      (lib.gvariant.mkVariant (lib.gvariant.mkInt32 1))
    ]
    ```

    :::
  */
  mkVariant = elem:
    let gvarElem = mkValue elem;
    in mkPrimitive type.variant gvarElem // {
      __toString = self: "<${toString self.value}>";
    };

  /**
    Returns the GVariant dictionary entry from the given key and value.


    # Inputs

    `name`

    : The key of the entry

    `value`

    : The value of the entry

    # Type

    ```
    mkDictionaryEntry :: String -> Any -> gvariant
    ```

    # Examples
    :::{.example}
    ## `lib.gvariant.mkDictionaryEntry` usage example

    ```nix
    # A dictionary describing an Epiphany’s search provider
    [
      (lib.gvariant.mkDictionaryEntry "url" (lib.gvariant.mkVariant "https://duckduckgo.com/?q=%s&t=epiphany"))
      (lib.gvariant.mkDictionaryEntry "bang" (lib.gvariant.mkVariant "!d"))
      (lib.gvariant.mkDictionaryEntry "name" (lib.gvariant.mkVariant "DuckDuckGo"))
    ]
    ```

    :::
  */
  mkDictionaryEntry =
    name:
    value:
    let
      name' = mkValue name;
      value' = mkValue value;
      dictionaryType = type.dictionaryEntryOf name'.type value'.type;
    in
    mkPrimitive dictionaryType { inherit name value; } // {
      __toString = self: "@${self.type} {${name'},${value'}}";
    };

  /**
    Returns the GVariant maybe from the given element type.


    # Inputs

    `elemType`

    : 1\. Function argument

    `elem`

    : 2\. Function argument

    # Type

    ```
    mkMaybe :: gvariant.type -> Any -> gvariant
    ```
  */
  mkMaybe = elemType: elem:
    mkPrimitive (type.maybeOf elemType) elem // {
      __toString = self:
        if self.value == null then
          "@${self.type} nothing"
        else
          "just ${toString self.value}";
    };

  /**
    Returns the GVariant nothing from the given element type.


    # Inputs

    `elemType`

    : 1\. Function argument

    # Type

    ```
    mkNothing :: gvariant.type -> gvariant
    ```
  */
  mkNothing = elemType: mkMaybe elemType null;

  /**
    Returns the GVariant just from the given Nix value.


    # Inputs

    `elem`

    : 1\. Function argument

    # Type

    ```
    mkJust :: Any -> gvariant
    ```
  */
  mkJust = elem: let gvarElem = mkValue elem; in mkMaybe gvarElem.type gvarElem;

  /**
    Returns the GVariant tuple from the given Nix list.


    # Inputs

    `elems`

    : 1\. Function argument

    # Type

    ```
    mkTuple :: [Any] -> gvariant
    ```
  */
  mkTuple = elems:
    let
      gvarElems = map mkValue elems;
      tupleType = type.tupleOf (map (e: e.type) gvarElems);
    in
    mkPrimitive tupleType gvarElems // {
      __toString = self:
        "@${self.type} (${concatMapStringsSep "," toString self.value})";
    };

  /**
    Returns the GVariant boolean from the given Nix bool value.


    # Inputs

    `v`

    : 1\. Function argument

    # Type

    ```
    mkBoolean :: Bool -> gvariant
    ```
  */
  mkBoolean = v:
    mkPrimitive type.boolean v // {
      __toString = self: if self.value then "true" else "false";
    };

  /**
    Returns the GVariant string from the given Nix string value.


    # Inputs

    `v`

    : 1\. Function argument

    # Type

    ```
    mkString :: String -> gvariant
    ```
  */
  mkString = v:
    let sanitize = s: replaceStrings [ "\n" ] [ "\\n" ] (escape [ "'" "\\" ] s);
    in mkPrimitive type.string v // {
      __toString = self: "'${sanitize self.value}'";
    };

  /**
    Returns the GVariant object path from the given Nix string value.


    # Inputs

    `v`

    : 1\. Function argument

    # Type

    ```
    mkObjectpath :: String -> gvariant
    ```
  */
  mkObjectpath = v:
    mkPrimitive type.string v // {
      __toString = self: "objectpath '${escape [ "'" ] self.value}'";
    };

  /**
    Returns the GVariant uchar from the given Nix int value.

    # Type

    ```
    mkUchar :: Int -> gvariant
    ```
  */
  mkUchar = mkPrimitive type.uchar;

  /**
    Returns the GVariant int16 from the given Nix int value.

    # Type

    ```
    mkInt16 :: Int -> gvariant
    ```
  */
  mkInt16 = mkPrimitive type.int16;

  /**
    Returns the GVariant uint16 from the given Nix int value.

    # Type

    ```
    mkUint16 :: Int -> gvariant
    ```
  */
  mkUint16 = mkPrimitive type.uint16;

  /**
    Returns the GVariant int32 from the given Nix int value.


    # Inputs

    `v`

    : 1\. Function argument

    # Type

    ```
    mkInt32 :: Int -> gvariant
    ```
  */
  mkInt32 = v:
    mkPrimitive type.int32 v // {
      __toString = self: toString self.value;
    };

  /**
    Returns the GVariant uint32 from the given Nix int value.

    # Type

    ```
    mkUint32 :: Int -> gvariant
    ```
  */
  mkUint32 = mkPrimitive type.uint32;

  /**
    Returns the GVariant int64 from the given Nix int value.

    # Type

    ```
    mkInt64 :: Int -> gvariant
    ```
  */
  mkInt64 = mkPrimitive type.int64;

  /**
    Returns the GVariant uint64 from the given Nix int value.

    # Type

    ```
    mkUint64 :: Int -> gvariant
    ```
  */
  mkUint64 = mkPrimitive type.uint64;

  /**
    Returns the GVariant double from the given Nix float value.


    # Inputs

    `v`

    : 1\. Function argument

    # Type

    ```
    mkDouble :: Float -> gvariant
    ```
  */
  mkDouble = v:
    mkPrimitive type.double v // {
      __toString = self: toString self.value;
    };
}