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 string = url.absoluteString();
287                        let string = std::ffi::CStr::from_ptr(string.UTF8String())
288                            .to_string_lossy()
289                            .to_string();
290                        if let Some(path) = string.strip_prefix("file://") {
291                            result.push(PathBuf::from(path));
292                        }
293                    }
294                    Some(result)
295                } else {
296                    None
297                };
298
299                if let Some(done_fn) = done_fn.take() {
300                    (done_fn)(result);
301                }
302            });
303            let block = block.copy();
304            let _: () = msg_send![panel, beginWithCompletionHandler: block];
305        }
306    }
307
308    fn prompt_for_new_path(
309        &self,
310        directory: &Path,
311        done_fn: Box<dyn FnOnce(Option<std::path::PathBuf>)>,
312    ) {
313        unsafe {
314            let panel = NSSavePanel::savePanel(nil);
315            let path = ns_string(directory.to_string_lossy().as_ref());
316            let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
317            panel.setDirectoryURL(url);
318
319            let done_fn = Cell::new(Some(done_fn));
320            let block = ConcreteBlock::new(move |response: NSModalResponse| {
321                let result = if response == NSModalResponse::NSModalResponseOk {
322                    let url = panel.URL();
323                    let string = url.absoluteString();
324                    let string = std::ffi::CStr::from_ptr(string.UTF8String())
325                        .to_string_lossy()
326                        .to_string();
327                    if let Some(path) = string.strip_prefix("file://") {
328                        Some(PathBuf::from(path))
329                    } else {
330                        None
331                    }
332                } else {
333                    None
334                };
335
336                if let Some(done_fn) = done_fn.take() {
337                    (done_fn)(result);
338                }
339            });
340            let block = block.copy();
341            let _: () = msg_send![panel, beginWithCompletionHandler: block];
342        }
343    }
344
345    fn fonts(&self) -> Arc<dyn platform::FontSystem> {
346        self.fonts.clone()
347    }
348
349    fn quit(&self) {
350        // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
351        // synchronously before this method terminates. If we call `Platform::quit` while holding a
352        // borrow of the app state (which most of the time we will do), we will end up
353        // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
354        // this, we make quitting the application asynchronous so that we aren't holding borrows to
355        // the app state on the stack when we actually terminate the app.
356
357        use super::dispatcher::{dispatch_async_f, dispatch_get_main_queue};
358
359        unsafe {
360            dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
361        }
362
363        unsafe extern "C" fn quit(_: *mut c_void) {
364            let app = NSApplication::sharedApplication(nil);
365            let _: () = msg_send![app, terminate: nil];
366        }
367    }
368
369    fn write_to_clipboard(&self, item: ClipboardItem) {
370        unsafe {
371            self.pasteboard.clearContents();
372
373            let text_bytes = NSData::dataWithBytes_length_(
374                nil,
375                item.text.as_ptr() as *const c_void,
376                item.text.len() as u64,
377            );
378            self.pasteboard
379                .setData_forType(text_bytes, NSPasteboardTypeString);
380
381            if let Some(metadata) = item.metadata.as_ref() {
382                let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
383                let hash_bytes = NSData::dataWithBytes_length_(
384                    nil,
385                    hash_bytes.as_ptr() as *const c_void,
386                    hash_bytes.len() as u64,
387                );
388                self.pasteboard
389                    .setData_forType(hash_bytes, self.text_hash_pasteboard_type);
390
391                let metadata_bytes = NSData::dataWithBytes_length_(
392                    nil,
393                    metadata.as_ptr() as *const c_void,
394                    metadata.len() as u64,
395                );
396                self.pasteboard
397                    .setData_forType(metadata_bytes, self.metadata_pasteboard_type);
398            }
399        }
400    }
401
402    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
403        unsafe {
404            if let Some(text_bytes) = self.read_from_pasteboard(NSPasteboardTypeString) {
405                let text = String::from_utf8_lossy(&text_bytes).to_string();
406                let hash_bytes = self
407                    .read_from_pasteboard(self.text_hash_pasteboard_type)
408                    .and_then(|bytes| bytes.try_into().ok())
409                    .map(u64::from_be_bytes);
410                let metadata_bytes = self
411                    .read_from_pasteboard(self.metadata_pasteboard_type)
412                    .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
413
414                if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
415                    if hash == ClipboardItem::text_hash(&text) {
416                        Some(ClipboardItem {
417                            text,
418                            metadata: Some(metadata),
419                        })
420                    } else {
421                        Some(ClipboardItem {
422                            text,
423                            metadata: None,
424                        })
425                    }
426                } else {
427                    Some(ClipboardItem {
428                        text,
429                        metadata: None,
430                    })
431                }
432            } else {
433                None
434            }
435        }
436    }
437
438    fn set_menus(&self, menus: Vec<Menu>) {
439        unsafe {
440            let app: id = msg_send![APP_CLASS, sharedApplication];
441            app.setMainMenu_(self.create_menu_bar(menus));
442        }
443    }
444}
445
446unsafe fn get_platform(object: &mut Object) -> &MacPlatform {
447    let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
448    assert!(!platform_ptr.is_null());
449    &*(platform_ptr as *const MacPlatform)
450}
451
452extern "C" fn send_event(this: &mut Object, _sel: Sel, native_event: id) {
453    unsafe {
454        if let Some(event) = Event::from_native(native_event, None) {
455            let platform = get_platform(this);
456            if let Some(callback) = platform.callbacks.borrow_mut().event.as_mut() {
457                if callback(event) {
458                    return;
459                }
460            }
461        }
462
463        msg_send![super(this, class!(NSApplication)), sendEvent: native_event]
464    }
465}
466
467extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
468    unsafe {
469        let app: id = msg_send![APP_CLASS, sharedApplication];
470        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
471
472        let platform = get_platform(this);
473        if let Some(callback) = platform.callbacks.borrow_mut().finish_launching.take() {
474            callback();
475        }
476    }
477}
478
479extern "C" fn did_become_active(this: &mut Object, _: Sel, _: id) {
480    let platform = unsafe { get_platform(this) };
481    if let Some(callback) = platform.callbacks.borrow_mut().become_active.as_mut() {
482        callback();
483    }
484}
485
486extern "C" fn did_resign_active(this: &mut Object, _: Sel, _: id) {
487    let platform = unsafe { get_platform(this) };
488    if let Some(callback) = platform.callbacks.borrow_mut().resign_active.as_mut() {
489        callback();
490    }
491}
492
493extern "C" fn open_files(this: &mut Object, _: Sel, _: id, paths: id) {
494    let paths = unsafe {
495        (0..paths.count())
496            .into_iter()
497            .filter_map(|i| {
498                let path = paths.objectAtIndex(i);
499                match CStr::from_ptr(path.UTF8String() as *mut c_char).to_str() {
500                    Ok(string) => Some(PathBuf::from(string)),
501                    Err(err) => {
502                        log::error!("error converting path to string: {}", err);
503                        None
504                    }
505                }
506            })
507            .collect::<Vec<_>>()
508    };
509    let platform = unsafe { get_platform(this) };
510    if let Some(callback) = platform.callbacks.borrow_mut().open_files.as_mut() {
511        callback(paths);
512    }
513}
514
515extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
516    unsafe {
517        let platform = get_platform(this);
518        if let Some(callback) = platform.callbacks.borrow_mut().menu_command.as_mut() {
519            let tag: NSInteger = msg_send![item, tag];
520            let index = tag as usize;
521            if let Some((action, arg)) = platform.menu_item_actions.borrow().get(index) {
522                callback(action, arg.as_ref().map(Box::as_ref));
523            }
524        }
525    }
526}
527
528unsafe fn ns_string(string: &str) -> id {
529    NSString::alloc(nil).init_str(string).autorelease()
530}
531
532#[cfg(test)]
533mod tests {
534    use crate::platform::Platform;
535
536    use super::*;
537
538    #[test]
539    fn test_clipboard() {
540        let platform = build_platform();
541        assert_eq!(platform.read_from_clipboard(), None);
542
543        let item = ClipboardItem::new("1".to_string());
544        platform.write_to_clipboard(item.clone());
545        assert_eq!(platform.read_from_clipboard(), Some(item));
546
547        let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
548        platform.write_to_clipboard(item.clone());
549        assert_eq!(platform.read_from_clipboard(), Some(item));
550
551        let text_from_other_app = "text from other app";
552        unsafe {
553            let bytes = NSData::dataWithBytes_length_(
554                nil,
555                text_from_other_app.as_ptr() as *const c_void,
556                text_from_other_app.len() as u64,
557            );
558            platform
559                .pasteboard
560                .setData_forType(bytes, NSPasteboardTypeString);
561        }
562        assert_eq!(
563            platform.read_from_clipboard(),
564            Some(ClipboardItem::new(text_from_other_app.to_string()))
565        );
566    }
567
568    fn build_platform() -> MacPlatform {
569        let mut platform = MacPlatform::new();
570        platform.pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
571        platform
572    }
573}