From 3cc90cc7d03c6123c1ecc1cb280cb4d4494552a9 Mon Sep 17 00:00:00 2001 From: oligami-0424 Date: Mon, 18 Dec 2023 23:14:30 +0900 Subject: [PATCH] test --- Cargo.toml | 3 + build.rs | 7 +- examples/android/Cargo.lock | 1 + examples/common/Cargo.lock | 1 + examples/iphone/Cargo.lock | 1 + rust/macos/mod.rs | 3 + rust/macos/objc/darling_classes.ts | 579 +++++++++++++++++++++++++++++ rust/macos/objc/mod.rs | 32 ++ rust/macos/objc/nick_name.rs | 84 ++++- 9 files changed, 706 insertions(+), 5 deletions(-) create mode 100644 rust/macos/objc/darling_classes.ts diff --git a/Cargo.toml b/Cargo.toml index 4ce01a3..9919b93 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,9 @@ winapi = { version = "0.3", features = [ [target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies] objc = { version = "0.5.0", package = "objc2" } +[target.'cfg(target_os = "macos")'.dependencies] +objc-sys = "0.3.2" + [target.'cfg(any(unix, target_os = "redox", target_os = "macos", target_os = "wasi"))'.dependencies] libc = "0.2" diff --git a/build.rs b/build.rs index b131810..d553ac1 100644 --- a/build.rs +++ b/build.rs @@ -13,11 +13,14 @@ fn main() { #[cfg(target_os = "macos")] { println!("cargo:rustc-link-lib=framework=Foundation"); - println!("cargo:rustc-link-lib=framework=AppKit"); - println!("cargo:rustc-link-lib=framework=CoreGraphics"); println!("cargo:rustc-link-lib=framework=QuartzCore"); println!("cargo:rustc-link-lib=framework=Security"); + println!("cargo:rustc-link-lib=framework=UIKit"); + println!("cargo:rustc-link-lib=framework=WebKit"); + println!("cargo:rustc-link-lib=framework=CloudKit"); + println!("cargo:rustc-link-lib=framework=UserNotifications"); + println!("cargo:rustc-link-lib=framework=QuickLook"); } } diff --git a/examples/android/Cargo.lock b/examples/android/Cargo.lock index 2f79bc0..b56c84b 100644 --- a/examples/android/Cargo.lock +++ b/examples/android/Cargo.lock @@ -233,6 +233,7 @@ dependencies = [ "jni", "libc", "ndk-context", + "objc-sys", "objc2", "thiserror", "winapi", diff --git a/examples/common/Cargo.lock b/examples/common/Cargo.lock index a4dc5ec..1371da2 100644 --- a/examples/common/Cargo.lock +++ b/examples/common/Cargo.lock @@ -84,6 +84,7 @@ dependencies = [ "jni", "libc", "ndk-context", + "objc-sys", "objc2", "thiserror", "winapi", diff --git a/examples/iphone/Cargo.lock b/examples/iphone/Cargo.lock index 9ad421b..1e68eb5 100644 --- a/examples/iphone/Cargo.lock +++ b/examples/iphone/Cargo.lock @@ -232,6 +232,7 @@ dependencies = [ "jni", "libc", "ndk-context", + "objc-sys", "objc2", "thiserror", "winapi", diff --git a/rust/macos/mod.rs b/rust/macos/mod.rs index b9eb5dc..0087aca 100644 --- a/rust/macos/mod.rs +++ b/rust/macos/mod.rs @@ -6,4 +6,7 @@ mod util { #[allow(non_camel_case_types)] pub(crate) type id = *const NSObject; + + #[allow(non_camel_case_types)] + pub(crate) type class_id = *const objc_sys::objc_class; } diff --git a/rust/macos/objc/darling_classes.ts b/rust/macos/objc/darling_classes.ts new file mode 100644 index 0000000..c2bcb41 --- /dev/null +++ b/rust/macos/objc/darling_classes.ts @@ -0,0 +1,579 @@ +// This is FoundationFramework Types? +[ + "NSProxy", // https://developer.apple.com/documentation/foundation/nsproxy?language=objc + "NSProtocolChecker", // https://developer.apple.com/documentation/foundation/nsprotocolchecker?language=objc + "NSConcreteProtocolChecker", // https://developer.apple.com/documentation/foundation/nsprotocolchecker?language=objc + "NSDistantObject", // https://developer.apple.com/documentation/foundation/NSDistantObject?language=objc + "NSMutableStringProxy", // https://github.com/darlinghq/darling-foundation/blob/ffedc7bda02b9bddfdb5e7b1baf78e68e2b57b3c/CMakeLists.txt#L119 + "_NSZombie_", // https://stackoverflow.com/questions/4168327/what-is-nszombie + "__NSMessageBuilder", // https://developer.apple.com/documentation/bundleresources/information_property_list/nsservices/nsmessage?language=objc + "__NSGenericDeallocHandler", + "Object", // https://developer.apple.com/documentation/objectivec/object?language=objc + "NSObject", // https://developer.apple.com/documentation/objectivec/id?language=objc + "NSCFType", + "NSKeyBinding", + "NSKeySetBinding", + "_NSKeyBindingSetWrapper", + "_NSKeyBindingGetWrapper", + "_NSKeyForwardingSetBinding", + "NSKeyGetBinding", + "_NSKeyForwardingGetBinding", + "NSUnitConverter", + "NSUnitConverterLinear", + "NSUnit", + "NSDimension", + "NSUnitLength", + "NSUnitDuration", + "NSMeasurement", + "NSDeserializer", + "NSGarbageCollector", + "NSDateInterval", + "NSUserNotificationCenter", + "NSUserNotificationAction", + "NSUserNotification", + "NSScriptCommandDescription", + "NSScriptCommand", + "NSPositionalSpecifier", + "NSScriptObjectSpecifier", + "NSWhoseSpecifier", + "NSUniqueIDSpecifier", + "NSRelativeSpecifier", + "NSRangeSpecifier", + "NSRandomSpecifier", + "NSPropertySpecifier", + "NSNameSpecifier", + "NSMiddleSpecifier", + "NSIndexSpecifier", + "NSExtension", + "NSExtensionContext", + "NSLayoutConstraint", + "NSIBPrototypingLayoutConstraint", + "NSContentSizeLayoutConstraint", + "NSAutoresizingMaskLayoutConstraint", + "NSMetadataQueryResultGroup", + "NSMetadataQueryAttributeValueTuple", + "NSMetadataItem", + "NSMetadataQuery", + "NSAppleEventManager", + "NSAppleEventDescriptor", + "NSFileWrapper", + "NSFileWrapperLink", + "NSFileWrapperDirectory", + "NSFileWrapperFile", + "NSSpellEngine", + "_NSXPCDistantObject", + "NSXPCListenerEndpoint", + "NSXPCListener", + "NSXPCConnection", + "_NSXPCConnectionImportInfo", + "_NSXPCConnectionExpectedReplies", + "_NSXPCConnectionExpectedReplyInfo", + "_NSXPCConnectionExportInfo", + "NSXPCInterface", + "_NSXPCInterfaceMethodInfo", + "NSXMLParser", + "NSXMLNode", + "NSXMLElement", + "NSXMLDTDNode", + "NSXMLDTD", + "NSXMLDocument", + "NSValueTransformer", + "_NSSharedValueTransformer", + "_NSUnarchiveFromDataTransformer", + "_NSKeyedUnarchiveFromDataTransformer", + "_NSNegateBooleanTransformer", + "_NSIsNotNilTransformer", + "_NSIsNilTransformer", + "NSUUID", + "__NSConcreteUUID", + "NSURLQueryItem", + "NSURLFileTypeMappingsInternal", + "NSURLFileTypeMappings", + "NSURLComponents", + "NSUndoManager", + "NSUndoGroup", + "NSUbiquitousKeyValueStore", + "_NSThreadPerformInfo", + "NSTask", + "NSConcreteTask", + "__NSStringRegexPatternKey", + "NSSortDescriptor", + "NSScanner", + "NSConcreteScanner", + "_NSRunLoopInfo", + "NSProgress", + "_NSProgressWithRemoteParent", + "NSProcessInfo", + "_NSPredicateUtilities", + "_NSPredicateOperatorUtilities", + "NSPointerFunctions", + "NSConcretePointerFunctions", + "NSPointerArray", + "NSConcretePointerArray", + "NSPortNameServer", + "NSMachBootstrapServer", + "NSDistantObjectRequest", + "NSConcreteDistantObjectRequest", + "NSConnection", + "NSPortMessage", + "NSPlatform", + "NSPlatform_posix", + "NSPlatform_darwin", + "NSOrthography", + "NSComplexOrthography", + "NSSimpleOrthography", + "NSOperationQueue", + "_NSOperationQueueInternal", + "_NSOperationInternal", + "_NSWeakRef", + "NSNotificationQueue", + "NSNotification", + "NSConcreteNotification", + "_NSNotificationObserver", + "NSNetServiceBrowser", + "NSNetService", + "NSNetServicesInternal", + "NSMapTable", + "NSConcreteMapTable", + "NSCondition", + "NSRecursiveLock", + "NSConditionLock", + "NSLock", + "NSLinguisticTagger", + "NSKeyValueObservationInfo", + "NSKeyValueObservance", + "NSKeyValueContainerClass", + "NSKeyValueProperty", + "NSKeyValueUnnestedProperty", + "NSKeyValueNestedProperty", + "NSKeyValueComputedProperty", + "NSKeyValueProxyShareKey", + "NSKeyValueMutatingCollectionMethodSet", + "NSKeyValueMutatingSetMethodSet", + "NSKeyValueMutatingOrderedSetMethodSet", + "NSKeyValueMutatingArrayMethodSet", + "NSKeyValueNonmutatingCollectionMethodSet", + "NSKeyValueNonmutatingSetMethodSet", + "NSKeyValueNonmutatingOrderedSetMethodSet", + "NSKeyValueNonmutatingArrayMethodSet", + "NSKeyValueAccessor", + "NSKeyValueGetter", + "NSKeyValueProxyGetter", + "NSKeyValueNotifyingMutableCollectionGetter", + "NSKeyValueIvarMutableCollectionGetter", + "NSKeyValueFastMutableCollection2Getter", + "NSKeyValueFastMutableCollection1Getter", + "NSKeyValueSlowMutableCollectionGetter", + "NSKeyValueCollectionGetter", + "NSKeyValueSlowGetter", + "NSKeyValueUndefinedGetter", + "NSKeyValueIvarGetter", + "NSKeyValueMethodGetter", + "NSKeyValueSetter", + "NSKeyValueSlowSetter", + "NSKeyValueUndefinedSetter", + "NSKeyValueIvarSetter", + "NSKeyValueMethodSetter", + "_NSKeyedUnarchiverHelper", + "_NSKeyedCoderOldStyleArray", + "NSJSONSerialization", + "_NSJSONWriter", + "_NSJSONReader", + "NSItemProvider", + "NSIndexSet", + "NSMutableIndexSet", + "NSIndexPath", + "NSHost", + "NSHashTable", + "NSConcreteHashTable", + "NSOperation", + "NSBlockOperation", + "NSInvocationOperation", + "NSFilesystemItemRemoveOperation", + "NSFileManager", + "NSPipe", + "NSConcretePipe", + "NSConcreteFileHandleARCWeakRef", + "NSFileHandle", + "NSNullFileHandle", + "NSConcreteFileHandle", + "_NSStdIOFileHandle", + "NSFileCoordinator", + "NSFileAccessIntent", + "NSAssertionHandler", + "NSNotificationCenter", + "NSDistributedNotificationCenter", + "NSDecimalNumberHandler", + "NSRegularExpression", + "NSDataDetector", + "NSClassDescription", + "NSScriptClassDescription", + "NSFormatter", + "NSISO8601DateFormatter", + "NSMeasurementFormatter", + "NSDateComponentsFormatter", + "NSNumberFormatter", + "NSMassFormatter", + "NSLengthFormatter", + "NSEnergyFormatter", + "NSDateIntervalFormatter", + "NSDateFormatter", + "NSByteCountFormatter", + "NSBundle", + "NSPredicate", + "NSTruePredicate", + "NSFalsePredicate", + "NSCompoundPredicate", + "NSComparisonPredicate", + "NSBlockPredicate", + "NSPredicateOperator", + "NSStringPredicateOperator", + "NSTokenMatchingPredicateOperator", + "NSSubstringPredicateOperator", + "NSMatchingPredicateOperator", + "NSLikePredicateOperator", + "NSInPredicateOperator", + "NSEqualityPredicateOperator", + "NSCustomPredicateOperator", + "NSCompoundPredicateOperator", + "NSComparisonPredicateOperator", + "NSBetweenPredicateOperator", + "NSAutoreleasePool", + "NSCoder", + "NSUnarchiver", + "NSXPCCoder", + "NSXPCEncoder", + "NSXPCDecoder", + "NSPortCoder", + "NSConcretePortCoder", + "NSKeyedPortCoder", + "NSUnkeyedPortCoder", + "NSKeyedUnarchiver", + "NSKeyedArchiver", + "NSArchiver", + "NSExpression", + "NSVariableExpression", + "NSVariableAssignmentExpression", + "NSTernaryExpression", + "NSSymbolicExpression", + "NSSubqueryExpression", + "NSSetExpression", + "NSSelfExpression", + "NSKeyPathSpecifierExpression", + "NSFunctionExpression", + "NSKeyPathExpression", + "NSConstantValueExpression", + "NSBlockExpression", + "NSAnyKeyExpression", + "NSAggregateExpression", + "NSAffineTransform", + "NSTextCheckingResult", + "NSTransitInformationCheckingResult", + "NSSubstitutionCheckingResult", + "NSQuoteCheckingResult", + "NSDashCheckingResult", + "NSCorrectionCheckingResult", + "NSSpellCheckingResult", + "NSRegularExpressionCheckingResult", + "NSComplexRegularExpressionCheckingResult", + "NSExtendedRegularExpressionCheckingResult", + "NSSimpleRegularExpressionCheckingResult", + "NSPhoneNumberCheckingResult", + "NSOrthographyCheckingResult", + "NSLinkCheckingResult", + "NSGrammarCheckingResult", + "NSDateCheckingResult", + "NSAddressCheckingResult", + "NSAppleScript", + "NSHTTPCookieStorage", + "NSHTTPCookie", + "NSURLSessionConfiguration", + "NSURLSessionTask", + "NSURLSessionDataTask", + "NSURLSessionUploadTask", + "NSURLSession", + "NSHTTPURLResponseInternal", + "NSURLResponse", + "NSHTTPURLResponse", + "NSURLResponseInternal", + "NSURLRequest", + "NSMutableURLRequest", + "NSURLRequestInternal", + "NSURLProtocol", + "NSURLProtocolDefaultClient", + "NSURLProtectionSpace", + "NSURLDownload", + "NSURLCredentialStorage", + "NSURLCredential", + "NSURLConnection", + "NSURLConnectionInternal", + "NSURLCache", + "NSCachedURLResponse", + "NSURLAuthenticationChallenge", + "NSURLSessionTaskMetrics", + "SecXPCUtils", + "SecXPCHelper", + "SOSCachedNotification", + "SecKeyProxy", + "SecKeyProxyTarget", + "SecSOSStatus", + "SFSQLiteStatement", + "SFObjCType", + "SFSQLite", + "SFAnalyticsSQLiteStore", + "SFAnalyticsSampler", + "SFAnalyticsMultiSampler", + "SFAnalyticsActivityTracker", + "SharedCredentialController", + "SecConcrete_sec_protocol_configuration", + "SecConcrete_sec_protocol_configuration_builder", + "SecConcrete_sec_trust", + "SecConcrete_sec_certificate", + "SecConcrete_sec_identity", + "SecConcrete_sec_array", + "OTJoiningConfiguration", + "OTControl", + "OTClique", + "OTOperationConfiguration", + "OTBottleIDs", + "OTConfigurationContext", + "SecEscrowRequest", + "CKKSControl", + "SecExperimentConfig", + "SecExperiment", + "SecExpConcrete_sec_experiment", + "SFAnalytics", + "SOSAnalytics", + "LocalKeychainAnalytics", + "LKAUpgradeOutcomeReport", + "SecCoreAnalytics", + "SecuritydXPCCallback", + "SecuritydXPCClient", + "HIDSession", + "HIDServiceClient", + "HIDEventService", + "HIDEvent", + "HIDElement", + "HIDDevice", + "HIDConnection", + "NSFileSecurity", + "NSUserDefaults", + "_NSTimerInfo", + "NSSharedKeySet", + "NSRunLoop", + "NSPropertyListSerialization", + "NSOrderedSet", + "NSKeyValueOrderedSet", + "__NSOrderedSetReversed", + "__NSOrderedSetI", + "NSMutableOrderedSet", + "NSKeyValueMutableOrderedSet", + "NSKeyValueNotifyingMutableOrderedSet", + "NSKeyValueIvarMutableOrderedSet", + "NSKeyValueFastMutableOrderedSet", + "NSKeyValueFastMutableOrderedSet2", + "NSKeyValueFastMutableOrderedSet1", + "NSKeyValueSlowMutableOrderedSet", + "__NSOrderedSetM", + "__NSPlaceholderOrderedSet", + "NSMethodSignature", + "NSException", + "NSDate", + "NSCalendarDate", + "__NSPlaceholderDate", + "__NSDate", + "NSDateComponents", + "NSCache", + "_NSCacheObject", + "NSEnumerator", + "NSConcreteMapTableKeyEnumerator", + "NSConcreteMapTableObjectEnumerator", + "NSConcreteHashTableEnumerator", + "NSKeyValueNilSetEnumerator", + "NSKeyValueNilOrderedSetEnumerator", + "NSDirectoryEnumerator", + "NSURLDirectoryEnumerator", + "NSAllDescendantPathsEnumerator", + "__NSOrderedSetReverseEnumerator", + "__NSFastEnumerationEnumerator", + "__NSDictionaryObjectEnumerator", + "__NSArrayReverseEnumerator", + "NSThread", + "NSValue", + "NSConcreteValue", + "NSNumber", + "NSPlaceholderValue", + "NSPlaceholderNumber", + "NSDecimalNumber", + "NSDecimalNumberPlaceholder", + "__NSCFNumber", + "__NSCFBoolean", + "NSAttributedString", + "__NSPlaceholderAttributedString", + "NSMutableAttributedString", + "__NSCFAttributedString", + "NSCharacterSet", + "NSMutableCharacterSet", + "__NSCFCharacterSet", + "NSError", + "__NSCFError", + "NSString", + "NSSimpleCString", + "NSConstantString", + "NSPlaceholderString", + "NSPathStore2", + "NSLocalizableString", + "NSMutableString", + "NSPlaceholderMutableString", + "NSCheapMutableString", + "NSMutableStringProxyForMutableAttributedString", + "__NSCFString", + "__NSCFConstantString", + "__NSBlockVariable", + "__NSBlockVariable__", + "NSBlock", + "__NSGlobalBlock", + "__NSGlobalBlock__", + "__NSAutoBlock", + "__NSFinalizingBlock", + "__NSFinalizingBlock__", + "__NSAutoBlock__", + "__NSMallocBlock", + "__NSMallocBlock__", + "__NSStackBlock", + "__NSStackBlock__", + "NSCalendar", + "NSAutoCalendar", + "__NSCFCalendar", + "NSTimeZone", + "__NSPlaceholderTimeZone", + "__NSTimeZone", + "NSTimer", + "__NSCFTimer", + "NSStream", + "NSOutputStream", + "__NSCFOutputStream", + "NSInputStream", + "__NSCFInputStream", + "NSPort", + "NSSocketPort", + "NSMessagePort", + "NSMachPort", + "NSLocale", + "NSAutoLocale", + "__NSCFLocale", + "NSURL", + "NSData", + "__NSZeroData", + "NSSubrangeData", + "NSConcreteData", + "__NSPlaceholderData", + "NSMutableData", + "NSPurgeableData", + "NSConcreteMutableData", + "__NSCFData", + "NSArray", + "NSKeyValueArray", + "__NSOrderedSetArrayProxy", + "__NSArrayI", + "NSMutableArray", + "NSKeyValueMutableArray", + "NSKeyValueNotifyingMutableArray", + "NSKeyValueIvarMutableArray", + "NSKeyValueFastMutableArray", + "NSKeyValueFastMutableArray2", + "NSKeyValueFastMutableArray1", + "NSKeyValueSlowMutableArray", + "__NSPlaceholderArray", + "__NSCFArray", + "NSDictionary", + "NSKeyValueChangeDictionary", + "NSFileAttributes", + "__NSDictionaryI", + "NSMutableDictionary", + "_NSNestedDictionary", + "NSSharedKeyDictionary", + "__NSPlaceholderDictionary", + "__NSCFDictionary", + "NSSet", + "NSKeyValueSet", + "__NSOrderedSetSetProxy", + "NSMutableSet", + "NSCountedSet", + "NSKeyValueMutableSet", + "NSKeyValueNotifyingMutableSet", + "NSKeyValueIvarMutableSet", + "NSKeyValueFastMutableSet", + "NSKeyValueFastMutableSet2", + "NSKeyValueFastMutableSet1", + "NSKeyValueSlowMutableSet", + "__NSPlaceholderSet", + "__NSCFSet", + "NSNull", + "__NSCFType", + "NSInvocation", + "NSBlockInvocation", + "Protocol", + "__IncompleteProtocol", + "__NSUnrecognizedTaggedPointer", + "OS_object", + "OS_os_eventlink", + "OS_os_workgroup", + "OS_os_workgroup_parallel", + "OS_os_workgroup_interval", + "OS_os_transaction", + "OS_xpc_object", + "OS_xpc_uuid", + "OS_xpc_uint64", + "OS_xpc_string", + "OS_xpc_shmem", + "OS_xpc_service", + "OS_xpc_service_instance", + "OS_xpc_deserializer", + "OS_xpc_serializer", + "OS_xpc_pointer", + "OS_xpc_plist_binary_v0_deserializer", + "OS_xpc_plist_xml_element", + "OS_xpc_pipe", + "OS_xpc_null", + "OS_xpc_mach_send", + "OS_xpc_mach_recv", + "OS_xpc_int64", + "OS_xpc_file_transfer", + "OS_xpc_fd", + "OS_xpc_endpoint", + "OS_xpc_double", + "OS_xpc_dictionary", + "OS_xpc_error", + "OS_xpc_date", + "OS_xpc_data", + "OS_xpc_connection", + "OS_xpc_bundle", + "OS_xpc_bool", + "OS_xpc_array", + "OS_xpc_activity", + "OS_os_log", + "OS_os_activity", + "OS_dispatch_object", + "OS_dispatch_disk", + "OS_dispatch_operation", + "OS_dispatch_io", + "OS_dispatch_mach_msg", + "OS_dispatch_queue_attr", + "OS_dispatch_group", + "OS_dispatch_semaphore", + "OS_dispatch_mach", + "OS_dispatch_source", + "OS_dispatch_channel", + "OS_dispatch_queue", + "OS_dispatch_queue_pthread_root", + "OS_dispatch_queue_global", + "OS_dispatch_queue_concurrent", + "OS_dispatch_workloop", + "OS_dispatch_queue_serial", + "OS_dispatch_queue_mgr", + "OS_dispatch_queue_main", + "OS_dispatch_queue_runloop", + "OS_dispatch_data", + "OS_dispatch_data_empty", +]; diff --git a/rust/macos/objc/mod.rs b/rust/macos/objc/mod.rs index 27448f2..6d659b2 100644 --- a/rust/macos/objc/mod.rs +++ b/rust/macos/objc/mod.rs @@ -1 +1,33 @@ +use std::ffi::CStr; + +use crate::macos::util::class_id; + pub mod nick_name; + +// https://qiita.com/yohei_takada201/items/eaf28d33f29384b6e8b4 +/// print all classes for debug +pub fn preview_all_classes() { + // count = objc_util.objc_getClassList(None, 0) + // print( '%d classes found:' % count ) + + let count = objc::runtime::AnyClass::classes_count(); + println!("classes_count: {:?}", count); + + // classes = (objc_util.c_void_p * count)() + // count = objc_util.objc_getClassList(classes, count) + let mut classes: Vec = Vec::with_capacity(count); + let count = unsafe { objc_sys::objc_getClassList(classes.as_mut_ptr(), count as i32) }; + unsafe { classes.set_len(count as usize) }; + + println!("classes_count: {:?}", count); + + let class_names = classes + .iter() + .map(|class| { + let name = unsafe { CStr::from_ptr(objc_sys::class_getName(*class)) }; + name.to_string_lossy().into_owned() + }) + .collect::>(); + + println!("classes: {:?}", class_names); +} diff --git a/rust/macos/objc/nick_name.rs b/rust/macos/objc/nick_name.rs index 2ffbcf4..d6c5728 100644 --- a/rust/macos/objc/nick_name.rs +++ b/rust/macos/objc/nick_name.rs @@ -4,12 +4,16 @@ use std::ffi::CStr; use std::fmt::Debug; use std::fmt::Formatter; use std::os::unix::ffi::OsStrExt; +use std::os::unix::process::CommandExt; use std::sync::Arc; use std::sync::RwLock; +use libc::sysctlbyname; use objc::{class, msg_send}; use crate::macos::util::id; + +use super::preview_all_classes; const _POSIX_HOST_NAME_MAX: libc::c_long = 255; pub struct NickName(pub Arc>); @@ -20,21 +24,45 @@ impl Debug for NickName { } } +#[link(name = "AppKit", kind = "framework")] +extern "system" { + static NSImageNameComputer: *const std::ffi::c_char; +} + impl NickName { pub fn new() -> crate::Result { + preview_all_classes(); + + let name = unsafe { CStr::from_ptr(NSImageNameComputer.into()) }; + + println!("global name: {}", name.to_str().unwrap()); + Ok(Self(Arc::new(RwLock::new(unsafe { // Create an instance of the UIDevice class - let superclass = class!(NSApplication); - + let superclass = class!(NSObject); // デバッグ用にsuperclassの情報を出力する println!("superclass: {:?}", superclass); - msg_send![class!(NSApplication), sharedApplication] + // let panel = class!(NSWindow); + // println!("panel: {:?}", panel); + + objc::runtime::AnyClass::get("NSObject").unwrap(); + + let mut cmd = std::process::Command::new("scutil --get ComputerName"); + let out = cmd.output().unwrap().stdout; + let out = String::from_utf8(out).unwrap(); + println!("out: {}", out); + + msg_send![class!(NSObject), alloc] })))) } pub fn get(&self) -> crate::Result { let hostname = self.get_hostname()?; + + let name = self.get_name()?; + println!("name: {}", name); + Ok(hostname) } @@ -62,9 +90,59 @@ impl NickName { } } + fn get_name(&self) -> crate::Result { + let mut mib: [libc::c_int; 2] = [0, 0]; + let mut len: libc::size_t = 0; + + mib[0] = libc::CTL_KERN; + mib[1] = libc::KERN_HOSTNAME; + + let result = unsafe { + sysctlbyname( + "kern.hostname\0".as_ptr() as *const libc::c_char, + std::ptr::null_mut(), + &mut len, + std::ptr::null_mut(), + 0, + ) + }; + + if result != 0 { + return Err(std::io::Error::last_os_error().into()); + } + + let mut hostname_buffer: Vec = vec![0; len + 1]; + + let result = unsafe { + sysctlbyname( + "kern.hostname\0".as_ptr() as *const libc::c_char, + hostname_buffer.as_mut_ptr() as *mut libc::c_void, + &mut len, + std::ptr::null_mut(), + 0, + ) + }; + + if result != 0 { + return Err(std::io::Error::last_os_error().into()); + } + + let hostname_cstr = + unsafe { CStr::from_ptr(hostname_buffer.as_ptr() as *const libc::c_char) }; + let hostname = hostname_cstr.to_str().unwrap(); + + Ok(hostname.into()) + } + pub fn set>(&self, nickname: S) -> crate::Result<()> { let nickname: String = nickname.into(); self.set_hostname(nickname)?; + + let name = self.get_name()?; + println!("name: {}", name); + + + Ok(()) }