knoll 0.4.0

A command-line tool for configuring macOS displays
Documentation
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
///! Concrete implementation of the display traits using macOS APIs.
///
/// Notes:
/// I Experimented with with the `CGDisplayMode` Core Graphics APIs rather
/// than using the private `CGSConfigureDisplayMode` APIs.  I encountered
/// puzzling behavior where the modes reported by `CGDisplayCopyAllDisplayModes`
/// would not include the mode reported by `CGDisplayCopyDisplayMode`.  It is
/// possible that perhaps I have not defined the FFI bindings quite correctly,
/// but for the time being the behavior of the private APIs seems closer to
/// the desired functionality.  
use log::*;
use serde::Serialize;
use std::collections::{BTreeMap, HashMap};
use std::hash::{Hash, Hasher};

use crate::core_graphics::*;
use crate::displays::*;

/// Helper for converting a `CGError` with a context string into a
/// `display::Error`.  Should not be used when `CGError` is `success`.
pub fn cg_error_to_error(cg_error: CGError, context: &str) -> Error {
    assert_ne!(
        cg_error,
        CGError::success,
        "cg_error_to_error should not be used CGError::success"
    );

    Error::Internal(context.to_owned())
}

/// Helper to lift a `CGError` to an `display::Error` by providing some additional
/// context as to what operation caused it.
pub fn cg_error_to_result(cg_error: CGError, context: &str) -> Result<(), Error> {
    match cg_error {
        CGError::success => Ok(()),
        _ => Err(cg_error_to_error(cg_error, context)),
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, Clone, Serialize)]
pub struct RealDisplayMode {
    /// DisplayID to which this mode corresponds.
    #[serde(skip_serializing)]
    display_id: DisplayID,
    /// Internal id for this specific mode.
    #[serde(skip_serializing)]
    mode: i32,
    pub scaled: bool,
    pub color_depth: usize,
    /// Monitor refresh rate in Hz.  Some displays may report 0.
    pub frequency: usize,
    pub extents: Point,
}

impl PartialEq for RealDisplayMode {
    fn eq(&self, other: &Self) -> bool {
        self.scaled() == other.scaled()
            && self.color_depth == other.color_depth
            && self.frequency == other.frequency
            && self.extents == other.extents
    }
}

impl Eq for RealDisplayMode {}

// TODO Only for debugging modes with seemingly identical properties.
impl Hash for RealDisplayMode {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.scaled.hash(state);
        self.color_depth.hash(state);
        self.frequency.hash(state);
        self.extents.hash(state);
    }
}

impl RealDisplayMode {
    /// Create a RealDisplayMode from a `DisplayID` and `core_graphics`
    /// mode description.
    fn new(display_id: DisplayID, mode_desc: CGSDisplayModeDescription) -> Self {
        if mode_desc.depth == 0 {
            warn!(
                "Encountered a display mode with a bit depth of zero: {:?} {:?}",
                display_id, mode_desc
            );
        }

        RealDisplayMode {
            display_id,
            mode: mode_desc.mode,
            scaled: mode_desc.scale > 1.0,
            // TODO u32 does not have From for usize, apparently just in case
            //   a 16-bit platform is the target.  Revise when infallible
            //   try_from might be standard here?
            color_depth: mode_desc.depth as usize,
            frequency: mode_desc.freq.into(),
            extents: Point {
                x: mode_desc.width.into(),
                y: mode_desc.height.into(),
            },
        }
    }
}

impl DisplayMode for RealDisplayMode {
    fn scaled(&self) -> bool {
        self.scaled
    }
    fn color_depth(&self) -> usize {
        self.color_depth
    }
    fn frequency(&self) -> usize {
        self.frequency
    }
    fn extents(&self) -> &Point {
        &self.extents
    }
}

////////////////////////////////////////////////////////////////////////////////

