|
| 1 | +use core::fmt; |
| 2 | +use core::panic::{RefUnwindSafe, UnwindSafe}; |
| 3 | + |
| 4 | +use super::{NSCopying, NSDictionary, NSObject, NSString}; |
| 5 | +use crate::rc::{Id, Shared}; |
| 6 | +use crate::{extern_class, extern_methods, msg_send_id, ns_string, ClassType}; |
| 7 | + |
| 8 | +extern_class!( |
| 9 | + /// A representation of the code and resources stored in a bundle |
| 10 | + /// directory on disk. |
| 11 | + /// |
| 12 | + /// See [Apple's documentation](https://developer.apple.com/documentation/foundation/nsbundle?language=objc). |
| 13 | + #[derive(PartialEq, Eq, Hash)] |
| 14 | + pub struct NSBundle; |
| 15 | + |
| 16 | + unsafe impl ClassType for NSBundle { |
| 17 | + type Super = NSObject; |
| 18 | + } |
| 19 | +); |
| 20 | + |
| 21 | +// SAFETY: Bundles are documented as thread-safe. |
| 22 | +unsafe impl Sync for NSBundle {} |
| 23 | +unsafe impl Send for NSBundle {} |
| 24 | + |
| 25 | +impl UnwindSafe for NSBundle {} |
| 26 | +impl RefUnwindSafe for NSBundle {} |
| 27 | + |
| 28 | +extern_methods!( |
| 29 | + unsafe impl NSBundle { |
| 30 | + pub fn main() -> Id<Self, Shared> { |
| 31 | + unsafe { msg_send_id![Self::class(), mainBundle] } |
| 32 | + } |
| 33 | + |
| 34 | + pub fn info(&self) -> Id<NSDictionary<NSString, NSObject>, Shared> { |
| 35 | + unsafe { msg_send_id![self, infoDictionary] } |
| 36 | + } |
| 37 | + |
| 38 | + pub fn name(&self) -> Option<Id<NSString, Shared>> { |
| 39 | + self.info().get(ns_string!("CFBundleName")).map(|name| { |
| 40 | + let ptr: *const NSObject = name; |
| 41 | + let ptr: *const NSString = ptr.cast(); |
| 42 | + // SAFETY: TODO |
| 43 | + let name = unsafe { ptr.as_ref().unwrap_unchecked() }; |
| 44 | + name.copy() |
| 45 | + }) |
| 46 | + } |
| 47 | + } |
| 48 | +); |
| 49 | + |
| 50 | +impl fmt::Debug for NSBundle { |
| 51 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 52 | + // Delegate to NSObject |
| 53 | + (**self).fmt(f) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +#[cfg(test)] |
| 58 | +mod tests { |
| 59 | + use super::*; |
| 60 | + use alloc::format; |
| 61 | + use std::println; |
| 62 | + |
| 63 | + #[test] |
| 64 | + #[cfg_attr(not(target_os = "macos"), ignore = "varies between platforms")] |
| 65 | + fn try_running_functions() { |
| 66 | + // This is mostly empty since cargo doesn't bundle the application |
| 67 | + // before executing. |
| 68 | + let bundle = NSBundle::main(); |
| 69 | + println!("{:?}", bundle); |
| 70 | + assert_eq!(format!("{:?}", bundle.info()), "{}"); |
| 71 | + assert_eq!(bundle.name(), None); |
| 72 | + } |
| 73 | +} |
0 commit comments