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
// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

mod frame;
mod shortcuts;
mod wm;

#[cfg(test)]
mod tests;

use anyhow::Error;
use appkit::{Event, EventSender, ProductionProtocolConnector, SystemEvent, ViewSpecHolder};
use fidl_fuchsia_element as felement;
use fidl_fuchsia_ui_app as ui_app;
use fuchsia_async as fasync;
use fuchsia_component::{client::connect_to_childs_protocol, server};
use fuchsia_inspect::health::Reporter;
use fuchsia_scenic::flatland::ViewCreationTokenPair;
use futures::{
    channel::mpsc::{unbounded, UnboundedReceiver},
    StreamExt, TryStreamExt,
};
use tracing::*;

use crate::wm::{
    get_first_view_creation_token, shell_view_name_annotation, Notification, WindowManager,
    WM_SHELLVIEWS,
};

// A fun picture to print to the log when gazelle launches. This is derived from
// a drawing in the public domain, found at
// https://www.rawpixel.com/image/6502476/png-sticker-vintage.
const WELCOME_LOG: &'static str = "
             ▒▒░          ░░▒
             ▒▒▒          ░▒░
             ░▒▒░        ▒▒▒░          GAZELLE
              ▒▒▒░      ▒▒▒
              ░▓▒░     ▒▒▓░     ░░░░
   ░░░░        ▓▒▒    ░▒▒▒     ░░░░▒░
   ░▒░░░░      ▒▒▒░  ░▒▒▓   ░░▒░░░░░░
    ░░ ░▒▒▒░   ▓▒▒░  ▒▒▒▒  ░▒▒▒▒░░░
      ░░▒▒▓▒▒░░▓▓▓▒░▒▓▓▒▒▒▒▒░▒▒▒░░░
       ░░░▒▒░▒▒▓▓▓▓▓▓▓▓░░▓░░▒▒░░
          ░▒▒▒░░▓▓▒▓▓▒░  ▒░▒░░
            ░▓▓░▒▓▓▓░ ░▒▓▓▒░
             ▒▒▒░▓▓▒  ░▒▒▓▒
              ▒▒▓▓▒▒ ▒▒░▒▓▒░
              ░▒▓▒▒▒▒▒░▒▓▓░▒░
               ▒▒▒░░▒▒▓▓▓▓▒▒░
              ░▓▓▓▒░░▓▓▓▓▓▒▒▒                    ░░░    ░░░░░
               ▒▓▓▒▒▓▓▒▒▒▓▒░▒░  ░░░     ░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░
                ▒▓▓▓▓▓▒░▒▓▒▒░▓▒▒▒▒▒▒▒▒▒▒▒▒▓▒▒▒▒▒░░░░▒▒░░░░░▒▒▒▒▓▓▒▒▒░░░░░
                ░▓▓▓▓▓▒░▒▓▓░▒▒▓▒▒▒░░░▒▒▒▒▒▒░░░░░░ ░░ ░░░░▒▒▒▒▒▒▒▒▒▒▒░▒▒▓▒░
                ░▓▓▓▓▓▒▒▒▓▓▒▒░▒▒▒▒▒░ ░░░▒▒░░░░░░░░░░    ░░▒▒▒▒▒░░░░▒░░░▒▒▒▒░
                 ▒▓▓▓▓▓▒░▒▒▒▒▒▒▒▒░░ ░░  ░▒▒░░░░░░░░░░░   ░░░░▒▒▒▒░░░▒░░▒▓▒▓░
                  ▒▓▓▓▓▒░░░▒▒▒▓▒░   ░░░░░▒▒░▒▒░░░░░░░░░░    ░▒▒▒▒░  ░▒░░▓▒▓░
                  ░▒▓▓▓▒▒░░░░░▒▒░░  ░░░░░▒░░░▒░░░░░░░░░░░░  ░▓▓▒░  ░░░░▒▓▒▓▒
                   ░▒▒▓▓▓▒▒░░░░▒░░ ░░  ░░▒░░░▒▒░░░░░░░░░░▒▒▒▓▓▓▒░░░░▒░░▒▓▒▓▓░
                     ░▓▓▓▓▒▒░░░▒▒░░░░░ ░░▒░░ ░▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▒▓▓░░░░▒░░▒▓░▒▓▒
                     ░▒▓▓▒▒▒▒▒░▒▒░ ░░░░░░░░░░░▓▓▓▓▓▓▓▓▓▓▓▓▓▒░░░▒░░░▒▒░▒▒▒   ░░
                      ░░▒▒▒▒▒▒▒▒▓▒░░▒░░░░░ ░▒▒▓▓▓▓▓▓▓▓▒▒▒░ ░▒▓▒▒▒░▒▒░░▒▓▒
                        ░▒▒░░  ░░▒▒▒▒▒░▒▒▒▒▒▒▓▓▒░░░░    ░░▒▓▓▓▓▒▒▓▓▒▒▒▓▓▒
                         ░░▒░░ ░░▒▒░▒▒░▒▒▒▓▓▓▓▓▒░░░░░░░░▒░▒▓▓▓▓▓▒▒▓▓▒▒▒▓▓▒░
                           ░░▒▒▒░░▒░▒▓▒▒░▒▒▓▓▓▓▒░░░░░░░░   ░▒▓▓▓▓▓▒▓▓▒▒▓▓▓▒░
                             ░░▓▓▒▒▒▒▒▒▒░░░▒▓▓▒░             ░▒▒▒▓▓▓▓▓▓▓▒▓▓▓▒
                               ▒▓▓▓▒▒    ░░▒▓▓▒                 ░▒▓▓▓▒▒▓▒▓▓▓▒
                               ▒▒▓▒▒░    ░▒▒▒▓▒                  ░░▓▒▒░▒░▒▒░▓";

