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            let new_pos = (chat_pos + pos_delta).map(|e| e.max(0.)).map2(
322                self.scale.scale_point(Vec2::new(ui.win_w, ui.win_h))
323                    - Vec2::unit_y() * CHAT_TAB_HEIGHT
324                    - chat_size,
325                |e, bounds| e.min(bounds),
326            );
327            if new_pos.abs_diff_ne(&chat_pos, f64::EPSILON) {
328                events.push(Event::MoveChat(new_pos));
329            }
330            let size_delta: Vec2<f64> = ui
331                .widget_input(state.ids.draggable_area)
332                .drags()
333                .right()
334                .map(|drag| Vec2::<f64>::from(drag.delta_xy))
335                .sum();
336            let new_size = (chat_size + size_delta)
337                .map3(
338                    self.scale.scale_point(MIN_DIMENSION),
339                    self.scale.scale_point(MAX_DIMENSION),
340                    |sz, min, max| sz.clamp(min, max),
341                )
342                .map2(
343                    self.scale.scale_point(Vec2::new(ui.win_w, ui.win_h))
344                        - Vec2::unit_y() * CHAT_TAB_HEIGHT
345                        - new_pos,
346                    |e, bounds| e.min(bounds),
347                );
348            if new_size.abs_diff_ne(&chat_size, f64::EPSILON) {
349                events.push(Event::ResizeChat(new_size));
350            }
351        }
352
353        // Maintain scrolling
354        if !self.new_messages.is_empty() {
355            for message in self.new_messages.iter() {
356                // Log the output of commands since the ingame terminal doesn't support copying
357                // the output to the clipboard
358                if let ChatType::CommandInfo = &message.chat_type {
359                    tracing::info!("Chat command info: {:?}", message.content());
360                }
361            }
362            // new messages - update chat w/ them & scroll down if at bottom of chat
363            state.update(|s| s.messages.extend(self.new_messages.drain(..)));
364            // Prevent automatic scroll upon new messages if not already scrolled to bottom
365            if Self::scrolled_to_bottom(state, ui) {
366                ui.scroll_widget(state.ids.message_box, [0.0, f64::MAX]);
367            }
368        }
369
370        // Trigger scroll event queued from previous frame
371        if state.scroll_next {
372            ui.scroll_widget(state.ids.message_box, [0.0, f64::MAX]);
373            state.update(|s| s.scroll_next = false);
374        }
375
376        // Queue scroll event if switching from a different tab
377        if current_chat_tab != state.prev_chat_tab.as_ref() {
378            state.update(|s| s.prev_chat_tab = current_chat_tab.cloned());
379            state.update(|s| s.scroll_next = true); //make scroll happen only once any filters to the messages have already been applied
380        }
381
382        if let Some(comps) = &self.force_completions {
383            state.update(|s| s.completions.clone_from(comps));
384        }
385
386        let mut force_cursor = self.force_cursor;
387
388        // If up or down are pressed: move through history
389        // If any key other than up, down, or tab is pressed: stop completion.
390        let (history_dir, tab_dir, stop_tab_completion) =
391            ui.widget_input(state.ids.chat_input).presses().key().fold(
392                (0isize, 0isize, false),
393                |(n, m, tc), key_press| match key_press.key {
394                    Key::Up => (n + 1, m - 1, tc),
395                    Key::Down => (n - 1, m + 1, tc),
396                    Key::Tab => (n, m + 1, tc),
397                    _ => (n, m, true),
398                },
399            );
400
401        // Handle tab completion
402        let request_tab_completions = if stop_tab_completion {
403            // End tab completion
404            state.update(|s| {
405                if s.completion_cursor.is_some() {
406                    s.completion_cursor = None;
407                }
408                s.completions_index = None;
409            });
410            false
411        } else if let Some(cursor) = state.completion_cursor {
412            // Cycle through tab completions of the current word
413            if state.input.message.contains('\t') {
414                state.update(|s| s.input.message.retain(|c| c != '\t'));
415                //tab_dir + 1
416            }
417            if !state.completions.is_empty() && (tab_dir != 0 || state.completions_index.is_none())
418            {
419                state.update(|s| {
420                    let len = s.completions.len();
421                    s.completions_index = Some(
422                        (s.completions_index.unwrap_or(0) + (tab_dir + len as isize) as usize)
423                            % len,
424                    );
425                    if let Some(replacement) = &s.completions.get(s.completions_index.unwrap()) {
426                        let (completed, offset) =
427                            do_tab_completion(cursor, &s.input.message, replacement);
428                        force_cursor = cursor_offset_to_index(
429                            offset,
430                            &completed,
431                            ui,
432                            self.fonts,
433                            chat_box_input_width,
434                        );
435                        s.input.message = completed;
436                    }
437                });
438            }
439            false
440        } else if let Some(cursor) = state.input.message.find('\t') {
441            // Begin tab completion
442            state.update(|s| s.completion_cursor = Some(cursor));
443            true
444        } else {
445            // Not tab completing
446            false
447        };
448
449        // Check if we need to change the chat mode if we have completed a command
450        if state.input.message.ends_with(' ') {
451            change_chat_mode(
452                state.input.message.clone(),
453                state,
454                &mut events,
455                chat_settings,
456            );
457        }
458
459        // Move through history
460        if history_dir != 0 && state.completion_cursor.is_none() {
461            state.update(|s| {
462                if history_dir > 0 {
463                    if s.history_pos < s.history.len() {
464                        s.history_pos += 1;
465                    }
466                } else if s.history_pos > 0 {
467                    s.history_pos -= 1;
468                }
469                if let Some(before) = s.history.iter().nth_back(s.history.len() - s.history_pos) {
470                    s.input.message.clone_from(before);
471                    force_cursor = cursor_offset_to_index(
472                        s.input.message.len(),
473                        &s.input.message,
474                        ui,
475                        self.fonts,
476                        chat_box_input_width,
477                    );
478                } else {
479                    s.input.message.clear();
480                }
481            });
482        }
483
484        let keyboard_capturer = ui.global_input().current.widget_capturing_keyboard;
485
486        if let Some(input) = &self.force_input {
487            state.update(|s| s.input.message = input.to_string());
488        }
489
490        let input_focused =
491            keyboard_capturer == Some(state.ids.chat_input) || keyboard_capturer == Some(id);
492
493        // Only show if it has the keyboard captured.
494        // Chat input uses a rectangle as its background.
495        if input_focused {
496            // Shallow comparison of ChatMode.
497            let discrim = std::mem::discriminant;
498            if discrim(&state.input.mode) != discrim(&self.client.chat_mode) {
499                state.update(|s| {
500                    s.input.mode = self.client.chat_mode.clone();
501                });
502            }
503
504            let (color, icon) = render_chat_mode(&state.input.mode, self.imgs);
505            Image::new(icon)
506                .w_h(CHAT_ICON_WIDTH, CHAT_ICON_HEIGHT)
507                .top_left_with_margin_on(state.ids.chat_input_bg, 2.0)
508                .set(state.ids.chat_input_icon, ui);
509
510            // Any changes to this TextEdit's width and font size must be reflected in
511            // `cursor_offset_to_index` below.
512            let mut text_edit = TextEdit::new(&state.input.message)
513                .w(chat_box_input_width)
514                .restrict_to_height(false)
515                .color(color)
516                .line_spacing(2.0)
517                .font_size(self.fonts.universal.scale(15))
518                .font_id(self.fonts.universal.conrod_id);
519
520            if let Some(pos) = force_cursor {
521                text_edit = text_edit.cursor_pos(pos);
522            }
523
524            let y = match text_edit.get_y_dimension(ui) {
525                Dimension::Absolute(y) => y + 6.0,
526                _ => 0.0,
527            };
528            Rectangle::fill([chat_size.x, y])
529                .rgba(0.0, 0.0, 0.0, chat_settings.chat_opacity)
530                .w(chat_size.x)
531                .and(|r| {
532                    if chat_in_screen_upper {
533                        r.down_from(state.ids.message_box_bg, CHAT_MARGIN_THICKNESS / 2.0)
534                    } else {
535                        r.bottom_left_with_margins_on(ui.window, chat_pos.y, chat_pos.x)
536                    }
537                })
538                .set(state.ids.chat_input_bg, ui);
539
540            //border around focused chat window
541            let border_color = adjust_border_opacity(color, chat_settings.chat_opacity);
542            //top line
543            Line::centred([0.0, 0.0], [chat_size.x, 0.0])
544                .color(border_color)
545                .thickness(CHAT_MARGIN_THICKNESS)
546                .top_left_of(state.ids.chat_input_bg)
547                .set(state.ids.chat_input_border_up, ui);
548            //bottom line
549            Line::centred([0.0, 0.0], [chat_size.x, 0.0])
550                .color(border_color)
551                .thickness(CHAT_MARGIN_THICKNESS)
552                .bottom_left_of(state.ids.chat_input_bg)
553                .set(state.ids.chat_input_border_down, ui);
554            //left line
555            Line::centred([0.0, 0.0], [0.0, y])
556                .color(border_color)
557                .thickness(CHAT_MARGIN_THICKNESS)
558                .bottom_left_of(state.ids.chat_input_bg)
559                .set(state.ids.chat_input_border_left, ui);
560            //right line
561            Line::centred([0.0, 0.0], [0.0, y])
562                .color(border_color)
563                .thickness(CHAT_MARGIN_THICKNESS)
564                .bottom_right_of(state.ids.chat_input_bg)
565                .set(state.ids.chat_input_border_right, ui);
566
567            if let Some(mut input) = text_edit
568                .right_from(state.ids.chat_input_icon, 1.0)
569                .set(state.ids.chat_input, ui)
570            {
571                input.retain(|c| c != '\n');
572                state.update(|s| s.input.message = input);
573            }
574        }
575
576        // Message box
577        Rectangle::fill([chat_size.x, chat_size.y])
578            .rgba(0.0, 0.0, 0.0, chat_settings.chat_opacity)
579            .and(|r| {
580                if input_focused && !chat_in_screen_upper {
581                    r.up_from(
582                        state.ids.chat_input_border_up,
583                        0.0 + CHAT_MARGIN_THICKNESS / 2.0,
584                    )
585                } else {
586                    r.bottom_left_with_margins_on(ui.window, chat_pos.y, chat_pos.x)
587                }
588            })
589            .crop_kids()
590            .set(state.ids.message_box_bg, ui);
591        if state.ids.chat_icons.len() < state.messages.len() {
592            state.update(|s| {
593                s.ids
594                    .chat_icons
595                    .resize(s.messages.len(), &mut ui.widget_id_generator())
596            });
597        }
598        let group_members = self
599            .client
600            .group_members()
601            .iter()
602            .filter_map(|(u, r)| match r {
603                Role::Member => Some(u),
604                Role::Pet => None,
605            })
606            .collect::<HashSet<_>>();
607        let show_char_name = chat_settings.chat_character_name;
608        let messages = &state
609            .messages
610            .iter()
611            .filter(|m| {
612                if let Some(chat_tab) = current_chat_tab {
613                    chat_tab.filter.satisfies(m, &group_members)
614                } else {
615                    true
616                }
617            })
618            .map(|m| {
619                let is_moderator = m
620                    .uid()
621                    .and_then(|uid| self.client.player_list().get(&uid).map(|i| i.is_moderator))
622                    .unwrap_or(false);
623                let (chat_type, text) = localize_chat_message(
624                    m,
625                    &self.client.lookup_msg_context(m),
626                    self.localized_strings,
627                    show_char_name,
628                );
629                (is_moderator, chat_type, text)
630            })
631            .collect::<Vec<_>>();
632        let n_badges = messages.iter().filter(|t| t.0).count();
633        if state.ids.chat_badges.len() < n_badges {
634            state.update(|s| {
635                s.ids
636                    .chat_badges
637                    .resize(n_badges, &mut ui.widget_id_generator())
638            })
639        }
640        Rectangle::fill_with([CHAT_ICON_WIDTH, chat_size.y], color::TRANSPARENT)
641            .top_left_with_margins_on(state.ids.message_box_bg, 0.0, 0.0)
642            .crop_kids()
643            .set(state.ids.chat_icon_align, ui);
644        let (mut items, _) = List::flow_down(messages.len() + 1)
645            .top_left_with_margins_on(state.ids.message_box_bg, 0.0, CHAT_ICON_WIDTH)
646            .w_h(chat_size.x - CHAT_ICON_WIDTH, chat_size.y)
647            .scroll_kids_vertically()
648            .set(state.ids.message_box, ui);
649
650        let mut badge_id = 0;
651        while let Some(item) = items.next(ui) {
652            /// Calculate the width of the group text or faction name
653            fn group_width(chat_type: &ChatType<String>, ui: &Ui, font: &Font) -> Option<f64> {
654                // This is a temporary solution on a best effort basis
655                // This needs to be reworked in the long run
656                let text = match chat_type {
657                    ChatType::Group(_, desc) => desc.as_str(),
658                    ChatType::Faction(_, desc) => desc.as_str(),
659                    _ => return None,
660                };
661                let bracket_width = Text::new("() ")
662                    .font_size(font.scale(15))
663                    .font_id(font.conrod_id)
664                    .get_w(ui)?;
665                Text::new(text)
666                    .font_size(font.scale(15))
667                    .font_id(font.conrod_id)
668                    .get_w(ui)
669                    .map(|v| bracket_width + v)
670            }
671            // This would be easier if conrod used the v-metrics from rusttype.
672            if item.i < messages.len() {
673                let (is_moderator, chat_type, text) = &messages[item.i];
674                let (color, icon) = render_chat_line(chat_type, self.imgs);
675                // For each ChatType needing localization get/set matching pre-formatted
676                // localized string. This string will be formatted with the data
677                // provided in ChatType in the client/src/mod.rs
678                // fn format_message called below
679
680                let text = Text::new(text)
681                    .font_size(self.fonts.universal.scale(15))
682                    .font_id(self.fonts.universal.conrod_id)
683                    .w(chat_size.x - CHAT_ICON_WIDTH - 1.0)
684                    .wrap_by_word()
685                    .color(color)
686                    .line_spacing(2.0);
687
688                // Add space between messages.
689                let y = match text.get_y_dimension(ui) {
690                    Dimension::Absolute(y) => y + 2.0,
691                    _ => 0.0,
692                };
693                item.set(text.h(y), ui);
694
695                // If the user is a moderator display a moderator icon with their alias.
696                if *is_moderator {
697                    let group_width =
698                        group_width(chat_type, ui, &self.fonts.universal).unwrap_or(0.0);
699                    Image::new(self.imgs.chat_moderator_badge)
700                        .w_h(CHAT_ICON_WIDTH, CHAT_ICON_HEIGHT)
701                        .top_left_with_margins_on(item.widget_id, 2.0, 7.0 + group_width)
702                        .parent(state.ids.message_box_bg)
703                        .set(state.ids.chat_badges[badge_id], ui);
704
705                    badge_id += 1;
706                }
707
708                let icon_id = state.ids.chat_icons[item.i];
709                Image::new(icon)
710                    .w_h(CHAT_ICON_WIDTH, CHAT_ICON_HEIGHT)
711                    .top_left_with_margins_on(item.widget_id, 2.0, -CHAT_ICON_WIDTH)
712                    .parent(state.ids.chat_icon_align)
713                    .set(icon_id, ui);
714            } else {
715                // Spacer at bottom of the last message so that it is not cut off.
716                // Needs to be larger than the space above.
717                item.set(
718                    Text::new("")
719                        .font_size(self.fonts.universal.scale(6))
720                        .font_id(self.fonts.universal.conrod_id)
721                        .w(chat_size.x),
722                    ui,
723                );
724            };
725        }
726
727        //Chat tabs
728        if ui
729            .rect_of(state.ids.message_box_bg)
730            .is_some_and(|r| r.is_over(ui.global_input().current.mouse.xy))
731        {
732            state.update(|s| s.tabs_last_hover_pulse = Some(self.pulse));
733        }
734
735        if let Some(time_since_hover) = state
736            .tabs_last_hover_pulse
737            .map(|t| self.pulse - t)
738            .filter(|t| t <= &1.5)
739        {
740            let alpha = 1.0 - (time_since_hover / 1.5).powi(4);
741            let shading = color::rgba(1.0, 0.82, 0.27, chat_settings.chat_opacity * alpha);
742
743            Rectangle::fill([chat_size.x, CHAT_TAB_HEIGHT])
744                .rgba(0.0, 0.0, 0.0, chat_settings.chat_opacity * alpha)
745                .up_from(state.ids.message_box_bg, 0.0)
746                .set(state.ids.chat_tab_align, ui);
747            if ui
748                .rect_of(state.ids.chat_tab_align)
749                .is_some_and(|r| r.is_over(ui.global_input().current.mouse.xy))
750            {
751                state.update(|s| s.tabs_last_hover_pulse = Some(self.pulse));
752            }
753
754            if Button::image(if chat_settings.chat_tab_index.is_none() {
755                self.imgs.selection
756            } else {
757                self.imgs.nothing
758            })
759            .top_left_with_margins_on(state.ids.chat_tab_align, 0.0, 0.0)
760            .w_h(CHAT_TAB_ALL_WIDTH, CHAT_TAB_HEIGHT)
761            .hover_image(self.imgs.selection_hover)
762            .hover_image(self.imgs.selection_press)
763            .image_color(shading)
764            .label(&self.localized_strings.get_msg("hud-chat-all"))
765            .label_font_size(self.fonts.cyri.scale(14))
766            .label_font_id(self.fonts.cyri.conrod_id)
767            .label_color(TEXT_COLOR.alpha(alpha))
768            .set(state.ids.chat_tab_all, ui)
769            .was_clicked()
770            {
771                events.push(Event::ChangeChatTab(None));
772            }
773
774            let chat_tab_width = (chat_size.x - CHAT_TAB_ALL_WIDTH) / (MAX_CHAT_TABS as f64);
775
776            if state.ids.chat_tabs.len() < chat_tabs.len() {
777                state.update(|s| {
778                    s.ids
779                        .chat_tabs
780                        .resize(chat_tabs.len(), &mut ui.widget_id_generator())
781                });
782            }
783            for (i, chat_tab) in chat_tabs.iter().enumerate() {
784                if Button::image(if chat_settings.chat_tab_index == Some(i) {
785                    self.imgs.selection
786                } else {
787                    self.imgs.nothing
788                })
789                .w_h(chat_tab_width, CHAT_TAB_HEIGHT)
790                .hover_image(self.imgs.selection_hover)
791                .press_image(self.imgs.selection_press)
792                .image_color(shading)
793                .label(chat_tab.label.as_str())
794                .label_font_size(self.fonts.cyri.scale(14))
795                .label_font_id(self.fonts.cyri.conrod_id)
796                .label_color(TEXT_COLOR.alpha(alpha))
797                .right_from(
798                    if i == 0 {
799                        state.ids.chat_tab_all
800                    } else {
801                        state.ids.chat_tabs[i - 1]
802                    },
803                    0.0,
804                )
805                .set(state.ids.chat_tabs[i], ui)
806                .was_clicked()
807                {
808                    events.push(Event::ChangeChatTab(Some(i)));
809                }
810
811                if ui
812                    .widget_input(state.ids.chat_tabs[i])
813                    .mouse()
814                    .is_some_and(|m| m.is_over())
815                {
816                    Rectangle::fill([120.0, 20.0])
817                        .rgba(0.0, 0.0, 0.0, 0.9)
818                        .top_left_with_margins_on(state.ids.chat_tabs[i], -20.0, 5.0)
819                        .parent(id)
820                        .set(state.ids.chat_tab_tooltip_bg, ui);
821
822                    Text::new(
823                        &self
824                            .localized_strings
825                            .get_msg("hud-chat-chat_tab_hover_tooltip"),
826                    )
827                    .mid_top_with_margin_on(state.ids.chat_tab_tooltip_bg, 3.0)
828                    .font_size(self.fonts.cyri.scale(10))
829                    .font_id(self.fonts.cyri.conrod_id)
830                    .color(TEXT_COLOR)
831                    .set(state.ids.chat_tab_tooltip_text, ui);
832                }
833
834                if ui
835                    .widget_input(state.ids.chat_tabs[i])
836                    .clicks()
837                    .right()
838                    .next()
839                    .is_some()
840                {
841                    events.push(Event::ShowChatTabSettings(i));
842                }
843            }
844        }
845
846        // Chat Arrow
847        // Check if already at bottom.
848        if !Self::scrolled_to_bottom(state, ui)
849            && Button::image(self.imgs.chat_arrow)
850                .w_h(20.0, 20.0)
851                .hover_image(self.imgs.chat_arrow_mo)
852                .press_image(self.imgs.chat_arrow_press)
853                .top_right_with_margins_on(state.ids.message_box_bg, 0.0, -22.0)
854                .parent(id)
855                .set(state.ids.chat_arrow, ui)
856                .was_clicked()
857        {
858            ui.scroll_widget(state.ids.message_box, [0.0, f64::MAX]);
859        }
860
861        // We've started a new tab completion. Populate tab completion suggestions.
862        if request_tab_completions {
863            events.push(Event::TabCompletionStart(state.input.message.to_string()));
864        // If the chat widget is focused, return a focus event to pass the focus
865        // to the input box.
866        } else if keyboard_capturer == Some(id) {
867            events.push(Event::Focus(state.ids.chat_input));
868        }
869        // If either Return or Enter is pressed and the input box is not empty, send the current
870        // message.
871        else if ui
872            .widget_input(state.ids.chat_input)
873            .presses()
874            .key()
875            .any(|key_press| {
876                let has_message = !state.input.message.is_empty();
877                let pressed = matches!(key_press.key, Key::Return | Key::NumPadEnter);
878                if pressed {
879                    // If chat was hidden, scroll to bottom the next time it is opened
880                    state.update(|s| s.scroll_next |= force_chat);
881                    events.push(Event::DisableForceChat);
882                }
883                has_message && pressed
884            })
885        {
886            let msg = state.input.message.clone();
887            state.update(|s| {
888                s.input.message.clear();
889                // Update the history
890                // Don't add if this is identical to the last message in the history
891                s.history_pos = 0;
892                if s.history.front() != Some(&msg) {
893                    s.history.push_front(msg.clone());
894                    s.history.truncate(self.history_max);
895                }
896            });
897            if let Some(msg) = msg.strip_prefix(chat_settings.chat_cmd_prefix) {
898                match parse_cmd(msg) {
899                    Ok((name, args)) => events.push(Event::SendCommand(name.to_owned(), args)),
900                    // TODO: Localise
901                    Err(err) => self
902                        .new_messages
903                        .push_back(ChatType::CommandError.into_plain_msg(err)),
904                }
905            } else {
906                events.push(Event::SendMessage(msg));
907            }
908        }
909
910        Rectangle::fill_with([chat_size.x, chat_size.y], color::TRANSPARENT)
911            .and(|r| {
912                if input_focused {
913                    r.up_from(state.ids.chat_input_border_up, CHAT_MARGIN_THICKNESS / 2.0)
914                } else {
915                    r.bottom_left_with_margins_on(ui.window, chat_pos.y, chat_pos.x)
916                }
917            })
918            .set(state.ids.draggable_area, ui);
919        events
920    }
921}
922
923fn do_tab_completion(cursor: usize, input: &str, word: &str) -> (String, usize) {
924    let mut pre_ws = None;
925    let mut post_ws = None;
926    let mut in_quotation = false;
927    for (char_i, (byte_i, c)) in input.char_indices().enumerate() {
928        if c == '"' {
929            in_quotation = !in_quotation;
930        } else if !in_quotation && c.is_whitespace() && c != '\t' {
931            if char_i < cursor {
932                pre_ws = Some(byte_i);
933            } else {
934                post_ws = Some(byte_i);
935                break;
936            }
937        }
938    }
939
940    match (pre_ws, post_ws) {
941        (None, None) => (word.to_string(), word.chars().count()),
942        (None, Some(i)) => (
943            format!("{}{}", word, input.split_at(i).1),
944            word.chars().count(),
945        ),
946        (Some(i), None) => {
947            let l_split = input.split_at(i).0;
948            let completed = format!("{} {}", l_split, word);
949            (
950                completed,
951                l_split.chars().count() + 1 + word.chars().count(),
952            )
953        },
954        (Some(i), Some(j)) => {
955            let l_split = input.split_at(i).0;
956            let r_split = input.split_at(j).1;
957            let completed = format!("{} {}{}", l_split, word, r_split);
958            (
959                completed,
960                l_split.chars().count() + 1 + word.chars().count(),
961            )
962        },
963    }
964}
965
966fn cursor_offset_to_index(
967    offset: usize,
968    text: &str,
969    ui: &Ui,
970    fonts: &Fonts,
971    input_width: f64,
972) -> Option<Index> {
973    // This moves the cursor to the given offset. Conrod is a pain.
974    //
975    // Width and font must match that of the chat TextEdit
976    let font = ui.fonts.get(fonts.universal.conrod_id)?;
977    let font_size = fonts.universal.scale(15);
978    let infos = text::line::infos(text, font, font_size).wrap_by_whitespace(input_width);
979
980    cursor::index_before_char(infos, offset)
981}
982
983/// Get the color and icon for a client's ChatMode.
984fn render_chat_mode(chat_mode: &ChatMode, imgs: &Imgs) -> (Color, conrod_core::image::Id) {
985    match chat_mode {
986        ChatMode::World => (WORLD_COLOR, imgs.chat_world_small),
987        ChatMode::Say => (SAY_COLOR, imgs.chat_say_small),
988        ChatMode::Region => (REGION_COLOR, imgs.chat_region_small),
989        ChatMode::Faction(_) => (FACTION_COLOR, imgs.chat_faction_small),
990        ChatMode::Group => (GROUP_COLOR, imgs.chat_group_small),
991        ChatMode::Tell(_) => (TELL_COLOR, imgs.chat_tell_small),
992    }
993}
994
995/// Get the color and icon for the current line in the chat box
996fn render_chat_line(chat_type: &ChatType<String>, imgs: &Imgs) -> (Color, conrod_core::image::Id) {
997    match chat_type {
998        ChatType::Online(_) => (ONLINE_COLOR, imgs.chat_online_small),
999        ChatType::Offline(_) => (OFFLINE_COLOR, imgs.chat_offline_small),
1000        ChatType::CommandError => (ERROR_COLOR, imgs.chat_command_error_small),
1001        ChatType::CommandInfo => (INFO_COLOR, imgs.chat_command_info_small),
1002        ChatType::GroupMeta(_) => (GROUP_COLOR, imgs.chat_group_small),
1003        ChatType::FactionMeta(_) => (FACTION_COLOR, imgs.chat_faction_small),
1004        ChatType::Kill(_, _) => (KILL_COLOR, imgs.chat_kill_small),
1005        ChatType::Tell(_from, _to) => (TELL_COLOR, imgs.chat_tell_small),
1006        ChatType::Say(_uid) => (SAY_COLOR, imgs.chat_say_small),
1007        ChatType::Group(_uid, _s) => (GROUP_COLOR, imgs.chat_group_small),
1008        ChatType::Faction(_uid, _s) => (FACTION_COLOR, imgs.chat_faction_small),
1009        ChatType::Region(_uid) => (REGION_COLOR, imgs.chat_region_small),
1010        ChatType::World(_uid) => (WORLD_COLOR, imgs.chat_world_small),
1011        ChatType::Npc(_uid) => panic!("NPCs can't talk!"), // Should be filtered by hud/mod.rs
1012        ChatType::NpcSay(_uid) => (SAY_COLOR, imgs.chat_say_small),
1013        ChatType::NpcTell(_from, _to) => (TELL_COLOR, imgs.chat_tell_small),
1014        ChatType::Meta => (INFO_COLOR, imgs.chat_command_info_small),
1015    }
1016}
1017
1018fn parse_cmd(msg: &str) -> Result<(&str, Vec<String>), String> {
1019    use chumsky::{extra::Err, prelude::*, text::unicode::ident};
1020
1021    let escape = just::<_, _, Err<Simple<char>>>('\\').ignore_then(
1022        just('\\')
1023            .or(just('/'))
1024            .or(just('"'))
1025            .or(just('b').to('\x08'))
1026            .or(just('f').to('\x0C'))
1027            .or(just('n').to('\n'))
1028            .or(just('r').to('\r'))
1029            .or(just('t').to('\t')),
1030    );
1031
1032    let string = any()
1033        .filter(|c| *c != '\\' && *c != '"')
1034        .or(escape)
1035        .repeated()
1036        .collect::<String>()
1037        .delimited_by(just('"'), just('"'))
1038        .labelled("quoted argument");
1039
1040    let arg = string.or(any()
1041        .filter(|c: &char| !c.is_whitespace() && *c != '"')
1042        .repeated()
1043        .at_least(1)
1044        .collect::<String>()
1045        .labelled("argument"));
1046
1047    let cmd = ident()
1048        .then(arg.padded().repeated().collect::<Vec<String>>())
1049        .then_ignore(end());
1050
1051    cmd.parse(msg).into_result().map_err(|errs| {
1052        errs.into_iter()
1053            .map(|err| err.to_string())
1054            .collect::<Vec<_>>()
1055            .join(", ")
1056    })
1057}
1058
1059/// Change the chat mode if we have a `ServerChatCommand` that corresponds to a
1060/// chat region (i.e. World, Region, Say, etc.).
1061fn change_chat_mode(
1062    message: String,
1063    state: &mut conrod_core::widget::State<State>,
1064    events: &mut Vec<Event>,
1065    chat_settings: &ChatSettings,
1066) {
1067    if let Some(msg) = message.strip_prefix(chat_settings.chat_cmd_prefix) {
1068        // Do nothing on Err because we are just completing the Chat Mode
1069        if let Ok((name, args)) = parse_cmd(msg.trim())
1070            && let Ok(command) = name.parse::<ServerChatCommand>()
1071        {
1072            match command {
1073                ServerChatCommand::Group
1074                | ServerChatCommand::Say
1075                | ServerChatCommand::Faction
1076                | ServerChatCommand::Region
1077                | ServerChatCommand::World => {
1078                    // Only remove the command if there is no message
1079                    if args.is_empty() {
1080                        // We found a match to a command so clear the input
1081                        // message
1082                        state.update(|s| s.input.message.clear());
1083                        events.push(Event::SendCommand(name.to_owned(), args))
1084                    }
1085                },
1086                // TODO: Add support for Whispers (might need to adjust widget
1087                // for this.)
1088                _ => (),
1089            }
1090        }
1091    }
1092}
1093
1094#[cfg(test)]
1095mod tests {
1096    use super::*;
1097
1098    #[test]
1099    fn parse_cmds() {
1100        let expected: Result<(&str, Vec<String>), String> = Ok(("help", vec![]));
1101        assert_eq!(parse_cmd(r"help"), expected);
1102
1103        let expected: Result<(&str, Vec<String>), String> =
1104            Ok(("say", vec!["foo".to_string(), "bar".to_string()]));
1105        assert_eq!(parse_cmd(r"say foo bar"), expected);
1106        assert_eq!(parse_cmd(r#"say "foo" "bar""#), expected);
1107
1108        let expected: Result<(&str, Vec<String>), String> =
1109            Ok(("say", vec!["Hello World".to_string()]));
1110        assert_eq!(parse_cmd(r#"say "Hello World""#), expected);
1111
1112        // Note: \n in the expected gets expanded by rust to a newline character, that's
1113        // why we must not use a raw string in the expected
1114        let expected: Result<(&str, Vec<String>), String> =
1115            Ok(("say", vec!["Hello\nWorld".to_string()]));
1116        assert_eq!(parse_cmd(r#"say "Hello\nWorld""#), expected);
1117    }
1118}