Echo Writes Code

appkit.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
use objc2_app_kit::{
  NSBackingStoreType,
  NSWindow,
  NSWindowDelegate,
  NSWindowStyleMask,
};

use objc2_foundation::{
  MainThreadMarker,
  NSNotification,
  NSObject,
  NSObjectProtocol,
  NSPoint,
  NSRect,
  NSSize,
  NSString,
};

use crate::color::{ Color };
use crate::geometry::{ Vector2D };
use crate::render::metal::{ MetalCanvas };
use crate::window::{ Window, WindowBuilder, WindowDelegate };

use objc2::{ DefinedClass, MainThreadOnly, define_class, msg_send };
use objc2::rc::{ Retained };
use objc2::runtime::{ ProtocolObject };

use std::cell::{ RefCell };

#[derive(Debug, Default)]
pub struct AppkitWindowBuilder<D> {
  delegate: Option<D>,
  resolution: Vector2D<u32>,
  title: String,
}

impl<D> AppkitWindowBuilder<D> {
  pub fn new() -> AppkitWindowBuilder<D> {
    AppkitWindowBuilder {
      delegate: None,
      resolution: Vector2D::new(1280, 720),
      title: "Crucible Application".to_string(),
    }
  }

  pub fn with_delegate(mut self, delegate: D) -> AppkitWindowBuilder<D> {
    self.delegate = Some(delegate);
    self
  }

  pub fn with_resolution(mut self, resolution: Vector2D<u32>) -> AppkitWindowBuilder<D> {
    self.resolution = resolution;
    self
  }

  pub fn with_title(mut self, title: &str) -> AppkitWindowBuilder<D> {
    self.title = title.to_string();
    self
  }
}

impl<D: WindowDelegate + 'static> WindowBuilder for AppkitWindowBuilder<D> {
  type Output = AppkitWindow;

  fn build(self) -> AppkitWindow {
    let Some(delegate) = self.delegate else {
      panic!("A delegate should have been set using AppkitWindowBuilder::with_delegate() before calling AppkitWindowBuilder::build()");
    };

    AppkitWindow::new(delegate, self.resolution, &self.title)
  }
}

#[derive(Debug)]
pub struct AppkitWindow {
  _appkit_delegate: Retained<AppkitWindowDelegate>,
  ns_window: Retained<NSWindow>,
  metal_canvas: MetalCanvas,
}

impl AppkitWindow {
  pub fn new<D: WindowDelegate + 'static>(delegate: D, resolution: Vector2D<u32>, title: &str) -> AppkitWindow {
    let mtm = MainThreadMarker::new()
      .expect("Must be called from the main thread");

    let content_rect = NSRect::new(
      NSPoint::new(0.0, 0.0),
      NSSize::new(resolution.x() as f64, resolution.y() as f64),
    );

    let style_mask = NSWindowStyleMask::Closable
      | NSWindowStyleMask::Miniaturizable
      | NSWindowStyleMask::Titled
      | NSWindowStyleMask::Resizable;

    let ns_window = unsafe {
      NSWindow::initWithContentRect_styleMask_backing_defer(
        NSWindow::alloc(mtm),
        content_rect,
        style_mask,
        NSBackingStoreType::Buffered,
        false
      )
    };

    unsafe {
      ns_window.setReleasedWhenClosed(false)
    };

    ns_window.setTitle(&NSString::from_str(title));
    ns_window.center();

    let appkit_delegate = AppkitWindowDelegate::new(mtm, delegate);
    ns_window.setDelegate(Some(ProtocolObject::from_ref(&*appkit_delegate)));
    ns_window.makeKeyAndOrderFront(None);

    let metal_canvas = MetalCanvas::new(mtm, ns_window.frame(), Color::white());
    ns_window.setContentView(Some(metal_canvas.view()));

    AppkitWindow {
      _appkit_delegate: appkit_delegate,
      ns_window,
      metal_canvas,
    }
  }
}

impl Window for AppkitWindow {
  fn resolution(&self) -> Vector2D<u32> {
    let content_rect = self.ns_window.contentLayoutRect();
    Vector2D::new(content_rect.size.width as u32, content_rect.size.height as u32)
  }
}

struct AppkitWindowIvars {
  delegate: RefCell<Box<dyn WindowDelegate>>,
}

impl AppkitWindowIvars {
  fn new<D: WindowDelegate + 'static>(delegate: D) -> AppkitWindowIvars {
    AppkitWindowIvars {
      delegate: RefCell::new(Box::new(delegate)),
    }
  }
}

impl std::fmt::Debug for AppkitWindowIvars {
  fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
    f.debug_struct("AppkitWindowIvars")
      .field("delegate", &"dyn WindowDelegate { ... }")
      .finish()
  }
}

define_class!{
  #[derive(Debug)]
  #[unsafe(super = NSObject)]
  #[thread_kind = MainThreadOnly]
  #[ivars = AppkitWindowIvars]
  struct AppkitWindowDelegate;

  unsafe impl NSObjectProtocol for AppkitWindowDelegate {}

  unsafe impl NSWindowDelegate for AppkitWindowDelegate {
    #[unsafe(method(windowWillClose:))]
    fn window_will_close(&self, _notification: &NSNotification) {
      self
        .ivars()
        .delegate
        .borrow_mut()
        .on_close();
    }
  }
}

impl AppkitWindowDelegate {
  fn new<D: WindowDelegate + 'static>(mtm: MainThreadMarker, delegate: D) -> Retained<AppkitWindowDelegate> {
    let this = AppkitWindowDelegate::alloc(mtm)
      .set_ivars(AppkitWindowIvars::new(delegate));

    unsafe {
      msg_send![super(this), init]
    }
  }
}