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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
pub mod bin;
pub mod checkbox;
pub mod on_off_button;
pub mod render;
pub mod scroll_bar;
pub mod slider;

use std::cmp::Reverse;
use std::collections::BTreeMap;
use std::sync::{Arc, Weak};

use ilmenite::{
    Ilmenite, ImtError, ImtFillQuality, ImtFont, ImtRasterOpts, ImtSampleQuality, ImtWeight,
};
use parking_lot::{Mutex, RwLock};
use vulkano::buffer::BufferContents;
use vulkano::command_buffer::{AutoCommandBufferBuilder, PrimaryAutoCommandBuffer};
use vulkano::device::{Device, Queue};
use vulkano::format::Format as VkFormat;
use vulkano::pipeline::graphics::vertex_input::Vertex;

use self::bin::{Bin, BinID};
use self::render::composer::{Composer, ComposerEv, ComposerInit};
pub use self::render::ItfDrawTarget;
use self::render::{ItfRenderer, ItfRendererInit};
use crate::image_view::BstImageView;
use crate::window::BstWindowID;
use crate::{Atlas, Basalt, BasaltWindow, BstOptions};

#[cfg(feature = "built_in_font")]
pub mod built_in_font {
    use ilmenite::ImtWeight;

    pub(super) const BYTES: &[u8] = include_bytes!("Roboto-Regular.ttf");
    pub const FAMILY: &str = "Roboto";
    pub const WEIGHT: ImtWeight = ImtWeight::Normal;
}

#[derive(BufferContents, Vertex, Clone, Debug)]
#[repr(C)]
pub(crate) struct ItfVertInfo {
    #[format(R32G32B32_SFLOAT)]
    pub position: [f32; 3],
    #[format(R32G32_SFLOAT)]
    pub coords: [f32; 2],
    #[format(R32G32B32A32_SFLOAT)]
    pub color: [f32; 4],
    #[format(R32_SINT)]
    pub ty: i32,
    #[format(R32_UINT)]
    pub tex_i: u32,
}

impl Default for ItfVertInfo {
    fn default() -> Self {
        ItfVertInfo {
            position: [0.0; 3],
            coords: [0.0; 2],
            color: [0.0; 4],
            ty: 0,
            tex_i: 0,
        }
    }
}

pub(crate) fn scale_verts(win_size: &[f32; 2], scale: f32, verts: &mut Vec<ItfVertInfo>) {
    for vert in verts {
        vert.position[0] *= scale;
        vert.position[1] *= scale;
        vert.position[0] += win_size[0] / -2.0;
        vert.position[0] /= win_size[0] / 2.0;
        vert.position[1] += win_size[1] / -2.0;
        vert.position[1] /= win_size[1] / 2.0;
    }
}

#[derive(Clone, Copy)]
struct Scale {
    pub win: f32,
    pub itf: f32,
}

impl Scale {
    fn effective(&self, ignore_win: bool) -> f32 {
        if ignore_win {
            self.itf
        } else {
            self.itf * self.win
        }
    }
}

pub struct Interface {
    options: BstOptions,
    ilmenite: Ilmenite,
    renderer: Mutex<ItfRenderer>,
    composer: Arc<Composer>,
    scale: Mutex<Scale>,
    bins_state: RwLock<BinsState>,
    default_font: RwLock<Option<(String, ImtWeight)>>,
}

#[derive(Default)]
struct BinsState {
    bst: Option<Arc<Basalt>>,
    id: u64,
    map: BTreeMap<BinID, Weak<Bin>>,
}

pub(crate) struct InterfaceInit {
    pub options: BstOptions,
    pub device: Arc<Device>,
    pub transfer_queue: Arc<Queue>,
    pub compute_queue: Arc<Queue>,
    pub itf_format: VkFormat,
    pub imt_format: VkFormat,
    pub atlas: Arc<Atlas>,
    pub window: Arc<dyn BasaltWindow>,
}

