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
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
use derivative::Derivative;
use serde::de::DeserializeOwned;
use std::{
    fmt::{Debug, Formatter},
    marker::PhantomData,
};

use amethyst_assets::{
    AssetPrefab, AssetStorage, Format, Handle, Loader, Prefab, PrefabData, PrefabLoaderSystem,
    PrefabLoaderSystemDesc, Progress, ProgressCounter,
};
use amethyst_audio::Source as Audio;
use amethyst_core::{
    ecs::{
        prelude::{Entities, Entity, Read, ReadExpect, World, Write, WriteStorage},
        shred::{ResourceId, SystemData},
    },
    HiddenPropagate,
};
use amethyst_error::{format_err, Error, ResultExt};
use amethyst_rendy::TexturePrefab;

use serde::{Deserialize, Serialize};

use crate::{
    get_default_font, Anchor, FontAsset, Interactable, LineMode, Selectable, Stretch, TextEditing,
    UiButton, UiButtonAction, UiButtonActionRetrigger, UiButtonActionType, UiImage,
    UiPlaySoundAction, UiSoundRetrigger, UiText, UiTransform, WidgetId, Widgets,
};

/// Loadable `UiTransform` data.
/// By default z is equal to one.
#[derive(Debug, Clone, Deserialize, Serialize, Derivative)]
#[serde(default)]
#[derivative(Default)]
pub struct UiTransformData<G> {
    /// An identifier. Serves no purpose other than to help you distinguish between UI elements.
    pub id: String,
    /// X coordinate
    pub x: f32,
    /// Y coordinate
    pub y: f32,
    #[derivative(Default(value = "1.0"))]
    /// Z coordinate, defaults to one.
    pub z: f32,
    /// The width of this UI element.
    pub width: f32,
    /// The height of this UI element.
    pub height: f32,
    /// Indicates if actions on the ui can go through this element.
    /// If set to false, the element will behaves as if it was transparent and will let events go to
    /// the next element (for example, the text on a button).
    #[derivative(Default(value = "true"))]
    pub opaque: bool,
    /// Renders this UI element by evaluating transform as a percentage of the parent size,
    /// rather than rendering it with pixel units.
    pub percent: bool,
    /// If a child ui element needs to fill its parent this can be used to stretch it to the appropriate size.
    pub stretch: Option<Stretch>,
    /// Indicates where the element sits, relative to the parent (or to the screen, if there is no parent)
    #[derivative(Default(value = "Anchor::Middle"))]
    pub anchor: Anchor,
    /// Indicates where the element sits, relative to itself
    #[derivative(Default(value = "Anchor::Middle"))]
    pub pivot: Anchor,
    /// Allow mouse events on this UI element.
    pub mouse_reactive: bool,
    /// Hides an entity by adding a [`HiddenPropagate`](../amethyst_renderer/struct.HiddenPropagate.html) component
    pub hidden: bool,
    /// Makes the UiTransform selectable through keyboard inputs, mouse inputs and other means.
    /// # Ordering
    /// The UI element tab order.  When the player presses tab the UI focus will shift to the
    /// UI element with the next highest tab order, or if another element with the same tab_order
    /// as this one exists they are ordered according to Entity creation order.  Shift-tab walks
    /// this ordering backwards.
    // TODO: Make full prefab for Selectable.
    pub selectable: Option<u32>,
    #[serde(skip)]
    _phantom: PhantomData<G>,
}

impl<G> UiTransformData<G> {
    /// Set id
    pub fn with_id<S>(mut self, id: S) -> Self
    where
        S: ToString,
    {
        self.id = id.to_string();
        self
    }

    /// Set position
    pub fn with_position(mut self, x: f32, y: f32, z: f32) -> Self {
        self.x = x;
        self.y = y;
        self.z = z;
        self
    }

    /// Set size
    pub fn with_size(mut self, width: f32, height: f32) -> Self {
        self.width = width;
        self.height = height;
        self
    }

    /// Set to event transparent
    pub fn transparent(mut self) -> Self {
        self.opaque = false;
        self
    }

    /// Hides an entity by adding a [`HiddenPropagate`](../amethyst_renderer/struct.HiddenPropagate.html) component
    pub fn hide(mut self) -> Self {
        self.hidden = true;
        self
    }

