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