impl Interface {
    pub(crate) fn new(init: InterfaceInit) -> Arc<Self> {
        let InterfaceInit {
            options,
            device,
            transfer_queue,
            compute_queue: _compute_queue,
            itf_format,
            imt_format: _imt_format,
            atlas,
            window,
        } = init;

        let ilmenite = Ilmenite::new();

        #[cfg(feature = "built_in_font")]
        {
            let fill_quality = options.imt_fill_quality.unwrap_or(ImtFillQuality::Normal);
            let sample_quality = options
                .imt_sample_quality
                .unwrap_or(ImtSampleQuality::Normal);

            if options.imt_gpu_accelerated {
                ilmenite.add_font(
                    ImtFont::from_bytes_gpu(
                        built_in_font::FAMILY,
                        built_in_font::WEIGHT,
                        ImtRasterOpts {
                            fill_quality,
                            sample_quality,
                            raster_image_format: _imt_format,
                            ..ImtRasterOpts::default()
                        },
                        device.clone(),
                        _compute_queue,
                        built_in_font::BYTES.to_vec(),
                    )
                    .unwrap(),
                );
            } else {
                ilmenite.add_font(
                    ImtFont::from_bytes_cpu(
                        built_in_font::FAMILY,
                        built_in_font::WEIGHT,
                        ImtRasterOpts {
                            fill_quality,
                            sample_quality,
                            ..ImtRasterOpts::default()
                        },
                        built_in_font::BYTES.to_vec(),
                    )
                    .unwrap(),
                );
            }
        }

        let scale = Scale {
            win: window.scale_factor(),
            itf: options.scale,
        };

        let composer = Composer::new(ComposerInit {
            options: options.clone(),
            device: device.clone(),
            transfer_queue,
            atlas: atlas.clone(),
            initial_scale: scale.effective(options.ignore_dpi),
        });

        Arc::new(Interface {
            bins_state: RwLock::new(BinsState::default()),
            scale: Mutex::new(scale),
            ilmenite,
            renderer: Mutex::new(ItfRenderer::new(ItfRendererInit {
                options: options.clone(),
                device,
                itf_format,
                atlas,
                composer: composer.clone(),
            })),
            composer,
            options,
            default_font: RwLock::new({
                #[cfg(feature = "built_in_font")]
                {
                    Some((built_in_font::FAMILY.to_string(), built_in_font::WEIGHT))
                }
                #[cfg(not(feature = "built_in_font"))]
                {
                    None
                }
            }),
        })
    }

    pub(crate) fn ilmenite(&self) -> &Ilmenite {
        &self.ilmenite
    }

    pub(crate) fn attach_basalt(&self, basalt: Arc<Basalt>) {
        let mut bins_state = self.bins_state.write();
        bins_state.bst = Some(basalt);
    }

    /// Returns the default font used currently.
    ///
    /// # Notes
    /// - If `built_in_font` feature is not enabled and `set_default_font` has not been called this will be `None`.
    pub fn default_font(&self) -> Option<(String, ImtWeight)> {
        self.default_font.read().clone()
    }

    /// Set the default font family and weight.
    pub fn set_default_font<F: Into<String>>(
        &self,
        family: F,
        weight: ImtWeight,
    ) -> Result<(), String> {
        let family = family.into();

        if !self.ilmenite.has_font(&family, weight) {
            return Err(format!(
                "Font family '{}' with the weight of {:?} has not been loaded.",
                family, weight
            ));
        }

        *self.default_font.write() = Some((family, weight));
        Ok(())
    }

    pub fn has_font<F: AsRef<str>>(&self, family: F, weight: ImtWeight) -> bool {
        self.ilmenite.has_font(family.as_ref(), weight)
    }

    /// Add a font that is available to use.
    ///
    /// # Notes
    /// - Overwrites previous font if added with same family and weight.
    /// - This does not set the default font. Use `set_default_font` to do this.
    pub fn add_font<F: AsRef<str>>(
        &self,
        family: F,
        weight: ImtWeight,
        bytes: Vec<u8>,
    ) -> Result<(), ImtError> {
        let fill_quality = self
            .options
            .imt_fill_quality
            .unwrap_or(ImtFillQuality::Normal);
        let sample_quality = self
            .options
            .imt_sample_quality
            .unwrap_or(ImtSampleQuality::Normal);

        if self.options.imt_gpu_accelerated {
            let (device, compute_queue, imt_format) = {
                let bin_state = self.bins_state.read();
                let basalt = bin_state
                    .bst
                    .as_ref()
                    .expect("Interface hasn't had Basalt set yet!");

                (
                    basalt.device(),
                    basalt.compute_queue(),
                    basalt.formats_in_use().atlas,
                )
            };

            self.ilmenite.add_font(ImtFont::from_bytes_gpu(
                family.as_ref(),
                weight,
                ImtRasterOpts {
                    fill_quality,
                    sample_quality,
                    raster_image_format: imt_format,
                    ..ImtRasterOpts::default()
                },
                device,
                compute_queue,
                bytes,
            )?);
        } else {
            self.ilmenite.add_font(ImtFont::from_bytes_cpu(
                family.as_ref(),
                weight,
                ImtRasterOpts {
                    fill_quality,
                    sample_quality,
                    ..ImtRasterOpts::default()
                },
                bytes,
            )?);
        }

        Ok(())
    }