    /// Add mouse reactive
    pub fn reactive(mut self) -> Self {
        self.mouse_reactive = true;
        self
    }

    /// Set anchor
    pub fn with_anchor(mut self, anchor: Anchor) -> Self {
        self.anchor = anchor;
        self
    }

    /// Set stretch
    pub fn with_stretch(mut self, stretch: Stretch) -> Self {
        self.stretch = Some(stretch);
        self
    }
}

impl<'a, G> PrefabData<'a> for UiTransformData<G>
where
    G: Send + Sync + 'static,
{
    type SystemData = (
        WriteStorage<'a, UiTransform>,
        WriteStorage<'a, Interactable>,
        WriteStorage<'a, HiddenPropagate>,
        WriteStorage<'a, Selectable<G>>,
    );
    type Result = ();

    fn add_to_entity(
        &self,
        entity: Entity,
        system_data: &mut Self::SystemData,
        _: &[Entity],
        _: &[Entity],
    ) -> Result<(), Error> {
        let mut transform = UiTransform::new(
            self.id.clone(),
            self.anchor.clone(),
            self.pivot.clone(),
            self.x,
            self.y,
            self.z,
            self.width,
            self.height,
        );
        if let Some(ref stretch) = self.stretch {
            transform = transform.with_stretch(stretch.clone());
        }
        if !self.opaque {
            transform = transform.into_transparent();
        }
        if self.percent {
            transform = transform.into_percent();
        }
        system_data.0.insert(entity, transform)?;
        if self.mouse_reactive {
            system_data.1.insert(entity, Interactable)?;
        }

        if self.hidden {
            system_data.2.insert(entity, HiddenPropagate)?;
        }

        if let Some(u) = self.selectable {
            system_data.3.insert(entity, Selectable::<G>::new(u))?;
        }

        Ok(())
    }
}

/// Loadable `UiText` data
///
/// ### Type parameters:
///
/// - `F`: `Format` used for loading `FontAsset`
/// - `G`: Selection Group Type
#[derive(Deserialize, Serialize, Clone)]
pub struct UiTextData {
    /// Text to display
    pub text: String,
    /// Font size
    pub font_size: f32,
    /// Font color
    pub color: [f32; 4],
    /// Font
    pub font: Option<AssetPrefab<FontAsset>>,
    /// Should the text be shown as dots instead of the proper characters?
    #[serde(default)]
    pub password: bool,
    /// Where should the text be aligned from. Relative to its own UiTransform's area.
    pub align: Option<Anchor>,
    /// How should the text behave with line breaks.
    pub line_mode: Option<LineMode>,
    /// Optionally make the text editable
    #[serde(default)]
    pub editable: Option<TextEditingPrefab>,
}
impl Debug for UiTextData {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let font = match self.font.as_ref() {
            Some(asset_prefab) => match asset_prefab {
                AssetPrefab::File(path, _) => format!("<Font:{}>", path),
                _ => "<Font>".to_string(),
            },
            _ => "<Font>".to_string(),
        };

        f.debug_struct("UiTextData")
            .field("text", &self.text)
            .field("font_size", &self.font_size)
            .field("font", &font)
            .field("color", &self.color)
            .field("password", &self.password)
            .field("align", &self.align)
            .field("line_mode", &self.line_mode)
            .field("editable", &self.editable)
            .finish()
    }
}

/// Loadable `TextEditing` data
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct TextEditingPrefab {
    /// Max number of graphemes
    pub max_length: usize,
    /// Text color on selection
    pub selected_text_color: [f32; 4],
    /// Background color on selection
    pub selected_background_color: [f32; 4],
    /// Use block cursor instead of line cursor
    pub use_block_cursor: bool,
}

impl Default for TextEditingPrefab {
    fn default() -> Self {
        TextEditingPrefab {
            max_length: 20,
            selected_text_color: [0., 0., 0., 1.],
            selected_background_color: [1., 1., 1., 1.],
            use_block_cursor: false,
        }
    }
}

impl<'a> PrefabData<'a> for UiTextData {
    type SystemData = (
        WriteStorage<'a, UiText>,
        WriteStorage<'a, TextEditing>,
        <AssetPrefab<FontAsset> as PrefabData<'a>>::SystemData,
    );
    type Result = ();

