Skip to content

Commit

Permalink
Add data from winit
Browse files Browse the repository at this point in the history
  • Loading branch information
madsmtm committed Sep 3, 2023
1 parent a9ff910 commit 321693b
Show file tree
Hide file tree
Showing 11 changed files with 296 additions and 42 deletions.
248 changes: 248 additions & 0 deletions crates/header-translator/src/data/AppKit.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,253 @@
// Most of these are marked as MainThreadOnly automatically
data! {
// TODO: This should be one of MainThreadOnly or Immutable (+Send/Sync)
class NSAppearance {
unsafe -appearanceNamed;
unsafe -bestMatchFromAppearancesWithNames;
}

class NSApplication {
unsafe +sharedApplication;

unsafe -currentEvent;
unsafe -postEvent_atStart;
unsafe -presentationOptions;
unsafe -windows;
unsafe -keyWindow;
unsafe -setDelegate;
unsafe -setPresentationOptions;
unsafe -hide;
unsafe -orderFrontCharacterPalette;
unsafe -hideOtherApplications;
unsafe -stop;
unsafe -activateIgnoringOtherApps;
unsafe -requestUserAttention;
unsafe -setActivationPolicy;
unsafe -setMainMenu;
unsafe -effectiveAppearance;
unsafe -setAppearance;

// `run` cannot be safe, the user must ensure there is no re-entrancy.
}

// Documentation says:
// > Color objects are immutable and thread-safe
//
// TODO: Send + Sync
class NSColor: Immutable {
unsafe -clear;
}

class NSControl {
unsafe -isEnabled;
unsafe -setEnabled;
}

// NSCursor is immutable, stated here:
// https://developer.apple.com/documentation/appkit/nscursor/1527062-image?language=objc
//
// TODO: Send + Sync
class NSCursor: Immutable {
unsafe -initWithImage_hotSpot;

unsafe -arrowCursor;
unsafe -IBeamCursor;
unsafe -pointingHandCursor;
unsafe -closedHandCursor;
unsafe -openHandCursor;
unsafe -resizeLeftCursor;
unsafe -resizeRightCursor;
unsafe -resizeLeftRightCursor;
unsafe -resizeUpCursor;
unsafe -resizeDownCursor;
unsafe -resizeUpDownCursor;
unsafe -crosshairCursor;
unsafe -disappearingItemCursor;
unsafe -operationNotAllowedCursor;
unsafe -dragLinkCursor;
unsafe -dragCopyCursor;
unsafe -contextualMenuCursor;
unsafe -IBeamCursorForVerticalLayout;
}

// Since this is immutable, it _may_ be possible to make Send+Sync, but
// let's refrain from doing so, because of:
// > Safely handled only on the same thread, whether that be the main
// > thread or a secondary thread; otherwise you run the risk of having
// > events get out of sequence.
// <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CocoaFundamentals/AddingBehaviortoaCocoaProgram/AddingBehaviorCocoa.html#//apple_ref/doc/uid/TP40002974-CH5-SW47>
// <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html#//apple_ref/doc/uid/10000057i-CH12-123383>
class NSEvent: Immutable {

}

// Documented Thread-Unsafe, but:
// > One thread can create an NSImage object, draw to the image buffer,
// > and pass it off to the main thread for drawing. The underlying image
// > cache is shared among all threads.
// <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html#//apple_ref/doc/uid/10000057i-CH12-126728>
//
// So really only unsafe to mutate on several threads.
//
// Unsure yet if it would be beneficial to mark this as `Mutable`, or if
// we should just keep it as interiormutable?
class NSImage {
unsafe -initWithData;
unsafe -initByReferencingFile;
}

class NSMenu: MainThreadOnly {
unsafe -init;
unsafe -addItem;
}

// Any modification of the target or the action has to remain `unsafe`
class NSMenuItem: MainThreadOnly {
unsafe -init;
unsafe +separatorItem;
unsafe -setKeyEquivalentModifierMask;
unsafe -setSubmenu;
}

class NSPasteboard {
unsafe -propertyListForType;
}

// Documented as "Thread-Unsafe"
class NSResponder {}

// Accesses the shared application, and hence is main thread only (even
// though not marked so in Swift).
class NSScreen: MainThreadOnly {
unsafe +mainScreen;
unsafe +screens;
unsafe -frame;
unsafe -visibleFrame;
unsafe -deviceDescription;
unsafe -backingScaleFactor;
}

class NSWindowTabGroup: MainThreadOnly {
unsafe -windows;
unsafe -setSelectedWindow;
}

class NSTextInputContext: MainThreadOnly {
unsafe -invalidateCharacterCoordinates;
unsafe -discardMarkedText;
unsafe -selectedKeyboardInputSource;
}

// Subclasses `NSMutableAttributedString`, though I think this should
// actually be `InteriorMutable`?
class NSTextStorage: Mutable {}

// Documented as "Main Thread Only".
// > generally thread safe, although operations on views such as creating,
// > resizing, and moving should happen on the main thread.
// <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CocoaFundamentals/AddingBehaviortoaCocoaProgram/AddingBehaviorCocoa.html#//apple_ref/doc/uid/TP40002974-CH5-SW47>
//
// > If you want to use a thread to draw to a view, bracket all drawing code
// > between the lockFocusIfCanDraw and unlockFocus methods of NSView.
// <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html#//apple_ref/doc/uid/10000057i-CH12-123351-BBCFIIEB>
class NSView {
unsafe -frame;
unsafe -bounds;
unsafe -inputContext;
unsafe -visibleRect;
unsafe -hasMarkedText;
unsafe -convertPoint_fromView;
unsafe -window;

unsafe -setWantsBestResolutionOpenGLSurface;
unsafe -setWantsLayer;
unsafe -setPostsFrameChangedNotifications;
unsafe -removeTrackingRect;
unsafe -addCursorRect_cursor;
unsafe -setHidden;
}

// Documented as "Main Thread Only", but:
// > Thread safe in that you can create and manage them on a secondary
// > thread.
// <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CocoaFundamentals/AddingBehaviortoaCocoaProgram/AddingBehaviorCocoa.html#//apple_ref/doc/uid/TP40002974-CH5-SW47>
// <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html#//apple_ref/doc/uid/10000057i-CH12-123364>
//
// So could in theory be `Send`, and perhaps also `Sync` - but we would
// like interior mutability on windows, since that's just much easier, and
// in that case, they can't be!
class NSWindow {
// Initializers are not safe, since it is critical to memory safety
// that `window.setReleasedWhenClosed(false)` is called.

unsafe -frame;
unsafe -backingScaleFactor;
unsafe -contentView;
unsafe -setContentView;
unsafe -setInitialFirstResponder;
unsafe -makeFirstResponder;
unsafe -contentRectForFrameRect;
unsafe -screen;
unsafe -setContentSize;
unsafe -setFrameTopLeftPoint;
unsafe -setMinSize;
unsafe -setMaxSize;
unsafe -setResizeIncrements;
unsafe -contentResizeIncrements;
unsafe -setContentResizeIncrements;
unsafe -setFrame_display;
unsafe -setMovable;
unsafe -setSharingType;
unsafe -setTabbingMode;
unsafe -setOpaque;
unsafe -hasShadow;
unsafe -setHasShadow;
unsafe -setIgnoresMouseEvents;
unsafe -setBackgroundColor;
unsafe -styleMask;
unsafe -setStyleMask;
unsafe -registerForDraggedTypes;
unsafe -makeKeyAndOrderFront;
unsafe -orderFront;
unsafe -miniaturize;
unsafe -sender;
unsafe -toggleFullScreen;
unsafe -orderOut;
unsafe -zoom;
unsafe -selectNextKeyView;
unsafe -selectPreviousKeyView;
unsafe -firstResponder;
unsafe -standardWindowButton;
unsafe -setTitle;
unsafe -title;
unsafe -setAcceptsMouseMovedEvents;
unsafe -setTitlebarAppearsTransparent;
unsafe -setTitleVisibility;
unsafe -setMovableByWindowBackground;
unsafe -setLevel;
unsafe -setAllowsAutomaticWindowTabbing;
unsafe -setTabbingIdentifier;
unsafe -setDocumentEdited;
unsafe -occlusionState;
unsafe -center;
unsafe -isResizable;
unsafe -isMiniaturizable;
unsafe -hasCloseBox;
unsafe -isMiniaturized;
unsafe -isVisible;
unsafe -isKeyWindow;
unsafe -isZoomed;
unsafe -allowsAutomaticWindowTabbing;
unsafe -selectNextTab;
unsafe -tabbingIdentifier;
unsafe -tabGroup;
unsafe -isDocumentEdited;
unsafe -close;
unsafe -performWindowDragWithEvent;
unsafe -invalidateCursorRectsForView;
unsafe -setDelegate;
unsafe -sendEvent;

// `addChildWindow:ordered:` is not safe, as cycles must be prevented
}
}
8 changes: 5 additions & 3 deletions crates/header-translator/src/data/Foundation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,12 +139,12 @@ data! {
unsafe -setName;
}

