lib/ios: implement ToggleEvent
[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
78 redef class App
79 redef fun did_finish_launching_with_options
80 do
81 app_delegate.window = new UIWindow
82 app_delegate.window.background_color = new UIColor.white_color
83 super
84 app_delegate.window.make_key_and_visible
85 return true
86 end
87
88 private fun set_view_controller(window: UIWindow, native: UIViewController)
89 in "ObjC" `{
90 // Set the required root view controller
91 UINavigationController *navController = (UINavigationController*)window.rootViewController;
92
93 if (navController == NULL) {
94 navController = [[UINavigationController alloc]initWithRootViewController:native];
95 navController.edgesForExtendedLayout = UIRectEdgeNone;
96
97 // Must be non-translucent for the controls to be placed under
98 // (as in Y axis) of the navigation bar.
99 navController.navigationBar.translucent = NO;
100
101 window.rootViewController = navController;
102 }
103 else {
104 [navController pushViewController:native animated:YES];
105 }
106
107 native.edgesForExtendedLayout = UIRectEdgeNone;
108 `}
109
110 redef fun window=(window)
111 do
112 set_view_controller(app_delegate.window, window.native)
113 super
114 end
115 end
116
117 redef class AppDelegate
118
119 # The main application window, must be set by `App::on_create`
120 fun window: UIWindow in "ObjC" `{ return [self window]; `}
121
122 # The main application window, must be set by `App::on_create`
123 fun window=(window: UIWindow) in "ObjC" `{ self.window = window; `}
124 end
125
126 redef class Control
127
128 # Native implementation of this control
129 fun native: NATIVE is abstract
130
131 # Type of the `native` implementation of this control
132 type NATIVE: NSObject
133 end
134
135 redef class View
136 redef type NATIVE: UIView
137
138 redef var enabled = null is lazy
139
140 private fun on_ios_event do end
141 end
142
143 redef class CompositeControl
144
145 redef fun remove(view)
146 do
147 super
148
149 if view isa View then
150 view.native.remove_from_superview
151 end
152 end
153 end
154
155 redef class Window
156
157 redef type NATIVE: UIViewController
158 redef var native = new UIViewController
159
160 # Title of this window
161 fun title: String do return native.title.to_s
162
163 # Set the title of this window
164 fun title=(title: String) do native.title = title.to_nsstring
165
166 redef fun add(view)
167 do
168 super
169
170 var native_view = view.native
171 assert native_view isa UIView
172
173 native.view = native_view
174 end
175 end
176
177 redef class Layout
178
179 redef type NATIVE: UIStackView
180 redef var native = new UIStackView
181
182 init
183 do
184 native.alignment = new UIStackViewAlignment.fill
185 native.distribution = new UIStackViewDistribution.fill_equally
186
187 # TODO make customizable
188 native.spacing = 4.0
189 end
190
191 redef fun add(view)
192 do
193 super
194
195 var native_view = view.native
196 assert native_view isa UIView
197 self.native.add_arranged_subview native_view
198 end
199 end
200
201 redef class HorizontalLayout
202 redef init do native.axis = new UILayoutConstraintAxis.horizontal
203 end
204
205 redef class VerticalLayout
206 redef init do native.axis = new UILayoutConstraintAxis.vertical
207 end
208
209 redef class Label
210
211 redef type NATIVE: UILabel
212 redef var native = new UILabel
213
214 redef fun text=(text) do native.text = (text or else "").to_nsstring
215 redef fun text do return native.text.to_s
216
217 redef fun size=(size)
218 do
219 size = size or else 1.0
220 var points = 8.0 + size * 8.0
221 set_size_native(native, points)
222 end
223
224 private fun set_size_native(native: UILabel, points: Float)
225 in "ObjC" `{
226 native.font = [UIFont systemFontOfSize: points];
227 `}
228
229 redef fun align=(align) do set_align_native(native, align or else 0.0)
230
231 private fun set_align_native(native: UILabel, align: Float)
232 in "ObjC" `{
233
234 if (align == 0.5)
235 native.textAlignment = NSTextAlignmentCenter;
236 else if (align < 0.5)
237 native.textAlignment = NSTextAlignmentLeft;
238 else//if (align > 0.5)
239 native.textAlignment = NSTextAlignmentRight;
240 `}
241 end
242
243 # On iOS, check boxes are a layout composed of a label and an `UISwitch`
244 redef class CheckBox
245
246 redef type NATIVE: UIStackView
247 redef fun native do return layout.native
248
249 # Root layout implementing this check box
250 var layout = new HorizontalLayout(parent=self.parent)
251
252 # Label with the text
253 var lbl = new Label(parent=layout)
254
255 # `UISwitch` acting as the real check box
256 var ui_switch: UISwitch is noautoinit
257
258 redef fun on_ios_event do notify_observers new ToggleEvent(self)
259
260 init
261 do
262 # Tweak the layout so it is centered
263 layout.native.distribution = new UIStackViewDistribution.fill_proportionally
264 layout.native.alignment = new UIStackViewAlignment.center
265 layout.native.layout_margins_relative_arrangement = true
266
267 var s = new UISwitch
268 native.add_arranged_subview s
269 ui_switch = s
270
271 ui_switch.set_callback self
272 end
273
274 redef fun text=(text) do lbl.text = text
275 redef fun text do return lbl.text
276
277 redef fun is_checked do return ui_switch.on
278 redef fun is_checked=(value) do ui_switch.set_on_animated(value, true)
279 end
280
281 redef class UISwitch
282 # Register callbacks on this switch to be relayed to `sender`
283 private fun set_callback(sender: View)
284 import View.on_ios_event in "ObjC" `{
285
286 NitCallbackReference *ncr = [[NitCallbackReference alloc] init];
287 ncr.nit_view = sender;
288
289 // Pin the objects in both Objective-C and Nit GC
290 View_incr_ref(sender);
291 ncr = (__bridge NitCallbackReference*)CFBridgingRetain(ncr);
292
293 [self addTarget:ncr action:@selector(nitOnEvent:)
294 forControlEvents:UIControlEventValueChanged];
295 `}
296 end
297
298 redef class TextInput
299
300 redef type NATIVE: UITextField
301 redef var native = new UITextField
302
303 redef fun text=(text) do native.text = (text or else "").to_nsstring
304 redef fun text do return native.text.to_s
305
306 redef fun is_password=(value)
307 do
308 native.secure_text_entry = value or else false
309 super
310 end
311 end
312
313 redef class Button
314
315 redef type NATIVE: UIButton
316 redef var native = new UIButton(new UIButtonType.system)
317
318 init do native.set_callback self
319
320 redef fun on_ios_event do notify_observers new ButtonPressEvent(self)
321
322 redef fun text=(text) do if text != null then native.title = text.to_nsstring
323 redef fun text do return native.current_title.to_s
324
325 redef fun enabled=(enabled) do native.enabled = enabled or else true
326 redef fun enabled do return native.enabled
327 end
328
329 redef class UIButton
330 # Register callbacks on this button to be relayed to `sender`
331 private fun set_callback(sender: View)
332 import View.on_ios_event in "ObjC" `{
333
334 NitCallbackReference *ncr = [[NitCallbackReference alloc] init];
335 ncr.nit_view = sender;
336
337 // Pin the objects in both Objective-C and Nit GC
338 View_incr_ref(sender);
339 ncr = (__bridge NitCallbackReference*)CFBridgingRetain(ncr);
340
341 [self addTarget:ncr action:@selector(nitOnEvent:)
342 forControlEvents:UIControlEventTouchUpInside];
343 `}
344 end
345
346 # On iOS, implemented by a `UIStackView` inside a ` UIScrollView`
347 redef class ListLayout
348
349 redef type NATIVE: UIScrollView
350 redef var native = new UIScrollView
351
352 # Real container of the subviews, contained within `native`
353 var native_stack_view = new UIStackView
354
355 init
356 do
357 native_stack_view.translates_autoresizing_mask_into_constraits = false
358 native_stack_view.axis = new UILayoutConstraintAxis.vertical
359 native_stack_view.alignment = new UIStackViewAlignment.fill
360 native_stack_view.distribution = new UIStackViewDistribution.fill_equally
361 native_stack_view.spacing = 4.0
362
363 native.add_subview native_stack_view
364 native_add_constraints(native, native_stack_view)
365 end
366
367 private fun native_add_constraints(scroll_view: UIScrollView, stack_view: UIStackView) in "ObjC" `{
368 [scroll_view addConstraints:[NSLayoutConstraint
369 constraintsWithVisualFormat: @"V:|-8-[view]-8-|"
370 options: NSLayoutFormatAlignAllCenterX metrics: nil views: @{@"view": stack_view}]];
371 [scroll_view addConstraints:[NSLayoutConstraint
372 constraintsWithVisualFormat: @"H:|-8-[view]"
373 options: NSLayoutFormatAlignAllCenterX metrics: nil views: @{@"view": stack_view}]];
374 `}
375
376 redef fun add(view)
377 do
378 super
379
380 if view isa View then
381 native_stack_view.add_arranged_subview view.native
382 end
383 end
384 end
385
386 # iOS specific layout using a `UITableView`, works only with simple children views
387 class TableView
388 super CompositeControl
389
390 redef type NATIVE: UITableView
391 redef var native = new UITableView(new UITableViewStyle.plain)
392
393 init
394 do
395 native.autoresizing_mask
396 native.assign_delegate_and_data_source self
397 end
398
399 redef fun add(item)
400 do
401 # Adding a view to a UITableView is a bit tricky.
402 #
403 # Items are added to the Objective-C view only by callbacks.
404 # We must store the sub views in local lists while waiting
405 # for the callbacks.
406 #
407 # As usual, we keep the Nity object in `items`.
408 # But we also keep their native counterparts in a list of
409 # the `UITableViewAndDataSource` set as `native.delegate`.
410 # Otherwise the native views could be freed by the Objective-C GC.
411
412 # TODO use an adapter for the app.nit ListLayout closer to what exists
413 # on both iOS and Android, to support large data sets.
414
415 if item isa View then
416 add_view_to_native_list(native, item.native)
417 end
418
419 super
420
421 # Force redraw and trigger callbacks
422 native.reload_data
423 end
424
425 private fun add_view_to_native_list(native: UITableView, item: UIView) in "ObjC" `{
426 [((UITableViewAndDataSource*)native.delegate).views addObject:item];
427 `}
428
429 private fun get_view_from_native_list(native: UITableView, index: Int): UIView in "ObjC" `{
430 return [((UITableViewAndDataSource*)native.delegate).views objectAtIndex:index];
431 `}
432
433 # Number of sections in this view
434 #
435 # By default, we assume that all `items` are in a single section,
436 # so there is only one section.
437 #
438 # iOS callback: `numberOfSectionsInTableView`
439 protected fun number_of_sections_in_table_view(view: UITableView): Int
440 do return 1
441
442 # Number of entries in `section`
443 #
444 # By default, we assume that all `items` are in a single section,
445 # so no matter the section, this returns `items.length`.
446 #
447 # iOS callback: `numberOfRowsInSection`
448 protected fun number_of_rows_in_section(view: UITableView, section: Int): Int
449 do return items.length
450
451 # Title for `section`, return `new NSString.nil` for no title
452 #
453 # By default, this returns no title.
454 #
455 # iOS callback: `titleForHeaderInSection`
456 protected fun title_for_header_in_section(view: UITableView, section: Int): NSString
457 do return new NSString.nil
458
459 # Return a `UITableViewCell` for the item at `index_path`
460 #
461 # By default, we assume that all `items` are in a single section.
462 # So no matter the depth of the `index_path`, this returns a cell with
463 # the view at index part of `index_path`.
464 #
465 # iOS callback: `cellForRowAtIndexPath`
466 protected fun cell_for_row_at_index_path(table_view: UITableView, index_path: NSIndexPath): UITableViewCell
467 do
468 var reuse_id = "NitCell".to_nsstring
469 var cell = new UITableViewCell(reuse_id)
470
471 # TODO if there is performance issues, reuse cells with
472 # the following code, but clear the cell before use.
473
474 #var cell = table_view.dequeue_reusable_cell_with_identifier(reuse_id)
475 #if cell.address_is_null then cell = new UITableViewCell(reuse_id)
476
477 var index = index_path.index_at_position(1)
478 var view_native = get_view_from_native_list(table_view, index)
479 var cv = cell.content_view
480 cv.add_subview view_native
481
482 return cell
483 end
484 end
485
486 redef class UITableView
487
488 # Assign `list_view` as `delegate` and `dataSource`, and pin all references in both GCs
489 private fun assign_delegate_and_data_source(list_view: TableView)
490 import TableView.number_of_sections_in_table_view,
491 TableView.number_of_rows_in_section,
492 TableView.title_for_header_in_section,
493 TableView.cell_for_row_at_index_path in "ObjC" `{
494
495 UITableViewAndDataSource *objc_delegate = [[UITableViewAndDataSource alloc] init];
496 objc_delegate = (__bridge UITableViewAndDataSource*)CFBridgingRetain(objc_delegate);
497
498 objc_delegate.nit_list_layout = list_view;
499 TableView_incr_ref(list_view);
500
501 // Set our
502 self.delegate = objc_delegate;
503 self.dataSource = objc_delegate;
504 `}
505 end