    fn add_to_entity(
        &self,
        entity: Entity,
        system_data: &mut Self::SystemData,
        _: &[Entity],
        _: &[Entity],
    ) -> Result<(), Error> {
        let (ref mut texts, ref mut editables, ref mut fonts) = system_data;
        let font_handle = self
            .font
            .as_ref()
            .ok_or_else(|| format_err!("did not load sub assets"))?
            .add_to_entity(entity, fonts, &[], &[])?;
        let mut ui_text = UiText::new(font_handle, self.text.clone(), self.color, self.font_size);
        ui_text.password = self.password;

        if let Some(ref align) = self.align {
            ui_text.align = align.clone();
        }

        if let Some(ref line_mode) = self.line_mode {
            ui_text.line_mode = line_mode.clone();
        }

        texts.insert(entity, ui_text)?;
        if let Some(ref editing) = self.editable {
            editables.insert(
                entity,
                TextEditing::new(
                    editing.max_length,
                    editing.selected_text_color,
                    editing.selected_background_color,
                    editing.use_block_cursor,
                ),
            )?;
        }
        Ok(())
    }

    fn load_sub_assets(
        &mut self,
        progress: &mut ProgressCounter,
        system_data: &mut Self::SystemData,
    ) -> Result<bool, Error> {
        let (_, _, ref mut fonts) = system_data;

        self.font
            .get_or_insert_with(|| {
                let (ref loader, _, ref storage) = fonts;
                AssetPrefab::Handle(get_default_font(loader, storage))
            })
            .load_sub_assets(progress, fonts)
    }
}

/// Loadable `UiImage` data. Adds UiImage component to the entity.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
pub struct UiImagePrefab(UiImageLoadPrefab);

/// Loadable `UiImage` data. Returns image component from `add_to_entity` instead of adding it.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename = "UiImagePrefab")]
pub enum UiImageLoadPrefab {
    /// A textured image
    Texture(TexturePrefab),
    /// A partial textured image
    PartialTexture(TexturePrefab, f32, f32, f32, f32),
    /// Solid color image
    SolidColor(f32, f32, f32, f32),
    /// 9-Slice image
    NineSlice {
        x_start: u32,
        y_start: u32,
        width: u32,
        height: u32,
        left_dist: u32,
        right_dist: u32,
        top_dist: u32,
        bottom_dist: u32,
        tex: TexturePrefab,
        texture_dimensions: (u32, u32),
    },
}

impl<'a> PrefabData<'a> for UiImagePrefab {
    type SystemData = (
        <UiImageLoadPrefab as PrefabData<'a>>::SystemData,
        WriteStorage<'a, UiImage>,
    );

    type Result = ();

    fn add_to_entity(
        &self,
        entity: Entity,
        (ref mut inner, ref mut images): &mut Self::SystemData,
        entities: &[Entity],
        children: &[Entity],
    ) -> Result<(), Error> {
        let image = self.0.add_to_entity(entity, inner, entities, children)?;
        images.insert(entity, image)?;
        Ok(())
    }
    fn load_sub_assets(
        &mut self,
        progress: &mut ProgressCounter,
        (ref mut inner, _): &mut Self::SystemData,
    ) -> Result<bool, Error> {
        self.0.load_sub_assets(progress, inner)
    }
}