pub struct RealDisplayConfigTransaction {
    /// Map from UUIDs to their `DisplayID`s.
    displays: BTreeMap<String, DisplayID>,
    /// Keep track of requested rotations, so that if
    /// other configuration steps fail or the configuration is cancelled,
    /// they will not be applied.  This is not strictly necessary, but
    /// it presents a more uniform behavior for the interface.
    rotations: HashMap<DisplayID, Rotation>,
    /// Keep track of requested brightness changes.
    brightness_map: HashMap<DisplayID, f32>,
    /// The active configuration reference for this transaction.
    config_ref: CGDisplayConfigRef,
    /// Keep track whether the transaction has been dropped.
    dropped: bool,
}

impl RealDisplayConfigTransaction {
    fn new(real_display_map: &BTreeMap<String, RealDisplay>) -> Result<Self, Error> {
        let config_ref = cg_begin_display_configuration().map_err(|cg_error| {
            cg_error_to_error(
                cg_error,
                "While attempting begin a configuration transaction",
            )
        })?;

        // Documentation seems to indicate that it should be possible to
        // configure a fade for the configuration change, but it always seems
        // to fail with `notImplemented`.
        // cg_error_to_result(
        //     cg_configure_display_fade_effect(&config_ref, 0.3, 0.5, 0.0, 0.0, 0.0),
        //     "Failure configuring the fade effect",
        // )?;

        Ok(Self {
            displays: real_display_map
                .iter()
                .map(|(uuid, real_display)| (uuid.clone(), real_display.display_id))
                .collect(),
            rotations: HashMap::new(),
            brightness_map: HashMap::new(),
            config_ref,
            dropped: false,
        })
    }

    /// Helper to abstract out some of boilerplate of mapping a UUID to a
    /// display id.
    fn display_id(&self, uuid: &str) -> Result<DisplayID, Error> {
        self.displays
            .get(uuid)
            .cloned()
            .ok_or(Error::UnknownUUID(uuid.to_owned()))
    }

    /// Cleaning up after beginning configuration will consume the
    /// `CGDisplayConfigRef`.  However, that requires a move.  As we
    /// cannot move the `config` field in `drop`, `complete`, and `cancel`
    /// we swap it out instead.
    fn move_config(&mut self) -> CGDisplayConfigRef {
        let mut config_ref = std::ptr::null_mut();
        std::mem::swap(&mut config_ref, &mut self.config_ref);
        config_ref
    }
}

impl DisplayConfigTransaction for RealDisplayConfigTransaction {
    type DisplayModeType = RealDisplayMode;

    fn set_mode(&mut self, uuid: &str, mode: &Self::DisplayModeType) -> Result<(), Error> {
        if self.dropped {
            return Err(Error::InvalidTransactionState);
        }

        let display_id = self.display_id(uuid)?;
        // Check that we were not passed a mode for a different display.
        // Panic here as this is a programming error.
        if mode.display_id != display_id {
            panic!(
                "Tried using a display mode for display {:?} with display {:?}",
                mode.display_id, display_id
            );
        }
        cg_error_to_result(
            cgs_configure_display_mode(&self.config_ref, display_id, mode.mode),
            format!("While attempting to set the mode of {}", uuid,).as_str(),
        )
    }

    fn set_rotation(&mut self, uuid: &str, rotation: Rotation) -> Result<(), Error> {
        if self.dropped {
            return Err(Error::InvalidTransactionState);
        }

        let display_id = self.display_id(uuid)?;

        if self.rotations.contains_key(&display_id) {
            return Err(Error::DuplicateConfiguration(uuid.to_owned()));
        }

        // Keep track of applied rotations and queue them up, so that
        // the overall configuration fails or is cancelled, we do not
        // apply them.
        self.rotations.insert(display_id, rotation);

        Ok(())
    }

