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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
use std::marker::PhantomData;
use std::sync::Arc;

use arboard::Clipboard;
use kludgine::app::{AppEvent, AsApplication};
use parking_lot::{Mutex, MutexGuard};

use crate::animation;
use crate::fonts::FontCollection;
use crate::window::sealed::WindowCommand;
use crate::window::WindowHandle;

/// A Cushy application that has not started running yet.
pub struct PendingApp {
    app: kludgine::app::PendingApp<WindowCommand>,
    cushy: Cushy,
}

impl PendingApp {
    /// Returns a new app using the provided runtime.
    pub fn new<Runtime: AppRuntime>(runtime: Runtime) -> Self {
        Self {
            app: kludgine::app::PendingApp::default(),
            cushy: Cushy::new(BoxedRuntime(Box::new(runtime))),
        }
    }

    /// The shared resources this application utilizes.
    #[must_use]
    pub const fn cushy(&self) -> &Cushy {
        &self.cushy
    }
}

impl Run for PendingApp {
    fn run(self) -> crate::Result {
        let _guard = self.cushy.enter_runtime();
        animation::spawn(self.cushy.clone());
        self.app.run()
    }
}

impl Default for PendingApp {
    fn default() -> Self {
        Self::new(DefaultRuntime::default())
    }
}

impl AsApplication<AppEvent<WindowCommand>> for PendingApp {
    fn as_application(&self) -> &dyn kludgine::app::Application<AppEvent<WindowCommand>> {
        self.app.as_application()
    }

    fn as_application_mut(&mut self) -> &mut dyn kludgine::app::Application<AppEvent<WindowCommand>>
    where
        AppEvent<WindowCommand>: kludgine::app::Message,
    {
        self.app.as_application_mut()
    }
}

/// A runtime associated with the Cushy application.
///
/// This trait is how Cushy adds optional support for `tokio`.
pub trait AppRuntime: Send + Clone + 'static {
    /// The guard type returned from entering the context of the app's runtime.
    type Guard<'a>;

    /// Enter the application's rutime context.
    fn enter(&self) -> Self::Guard<'_>;
}

/// A default application runtime.
///
/// When the `tokio` feature is enabled, a tokio runtime is spawned when this
/// runtime is used in Cushy.
#[derive(Debug, Clone, Default)]
pub struct DefaultRuntime {
    #[cfg(feature = "tokio")]
    tokio: TokioRuntime,
    _private: (),
}

impl AppRuntime for DefaultRuntime {
    type Guard<'a> = DefaultRuntimeGuard<'a>;

    fn enter(&self) -> Self::Guard<'_> {
        DefaultRuntimeGuard {
            #[cfg(feature = "tokio")]
            _tokio: self.tokio.enter(),
            _phantom: PhantomData,
        }
    }
}

pub struct DefaultRuntimeGuard<'a> {
    #[cfg(feature = "tokio")]
    _tokio: ::tokio::runtime::EnterGuard<'a>,
    _phantom: PhantomData<&'a ()>,
}

#[cfg(feature = "tokio")]
mod tokio {
    use std::future::Future;
    use std::ops::Deref;
    use std::task::Poll;
    use std::thread;

    use tokio::runtime::{self, Handle};

    use super::AppRuntime;
    use crate::Lazy;

    /// A spawned `tokio` runtime.
    #[derive(Debug, Clone)]
    pub struct TokioRuntime {
        pub(crate) handle: Handle,
    }

    impl From<Handle> for TokioRuntime {
        fn from(handle: Handle) -> Self {
            Self { handle }
        }
    }

    static TOKIO: Lazy<Handle> = Lazy::new(|| {
        #[cfg(feature = "tokio-multi-thread")]
        let mut rt = runtime::Builder::new_multi_thread();
        #[cfg(not(feature = "tokio-multi-thread"))]
        let mut rt = runtime::Builder::new_current_thread();
        let runtime = rt
            .enable_all()
            .build()
            .expect("failure to initialize tokio");
        let handle = runtime.handle().clone();
        thread::Builder::new()
            .name(String::from("tokio"))
            .spawn(move || {
                runtime.block_on(BlockForever);
            })
            .expect("error spawning tokio thread");
        handle
    });

    impl Default for TokioRuntime {
        fn default() -> Self {
            Self {
                handle: TOKIO.clone(),
            }
        }
    }

    impl Deref for TokioRuntime {
        type Target = Handle;

        fn deref(&self) -> &Self::Target {
            &self.handle
        }
    }

    struct BlockForever;
    impl Future for BlockForever {
        type Output = ();

        fn poll(
            self: std::pin::Pin<&mut Self>,
            _cx: &mut std::task::Context<'_>,
        ) -> Poll<Self::Output> {
            Poll::<()>::Pending
        }
    }

    impl AppRuntime for TokioRuntime {
        type Guard<'a> = tokio::runtime::EnterGuard<'a>;

        fn enter(&self) -> Self::Guard<'_> {
            self.handle.enter()
        }
    }
}

