aboutsummaryrefslogtreecommitdiff
path: root/server/locale/src/message.rs
blob: bedf45fddbdbb5389a9ee1bde766673b084fbac6 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
    Hurry Curry! - a game about cooking
    Copyright (C) 2025 Hurry Curry! Contributors

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

*/

use crate::Locale;
use hurrycurry_protocol::{Gamedata, Message};

pub trait MessageDisplayExt {
    fn display_message(&self, locale: &Locale, data: &Gamedata, style: &DisplayStyle) -> String;
}
impl MessageDisplayExt for Message {
    fn display_message(&self, locale: &Locale, data: &Gamedata, style: &DisplayStyle) -> String {
        display_message_inner(self, locale, data, style)
    }
}
fn display_message_inner(
    message: &Message,
    locale: &Locale,
    data: &Gamedata,
    style: &DisplayStyle,
) -> String {
    let DisplayStyle {
        default,
        error,
        tile_item,
        highlighted,
    } = style;
    match message {
        Message::Translation { id, params } => {
            let Some(template) = locale.get(&id) else {
                return format!("[translation missing: {error}{id}{default}]");
            };
            let mut s = template.to_string();
            for (i, p) in params.iter().enumerate() {
                s = s.replace(&format!("{{{i}}}"), &p.display_message(locale, data, style));
            }
            s
        }
        Message::Text(s) => format!("{highlighted}{s}{default}"),
        Message::Item(item_index) => format!("{tile_item}{}{default}", data.item_name(*item_index)),
        Message::Tile(tile_index) => format!("{tile_item}{}{default}", data.tile_name(*tile_index)),
    }
}

pub struct DisplayStyle<'a> {
    default: &'a str,
    error: &'a str,
    tile_item: &'a str,
    highlighted: &'a str,
}
pub static PLAIN: DisplayStyle = DisplayStyle {
    default: "",
    error: "",
    tile_item: "",
    highlighted: "",
};
pub static COLORED: DisplayStyle = DisplayStyle {
    default: "\x1b[0m",
    error: "\x1b[31m",
    tile_item: "\x1b[34m",
    highlighted: "\x1b[1m",
};