class NSValue {
class NSValue: Immutable {
unsafe -objCType;
unsafe -isEqualToValue;
}

class NSUUID {
class NSUUID: Immutable {
unsafe +UUID;
unsafe -init;
unsafe -initWithUUIDString;
Expand Down Expand Up @@ -186,7 +186,7 @@ data! {
class NSIndexSet: ImmutableWithMutableSubclass<Foundation::NSMutableIndexSet> {}
class NSMutableIndexSet: MutableWithImmutableSuperclass<Foundation::NSIndexSet> {}

class NSNumber {
class NSNumber: Immutable {
unsafe -initWithChar;
unsafe -initWithUnsignedChar;
unsafe -initWithShort;
Expand Down Expand Up @@ -237,6 +237,8 @@ data! {
unsafe -stringValue;
}

class NSDecimalNumber: Immutable {}

class NSURLRequest: ImmutableWithMutableSubclass<Foundation::NSMutableURLRequest> {}
class NSMutableURLRequest: MutableWithImmutableSuperclass<Foundation::NSURLRequest> {}
}
3 changes: 3 additions & 0 deletions crates/header-translator/src/data/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ macro_rules! __set_mutability {
($data:expr; Mutable) => {
$data.mutability = $crate::stmt::Mutability::Mutable;
};
($data:expr; MainThreadOnly) => {
$data.mutability = $crate::stmt::Mutability::MainThreadOnly;
};
}

macro_rules! __data_inner {
Expand Down
6 changes: 5 additions & 1 deletion crates/header-translator/src/method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,11 @@ impl Method {
}

pub(crate) fn usable_in_default_id(&self) -> bool {
self.selector == "new" && self.is_class && self.arguments.is_empty() && self.safe
self.selector == "new"
&& self.is_class
&& self.arguments.is_empty()
&& self.safe
&& !self.mainthreadonly
}

fn parent_type_data(entity: &Entity<'_>, context: &Context<'_>) -> (bool, bool) {
Expand Down
1 change: 1 addition & 0 deletions crates/header-translator/translation-config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ tvos = "9.0"
[library.AppKit]
imports = ["CoreData", "Foundation"]
gnustep-library = "gnustep-gui"
additions = true
fixes = true
extra-features = [
# Temporary, since some structs and statics use these
Expand Down
3 changes: 1 addition & 2 deletions crates/icrate/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
let view = unsafe { NSView::initWithFrame(mtm.alloc(), frame) };
// Do something with `app` and `view`
```
* **BREAKING**: Changed the `NSApp` static to be a function taking `MainThreadMarker`.

### Removed
* **BREAKING**: Removed the `MainThreadMarker` argument from the closure
passed to `MainThreadBound::get_on_main`.
* **BREAKING**: Removed the `NSApp` static for now - it will likely be
re-added later in another form.


## icrate 0.0.4 - 2023-07-31
Expand Down
28 changes: 12 additions & 16 deletions crates/icrate/examples/browser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ declare_class!(

// create the window content view
let content_view = {
let frame_rect = unsafe { window.frame() };
let frame_rect = window.frame();
let this = unsafe { NSStackView::initWithFrame(mtm.alloc(), frame_rect) };
unsafe {
this.setOrientation(NSUserInterfaceLayoutOrientationVertical);
Expand Down Expand Up @@ -196,14 +196,14 @@ declare_class!(

// create the menu with a "quit" entry
unsafe {
let menu = NSMenu::initWithTitle(NSMenu::alloc(), ns_string!(""));
let menu = NSMenu::initWithTitle(mtm.alloc(), ns_string!(""));
let menu_app_item = NSMenuItem::initWithTitle_action_keyEquivalent(
NSMenuItem::alloc(),
mtm.alloc(),
ns_string!(""),
None,
ns_string!(""),
);
let menu_app_menu = NSMenu::initWithTitle(NSMenu::alloc(), ns_string!(""));
let menu_app_menu = NSMenu::initWithTitle(mtm.alloc(), ns_string!(""));
menu_app_menu.addItemWithTitle_action_keyEquivalent(
ns_string!("Quit"),
Some(sel!(terminate:)),
Expand All @@ -217,12 +217,10 @@ declare_class!(
}

// configure the window
unsafe {
window.setContentView(Some(&content_view));
window.center();
window.setTitle(ns_string!("browser example"));
window.makeKeyAndOrderFront(None);
}
window.setContentView(Some(&content_view));
window.center();
window.setTitle(ns_string!("browser example"));
window.makeKeyAndOrderFront(None);

// request the web view navigate to a page
unsafe {
Expand Down Expand Up @@ -290,17 +288,15 @@ unsafe impl NSObjectProtocol for Delegate {}

fn main() {
let mtm = MainThreadMarker::new().unwrap();
let app = unsafe { NSApplication::sharedApplication(mtm) };
unsafe { app.setActivationPolicy(NSApplicationActivationPolicyRegular) };
let app = NSApplication::sharedApplication(mtm);
app.setActivationPolicy(NSApplicationActivationPolicyRegular);

// initialize the delegate
let delegate = Delegate::new(mtm);

// configure the application delegate
unsafe {
let object = ProtocolObject::from_ref(&*delegate);
app.setDelegate(Some(object))
};
let object = ProtocolObject::from_ref(&*delegate);
app.setDelegate(Some(object));

// run the app
unsafe { app.run() };
Expand Down
Loading

0 comments on commit 321693b

Please sign in to comment.