    fn set_brightness(&mut self, uuid: &str, brightness: f32) -> Result<(), Error> {
        if self.dropped {
            return Err(Error::InvalidTransactionState);
        } else if brightness < 0.0 || brightness > 1.0 {
            return Err(Error::InvalidBrightness(brightness));
        }

        let display_id = self.display_id(uuid)?;
        if self.brightness_map.contains_key(&display_id) {
            return Err(Error::DuplicateConfiguration(uuid.to_owned()));
        }
        self.brightness_map.insert(display_id, brightness);
        Ok(())
    }

    fn set_origin(&mut self, uuid: &str, point: &Point) -> Result<(), Error> {
        if self.dropped {
            return Err(Error::InvalidTransactionState);
        }

        let display_id = self.display_id(uuid)?;
        cg_error_to_result(
            cg_configure_display_origin(
                &self.config_ref,
                display_id,
                point.x as i32,
                point.y as i32,
            ),
            format!("While attempting to set the origin of {}", uuid).as_str(),
        )
    }

    fn set_enabled(&mut self, uuid: &str, enabled: bool) -> Result<(), Error> {
        if self.dropped {
            return Err(Error::InvalidTransactionState);
        }

        let display_id = self.display_id(uuid)?;
        if !enabled {
            cg_error_to_result(
                cgs_configure_display_enabled(&self.config_ref, display_id, enabled),
                format!("While attempting to adjust the enablement of {}", uuid).as_str(),
            )
        } else {
            Ok(())
        }
    }

    fn set_mirroring(&mut self, uuid: &str, mirror_of_uuid: Option<&str>) -> Result<(), Error> {
        if self.dropped {
            return Err(Error::InvalidTransactionState);
        }

        let display_id = self.display_id(uuid)?;
        // Determine master DisplayID (None disables mirroring)
        let master_id = mirror_of_uuid
            .map(|uuid| self.display_id(uuid))
            .transpose()?;

        cg_error_to_result(
            cg_configure_display_mirror_of_display(&self.config_ref, display_id, master_id),
            match mirror_of_uuid {
                Some(mirror_uuid) => format!(
                    "While attempting to set display {} mirroring to {}",
                    uuid, mirror_uuid
                ),
                None => format!("While attempting to disable mirroring for display {}", uuid),
            }
            .as_str(),
        )
    }

    fn commit(mut self) -> Result<(), Error> {
        if self.dropped {
            return Err(Error::InvalidTransactionState);
        }

        cg_error_to_result(
            cg_complete_display_configuration(
                self.move_config(),
                CGConfigureOption::kCGConfigurePermanently,
            ),
            "While attempting to commit the configuration transaction",
        )?;

        for (&display_id, &rotation) in &self.rotations {
            cg_error_to_result(
                sls_set_display_rotation(display_id, rotation.into()),
                format!(
                    "While attempting to set display rotation of {:?} to {:?}",
                    display_id, rotation
                )
                .as_str(),
            )?;
        }

        for (&display_id, &brightness) in &self.brightness_map {
            cg_error_to_result(
                display_services_set_brightness(display_id, brightness),
                format!(
                    "While attempting to set display brightness of {:?} to {:?}",
                    display_id, brightness
                )
                .as_str(),
            )?;
        }

        self.dropped = true;
        Ok(())
    }
}

impl Drop for RealDisplayConfigTransaction {
    /// Ensure that we consume the `CGDisplayConfigRef` if an API consumer
    /// fails to call `complete` or `cancel`.
    fn drop(&mut self) {
        if !self.dropped {
            if cg_cancel_display_configuration(self.move_config()) != CGError::success {
                error!("Failed to cancel the configuration transaction");
            }
            self.dropped = true;
        }
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug)]
pub struct RealDisplay {
    /// DisplayID used to associate this RealDisplay with an attached display.
    display_id: DisplayID,
    uuid: String,
    mirror_of: Option<String>,
    enabled: bool,
    origin: Point,
    rotation: Rotation,
    mode: RealDisplayMode,
    modes: Vec<RealDisplayMode>,
    brightness: Option<f32>,
}

