display.rs

  1use crate::{point, size, Bounds, DisplayId, GlobalPixels, PlatformDisplay};
  2use anyhow::Result;
  3use cocoa::{
  4    appkit::NSScreen,
  5    base::{id, nil},
  6    foundation::{NSDictionary, NSPoint, NSRect, NSSize, NSString},
  7};
  8use core_foundation::uuid::{CFUUIDGetUUIDBytes, CFUUIDRef};
  9use core_graphics::display::{CGDirectDisplayID, CGDisplayBounds, CGGetActiveDisplayList};
 10use objc::{msg_send, sel, sel_impl};
 11use uuid::Uuid;
 12
 13#[derive(Debug)]
 14pub struct MacDisplay(pub(crate) CGDirectDisplayID);
 15
 16unsafe impl Send for MacDisplay {}
 17
 18impl MacDisplay {
 19    /// Get the screen with the given [`DisplayId`].
 20    pub fn find_by_id(id: DisplayId) -> Option<Self> {
 21        Self::all().find(|screen| screen.id() == id)
 22    }
 23
 24    /// Get the screen with the given persistent [`Uuid`].
 25    pub fn find_by_uuid(uuid: Uuid) -> Option<Self> {
 26        Self::all().find(|screen| screen.uuid().ok() == Some(uuid))
 27    }
 28
 29    /// Get the primary screen - the one with the menu bar, and whose bottom left
 30    /// corner is at the origin of the AppKit coordinate system.
 31    pub fn primary() -> Self {
 32        // Instead of iterating through all active systems displays via `all()` we use the first
 33        // NSScreen and gets its CGDirectDisplayID, because we can't be sure that `CGGetActiveDisplayList`
 34        // will always return a list of active displays (machine might be sleeping).
 35        //
 36        // The following is what Chromium does too:
 37        //
 38        // https://chromium.googlesource.com/chromium/src/+/66.0.3359.158/ui/display/mac/screen_mac.mm#56
 39        unsafe {
 40            let screens = NSScreen::screens(nil);
 41            let screen = cocoa::foundation::NSArray::objectAtIndex(screens, 0);
 42            let device_description = NSScreen::deviceDescription(screen);
 43            let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
 44            let screen_number = device_description.objectForKey_(screen_number_key);
 45            let screen_number: CGDirectDisplayID = msg_send![screen_number, unsignedIntegerValue];
 46            Self(screen_number)
 47        }
 48    }
 49
 50    /// Obtains an iterator over all currently active system displays.
 51    pub fn all() -> impl Iterator<Item = Self> {
 52        unsafe {
 53            // We're assuming there aren't more than 32 displays connected to the system.
 54            let mut displays = Vec::with_capacity(32);
 55            let mut display_count = 0;
 56            let result = CGGetActiveDisplayList(
 57                displays.capacity() as u32,
 58                displays.as_mut_ptr(),
 59                &mut display_count,
 60            );
 61
 62            if result == 0 {
 63                displays.set_len(display_count as usize);
 64                displays.into_iter().map(MacDisplay)
 65            } else {
 66                panic!("Failed to get active display list. Result: {result}");
 67            }
 68        }
 69    }
 70}
 71
 72#[link(name = "ApplicationServices", kind = "framework")]
 73extern "C" {
 74    fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> CFUUIDRef;
 75}
 76
 77/// Convert the given rectangle from Cocoa's coordinate space to GPUI's coordinate space.
 78///
 79/// Cocoa's coordinate space has its origin at the bottom left of the primary screen,
 80/// with the Y axis pointing upwards.
 81///
 82/// Conversely, in GPUI's coordinate system, the origin is placed at the top left of the primary
 83/// screen, with the Y axis pointing downwards (matching CoreGraphics)
 84pub(crate) fn global_bounds_from_ns_rect(rect: NSRect) -> Bounds<GlobalPixels> {
 85    let primary_screen_size = unsafe { CGDisplayBounds(MacDisplay::primary().id().0) }.size;
 86
 87    Bounds {
 88        origin: point(
 89            GlobalPixels(rect.origin.x as f32),
 90            GlobalPixels(
 91                primary_screen_size.height as f32 - rect.origin.y as f32 - rect.size.height as f32,
 92            ),
 93        ),
 94        size: size(
 95            GlobalPixels(rect.size.width as f32),
 96            GlobalPixels(rect.size.height as f32),
 97        ),
 98    }
 99}
100
101/// Convert the given rectangle from GPUI's coordinate system to Cocoa's native coordinate space.
102///
103/// Cocoa's coordinate space has its origin at the bottom left of the primary screen,
104/// with the Y axis pointing upwards.
105///
106/// Conversely, in GPUI's coordinate system, the origin is placed at the top left of the primary
107/// screen, with the Y axis pointing downwards (matching CoreGraphics)
108pub(crate) fn global_bounds_to_ns_rect(bounds: Bounds<GlobalPixels>) -> NSRect {
109    let primary_screen_height = MacDisplay::primary().bounds().size.height;
110
111    NSRect::new(
112        NSPoint::new(
113            bounds.origin.x.into(),
114            (primary_screen_height - bounds.origin.y - bounds.size.height).into(),
115        ),
116        NSSize::new(bounds.size.width.into(), bounds.size.height.into()),
117    )
118}
119
120impl PlatformDisplay for MacDisplay {
121    fn id(&self) -> DisplayId {
122        DisplayId(self.0)
123    }
124
125    fn uuid(&self) -> Result<Uuid> {
126        let cfuuid = unsafe { CGDisplayCreateUUIDFromDisplayID(self.0 as CGDirectDisplayID) };
127        anyhow::ensure!(
128            !cfuuid.is_null(),
129            "AppKit returned a null from CGDisplayCreateUUIDFromDisplayID"
130        );
131
132        let bytes = unsafe { CFUUIDGetUUIDBytes(cfuuid) };
133        Ok(Uuid::from_bytes([
134            bytes.byte0,
135            bytes.byte1,
136            bytes.byte2,
137            bytes.byte3,
138            bytes.byte4,
139            bytes.byte5,
140            bytes.byte6,
141            bytes.byte7,
142            bytes.byte8,
143            bytes.byte9,
144            bytes.byte10,
145            bytes.byte11,
146            bytes.byte12,
147            bytes.byte13,
148            bytes.byte14,
149            bytes.byte15,
150        ]))
151    }
152
153    fn bounds(&self) -> Bounds<GlobalPixels> {
154        unsafe {
155            // CGDisplayBounds is in "global display" coordinates, where 0 is
156            // the top left of the primary display.
157            let bounds = CGDisplayBounds(self.0);
158
159            Bounds {
160                origin: point(
161                    GlobalPixels(bounds.origin.x as f32),
162                    GlobalPixels(bounds.origin.y as f32),
163                ),
164                size: size(
165                    GlobalPixels(bounds.size.width as f32),
166                    GlobalPixels(bounds.size.height as f32),
167                ),
168            }
169        }
170    }
171}