-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathbrowser.rs
321 lines (288 loc) · 11.5 KB
/
browser.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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
#![deny(unsafe_op_in_unsafe_fn)]
#![allow(clippy::incompatible_msrv)]
#![cfg_attr(not(target_os = "macos"), allow(dead_code, unused))]
use core::cell::OnceCell;
use objc2::{
declare_class, msg_send_id,
rc::Retained,
runtime::{AnyObject, ProtocolObject, Sel},
sel, ClassType, DeclaredClass, MainThreadMarker, MainThreadOnly,
};
#[allow(deprecated)]
#[cfg(target_os = "macos")]
use objc2_app_kit::{
NSApplication, NSApplicationActivationPolicy, NSApplicationDelegate, NSBackingStoreType,
NSBezelStyle, NSButton, NSColor, NSControl, NSControlTextEditingDelegate, NSLayoutAttribute,
NSMenu, NSMenuItem, NSStackView, NSStackViewDistribution, NSTextField, NSTextFieldDelegate,
NSTextView, NSUserInterfaceLayoutOrientation, NSWindow, NSWindowStyleMask,
};
use objc2_foundation::{
ns_string, NSNotification, NSObject, NSObjectProtocol, NSPoint, NSRect, NSSize, NSURLRequest,
NSURL,
};
#[cfg(target_os = "macos")]
use objc2_web_kit::{WKNavigation, WKNavigationDelegate, WKWebView};
macro_rules! idcell {
($name:ident => $this:expr) => {
$this.ivars().$name.set($name).expect(&format!(
"ivar should not already be initialized: `{}`",
stringify!($name)
));
};
($name:ident <= $this:expr) => {
#[rustfmt::skip]
let Some($name) = $this.ivars().$name.get() else {
unreachable!(
"ivar should be initialized: `{}`",
stringify!($name)
)
};
};
}
#[derive(Default)]
struct Ivars {
#[cfg(target_os = "macos")]
nav_url: OnceCell<Retained<NSTextField>>,
#[cfg(target_os = "macos")]
web_view: OnceCell<Retained<WKWebView>>,
#[cfg(target_os = "macos")]
window: OnceCell<Retained<NSWindow>>,
}
declare_class!(
struct Delegate;
// SAFETY:
// - The superclass NSObject does not have any subclassing requirements.
// - `MainThreadOnly` is correct, since this is an application delegate.
// - `Delegate` does not implement `Drop`.
unsafe impl ClassType for Delegate {
type Super = NSObject;
type ThreadKind = dyn MainThreadOnly;
const NAME: &'static str = "Delegate";
}
impl DeclaredClass for Delegate {
type Ivars = Ivars;
}
unsafe impl NSObjectProtocol for Delegate {}
#[cfg(target_os = "macos")]
unsafe impl NSApplicationDelegate for Delegate {
#[method(applicationDidFinishLaunching:)]
#[allow(non_snake_case)]
unsafe fn applicationDidFinishLaunching(&self, _notification: &NSNotification) {
let mtm = self.mtm();
// create the app window
let window = {
let content_rect = NSRect::new(NSPoint::new(0., 0.), NSSize::new(1024., 768.));
let style = NSWindowStyleMask::Closable
| NSWindowStyleMask::Resizable
| NSWindowStyleMask::Titled;
let backing_store_type = NSBackingStoreType::NSBackingStoreBuffered;
let flag = false;
unsafe {
NSWindow::initWithContentRect_styleMask_backing_defer(
NSWindow::alloc(mtm),
content_rect,
style,
backing_store_type,
flag,
)
}
};
// create the web view
let web_view = {
let frame_rect = NSRect::ZERO;
unsafe { WKWebView::initWithFrame(WKWebView::alloc(mtm), frame_rect) }
};
// create the nav bar view
let nav_bar = {
let frame_rect = NSRect::ZERO;
let this = unsafe { NSStackView::initWithFrame(NSStackView::alloc(mtm), frame_rect) };
unsafe {
this.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
this.setAlignment(NSLayoutAttribute::Height);
this.setDistribution(NSStackViewDistribution::Fill);
this.setSpacing(0.);
}
this
};
// create the nav buttons view
let nav_buttons = {
let frame_rect = NSRect::ZERO;
let this = unsafe { NSStackView::initWithFrame(NSStackView::alloc(mtm), frame_rect) };
unsafe {
this.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
this.setAlignment(NSLayoutAttribute::Height);
this.setDistribution(NSStackViewDistribution::FillEqually);
this.setSpacing(0.);
}
this
};
// create the back button
let back_button = {
// configure the button to navigate the webview backward
let title = ns_string!("back");
let target = Some::<&AnyObject>(&web_view);
let action = Some(sel!(goBack));
let this =
unsafe { NSButton::buttonWithTitle_target_action(title, target, action, mtm) };
#[allow(deprecated)]
unsafe {
this.setBezelStyle(NSBezelStyle::ShadowlessSquare)
};
this
};
// create the forward button
let forward_button = {
// configure the button to navigate the web view forward
let title = ns_string!("forward");
let target = Some::<&AnyObject>(&web_view);
let action = Some(sel!(goForward));
let this =
unsafe { NSButton::buttonWithTitle_target_action(title, target, action, mtm) };
#[allow(deprecated)]
unsafe {
this.setBezelStyle(NSBezelStyle::ShadowlessSquare)
};
this
};
unsafe {
nav_buttons.addArrangedSubview(&back_button);
nav_buttons.addArrangedSubview(&forward_button);
}
// create the url text field
let nav_url = {
let frame_rect = NSRect::ZERO;
let this = unsafe { NSTextField::initWithFrame(NSTextField::alloc(mtm), frame_rect) };
unsafe {
this.setDrawsBackground(true);
this.setBackgroundColor(Some(&NSColor::lightGrayColor()));
this.setTextColor(Some(&NSColor::blackColor()));
}
this
};
unsafe {
nav_bar.addArrangedSubview(&nav_buttons);
nav_bar.addArrangedSubview(&nav_url);
}
// create the window content view
let content_view = {
let frame_rect = window.frame();
let this = unsafe { NSStackView::initWithFrame(NSStackView::alloc(mtm), frame_rect) };
unsafe {
this.setOrientation(NSUserInterfaceLayoutOrientation::Vertical);
this.setAlignment(NSLayoutAttribute::Width);
this.setDistribution(NSStackViewDistribution::Fill);
this.setSpacing(0.);
}
this
};
unsafe {
content_view.addArrangedSubview(&nav_bar);
content_view.addArrangedSubview(&web_view);
}
unsafe {
// handle input from text field (on <ENTER>, load URL from text field in web view)
nav_url.setDelegate(Some(self));
// handle nav events from web view (on finished navigating, update text area with current URL)
web_view.setNavigationDelegate(Some(self));
}
// create the menu with a "quit" entry
unsafe {
let menu = NSMenu::initWithTitle(NSMenu::alloc(mtm), ns_string!(""));
let menu_app_item = NSMenuItem::initWithTitle_action_keyEquivalent(
NSMenuItem::alloc(mtm),
ns_string!(""),
None,
ns_string!(""),
);
let menu_app_menu = NSMenu::initWithTitle(NSMenu::alloc(mtm), ns_string!(""));
menu_app_menu.addItemWithTitle_action_keyEquivalent(
ns_string!("Quit"),
Some(sel!(terminate:)),
ns_string!("q"),
);
menu_app_item.setSubmenu(Some(&menu_app_menu));
menu.addItem(&menu_app_item);
let app = NSApplication::sharedApplication(mtm);
app.setMainMenu(Some(&menu));
}
// configure the window
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 {
let request = {
let url_string = ns_string!("https://google.com");
let url = NSURL::URLWithString(url_string).expect("URL should parse");
NSURLRequest::requestWithURL(&url)
};
web_view.loadRequest(&request);
}
idcell!(nav_url => self);
idcell!(web_view => self);
idcell!(window => self);
}
}
#[cfg(target_os = "macos")]
unsafe impl NSControlTextEditingDelegate for Delegate {
#[method(control:textView:doCommandBySelector:)]
#[allow(non_snake_case)]
unsafe fn control_textView_doCommandBySelector(
&self,
_control: &NSControl,
text_view: &NSTextView,
command_selector: Sel,
) -> bool {
idcell!(web_view <= self);
if command_selector == sel!(insertNewline:) {
if let Some(url) = unsafe { NSURL::URLWithString(&text_view.string()) } {
unsafe { web_view.loadRequest(&NSURLRequest::requestWithURL(&url)) };
return true.into();
}
}
false
}
}
#[cfg(target_os = "macos")]
unsafe impl NSTextFieldDelegate for Delegate {}
#[cfg(target_os = "macos")] // TODO: Enable this on iOS
unsafe impl WKNavigationDelegate for Delegate {
#[method(webView:didFinishNavigation:)]
#[allow(non_snake_case)]
unsafe fn webView_didFinishNavigation(
&self,
web_view: &WKWebView,
_navigation: Option<&WKNavigation>,
) {
idcell!(nav_url <= self);
unsafe {
if let Some(url) = web_view.URL().and_then(|url| url.absoluteString()) {
nav_url.setStringValue(&url);
}
}
}
}
);
impl Delegate {
fn new(mtm: MainThreadMarker) -> Retained<Self> {
let this = Self::alloc(mtm);
let this = this.set_ivars(Ivars::default());
unsafe { msg_send_id![super(this), init] }
}
}
#[cfg(target_os = "macos")]
fn main() {
let mtm = MainThreadMarker::new().unwrap();
let app = NSApplication::sharedApplication(mtm);
app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
// configure the application delegate
let delegate = Delegate::new(mtm);
app.setDelegate(Some(&*delegate));
// run the app
app.run();
}
#[cfg(not(target_os = "macos"))]
fn main() {
panic!("This example is currently only supported on macOS");
}