/// Undo display_rotation to the Point.  Note that this is not
/// the same thing as rotating the Point in 2D space.  This is just
/// so that display extents can be presented uniformly in landscape
/// resolution.
pub fn undo_display_rotation(point: Point, rotation: Rotation) -> Point {
    match rotation {
        Rotation::Zero | Rotation::OneEighty => point,
        Rotation::Ninety | Rotation::TwoSeventy => Point {
            x: point.y,
            y: point.x,
        },
    }
}

impl RealDisplay {
    /// Obtain a unique identifying name for the given display.
    // TODO Perform some additional testing to see this remains "persistent"
    //  for identical model displays.
    fn compute_uuid(display_id: DisplayID) -> String {
        // Use CoreGraphics UUID API.  I've already determined that for
        // some of dual displays that the manufacturer doesn't report a
        // meaningful serial number.
        let cfuuid = cg_display_create_uuid_from_display_id(display_id);
        let cfstring = cf_uuid_create_string(kCFAllocatorDefault, cfuuid);
        let mut buffer: [u8; 37] = [0; 37];
        if !cf_string_get_cstring(
            cfstring,
            &mut buffer,
            CFStringBuiltInEncodings::ASCII.into(),
        ) {
            // It seems reasonable to panic here, as the UUID has a fixed
            // format and length.
            panic!("Buffer to receive UUID is too small.")
        }
        // Need to manually release the resources.
        cf_release(cfstring);
        cf_release(cfuuid);

        // It is safe to unwrap here as we know that the UUID will always
        // be ASCII which should never fail with from_utf8.
        String::from_utf8(buffer[0..36].to_vec())
            .unwrap()
            .to_lowercase()
            .replace('-', "")
    }

    /// Create a `RealDisplay` given a `DisplayID`.
    fn new(display_id: DisplayID) -> Result<Self, Error> {
        let uuid = RealDisplay::compute_uuid(display_id);
        // Determine if this display is mirroring another and record master UUID
        let mirror_of =
            cg_display_mirrors_display(display_id).map(|did| RealDisplay::compute_uuid(did));

        let mut num_modes = 0;
        cg_error_to_result(
            cgs_get_number_of_display_modes(display_id, &mut num_modes),
            format!(
                "While attempting to obtain the number of display modes on {}",
                uuid
            )
            .as_str(),
        )?;

        // Obtain the current display rotation for normalizing the modes.
        let float_rotation = cg_display_rotation(display_id);
        let rotation = Rotation::try_from(float_rotation)
            .expect(format!("Unexpected display rotation angle: {}", float_rotation).as_str());

        let mut current_mode_num = 0;
        cg_error_to_result(
            cgs_get_current_display_mode(display_id, &mut current_mode_num),
            format!(
                "While attempting to obtain the current display mode on {}",
                uuid
            )
            .as_str(),
        )?;
        let mut current_mode = None;

        // Temporary for debugging
        let mut mode_buckets: HashMap<RealDisplayMode, Vec<CGSDisplayModeDescription>> =
            HashMap::new();

        let mut possible_modes = Vec::new();
        for mode_num in 0..num_modes {
            let mut desc = CGSDisplayModeDescription::default();
            cg_error_to_result(
                cgs_get_display_mode_description(display_id, mode_num, &mut desc),
                format!("While attempting to obtain a mode description on {}", uuid).as_str(),
            )?;

            // TODO Eliminate clone
            let mut mode = RealDisplayMode::new(display_id, desc.clone());
            // Normalize the extents.
            mode.extents = undo_display_rotation(mode.extents, rotation);

            if current_mode_num == mode_num {
                current_mode = Some(mode.clone());
            }

            // Group mode descriptions into buckets for investigation.
            match mode_buckets.get_mut(&mode) {
                Some(descs) => descs.push(desc),
                None => {
                    mode_buckets.insert(mode.clone(), vec![desc]);
                }
            }

            possible_modes.push(mode);
        }

        // Log the duplicates.
        // Further investigation is needed as to why some essentially duplicate
        // modes are reported from the API.
        for (mode, descs) in &mode_buckets {
            if descs.len() > 1 {
                warn!(
                    "Encountered display modes with identical properties {:?}:  {:?}",
                    mode, descs
                );
            }
        }

        // TODO Is the likely enough that it should be reported as an actual
        //   error condition?
        assert!(current_mode.is_some());

        let enabled = cg_display_is_active(display_id) || cg_display_is_in_mirror_set(display_id);
        let cg_point = cg_display_bounds(display_id).origin;

        let mut brightness = 0.0;
        let brightness = match cg_error_to_result(
            display_services_get_brightness(display_id, &mut brightness),
            "Error obtaining display brightness",
        ) {
            Ok(()) => Some(brightness),
            Err(Error::Internal(_)) => None, // Not all displays support brightness.
            Err(e) => return Err(e),         // Other errors are unexpected.
        };

        Ok(RealDisplay {
            display_id,
            uuid,
            mirror_of,
            enabled,
            origin: Point {
                // TODO Could not find a safer more idiomatic way of converting?
                x: cg_point.x as i64,
                y: cg_point.y as i64,
            },
            rotation,
            mode: current_mode.unwrap(),
            modes: mode_buckets.into_keys().collect::<Vec<RealDisplayMode>>(),
            brightness,
        })
    }
}