impl<'a> PrefabData<'a> for UiImageLoadPrefab {
    type SystemData = (<TexturePrefab as PrefabData<'a>>::SystemData);
    type Result = UiImage;

    fn add_to_entity(
        &self,
        entity: Entity,
        textures: &mut Self::SystemData,
        entities: &[Entity],
        children: &[Entity],
    ) -> Result<UiImage, Error> {
        let image = match self {
            UiImageLoadPrefab::Texture(tex) => {
                UiImage::Texture(tex.add_to_entity(entity, textures, entities, children)?)
            }
            UiImageLoadPrefab::PartialTexture(tex, left, right, bottom, top) => {
                UiImage::PartialTexture(
                    tex.add_to_entity(entity, textures, entities, children)?,
                    [*left, *right, *bottom, *top].into(),
                )
            }
            UiImageLoadPrefab::NineSlice {
                x_start,
                y_start,
                height,
                width,
                left_dist,
                right_dist,
                top_dist,
                bottom_dist,
                tex,
                texture_dimensions,
            } => UiImage::NineSlice {
                x_start: *x_start,
                y_start: *y_start,
                height: *height,
                width: *width,
                left_dist: *left_dist,
                right_dist: *right_dist,
                top_dist: *top_dist,
                bottom_dist: *bottom_dist,
                tex: tex.add_to_entity(entity, textures, entities, children)?,
                texture_dimensions: [texture_dimensions.0, texture_dimensions.1],
            },
            UiImageLoadPrefab::SolidColor(r, g, b, a) => UiImage::SolidColor([*r, *g, *b, *a]),
        };
        Ok(image)
    }

    fn load_sub_assets(
        &mut self,
        progress: &mut ProgressCounter,
        textures: &mut Self::SystemData,
    ) -> Result<bool, Error> {
        match self {
            UiImageLoadPrefab::Texture(tex) => tex.load_sub_assets(progress, textures),
            UiImageLoadPrefab::PartialTexture(tex, ..) => tex.load_sub_assets(progress, textures),
            UiImageLoadPrefab::NineSlice { tex, .. } => tex.load_sub_assets(progress, textures),
            UiImageLoadPrefab::SolidColor(..) => Ok(false),
        }
    }
}

/// Loadable `UiButton` data
///
/// ### Type parameters:
///
/// - `W`: Type used for Widget IDs
#[derive(Deserialize, Serialize, Clone)]
pub struct UiButtonData<W: WidgetId = u32> {
    /// Id for the widget
    pub id: Option<W>,
    /// Text to display
    pub text: String,
    /// Font size
    pub font_size: f32,
    /// Font
    pub font: Option<AssetPrefab<FontAsset>>,
    /// Default text color
    pub normal_text_color: [f32; 4],
    // this `normal_image` is "transplanted" into UiImagePrefab at the top level
    // of ui widegt. This happens inside `walk_ui_tree` function. It means that
    // it will always be `None` during `add_to_entity`.
    /// Default image
    pub normal_image: Option<UiImageLoadPrefab>,
    /// Image used when the mouse hovers over this element
    pub hover_image: Option<UiImageLoadPrefab>,
    /// Text color used when this button is hovered over
    pub hover_text_color: Option<[f32; 4]>,
    /// Image used when button is pressed
    pub press_image: Option<UiImageLoadPrefab>,
    /// Text color used when this button is pressed
    pub press_text_color: Option<[f32; 4]>,
    /// Sound made when this button is hovered over
    pub hover_sound: Option<AssetPrefab<Audio>>,
    /// Sound made when this button is pressed.
    pub press_sound: Option<AssetPrefab<Audio>>,
    /// Sound made when this button is released.
    pub release_sound: Option<AssetPrefab<Audio>>,
}

impl<W: WidgetId + Debug> Debug for UiButtonData<W> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let font = match self.font.as_ref() {
            Some(asset_prefab) => match asset_prefab {
                AssetPrefab::File(path, _) => format!("<Font:{}>", path),
                _ => "<Font>".to_string(),
            },
            _ => "<Font>".to_string(),
        };

        f.debug_struct("UiTextData")
            .field("id", &self.id)
            .field("text", &self.text)
            .field("font_size", &self.font_size)
            .field("font", &font)
            .field("normal_text_color", &self.normal_text_color)
            .field("normal_image", &self.normal_image)
            .field("hover_image", &self.hover_image)
            .field("press_image", &self.press_image)
            .field("press_text_color", &self.press_text_color)
            .field("hover_sound", &self.hover_sound)
            .field("press_sound", &self.press_sound)
            .field("release_sound", &self.release_sound)
            .finish()
    }
}