    /// The current scale without taking into account dpi based window scaling.
    pub fn current_scale(&self) -> f32 {
        self.scale.lock().itf
    }

    /// The current scale taking into account dpi based window scaling.
    pub fn current_effective_scale(&self) -> f32 {
        let ignore_dpi = self.options.ignore_dpi;
        self.scale.lock().effective(ignore_dpi)
    }

    /// Set the current scale. Doesn't account for dpi based window scaling.
    pub fn set_scale(&self, set_scale: f32) {
        let ignore_dpi = self.options.ignore_dpi;
        let mut scale = self.scale.lock();
        scale.itf = set_scale;
        self.composer
            .send_event(ComposerEv::Scale(scale.effective(ignore_dpi)));
    }

    pub(crate) fn set_window_scale(&self, set_scale: f32) {
        let ignore_dpi = self.options.ignore_dpi;
        let mut scale = self.scale.lock();
        scale.win = set_scale;
        self.composer
            .send_event(ComposerEv::Scale(scale.effective(ignore_dpi)));
    }

    /// Set the current scale taking into account dpi based window scaling.
    pub fn set_effective_scale(&self, set_scale: f32) {
        let ignore_dpi = self.options.ignore_dpi;
        let mut scale = self.scale.lock();

        if ignore_dpi {
            scale.itf = set_scale;
        } else {
            scale.itf = set_scale / scale.win;
        };

        self.composer
            .send_event(ComposerEv::Scale(scale.effective(ignore_dpi)));
    }

    /// Get the current MSAA level.
    pub fn current_msaa(&self) -> BstMSAALevel {
        let mut renderer = self.renderer.lock();
        *renderer.msaa_mut_ref()
    }

    /// Set the MSAA Level.
    pub fn set_msaa(&self, set_msaa: BstMSAALevel) {
        let mut renderer = self.renderer.lock();
        *renderer.msaa_mut_ref() = set_msaa;
    }

    /// Increase MSAA to the next step.
    pub fn increase_msaa(&self) -> BstMSAALevel {
        let mut renderer = self.renderer.lock();
        renderer.msaa_mut_ref().increase();
        *renderer.msaa_mut_ref()
    }

    /// Decrease MSAA to the next step.
    pub fn decrease_msaa(&self) -> BstMSAALevel {
        let mut renderer = self.renderer.lock();
        renderer.msaa_mut_ref().decrease();
        *renderer.msaa_mut_ref()
    }

    pub(crate) fn composer_ref(&self) -> &Arc<Composer> {
        &self.composer
    }

    #[inline]
    pub fn get_bin_id_atop(&self, window: BstWindowID, x: f32, y: f32) -> Option<BinID> {
        self.get_bins_atop(window, x, y)
            .into_iter()
            .next()
            .map(|bin| bin.id())
    }

    #[inline]
    pub fn get_bin_atop(&self, window: BstWindowID, x: f32, y: f32) -> Option<Arc<Bin>> {
        self.get_bins_atop(window, x, y).into_iter().next()
    }