impl Display for RealDisplay {
    fn uuid(&self) -> &str {
        self.uuid.as_str()
    }

    fn enabled(&self) -> bool {
        self.enabled
    }

    fn origin(&self) -> &Point {
        &self.origin
    }

    fn rotation(&self) -> Rotation {
        self.rotation
    }

    fn brightness(&self) -> Option<f32> {
        self.brightness
    }

    type DisplayModeType = RealDisplayMode;

    fn current_mode(&self) -> &Self::DisplayModeType {
        &self.mode
    }

    fn possible_modes(&self) -> &[Self::DisplayModeType] {
        self.modes.as_slice()
    }

    fn mirror_of(&self) -> Option<&str> {
        self.mirror_of.as_deref()
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug)]
pub struct RealDisplayState {
    displays: BTreeMap<String, RealDisplay>,
}

impl DisplayState for RealDisplayState {
    fn current() -> Result<Self, Error> {
        // The current Mac Pro supports eight monitors:
        // https://support.apple.com/en-us/HT213665
        // I have seen references to twelve being supported on some models.
        // So I feel for now 64 is a reasonable bound on real monitors.
        // I will need to experiment with if/how Sidecar displays respond
        // to these APIs.
        let mut display_ids: [DisplayID; 64] = [DisplayID::default(); 64];
        let mut num_displays: u32 = 0;
        // We want the online rather than active displays as that will not
        // include mirrored or sleeping displays.
        cg_get_online_display_list(&mut display_ids, &mut num_displays);
        assert!(
            num_displays <= 64,
            "Number of displays is more than the input array."
        );

        let mut displays = Vec::new();
        // TODO u32 does not have From for usize, apparently just in case
        //   a 16-bit platform is the target.  Revise when infallible
        //   try_from might be standard here?
        for id in display_ids.into_iter().take(num_displays as usize) {
            displays.push(RealDisplay::new(id)?);
        }

        Ok(RealDisplayState {
            displays: displays
                .into_iter()
                .map(|d: RealDisplay| (d.uuid.clone(), d))
                .collect(),
        })
    }

    type DisplayModeType = RealDisplayMode;
    type DisplayType = RealDisplay;
    type DisplayConfigTransactionType = RealDisplayConfigTransaction;

    fn get_displays(&self) -> &BTreeMap<String, Self::DisplayType> {
        &self.displays
    }

    fn configure(&self) -> Result<Self::DisplayConfigTransactionType, Error> {
        RealDisplayConfigTransaction::new(&self.displays)
    }
}