impl<'a, W> PrefabData<'a> for UiButtonData<W>
where
    W: WidgetId,
{
    type SystemData = (
        WriteStorage<'a, UiSoundRetrigger>,
        WriteStorage<'a, UiButtonActionRetrigger>,
        Write<'a, Widgets<UiButton, W>>,
        <UiImageLoadPrefab as PrefabData<'a>>::SystemData,
        <AssetPrefab<Audio> as PrefabData<'a>>::SystemData,
    );
    type Result = ();

    fn add_to_entity(
        &self,
        entity: Entity,
        system_data: &mut Self::SystemData,
        entity_set: &[Entity],
        children: &[Entity],
    ) -> Result<(), Error> {
        let (
            ref mut sound_retrigger,
            ref mut button_action_retrigger,
            ref mut widgets,
            ref mut images,
            ref mut sounds,
        ) = system_data;

        let text_entity = children.get(0).expect("Invalid: Should have text child");
        let widget = UiButton::new(entity, *text_entity);
        if let Some(id) = &self.id {
            widgets.add_with_id(id.clone(), widget);
        } else {
            widgets.add(widget);
        }

        let _normal_image = self
            .normal_image
            .add_to_entity(entity, images, entity_set, children)?;
        let hover_image = self
            .hover_image
            .add_to_entity(entity, images, entity_set, children)?;
        let press_image = self
            .press_image
            .add_to_entity(entity, images, entity_set, children)?;

        let hover_sound = self
            .hover_sound
            .add_to_entity(entity, sounds, entity_set, children)?;
        let press_sound = self
            .press_sound
            .add_to_entity(entity, sounds, entity_set, children)?;
        let release_sound = self
            .release_sound
            .add_to_entity(entity, sounds, entity_set, children)?;

        let mut on_click_start = Vec::new();
        let mut on_click_stop = Vec::new();
        let mut on_hover_start = Vec::new();
        let mut on_hover_stop = Vec::new();

        if let Some(press_image) = press_image {
            on_click_start.push(UiButtonAction {
                target: entity,
                event_type: UiButtonActionType::SetImage(press_image.clone()),
            });

            on_click_stop.push(UiButtonAction {
                target: entity,
                event_type: UiButtonActionType::UnsetTexture(press_image.clone()),
            });
        }

        if let Some(hover_image) = hover_image {
            on_hover_start.push(UiButtonAction {
                target: entity,
                event_type: UiButtonActionType::SetImage(hover_image.clone()),
            });

            on_hover_stop.push(UiButtonAction {
                target: entity,
                event_type: UiButtonActionType::UnsetTexture(hover_image.clone()),
            });
        }

        if let Some(press_text_color) = self.press_text_color {
            on_click_start.push(UiButtonAction {
                target: entity,
                event_type: UiButtonActionType::SetTextColor(press_text_color),
            });

            on_click_stop.push(UiButtonAction {
                target: entity,
                event_type: UiButtonActionType::UnsetTextColor(press_text_color),
            });
        }

        if let Some(hover_text_color) = self.hover_text_color {
            on_hover_start.push(UiButtonAction {
                target: entity,
                event_type: UiButtonActionType::SetTextColor(hover_text_color),
            });

            on_hover_stop.push(UiButtonAction {
                target: entity,
                event_type: UiButtonActionType::UnsetTextColor(hover_text_color),
            });
        }

        if !on_click_start.is_empty()
            || !on_click_stop.is_empty()
            || !on_hover_start.is_empty()
            || !on_hover_stop.is_empty()
        {
            let retrigger = UiButtonActionRetrigger {
                on_click_start,
                on_click_stop,
                on_hover_start,
                on_hover_stop,
            };

            button_action_retrigger.insert(entity, retrigger)?;
        }

        if hover_sound.is_some() || press_sound.is_some() || release_sound.is_some() {
            let retrigger = UiSoundRetrigger {
                on_click_start: press_sound.map(UiPlaySoundAction),
                on_click_stop: release_sound.map(UiPlaySoundAction),
                on_hover_start: hover_sound.map(UiPlaySoundAction),
                on_hover_stop: None,
            };

            sound_retrigger.insert(entity, retrigger)?;
        }

        Ok(())
    }

    fn load_sub_assets(
        &mut self,
        progress: &mut ProgressCounter,
        system_data: &mut Self::SystemData,
    ) -> Result<bool, Error> {
        let (_, _, _, ref mut images, ref mut sounds) = system_data;
        self.normal_image.load_sub_assets(progress, images)?;
        self.hover_image.load_sub_assets(progress, images)?;
        self.press_image.load_sub_assets(progress, images)?;
        self.press_sound.load_sub_assets(progress, sounds)?;
        self.hover_sound.load_sub_assets(progress, sounds)?;
        self.release_sound.load_sub_assets(progress, sounds)
    }
}

