ci: compile the manual
[nit.git] / lib / ios / ui / ui.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Implementation of `app::ui` for iOS
16 module ui
17
18 import app::ui
19
20 import ios
21 import uikit
22
23 in "ObjC" `{
24 // Objective-C object receiving callbacks from UI events
25 @interface NitCallbackReference: NSObject
26
27 // Nit object target of the callbacks from UI events
28 @property (nonatomic) View nit_view;
29
30 // Actual callback method
31 -(void) nitOnEvent: (UIView*) sender;
32 @end
33
34 @implementation NitCallbackReference
35
36 -(void) nitOnEvent: (UIView*) sender {
37 View_on_ios_event(self.nit_view);
38 }
39 @end
40
41 // Proxy for both delegates of UITableView relaying all callbacks to `nit_list_layout`
42 @interface UITableViewAndDataSource: NSObject <UITableViewDelegate, UITableViewDataSource>
43
44 // Nit object receiving the callbacks
45 @property TableView nit_list_layout;
46
47 // List of native views added to this list view from the Nit side
48 @property NSMutableArray *views;
49 @end
50
51 @implementation UITableViewAndDataSource
52
53 - (id)init
54 {
55 self = [super init];
56 self.views = [[NSMutableArray alloc] initWithCapacity:8];
57 return self;
58 }
59
60 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
61 return TableView_number_of_sections_in_table_view(self.nit_list_layout, tableView);
62 }
63
64 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
65 return TableView_number_of_rows_in_section(self.nit_list_layout, tableView, section);
66 }
67
68 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
69 return TableView_title_for_header_in_section(self.nit_list_layout, tableView, section);
70 }
71
72 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
73 return TableView_cell_for_row_at_index_path(self.nit_list_layout, tableView, indexPath);
74 }
75 @end
76
77 // View controller associated to an app.nit Window
78 @interface NitViewController: UIViewController
79 @end
80
81 @implementation NitViewController
82 - (void)viewWillDisappear:(BOOL)animated {
83 [super viewWillDisappear:animated];
84
85 if (self.isMovingFromParentViewController || self.isBeingDismissed) {
86 extern App app_nit_ios_app;
87 App_after_window_pop(app_nit_ios_app);
88 }
89 }
90 @end
91 `}
92
93 redef class App
94
95 redef fun did_finish_launching_with_options
96 do
97 app_delegate.window = new UIWindow
98 app_delegate.window.background_color = new UIColor.white_color
99 super
100 app_delegate.window.make_key_and_visible
101 return true
102 end
103
104 private fun set_view_controller(window: UIWindow, native: UIViewController)
105 in "ObjC" `{
106 // Set the required root view controller
107 UINavigationController *navController = (UINavigationController*)window.rootViewController;
108
109 if (navController == NULL) {
110 navController = [[UINavigationController alloc]initWithRootViewController:native];
111 navController.edgesForExtendedLayout = UIRectEdgeNone;
112
113 // Must be non-translucent for the controls to be placed under
114 // (as in Y axis) of the navigation bar.
115 navController.navigationBar.translucent = NO;
116
117 window.rootViewController = navController;
118 }
119 else {
120 [navController pushViewController:native animated:YES];
121 }
122
123 native.edgesForExtendedLayout = UIRectEdgeNone;
124 `}
125
126 redef fun push_window(window)
127 do
128 set_view_controller(app_delegate.window, window.native)
129 super
130 end
131
132 # Use iOS ` popViewControllerAnimated`
133 redef fun pop_window
134 do
135 manual_pop = true
136 pop_view_controller app_delegate.window
137 super
138 end
139
140 private fun pop_view_controller(window: UIWindow) in "ObjC" `{
141 UINavigationController *navController = (UINavigationController*)window.rootViewController;
142 [navController popViewControllerAnimated: YES];
143 `}
144
145 # Is the next `after_window_pop` triggered by a call to `pop_window`?
146 #
147 # Otherwise, it's by the user via the navigation bar "Back" button.
148 private var manual_pop = false
149
150 # Callback when `window` is displayed again
151 private fun after_window_pop
152 do
153 if not manual_pop then window_stack.pop
154 manual_pop = false
155 window.on_resume
156 end
157 end
158
159 redef class AppDelegate
160
161 # The main application window, must be set by `App::on_create`
162 fun window: UIWindow in "ObjC" `{ return [self window]; `}
163
164 # The main application window, must be set by `App::on_create`
165 fun window=(window: UIWindow) in "ObjC" `{ self.window = window; `}
166 end
167
168 redef class Control
169
170 # Native implementation of this control
171 fun native: NATIVE is abstract
172
173 # Type of the `native` implementation of this control
174 type NATIVE: NSObject
175 end
176
177 redef class View
178 redef type NATIVE: UIView
179
180 redef var enabled = null is lazy
181
182 private fun on_ios_event do end
183 end
184
185 redef class CompositeControl
186
187 redef fun remove(view)
188 do
189 super
190
191 if view isa View then
192 view.native.remove_from_superview
193 end
194 end
195 end
196
197 # View controller associated to an app.nit `Window`
198 extern class NitViewController
199 super UIViewController
200
201 new import App.after_window_pop in "ObjC" `{
202 return [[NitViewController alloc] init];
203 `}
204 end
205
206 redef class Window
207
208 redef type NATIVE: NitViewController
209 redef var native = new NitViewController
210
211 # Title of this window
212 fun title: String do return native.title.to_s
213
214 # Set the title of this window
215 fun title=(title: String) do native.title = title.to_nsstring
216
217 redef fun add(view)
218 do
219 super
220
221 var native_view = view.native
222 assert native_view isa UIView
223
224 if view isa ListLayout then
225 native.view.add_subview native_view
226 else native.view = native_view
227 end
228 end
229
230 redef class Layout
231
232 redef type NATIVE: UIStackView
233 redef var native = new UIStackView
234
235 init
236 do
237 native.alignment = new UIStackViewAlignment.fill
238 end
239
240 redef fun add(view)
241 do
242 super
243
244 var native_view = view.native
245 assert native_view isa UIView
246 self.native.add_arranged_subview native_view
247 end
248 end
249
250 redef class HorizontalLayout
251 redef init
252 do
253 native.axis = new UILayoutConstraintAxis.horizontal
254 native.distribution = new UIStackViewDistribution.fill_equally
255 end
256 end
257
258 redef class VerticalLayout
259 redef init
260 do
261 native.axis = new UILayoutConstraintAxis.vertical
262 native.distribution = new UIStackViewDistribution.equal_spacing
263 end
264 end
265
266 redef class TextView
267 # Convert `size` from app.nit relative size to iOS font points
268 private fun ios_points(size: nullable Float): Float
269 do
270 size = size or else 1.0
271 return 8.0 + size * 5.0
272 end
273 end
274
275 redef class Label
276
277 redef type NATIVE: UILabel
278 redef var native = new UILabel
279
280 redef fun text=(text) do native.text = (text or else "").to_nsstring
281 redef fun text do return native.text.to_s
282
283 redef fun size=(size) do native.size = ios_points(size)
284
285 redef fun align=(align) do native.align = align or else 0.0
286 end
287
288 redef class UILabel
289
290 private fun size=(points: Float)
291 in "ObjC" `{
292 self.font = [UIFont systemFontOfSize: points];
293 `}
294
295 private fun align=(align: Float)
296 in "ObjC" `{
297 if (align == 0.5)
298 self.textAlignment = NSTextAlignmentCenter;
299 else if (align < 0.5)
300 self.textAlignment = NSTextAlignmentLeft;
301 else//if (align > 0.5)
302 self.textAlignment = NSTextAlignmentRight;
303 `}
304 end
305
306 # On iOS, check boxes are a layout composed of a label and an `UISwitch`
307 redef class CheckBox
308
309 redef type NATIVE: UIStackView
310 redef fun native do return layout.native
311
312 # Root layout implementing this check box
313 var layout = new HorizontalLayout(parent=self.parent)
314
315 # Label with the text
316 var lbl = new Label(parent=layout)
317
318 # `UISwitch` acting as the real check box
319 var ui_switch: UISwitch is noautoinit
320
321 redef fun on_ios_event do notify_observers new ToggleEvent(self)
322
323 init
324 do
325 # Tweak the layout so it is centered
326 layout.native.distribution = new UIStackViewDistribution.equal_spacing
327 layout.native.alignment = new UIStackViewAlignment.fill
328 layout.native.layout_margins_relative_arrangement = true
329
330 var s = new UISwitch
331 native.add_arranged_subview s
332 ui_switch = s
333
334 ui_switch.set_callback self
335 end
336
337 redef fun text=(text) do lbl.text = text
338 redef fun text do return lbl.text
339
340 redef fun is_checked do return ui_switch.on
341 redef fun is_checked=(value) do ui_switch.set_on_animated(value, true)
342 end
343
344 redef class UISwitch
345 # Register callbacks on this switch to be relayed to `sender`
346 private fun set_callback(sender: View)
347 import View.on_ios_event in "ObjC" `{
348
349 NitCallbackReference *ncr = [[NitCallbackReference alloc] init];
350 ncr.nit_view = sender;
351
352 // Pin the objects in both Objective-C and Nit GC
353 View_incr_ref(sender);
354 ncr = (__bridge NitCallbackReference*)CFBridgingRetain(ncr);
355
356 [self addTarget:ncr action:@selector(nitOnEvent:)
357 forControlEvents:UIControlEventValueChanged];
358 `}
359 end
360
361 redef class TextInput
362
363 redef type NATIVE: UITextField
364 redef var native = new UITextField
365
366 redef fun text=(text) do native.text = (text or else "").to_nsstring
367 redef fun text do return native.text.to_s
368
369 redef fun is_password=(value)
370 do
371 native.secure_text_entry = value or else false
372 super
373 end
374
375 redef fun size=(size) do native.size = ios_points(size)
376
377 redef fun align=(align) do native.align = align or else 0.0
378
379 # Set the placeholder text, shown in light gray when the field is empty
380 fun placeholder=(text: Text) do native.placeholder = text.to_nsstring
381 end
382
383 redef class UITextField
384
385 private fun size=(points: Float)
386 in "ObjC" `{
387 self.font = [UIFont systemFontOfSize: points];
388 `}
389
390 private fun align=(align: Float)
391 in "ObjC" `{
392 if (align == 0.5)
393 self.textAlignment = NSTextAlignmentCenter;
394 else if (align < 0.5)
395 self.textAlignment = NSTextAlignmentLeft;
396 else//if (align > 0.5)
397 self.textAlignment = NSTextAlignmentRight;
398 `}
399 end
400
401 redef class Button
402
403 redef type NATIVE: UIButton
404 redef var native = new UIButton(new UIButtonType.system)
405
406 init do native.set_callback self
407
408 redef fun on_ios_event do notify_observers new ButtonPressEvent(self)
409
410 redef fun text=(text) do if text != null then native.title = text.to_nsstring
411 redef fun text do return native.current_title.to_s
412
413 redef fun enabled=(enabled) do native.enabled = enabled or else true
414 redef fun enabled do return native.enabled
415
416 redef fun size=(size) do native.title_label.size = ios_points(size)
417
418 redef fun align=(align) do native.title_label.align = align or else 0.0
419 end
420
421 redef class UIButton
422 # Register callbacks on this button to be relayed to `sender`
423 private fun set_callback(sender: View)
424 import View.on_ios_event in "ObjC" `{
425
426 NitCallbackReference *ncr = [[NitCallbackReference alloc] init];
427 ncr.nit_view = sender;
428
429 // Pin the objects in both Objective-C and Nit GC
430 View_incr_ref(sender);
431 ncr = (__bridge NitCallbackReference*)CFBridgingRetain(ncr);
432
433 [self addTarget:ncr action:@selector(nitOnEvent:)
434 forControlEvents:UIControlEventTouchUpInside];
435 `}
436 end
437
438 # On iOS, implemented by a `UIStackView` inside a ` UIScrollView`
439 redef class ListLayout
440
441 redef type NATIVE: UIScrollView
442 redef var native = new UIScrollView
443
444 # Real container of the subviews, contained within `native`
445 var native_stack_view = new UIStackView
446
447 redef fun parent=(parent)
448 do
449 super
450
451 var root_view
452 if parent isa Window then
453 root_view = parent.native.view
454 else if parent isa View then
455 root_view = parent.native
456 else return
457
458 # Setup scroll view
459 var native_scroll_view = native
460 native_scroll_view.translates_autoresizing_mask_into_constraits = false
461 native_add_constraints(root_view, native_scroll_view)
462
463 # Setup stack_view
464 native_stack_view.translates_autoresizing_mask_into_constraits = false
465 native_stack_view.axis = new UILayoutConstraintAxis.vertical
466 native_scroll_view.add_subview native_stack_view
467 native_add_constraints(native_scroll_view, native_stack_view)
468 native_lock_vertical_scroll(native_scroll_view, native_stack_view)
469 end
470
471 # Add constraints to lock the vertical and horizontal dimensions
472 private fun native_add_constraints(root_view: UIView, nested_view: UIView)
473 in "ObjC" `{
474 [root_view addConstraints:[NSLayoutConstraint
475 constraintsWithVisualFormat: @"V:|-0-[nested_view]-0-|"
476 options: NSLayoutFormatAlignAllCenterX metrics: nil views: @{@"nested_view": nested_view}]];
477 [root_view addConstraints:[NSLayoutConstraint
478 constraintsWithVisualFormat: @"H:|-0-[nested_view]-0-|"
479 options: NSLayoutFormatAlignAllCenterX metrics: nil views: @{@"nested_view": nested_view}]];
480 `}
481
482 # Add a constraint to lock to the scroll vertically
483 private fun native_lock_vertical_scroll(scroll_view: UIScrollView, stack_view: UIStackView)
484 in "ObjC" `{
485 [scroll_view addConstraint: [scroll_view.widthAnchor constraintEqualToAnchor:stack_view.widthAnchor]];
486 `}
487
488 redef fun add(view)
489 do
490 super
491
492 if view isa View then
493 native_stack_view.add_arranged_subview view.native
494 end
495 end
496 end
497
498 # iOS specific layout using a `UITableView`, works only with simple children views
499 class TableView
500 super CompositeControl
501
502 redef type NATIVE: UITableView
503 redef var native = new UITableView(new UITableViewStyle.plain)
504
505 init
506 do
507 native.autoresizing_mask
508 native.assign_delegate_and_data_source self
509 end
510
511 redef fun add(item)
512 do
513 # Adding a view to a UITableView is a bit tricky.
514 #
515 # Items are added to the Objective-C view only by callbacks.
516 # We must store the sub views in local lists while waiting
517 # for the callbacks.
518 #
519 # As usual, we keep the Nity object in `items`.
520 # But we also keep their native counterparts in a list of
521 # the `UITableViewAndDataSource` set as `native.delegate`.
522 # Otherwise the native views could be freed by the Objective-C GC.
523
524 # TODO use an adapter for the app.nit ListLayout closer to what exists
525 # on both iOS and Android, to support large data sets.
526
527 if item isa View then
528 add_view_to_native_list(native, item.native)
529 end
530
531 super
532
533 # Force redraw and trigger callbacks
534 native.reload_data
535 end
536
537 private fun add_view_to_native_list(native: UITableView, item: UIView) in "ObjC" `{
538 [((UITableViewAndDataSource*)native.delegate).views addObject:item];
539 `}
540
541 private fun get_view_from_native_list(native: UITableView, index: Int): UIView in "ObjC" `{
542 return [((UITableViewAndDataSource*)native.delegate).views objectAtIndex:index];
543 `}
544
545 # Number of sections in this view
546 #
547 # By default, we assume that all `items` are in a single section,
548 # so there is only one section.
549 #
550 # iOS callback: `numberOfSectionsInTableView`
551 protected fun number_of_sections_in_table_view(view: UITableView): Int
552 do return 1
553
554 # Number of entries in `section`
555 #
556 # By default, we assume that all `items` are in a single section,
557 # so no matter the section, this returns `items.length`.
558 #
559 # iOS callback: `numberOfRowsInSection`
560 protected fun number_of_rows_in_section(view: UITableView, section: Int): Int
561 do return items.length
562
563 # Title for `section`, return `new NSString.nil` for no title
564 #
565 # By default, this returns no title.
566 #
567 # iOS callback: `titleForHeaderInSection`
568 protected fun title_for_header_in_section(view: UITableView, section: Int): NSString
569 do return new NSString.nil
570
571 # Return a `UITableViewCell` for the item at `index_path`
572 #
573 # By default, we assume that all `items` are in a single section.
574 # So no matter the depth of the `index_path`, this returns a cell with
575 # the view at index part of `index_path`.
576 #
577 # iOS callback: `cellForRowAtIndexPath`
578 protected fun cell_for_row_at_index_path(table_view: UITableView, index_path: NSIndexPath): UITableViewCell
579 do
580 var reuse_id = "NitCell".to_nsstring
581 var cell = new UITableViewCell(reuse_id)
582
583 # TODO if there is performance issues, reuse cells with
584 # the following code, but clear the cell before use.
585
586 #var cell = table_view.dequeue_reusable_cell_with_identifier(reuse_id)
587 #if cell.address_is_null then cell = new UITableViewCell(reuse_id)
588
589 var index = index_path.index_at_position(1)
590 var view_native = get_view_from_native_list(table_view, index)
591 var cv = cell.content_view
592 cv.add_subview view_native
593
594 return cell
595 end
596 end
597
598 redef class UITableView
599
600 # Assign `list_view` as `delegate` and `dataSource`, and pin all references in both GCs
601 private fun assign_delegate_and_data_source(list_view: TableView)
602 import TableView.number_of_sections_in_table_view,
603 TableView.number_of_rows_in_section,
604 TableView.title_for_header_in_section,
605 TableView.cell_for_row_at_index_path in "ObjC" `{
606
607 UITableViewAndDataSource *objc_delegate = [[UITableViewAndDataSource alloc] init];
608 objc_delegate = (__bridge UITableViewAndDataSource*)CFBridgingRetain(objc_delegate);
609
610 objc_delegate.nit_list_layout = list_view;
611 TableView_incr_ref(list_view);
612
613 // Set our
614 self.delegate = objc_delegate;
615 self.dataSource = objc_delegate;
616 `}
617 end
618
619 redef class Text
620 redef fun open_in_browser do to_nsstring.native_open_in_browser
621 end
622
623 redef class NSString
624 private fun native_open_in_browser
625 in "ObjC" `{
626 NSURL *nsurl = [NSURL URLWithString: self];
627 [[UIApplication sharedApplication] openURL: nsurl];
628 `}
629 end