const MAX_CONCURRENT: usize = 100;

enum IncomingService {
    GraphicalPresenter(felement::GraphicalPresenterRequestStream),
    ViewProvider(ui_app::ViewProviderRequestStream),
}

#[fuchsia::main(logging = true)]
async fn main() -> Result<(), Error> {
    info!("{}", WELCOME_LOG);

    fuchsia_inspect::component::health().set_starting_up();

    // Create an event sender receiver pair.
    let (sender, mut receiver) = EventSender::new();

    // Start listening to incoming services.
    start_services(sender.clone());

    // Get the first `view_creation_token` from incoming ViewProvider::CreateView2 request.
    let (view_creation_token, view_spec_holders) =
        get_first_view_creation_token(&mut receiver).await;

    // Launch shell views.
    launch_shell_views(sender.clone()).await?;

    // Create an notification reporting sender and receiver pair.
    let (notification_sender, notification_receiver) = unbounded::<Notification>();
    start_notifications_logger(notification_receiver);

    // Create WindowManager instance and start handling events.
    let protocol_connector = Box::new(ProductionProtocolConnector());
    let mut wm = WindowManager::new(
        sender,
        notification_sender,
        view_creation_token,
        view_spec_holders,
        protocol_connector,
    )?;

    match wm.run(receiver).await {
        Err(err) => error!("Encountered error: {:?}, shutting down", err),
        Ok(()) => info!("Shutdown"),
    }

    Ok(())
}

fn start_services(sender: EventSender) {
    fasync::Task::local(async move {
        let mut fs = server::ServiceFs::new();

        fs.dir("svc").add_fidl_service(IncomingService::GraphicalPresenter);
        fs.dir("svc").add_fidl_service(IncomingService::ViewProvider);

        let inspector = fuchsia_inspect::component::inspector();
        inspect_runtime::serve(inspector, &mut fs).expect("Failed to serve inspect");

        fs.take_and_serve_directory_handle().expect("Failed to start ServiceFs");

        fs.for_each_concurrent(MAX_CONCURRENT, |request| async {
            if let Err(err) = match request {
                IncomingService::ViewProvider(request_stream) => {
                    serve_view_provider(request_stream, sender.clone()).await
                }
                IncomingService::GraphicalPresenter(request_stream) => {
                    serve_graphical_presenter(request_stream, sender.clone()).await
                }
            } {
                tracing::error!("{:?}", err);
            }
        })
        .await;
    })
    .detach();
}

fn start_notifications_logger(mut receiver: UnboundedReceiver<Notification>) {
    fasync::Task::local(async move {
        while let Some(notification) = receiver.next().await {
            // We currently just log the notification. In future, we can populate inspect data.
            debug!("{:?}", notification);
        }
    })
    .detach();
}

async fn serve_view_provider(
    mut request_stream: ui_app::ViewProviderRequestStream,
    sender: EventSender,
) -> Result<(), Error> {
    while let Some(request) = request_stream.next().await {
        match request {
            Ok(ui_app::ViewProviderRequest::CreateView2 { args, .. }) => {
                if let Some(view_creation_token) = args.view_creation_token {
                    sender.send(Event::SystemEvent {
                        event: SystemEvent::ViewCreationToken { token: view_creation_token },
                    });
                } else {
                    error!("CreateView2() missing view_creation_token field");
                }
            }
            Ok(_) => error!("ViewProvider impl only handles CreateView2"),
            Err(e) => error!("Failed to read request from ViewProvider: {:?}", e),
        }
    }
    Ok(())
}

async fn serve_graphical_presenter(
    mut request_stream: felement::GraphicalPresenterRequestStream,
    sender: EventSender,
) -> Result<(), Error> {
    while let Ok(Some(request)) = request_stream.try_next().await {
        match request {
            felement::GraphicalPresenterRequest::PresentView {
                view_spec,
                annotation_controller,
                view_controller_request,
                responder,
            } => {
                sender.send(Event::SystemEvent {
                    event: SystemEvent::PresentViewSpec {
                        view_spec_holder: ViewSpecHolder {
                            view_spec,
                            annotation_controller,
                            view_controller_request,
                            responder: Some(responder),
                        },
                    },
                });
            }
        }
    }
    Ok(())
}

async fn launch_shell_views(sender: EventSender) -> Result<(), Error> {
    for shell_view in WM_SHELLVIEWS {
        let view_provider =
            connect_to_childs_protocol::<ui_app::ViewProviderMarker>(shell_view.to_string(), None)
                .await?;
        let ViewCreationTokenPair { view_creation_token, viewport_creation_token } =
            ViewCreationTokenPair::new()?;
        view_provider.create_view2(ui_app::CreateView2Args {
            view_creation_token: Some(view_creation_token),
            ..ui_app::CreateView2Args::EMPTY
        })?;

        let name_annotation = shell_view_name_annotation(shell_view);
        let view_spec = felement::ViewSpec {
            viewport_creation_token: Some(viewport_creation_token),
            annotations: Some(vec![name_annotation]),
            ..felement::ViewSpec::EMPTY
        };

        sender.send(Event::SystemEvent {
            event: SystemEvent::PresentViewSpec {
                view_spec_holder: ViewSpecHolder {
                    view_spec,
                    annotation_controller: None,
                    view_controller_request: None,
                    responder: None,
                },
            },
        });
    }
    Ok(())
}