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