#[cfg(feature = "tokio")]
pub use tokio::TokioRuntime;

struct BoxedRuntime(Box<dyn BoxableRuntime>);

impl Clone for BoxedRuntime {
    fn clone(&self) -> Self {
        self.0.cloned()
    }
}

trait BoxableRuntime: Send {
    fn enter_runtime(&self) -> RuntimeGuard<'_>;
    fn cloned(&self) -> BoxedRuntime;
}

impl<T> BoxableRuntime for T
where
    T: AppRuntime,
    for<'a> T::Guard<'a>: BoxableGuard<'a>,
{
    fn enter_runtime(&self) -> RuntimeGuard<'_> {
        RuntimeGuard(Box::new(AppRuntime::enter(self)))
    }

    fn cloned(&self) -> BoxedRuntime {
        BoxedRuntime(Box::new(self.clone()))
    }
}

#[allow(dead_code)]
pub struct RuntimeGuard<'a>(Box<dyn BoxableGuard<'a> + 'a>);

trait BoxableGuard<'a> {}
impl<'a, T> BoxableGuard<'a> for T {}

/// Shared resources for a GUI application.
#[derive(Clone)]
pub struct Cushy {
    pub(crate) clipboard: Option<Arc<Mutex<Clipboard>>>,
    pub(crate) fonts: FontCollection,
    runtime: BoxedRuntime,
}

impl Cushy {
    fn new(runtime: BoxedRuntime) -> Self {
        Self {
            clipboard: Clipboard::new()
                .ok()
                .map(|clipboard| Arc::new(Mutex::new(clipboard))),
            fonts: FontCollection::default(),
            runtime,
        }
    }

    /// Returns a locked mutex guard to the OS's clipboard, if one was able to be
    /// initialized when the window opened.
    #[must_use]
    pub fn clipboard_guard(&self) -> Option<MutexGuard<'_, Clipboard>> {
        self.clipboard.as_ref().map(|mutex| mutex.lock())
    }

    /// Returns the font collection that will be loaded in all Cushy windows.
    #[must_use]
    pub fn fonts(&self) -> &FontCollection {
        &self.fonts
    }

    /// Enters the application's runtime context.
    ///
    /// When the `tokio` feature is enabled, the guard returned by this function
    /// allows for functions like `tokio::spawn` to work for the current thread.
    /// Outside of application startup, this function shouldn't need to be
    /// called unless you are manually spawning threads.
    #[must_use]
    pub fn enter_runtime(&self) -> RuntimeGuard<'_> {
        self.runtime.0.enter_runtime()
    }
}

impl Default for Cushy {
    fn default() -> Self {
        Self::new(BoxedRuntime(Box::<DefaultRuntime>::default()))
    }
}

/// A type that is a Cushy application.
pub trait Application: AsApplication<AppEvent<WindowCommand>> {
    /// Returns the shared resources for the application.
    fn cushy(&self) -> &Cushy;
    /// Returns this type as an [`App`] handle.
    fn as_app(&self) -> App;
}

impl Application for PendingApp {
    fn cushy(&self) -> &Cushy {
        &self.cushy
    }

    fn as_app(&self) -> App {
        App {
            app: Some(self.app.as_app()),
            cushy: self.cushy.clone(),
        }
    }
}

/// A handle to a Cushy application.
#[derive(Clone)]
pub struct App {
    app: Option<kludgine::app::App<WindowCommand>>,
    cushy: Cushy,
}

impl Application for App {
    fn cushy(&self) -> &Cushy {
        &self.cushy
    }

    fn as_app(&self) -> App {
        self.clone()
    }
}

impl AsApplication<AppEvent<WindowCommand>> for App {
    fn as_application(&self) -> &dyn kludgine::app::Application<AppEvent<WindowCommand>> {
        self.app
            .as_ref()
            .map(AsApplication::as_application)
            .expect("no app")
    }

    fn as_application_mut(&mut self) -> &mut dyn kludgine::app::Application<AppEvent<WindowCommand>>
    where
        AppEvent<WindowCommand>: kludgine::app::Message,
    {
        self.app
            .as_mut()
            .map(AsApplication::as_application_mut)
            .expect("no app")
    }
}

/// A type that can be run as an application.
pub trait Run: Sized {
    /// Runs the provided type, returning `Ok(())` upon successful execution and
    /// program exit. Note that this function may not ever return on some
    /// platforms.
    fn run(self) -> crate::Result;
}

/// A type that can be opened as a window in an application.
pub trait Open: Sized {
    /// Opens the provided type as a window inside of `app`.
    fn open<App>(self, app: &mut App) -> crate::Result<Option<WindowHandle>>
    where
        App: Application + ?Sized;

    /// Runs the provided type inside of the pending `app`, returning `Ok(())`
    /// upon successful execution and program exit. Note that this function may
    /// not ever return on some platforms.
    fn run_in(self, app: PendingApp) -> crate::Result;
}