1    let contains_mouse (control : Control
2                        x : u32
3                        y : u32) =
4        let position = control.global_position
5        let width = control.width
6        let height = control.height
7    
8        x as f32 >= position.x
9        && y as f32 >= position.y
10       && x as f32 < position.x + width as f32
11       && y as f32 < position.y + height as f32
12   
13   local find_control (control : Control
14                       x : u32
15                       y : u32
16                       f : Control -> bool) : Option<Control> =
17       let slice = if control is Container
18                   then control.get_slice
19                   else SafeSlice<Control>.empty
20   
21       let controls = if slice.is_empty then
22           List<Control>.empty
23       else
24           slice
25           |> filter { item -> item.is_visible && contains_mouse item x y }
26           |> map { find_control _ x y f }
27           |> filter { _.is_some }
28           |> map { _.unwrap }
29   
30       when
31           controls.size > 1 -> controls.min_by { _.global_position.z } |> Some
32           controls.size == 1 -> Some controls[0]
33           else -> if f control
34                   then Some control
35                   else None
36   
37   local find_focusable (control : Control) : Option<Control> =
38       if control.is_focusable
39       then Some control
40       else control.parent.flat_map { find_focusable _ }
41   
42   local get_control (controls : List<Control>
43                      x : u32
44                      y : u32) =
45       controls.try_find_index
46           { control -> control.is_visible && contains_mouse control x y }
47       |> map { controls[_] }
48   
49   local try_window (control : Control) : Option<Window> =
50       control.parent.flat_map { parent -> if parent is Window
51                                           then Some parent
52                                           else try_window parent }
53   
54   def bring_to_front (window : Window) =
55       let canvas = window.parent.unwrap as Canvas
56       let items = canvas.items
57       if window as Control <> items[0] then
58           items.remove window
59           items.add 0 window
60           let mut z = Control.window_z
61           for i = items.size - 1 downto 0 do
62               let item = items[i]
63               item.set_z z
64               z += Control.window_z
65