### Basic NSApplication Setup in Rust (fullscreen.rs) Source: https://docs.rs/cocoa/latest/cocoa/foundation/trait.NSString Demonstrates the basic setup for an NSApplication, including creating the menu bar and an application menu with a quit option. This code is a snippet from the fullscreen.rs example and relies on AppKit. ```rust let _pool = NSAutoreleasePool::new(nil); let app = NSApp(); app.setActivationPolicy_(NSApplicationActivationPolicyRegular); // create Menu Bar let menubar = NSMenu::new(nil).autorelease(); let app_menu_item = NSMenuItem::new(nil).autorelease(); menubar.addItem_(app_menu_item); app.setMainMenu_(menubar); // create Application menu let app_menu = NSMenu::new(nil).autorelease(); let quit_prefix = NSString::alloc(nil).init_str("Quit "); let quit_title = quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); let quit_action = selector("terminate:"); let quit_key = NSString::alloc(nil).init_str("q"); ``` -------------------------------- ### Rust Cocoa Fullscreen Window Setup Source: https://docs.rs/cocoa/latest/src/fullscreen/fullscreen.rs This Rust code snippet initializes a Cocoa application, sets up a menu bar, and creates a main window. It configures the application's activation policy and creates a basic application menu with a 'Quit' option. It also defines a custom `NSWindowDelegate` to manage fullscreen presentation options. ```rust #![allow(deprecated)] // the cocoa crate is deprecated use cocoa::appkit::{ NSApp, NSApplication, NSApplicationActivateIgnoringOtherApps, NSApplicationActivationPolicyRegular, NSApplicationPresentationOptions, NSBackingStoreBuffered, NSMenu, NSMenuItem, NSRunningApplication, NSWindow, NSWindowCollectionBehavior, NSWindowStyleMask, }; use cocoa::base::{id, nil, selector, NO}; use cocoa::foundation::{ NSAutoreleasePool, NSPoint, NSProcessInfo, NSRect, NSSize, NSString, NSUInteger, }; use core_graphics::display::CGDisplay; use objc::declare::ClassDecl; use objc::runtime::{Object, Sel}; use objc::{class, msg_send, sel, sel_impl}; fn main() { unsafe { let _pool = NSAutoreleasePool::new(nil); let app = NSApp(); app.setActivationPolicy_(NSApplicationActivationPolicyRegular); // create Menu Bar let menubar = NSMenu::new(nil).autorelease(); let app_menu_item = NSMenuItem::new(nil).autorelease(); menubar.addItem_(app_menu_item); app.setMainMenu_(menubar); // create Application menu let app_menu = NSMenu::new(nil).autorelease(); let quit_prefix = NSString::alloc(nil).init_str("Quit "); let quit_title = quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); let quit_action = selector("terminate:"); let quit_key = NSString::alloc(nil).init_str("q"); let quit_item = NSMenuItem::alloc(nil) .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key) .autorelease(); app_menu.addItem_(quit_item); app_menu_item.setSubmenu_(app_menu); // Create NSWindowDelegate let superclass = class!(NSObject); let mut decl = ClassDecl::new("MyWindowDelegate", superclass).unwrap(); extern "C" fn will_use_fillscreen_presentation_options( _: &Object, _: Sel, _: id, _: NSUInteger, ) -> NSUInteger { // Set initial presentation options for fullscreen let options = NSApplicationPresentationOptions::NSApplicationPresentationFullScreen | NSApplicationPresentationOptions::NSApplicationPresentationHideDock | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar | NSApplicationPresentationOptions::NSApplicationPresentationDisableProcessSwitching; options.bits() } extern "C" fn window_entering_fullscreen(_: &Object, _: Sel, _: id) { // Reset HideDock and HideMenuBar settings during/after we entered fullscreen. let options = NSApplicationPresentationOptions::NSApplicationPresentationHideDock | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar; unsafe { NSApp().setPresentationOptions_(options); } } decl.add_method( sel!(window:willUseFullScreenPresentationOptions:), will_use_fillscreen_presentation_options as extern "C" fn(&Object, Sel, id, NSUInteger) -> NSUInteger, ); decl.add_method( sel!(windowWillEnterFullScreen:), window_entering_fullscreen as extern "C" fn(&Object, Sel, id), ); decl.add_method( sel!(windowDidEnterFullScreen:), window_entering_fullscreen as extern "C" fn(&Object, Sel, id), ); let delegate_class = decl.register(); let delegate_object = msg_send![delegate_class, new]; // create Window let display = CGDisplay::main(); let size = NSSize::new(display.pixels_wide() as _, display.pixels_high() as _); let window = NSWindow::alloc(nil) .initWithContentRect_styleMask_backing_defer_( NSRect::new(NSPoint::new(0., 0.), size), NSWindowStyleMask::NSTitledWindowMask, NSBackingStoreBuffered, NO, ) .autorelease(); window.setDelegate_(delegate_object); let title = NSString::alloc(nil).init_str("Fullscreen!"); window.setTitle_(title); window.makeKeyAndOrderFront_(nil); let current_app = NSRunningApplication::currentApplication(nil); current_app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps); window.setCollectionBehavior_( NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenPrimary, ); window.toggleFullScreen_(nil); app.run(); } } ``` -------------------------------- ### Create and Configure AppKit Application and Window in Rust Source: https://docs.rs/cocoa/latest/cocoa/appkit/fn.NSApp This example demonstrates the initialization of an AppKit application and a main window in Rust. It sets up the application's activation policy, creates a menu bar, and configures a basic window with standard style masks. It's a foundational example for creating macOS applications with Rust. ```rust fn main() { unsafe { let _pool = NSAutoreleasePool::new(nil); let app = NSApp(); app.setActivationPolicy_(NSApplicationActivationPolicyRegular); let menubar = NSMenu::new(nil).autorelease(); let app_menu_item = NSMenuItem::new(nil).autorelease(); menubar.addItem_(app_menu_item); app.setMainMenu_(menubar); let app_menu = NSMenu::new(nil).autorelease(); let quit_prefix = NSString::alloc(nil).init_str("Quit "); let quit_title = quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); let quit_action = selector("terminate:"); let quit_key = NSString::alloc(nil).init_str("q"); let quit_item = NSMenuItem::alloc(nil).initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key).autorelease(); app_menu.addItem_(quit_item); app_menu_item.setSubmenu_(app_menu); let clear = NSColor::clearColor(nil); let window = NSWindow::alloc(nil).initWithContentRect_styleMask_backing_defer_(NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), NSWindowStyleMask::NSTitledWindowMask | NSWindowStyleMask::NSClosableWindowMask | NSWindowStyleMask::NSResizableWindowMask | NSWindowStyleMask::NSMiniaturizableWindowMask | NSWindowStyleMask::NSUnifiedTitleAndToolbarWindowMask, NSBackingStoreType::NSBackingStoreBuffered, NO).autorelease(); window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.)); window.setTitle_(NSString::alloc(nil).init_str("NSVisualEffectView_blur")); window.setBackgroundColor_(clear); window.makeKeyAndOrderFront_(nil); apply_blur_effect(window); app.run(); } } ``` -------------------------------- ### Rustdoc: Include function example in documentation Source: https://docs.rs/cocoa/latest/scrape-examples-help This Rust code demonstrates how a public function in `src/lib.rs` can have its usage documented via an example in `examples/ex.rs`. Rustdoc automatically scrapes these examples to be included in the generated documentation for the function. ```rust // src/lib.rs pub fn a_func() {} ``` ```rust // examples/ex.rs fn main() { a_crate::a_func(); } ``` -------------------------------- ### Post Event at Start with NSRunningApplication in Rust Source: https://docs.rs/cocoa/latest/src/cocoa/appkit.rs This function posts an event at the start of an application's process using Rust. It takes an `id` for the event and a `BOOL` flag indicating if it should be at the start. Ensure the event and flag are correctly typed. ```rust impl NSRunningApplication for id { // ... other methods unsafe fn postEvent_atStart_(self, anEvent: id, flag: BOOL) { msg_send![self, postEvent:anEvent atStart:flag] } // ... other methods } ``` -------------------------------- ### Window Sizing and Resizing Source: https://docs.rs/cocoa/latest/src/cocoa/appkit.rs APIs for setting and getting window dimensions, aspect ratios, and resizing behavior. ```APIDOC ## Window Sizing and Resizing ### Description Methods to control the size, aspect ratio, and resizing increments of a window. ### Methods - **`setFrame_(display:animate:)`** - **Description**: Sets the window's frame, optionally with animation. - **Method**: `unsafe fn setFrame_display_animate_(self, windowFrame: NSRect, display: BOOL, animate: BOOL)` - **`aspectRatio()`** - **Description**: Gets the window's aspect ratio. - **Method**: `unsafe fn aspectRatio(self) -> NSSize` - **`setAspectRatio_(aspectRatio:)`** - **Description**: Sets the window's aspect ratio. - **Method**: `unsafe fn setAspectRatio_(self, aspectRatio: NSSize)` - **`minSize()`** - **Description**: Gets the minimum size of the window. - **Method**: `unsafe fn minSize(self) -> NSSize` - **`setMinSize_(minSize:)`** - **Description**: Sets the minimum size of the window. - **Method**: `unsafe fn setMinSize_(self, minSize: NSSize)` - **`maxSize()`** - **Description**: Gets the maximum size of the window. - **Method**: `unsafe fn maxSize(self) -> NSSize` - **`setMaxSize_(maxSize:)`** - **Description**: Sets the maximum size of the window. - **Method**: `unsafe fn setMaxSize_(self, maxSize: NSSize)` - **`resizeIncrements()`** - **Description**: Gets the resize increments for the window. - **Method**: `unsafe fn resizeIncrements(self) -> NSSize` - **`setResizeIncrements_(resizeIncrements:)`** - **Description**: Sets the resize increments for the window. - **Method**: `unsafe fn setResizeIncrements_(self, resizeIncrements: NSSize)` - **`preservesContentDuringLiveResize()`** - **Description**: Checks if the window preserves content during live resize. - **Method**: `unsafe fn preservesContentDuringLiveResize(self) -> BOOL` - **`setPreservesContentDuringLiveResize_(preservesContentDuringLiveResize:)`** - **Description**: Sets whether the window preserves content during live resize. - **Method**: `unsafe fn setPreservesContentDuringLiveResize_(self, preservesContentDuringLiveResize: BOOL)` - **`inLiveResize()`** - **Description**: Checks if the window is currently in a live resize operation. - **Method**: `unsafe fn inLiveResize(self) -> BOOL` ``` -------------------------------- ### Window Size Management Source: https://docs.rs/cocoa/latest/src/cocoa/appkit.rs Methods for getting and setting the content size and resize increments of a window. ```APIDOC ## Window Size Management ### Description Methods for managing the content size and resize increments of an `NSWindow`. ### Methods - **`contentMaxSize`** - **Description**: Returns the maximum size of the window's content area. - **Method**: `GET` - **Endpoint**: Not applicable (instance method) - **`setContentMaxSize:`** - **Description**: Sets the maximum size of the window's content area. - **Method**: `POST` - **Endpoint**: Not applicable (instance method) - **Parameters**: - **`contentMaxSize`** (`NSSize`) - The new maximum size for the content area. - **`contentResizeIncrements`** - **Description**: Returns the window's resize increments. - **Method**: `GET` - **Endpoint**: Not applicable (instance method) - **`setContentResizeIncrements:`** - **Description**: Sets the window's resize increments. - **Method**: `POST` - **Endpoint**: Not applicable (instance method) - **Parameters**: - **`contentResizeIncrements`** (`NSSize`) - The new resize increments. ### Request Example (setContentMaxSize:) ```swift let newMaxSize = NSSize(width: 800, height: 600) window.setContentMaxSize(newMaxSize) ``` ### Response Example (contentMaxSize) ```swift let maxSize: NSSize = window.contentMaxSize() // maxSize will contain the current maximum content size ``` ``` -------------------------------- ### Basic Hello World Application Setup (Rust) Source: https://docs.rs/cocoa/latest/cocoa/foundation/struct.NSRect This code snippet sets up a basic NSApplication for a 'Hello World' application. It configures the activation policy, creates a menu bar with an application menu, and initializes the main application event loop. This serves as a foundation for simple macOS applications. ```rust fn main() { unsafe { let _pool = NSAutoreleasePool::new(nil); let app = NSApp(); app.setActivationPolicy_(NSApplicationActivationPolicyRegular); // create Menu Bar let menubar = NSMenu::new(nil).autorelease(); let app_menu_item = NSMenuItem::new(nil).autorelease(); menubar.addItem_(app_menu_item); app.setMainMenu_(menubar); // create Application menu let app_menu = NSMenu::new(nil).autorelease(); let quit_prefix = NSString::alloc(nil).init_str("Quit "); let quit_title = quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); let quit_action = selector("terminate:"); let quit_key = NSString::alloc(nil).init_str("q"); let quit_item = NSMenuItem::alloc(nil) ``` -------------------------------- ### Deprecated CARenderer Methods (Rust) Source: https://docs.rs/cocoa/latest/cocoa/quartzcore/struct.CARenderer Provides examples of deprecated methods for the CARenderer struct in Rust. These methods are marked as deprecated and recommend using the 'objc2-quartz-core' crate. Includes methods for getting IDs, creating from CGL contexts and Metal textures, managing layers, bounds, frames, and rendering. ```rust pub fn id(&self) -> id // Deprecated: use the objc2-quartz-core crate instead ``` ```rust pub unsafe fn from_cgl_context( context: CGLContextObj, color_space: Option, ) -> CARenderer // Deprecated: use the objc2-quartz-core crate instead ``` ```rust pub unsafe fn from_metal_texture( metal_texture: id, metal_command_queue: id, color_space: Option, ) -> CARenderer // Deprecated: use the objc2-quartz-core crate instead ``` ```rust pub fn layer(&self) -> Option // Deprecated: use the objc2-quartz-core crate instead ``` ```rust pub fn set_layer(&self, layer: Option) // Deprecated: use the objc2-quartz-core crate instead ``` ```rust pub fn bounds(&self) -> CGRect // Deprecated: use the objc2-quartz-core crate instead ``` ```rust pub fn set_bounds(&self, bounds: CGRect) // Deprecated: use the objc2-quartz-core crate instead ``` ```rust pub fn begin_frame_at( &self, time: CFTimeInterval, timestamp: Option<&CVTimeStamp>, ) // Deprecated: use the objc2-quartz-core crate instead ``` ```rust pub fn update_bounds(&self) -> CGRect // Deprecated: use the objc2-quartz-core crate instead ``` ```rust pub fn add_update_rect(&self, rect: CGRect) // Deprecated: use the objc2-quartz-core crate instead ``` ```rust pub fn render(&self) // Deprecated: use the objc2-quartz-core crate instead ``` ```rust pub fn next_frame_time(&self) -> CFTimeInterval // Deprecated: use the objc2-quartz-core crate instead ``` ```rust pub fn end_frame(&self) // Deprecated: use the objc2-quartz-core crate instead ``` ```rust pub unsafe fn set_destination(&self, metal_texture: id) // Deprecated: use the objc2-quartz-core crate instead ``` -------------------------------- ### Rust Cocoa: Create 'Hello World' App with Window and Menu Source: https://docs.rs/cocoa/latest/src/hello_world/hello_world.rs This Rust code snippet utilizes the `cocoa` crate to build a simple macOS application. It sets up the application's activation policy, creates a main menu bar with a 'Quit' option, and presents a basic titled window. It requires the `cocoa` crate and is intended for macOS. ```rust #![allow(deprecated)] // the cocoa crate is deprecated use cocoa::appkit::{ NSApp, NSApplication, NSApplicationActivateIgnoringOtherApps, NSApplicationActivationPolicyRegular, NSBackingStoreBuffered, NSMenu, NSMenuItem, NSRunningApplication, NSWindow, NSWindowStyleMask, }; use cocoa::base::{nil, selector, NO}; use cocoa::foundation::{NSAutoreleasePool, NSPoint, NSProcessInfo, NSRect, NSSize, NSString}; fn main() { unsafe { let _pool = NSAutoreleasePool::new(nil); let app = NSApp(); app.setActivationPolicy_(NSApplicationActivationPolicyRegular); // create Menu Bar let menubar = NSMenu::new(nil).autorelease(); let app_menu_item = NSMenuItem::new(nil).autorelease(); menubar.addItem_(app_menu_item); app.setMainMenu_(menubar); // create Application menu let app_menu = NSMenu::new(nil).autorelease(); let quit_prefix = NSString::alloc(nil).init_str("Quit "); let quit_title = quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); let quit_action = selector("terminate:"); let quit_key = NSString::alloc(nil).init_str("q"); let quit_item = NSMenuItem::alloc(nil) .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key) .autorelease(); app_menu.addItem_(quit_item); app_menu_item.setSubmenu_(app_menu); // create Window let window = NSWindow::alloc(nil) .initWithContentRect_styleMask_backing_defer_( NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), NSWindowStyleMask::NSTitledWindowMask, NSBackingStoreBuffered, NO, ) .autorelease(); window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.)); window.center(); let title = NSString::alloc(nil).init_str("Hello World!"); window.setTitle_(title); window.makeKeyAndOrderFront_(nil); let current_app = NSRunningApplication::currentApplication(nil); current_app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps); app.run(); } } ``` -------------------------------- ### Start Periodic Events (Deprecated) Source: https://docs.rs/cocoa/latest/cocoa/appkit/trait.NSEvent Starts periodic event generation with specified delay and period. This method is deprecated. Consult the 'objc2-app-kit' crate for modern event scheduling. ```rust unsafe fn startPeriodicEventsAfterDelay_withPeriod_( _: Self, delaySeconds: NSTimeInterval, periodSeconds: NSTimeInterval, ) // Deprecated: use the objc2-app-kit crate instead ``` -------------------------------- ### Set Up Basic App Structure and Menu Bar in Rust Source: https://docs.rs/cocoa/latest/cocoa/appkit/trait.NSMenuItem This Rust code demonstrates the fundamental setup for a macOS application. It initializes the application, creates a menu bar with a quit option, and prepares the app to run. This is a common pattern for many AppKit applications. ```rust fn setup_app_and_menubar() { let _pool = NSAutoreleasePool::new(nil); let app = NSApp(); app.setActivationPolicy_(NSApplicationActivationPolicyRegular); let menubar = NSMenu::new(nil).autorelease(); let app_menu_item = NSMenuItem::new(nil).autorelease(); menubar.addItem_(app_menu_item); app.setMainMenu_(menubar); let app_menu = NSMenu::new(nil).autorelease(); let quit_prefix = NSString::alloc(nil).init_str("Quit "); let quit_title = quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); let quit_action = selector("terminate:"); let quit_key = NSString::alloc(nil).init_str("q"); let quit_item = NSMenuItem::alloc(nil) .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key) .autorelease(); app_menu.addItem_(quit_item); app_menu_item.setSubmenu_(app_menu); // ... rest of the app setup app.run(); } ``` -------------------------------- ### Create NSApplication and Window - Rust Source: https://docs.rs/cocoa/latest/cocoa/foundation/struct.NSPoint This Rust code snippet illustrates the creation of a basic macOS application using the `cocoa` crate. It sets the application's activation policy, creates a menu bar with an application menu, and sets up a main window with standard styling. The function `create_app` returns an `id` representing the application instance. ```rust fn create_app(title: id, content: id) -> id { let _pool = NSAutoreleasePool::new(nil); let app = NSApp(); app.setActivationPolicy_(NSApplicationActivationPolicyRegular); let menubar = NSMenu::new(nil).autorelease(); let app_menu_item = NSMenuItem::new(nil).autorelease(); menubar.addItem_(app_menu_item); app.setMainMenu_(menubar); let app_menu = NSMenu::new(nil).autorelease(); let quit_prefix = NSString::alloc(nil).init_str("Quit "); let quit_title = quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); let quit_action = selector("terminate:"); let quit_key = NSString::alloc(nil).init_str("q"); let quit_item = NSMenuItem::alloc(nil) .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key) .autorelease(); app_menu.addItem_(quit_item); app_menu_item.setSubmenu_(app_menu); let window = NSWindow::alloc(nil) .initWithContentRect_styleMask_backing_defer_( NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), NSWindowStyleMask::NSTitledWindowMask | NSWindowStyleMask::NSClosableWindowMask | NSWindowStyleMask::NSResizableWindowMask | NSWindowStyleMask::NSMiniaturizableWindowMask | NSWindowStyleMask::NSUnifiedTitleAndToolbarWindowMask, NSBackingStoreType::NSBackingStoreBuffered, NO, ) .autorelease(); window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.)); window.center(); window.setTitle_(title); window.makeKeyAndOrderFront_(nil); window.setContentView_(content); let current_app = NSRunningApplication::currentApplication(nil); current_app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps); app } ``` -------------------------------- ### Get and Set NSWindow Alpha Value (Objective-C/Rust) Source: https://docs.rs/cocoa/latest/cocoa/appkit/trait.NSWindow Allows getting and setting the alpha transparency value of an NSWindow. These functions are deprecated; use objc2-app-kit. ```Rust unsafe fn alphaValue(self) -> CGFloat ``` ```Rust unsafe fn setAlphaValue_(self, windowAlpha: CGFloat) ``` -------------------------------- ### Hello World Application with Menu and Window (Rust) Source: https://docs.rs/cocoa/latest/cocoa/appkit/fn.NSApp This Rust code snippet creates a simple 'Hello World' macOS application. It sets up the application, a menu bar with a quit option, and a basic titled window. The application then enters its main run loop. ```rust fn main() { unsafe { let _pool = NSAutoreleasePool::new(nil); let app = NSApp(); app.setActivationPolicy_(NSApplicationActivationPolicyRegular); // create Menu Bar let menubar = NSMenu::new(nil).autorelease(); let app_menu_item = NSMenuItem::new(nil).autorelease(); menubar.addItem_(app_menu_item); app.setMainMenu_(menubar); // create Application menu let app_menu = NSMenu::new(nil).autorelease(); let quit_prefix = NSString::alloc(nil).init_str("Quit "); let quit_title = quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); let quit_action = selector("terminate:"); let quit_key = NSString::alloc(nil).init_str("q"); let quit_item = NSMenuItem::alloc(nil) .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key) .autorelease(); app_menu.addItem_(quit_item); app_menu_item.setSubmenu_(app_menu); // create Window let window = NSWindow::alloc(nil) .initWithContentRect_styleMask_backing_defer_( NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), NSWindowStyleMask::NSTitledWindowMask, NSBackingStoreBuffered, NO, ) .autorelease(); window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.)); window.center(); let title = NSString::alloc(nil).init_str("Hello World!"); window.setTitle_(title); window.makeKeyAndOrderFront_(nil); let current_app = NSRunningApplication::currentApplication(nil); current_app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps); app.run(); } } ``` -------------------------------- ### Rust: Get and Set NSWindow Background Color Source: https://docs.rs/cocoa/latest/src/cocoa/appkit.rs Enables getting and setting the background color of an NSWindow. The color is represented by an `id` type, typically an `NSColor` object. These functions are unsafe as they perform direct Objective-C calls. ```rust unsafe fn backgroundColor(self) -> id { msg_send![self, backgroundColor] } ``` ```rust unsafe fn setBackgroundColor_(self, color: id) { msg_send![self, setBackgroundColor: color] } ``` -------------------------------- ### Initialize NSApplication and Menu - Rust Source: https://docs.rs/cocoa/latest/cocoa/foundation/struct.NSPoint This Rust code snippet shows the initialization of a macOS application and its main menu using the `cocoa` crate. It creates an `NSApplication` instance, sets its activation policy, and constructs a menu bar with a basic application menu containing a quit item. This is a foundational part of setting up a GUI application. ```rust let _pool = NSAutoreleasePool::new(nil); let app = NSApp(); app.setActivationPolicy_(NSApplicationActivationPolicyRegular); let menubar = NSMenu::new(nil).autorelease(); let app_menu_item = NSMenuItem::new(nil).autorelease(); menubar.addItem_(app_menu_item); app.setMainMenu_(menubar); let app_menu = NSMenu::new(nil).autorelease(); let quit_prefix = NSString::alloc(nil).init_str("Quit "); let quit_title = quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); let quit_action = selector("terminate:"); let quit_key = NSString::alloc(nil).init_str("q"); let quit_item = NSMenuItem::alloc(nil) .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key) .autorelease(); ``` -------------------------------- ### Manage Periodic Events in Rust/Cocoa Source: https://docs.rs/cocoa/latest/src/cocoa/appkit.rs These functions provide the ability to start and stop periodic events. `startPeriodicEventsAfterDelay_withPeriod_` starts a timer that fires periodically after an initial delay, while `stopPeriodicEvents` cancels the periodic events. These functions are crucial for tasks that require repeated execution over time. ```rust unsafe fn startPeriodicEventsAfterDelay_withPeriod_( _: Self, delaySeconds: NSTimeInterval, periodSeconds: NSTimeInterval, ); unsafe fn stopPeriodicEvents(_: Self); ``` -------------------------------- ### Rust: Example of Creating and Managing NSTabViewItems Source: https://docs.rs/cocoa/latest/cocoa/appkit/trait.NSTabViewItem Demonstrates how to create a `NSTabView` and populate it with multiple `NSTabViewItem` instances in Rust. This example showcases initializing tab view items with identifiers and labels, adding them to the tab view, and then running the application. It utilizes unsafe blocks for direct interaction with Cocoa APIs. ```rust fn main() { unsafe { // create a tab View let tab_view = NSTabView::new(nil) .initWithFrame_(NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.))); // create a tab view item let tab_view_item = NSTabViewItem::new(nil).initWithIdentifier_(NSString::alloc(nil).init_str("TabView1")); tab_view_item.setLabel_(NSString::alloc(nil).init_str("Tab view item 1")); tab_view.addTabViewItem_(tab_view_item); // create a second tab view item let tab_view_item2 = NSTabViewItem::new(nil).initWithIdentifier_(NSString::alloc(nil).init_str("TabView2")); tab_view_item2.setLabel_(NSString::alloc(nil).init_str("Tab view item 2")); tab_view.addTabViewItem_(tab_view_item2); // Create the app and set the content. let app = create_app(NSString::alloc(nil).init_str("Tab View"), tab_view); app.run(); } } ``` -------------------------------- ### Create Application with Menu and Configurable Window (Rust) Source: https://docs.rs/cocoa/latest/cocoa/appkit/fn.NSApp This Rust code snippet sets up a macOS application with a menu bar, including a 'Quit' option, and creates a window with various style masks for title, closing, resizing, and miniaturization. It's a more advanced setup than the basic 'Hello World'. ```rust unsafe fn create_app(title: id, content: id) -> id { let _pool = NSAutoreleasePool::new(nil); let app = NSApp(); app.setActivationPolicy_(NSApplicationActivationPolicyRegular); // create Menu Bar let menubar = NSMenu::new(nil).autorelease(); let app_menu_item = NSMenuItem::new(nil).autorelease(); menubar.addItem_(app_menu_item); app.setMainMenu_(menubar); // create Application menu let app_menu = NSMenu::new(nil).autorelease(); let quit_prefix = NSString::alloc(nil).init_str("Quit "); let quit_title = quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); let quit_action = selector("terminate:"); let quit_key = NSString::alloc(nil).init_str("q"); let quit_item = NSMenuItem::alloc(nil) .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key) .autorelease(); app_menu.addItem_(quit_item); app_menu_item.setSubmenu_(app_menu); // create Window let window = NSWindow::alloc(nil) .initWithContentRect_styleMask_backing_defer_( NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), NSWindowStyleMask::NSTitledWindowMask | NSWindowStyleMask::NSClosableWindowMask | NSWindowStyleMask::NSResizableWindowMask | NSWindowStyleMask::NSMiniaturizableWindowMask | NSWindowStyleMask::NSUnifiedTitleAndToolbarWindowMask, NSBackingStoreType::NSBackingStoreBuffered, NO, ) .autorelease(); window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.)); ``` -------------------------------- ### Manage Window Tabbing in Rust Source: https://docs.rs/cocoa/latest/src/cocoa/appkit.rs These functions manage window tabbing. `allowsAutomaticWindowTabbing` and `setAllowsAutomaticWindowTabbing_` get and set automatic window tabbing. `tabbingIdentifier` retrieves the tabbing identifier, `tabbingMode` gets the tabbing mode, `setTabbingMode_` sets the mode, `addTabbedWindow_ordered_` adds a tabbed window, and `toggleTabBar_` toggles the tab bar. ```rust unsafe fn allowsAutomaticWindowTabbing(_: Self) -> BOOL { msg_send![class!(NSWindow), allowsAutomaticWindowTabbing] } unsafe fn setAllowsAutomaticWindowTabbing_(_: Self, allowsAutomaticWindowTabbing: BOOL) { msg_send![ class!(NSWindow), setAllowsAutomaticWindowTabbing: allowsAutomaticWindowTabbing ] } unsafe fn tabbingIdentifier(self) -> id { msg_send![self, tabbingIdentifier] } unsafe fn tabbingMode(self) -> NSWindowTabbingMode { msg_send!(self, tabbingMode) } unsafe fn setTabbingMode_(self, tabbingMode: NSWindowTabbingMode) { msg_send![self, setTabbingMode: tabbingMode] } unsafe fn addTabbedWindow_ordered_(self, window: id, ordering_mode: NSWindowOrderingMode) { msg_send![self, addTabbedWindow:window ordered: ordering_mode] } unsafe fn toggleTabBar_(self, sender: id) { msg_send![self, toggleTabBar: sender] } ``` -------------------------------- ### Create and Show a Basic Window in Rust Source: https://docs.rs/cocoa/latest/cocoa/appkit/trait.NSMenuItem Demonstrates how to create a basic macOS window with a title and content view using Rust and AppKit. It also activates the application and makes the window visible. Dependencies include AppKit and Foundation frameworks. ```rust fn create_and_show_window(title: &str, content: id) -> id { window.center(); window.setTitle_(title); window.makeKeyAndOrderFront_(nil); window.setContentView_(content); let current_app = NSRunningApplication::currentApplication(nil); current_app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps); app } ``` -------------------------------- ### Create and Display a Basic Window in Rust Source: https://docs.rs/cocoa/latest/cocoa/appkit/trait.NSMenuItem Demonstrates how to create a basic application window with a title and content view in Rust using the AppKit framework. It initializes the application, sets up a menu bar, creates a window with standard style masks, and displays it. Dependencies include `std` and `objc` crates. ```rust fn main() { unsafe { let _pool = NSAutoreleasePool::new(nil); let app = NSApp(); app.setActivationPolicy_(NSApplicationActivationPolicyRegular); let menubar = NSMenu::new(nil).autorelease(); let app_menu_item = NSMenuItem::new(nil).autorelease(); menubar.addItem_(app_menu_item); app.setMainMenu_(menubar); let app_menu = NSMenu::new(nil).autorelease(); let quit_prefix = NSString::alloc(nil).init_str("Quit "); let quit_title = quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); let quit_action = selector("terminate:"); let quit_key = NSString::alloc(nil).init_str("q"); let quit_item = NSMenuItem::alloc(nil) .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key) .autorelease(); app_menu.addItem_(quit_item); app_menu_item.setSubmenu_(app_menu); let clear = NSColor::clearColor(nil); let window = NSWindow::alloc(nil) .initWithContentRect_styleMask_backing_defer_( NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), NSWindowStyleMask::NSTitledWindowMask | NSWindowStyleMask::NSClosableWindowMask | NSWindowStyleMask::NSResizableWindowMask | NSWindowStyleMask::NSMiniaturizableWindowMask | NSWindowStyleMask::NSUnifiedTitleAndToolbarWindowMask, NSBackingStoreType::NSBackingStoreBuffered, NO, ) .autorelease(); window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.)); window.setTitle_(NSString::alloc(nil).init_str("NSVisualEffectView_blur")); window.setBackgroundColor_(clear); window.makeKeyAndOrderFront_(nil); let ns_view = window.contentView(); let bounds = NSView::bounds(ns_view); let blurred_view = NSVisualEffectView::initWithFrame_(NSVisualEffectView::alloc(nil), bounds); blurred_view.autorelease(); blurred_view.setMaterial_(NSVisualEffectMaterial::HudWindow); blurred_view.setBlendingMode_(NSVisualEffectBlendingMode::BehindWindow); blurred_view.setState_(NSVisualEffectState::FollowsWindowActiveState); blurred_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable); let _: () = msg_send![ns_view, addSubview: blurred_view positioned: NSWindowOrderingMode::NSWindowBelow relativeTo: 0]; app.run(); } } ``` -------------------------------- ### CornerMask Default and Initialization Source: https://docs.rs/cocoa/latest/cocoa/quartzcore/struct.CornerMask Information on how to get the default value for CornerMask. ```APIDOC ## GET /websites/rs_cocoa/CornerMask/default ### Description Returns the default value for the CornerMask type. ### Method GET ### Endpoint /websites/rs_cocoa/CornerMask/default ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **default_value** (CornerMask) - The default CornerMask value. #### Response Example ```json { "default_value": "[default corner mask value]" } ``` ``` -------------------------------- ### Create Windows in Cocoa (Rust) Source: https://docs.rs/cocoa/latest/src/cocoa/appkit.rs Defines functions to create and initialize NSWindow instances. It includes methods to initialize a window with a specified content rectangle, style mask, backing store type, and deferral option. There are options to specify the screen on which the window is created. ```rust unsafe fn initWithContentRect_styleMask_backing_defer_( self, rect: NSRect, style: NSWindowStyleMask, backing: NSBackingStoreType, defer: BOOL, ) -> id { msg_send![self, initWithContentRect:rect styleMask:style.bits() backing:backing as NSUInteger defer:defer] } unsafe fn initWithContentRect_styleMask_backing_defer_screen_( self, rect: NSRect, style: NSWindowStyleMask, backing: NSBackingStoreType, defer: BOOL, screen: id, ) -> id { msg_send![self, initWithContentRect:rect styleMask:style.bits() backing:backing as NSUInteger defer:defer screen:screen] } ``` -------------------------------- ### NSOpenGLContext Management in Rust Source: https://docs.rs/cocoa/latest/src/cocoa/appkit.rs This Rust code demonstrates several methods for managing an NSOpenGLContext. It covers clearing the current context, getting the current context, making a context current, setting the view, getting the view, clearing the drawable, updating, flushing the buffer. These methods are vital for controlling the OpenGL rendering pipeline within a Cocoa application. ```rust unsafe fn clearCurrentContext(_: Self) { msg_send![class!(NSOpenGLContext), clearCurrentContext] } unsafe fn currentContext(_: Self) -> id /* (NSOpenGLContext *) */ { msg_send![class!(NSOpenGLContext), currentContext] } unsafe fn makeCurrentContext(self) { msg_send![self, makeCurrentContext] } unsafe fn setView_(self, view: id /* (NSView *) */) { msg_send![self, setView: view] } unsafe fn view(self) -> id /* (NSView *) */ { msg_send![self, view] } unsafe fn clearDrawable(self) { msg_send![self, clearDrawable] } unsafe fn update(self) { msg_send![self, update] } unsafe fn flushBuffer(self) { msg_send![self, flushBuffer] } ``` -------------------------------- ### NSApplication Methods Source: https://docs.rs/cocoa/latest/src/cocoa/appkit.rs Details the methods available for interacting with and controlling the shared application instance, including activation, event handling, and launching. ```APIDOC ## NSApplication Control ### Description Methods for managing the application's lifecycle, event loop, and presentation. ### Methods - `sharedApplication()`: Returns the singleton shared application instance. - `setActivationPolicy_(policy: NSApplicationActivationPolicy)`: Sets the application's activation policy. - `setPresentationOptions_(options: NSApplicationPresentationOptions)`: Sets the application's presentation options. - `presentationOptions()`: Retrieves the current presentation options. - `activateIgnoringOtherApps_(ignore: BOOL)`: Activates the application, optionally ignoring other applications. - `run()`: Starts the application's main event loop. - `finishLaunching()`: Completes the application's launch process. - `nextEventMatchingMask_untilDate_inMode_dequeue_()`: Retrieves the next event from the application's event queue. - `sendEvent_(an_event: id)`: Sends an event to the application. - `postEvent_atStart_(anEvent: id, flag: BOOL)`: Posts an event to be processed. - `stop_(sender: id)`: Stops the application. - `setApplicationIconImage_(image: id)`: Sets the application's icon image. - `requestUserAttention_(requestType: NSRequestUserAttentionType)`: Requests user attention. ### Endpoint N/A (Instance methods on `NSApplication`) ### Parameters - **policy** (`NSApplicationActivationPolicy`): The activation policy to set. - **options** (`NSApplicationPresentationOptions`): The presentation options to configure. - **ignore** (`BOOL`): If YES, other applications are ignored during activation. - **mask** (`NSUInteger`): Event mask for filtering events. - **expiration** (`id`): Date until which to wait for an event. - **in_mode** (`id`): The event processing mode. - **dequeue** (`BOOL`): Whether to remove the event from the queue after retrieval. - **an_event** (`id`): The event object to send or post. - **flag** (`BOOL`): A flag associated with posting an event. - **sender** (`id`): The object sending the stop message. - **image** (`id`): The image object for the application icon. - **requestType** (`NSRequestUserAttentionType`): The type of user attention requested. ### Request Example ```objectivec // Get the shared application instance let app = unsafe { NSApplication::sharedApplication(msg_send![class!(NSApplication), sharedApplication]) }; // Set presentation options app.setPresentationOptions_(NSApplicationPresentationOptions::NSApplicationPresentationFullScreen); // Request user attention app.requestUserAttention_(NSRequestUserAttentionType::NSCriticalRequest); ``` ### Response - **Success Response (Return Value)**: Varies by method. `setActivationPolicy_` and `setPresentationOptions_` return `BOOL`. `presentationOptions_` returns `NSApplicationPresentationOptions`. `nextEventMatchingMask_untilDate_inMode_dequeue_` returns an `id` representing the event. ``` -------------------------------- ### Create Basic Application Window in Rust Source: https://docs.rs/cocoa/latest/cocoa/foundation/trait.NSString This example shows how to create a simple macOS application window with a title and a basic menu using Rust and RS Cocoa. It initializes the application, sets up the menu bar with a quit option, and creates a main window. ```Rust fn main() { unsafe { let _pool = NSAutoreleasePool::new(nil); let app = NSApp(); app.setActivationPolicy_(NSApplicationActivationPolicyRegular); // create Menu Bar let menubar = NSMenu::new(nil).autorelease(); let app_menu_item = NSMenuItem::new(nil).autorelease(); menubar.addItem_(app_menu_item); app.setMainMenu_(menubar); // create Application menu let app_menu = NSMenu::new(nil).autorelease(); let quit_prefix = NSString::alloc(nil).init_str("Quit "); let quit_title = quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); let quit_action = selector("terminate:"); let quit_key = NSString::alloc(nil).init_str("q"); let quit_item = NSMenuItem::alloc(nil) .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key) .autorelease(); app_menu.addItem_(quit_item); app_menu_item.setSubmenu_(app_menu); // create Window let window = NSWindow::alloc(nil) .initWithContentRect_styleMask_backing_defer_( NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), NSWindowStyleMask::NSTitledWindowMask, NSBackingStoreBuffered, NO, ) .autorelease(); window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.)); window.center(); let title = NSString::alloc(nil).init_str("Hello World!"); window.setTitle_(title); window.makeKeyAndOrderFront_(nil); let current_app = NSRunningApplication::currentApplication(nil); } } ``` -------------------------------- ### Periodic Event Management Source: https://docs.rs/cocoa/latest/src/cocoa/appkit.rs Methods to start and stop periodic event generation. ```APIDOC ## `startPeriodicEventsAfterDelay:withPeriod:` ### Description Starts the generation of periodic events after a specified delay and with a given interval. ### Method `POST` ### Endpoint `/websites/rs_cocoa/NSEvent/startPeriodicEvents` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **delaySeconds** (NSTimeInterval) - Required - The delay in seconds before the first event. - **periodSeconds** (NSTimeInterval) - Required - The interval in seconds between subsequent events. ### Request Example ```json { "delaySeconds": 1.0, "periodSeconds": 0.1 } ``` ### Response #### Success Response (200) No specific response body defined, indicates successful execution. #### Response Example ```json {} ``` ## `stopPeriodicEvents` ### Description Stops the generation of periodic events. ### Method `POST` ### Endpoint `/websites/rs_cocoa/NSEvent/stopPeriodicEvents` ### Parameters #### Path Parameters None #### Query Parameters None ### Response #### Success Response (200) No specific response body defined, indicates successful execution. #### Response Example ```json {} ``` ```