/// Loadable ui components
///
/// ### Type parameters:
///
/// - `W`: Type used for Widget ID for this widget and its children
#[derive(Serialize, Deserialize, Clone, Debug)]
#[allow(clippy::large_enum_variant)] // TODO: revisit this for actual memory usage optimization
pub enum UiWidget<C = NoCustomUi, W = u32, G = ()>
where
    C: ToNativeWidget<W>,
    W: WidgetId,
{
    /// Container widget
    Container {
        /// Spatial information for the container
        transform: UiTransformData<G>,
        /// Background image
        #[serde(default = "default_container_image")]
        background: Option<UiImagePrefab>,
        /// Child widgets
        children: Vec<UiWidget<C, W>>,
    },
    /// Image widget
    Image {
        /// Spatial information
        transform: UiTransformData<G>,
        /// Image
        image: UiImagePrefab,
    },
    /// Text widget
    Label {
        /// Spatial information
        transform: UiTransformData<G>,
        /// Text
        text: UiTextData,
    },
    /// Button widget
    Button {
        /// Spatial information
        transform: UiTransformData<G>,
        /// Button
        button: UiButtonData<W>,
    },
    /// Custom UI widget
    Custom(Box<C>),
}

impl<C, W, G> UiWidget<C, W, G>
where
    C: ToNativeWidget<W>,
    W: WidgetId,
{
    /// Convenience function to access widgets `UiTransformData`
    pub fn transform(&self) -> Option<&UiTransformData<G>> {
        match self {
            UiWidget::Container { ref transform, .. } => Some(transform),
            UiWidget::Image { ref transform, .. } => Some(transform),
            UiWidget::Label { ref transform, .. } => Some(transform),
            UiWidget::Button { ref transform, .. } => Some(transform),
            UiWidget::Custom(_) => None,
        }
    }

    /// Convenience function to access widgets `UiTransformData`
    pub fn transform_mut(&mut self) -> Option<&mut UiTransformData<G>> {
        match self {
            UiWidget::Container {
                ref mut transform, ..
            } => Some(transform),
            UiWidget::Image {
                ref mut transform, ..
            } => Some(transform),
            UiWidget::Label {
                ref mut transform, ..
            } => Some(transform),
            UiWidget::Button {
                ref mut transform, ..
            } => Some(transform),
            UiWidget::Custom(_) => None,
        }
    }

    /// Convenience function to access widgets `UiImagePrefab`
    pub fn image(&self) -> Option<&UiImagePrefab> {
        match self {
            UiWidget::Container { ref background, .. } => background.as_ref(),
            UiWidget::Image { ref image, .. } => Some(image),
            _ => None,
        }
    }

    /// Convenience function to access widgets `UiImagePrefab`
    pub fn image_mut(&mut self) -> Option<&mut UiImagePrefab> {
        match self {
            UiWidget::Container {
                ref mut background, ..
            } => background.as_mut(),
            UiWidget::Image { ref mut image, .. } => Some(image),
            _ => None,
        }
    }
}

/// Create native `UiWidget` from custom UI
pub trait ToNativeWidget<W = u32>
where
    W: WidgetId,
    Self: Sized + 'static,
{
    /// Additional data used when loading UI prefab
    type PrefabData: for<'a> PrefabData<'a> + Default + Send + Sync + 'static;
    /// Create native `UiWidget` and custom prefab data from custom UI
    ///
    /// Returning `UiWidget::Custom` will cause recursion.
    /// Please make sure that the recursion is finite.
    fn to_native_widget(
        self,
        parent_data: Self::PrefabData,
    ) -> (UiWidget<Self, W>, Self::PrefabData);
}

/// Type used when no custom ui is desired
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
pub enum NoCustomUi {}

impl<W> ToNativeWidget<W> for NoCustomUi
where
    W: WidgetId,
{
    type PrefabData = ();
    fn to_native_widget(self, _: Self::PrefabData) -> (UiWidget<NoCustomUi, W>, Self::PrefabData) {
        // self can not exist
        unreachable!()
    }
}

fn default_container_image() -> Option<UiImagePrefab> {
    None
}

