veloren_voxygen/hud/
chat.rs

1use super::{
2    ChatTab, ERROR_COLOR, FACTION_COLOR, GROUP_COLOR, INFO_COLOR, KILL_COLOR, OFFLINE_COLOR,
3    ONLINE_COLOR, REGION_COLOR, SAY_COLOR, TELL_COLOR, TEXT_COLOR, WORLD_COLOR, img_ids::Imgs,
4};
5use crate::{
6    GlobalState,
7    cmd::complete,
8    settings::{ChatSettings, chat::MAX_CHAT_TABS},
9    ui::{
10        Scale,
11        fonts::{Font, Fonts},
12    },
13};
14use client::Client;
15use common::{
16    cmd::ServerChatCommand,
17    comp::{ChatMode, ChatMsg, ChatType, group::Role},
18};
19use conrod_core::{
20    Color, Colorable, Labelable, Positionable, Sizeable, Ui, UiCell, Widget, WidgetCommon, color,
21    input::Key,
22    position::Dimension,
23    text::{
24        self,
25        cursor::{self, Index},
26    },
27    widget::{self, Button, Id, Image, Line, List, Rectangle, Text, TextEdit},
28    widget_ids,
29};
30use i18n::Localization;
31use i18n_helpers::localize_chat_message;
32use std::collections::{HashSet, VecDeque};
33use vek::{Vec2, approx::AbsDiffEq};
34
35/// Determines whether a message is from a muted player.
36///
37/// These messages will not be shown anywhere and do not need to be retained in
38/// chat queues.
39pub fn is_muted(client: &Client, profile: &crate::profile::Profile, msg: &ChatMsg) -> bool {
40    if let Some(uid) = msg.uid()
41        && let Some(player_info) = client.player_list().get(&uid)
42    {
43        profile.mutelist.contains_key(&player_info.uuid)
44    } else {
45        false
46    }
47}
48
49/// Determines whether a message will be sent to the chat box.
50///
51/// Some messages like NPC messages are only displayed as in-world chat bubbles.
52pub fn show_in_chatbox(msg: &ChatMsg) -> bool {
53    // Don't put NPC messages in chat box.
54    !matches!(msg.chat_type, ChatType::Npc(_))
55}
56
57pub const MAX_MESSAGES: usize = 100;
58
59/// Chat messages received from the client before entering the
60/// `SessionState`.
61///
62/// We transfer these to HUD when it is displayed in `SessionState`.
63///
64/// Messages that aren't show in the chat box aren't retained (e.g. ones
65/// that would just show as in-world chat bubbles).
66#[derive(Default)]
67pub struct MessageBacklog(pub(super) VecDeque<ChatMsg>);
68
69impl MessageBacklog {
70    pub fn new_message(
71        &mut self,
72        client: &Client,
73        profile: &crate::profile::Profile,
74        msg: ChatMsg,
75    ) {
76        if !is_muted(client, profile, &msg) && show_in_chatbox(&msg) {
77            self.0.push_back(msg);
78            if self.0.len() > MAX_MESSAGES {
79                self.0.pop_front();
80            }
81        }
82    }
83}
84
85const CHAT_ICON_WIDTH: f64 = 16.0;
86const CHAT_MARGIN_THICKNESS: f64 = 2.0;
87const CHAT_ICON_HEIGHT: f64 = 16.0;
88const MIN_DIMENSION: Vec2<f64> = Vec2::new(400.0, 150.0);
89const MAX_DIMENSION: Vec2<f64> = Vec2::new(650.0, 500.0);
90
91const CHAT_TAB_HEIGHT: f64 = 20.0;
92const CHAT_TAB_ALL_WIDTH: f64 = 40.0;
93
94/*#[const_tweaker::tweak(min = 0.0, max = 60.0, step = 1.0)]
95const X: f64 = 18.0;*/
96
97widget_ids! {
98    struct Ids {
99        draggable_area,
100        message_box,
101        message_box_bg,
102        chat_input,
103        chat_input_bg,
104        chat_input_icon,
105        chat_input_border_up,
106        chat_input_border_down,
107        chat_input_border_left,
108        chat_input_border_right,
109        chat_arrow,
110        chat_icon_align,
111        chat_icons[],
112        chat_badges[],
113
114        chat_tab_align,
115        chat_tab_all,
116        chat_tab_selected,
117        chat_tabs[],
118        chat_tab_tooltip_bg,
119        chat_tab_tooltip_text,
120    }
121}
122
123#[derive(WidgetCommon)]
124pub struct Chat<'a> {
125    pulse: f32,
126    new_messages: &'a mut VecDeque<ChatMsg>,
127    client: &'a Client,
128    force_input: Option<String>,
129    force_cursor: Option<Index>,
130    force_completions: Option<Vec<String>>,
131
132    global_state: &'a GlobalState,
133    imgs: &'a Imgs,
134    fonts: &'a Fonts,
135
136    #[conrod(common_builder)]
137    common: widget::CommonBuilder,
138
139    // TODO: add an option to adjust this
140    history_max: usize,
141    scale: Scale,
142
143    localized_strings: &'a Localization,
144    clear_messages: bool,
145}
146
147impl<'a> Chat<'a> {
148    pub fn new(
149        new_messages: &'a mut VecDeque<ChatMsg>,
150        client: &'a Client,
151        global_state: &'a GlobalState,
152        pulse: f32,
153        imgs: &'a Imgs,
154        fonts: &'a Fonts,
155        localized_strings: &'a Localization,
156        scale: Scale,
157        clear_messages: bool,
158    ) -> Self {
159        Self {
160            pulse,
161            new_messages,
162            client,
163            force_input: None,
164            force_cursor: None,
165            force_completions: None,
166            imgs,
167            fonts,
168            global_state,
169            common: widget::CommonBuilder::default(),
170            history_max: 32,
171            localized_strings,
172            scale,
173            clear_messages,
174        }
175    }
176
177    pub fn prepare_tab_completion(mut self, input: String) -> Self {
178        self.force_completions = if let Some(index) = input.find('\t') {
179            Some(complete(
180                &input[..index],
181                self.client,
182                self.localized_strings,
183                &self.global_state.settings.chat.chat_cmd_prefix.to_string(),
184            ))
185        } else {
186            None
187        };
188        self
189    }
190
191    pub fn input(mut self, input: String) -> Self {
192        self.force_input = Some(input);
193        self
194    }
195
196    pub fn cursor_pos(mut self, index: Index) -> Self {
197        self.force_cursor = Some(index);
198        self
199    }
200
201    pub fn scrolled_to_bottom(state: &State, ui: &UiCell) -> bool {
202        // Might be more efficient to cache result and update it when a scroll event has
203        // occurred instead of every frame.
204        if let Some(scroll) = ui
205            .widget_graph()
206            .widget(state.ids.message_box)
207            .and_then(|widget| widget.maybe_y_scroll_state)
208        {
209            scroll.offset + 50.0 >= scroll.offset_bounds.start
210        } else {
211            false
212        }
213    }
214}
215
216struct InputState {
217    message: String,
218    mode: ChatMode,
219}
220
221pub struct State {
222    messages: VecDeque<ChatMsg>,
223    input: InputState,
224    ids: Ids,
225    history: VecDeque<String>,
226    // Index into the history Vec, history_pos == 0 is history not in use
227    // otherwise index is history_pos -1
228    history_pos: usize,
229    completions: Vec<String>,
230    // Index into the completion Vec
231    completions_index: Option<usize>,
232    // At which character is tab completion happening
233    completion_cursor: Option<usize>,
234    // last time mouse has been hovered
235    tabs_last_hover_pulse: Option<f32>,
236    // last chat_tab (used to see if chat tab has been changed)
237    prev_chat_tab: Option<ChatTab>,
238    //whether or not a scroll action is queued
239    scroll_next: bool,
240}
241
242pub enum Event {
243    TabCompletionStart(String),
244    SendMessage(String),
245    SendCommand(String, Vec<String>),
246    Focus(Id),
247    ChangeChatTab(Option<usize>),
248    ShowChatTabSettings(usize),
249    ResizeChat(Vec2<f64>),
250    MoveChat(Vec2<f64>),
251    DisableForceChat,
252}
253
254impl Widget for Chat<'_> {
255    type Event = Vec<Event>;
256    type State = State;
257    type Style = ();
258
259    fn init_state(&self, id_gen: widget::id::Generator) -> Self::State {
260        State {
261            input: InputState {
262                message: "".to_owned(),
263                mode: ChatMode::default(),
264            },
265            messages: VecDeque::new(),
266            history: VecDeque::new(),
267            history_pos: 0,
268            completions: Vec::new(),
269            completions_index: None,
270            completion_cursor: None,
271            ids: Ids::new(id_gen),
272            tabs_last_hover_pulse: None,
273            prev_chat_tab: None,
274            scroll_next: false,
275        }
276    }
277
278    fn style(&self) -> Self::Style {}
279
280    fn update(self, args: widget::UpdateArgs<Self>) -> Self::Event {
281        fn adjust_border_opacity(color: Color, opacity: f32) -> Color {
282            match color {
283                Color::Rgba(r, g, b, a) => Color::Rgba(r, g, b, (a + opacity) / 2.0),
284                _ => panic!("Color input should be Rgba, instead found: {:?}", color),
285            }
286        }
287        common_base::prof_span!("Chat::update");
288
289        let widget::UpdateArgs { id, state, ui, .. } = args;
290
291        let mut events = Vec::new();
292
293        let chat_settings = &self.global_state.settings.chat;
294        let force_chat = !(&self.global_state.settings.interface.toggle_chat);
295        let chat_tabs = &chat_settings.chat_tabs;
296        let current_chat_tab = chat_settings.chat_tab_index.and_then(|i| chat_tabs.get(i));
297        let chat_size = Vec2::new(chat_settings.chat_size_x, chat_settings.chat_size_y);
298        let chat_pos = Vec2::new(chat_settings.chat_pos_x, chat_settings.chat_pos_y);
299        let chat_box_input_width = chat_size.x - CHAT_ICON_WIDTH - 12.0;
300
301        if self.clear_messages {
302            state.update(|s| s.messages.clear());
303        }
304
305        // Empty old messages
306        state.update(|s| {
307            while s.messages.len() > MAX_MESSAGES {
308                s.messages.pop_front();
309            }
310        });
311
312        let chat_in_screen_upper = chat_pos.y > ui.win_h / 2.0;
313
314        if !chat_settings.lock_chat {
315            let pos_delta: Vec2<f64> = ui
316                .widget_input(state.ids.draggable_area)
317                .drags()
318                .left()
319                .map(|drag| Vec2::<f64>::from(drag.delta_xy))
320                .sum();
321
322            let window_clamp =
323                Vec2::new(ui.win_w, ui.win_h) - Vec2::unit_y() * CHAT_TAB_HEIGHT - chat_size;
324
325            let new_pos = (chat_pos + pos_delta)
326                .map(|e| e.max(0.))
327                .map2(window_clamp, |e, bounds| e.min(bounds));
328
329            if new_pos.abs_diff_ne(&chat_pos, f64::EPSILON) {
330                events.push(Event::MoveChat(new_pos));
331            }
332
333            let size_delta: Vec2<f64> = ui
334                .widget_input(state.ids.draggable_area)
335                .drags()
336                .right()
337                .map(|drag| Vec2::<f64>::from(drag.delta_xy))
338                .sum();
339
340            let new_size = (chat_size + size_delta)
341                .map3(
342                    self.scale.scale_point(MIN_DIMENSION),
343                    self.scale.scale_point(MAX_DIMENSION),
344                    |sz, min, max| sz.clamp(min, max),
345                )
346                .map2(window_clamp, |e, bounds| e.min(bounds));
347            if new_size.abs_diff_ne(&chat_size, f64::EPSILON) {
348                events.push(Event::ResizeChat(new_size));
349            }
350        }
351
352        // Maintain scrolling
353        if !self.new_messages.is_empty() {
354            for message in self.new_messages.iter() {
355                // Log the output of commands since the ingame terminal doesn't support copying
356                // the output to the clipboard
357                if let ChatType::CommandInfo = &message.chat_type {
358                    tracing::info!("Chat command info: {:?}", message.content());
359                }
360            }
361            // new messages - update chat w/ them & scroll down if at bottom of chat
362            state.update(|s| s.messages.extend(self.new_messages.drain(..)));
363            // Prevent automatic scroll upon new messages if not already scrolled to bottom
364            if Self::scrolled_to_bottom(state, ui) {
365                ui.scroll_widget(state.ids.message_box, [0.0, f64::MAX]);
366            }
367        }
368
369        // Trigger scroll event queued from previous frame
370        if state.scroll_next {
371            ui.scroll_widget(state.ids.message_box, [0.0, f64::MAX]);
372            state.update(|s| s.scroll_next = false);
373        }
374
375        // Queue scroll event if switching from a different tab
376        if current_chat_tab != state.prev_chat_tab.as_ref() {
377            state.update(|s| s.prev_chat_tab = current_chat_tab.cloned());
378            state.update(|s| s.scroll_next = true); //make scroll happen only once any filters to the messages have already been applied
379        }
380
381        if let Some(comps) = &self.force_completions {
382            state.update(|s| s.completions.clone_from(comps));
383        }
384
385        let mut force_cursor = self.force_cursor;
386
387        // If up or down are pressed: move through history
388        // If any key other than up, down, or tab is pressed: stop completion.
389        let (history_dir, tab_dir, stop_tab_completion) =
390            ui.widget_input(state.ids.chat_input).presses().key().fold(
391                (0isize, 0isize, false),
392                |(n, m, tc), key_press| match key_press.key {
393                    Key::Up => (n + 1, m - 1, tc),
394                    Key::Down => (n - 1, m + 1, tc),
395                    Key::Tab => (n, m + 1, tc),
396                    _ => (n, m, true),
397                },
398            );
399
400        // Handle tab completion
401        let request_tab_completions = if stop_tab_completion {
402            // End tab completion
403            state.update(|s| {
404                if s.completion_cursor.is_some() {
405                    s.completion_cursor = None;
406                }
407                s.completions_index = None;
408            });
409            false
410        } else if let Some(cursor) = state.completion_cursor {
411            // Cycle through tab completions of the current word
412            if state.input.message.contains('\t') {
413                state.update(|s| s.input.message.retain(|c| c != '\t'));
414                //tab_dir + 1
415            }
416            if !state.completions.is_empty() && (tab_dir != 0 || state.completions_index.is_none())
417            {
418                state.update(|s| {
419                    let len = s.completions.len();
420                    s.completions_index = Some(
421                        (s.completions_index.unwrap_or(0) + (tab_dir + len as isize) as usize)
422                            % len,
423                    );
424                    if let Some(replacement) = &s.completions.get(s.completions_index.unwrap()) {
425                        let (completed, offset) =
426                            do_tab_completion(cursor, &s.input.message, replacement);
427                        force_cursor = cursor_offset_to_index(
428                            offset,
429                            &completed,
430                            ui,
431                            self.fonts,
432                            chat_box_input_width,
433                        );
434                        s.input.message = completed;
435                    }
436                });
437            }
438            false
439        } else if let Some(cursor) = state.input.message.find('\t') {
440            // Begin tab completion
441            state.update(|s| s.completion_cursor = Some(cursor));
442            true
443        } else {
444            // Not tab completing
445            false
446        };
447
448        // Check if we need to change the chat mode if we have completed a command
449        if state.input.message.ends_with(' ') {
450            change_chat_mode(
451                state.input.message.clone(),
452                state,
453                &mut events,
454                chat_settings,
455            );
456        }
457
458        // Move through history
459        if history_dir != 0 && state.completion_cursor.is_none() {
460            state.update(|s| {
461                if history_dir > 0 {
462                    if s.history_pos < s.history.len() {
463                        s.history_pos += 1;
464                    }
465                } else if s.history_pos > 0 {
466                    s.history_pos -= 1;
467                }
468                if let Some(before) = s.history.iter().nth_back(s.history.len() - s.history_pos) {
469                    s.input.message.clone_from(before);
470                    force_cursor = cursor_offset_to_index(
471                        s.input.message.len(),
472                        &s.input.message,
473                        ui,
474                        self.fonts,
475                        chat_box_input_width,
476                    );
477                } else {
478                    s.input.message.clear();
479                }
480            });
481        }
482
483        let keyboard_capturer = ui.global_input().current.widget_capturing_keyboard;
484
485        if let Some(input) = &self.force_input {
486            state.update(|s| s.input.message = input.to_string());
487        }
488
489        let input_focused =
490            keyboard_capturer == Some(state.ids.chat_input) || keyboard_capturer == Some(id);
491
492        // Only show if it has the keyboard captured.
493        // Chat input uses a rectangle as its background.
494        if input_focused {
495            // Shallow comparison of ChatMode.
496            let discrim = std::mem::discriminant;
497            if discrim(&state.input.mode) != discrim(&self.client.chat_mode) {
498                state.update(|s| {
499                    s.input.mode = self.client.chat_mode.clone();
500                });
501            }
502
503            let (color, icon) = render_chat_mode(&state.input.mode, self.imgs);
504            Image::new(icon)
505                .w_h(CHAT_ICON_WIDTH, CHAT_ICON_HEIGHT)
506                .top_left_with_margin_on(state.ids.chat_input_bg, 2.0)
507                .set(state.ids.chat_input_icon, ui);
508
509            // Any changes to this TextEdit's width and font size must be reflected in
510            // `cursor_offset_to_index` below.
511            let mut text_edit = TextEdit::new(&state.input.message)
512                .w(chat_box_input_width)
513                .restrict_to_height(false)
514                .color(color)
515                .line_spacing(2.0)
516                .font_size(self.fonts.universal.scale(15))
517                .font_id(self.fonts.universal.conrod_id);
518
519            if let Some(pos) = force_cursor {
520                text_edit = text_edit.cursor_pos(pos);
521            }
522
523            let y = match text_edit.get_y_dimension(ui) {
524                Dimension::Absolute(y) => y + 6.0,
525                _ => 0.0,
526            };
527            Rectangle::fill([chat_size.x, y])
528                .rgba(0.0, 0.0, 0.0, chat_settings.chat_opacity)
529                .w(chat_size.x)
530                .and(|r| {
531                    if chat_in_screen_upper {
532                        r.down_from(state.ids.message_box_bg, CHAT_MARGIN_THICKNESS / 2.0)
533                    } else {
534                        r.bottom_left_with_margins_on(ui.window, chat_pos.y, chat_pos.x)
535                    }
536                })
537                .set(state.ids.chat_input_bg, ui);
538
539            //border around focused chat window
540            let border_color = adjust_border_opacity(color, chat_settings.chat_opacity);
541            //top line
542            Line::centred([0.0, 0.0], [chat_size.x, 0.0])
543                .color(border_color)
544                .thickness(CHAT_MARGIN_THICKNESS)
545                .top_left_of(state.ids.chat_input_bg)
546                .set(state.ids.chat_input_border_up, ui);
547            //bottom line
548            Line::centred([0.0, 0.0], [chat_size.x, 0.0])
549                .color(border_color)
550                .thickness(CHAT_MARGIN_THICKNESS)
551                .bottom_left_of(state.ids.chat_input_bg)
552                .set(state.ids.chat_input_border_down, ui);
553            //left line
554            Line::centred([0.0, 0.0], [0.0, y])
555                .color(border_color)
556                .thickness(CHAT_MARGIN_THICKNESS)
557                .bottom_left_of(state.ids.chat_input_bg)
558                .set(state.ids.chat_input_border_left, ui);
559            //right line
560            Line::centred([0.0, 0.0], [0.0, y])
561                .color(border_color)
562                .thickness(CHAT_MARGIN_THICKNESS)
563                .bottom_right_of(state.ids.chat_input_bg)
564                .set(state.ids.chat_input_border_right, ui);
565
566            if let Some(mut input) = text_edit
567                .right_from(state.ids.chat_input_icon, 1.0)
568                .set(state.ids.chat_input, ui)
569            {
570                input.retain(|c| c != '\n');
571                state.update(|s| s.input.message = input);
572            }
573        }
574
575        // Message box
576        Rectangle::fill([chat_size.x, chat_size.y])
577            .rgba(0.0, 0.0, 0.0, chat_settings.chat_opacity)
578            .and(|r| {
579                if input_focused && !chat_in_screen_upper {
580                    r.up_from(
581                        state.ids.chat_input_border_up,
582                        0.0 + CHAT_MARGIN_THICKNESS / 2.0,
583                    )
584                } else {
585                    r.bottom_left_with_margins_on(ui.window, chat_pos.y, chat_pos.x)
586                }
587            })
588            .crop_kids()
589            .set(state.ids.message_box_bg, ui);
590        if state.ids.chat_icons.len() < state.messages.len() {
591            state.update(|s| {
592                s.ids
593                    .chat_icons
594                    .resize(s.messages.len(), &mut ui.widget_id_generator())
595            });
596        }
597        let group_members = self
598            .client
599            .group_members()
600            .iter()
601            .filter_map(|(u, r)| match r {
602                Role::Member => Some(u),
603                Role::Pet => None,
604            })
605            .collect::<HashSet<_>>();
606        let show_char_name = chat_settings.chat_character_name;
607        let messages = &state
608            .messages
609            .iter()
610            .filter(|m| {
611                if let Some(chat_tab) = current_chat_tab {
612                    chat_tab.filter.satisfies(m, &group_members)
613                } else {
614                    true
615                }
616            })
617            .map(|m| {
618                let is_moderator = m
619                    .uid()
620                    .and_then(|uid| self.client.player_list().get(&uid).map(|i| i.is_moderator))
621                    .unwrap_or(false);
622                let (chat_type, text) = localize_chat_message(
623                    m,
624                    &self.client.lookup_msg_context(m),
625                    self.localized_strings,
626                    show_char_name,
627                );
628                (is_moderator, chat_type, text)
629            })
630            .collect::<Vec<_>>();
631        let n_badges = messages.iter().filter(|t| t.0).count();
632        if state.ids.chat_badges.len() < n_badges {
633            state.update(|s| {
634                s.ids
635                    .chat_badges
636                    .resize(n_badges, &mut ui.widget_id_generator())
637            })
638        }
639        Rectangle::fill_with([CHAT_ICON_WIDTH, chat_size.y], color::TRANSPARENT)
640            .top_left_with_margins_on(state.ids.message_box_bg, 0.0, 0.0)
641            .crop_kids()
642            .set(state.ids.chat_icon_align, ui);
643        let (mut items, _) = List::flow_down(messages.len() + 1)
644            .top_left_with_margins_on(state.ids.message_box_bg, 0.0, CHAT_ICON_WIDTH)
645            .w_h(chat_size.x - CHAT_ICON_WIDTH, chat_size.y)
646            .scroll_kids_vertically()
647            .set(state.ids.message_box, ui);
648
649        let mut badge_id = 0;
650        while let Some(item) = items.next(ui) {
651            /// Calculate the width of the group text or faction name
652            fn group_width(chat_type: &ChatType<String>, ui: &Ui, font: &Font) -> Option<f64> {
653                // This is a temporary solution on a best effort basis
654                // This needs to be reworked in the long run
655                let text = match chat_type {
656                    ChatType::Group(_, desc) => desc.as_str(),
657                    ChatType::Faction(_, desc) => desc.as_str(),
658                    _ => return None,
659                };
660                let bracket_width = Text::new("() ")
661                    .font_size(font.scale(15))
662                    .font_id(font.conrod_id)
663                    .get_w(ui)?;
664                Text::new(text)
665                    .font_size(font.scale(15))
666                    .font_id(font.conrod_id)
667                    .get_w(ui)
668                    .map(|v| bracket_width + v)
669            }
670            // This would be easier if conrod used the v-metrics from rusttype.
671            if item.i < messages.len() {
672                let (is_moderator, chat_type, text) = &messages[item.i];
673                let (color, icon) = render_chat_line(chat_type, self.imgs);
674                // For each ChatType needing localization get/set matching pre-formatted
675                // localized string. This string will be formatted with the data
676                // provided in ChatType in the client/src/mod.rs
677                // fn format_message called below
678
679                let text = Text::new(text)
680                    .font_size(self.fonts.universal.scale(15))
681                    .font_id(self.fonts.universal.conrod_id)
682                    .w(chat_size.x - CHAT_ICON_WIDTH - 1.0)
683                    .wrap_by_word()
684                    .color(color)
685                    .line_spacing(2.0);
686
687                // Add space between messages.
688                let y = match text.get_y_dimension(ui) {
689                    Dimension::Absolute(y) => y + 2.0,
690                    _ => 0.0,
691                };
692                item.set(text.h(y), ui);
693
694                // If the user is a moderator display a moderator icon with their alias.
695                if *is_moderator {
696                    let group_width =
697                        group_width(chat_type, ui, &self.fonts.universal).unwrap_or(0.0);
698                    Image::new(self.imgs.chat_moderator_badge)
699                        .w_h(CHAT_ICON_WIDTH, CHAT_ICON_HEIGHT)
700                        .top_left_with_margins_on(item.widget_id, 2.0, 7.0 + group_width)
701                        .parent(state.ids.message_box_bg)
702                        .set(state.ids.chat_badges[badge_id], ui);
703
704                    badge_id += 1;
705                }
706
707                let icon_id = state.ids.chat_icons[item.i];
708                Image::new(icon)
709                    .w_h(CHAT_ICON_WIDTH, CHAT_ICON_HEIGHT)
710                    .top_left_with_margins_on(item.widget_id, 2.0, -CHAT_ICON_WIDTH)
711                    .parent(state.ids.chat_icon_align)
712                    .set(icon_id, ui);
713            } else {
714                // Spacer at bottom of the last message so that it is not cut off.
715                // Needs to be larger than the space above.
716                item.set(
717                    Text::new("")
718                        .font_size(self.fonts.universal.scale(6))
719                        .font_id(self.fonts.universal.conrod_id)
720                        .w(chat_size.x),
721                    ui,
722                );
723            };
724        }
725
726        //Chat tabs
727        if ui
728            .rect_of(state.ids.message_box_bg)
729            .is_some_and(|r| r.is_over(ui.global_input().current.mouse.xy))
730        {
731            state.update(|s| s.tabs_last_hover_pulse = Some(self.pulse));
732        }
733
734        if let Some(time_since_hover) = state
735            .tabs_last_hover_pulse
736            .map(|t| self.pulse - t)
737            .filter(|t| t <= &1.5)
738        {
739            let alpha = 1.0 - (time_since_hover / 1.5).powi(4);
740            let shading = color::rgba(1.0, 0.82, 0.27, chat_settings.chat_opacity * alpha);
741
742            Rectangle::fill([chat_size.x, CHAT_TAB_HEIGHT])
743                .rgba(0.0, 0.0, 0.0, chat_settings.chat_opacity * alpha)
744                .up_from(state.ids.message_box_bg, 0.0)
745                .set(state.ids.chat_tab_align, ui);
746            if ui
747                .rect_of(state.ids.chat_tab_align)
748                .is_some_and(|r| r.is_over(ui.global_input().current.mouse.xy))
749            {
750                state.update(|s| s.tabs_last_hover_pulse = Some(self.pulse));
751            }
752
753            if Button::image(if chat_settings.chat_tab_index.is_none() {
754                self.imgs.selection
755            } else {
756                self.imgs.nothing
757            })
758            .top_left_with_margins_on(state.ids.chat_tab_align, 0.0, 0.0)
759            .w_h(CHAT_TAB_ALL_WIDTH, CHAT_TAB_HEIGHT)
760            .hover_image(self.imgs.selection_hover)
761            .hover_image(self.imgs.selection_press)
762            .image_color(shading)
763            .label(&self.localized_strings.get_msg("hud-chat-all"))
764            .label_font_size(self.fonts.cyri.scale(14))
765            .label_font_id(self.fonts.cyri.conrod_id)
766            .label_color(TEXT_COLOR.alpha(alpha))
767            .set(state.ids.chat_tab_all, ui)
768            .was_clicked()
769            {
770                events.push(Event::ChangeChatTab(None));
771            }
772
773            let chat_tab_width = (chat_size.x - CHAT_TAB_ALL_WIDTH) / (MAX_CHAT_TABS as f64);
774
775            if state.ids.chat_tabs.len() < chat_tabs.len() {
776                state.update(|s| {
777                    s.ids
778                        .chat_tabs
779                        .resize(chat_tabs.len(), &mut ui.widget_id_generator())
780                });
781            }
782            for (i, chat_tab) in chat_tabs.iter().enumerate() {
783                if Button::image(if chat_settings.chat_tab_index == Some(i) {
784                    self.imgs.selection
785                } else {
786                    self.imgs.nothing
787                })
788                .w_h(chat_tab_width, CHAT_TAB_HEIGHT)
789                .hover_image(self.imgs.selection_hover)
790                .press_image(self.imgs.selection_press)
791                .image_color(shading)
792                .label(chat_tab.label.as_str())
793                .label_font_size(self.fonts.cyri.scale(14))
794                .label_font_id(self.fonts.cyri.conrod_id)
795                .label_color(TEXT_COLOR.alpha(alpha))
796                .right_from(
797                    if i == 0 {
798                        state.ids.chat_tab_all
799                    } else {
800                        state.ids.chat_tabs[i - 1]
801                    },
802                    0.0,
803                )
804                .set(state.ids.chat_tabs[i], ui)
805                .was_clicked()
806                {
807                    events.push(Event::ChangeChatTab(Some(i)));
808                }
809
810                if ui
811                    .widget_input(state.ids.chat_tabs[i])
812                    .mouse()
813                    .is_some_and(|m| m.is_over())
814                {
815                    Rectangle::fill([120.0, 20.0])
816                        .rgba(0.0, 0.0, 0.0, 0.9)
817                        .top_left_with_margins_on(state.ids.chat_tabs[i], -20.0, 5.0)
818                        .parent(id)
819                        .set(state.ids.chat_tab_tooltip_bg, ui);
820
821                    Text::new(
822                        &self
823                            .localized_strings
824                            .get_msg("hud-chat-chat_tab_hover_tooltip"),
825                    )
826                    .mid_top_with_margin_on(state.ids.chat_tab_tooltip_bg, 3.0)
827                    .font_size(self.fonts.cyri.scale(10))
828                    .font_id(self.fonts.cyri.conrod_id)
829                    .color(TEXT_COLOR)
830                    .set(state.ids.chat_tab_tooltip_text, ui);
831                }
832
833                if ui
834                    .widget_input(state.ids.chat_tabs[i])
835                    .clicks()
836                    .right()
837                    .next()
838                    .is_some()
839                {
840                    events.push(Event::ShowChatTabSettings(i));
841                }
842            }
843        }
844
845        // Chat Arrow
846        // Check if already at bottom.
847        if !Self::scrolled_to_bottom(state, ui)
848            && Button::image(self.imgs.chat_arrow)
849                .w_h(20.0, 20.0)
850                .hover_image(self.imgs.chat_arrow_mo)
851                .press_image(self.imgs.chat_arrow_press)
852                .top_right_with_margins_on(state.ids.message_box_bg, 0.0, -22.0)
853                .parent(id)
854                .set(state.ids.chat_arrow, ui)
855                .was_clicked()
856        {
857            ui.scroll_widget(state.ids.message_box, [0.0, f64::MAX]);
858        }
859
860        // We've started a new tab completion. Populate tab completion suggestions.
861        if request_tab_completions {
862            events.push(Event::TabCompletionStart(state.input.message.to_string()));
863        // If the chat widget is focused, return a focus event to pass the focus
864        // to the input box.
865        } else if keyboard_capturer == Some(id) {
866            events.push(Event::Focus(state.ids.chat_input));
867        }
868        // If either Return or Enter is pressed and the input box is not empty, send the current
869        // message.
870        else if ui
871            .widget_input(state.ids.chat_input)
872            .presses()
873            .key()
874            .any(|key_press| {
875                let has_message = !state.input.message.is_empty();
876                let pressed = matches!(key_press.key, Key::Return | Key::NumPadEnter);
877                if pressed {
878                    // If chat was hidden, scroll to bottom the next time it is opened
879                    state.update(|s| s.scroll_next |= force_chat);
880                    events.push(Event::DisableForceChat);
881                }
882                has_message && pressed
883            })
884        {
885            let msg = state.input.message.clone();
886            state.update(|s| {
887                s.input.message.clear();
888                // Update the history
889                // Don't add if this is identical to the last message in the history
890                s.history_pos = 0;
891                if s.history.front() != Some(&msg) {
892                    s.history.push_front(msg.clone());
893                    s.history.truncate(self.history_max);
894                }
895            });
896            if let Some(msg) = msg.strip_prefix(chat_settings.chat_cmd_prefix) {
897                match parse_cmd(msg) {
898                    Ok((name, args)) => events.push(Event::SendCommand(name.to_owned(), args)),
899                    // TODO: Localise
900                    Err(err) => self
901                        .new_messages
902                        .push_back(ChatType::CommandError.into_plain_msg(err)),
903                }
904            } else {
905                events.push(Event::SendMessage(msg));
906            }
907        }
908
909        Rectangle::fill_with([chat_size.x, chat_size.y], color::TRANSPARENT)
910            .and(|r| {
911                if input_focused {
912                    r.up_from(state.ids.chat_input_border_up, CHAT_MARGIN_THICKNESS / 2.0)
913                } else {
914                    r.bottom_left_with_margins_on(ui.window, chat_pos.y, chat_pos.x)
915                }
916            })
917            .set(state.ids.draggable_area, ui);
918        events
919    }
920}
921
922fn do_tab_completion(cursor: usize, input: &str, word: &str) -> (String, usize) {
923    let mut pre_ws = None;
924    let mut post_ws = None;
925    let mut in_quotation = false;
926    for (char_i, (byte_i, c)) in input.char_indices().enumerate() {
927        if c == '"' {
928            in_quotation = !in_quotation;
929        } else if !in_quotation && c.is_whitespace() && c != '\t' {
930            if char_i < cursor {
931                pre_ws = Some(byte_i);
932            } else {
933                post_ws = Some(byte_i);
934                break;
935            }
936        }
937    }
938
939    match (pre_ws, post_ws) {
940        (None, None) => (word.to_string(), word.chars().count()),
941        (None, Some(i)) => (
942            format!("{}{}", word, input.split_at(i).1),
943            word.chars().count(),
944        ),
945        (Some(i), None) => {
946            let l_split = input.split_at(i).0;
947            let completed = format!("{} {}", l_split, word);
948            (
949                completed,
950                l_split.chars().count() + 1 + word.chars().count(),
951            )
952        },
953        (Some(i), Some(j)) => {
954            let l_split = input.split_at(i).0;
955            let r_split = input.split_at(j).1;
956            let completed = format!("{} {}{}", l_split, word, r_split);
957            (
958                completed,
959                l_split.chars().count() + 1 + word.chars().count(),
960            )
961        },
962    }
963}
964
965fn cursor_offset_to_index(
966    offset: usize,
967    text: &str,
968    ui: &Ui,
969    fonts: &Fonts,
970    input_width: f64,
971) -> Option<Index> {
972    // This moves the cursor to the given offset. Conrod is a pain.
973    //
974    // Width and font must match that of the chat TextEdit
975    let font = ui.fonts.get(fonts.universal.conrod_id)?;
976    let font_size = fonts.universal.scale(15);
977    let infos = text::line::infos(text, font, font_size).wrap_by_whitespace(input_width);
978
979    cursor::index_before_char(infos, offset)
980}
981
982/// Get the color and icon for a client's ChatMode.
983fn render_chat_mode(chat_mode: &ChatMode, imgs: &Imgs) -> (Color, conrod_core::image::Id) {
984    match chat_mode {
985        ChatMode::World => (WORLD_COLOR, imgs.chat_world_small),
986        ChatMode::Say => (SAY_COLOR, imgs.chat_say_small),
987        ChatMode::Region => (REGION_COLOR, imgs.chat_region_small),
988        ChatMode::Faction(_) => (FACTION_COLOR, imgs.chat_faction_small),
989        ChatMode::Group => (GROUP_COLOR, imgs.chat_group_small),
990        ChatMode::Tell(_) => (TELL_COLOR, imgs.chat_tell_small),
991    }
992}
993
994/// Get the color and icon for the current line in the chat box
995fn render_chat_line(chat_type: &ChatType<String>, imgs: &Imgs) -> (Color, conrod_core::image::Id) {
996    match chat_type {
997        ChatType::Online(_) => (ONLINE_COLOR, imgs.chat_online_small),
998        ChatType::Offline(_) => (OFFLINE_COLOR, imgs.chat_offline_small),
999        ChatType::CommandError => (ERROR_COLOR, imgs.chat_command_error_small),
1000        ChatType::CommandInfo => (INFO_COLOR, imgs.chat_command_info_small),
1001        ChatType::GroupMeta(_) => (GROUP_COLOR, imgs.chat_group_small),
1002        ChatType::FactionMeta(_) => (FACTION_COLOR, imgs.chat_faction_small),
1003        ChatType::Kill(_, _) => (KILL_COLOR, imgs.chat_kill_small),
1004        ChatType::Tell(_from, _to) => (TELL_COLOR, imgs.chat_tell_small),
1005        ChatType::Say(_uid) => (SAY_COLOR, imgs.chat_say_small),
1006        ChatType::Group(_uid, _s) => (GROUP_COLOR, imgs.chat_group_small),
1007        ChatType::Faction(_uid, _s) => (FACTION_COLOR, imgs.chat_faction_small),
1008        ChatType::Region(_uid) => (REGION_COLOR, imgs.chat_region_small),
1009        ChatType::World(_uid) => (WORLD_COLOR, imgs.chat_world_small),
1010        ChatType::Npc(_uid) => panic!("NPCs can't talk!"), // Should be filtered by hud/mod.rs
1011        ChatType::NpcSay(_uid) => (SAY_COLOR, imgs.chat_say_small),
1012        ChatType::NpcTell(_from, _to) => (TELL_COLOR, imgs.chat_tell_small),
1013        ChatType::Meta => (INFO_COLOR, imgs.chat_command_info_small),
1014    }
1015}
1016
1017fn parse_cmd(msg: &str) -> Result<(&str, Vec<String>), String> {
1018    use chumsky::{extra::Err, prelude::*, text::unicode::ident};
1019
1020    let escape = just::<_, _, Err<Simple<char>>>('\\').ignore_then(
1021        just('\\')
1022            .or(just('/'))
1023            .or(just('"'))
1024            .or(just('b').to('\x08'))
1025            .or(just('f').to('\x0C'))
1026            .or(just('n').to('\n'))
1027            .or(just('r').to('\r'))
1028            .or(just('t').to('\t')),
1029    );
1030
1031    let string = any()
1032        .filter(|c| *c != '\\' && *c != '"')
1033        .or(escape)
1034        .repeated()
1035        .collect::<String>()
1036        .delimited_by(just('"'), just('"'))
1037        .labelled("quoted argument");
1038
1039    let arg = string.or(any()
1040        .filter(|c: &char| !c.is_whitespace() && *c != '"')
1041        .repeated()
1042        .at_least(1)
1043        .collect::<String>()
1044        .labelled("argument"));
1045
1046    let cmd = ident()
1047        .then(arg.padded().repeated().collect::<Vec<String>>())
1048        .then_ignore(end());
1049
1050    cmd.parse(msg).into_result().map_err(|errs| {
1051        errs.into_iter()
1052            .map(|err| err.to_string())
1053            .collect::<Vec<_>>()
1054            .join(", ")
1055    })
1056}
1057
1058/// Change the chat mode if we have a `ServerChatCommand` that corresponds to a
1059/// chat region (i.e. World, Region, Say, etc.).
1060fn change_chat_mode(
1061    message: String,
1062    state: &mut conrod_core::widget::State<State>,
1063    events: &mut Vec<Event>,
1064    chat_settings: &ChatSettings,
1065) {
1066    if let Some(msg) = message.strip_prefix(chat_settings.chat_cmd_prefix) {
1067        // Do nothing on Err because we are just completing the Chat Mode
1068        if let Ok((name, args)) = parse_cmd(msg.trim())
1069            && let Ok(command) = name.parse::<ServerChatCommand>()
1070        {
1071            match command {
1072                ServerChatCommand::Group
1073                | ServerChatCommand::Say
1074                | ServerChatCommand::Faction
1075                | ServerChatCommand::Region
1076                | ServerChatCommand::World => {
1077                    // Only remove the command if there is no message
1078                    if args.is_empty() {
1079                        // We found a match to a command so clear the input
1080                        // message
1081                        state.update(|s| s.input.message.clear());
1082                        events.push(Event::SendCommand(name.to_owned(), args))
1083                    }
1084                },
1085                // TODO: Add support for Whispers (might need to adjust widget
1086                // for this.)
1087                _ => (),
1088            }
1089        }
1090    }
1091}
1092
1093#[cfg(test)]
1094mod tests {
1095    use super::*;
1096
1097    #[test]
1098    fn parse_cmds() {
1099        let expected: Result<(&str, Vec<String>), String> = Ok(("help", vec![]));
1100        assert_eq!(parse_cmd(r"help"), expected);
1101
1102        let expected: Result<(&str, Vec<String>), String> =
1103            Ok(("say", vec!["foo".to_string(), "bar".to_string()]));
1104        assert_eq!(parse_cmd(r"say foo bar"), expected);
1105        assert_eq!(parse_cmd(r#"say "foo" "bar""#), expected);
1106
1107        let expected: Result<(&str, Vec<String>), String> =
1108            Ok(("say", vec!["Hello World".to_string()]));
1109        assert_eq!(parse_cmd(r#"say "Hello World""#), expected);
1110
1111        // Note: \n in the expected gets expanded by rust to a newline character, that's
1112        // why we must not use a raw string in the expected
1113        let expected: Result<(&str, Vec<String>), String> =
1114            Ok(("say", vec!["Hello\nWorld".to_string()]));
1115        assert_eq!(parse_cmd(r#"say "Hello\nWorld""#), expected);
1116    }
1117}