summaryrefslogtreecommitdiffstats
path: root/examples/ggez/main.rs
blob: 7deef072da1f351cbded2ac766334a0fb168731c (plain) (blame)
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
mod renderer;
mod widget;

use renderer::Renderer;
use widget::{button, Button, Column, Text};

use ggez;
use ggez::event;
use ggez::graphics;
use ggez::input::mouse;

use iced::Interface;

pub fn main() -> ggez::GameResult {
    let cb = ggez::ContextBuilder::new("iced", "ggez");
    let (ctx, event_loop) = &mut cb.build()?;
    let state = &mut Game::new(ctx)?;
    event::run(ctx, event_loop, state)
}

struct Game {
    spritesheet: graphics::Image,
    button: button::State,
}

impl Game {
    fn new(context: &mut ggez::Context) -> ggez::GameResult<Game> {
        Ok(Game {
            spritesheet: graphics::Image::new(context, "/ui.png").unwrap(),
            button: button::State::new(),
        })
    }
}

impl event::EventHandler for Game {
    fn update(&mut self, _ctx: &mut ggez::Context) -> ggez::GameResult {
        Ok(())
    }

    fn draw(&mut self, context: &mut ggez::Context) -> ggez::GameResult {
        graphics::clear(context, [0.1, 0.2, 0.3, 1.0].into());

        let screen = graphics::screen_coordinates(context);

        let cursor = {
            let hello = Text::new("Hello, iced!")
                .horizontal_alignment(iced::text::HorizontalAlignment::Center);

            let button = Button::new(&mut self.button, "Press me!").width(200);

            let content = Column::new()
                .width(screen.w as u32)
                .height(screen.h as u32)
                .align_items(iced::Align::Center)
                .justify_content(iced::Justify::Center)
                .spacing(20)
                .push(hello)
                .push(button);

            let renderer =
                &mut Renderer::new(context, self.spritesheet.clone());

            let ui: Interface<(), Renderer> =
                Interface::compute(content.into(), renderer);

            let cursor = ui.draw(renderer, iced::Point::new(0.0, 0.0));

            renderer.flush();

            cursor
        };

        mouse::set_cursor_type(context, into_cursor_type(cursor));

        graphics::present(context)?;
        Ok(())
    }
}

fn into_cursor_type(cursor: iced::MouseCursor) -> mouse::MouseCursor {
    match cursor {
        iced::MouseCursor::OutOfBounds => mouse::MouseCursor::Default,
        iced::MouseCursor::Idle => mouse::MouseCursor::Default,
        iced::MouseCursor::Pointer => mouse::MouseCursor::Hand,
        iced::MouseCursor::Working => mouse::MouseCursor::Progress,
        iced::MouseCursor::Grab => mouse::MouseCursor::Grab,
        iced::MouseCursor::Grabbing => mouse::MouseCursor::Grabbing,
    }
}