type UiPrefabData<D = <NoCustomUi as ToNativeWidget>::PrefabData, W = u32, G = ()> = (
    Option<UiTransformData<G>>,
    Option<UiImagePrefab>,
    Option<UiTextData>,
    Option<UiButtonData<W>>,
    D,
);

/// Ui prefab
///
/// ### Type parameters:
///
/// - `D`: `ToNativeWidget::PrefabData` data used by custom UI
/// - `W`: Type used for Widget IDs
pub type UiPrefab<D = <NoCustomUi as ToNativeWidget>::PrefabData, W = u32> =
    Prefab<UiPrefabData<D, W>>;

/// Ui format.
///
/// Load `UiPrefab` from `ron` file.
#[derive(Serialize, Deserialize, Derivative)]
#[derivative(Clone(bound = ""), Debug(bound = ""), Default(bound = ""))]
pub struct UiFormat<C>(PhantomData<C>);

unsafe impl<C> Send for UiFormat<C> {}
unsafe impl<C> Sync for UiFormat<C> {}

impl<C, W> Format<UiPrefab<C::PrefabData, W>> for UiFormat<C>
where
    C: ToNativeWidget<W> + for<'de> serde::Deserialize<'de>,
    W: WidgetId + DeserializeOwned,
{
    fn name(&self) -> &'static str {
        "Ui"
    }

    fn import_simple(&self, bytes: Vec<u8>) -> Result<UiPrefab<C::PrefabData, W>, Error> {
        use ron::de::Deserializer;
        let mut d = Deserializer::from_bytes(&bytes)
            .with_context(|_| format_err!("Failed deserializing Ron file"))?;
        let root: UiWidget<C, W> = UiWidget::deserialize(&mut d)
            .with_context(|_| format_err!("Failed parsing Ron file"))?;
        d.end()
            .with_context(|_| format_err!("Failed parsing Ron file"))?;

        let mut prefab = Prefab::new();
        walk_ui_tree(root, 0, &mut prefab, Default::default());

        Ok(prefab)
    }
}

fn walk_ui_tree<C, W>(
    widget: UiWidget<C, W>,
    current_index: usize,
    prefab: &mut Prefab<UiPrefabData<C::PrefabData, W>>,
    custom_data: C::PrefabData,
) where
    C: ToNativeWidget<W>,
    W: WidgetId,
{
    match widget {
        UiWidget::Custom(custom) => {
            let (widget, custom_data) = custom.to_native_widget(custom_data);
            walk_ui_tree(widget, current_index, prefab, custom_data);
        }

        UiWidget::Image { transform, image } => {
            prefab
                .entity(current_index)
                .expect("Unreachable: `Prefab` entity should always be set when walking ui tree")
                .set_data((Some(transform), Some(image), None, None, custom_data));
        }

        UiWidget::Label { transform, text } => {
            prefab
                .entity(current_index)
                .expect("Unreachable: `Prefab` entity should always be set when walking ui tree")
                .set_data((Some(transform), None, Some(text), None, custom_data));
        }

        UiWidget::Container {
            transform,
            background,
            children,
        } => {
            prefab
                .entity(current_index)
                .expect("Unreachable: `Prefab` entity should always be set when walking ui tree")
                .set_data((Some(transform), background, None, None, custom_data));

            for child_widget in children {
                let child_index = prefab.add(Some(current_index), None);
                walk_ui_tree(child_widget, child_index, prefab, Default::default());
            }
        }

        UiWidget::Button {
            transform,
            mut button,
        } => {
            let id = transform.id.clone();
            let text = UiTextData {
                color: button.normal_text_color,
                editable: None,
                font: button.font.clone(),
                password: false,
                align: None,
                line_mode: None,
                text: button.text.clone(),
                font_size: button.font_size,
            };

            prefab
                .entity(current_index)
                .expect("Unreachable: `Prefab` entity should always be set when walking ui tree")
                .set_data((
                    Some(transform),
                    button.normal_image.take().map(UiImagePrefab),
                    None,
                    Some(button),
                    custom_data,
                ));

            prefab.add(
                Some(current_index),
                Some((
                    Some(button_text_transform(id)),
                    None,
                    Some(text),
                    None,
                    Default::default(),
                )),
            );
        }
    }
}

