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
#![crate_name = "direct_gui"]

//! Draw GUI controls directly on a buffer
//!
//! # Usage
//!
//! This crate is [on crates.io](htpps://crates.io/crates/direct-gui) and can be used by adding
//! `direct-gui` to the dependencies in your project's `Cargo.toml`.
//!
//! ```toml
//! [dependencies]
//! direct-gui = "0.1"
//! ```
//!
//! and this to your crate root:
//!
//! ```rust
//! extern crate direct_gui;
//! ```
//!
//! # Examples
//!
//! ```rust
//! use direct_gui::*;
//! use direct_gui::controls::*;
//!
//! let screen_size = (800i32, 600i32);
//!
//! // Create a buffer where we will render to
//! let mut buffer: Vec<u32> = vec![0; (screen_size.0 * screen_size.1) as usize];
//!
//! // Create a new instance of the gui
//! let mut gui = Gui::new(screen_size);
//!
//! // Load the sprite of a button
//! let button_img = gui.load_sprite_from_file("examples/button.png", Color::from_u32(0xFF00FF)).unwrap();
//!
//! // Create a new button using the sprite loaded before at pixel (20, 10)
//! gui.register(Button::new_with_sprite(button_img).with_pos(20, 10));
//!
//! // Handle "input events" by pretending that the mouse is hovering over the button.
//! let cs = ControlState {
//!     mouse_pos: (22, 12),
//!     ..ControlState::default()
//! };
//! gui.update(&cs);
//!
//! // Finally render the current gui state to the buffer
//! gui.draw_to_buffer(&mut buffer);
//! ```

extern crate blit;
extern crate image;

use std::fmt;
use std::path::Path;
use std::error::Error;

pub mod controls;
mod resources;
mod font;

pub use blit::Color;

pub use font::FontSettings;
pub use resources::{SpriteRef, FontRef};
use controls::*;
use resources::*;

/// An error type for when a reference is not valid anymore.
#[derive(Debug, Clone)]
pub struct InvalidControlReference;

impl fmt::Display for InvalidControlReference {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "reference to control object doesn't exist anymore")
    }
}

impl Error for InvalidControlReference {
    fn description(&self) -> &str {
        "reference to control object doesn't exist anymore"
    }

    fn cause(&self) -> Option<&Error> {
        None
    }
}

/// A newtype used to as a reference for controls.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct ControlRef(usize);

/// The main entry point.
///
/// Typically a game has one instance of this struct where the resources are loaded before the main loop.
pub struct Gui {
    size: (i32, i32),

    resources: Resources,
    controls: Vec<(ControlRef, Box<Control>)>,
    control_ref: usize
}

impl Gui {
    /// Creates a new GUI.
    pub fn new(size: (i32, i32)) -> Self {
        Gui {
            size,
            resources: Resources::new(),
            controls: Vec::new(),
            control_ref: 0
        }
    }

    /// Handle the user input and information as supplied by the windowing library.
    pub fn update(&mut self, state: &ControlState) {
        for control_tuple in self.controls.iter_mut() {
            control_tuple.1.update(state, &self.resources);
        }
    }

    /// Draw the drawable GUI controls on a target buffer.
    pub fn draw_to_buffer(&mut self, buffer: &mut Vec<u32>) {
        for control_tuple in self.controls.iter_mut() {
            control_tuple.1.draw(buffer, self.size.0 as usize, &self.resources);
        }
    }

    /// Draw a label a single frame.
    pub fn draw_label(&mut self, buffer: &mut Vec<u32>, font_ref: FontRef, string: &String, pos: (i32, i32)) {
        let font = self.resources.get_font(font_ref).unwrap();

        font.draw_string(buffer, self.size.0 as usize, string, pos);
    }

    /// Register a control.
    pub fn register<T: 'static + Control>(&mut self, ctrl: T) -> ControlRef {
        self.control_ref += 1;

        self.controls.push((ControlRef(self.control_ref), Box::new(ctrl)));

        ControlRef(self.control_ref)
    }

    /// Retrieve a control by reference.
    pub fn get<T: 'static + Control>(&self, control_ref: ControlRef) -> Result<&T, Box<Error>> {
        match self.controls.iter().find(|&c| c.0 == control_ref) {
            Some(c) => {
                match c.1.as_any().downcast_ref::<T>() {
                    Some(obj) => Ok(obj),
                    None => Err(Box::new(InvalidControlReference))
                }
            },
            None => Err(Box::new(InvalidControlReference))
        }
    }

    /// Retrieve a control by mutable reference.
    pub fn get_mut<T: 'static + Control>(&mut self, control_ref: ControlRef) -> Result<&mut T, Box<Error>> {
        match self.controls.iter_mut().find(|c| c.0 == control_ref) {
            Some(c) => {
                match c.1.as_any_mut().downcast_mut::<T>() {
                    Some(obj) => Ok(obj),
                    None => Err(Box::new(InvalidControlReference))
                }
            },
            None => Err(Box::new(InvalidControlReference))
        }
    }

    /// Return the default font loaded from the `assets/` folder and parsed by `build.rs`. Which is
    /// always the first item added to the fonts array.
    pub fn default_font(&self) -> FontRef {
        self.resources.default_font()
    }

    /// Load image from a path.
    ///
    /// The mask color is the color that will be used as alpha in the sprite, a common color to use
    /// for this is `0xFF00FF`.
    ///
    /// Returns a reference to the image.
    pub fn load_sprite_from_file<P>(&mut self, path: P, mask_color: Color) -> Result<SpriteRef, Box<Error>> where P: AsRef<Path> {
        self.resources.load_sprite_from_file(path, mask_color)
    }

    /// Load image from serialized memory. Returns a reference to the image.
    pub fn load_sprite_from_memory(&mut self, buffer: &[u8]) -> Result<SpriteRef, Box<Error>> {
        self.resources.load_sprite_from_memory(buffer)
    }

    /// Load font image from a path.
    ///
    /// The mask color is the color that will be used as alpha in the sprite, a common color to use
    /// for this is `0xFF00FF`.
    ///
    /// Returns a reference to the font.
    pub fn load_font_sprite_from_file<P>(&mut self, path: P, settings: FontSettings) -> Result<FontRef, Box<Error>> where P: AsRef<Path> {
        self.resources.load_font_sprite_from_file(path, settings)
    }

    /// Load image from serialized memory. Returns a reference to the image.
    pub fn load_font_sprite_from_memory(&mut self, buffer: &[u8], settings: FontSettings) -> Result<FontRef, Box<Error>> {
        self.resources.load_font_sprite_from_memory(buffer, settings)
    }
}