    /// Get the `Bin`'s that are at the given mouse position accounting for current effective
    /// scale. Returned `Vec` is sorted where the top-most `Bin`'s are first.
    pub fn get_bins_atop(&self, _window: BstWindowID, mut x: f32, mut y: f32) -> Vec<Arc<Bin>> {
        // TODO: Check window

        let scale = self.current_effective_scale();
        x /= scale;
        y /= scale;

        let mut bins: Vec<_> = self
            .bins_state
            .read()
            .map
            .iter()
            .filter_map(|(_, bin_wk)| {
                match bin_wk.upgrade() {
                    Some(bin) if bin.mouse_inside(x, y) => Some(bin),
                    _ => None,
                }
            })
            .collect();

        bins.sort_by_cached_key(|bin| Reverse(bin.post_update().z_index));
        bins
    }

    /// Get the `BinID`'s that are at the given mouse position accounting for current effective
    /// scale. Returned `Vec` is sorted where the top-most `Bin`'s are first.
    #[inline]
    pub fn get_bin_ids_atop(&self, window: BstWindowID, x: f32, y: f32) -> Vec<BinID> {
        self.get_bins_atop(window, x, y)
            .into_iter()
            .map(|bin| bin.id())
            .collect()
    }

    /// Returns a list of all bins that have a strong reference. Note keeping this
    /// list will keep all bins returned alive and prevent them from being dropped.
    /// This list should be dropped asap to prevent issues with bins being dropped.
    pub fn bins(&self) -> Vec<Arc<Bin>> {
        self.bins_state
            .read()
            .map
            .iter()
            .filter_map(|(_, b)| b.upgrade())
            .collect()
    }

    pub fn new_bins(&self, amt: usize) -> Vec<Arc<Bin>> {
        let mut out = Vec::with_capacity(amt);
        let mut bins_state = self.bins_state.write();

        for _ in 0..amt {
            let id = BinID(bins_state.id);
            bins_state.id += 1;
            let bin = Bin::new(id, bins_state.bst.clone().unwrap());
            bins_state.map.insert(id, Arc::downgrade(&bin));
            self.composer
                .send_event(ComposerEv::AddBin(Arc::downgrade(&bin)));
            out.push(bin);
        }

        out
    }

    pub fn new_bin(&self) -> Arc<Bin> {
        self.new_bins(1).pop().unwrap()
    }

    pub fn get_bin(&self, id: BinID) -> Option<Arc<Bin>> {
        match self.bins_state.read().map.get(&id) {
            Some(some) => some.upgrade(),
            None => None,
        }
    }

    /// Checks if the mouse position is on top of any `Bin`'s in the interface.
    pub fn mouse_inside(&self, _window: BstWindowID, mut mouse_x: f32, mut mouse_y: f32) -> bool {
        let scale = self.current_effective_scale();
        mouse_x /= scale;
        mouse_y /= scale;

        for bin in self.bins() {
            if bin.mouse_inside(mouse_x, mouse_y) {
                return true;
            }
        }

        false
    }

    pub fn draw(
        &self,
        cmd: AutoCommandBufferBuilder<PrimaryAutoCommandBuffer>,
        target: ItfDrawTarget,
    ) -> (
        AutoCommandBufferBuilder<PrimaryAutoCommandBuffer>,
        Option<Arc<BstImageView>>,
    ) {
        self.renderer.lock().draw(cmd, target)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BstMSAALevel {
    One,
    Two,
    Four,
    Eight,
}

impl PartialOrd for BstMSAALevel {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for BstMSAALevel {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_u32().cmp(&other.as_u32())
    }
}

impl BstMSAALevel {
    pub(crate) fn as_u32(&self) -> u32 {
        match self {
            Self::One => 1,
            Self::Two => 2,
            Self::Four => 4,
            Self::Eight => 8,
        }
    }

    pub(crate) fn as_vulkano(&self) -> vulkano::image::SampleCount {
        match self {
            Self::One => vulkano::image::SampleCount::Sample1,
            Self::Two => vulkano::image::SampleCount::Sample2,
            Self::Four => vulkano::image::SampleCount::Sample4,
            Self::Eight => vulkano::image::SampleCount::Sample8,
        }
    }

    pub fn increase(&mut self) {
        *self = match self {
            Self::One => Self::Two,
            Self::Two => Self::Four,
            Self::Four => Self::Eight,
            Self::Eight => Self::Eight,
        };
    }

    pub fn decrease(&mut self) {
        *self = match self {
            Self::One => Self::One,
            Self::Two => Self::One,
            Self::Four => Self::Two,
            Self::Eight => Self::Four,
        };
    }
}