aboutsummaryrefslogtreecommitdiff
path: root/src/utils.rs
blob: 3e5ff55136d0123b865f74ae88389fb15169d6e7 (plain)
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
use crate::{consts::FONT_PATH, lisp::error::LispError, message::Message};
use sdl2::{
    keyboard::{Keycode, Mod},
    pixels::Color,
    render::Canvas,
    ttf::Sdl2TtfContext,
    video::Window,
};

#[macro_export]
macro_rules! rect(
    ($x:expr, $y:expr, $w:expr, $h:expr) => (
        ::sdl2::rect::Rect::new($x as i32, $y as i32, $w as u32, $h as u32)
    )
);

pub fn draw_text<S: AsRef<str>>(
    canvas: &mut Canvas<Window>,
    ttf_context: &Sdl2TtfContext,
    text: S,
    color: Color,
    (x, y): (u32, u32),
) -> u32 {
    let text = text.as_ref();
    let texture_creator = canvas.texture_creator();
    let mut font = ttf_context.load_font(FONT_PATH, 17).unwrap();
    font.set_style(sdl2::ttf::FontStyle::NORMAL);
    font.set_hinting(sdl2::ttf::Hinting::Mono);
    let surface = font
        .render(if text.is_empty() { " " } else { text.as_ref() })
        .blended(color)
        .unwrap();
    let texture = texture_creator
        .create_texture_from_surface(&surface)
        .unwrap();
    let (width, height) = font.size_of(&text).unwrap();
    let area = rect!(x, y, width, height);
    canvas.copy(&texture, None, area).unwrap();
    width
}

pub fn is_copy_event(keycode: Option<Keycode>, keymod: Mod) -> bool {
    keycode == Some(Keycode::C) && (keymod == Mod::LCTRLMOD || keymod == Mod::RCTRLMOD)
}

pub fn is_paste_event(keycode: Option<Keycode>, keymod: Mod) -> bool {
    keycode == Some(Keycode::V) && (keymod == Mod::LCTRLMOD || keymod == Mod::RCTRLMOD)
}

pub fn handle_error(err: LispError, src: &str) -> Message {
    let mut message = Message::new();
    match err {
        LispError::Parse(p) => message.set_error(p.display(&src)),
        eval_err => message.set_error(eval_err.to_string()),
    }
    message
}