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