/// Specialised UI loader
///
/// The recommended way of using this in `State`s is with `world.exec`.
///
/// ### Type parameters:
///
/// - `I`: `Format` used for loading `Texture`s
/// - `F`: `Format` used for loading `FontAsset`
/// - `W`: Type used for Widget IDs
///
/// ### Example:
///
/// ```rust,ignore
/// let ui_handle = world.exec(|loader: UiLoader<TextureFormat, FontFormat>| {
///     loader.load("renderable.ron", ())
/// });
/// ```
#[derive(SystemData)]
#[allow(missing_debug_implementations)]
pub struct UiLoader<'a, C = NoCustomUi, W = u32>
where
    C: ToNativeWidget<W>,
    W: WidgetId,
{
    loader: ReadExpect<'a, Loader>,
    storage: Read<'a, AssetStorage<UiPrefab<C::PrefabData, W>>>,
}

impl<'a, C, W> UiLoader<'a, C, W>
where
    C: ToNativeWidget<W> + for<'de> serde::Deserialize<'de> + Send + Sync + 'static,
    W: WidgetId + DeserializeOwned,
{
    /// Load ui from disc
    pub fn load<N, P>(&self, name: N, progress: P) -> Handle<UiPrefab<C::PrefabData, W>>
    where
        N: Into<String>,
        P: Progress,
    {
        self.loader
            .load(name, UiFormat::<C>::default(), progress, &self.storage)
    }
}

/// Ui Creator, wrapper around loading and creating a UI directly.
///
/// The recommended way of using this in `State`s is with `world.exec`.
///
/// ### Type parameters:
///
/// - `C`: custom UI widget
/// - `W`: Type used for Widget IDs
///
/// ### Example:
///
/// ```rust,ignore
/// let ui_handle = world.exec(|creator: UiCreator| {
///     creator.create("renderable.ron", ())
/// });
/// ```
#[derive(SystemData)]
#[allow(missing_debug_implementations)]
pub struct UiCreator<'a, C = NoCustomUi, W = u32>
where
    C: ToNativeWidget<W>,
    W: WidgetId,
{
    loader: UiLoader<'a, C, W>,
    entities: Entities<'a>,
    handles: WriteStorage<'a, Handle<UiPrefab<C::PrefabData, W>>>,
}

impl<'a, C, W> UiCreator<'a, C, W>
where
    C: ToNativeWidget<W> + for<'de> serde::Deserialize<'de> + Send + Sync + 'static,
    W: WidgetId + DeserializeOwned,
{
    /// Create a UI.
    ///
    /// Will load a UI from the given `ron` file, create an `Entity` and load the UI with that
    /// `Entity` as the root of the UI hierarchy.
    ///
    /// ### Parameters:
    ///
    /// - `name`: Name of a `ron` asset in the `UiFormat` format
    /// - `progress`: Progress tracker
    ///
    /// ### Returns
    ///
    /// The `Entity` that was created that will form the root of the loaded UI.
    pub fn create<N, P>(&mut self, name: N, progress: P) -> Entity
    where
        N: Into<String>,
        P: Progress,
    {
        let entity = self.entities.create();
        let handle = self.loader.load(name, progress);
        self.handles
            .insert(entity, handle)
            .expect("Unreachable: We just created the entity");
        entity
    }
}

/// Builds a `UiLoaderSystem`.
pub type UiLoaderSystemDesc<CD, W> = PrefabLoaderSystemDesc<UiPrefabData<CD, W>>;

/// Prefab loader system for UI
///
/// ### Type parameters:
///
/// - `CD`: prefab data from custom UI, see `ToNativeWidget::PrefabData`
/// - `W`: Type used for Widget IDs
pub type UiLoaderSystem<CD, W> = PrefabLoaderSystem<UiPrefabData<CD, W>>;

fn button_text_transform<G>(mut id: String) -> UiTransformData<G> {
    id.push_str("_btn_txt");
    UiTransformData::default()
        .with_id(id)
        .with_position(0., 0., 1.)
        .with_anchor(Anchor::Middle)
        .with_stretch(Stretch::XY {
            x_margin: 0.,
            y_margin: 0.,
            keep_aspect_ratio: false,
        })
        .transparent()
}