platform.rs

   1use super::{events::key_to_native, BoolExt};
   2use crate::{
   3    Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, ForegroundExecutor,
   4    Keymap, MacDispatcher, MacDisplay, MacTextSystem, MacWindow, Menu, MenuItem, PathPromptOptions,
   5    Platform, PlatformDisplay, PlatformTextSystem, PlatformWindow, Result, SemanticVersion, Task,
   6    WindowAppearance, WindowParams,
   7};
   8use anyhow::{anyhow, bail};
   9use block::ConcreteBlock;
  10use cocoa::{
  11    appkit::{
  12        NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
  13        NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
  14        NSPasteboardTypeString, NSSavePanel, NSWindow,
  15    },
  16    base::{id, nil, selector, BOOL, YES},
  17    foundation::{
  18        NSArray, NSAutoreleasePool, NSBundle, NSData, NSInteger, NSProcessInfo, NSString,
  19        NSUInteger, NSURL,
  20    },
  21};
  22use core_foundation::{
  23    base::{CFRelease, CFType, CFTypeRef, OSStatus, TCFType as _},
  24    boolean::CFBoolean,
  25    data::CFData,
  26    dictionary::{CFDictionary, CFDictionaryRef, CFMutableDictionary},
  27    string::{CFString, CFStringRef},
  28};
  29use ctor::ctor;
  30use futures::channel::oneshot;
  31use objc::{
  32    class,
  33    declare::ClassDecl,
  34    msg_send,
  35    runtime::{Class, Object, Sel},
  36    sel, sel_impl,
  37};
  38use parking_lot::Mutex;
  39use ptr::null_mut;
  40use std::{
  41    cell::Cell,
  42    convert::TryInto,
  43    ffi::{c_void, CStr, OsStr},
  44    os::{raw::c_char, unix::ffi::OsStrExt},
  45    path::{Path, PathBuf},
  46    process::Command,
  47    ptr,
  48    rc::Rc,
  49    slice, str,
  50    sync::Arc,
  51};
  52use time::UtcOffset;
  53
  54use super::renderer;
  55
  56#[allow(non_upper_case_globals)]
  57const NSUTF8StringEncoding: NSUInteger = 4;
  58
  59const MAC_PLATFORM_IVAR: &str = "platform";
  60static mut APP_CLASS: *const Class = ptr::null();
  61static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
  62
  63#[ctor]
  64unsafe fn build_classes() {
  65    APP_CLASS = {
  66        let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
  67        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  68        decl.register()
  69    };
  70
  71    APP_DELEGATE_CLASS = {
  72        let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
  73        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  74        decl.add_method(
  75            sel!(applicationDidFinishLaunching:),
  76            did_finish_launching as extern "C" fn(&mut Object, Sel, id),
  77        );
  78        decl.add_method(
  79            sel!(applicationShouldHandleReopen:hasVisibleWindows:),
  80            should_handle_reopen as extern "C" fn(&mut Object, Sel, id, bool),
  81        );
  82        decl.add_method(
  83            sel!(applicationWillTerminate:),
  84            will_terminate as extern "C" fn(&mut Object, Sel, id),
  85        );
  86        decl.add_method(
  87            sel!(handleGPUIMenuItem:),
  88            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
  89        );
  90        // Add menu item handlers so that OS save panels have the correct key commands
  91        decl.add_method(
  92            sel!(cut:),
  93            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
  94        );
  95        decl.add_method(
  96            sel!(copy:),
  97            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
  98        );
  99        decl.add_method(
 100            sel!(paste:),
 101            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 102        );
 103        decl.add_method(
 104            sel!(selectAll:),
 105            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 106        );
 107        decl.add_method(
 108            sel!(undo:),
 109            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 110        );
 111        decl.add_method(
 112            sel!(redo:),
 113            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 114        );
 115        decl.add_method(
 116            sel!(validateMenuItem:),
 117            validate_menu_item as extern "C" fn(&mut Object, Sel, id) -> bool,
 118        );
 119        decl.add_method(
 120            sel!(menuWillOpen:),
 121            menu_will_open as extern "C" fn(&mut Object, Sel, id),
 122        );
 123        decl.add_method(
 124            sel!(applicationDockMenu:),
 125            handle_dock_menu as extern "C" fn(&mut Object, Sel, id) -> id,
 126        );
 127        decl.add_method(
 128            sel!(application:openURLs:),
 129            open_urls as extern "C" fn(&mut Object, Sel, id, id),
 130        );
 131
 132        decl.register()
 133    }
 134}
 135
 136pub(crate) struct MacPlatform(Mutex<MacPlatformState>);
 137
 138pub(crate) struct MacPlatformState {
 139    background_executor: BackgroundExecutor,
 140    foreground_executor: ForegroundExecutor,
 141    text_system: Arc<MacTextSystem>,
 142    renderer_context: renderer::Context,
 143    pasteboard: id,
 144    text_hash_pasteboard_type: id,
 145    metadata_pasteboard_type: id,
 146    reopen: Option<Box<dyn FnMut()>>,
 147    quit: Option<Box<dyn FnMut()>>,
 148    menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
 149    validate_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 150    will_open_menu: Option<Box<dyn FnMut()>>,
 151    menu_actions: Vec<Box<dyn Action>>,
 152    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 153    finish_launching: Option<Box<dyn FnOnce()>>,
 154    dock_menu: Option<id>,
 155}
 156
 157impl Default for MacPlatform {
 158    fn default() -> Self {
 159        Self::new()
 160    }
 161}
 162
 163impl MacPlatform {
 164    pub(crate) fn new() -> Self {
 165        let dispatcher = Arc::new(MacDispatcher::new());
 166        Self(Mutex::new(MacPlatformState {
 167            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 168            foreground_executor: ForegroundExecutor::new(dispatcher),
 169            text_system: Arc::new(MacTextSystem::new()),
 170            renderer_context: renderer::Context::default(),
 171            pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
 172            text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
 173            metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
 174            reopen: None,
 175            quit: None,
 176            menu_command: None,
 177            validate_menu_command: None,
 178            will_open_menu: None,
 179            menu_actions: Default::default(),
 180            open_urls: None,
 181            finish_launching: None,
 182            dock_menu: None,
 183        }))
 184    }
 185
 186    unsafe fn read_from_pasteboard(&self, pasteboard: *mut Object, kind: id) -> Option<&[u8]> {
 187        let data = pasteboard.dataForType(kind);
 188        if data == nil {
 189            None
 190        } else {
 191            Some(slice::from_raw_parts(
 192                data.bytes() as *mut u8,
 193                data.length() as usize,
 194            ))
 195        }
 196    }
 197
 198    unsafe fn create_menu_bar(
 199        &self,
 200        menus: Vec<Menu>,
 201        delegate: id,
 202        actions: &mut Vec<Box<dyn Action>>,
 203        keymap: &Keymap,
 204    ) -> id {
 205        let application_menu = NSMenu::new(nil).autorelease();
 206        application_menu.setDelegate_(delegate);
 207
 208        for menu_config in menus {
 209            let menu = NSMenu::new(nil).autorelease();
 210            menu.setTitle_(ns_string(menu_config.name));
 211            menu.setDelegate_(delegate);
 212
 213            for item_config in menu_config.items {
 214                menu.addItem_(Self::create_menu_item(
 215                    item_config,
 216                    delegate,
 217                    actions,
 218                    keymap,
 219                ));
 220            }
 221
 222            let menu_item = NSMenuItem::new(nil).autorelease();
 223            menu_item.setSubmenu_(menu);
 224            application_menu.addItem_(menu_item);
 225
 226            if menu_config.name == "Window" {
 227                let app: id = msg_send![APP_CLASS, sharedApplication];
 228                app.setWindowsMenu_(menu);
 229            }
 230        }
 231
 232        application_menu
 233    }
 234
 235    unsafe fn create_dock_menu(
 236        &self,
 237        menu_items: Vec<MenuItem>,
 238        delegate: id,
 239        actions: &mut Vec<Box<dyn Action>>,
 240        keymap: &Keymap,
 241    ) -> id {
 242        let dock_menu = NSMenu::new(nil);
 243        dock_menu.setDelegate_(delegate);
 244        for item_config in menu_items {
 245            dock_menu.addItem_(Self::create_menu_item(
 246                item_config,
 247                delegate,
 248                actions,
 249                keymap,
 250            ));
 251        }
 252
 253        dock_menu
 254    }
 255
 256    unsafe fn create_menu_item(
 257        item: MenuItem,
 258        delegate: id,
 259        actions: &mut Vec<Box<dyn Action>>,
 260        keymap: &Keymap,
 261    ) -> id {
 262        match item {
 263            MenuItem::Separator => NSMenuItem::separatorItem(nil),
 264            MenuItem::Action {
 265                name,
 266                action,
 267                os_action,
 268            } => {
 269                let keystrokes = keymap
 270                    .bindings_for_action(action.as_ref())
 271                    .next()
 272                    .map(|binding| binding.keystrokes());
 273
 274                let selector = match os_action {
 275                    Some(crate::OsAction::Cut) => selector("cut:"),
 276                    Some(crate::OsAction::Copy) => selector("copy:"),
 277                    Some(crate::OsAction::Paste) => selector("paste:"),
 278                    Some(crate::OsAction::SelectAll) => selector("selectAll:"),
 279                    Some(crate::OsAction::Undo) => selector("undo:"),
 280                    Some(crate::OsAction::Redo) => selector("redo:"),
 281                    None => selector("handleGPUIMenuItem:"),
 282                };
 283
 284                let item;
 285                if let Some(keystrokes) = keystrokes {
 286                    if keystrokes.len() == 1 {
 287                        let keystroke = &keystrokes[0];
 288                        let mut mask = NSEventModifierFlags::empty();
 289                        for (modifier, flag) in &[
 290                            (
 291                                keystroke.modifiers.platform,
 292                                NSEventModifierFlags::NSCommandKeyMask,
 293                            ),
 294                            (
 295                                keystroke.modifiers.control,
 296                                NSEventModifierFlags::NSControlKeyMask,
 297                            ),
 298                            (
 299                                keystroke.modifiers.alt,
 300                                NSEventModifierFlags::NSAlternateKeyMask,
 301                            ),
 302                            (
 303                                keystroke.modifiers.shift,
 304                                NSEventModifierFlags::NSShiftKeyMask,
 305                            ),
 306                        ] {
 307                            if *modifier {
 308                                mask |= *flag;
 309                            }
 310                        }
 311
 312                        item = NSMenuItem::alloc(nil)
 313                            .initWithTitle_action_keyEquivalent_(
 314                                ns_string(name),
 315                                selector,
 316                                ns_string(key_to_native(&keystroke.key).as_ref()),
 317                            )
 318                            .autorelease();
 319                        item.setKeyEquivalentModifierMask_(mask);
 320                    }
 321                    // For multi-keystroke bindings, render the keystroke as part of the title.
 322                    else {
 323                        use std::fmt::Write;
 324
 325                        let mut name = format!("{name} [");
 326                        for (i, keystroke) in keystrokes.iter().enumerate() {
 327                            if i > 0 {
 328                                name.push(' ');
 329                            }
 330                            write!(&mut name, "{}", keystroke).unwrap();
 331                        }
 332                        name.push(']');
 333
 334                        item = NSMenuItem::alloc(nil)
 335                            .initWithTitle_action_keyEquivalent_(
 336                                ns_string(&name),
 337                                selector,
 338                                ns_string(""),
 339                            )
 340                            .autorelease();
 341                    }
 342                } else {
 343                    item = NSMenuItem::alloc(nil)
 344                        .initWithTitle_action_keyEquivalent_(
 345                            ns_string(name),
 346                            selector,
 347                            ns_string(""),
 348                        )
 349                        .autorelease();
 350                }
 351
 352                let tag = actions.len() as NSInteger;
 353                let _: () = msg_send![item, setTag: tag];
 354                actions.push(action);
 355                item
 356            }
 357            MenuItem::Submenu(Menu { name, items }) => {
 358                let item = NSMenuItem::new(nil).autorelease();
 359                let submenu = NSMenu::new(nil).autorelease();
 360                submenu.setDelegate_(delegate);
 361                for item in items {
 362                    submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
 363                }
 364                item.setSubmenu_(submenu);
 365                item.setTitle_(ns_string(name));
 366                item
 367            }
 368        }
 369    }
 370}
 371
 372impl Platform for MacPlatform {
 373    fn background_executor(&self) -> BackgroundExecutor {
 374        self.0.lock().background_executor.clone()
 375    }
 376
 377    fn foreground_executor(&self) -> crate::ForegroundExecutor {
 378        self.0.lock().foreground_executor.clone()
 379    }
 380
 381    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
 382        self.0.lock().text_system.clone()
 383    }
 384
 385    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
 386        self.0.lock().finish_launching = Some(on_finish_launching);
 387
 388        unsafe {
 389            let app: id = msg_send![APP_CLASS, sharedApplication];
 390            let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
 391            app.setDelegate_(app_delegate);
 392
 393            let self_ptr = self as *const Self as *const c_void;
 394            (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 395            (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 396
 397            let pool = NSAutoreleasePool::new(nil);
 398            app.run();
 399            pool.drain();
 400
 401            (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 402            (*app.delegate()).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 403        }
 404    }
 405
 406    fn quit(&self) {
 407        // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
 408        // synchronously before this method terminates. If we call `Platform::quit` while holding a
 409        // borrow of the app state (which most of the time we will do), we will end up
 410        // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
 411        // this, we make quitting the application asynchronous so that we aren't holding borrows to
 412        // the app state on the stack when we actually terminate the app.
 413
 414        use super::dispatcher::{dispatch_get_main_queue, dispatch_sys::dispatch_async_f};
 415
 416        unsafe {
 417            dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
 418        }
 419
 420        unsafe extern "C" fn quit(_: *mut c_void) {
 421            let app = NSApplication::sharedApplication(nil);
 422            let _: () = msg_send![app, terminate: nil];
 423        }
 424    }
 425
 426    fn restart(&self, _binary_path: Option<PathBuf>) {
 427        use std::os::unix::process::CommandExt as _;
 428
 429        let app_pid = std::process::id().to_string();
 430        let app_path = self
 431            .app_path()
 432            .ok()
 433            // When the app is not bundled, `app_path` returns the
 434            // directory containing the executable. Disregard this
 435            // and get the path to the executable itself.
 436            .and_then(|path| (path.extension()?.to_str()? == "app").then_some(path))
 437            .unwrap_or_else(|| std::env::current_exe().unwrap());
 438
 439        // Wait until this process has exited and then re-open this path.
 440        let script = r#"
 441            while kill -0 $0 2> /dev/null; do
 442                sleep 0.1
 443            done
 444            open "$1"
 445        "#;
 446
 447        let restart_process = Command::new("/bin/bash")
 448            .arg("-c")
 449            .arg(script)
 450            .arg(app_pid)
 451            .arg(app_path)
 452            .process_group(0)
 453            .spawn();
 454
 455        match restart_process {
 456            Ok(_) => self.quit(),
 457            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
 458        }
 459    }
 460
 461    fn activate(&self, ignoring_other_apps: bool) {
 462        unsafe {
 463            let app = NSApplication::sharedApplication(nil);
 464            app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
 465        }
 466    }
 467
 468    fn hide(&self) {
 469        unsafe {
 470            let app = NSApplication::sharedApplication(nil);
 471            let _: () = msg_send![app, hide: nil];
 472        }
 473    }
 474
 475    fn hide_other_apps(&self) {
 476        unsafe {
 477            let app = NSApplication::sharedApplication(nil);
 478            let _: () = msg_send![app, hideOtherApplications: nil];
 479        }
 480    }
 481
 482    fn unhide_other_apps(&self) {
 483        unsafe {
 484            let app = NSApplication::sharedApplication(nil);
 485            let _: () = msg_send![app, unhideAllApplications: nil];
 486        }
 487    }
 488
 489    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 490        Some(Rc::new(MacDisplay::primary()))
 491    }
 492
 493    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 494        MacDisplay::all()
 495            .map(|screen| Rc::new(screen) as Rc<_>)
 496            .collect()
 497    }
 498
 499    fn active_window(&self) -> Option<AnyWindowHandle> {
 500        MacWindow::active_window()
 501    }
 502
 503    fn open_window(
 504        &self,
 505        handle: AnyWindowHandle,
 506        options: WindowParams,
 507    ) -> Box<dyn PlatformWindow> {
 508        // Clippy thinks that this evaluates to `()`, for some reason.
 509        #[allow(clippy::unit_arg, clippy::clone_on_copy)]
 510        let renderer_context = self.0.lock().renderer_context.clone();
 511        Box::new(MacWindow::open(
 512            handle,
 513            options,
 514            self.foreground_executor(),
 515            renderer_context,
 516        ))
 517    }
 518
 519    fn window_appearance(&self) -> WindowAppearance {
 520        unsafe {
 521            let app = NSApplication::sharedApplication(nil);
 522            let appearance: id = msg_send![app, effectiveAppearance];
 523            WindowAppearance::from_native(appearance)
 524        }
 525    }
 526
 527    fn open_url(&self, url: &str) {
 528        unsafe {
 529            let url = NSURL::alloc(nil)
 530                .initWithString_(ns_string(url))
 531                .autorelease();
 532            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 533            msg_send![workspace, openURL: url]
 534        }
 535    }
 536
 537    fn register_url_scheme(&self, scheme: &str) -> Task<anyhow::Result<()>> {
 538        // API only available post Monterey
 539        // https://developer.apple.com/documentation/appkit/nsworkspace/3753004-setdefaultapplicationaturl
 540        let (done_tx, done_rx) = oneshot::channel();
 541        if self.os_version().ok() < Some(SemanticVersion::new(12, 0, 0)) {
 542            return Task::ready(Err(anyhow!(
 543                "macOS 12.0 or later is required to register URL schemes"
 544            )));
 545        }
 546
 547        let bundle_id = unsafe {
 548            let bundle: id = msg_send![class!(NSBundle), mainBundle];
 549            let bundle_id: id = msg_send![bundle, bundleIdentifier];
 550            if bundle_id == nil {
 551                return Task::ready(Err(anyhow!("Can only register URL scheme in bundled apps")));
 552            }
 553            bundle_id
 554        };
 555
 556        unsafe {
 557            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 558            let scheme: id = ns_string(scheme);
 559            let app: id = msg_send![workspace, URLForApplicationWithBundleIdentifier: bundle_id];
 560            if app == nil {
 561                return Task::ready(Err(anyhow!(
 562                    "Cannot register URL scheme until app is installed"
 563                )));
 564            }
 565            let done_tx = Cell::new(Some(done_tx));
 566            let block = ConcreteBlock::new(move |error: id| {
 567                let result = if error == nil {
 568                    Ok(())
 569                } else {
 570                    let msg: id = msg_send![error, localizedDescription];
 571                    Err(anyhow!("Failed to register: {:?}", msg))
 572                };
 573
 574                if let Some(done_tx) = done_tx.take() {
 575                    let _ = done_tx.send(result);
 576                }
 577            });
 578            let block = block.copy();
 579            let _: () = msg_send![workspace, setDefaultApplicationAtURL: app toOpenURLsWithScheme: scheme completionHandler: block];
 580        }
 581
 582        self.background_executor()
 583            .spawn(async { crate::Flatten::flatten(done_rx.await.map_err(|e| anyhow!(e))) })
 584    }
 585
 586    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
 587        self.0.lock().open_urls = Some(callback);
 588    }
 589
 590    fn prompt_for_paths(
 591        &self,
 592        options: PathPromptOptions,
 593    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 594        let (done_tx, done_rx) = oneshot::channel();
 595        self.foreground_executor()
 596            .spawn(async move {
 597                unsafe {
 598                    let panel = NSOpenPanel::openPanel(nil);
 599                    panel.setCanChooseDirectories_(options.directories.to_objc());
 600                    panel.setCanChooseFiles_(options.files.to_objc());
 601                    panel.setAllowsMultipleSelection_(options.multiple.to_objc());
 602                    panel.setResolvesAliases_(false.to_objc());
 603                    let done_tx = Cell::new(Some(done_tx));
 604                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 605                        let result = if response == NSModalResponse::NSModalResponseOk {
 606                            let mut result = Vec::new();
 607                            let urls = panel.URLs();
 608                            for i in 0..urls.count() {
 609                                let url = urls.objectAtIndex(i);
 610                                if url.isFileURL() == YES {
 611                                    if let Ok(path) = ns_url_to_path(url) {
 612                                        result.push(path)
 613                                    }
 614                                }
 615                            }
 616                            Some(result)
 617                        } else {
 618                            None
 619                        };
 620
 621                        if let Some(done_tx) = done_tx.take() {
 622                            let _ = done_tx.send(result);
 623                        }
 624                    });
 625                    let block = block.copy();
 626                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 627                }
 628            })
 629            .detach();
 630        done_rx
 631    }
 632
 633    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
 634        let directory = directory.to_owned();
 635        let (done_tx, done_rx) = oneshot::channel();
 636        self.foreground_executor()
 637            .spawn(async move {
 638                unsafe {
 639                    let panel = NSSavePanel::savePanel(nil);
 640                    let path = ns_string(directory.to_string_lossy().as_ref());
 641                    let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
 642                    panel.setDirectoryURL(url);
 643
 644                    let done_tx = Cell::new(Some(done_tx));
 645                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 646                        let mut result = None;
 647                        if response == NSModalResponse::NSModalResponseOk {
 648                            let url = panel.URL();
 649                            if url.isFileURL() == YES {
 650                                result = ns_url_to_path(panel.URL()).ok()
 651                            }
 652                        }
 653
 654                        if let Some(done_tx) = done_tx.take() {
 655                            let _ = done_tx.send(result);
 656                        }
 657                    });
 658                    let block = block.copy();
 659                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 660                }
 661            })
 662            .detach();
 663
 664        done_rx
 665    }
 666
 667    fn reveal_path(&self, path: &Path) {
 668        unsafe {
 669            let path = path.to_path_buf();
 670            self.0
 671                .lock()
 672                .background_executor
 673                .spawn(async move {
 674                    let full_path = ns_string(path.to_str().unwrap_or(""));
 675                    let root_full_path = ns_string("");
 676                    let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 677                    let _: BOOL = msg_send![
 678                        workspace,
 679                        selectFile: full_path
 680                        inFileViewerRootedAtPath: root_full_path
 681                    ];
 682                })
 683                .detach();
 684        }
 685    }
 686
 687    fn on_quit(&self, callback: Box<dyn FnMut()>) {
 688        self.0.lock().quit = Some(callback);
 689    }
 690
 691    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 692        self.0.lock().reopen = Some(callback);
 693    }
 694
 695    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 696        self.0.lock().menu_command = Some(callback);
 697    }
 698
 699    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 700        self.0.lock().will_open_menu = Some(callback);
 701    }
 702
 703    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 704        self.0.lock().validate_menu_command = Some(callback);
 705    }
 706
 707    fn os_name(&self) -> &'static str {
 708        "macOS"
 709    }
 710
 711    fn os_version(&self) -> Result<SemanticVersion> {
 712        unsafe {
 713            let process_info = NSProcessInfo::processInfo(nil);
 714            let version = process_info.operatingSystemVersion();
 715            Ok(SemanticVersion::new(
 716                version.majorVersion as usize,
 717                version.minorVersion as usize,
 718                version.patchVersion as usize,
 719            ))
 720        }
 721    }
 722
 723    fn app_version(&self) -> Result<SemanticVersion> {
 724        unsafe {
 725            let bundle: id = NSBundle::mainBundle();
 726            if bundle.is_null() {
 727                Err(anyhow!("app is not running inside a bundle"))
 728            } else {
 729                let version: id = msg_send![bundle, objectForInfoDictionaryKey: ns_string("CFBundleShortVersionString")];
 730                if version.is_null() {
 731                    bail!("bundle does not have version");
 732                }
 733                let len = msg_send![version, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
 734                let bytes = version.UTF8String() as *const u8;
 735                let version = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
 736                version.parse()
 737            }
 738        }
 739    }
 740
 741    fn app_path(&self) -> Result<PathBuf> {
 742        unsafe {
 743            let bundle: id = NSBundle::mainBundle();
 744            if bundle.is_null() {
 745                Err(anyhow!("app is not running inside a bundle"))
 746            } else {
 747                Ok(path_from_objc(msg_send![bundle, bundlePath]))
 748            }
 749        }
 750    }
 751
 752    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
 753        unsafe {
 754            let app: id = msg_send![APP_CLASS, sharedApplication];
 755            let mut state = self.0.lock();
 756            let actions = &mut state.menu_actions;
 757            app.setMainMenu_(self.create_menu_bar(menus, app.delegate(), actions, keymap));
 758        }
 759    }
 760
 761    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
 762        unsafe {
 763            let app: id = msg_send![APP_CLASS, sharedApplication];
 764            let mut state = self.0.lock();
 765            let actions = &mut state.menu_actions;
 766            let new = self.create_dock_menu(menu, app.delegate(), actions, keymap);
 767            if let Some(old) = state.dock_menu.replace(new) {
 768                CFRelease(old as _)
 769            }
 770        }
 771    }
 772
 773    fn add_recent_document(&self, path: &Path) {
 774        if let Some(path_str) = path.to_str() {
 775            unsafe {
 776                let document_controller: id =
 777                    msg_send![class!(NSDocumentController), sharedDocumentController];
 778                let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
 779                let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
 780            }
 781        }
 782    }
 783
 784    fn local_timezone(&self) -> UtcOffset {
 785        unsafe {
 786            let local_timezone: id = msg_send![class!(NSTimeZone), localTimeZone];
 787            let seconds_from_gmt: NSInteger = msg_send![local_timezone, secondsFromGMT];
 788            UtcOffset::from_whole_seconds(seconds_from_gmt.try_into().unwrap()).unwrap()
 789        }
 790    }
 791
 792    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 793        unsafe {
 794            let bundle: id = NSBundle::mainBundle();
 795            if bundle.is_null() {
 796                Err(anyhow!("app is not running inside a bundle"))
 797            } else {
 798                let name = ns_string(name);
 799                let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
 800                if url.is_null() {
 801                    Err(anyhow!("resource not found"))
 802                } else {
 803                    ns_url_to_path(url)
 804                }
 805            }
 806        }
 807    }
 808
 809    /// Match cursor style to one of the styles available
 810    /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
 811    fn set_cursor_style(&self, style: CursorStyle) {
 812        unsafe {
 813            let new_cursor: id = match style {
 814                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
 815                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
 816                CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
 817                CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
 818                CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
 819                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
 820                CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
 821                CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
 822                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
 823                CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
 824                CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
 825                CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
 826                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
 827                CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
 828                CursorStyle::DisappearingItem => {
 829                    msg_send![class!(NSCursor), disappearingItemCursor]
 830                }
 831                CursorStyle::IBeamCursorForVerticalLayout => {
 832                    msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
 833                }
 834                CursorStyle::OperationNotAllowed => {
 835                    msg_send![class!(NSCursor), operationNotAllowedCursor]
 836                }
 837                CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
 838                CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
 839                CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
 840            };
 841
 842            let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
 843            if new_cursor != old_cursor {
 844                let _: () = msg_send![new_cursor, set];
 845            }
 846        }
 847    }
 848
 849    fn should_auto_hide_scrollbars(&self) -> bool {
 850        #[allow(non_upper_case_globals)]
 851        const NSScrollerStyleOverlay: NSInteger = 1;
 852
 853        unsafe {
 854            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
 855            style == NSScrollerStyleOverlay
 856        }
 857    }
 858
 859    fn write_to_clipboard(&self, item: ClipboardItem) {
 860        let state = self.0.lock();
 861        unsafe {
 862            state.pasteboard.clearContents();
 863
 864            let text_bytes = NSData::dataWithBytes_length_(
 865                nil,
 866                item.text.as_ptr() as *const c_void,
 867                item.text.len() as u64,
 868            );
 869            state
 870                .pasteboard
 871                .setData_forType(text_bytes, NSPasteboardTypeString);
 872
 873            if let Some(metadata) = item.metadata.as_ref() {
 874                let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
 875                let hash_bytes = NSData::dataWithBytes_length_(
 876                    nil,
 877                    hash_bytes.as_ptr() as *const c_void,
 878                    hash_bytes.len() as u64,
 879                );
 880                state
 881                    .pasteboard
 882                    .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
 883
 884                let metadata_bytes = NSData::dataWithBytes_length_(
 885                    nil,
 886                    metadata.as_ptr() as *const c_void,
 887                    metadata.len() as u64,
 888                );
 889                state
 890                    .pasteboard
 891                    .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
 892            }
 893        }
 894    }
 895
 896    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
 897        let state = self.0.lock();
 898        unsafe {
 899            if let Some(text_bytes) =
 900                self.read_from_pasteboard(state.pasteboard, NSPasteboardTypeString)
 901            {
 902                let text = String::from_utf8_lossy(text_bytes).to_string();
 903                let hash_bytes = self
 904                    .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
 905                    .and_then(|bytes| bytes.try_into().ok())
 906                    .map(u64::from_be_bytes);
 907                let metadata_bytes = self
 908                    .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)
 909                    .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
 910
 911                if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
 912                    if hash == ClipboardItem::text_hash(&text) {
 913                        Some(ClipboardItem {
 914                            text,
 915                            metadata: Some(metadata),
 916                        })
 917                    } else {
 918                        Some(ClipboardItem {
 919                            text,
 920                            metadata: None,
 921                        })
 922                    }
 923                } else {
 924                    Some(ClipboardItem {
 925                        text,
 926                        metadata: None,
 927                    })
 928                }
 929            } else {
 930                None
 931            }
 932        }
 933    }
 934
 935    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
 936        let url = url.to_string();
 937        let username = username.to_string();
 938        let password = password.to_vec();
 939        self.background_executor().spawn(async move {
 940            unsafe {
 941                use security::*;
 942
 943                let url = CFString::from(url.as_str());
 944                let username = CFString::from(username.as_str());
 945                let password = CFData::from_buffer(&password);
 946
 947                // First, check if there are already credentials for the given server. If so, then
 948                // update the username and password.
 949                let mut verb = "updating";
 950                let mut query_attrs = CFMutableDictionary::with_capacity(2);
 951                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 952                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 953
 954                let mut attrs = CFMutableDictionary::with_capacity(4);
 955                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 956                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 957                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
 958                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
 959
 960                let mut status = SecItemUpdate(
 961                    query_attrs.as_concrete_TypeRef(),
 962                    attrs.as_concrete_TypeRef(),
 963                );
 964
 965                // If there were no existing credentials for the given server, then create them.
 966                if status == errSecItemNotFound {
 967                    verb = "creating";
 968                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
 969                }
 970
 971                if status != errSecSuccess {
 972                    return Err(anyhow!("{} password failed: {}", verb, status));
 973                }
 974            }
 975            Ok(())
 976        })
 977    }
 978
 979    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
 980        let url = url.to_string();
 981        self.background_executor().spawn(async move {
 982            let url = CFString::from(url.as_str());
 983            let cf_true = CFBoolean::true_value().as_CFTypeRef();
 984
 985            unsafe {
 986                use security::*;
 987
 988                // Find any credentials for the given server URL.
 989                let mut attrs = CFMutableDictionary::with_capacity(5);
 990                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
 991                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
 992                attrs.set(kSecReturnAttributes as *const _, cf_true);
 993                attrs.set(kSecReturnData as *const _, cf_true);
 994
 995                let mut result = CFTypeRef::from(ptr::null());
 996                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
 997                match status {
 998                    security::errSecSuccess => {}
 999                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1000                    _ => return Err(anyhow!("reading password failed: {}", status)),
1001                }
1002
1003                let result = CFType::wrap_under_create_rule(result)
1004                    .downcast::<CFDictionary>()
1005                    .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
1006                let username = result
1007                    .find(kSecAttrAccount as *const _)
1008                    .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
1009                let username = CFType::wrap_under_get_rule(*username)
1010                    .downcast::<CFString>()
1011                    .ok_or_else(|| anyhow!("account was not a string"))?;
1012                let password = result
1013                    .find(kSecValueData as *const _)
1014                    .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
1015                let password = CFType::wrap_under_get_rule(*password)
1016                    .downcast::<CFData>()
1017                    .ok_or_else(|| anyhow!("password was not a string"))?;
1018
1019                Ok(Some((username.to_string(), password.bytes().to_vec())))
1020            }
1021        })
1022    }
1023
1024    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1025        let url = url.to_string();
1026
1027        self.background_executor().spawn(async move {
1028            unsafe {
1029                use security::*;
1030
1031                let url = CFString::from(url.as_str());
1032                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1033                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1034                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1035
1036                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1037
1038                if status != errSecSuccess {
1039                    return Err(anyhow!("delete password failed: {}", status));
1040                }
1041            }
1042            Ok(())
1043        })
1044    }
1045}
1046
1047unsafe fn path_from_objc(path: id) -> PathBuf {
1048    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1049    let bytes = path.UTF8String() as *const u8;
1050    let path = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
1051    PathBuf::from(path)
1052}
1053
1054unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1055    let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1056    assert!(!platform_ptr.is_null());
1057    &*(platform_ptr as *const MacPlatform)
1058}
1059
1060extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1061    unsafe {
1062        let app: id = msg_send![APP_CLASS, sharedApplication];
1063        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1064        let platform = get_mac_platform(this);
1065        let callback = platform.0.lock().finish_launching.take();
1066        if let Some(callback) = callback {
1067            callback();
1068        }
1069    }
1070}
1071
1072extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1073    if !has_open_windows {
1074        let platform = unsafe { get_mac_platform(this) };
1075        let mut lock = platform.0.lock();
1076        if let Some(mut callback) = lock.reopen.take() {
1077            drop(lock);
1078            callback();
1079            platform.0.lock().reopen.get_or_insert(callback);
1080        }
1081    }
1082}
1083
1084extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1085    let platform = unsafe { get_mac_platform(this) };
1086    let mut lock = platform.0.lock();
1087    if let Some(mut callback) = lock.quit.take() {
1088        drop(lock);
1089        callback();
1090        platform.0.lock().quit.get_or_insert(callback);
1091    }
1092}
1093
1094extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1095    let urls = unsafe {
1096        (0..urls.count())
1097            .filter_map(|i| {
1098                let url = urls.objectAtIndex(i);
1099                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1100                    Ok(string) => Some(string.to_string()),
1101                    Err(err) => {
1102                        log::error!("error converting path to string: {}", err);
1103                        None
1104                    }
1105                }
1106            })
1107            .collect::<Vec<_>>()
1108    };
1109    let platform = unsafe { get_mac_platform(this) };
1110    let mut lock = platform.0.lock();
1111    if let Some(mut callback) = lock.open_urls.take() {
1112        drop(lock);
1113        callback(urls);
1114        platform.0.lock().open_urls.get_or_insert(callback);
1115    }
1116}
1117
1118extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1119    unsafe {
1120        let platform = get_mac_platform(this);
1121        let mut lock = platform.0.lock();
1122        if let Some(mut callback) = lock.menu_command.take() {
1123            let tag: NSInteger = msg_send![item, tag];
1124            let index = tag as usize;
1125            if let Some(action) = lock.menu_actions.get(index) {
1126                let action = action.boxed_clone();
1127                drop(lock);
1128                callback(&*action);
1129            }
1130            platform.0.lock().menu_command.get_or_insert(callback);
1131        }
1132    }
1133}
1134
1135extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1136    unsafe {
1137        let mut result = false;
1138        let platform = get_mac_platform(this);
1139        let mut lock = platform.0.lock();
1140        if let Some(mut callback) = lock.validate_menu_command.take() {
1141            let tag: NSInteger = msg_send![item, tag];
1142            let index = tag as usize;
1143            if let Some(action) = lock.menu_actions.get(index) {
1144                let action = action.boxed_clone();
1145                drop(lock);
1146                result = callback(action.as_ref());
1147            }
1148            platform
1149                .0
1150                .lock()
1151                .validate_menu_command
1152                .get_or_insert(callback);
1153        }
1154        result
1155    }
1156}
1157
1158extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1159    unsafe {
1160        let platform = get_mac_platform(this);
1161        let mut lock = platform.0.lock();
1162        if let Some(mut callback) = lock.will_open_menu.take() {
1163            drop(lock);
1164            callback();
1165            platform.0.lock().will_open_menu.get_or_insert(callback);
1166        }
1167    }
1168}
1169
1170extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1171    unsafe {
1172        let platform = get_mac_platform(this);
1173        let mut state = platform.0.lock();
1174        if let Some(id) = state.dock_menu {
1175            id
1176        } else {
1177            nil
1178        }
1179    }
1180}
1181
1182unsafe fn ns_string(string: &str) -> id {
1183    NSString::alloc(nil).init_str(string).autorelease()
1184}
1185
1186unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1187    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1188    if path.is_null() {
1189        Err(anyhow!(
1190            "url is not a file path: {}",
1191            CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1192        ))
1193    } else {
1194        Ok(PathBuf::from(OsStr::from_bytes(
1195            CStr::from_ptr(path).to_bytes(),
1196        )))
1197    }
1198}
1199
1200mod security {
1201    #![allow(non_upper_case_globals)]
1202    use super::*;
1203
1204    #[link(name = "Security", kind = "framework")]
1205    extern "C" {
1206        pub static kSecClass: CFStringRef;
1207        pub static kSecClassInternetPassword: CFStringRef;
1208        pub static kSecAttrServer: CFStringRef;
1209        pub static kSecAttrAccount: CFStringRef;
1210        pub static kSecValueData: CFStringRef;
1211        pub static kSecReturnAttributes: CFStringRef;
1212        pub static kSecReturnData: CFStringRef;
1213
1214        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1215        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1216        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1217        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1218    }
1219
1220    pub const errSecSuccess: OSStatus = 0;
1221    pub const errSecUserCanceled: OSStatus = -128;
1222    pub const errSecItemNotFound: OSStatus = -25300;
1223}
1224
1225#[cfg(test)]
1226mod tests {
1227    use crate::ClipboardItem;
1228
1229    use super::*;
1230
1231    #[test]
1232    fn test_clipboard() {
1233        let platform = build_platform();
1234        assert_eq!(platform.read_from_clipboard(), None);
1235
1236        let item = ClipboardItem::new("1".to_string());
1237        platform.write_to_clipboard(item.clone());
1238        assert_eq!(platform.read_from_clipboard(), Some(item));
1239
1240        let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
1241        platform.write_to_clipboard(item.clone());
1242        assert_eq!(platform.read_from_clipboard(), Some(item));
1243
1244        let text_from_other_app = "text from other app";
1245        unsafe {
1246            let bytes = NSData::dataWithBytes_length_(
1247                nil,
1248                text_from_other_app.as_ptr() as *const c_void,
1249                text_from_other_app.len() as u64,
1250            );
1251            platform
1252                .0
1253                .lock()
1254                .pasteboard
1255                .setData_forType(bytes, NSPasteboardTypeString);
1256        }
1257        assert_eq!(
1258            platform.read_from_clipboard(),
1259            Some(ClipboardItem::new(text_from_other_app.to_string()))
1260        );
1261    }
1262
1263    fn build_platform() -> MacPlatform {
1264        let platform = MacPlatform::new();
1265        platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1266        platform
1267    }
1268}