platform.rs

  1use super::{BoolExt as _, Dispatcher, FontSystem, Window};
  2use crate::{executor, keymap::Keystroke, platform, ClipboardItem, Event, Menu, MenuItem};
  3use block::ConcreteBlock;
  4use cocoa::{
  5    appkit::{
  6        NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
  7        NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
  8        NSPasteboardTypeString, NSSavePanel, NSWindow,
  9    },
 10    base::{id, nil, selector},
 11    foundation::{NSArray, NSAutoreleasePool, NSData, NSInteger, NSString, NSURL},
 12};
 13use ctor::ctor;
 14use objc::{
 15    class,
 16    declare::ClassDecl,
 17    msg_send,
 18    runtime::{Class, Object, Sel},
 19    sel, sel_impl,
 20};
 21use ptr::null_mut;
 22use std::{
 23    any::Any,
 24    cell::{Cell, RefCell},
 25    convert::TryInto,
 26    ffi::{c_void, CStr},
 27    os::raw::c_char,
 28    path::{Path, PathBuf},
 29    ptr,
 30    rc::Rc,
 31    slice, str,
 32    sync::Arc,
 33};
 34
 35const MAC_PLATFORM_IVAR: &'static str = "platform";
 36static mut APP_CLASS: *const Class = ptr::null();
 37static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
 38
 39#[ctor]
 40unsafe fn build_classes() {
 41    APP_CLASS = {
 42        let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
 43        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
 44        decl.add_method(
 45            sel!(sendEvent:),
 46            send_event as extern "C" fn(&mut Object, Sel, id),
 47        );
 48        decl.register()
 49    };
 50
 51    APP_DELEGATE_CLASS = {
 52        let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
 53        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
 54        decl.add_method(
 55            sel!(applicationDidFinishLaunching:),
 56            did_finish_launching as extern "C" fn(&mut Object, Sel, id),
 57        );
 58        decl.add_method(
 59            sel!(applicationDidBecomeActive:),
 60            did_become_active as extern "C" fn(&mut Object, Sel, id),
 61        );
 62        decl.add_method(
 63            sel!(applicationDidResignActive:),
 64            did_resign_active as extern "C" fn(&mut Object, Sel, id),
 65        );
 66        decl.add_method(
 67            sel!(handleGPUIMenuItem:),
 68            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 69        );
 70        decl.add_method(
 71            sel!(application:openFiles:),
 72            open_files as extern "C" fn(&mut Object, Sel, id, id),
 73        );
 74        decl.register()
 75    }
 76}
 77
 78#[derive(Default)]
 79pub struct MacMainThreadPlatform(RefCell<MacMainThreadPlatformState>);
 80
 81#[derive(Default)]
 82pub struct MacMainThreadPlatformState {
 83    become_active: Option<Box<dyn FnMut()>>,
 84    resign_active: Option<Box<dyn FnMut()>>,
 85    event: Option<Box<dyn FnMut(crate::Event) -> bool>>,
 86    menu_command: Option<Box<dyn FnMut(&str, Option<&dyn Any>)>>,
 87    open_files: Option<Box<dyn FnMut(Vec<PathBuf>)>>,
 88    finish_launching: Option<Box<dyn FnOnce() -> ()>>,
 89    menu_actions: Vec<(String, Option<Box<dyn Any>>)>,
 90}
 91
 92impl MacMainThreadPlatform {
 93    unsafe fn create_menu_bar(&self, menus: Vec<Menu>) -> id {
 94        let menu_bar = NSMenu::new(nil).autorelease();
 95        let mut state = self.0.borrow_mut();
 96
 97        state.menu_actions.clear();
 98
 99        for menu_config in menus {
100            let menu_bar_item = NSMenuItem::new(nil).autorelease();
101            let menu = NSMenu::new(nil).autorelease();
102            let menu_name = menu_config.name;
103
104            menu.setTitle_(ns_string(menu_name));
105
106            for item_config in menu_config.items {
107                let item;
108
109                match item_config {
110                    MenuItem::Separator => {
111                        item = NSMenuItem::separatorItem(nil);
112                    }
113                    MenuItem::Action {
114                        name,
115                        keystroke,
116                        action,
117                        arg,
118                    } => {
119                        if let Some(keystroke) = keystroke {
120                            let keystroke = Keystroke::parse(keystroke).unwrap_or_else(|err| {
121                                panic!(
122                                    "Invalid keystroke for menu item {}:{} - {:?}",
123                                    menu_name, name, err
124                                )
125                            });
126
127                            let mut mask = NSEventModifierFlags::empty();
128                            for (modifier, flag) in &[
129                                (keystroke.cmd, NSEventModifierFlags::NSCommandKeyMask),
130                                (keystroke.ctrl, NSEventModifierFlags::NSControlKeyMask),
131                                (keystroke.alt, NSEventModifierFlags::NSAlternateKeyMask),
132                            ] {
133                                if *modifier {
134                                    mask |= *flag;
135                                }
136                            }
137
138                            item = NSMenuItem::alloc(nil)
139                                .initWithTitle_action_keyEquivalent_(
140                                    ns_string(name),
141                                    selector("handleGPUIMenuItem:"),
142                                    ns_string(&keystroke.key),
143                                )
144                                .autorelease();
145                            item.setKeyEquivalentModifierMask_(mask);
146                        } else {
147                            item = NSMenuItem::alloc(nil)
148                                .initWithTitle_action_keyEquivalent_(
149                                    ns_string(name),
150                                    selector("handleGPUIMenuItem:"),
151                                    ns_string(""),
152                                )
153                                .autorelease();
154                        }
155
156                        let tag = state.menu_actions.len() as NSInteger;
157                        let _: () = msg_send![item, setTag: tag];
158                        state.menu_actions.push((action.to_string(), arg));
159                    }
160                }
161
162                menu.addItem_(item);
163            }
164
165            menu_bar_item.setSubmenu_(menu);
166            menu_bar.addItem_(menu_bar_item);
167        }
168
169        menu_bar
170    }
171}
172
173impl platform::MainThreadPlatform for MacMainThreadPlatform {
174    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
175        self.0.borrow_mut().become_active = Some(callback);
176    }
177
178    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
179        self.0.borrow_mut().resign_active = Some(callback);
180    }
181
182    fn on_event(&self, callback: Box<dyn FnMut(crate::Event) -> bool>) {
183        self.0.borrow_mut().event = Some(callback);
184    }
185
186    fn on_open_files(&self, callback: Box<dyn FnMut(Vec<PathBuf>)>) {
187        self.0.borrow_mut().open_files = Some(callback);
188    }
189
190    fn run(&self, on_finish_launching: Box<dyn FnOnce() -> ()>) {
191        self.0.borrow_mut().finish_launching = Some(on_finish_launching);
192
193        unsafe {
194            let app: id = msg_send![APP_CLASS, sharedApplication];
195            let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
196            app.setDelegate_(app_delegate);
197
198            let self_ptr = self as *const Self as *const c_void;
199            (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
200            (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
201
202            let pool = NSAutoreleasePool::new(nil);
203            app.run();
204            pool.drain();
205
206            (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
207            (*app.delegate()).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
208        }
209    }
210
211    fn on_menu_command(&self, callback: Box<dyn FnMut(&str, Option<&dyn Any>)>) {
212        self.0.borrow_mut().menu_command = Some(callback);
213    }
214
215    fn set_menus(&self, menus: Vec<Menu>) {
216        unsafe {
217            let app: id = msg_send![APP_CLASS, sharedApplication];
218            app.setMainMenu_(self.create_menu_bar(menus));
219        }
220    }
221
222    fn prompt_for_paths(
223        &self,
224        options: platform::PathPromptOptions,
225        done_fn: Box<dyn FnOnce(Option<Vec<std::path::PathBuf>>)>,
226    ) {
227        unsafe {
228            let panel = NSOpenPanel::openPanel(nil);
229            panel.setCanChooseDirectories_(options.directories.to_objc());
230            panel.setCanChooseFiles_(options.files.to_objc());
231            panel.setAllowsMultipleSelection_(options.multiple.to_objc());
232            panel.setResolvesAliases_(false.to_objc());
233            let done_fn = Cell::new(Some(done_fn));
234            let block = ConcreteBlock::new(move |response: NSModalResponse| {
235                let result = if response == NSModalResponse::NSModalResponseOk {
236                    let mut result = Vec::new();
237                    let urls = panel.URLs();
238                    for i in 0..urls.count() {
239                        let url = urls.objectAtIndex(i);
240                        let string = url.absoluteString();
241                        let string = std::ffi::CStr::from_ptr(string.UTF8String())
242                            .to_string_lossy()
243                            .to_string();
244                        if let Some(path) = string.strip_prefix("file://") {
245                            result.push(PathBuf::from(path));
246                        }
247                    }
248                    Some(result)
249                } else {
250                    None
251                };
252
253                if let Some(done_fn) = done_fn.take() {
254                    (done_fn)(result);
255                }
256            });
257            let block = block.copy();
258            let _: () = msg_send![panel, beginWithCompletionHandler: block];
259        }
260    }
261
262    fn prompt_for_new_path(
263        &self,
264        directory: &Path,
265        done_fn: Box<dyn FnOnce(Option<std::path::PathBuf>)>,
266    ) {
267        unsafe {
268            let panel = NSSavePanel::savePanel(nil);
269            let path = ns_string(directory.to_string_lossy().as_ref());
270            let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
271            panel.setDirectoryURL(url);
272
273            let done_fn = Cell::new(Some(done_fn));
274            let block = ConcreteBlock::new(move |response: NSModalResponse| {
275                let result = if response == NSModalResponse::NSModalResponseOk {
276                    let url = panel.URL();
277                    let string = url.absoluteString();
278                    let string = std::ffi::CStr::from_ptr(string.UTF8String())
279                        .to_string_lossy()
280                        .to_string();
281                    if let Some(path) = string.strip_prefix("file://") {
282                        Some(PathBuf::from(path))
283                    } else {
284                        None
285                    }
286                } else {
287                    None
288                };
289
290                if let Some(done_fn) = done_fn.take() {
291                    (done_fn)(result);
292                }
293            });
294            let block = block.copy();
295            let _: () = msg_send![panel, beginWithCompletionHandler: block];
296        }
297    }
298}
299
300pub struct MacPlatform {
301    dispatcher: Arc<Dispatcher>,
302    fonts: Arc<FontSystem>,
303    pasteboard: id,
304    text_hash_pasteboard_type: id,
305    metadata_pasteboard_type: id,
306}
307
308impl MacPlatform {
309    pub fn new() -> Self {
310        Self {
311            dispatcher: Arc::new(Dispatcher),
312            fonts: Arc::new(FontSystem::new()),
313            pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
314            text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
315            metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
316        }
317    }
318
319    unsafe fn read_from_pasteboard(&self, kind: id) -> Option<&[u8]> {
320        let data = self.pasteboard.dataForType(kind);
321        if data == nil {
322            None
323        } else {
324            Some(slice::from_raw_parts(
325                data.bytes() as *mut u8,
326                data.length() as usize,
327            ))
328        }
329    }
330}
331
332unsafe impl Send for MacPlatform {}
333unsafe impl Sync for MacPlatform {}
334
335impl platform::Platform for MacPlatform {
336    fn dispatcher(&self) -> Arc<dyn platform::Dispatcher> {
337        self.dispatcher.clone()
338    }
339
340    fn activate(&self, ignoring_other_apps: bool) {
341        unsafe {
342            let app = NSApplication::sharedApplication(nil);
343            app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
344        }
345    }
346
347    fn open_window(
348        &self,
349        id: usize,
350        options: platform::WindowOptions,
351        executor: Rc<executor::Foreground>,
352    ) -> Box<dyn platform::Window> {
353        Box::new(Window::open(id, options, executor, self.fonts()))
354    }
355
356    fn key_window_id(&self) -> Option<usize> {
357        Window::key_window_id()
358    }
359
360    fn fonts(&self) -> Arc<dyn platform::FontSystem> {
361        self.fonts.clone()
362    }
363
364    fn quit(&self) {
365        // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
366        // synchronously before this method terminates. If we call `Platform::quit` while holding a
367        // borrow of the app state (which most of the time we will do), we will end up
368        // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
369        // this, we make quitting the application asynchronous so that we aren't holding borrows to
370        // the app state on the stack when we actually terminate the app.
371
372        use super::dispatcher::{dispatch_async_f, dispatch_get_main_queue};
373
374        unsafe {
375            dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
376        }
377
378        unsafe extern "C" fn quit(_: *mut c_void) {
379            let app = NSApplication::sharedApplication(nil);
380            let _: () = msg_send![app, terminate: nil];
381        }
382    }
383
384    fn write_to_clipboard(&self, item: ClipboardItem) {
385        unsafe {
386            self.pasteboard.clearContents();
387
388            let text_bytes = NSData::dataWithBytes_length_(
389                nil,
390                item.text.as_ptr() as *const c_void,
391                item.text.len() as u64,
392            );
393            self.pasteboard
394                .setData_forType(text_bytes, NSPasteboardTypeString);
395
396            if let Some(metadata) = item.metadata.as_ref() {
397                let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
398                let hash_bytes = NSData::dataWithBytes_length_(
399                    nil,
400                    hash_bytes.as_ptr() as *const c_void,
401                    hash_bytes.len() as u64,
402                );
403                self.pasteboard
404                    .setData_forType(hash_bytes, self.text_hash_pasteboard_type);
405
406                let metadata_bytes = NSData::dataWithBytes_length_(
407                    nil,
408                    metadata.as_ptr() as *const c_void,
409                    metadata.len() as u64,
410                );
411                self.pasteboard
412                    .setData_forType(metadata_bytes, self.metadata_pasteboard_type);
413            }
414        }
415    }
416
417    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
418        unsafe {
419            if let Some(text_bytes) = self.read_from_pasteboard(NSPasteboardTypeString) {
420                let text = String::from_utf8_lossy(&text_bytes).to_string();
421                let hash_bytes = self
422                    .read_from_pasteboard(self.text_hash_pasteboard_type)
423                    .and_then(|bytes| bytes.try_into().ok())
424                    .map(u64::from_be_bytes);
425                let metadata_bytes = self
426                    .read_from_pasteboard(self.metadata_pasteboard_type)
427                    .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
428
429                if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
430                    if hash == ClipboardItem::text_hash(&text) {
431                        Some(ClipboardItem {
432                            text,
433                            metadata: Some(metadata),
434                        })
435                    } else {
436                        Some(ClipboardItem {
437                            text,
438                            metadata: None,
439                        })
440                    }
441                } else {
442                    Some(ClipboardItem {
443                        text,
444                        metadata: None,
445                    })
446                }
447            } else {
448                None
449            }
450        }
451    }
452}
453
454unsafe fn get_main_thread_platform(object: &mut Object) -> &MacMainThreadPlatform {
455    let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
456    assert!(!platform_ptr.is_null());
457    &*(platform_ptr as *const MacMainThreadPlatform)
458}
459
460extern "C" fn send_event(this: &mut Object, _sel: Sel, native_event: id) {
461    unsafe {
462        if let Some(event) = Event::from_native(native_event, None) {
463            let platform = get_main_thread_platform(this);
464            if let Some(callback) = platform.0.borrow_mut().event.as_mut() {
465                if callback(event) {
466                    return;
467                }
468            }
469        }
470
471        msg_send![super(this, class!(NSApplication)), sendEvent: native_event]
472    }
473}
474
475extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
476    unsafe {
477        let app: id = msg_send![APP_CLASS, sharedApplication];
478        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
479
480        let platform = get_main_thread_platform(this);
481        let callback = platform.0.borrow_mut().finish_launching.take();
482        if let Some(callback) = callback {
483            callback();
484        }
485    }
486}
487
488extern "C" fn did_become_active(this: &mut Object, _: Sel, _: id) {
489    let platform = unsafe { get_main_thread_platform(this) };
490    if let Some(callback) = platform.0.borrow_mut().become_active.as_mut() {
491        callback();
492    }
493}
494
495extern "C" fn did_resign_active(this: &mut Object, _: Sel, _: id) {
496    let platform = unsafe { get_main_thread_platform(this) };
497    if let Some(callback) = platform.0.borrow_mut().resign_active.as_mut() {
498        callback();
499    }
500}
501
502extern "C" fn open_files(this: &mut Object, _: Sel, _: id, paths: id) {
503    let paths = unsafe {
504        (0..paths.count())
505            .into_iter()
506            .filter_map(|i| {
507                let path = paths.objectAtIndex(i);
508                match CStr::from_ptr(path.UTF8String() as *mut c_char).to_str() {
509                    Ok(string) => Some(PathBuf::from(string)),
510                    Err(err) => {
511                        log::error!("error converting path to string: {}", err);
512                        None
513                    }
514                }
515            })
516            .collect::<Vec<_>>()
517    };
518    let platform = unsafe { get_main_thread_platform(this) };
519    if let Some(callback) = platform.0.borrow_mut().open_files.as_mut() {
520        callback(paths);
521    }
522}
523
524extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
525    unsafe {
526        let platform = get_main_thread_platform(this);
527        if let Some(callback) = platform.0.borrow_mut().menu_command.as_mut() {
528            let tag: NSInteger = msg_send![item, tag];
529            let index = tag as usize;
530            if let Some((action, arg)) = platform.0.borrow_mut().menu_actions.get(index) {
531                callback(action, arg.as_ref().map(Box::as_ref));
532            }
533        }
534    }
535}
536
537unsafe fn ns_string(string: &str) -> id {
538    NSString::alloc(nil).init_str(string).autorelease()
539}
540
541#[cfg(test)]
542mod tests {
543    use crate::platform::Platform;
544
545    use super::*;
546
547    #[test]
548    fn test_clipboard() {
549        let platform = build_platform();
550        assert_eq!(platform.read_from_clipboard(), None);
551
552        let item = ClipboardItem::new("1".to_string());
553        platform.write_to_clipboard(item.clone());
554        assert_eq!(platform.read_from_clipboard(), Some(item));
555
556        let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
557        platform.write_to_clipboard(item.clone());
558        assert_eq!(platform.read_from_clipboard(), Some(item));
559
560        let text_from_other_app = "text from other app";
561        unsafe {
562            let bytes = NSData::dataWithBytes_length_(
563                nil,
564                text_from_other_app.as_ptr() as *const c_void,
565                text_from_other_app.len() as u64,
566            );
567            platform
568                .pasteboard
569                .setData_forType(bytes, NSPasteboardTypeString);
570        }
571        assert_eq!(
572            platform.read_from_clipboard(),
573            Some(ClipboardItem::new(text_from_other_app.to_string()))
574        );
575    }
576
577    fn build_platform() -> MacPlatform {
578        let mut platform = MacPlatform::new();
579        platform.pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
580        platform
581    }
582}