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::chat::MAX_CHAT_TABS,
9 ui::{
10 Scale,
11 fonts::{Font, Fonts},
12 },
13};
14use client::Client;
15use common::comp::{ChatMode, ChatMsg, ChatType, group::Role};
16use conrod_core::{
17 Color, Colorable, Labelable, Positionable, Sizeable, Ui, UiCell, Widget, WidgetCommon, color,
18 input::Key,
19 position::Dimension,
20 text::{
21 self,
22 cursor::{self, Index},
23 },
24 widget::{self, Button, Id, Image, Line, List, Rectangle, Text, TextEdit},
25 widget_ids,
26};
27use i18n::Localization;
28use i18n_helpers::localize_chat_message;
29use std::collections::{HashSet, VecDeque};
30use vek::{Vec2, approx::AbsDiffEq};
31
32pub fn is_muted(client: &Client, profile: &crate::profile::Profile, msg: &ChatMsg) -> bool {
37 if let Some(uid) = msg.uid()
38 && let Some(player_info) = client.player_list().get(&uid)
39 {
40 profile.mutelist.contains_key(&player_info.uuid)
41 } else {
42 false
43 }
44}
45
46pub fn show_in_chatbox(msg: &ChatMsg) -> bool {
50 !matches!(msg.chat_type, ChatType::Npc(_))
52}
53
54pub const MAX_MESSAGES: usize = 100;
55
56#[derive(Default)]
64pub struct MessageBacklog(pub(super) VecDeque<ChatMsg>);
65
66impl MessageBacklog {
67 pub fn new_message(
68 &mut self,
69 client: &Client,
70 profile: &crate::profile::Profile,
71 msg: ChatMsg,
72 ) {
73 if !is_muted(client, profile, &msg) && show_in_chatbox(&msg) {
74 self.0.push_back(msg);
75 if self.0.len() > MAX_MESSAGES {
76 self.0.pop_front();
77 }
78 }
79 }
80}
81
82const CHAT_ICON_WIDTH: f64 = 16.0;
83const CHAT_MARGIN_THICKNESS: f64 = 2.0;
84const CHAT_ICON_HEIGHT: f64 = 16.0;
85const MIN_DIMENSION: Vec2<f64> = Vec2::new(400.0, 150.0);
86const MAX_DIMENSION: Vec2<f64> = Vec2::new(650.0, 500.0);
87
88const CHAT_TAB_HEIGHT: f64 = 20.0;
89const CHAT_TAB_ALL_WIDTH: f64 = 40.0;
90
91widget_ids! {
95 struct Ids {
96 draggable_area,
97 message_box,
98 message_box_bg,
99 chat_input,
100 chat_input_bg,
101 chat_input_icon,
102 chat_input_border_up,
103 chat_input_border_down,
104 chat_input_border_left,
105 chat_input_border_right,
106 chat_arrow,
107 chat_icon_align,
108 chat_icons[],
109 chat_badges[],
110
111 chat_tab_align,
112 chat_tab_all,
113 chat_tab_selected,
114 chat_tabs[],
115 chat_tab_tooltip_bg,
116 chat_tab_tooltip_text,
117 }
118}
119
120#[derive(WidgetCommon)]
121pub struct Chat<'a> {
122 pulse: f32,
123 new_messages: &'a mut VecDeque<ChatMsg>,
124 client: &'a Client,
125 force_input: Option<String>,
126 force_cursor: Option<Index>,
127 force_completions: Option<Vec<String>>,
128
129 global_state: &'a GlobalState,
130 imgs: &'a Imgs,
131 fonts: &'a Fonts,
132
133 #[conrod(common_builder)]
134 common: widget::CommonBuilder,
135
136 history_max: usize,
138 scale: Scale,
139
140 localized_strings: &'a Localization,
141 clear_messages: bool,
142}
143
144impl<'a> Chat<'a> {
145 pub fn new(
146 new_messages: &'a mut VecDeque<ChatMsg>,
147 client: &'a Client,
148 global_state: &'a GlobalState,
149 pulse: f32,
150 imgs: &'a Imgs,
151 fonts: &'a Fonts,
152 localized_strings: &'a Localization,
153 scale: Scale,
154 clear_messages: bool,
155 ) -> Self {
156 Self {
157 pulse,
158 new_messages,
159 client,
160 force_input: None,
161 force_cursor: None,
162 force_completions: None,
163 imgs,
164 fonts,
165 global_state,
166 common: widget::CommonBuilder::default(),
167 history_max: 32,
168 localized_strings,
169 scale,
170 clear_messages,
171 }
172 }
173
174 pub fn prepare_tab_completion(mut self, input: String) -> Self {
175 self.force_completions = if let Some(index) = input.find('\t') {
176 Some(complete(
177 &input[..index],
178 self.client,
179 self.localized_strings,
180 &self.global_state.settings.chat.chat_cmd_prefix.to_string(),
181 ))
182 } else {
183 None
184 };
185 self
186 }
187
188 pub fn input(mut self, input: String) -> Self {
189 self.force_input = Some(input);
190 self
191 }
192
193 pub fn cursor_pos(mut self, index: Index) -> Self {
194 self.force_cursor = Some(index);
195 self
196 }
197
198 pub fn scrolled_to_bottom(state: &State, ui: &UiCell) -> bool {
199 if let Some(scroll) = ui
202 .widget_graph()
203 .widget(state.ids.message_box)
204 .and_then(|widget| widget.maybe_y_scroll_state)
205 {
206 scroll.offset + 50.0 >= scroll.offset_bounds.start
207 } else {
208 false
209 }
210 }
211}
212
213struct InputState {
214 message: String,
215 mode: ChatMode,
216}
217
218pub struct State {
219 messages: VecDeque<ChatMsg>,
220 input: InputState,
221 ids: Ids,
222 history: VecDeque<String>,
223 history_pos: usize,
226 completions: Vec<String>,
227 completions_index: Option<usize>,
229 completion_cursor: Option<usize>,
231 tabs_last_hover_pulse: Option<f32>,
233 prev_chat_tab: Option<ChatTab>,
235 scroll_next: bool,
237}
238
239pub enum Event {
240 TabCompletionStart(String),
241 SendMessage(String),
242 SendCommand(String, Vec<String>),
243 Focus(Id),
244 ChangeChatTab(Option<usize>),
245 ShowChatTabSettings(usize),
246 ResizeChat(Vec2<f64>),
247 MoveChat(Vec2<f64>),
248 DisableForceChat,
249}
250
251impl Widget for Chat<'_> {
252 type Event = Vec<Event>;
253 type State = State;
254 type Style = ();
255
256 fn init_state(&self, id_gen: widget::id::Generator) -> Self::State {
257 State {
258 input: InputState {
259 message: "".to_owned(),
260 mode: ChatMode::default(),
261 },
262 messages: VecDeque::new(),
263 history: VecDeque::new(),
264 history_pos: 0,
265 completions: Vec::new(),
266 completions_index: None,
267 completion_cursor: None,
268 ids: Ids::new(id_gen),
269 tabs_last_hover_pulse: None,
270 prev_chat_tab: None,
271 scroll_next: false,
272 }
273 }
274
275 fn style(&self) -> Self::Style {}
276
277 fn update(self, args: widget::UpdateArgs<Self>) -> Self::Event {
278 fn adjust_border_opacity(color: Color, opacity: f32) -> Color {
279 match color {
280 Color::Rgba(r, g, b, a) => Color::Rgba(r, g, b, (a + opacity) / 2.0),
281 _ => panic!("Color input should be Rgba, instead found: {:?}", color),
282 }
283 }
284 common_base::prof_span!("Chat::update");
285
286 let widget::UpdateArgs { id, state, ui, .. } = args;
287
288 let mut events = Vec::new();
289
290 let chat_settings = &self.global_state.settings.chat;
291 let force_chat = !(&self.global_state.settings.interface.toggle_chat);
292 let chat_tabs = &chat_settings.chat_tabs;
293 let current_chat_tab = chat_settings.chat_tab_index.and_then(|i| chat_tabs.get(i));
294 let chat_size = Vec2::new(chat_settings.chat_size_x, chat_settings.chat_size_y);
295 let chat_pos = Vec2::new(chat_settings.chat_pos_x, chat_settings.chat_pos_y);
296 let chat_box_input_width = chat_size.x - CHAT_ICON_WIDTH - 12.0;
297
298 if self.clear_messages {
299 state.update(|s| s.messages.clear());
300 }
301
302 state.update(|s| {
304 while s.messages.len() > MAX_MESSAGES {
305 s.messages.pop_front();
306 }
307 });
308
309 let chat_in_screen_upper = chat_pos.y > ui.win_h / 2.0;
310
311 let pos_delta: Vec2<f64> = ui
312 .widget_input(state.ids.draggable_area)
313 .drags()
314 .left()
315 .map(|drag| Vec2::<f64>::from(drag.delta_xy))
316 .sum();
317 let new_pos = (chat_pos + pos_delta).map(|e| e.max(0.)).map2(
318 self.scale.scale_point(Vec2::new(ui.win_w, ui.win_h))
319 - Vec2::unit_y() * CHAT_TAB_HEIGHT
320 - chat_size,
321 |e, bounds| e.min(bounds),
322 );
323 if new_pos.abs_diff_ne(&chat_pos, f64::EPSILON) {
324 events.push(Event::MoveChat(new_pos));
325 }
326 let size_delta: Vec2<f64> = ui
327 .widget_input(state.ids.draggable_area)
328 .drags()
329 .right()
330 .map(|drag| Vec2::<f64>::from(drag.delta_xy))
331 .sum();
332 let new_size = (chat_size + size_delta)
333 .map3(
334 self.scale.scale_point(MIN_DIMENSION),
335 self.scale.scale_point(MAX_DIMENSION),
336 |sz, min, max| sz.clamp(min, max),
337 )
338 .map2(
339 self.scale.scale_point(Vec2::new(ui.win_w, ui.win_h))
340 - Vec2::unit_y() * CHAT_TAB_HEIGHT
341 - new_pos,
342 |e, bounds| e.min(bounds),
343 );
344 if new_size.abs_diff_ne(&chat_size, f64::EPSILON) {
345 events.push(Event::ResizeChat(new_size));
346 }
347
348 if !self.new_messages.is_empty() {
350 for message in self.new_messages.iter() {
351 if let ChatType::CommandInfo = &message.chat_type {
354 tracing::info!("Chat command info: {:?}", message.content());
355 }
356 }
357 state.update(|s| s.messages.extend(self.new_messages.drain(..)));
359 if Self::scrolled_to_bottom(state, ui) {
361 ui.scroll_widget(state.ids.message_box, [0.0, f64::MAX]);
362 }
363 }
364
365 if state.scroll_next {
367 ui.scroll_widget(state.ids.message_box, [0.0, f64::MAX]);
368 state.update(|s| s.scroll_next = false);
369 }
370
371 if current_chat_tab != state.prev_chat_tab.as_ref() {
373 state.update(|s| s.prev_chat_tab = current_chat_tab.cloned());
374 state.update(|s| s.scroll_next = true); }
376
377 if let Some(comps) = &self.force_completions {
378 state.update(|s| s.completions.clone_from(comps));
379 }
380
381 let mut force_cursor = self.force_cursor;
382
383 let (history_dir, tab_dir, stop_tab_completion) =
386 ui.widget_input(state.ids.chat_input).presses().key().fold(
387 (0isize, 0isize, false),
388 |(n, m, tc), key_press| match key_press.key {
389 Key::Up => (n + 1, m - 1, tc),
390 Key::Down => (n - 1, m + 1, tc),
391 Key::Tab => (n, m + 1, tc),
392 _ => (n, m, true),
393 },
394 );
395
396 let request_tab_completions = if stop_tab_completion {
398 state.update(|s| {
400 if s.completion_cursor.is_some() {
401 s.completion_cursor = None;
402 }
403 s.completions_index = None;
404 });
405 false
406 } else if let Some(cursor) = state.completion_cursor {
407 if state.input.message.contains('\t') {
409 state.update(|s| s.input.message.retain(|c| c != '\t'));
410 }
412 if !state.completions.is_empty() && (tab_dir != 0 || state.completions_index.is_none())
413 {
414 state.update(|s| {
415 let len = s.completions.len();
416 s.completions_index = Some(
417 (s.completions_index.unwrap_or(0) + (tab_dir + len as isize) as usize)
418 % len,
419 );
420 if let Some(replacement) = &s.completions.get(s.completions_index.unwrap()) {
421 let (completed, offset) =
422 do_tab_completion(cursor, &s.input.message, replacement);
423 force_cursor = cursor_offset_to_index(
424 offset,
425 &completed,
426 ui,
427 self.fonts,
428 chat_box_input_width,
429 );
430 s.input.message = completed;
431 }
432 });
433 }
434 false
435 } else if let Some(cursor) = state.input.message.find('\t') {
436 state.update(|s| s.completion_cursor = Some(cursor));
438 true
439 } else {
440 false
442 };
443
444 if history_dir != 0 && state.completion_cursor.is_none() {
446 state.update(|s| {
447 if history_dir > 0 {
448 if s.history_pos < s.history.len() {
449 s.history_pos += 1;
450 }
451 } else if s.history_pos > 0 {
452 s.history_pos -= 1;
453 }
454 if let Some(before) = s.history.iter().nth_back(s.history.len() - s.history_pos) {
455 s.input.message.clone_from(before);
456 force_cursor = cursor_offset_to_index(
457 s.input.message.len(),
458 &s.input.message,
459 ui,
460 self.fonts,
461 chat_box_input_width,
462 );
463 } else {
464 s.input.message.clear();
465 }
466 });
467 }
468
469 let keyboard_capturer = ui.global_input().current.widget_capturing_keyboard;
470
471 if let Some(input) = &self.force_input {
472 state.update(|s| s.input.message = input.to_string());
473 }
474
475 let input_focused =
476 keyboard_capturer == Some(state.ids.chat_input) || keyboard_capturer == Some(id);
477
478 if input_focused {
481 let discrim = std::mem::discriminant;
483 if discrim(&state.input.mode) != discrim(&self.client.chat_mode) {
484 state.update(|s| {
485 s.input.mode = self.client.chat_mode.clone();
486 });
487 }
488
489 let (color, icon) = render_chat_mode(&state.input.mode, self.imgs);
490 Image::new(icon)
491 .w_h(CHAT_ICON_WIDTH, CHAT_ICON_HEIGHT)
492 .top_left_with_margin_on(state.ids.chat_input_bg, 2.0)
493 .set(state.ids.chat_input_icon, ui);
494
495 let mut text_edit = TextEdit::new(&state.input.message)
498 .w(chat_box_input_width)
499 .restrict_to_height(false)
500 .color(color)
501 .line_spacing(2.0)
502 .font_size(self.fonts.opensans.scale(15))
503 .font_id(self.fonts.opensans.conrod_id);
504
505 if let Some(pos) = force_cursor {
506 text_edit = text_edit.cursor_pos(pos);
507 }
508
509 let y = match text_edit.get_y_dimension(ui) {
510 Dimension::Absolute(y) => y + 6.0,
511 _ => 0.0,
512 };
513 Rectangle::fill([chat_size.x, y])
514 .rgba(0.0, 0.0, 0.0, chat_settings.chat_opacity)
515 .w(chat_size.x)
516 .and(|r| {
517 if chat_in_screen_upper {
518 r.down_from(state.ids.message_box_bg, CHAT_MARGIN_THICKNESS / 2.0)
519 } else {
520 r.bottom_left_with_margins_on(ui.window, chat_pos.y, chat_pos.x)
521 }
522 })
523 .set(state.ids.chat_input_bg, ui);
524
525 let border_color = adjust_border_opacity(color, chat_settings.chat_opacity);
527 Line::centred([0.0, 0.0], [chat_size.x, 0.0])
529 .color(border_color)
530 .thickness(CHAT_MARGIN_THICKNESS)
531 .top_left_of(state.ids.chat_input_bg)
532 .set(state.ids.chat_input_border_up, ui);
533 Line::centred([0.0, 0.0], [chat_size.x, 0.0])
535 .color(border_color)
536 .thickness(CHAT_MARGIN_THICKNESS)
537 .bottom_left_of(state.ids.chat_input_bg)
538 .set(state.ids.chat_input_border_down, ui);
539 Line::centred([0.0, 0.0], [0.0, y])
541 .color(border_color)
542 .thickness(CHAT_MARGIN_THICKNESS)
543 .bottom_left_of(state.ids.chat_input_bg)
544 .set(state.ids.chat_input_border_left, ui);
545 Line::centred([0.0, 0.0], [0.0, y])
547 .color(border_color)
548 .thickness(CHAT_MARGIN_THICKNESS)
549 .bottom_right_of(state.ids.chat_input_bg)
550 .set(state.ids.chat_input_border_right, ui);
551
552 if let Some(mut input) = text_edit
553 .right_from(state.ids.chat_input_icon, 1.0)
554 .set(state.ids.chat_input, ui)
555 {
556 input.retain(|c| c != '\n');
557 state.update(|s| s.input.message = input);
558 }
559 }
560
561 Rectangle::fill([chat_size.x, chat_size.y])
563 .rgba(0.0, 0.0, 0.0, chat_settings.chat_opacity)
564 .and(|r| {
565 if input_focused && !chat_in_screen_upper {
566 r.up_from(
567 state.ids.chat_input_border_up,
568 0.0 + CHAT_MARGIN_THICKNESS / 2.0,
569 )
570 } else {
571 r.bottom_left_with_margins_on(ui.window, chat_pos.y, chat_pos.x)
572 }
573 })
574 .crop_kids()
575 .set(state.ids.message_box_bg, ui);
576 if state.ids.chat_icons.len() < state.messages.len() {
577 state.update(|s| {
578 s.ids
579 .chat_icons
580 .resize(s.messages.len(), &mut ui.widget_id_generator())
581 });
582 }
583 let group_members = self
584 .client
585 .group_members()
586 .iter()
587 .filter_map(|(u, r)| match r {
588 Role::Member => Some(u),
589 Role::Pet => None,
590 })
591 .collect::<HashSet<_>>();
592 let show_char_name = chat_settings.chat_character_name;
593 let messages = &state
594 .messages
595 .iter()
596 .filter(|m| {
597 if let Some(chat_tab) = current_chat_tab {
598 chat_tab.filter.satisfies(m, &group_members)
599 } else {
600 true
601 }
602 })
603 .map(|m| {
604 let is_moderator = m
605 .uid()
606 .and_then(|uid| self.client.player_list().get(&uid).map(|i| i.is_moderator))
607 .unwrap_or(false);
608 let (chat_type, text) = localize_chat_message(
609 m,
610 &self.client.lookup_msg_context(m),
611 self.localized_strings,
612 show_char_name,
613 );
614 (is_moderator, chat_type, text)
615 })
616 .collect::<Vec<_>>();
617 let n_badges = messages.iter().filter(|t| t.0).count();
618 if state.ids.chat_badges.len() < n_badges {
619 state.update(|s| {
620 s.ids
621 .chat_badges
622 .resize(n_badges, &mut ui.widget_id_generator())
623 })
624 }
625 Rectangle::fill_with([CHAT_ICON_WIDTH, chat_size.y], color::TRANSPARENT)
626 .top_left_with_margins_on(state.ids.message_box_bg, 0.0, 0.0)
627 .crop_kids()
628 .set(state.ids.chat_icon_align, ui);
629 let (mut items, _) = List::flow_down(messages.len() + 1)
630 .top_left_with_margins_on(state.ids.message_box_bg, 0.0, CHAT_ICON_WIDTH)
631 .w_h(chat_size.x - CHAT_ICON_WIDTH, chat_size.y)
632 .scroll_kids_vertically()
633 .set(state.ids.message_box, ui);
634
635 let mut badge_id = 0;
636 while let Some(item) = items.next(ui) {
637 fn group_width(chat_type: &ChatType<String>, ui: &Ui, font: &Font) -> Option<f64> {
639 let text = match chat_type {
642 ChatType::Group(_, desc) => desc.as_str(),
643 ChatType::Faction(_, desc) => desc.as_str(),
644 _ => return None,
645 };
646 let bracket_width = Text::new("() ")
647 .font_size(font.scale(15))
648 .font_id(font.conrod_id)
649 .get_w(ui)?;
650 Text::new(text)
651 .font_size(font.scale(15))
652 .font_id(font.conrod_id)
653 .get_w(ui)
654 .map(|v| bracket_width + v)
655 }
656 if item.i < messages.len() {
658 let (is_moderator, chat_type, text) = &messages[item.i];
659 let (color, icon) = render_chat_line(chat_type, self.imgs);
660 let text = Text::new(text)
666 .font_size(self.fonts.opensans.scale(15))
667 .font_id(self.fonts.opensans.conrod_id)
668 .w(chat_size.x - CHAT_ICON_WIDTH - 1.0)
669 .wrap_by_word()
670 .color(color)
671 .line_spacing(2.0);
672
673 let y = match text.get_y_dimension(ui) {
675 Dimension::Absolute(y) => y + 2.0,
676 _ => 0.0,
677 };
678 item.set(text.h(y), ui);
679
680 if *is_moderator {
682 let group_width =
683 group_width(chat_type, ui, &self.fonts.opensans).unwrap_or(0.0);
684 Image::new(self.imgs.chat_moderator_badge)
685 .w_h(CHAT_ICON_WIDTH, CHAT_ICON_HEIGHT)
686 .top_left_with_margins_on(item.widget_id, 2.0, 7.0 + group_width)
687 .parent(state.ids.message_box_bg)
688 .set(state.ids.chat_badges[badge_id], ui);
689
690 badge_id += 1;
691 }
692
693 let icon_id = state.ids.chat_icons[item.i];
694 Image::new(icon)
695 .w_h(CHAT_ICON_WIDTH, CHAT_ICON_HEIGHT)
696 .top_left_with_margins_on(item.widget_id, 2.0, -CHAT_ICON_WIDTH)
697 .parent(state.ids.chat_icon_align)
698 .set(icon_id, ui);
699 } else {
700 item.set(
703 Text::new("")
704 .font_size(self.fonts.opensans.scale(6))
705 .font_id(self.fonts.opensans.conrod_id)
706 .w(chat_size.x),
707 ui,
708 );
709 };
710 }
711
712 if ui
714 .rect_of(state.ids.message_box_bg)
715 .is_some_and(|r| r.is_over(ui.global_input().current.mouse.xy))
716 {
717 state.update(|s| s.tabs_last_hover_pulse = Some(self.pulse));
718 }
719
720 if let Some(time_since_hover) = state
721 .tabs_last_hover_pulse
722 .map(|t| self.pulse - t)
723 .filter(|t| t <= &1.5)
724 {
725 let alpha = 1.0 - (time_since_hover / 1.5).powi(4);
726 let shading = color::rgba(1.0, 0.82, 0.27, chat_settings.chat_opacity * alpha);
727
728 Rectangle::fill([chat_size.x, CHAT_TAB_HEIGHT])
729 .rgba(0.0, 0.0, 0.0, chat_settings.chat_opacity * alpha)
730 .up_from(state.ids.message_box_bg, 0.0)
731 .set(state.ids.chat_tab_align, ui);
732 if ui
733 .rect_of(state.ids.chat_tab_align)
734 .is_some_and(|r| r.is_over(ui.global_input().current.mouse.xy))
735 {
736 state.update(|s| s.tabs_last_hover_pulse = Some(self.pulse));
737 }
738
739 if Button::image(if chat_settings.chat_tab_index.is_none() {
740 self.imgs.selection
741 } else {
742 self.imgs.nothing
743 })
744 .top_left_with_margins_on(state.ids.chat_tab_align, 0.0, 0.0)
745 .w_h(CHAT_TAB_ALL_WIDTH, CHAT_TAB_HEIGHT)
746 .hover_image(self.imgs.selection_hover)
747 .hover_image(self.imgs.selection_press)
748 .image_color(shading)
749 .label(&self.localized_strings.get_msg("hud-chat-all"))
750 .label_font_size(self.fonts.cyri.scale(14))
751 .label_font_id(self.fonts.cyri.conrod_id)
752 .label_color(TEXT_COLOR.alpha(alpha))
753 .set(state.ids.chat_tab_all, ui)
754 .was_clicked()
755 {
756 events.push(Event::ChangeChatTab(None));
757 }
758
759 let chat_tab_width = (chat_size.x - CHAT_TAB_ALL_WIDTH) / (MAX_CHAT_TABS as f64);
760
761 if state.ids.chat_tabs.len() < chat_tabs.len() {
762 state.update(|s| {
763 s.ids
764 .chat_tabs
765 .resize(chat_tabs.len(), &mut ui.widget_id_generator())
766 });
767 }
768 for (i, chat_tab) in chat_tabs.iter().enumerate() {
769 if Button::image(if chat_settings.chat_tab_index == Some(i) {
770 self.imgs.selection
771 } else {
772 self.imgs.nothing
773 })
774 .w_h(chat_tab_width, CHAT_TAB_HEIGHT)
775 .hover_image(self.imgs.selection_hover)
776 .press_image(self.imgs.selection_press)
777 .image_color(shading)
778 .label(chat_tab.label.as_str())
779 .label_font_size(self.fonts.cyri.scale(14))
780 .label_font_id(self.fonts.cyri.conrod_id)
781 .label_color(TEXT_COLOR.alpha(alpha))
782 .right_from(
783 if i == 0 {
784 state.ids.chat_tab_all
785 } else {
786 state.ids.chat_tabs[i - 1]
787 },
788 0.0,
789 )
790 .set(state.ids.chat_tabs[i], ui)
791 .was_clicked()
792 {
793 events.push(Event::ChangeChatTab(Some(i)));
794 }
795
796 if ui
797 .widget_input(state.ids.chat_tabs[i])
798 .mouse()
799 .is_some_and(|m| m.is_over())
800 {
801 Rectangle::fill([120.0, 20.0])
802 .rgba(0.0, 0.0, 0.0, 0.9)
803 .top_left_with_margins_on(state.ids.chat_tabs[i], -20.0, 5.0)
804 .parent(id)
805 .set(state.ids.chat_tab_tooltip_bg, ui);
806
807 Text::new(
808 &self
809 .localized_strings
810 .get_msg("hud-chat-chat_tab_hover_tooltip"),
811 )
812 .mid_top_with_margin_on(state.ids.chat_tab_tooltip_bg, 3.0)
813 .font_size(self.fonts.cyri.scale(10))
814 .font_id(self.fonts.cyri.conrod_id)
815 .color(TEXT_COLOR)
816 .set(state.ids.chat_tab_tooltip_text, ui);
817 }
818
819 if ui
820 .widget_input(state.ids.chat_tabs[i])
821 .clicks()
822 .right()
823 .next()
824 .is_some()
825 {
826 events.push(Event::ShowChatTabSettings(i));
827 }
828 }
829 }
830
831 if !Self::scrolled_to_bottom(state, ui)
834 && Button::image(self.imgs.chat_arrow)
835 .w_h(20.0, 20.0)
836 .hover_image(self.imgs.chat_arrow_mo)
837 .press_image(self.imgs.chat_arrow_press)
838 .top_right_with_margins_on(state.ids.message_box_bg, 0.0, -22.0)
839 .parent(id)
840 .set(state.ids.chat_arrow, ui)
841 .was_clicked()
842 {
843 ui.scroll_widget(state.ids.message_box, [0.0, f64::MAX]);
844 }
845
846 if request_tab_completions {
848 events.push(Event::TabCompletionStart(state.input.message.to_string()));
849 } else if keyboard_capturer == Some(id) {
852 events.push(Event::Focus(state.ids.chat_input));
853 }
854 else if ui
857 .widget_input(state.ids.chat_input)
858 .presses()
859 .key()
860 .any(|key_press| {
861 let has_message = !state.input.message.is_empty();
862 let pressed = matches!(key_press.key, Key::Return | Key::NumPadEnter);
863 if pressed {
864 state.update(|s| s.scroll_next |= force_chat);
866 events.push(Event::DisableForceChat);
867 }
868 has_message && pressed
869 })
870 {
871 let msg = state.input.message.clone();
872 state.update(|s| {
873 s.input.message.clear();
874 s.history_pos = 0;
877 if s.history.front() != Some(&msg) {
878 s.history.push_front(msg.clone());
879 s.history.truncate(self.history_max);
880 }
881 });
882 if let Some(msg) = msg.strip_prefix(chat_settings.chat_cmd_prefix) {
883 match parse_cmd(msg) {
884 Ok((name, args)) => events.push(Event::SendCommand(name, args)),
885 Err(err) => self
887 .new_messages
888 .push_back(ChatType::CommandError.into_plain_msg(err)),
889 }
890 } else {
891 events.push(Event::SendMessage(msg));
892 }
893 }
894
895 Rectangle::fill_with([chat_size.x, chat_size.y], color::TRANSPARENT)
896 .and(|r| {
897 if input_focused {
898 r.up_from(state.ids.chat_input_border_up, CHAT_MARGIN_THICKNESS / 2.0)
899 } else {
900 r.bottom_left_with_margins_on(ui.window, chat_pos.y, chat_pos.x)
901 }
902 })
903 .set(state.ids.draggable_area, ui);
904 events
905 }
906}
907
908fn do_tab_completion(cursor: usize, input: &str, word: &str) -> (String, usize) {
909 let mut pre_ws = None;
910 let mut post_ws = None;
911 let mut in_quotation = false;
912 for (char_i, (byte_i, c)) in input.char_indices().enumerate() {
913 if c == '"' {
914 in_quotation = !in_quotation;
915 } else if !in_quotation && c.is_whitespace() && c != '\t' {
916 if char_i < cursor {
917 pre_ws = Some(byte_i);
918 } else {
919 post_ws = Some(byte_i);
920 break;
921 }
922 }
923 }
924
925 match (pre_ws, post_ws) {
926 (None, None) => (word.to_string(), word.chars().count()),
927 (None, Some(i)) => (
928 format!("{}{}", word, input.split_at(i).1),
929 word.chars().count(),
930 ),
931 (Some(i), None) => {
932 let l_split = input.split_at(i).0;
933 let completed = format!("{} {}", l_split, word);
934 (
935 completed,
936 l_split.chars().count() + 1 + word.chars().count(),
937 )
938 },
939 (Some(i), Some(j)) => {
940 let l_split = input.split_at(i).0;
941 let r_split = input.split_at(j).1;
942 let completed = format!("{} {}{}", l_split, word, r_split);
943 (
944 completed,
945 l_split.chars().count() + 1 + word.chars().count(),
946 )
947 },
948 }
949}
950
951fn cursor_offset_to_index(
952 offset: usize,
953 text: &str,
954 ui: &Ui,
955 fonts: &Fonts,
956 input_width: f64,
957) -> Option<Index> {
958 let font = ui.fonts.get(fonts.opensans.conrod_id)?;
962 let font_size = fonts.opensans.scale(15);
963 let infos = text::line::infos(text, font, font_size).wrap_by_whitespace(input_width);
964
965 cursor::index_before_char(infos, offset)
966}
967
968fn render_chat_mode(chat_mode: &ChatMode, imgs: &Imgs) -> (Color, conrod_core::image::Id) {
970 match chat_mode {
971 ChatMode::World => (WORLD_COLOR, imgs.chat_world_small),
972 ChatMode::Say => (SAY_COLOR, imgs.chat_say_small),
973 ChatMode::Region => (REGION_COLOR, imgs.chat_region_small),
974 ChatMode::Faction(_) => (FACTION_COLOR, imgs.chat_faction_small),
975 ChatMode::Group => (GROUP_COLOR, imgs.chat_group_small),
976 ChatMode::Tell(_) => (TELL_COLOR, imgs.chat_tell_small),
977 }
978}
979
980fn render_chat_line(chat_type: &ChatType<String>, imgs: &Imgs) -> (Color, conrod_core::image::Id) {
982 match chat_type {
983 ChatType::Online(_) => (ONLINE_COLOR, imgs.chat_online_small),
984 ChatType::Offline(_) => (OFFLINE_COLOR, imgs.chat_offline_small),
985 ChatType::CommandError => (ERROR_COLOR, imgs.chat_command_error_small),
986 ChatType::CommandInfo => (INFO_COLOR, imgs.chat_command_info_small),
987 ChatType::GroupMeta(_) => (GROUP_COLOR, imgs.chat_group_small),
988 ChatType::FactionMeta(_) => (FACTION_COLOR, imgs.chat_faction_small),
989 ChatType::Kill(_, _) => (KILL_COLOR, imgs.chat_kill_small),
990 ChatType::Tell(_from, _to) => (TELL_COLOR, imgs.chat_tell_small),
991 ChatType::Say(_uid) => (SAY_COLOR, imgs.chat_say_small),
992 ChatType::Group(_uid, _s) => (GROUP_COLOR, imgs.chat_group_small),
993 ChatType::Faction(_uid, _s) => (FACTION_COLOR, imgs.chat_faction_small),
994 ChatType::Region(_uid) => (REGION_COLOR, imgs.chat_region_small),
995 ChatType::World(_uid) => (WORLD_COLOR, imgs.chat_world_small),
996 ChatType::Npc(_uid) => panic!("NPCs can't talk!"), ChatType::NpcSay(_uid) => (SAY_COLOR, imgs.chat_say_small),
998 ChatType::NpcTell(_from, _to) => (TELL_COLOR, imgs.chat_tell_small),
999 ChatType::Meta => (INFO_COLOR, imgs.chat_command_info_small),
1000 }
1001}
1002
1003fn parse_cmd(msg: &str) -> Result<(String, Vec<String>), String> {
1004 use chumsky::prelude::*;
1005
1006 let escape = just::<_, _, Simple<char>>('\\').ignore_then(
1007 just('\\')
1008 .or(just('/'))
1009 .or(just('"'))
1010 .or(just('b').to('\x08'))
1011 .or(just('f').to('\x0C'))
1012 .or(just('n').to('\n'))
1013 .or(just('r').to('\r'))
1014 .or(just('t').to('\t')),
1015 );
1016
1017 let string = just('"')
1018 .ignore_then(filter(|c| *c != '\\' && *c != '"').or(escape).repeated())
1019 .then_ignore(just('"'))
1020 .labelled("quoted argument");
1021
1022 let arg = string
1023 .or(filter(|c: &char| !c.is_whitespace() && *c != '"')
1024 .repeated()
1025 .at_least(1)
1026 .labelled("argument"))
1027 .collect::<String>();
1028
1029 let cmd = text::ident()
1030 .then(arg.padded().repeated())
1031 .then_ignore(end());
1032
1033 cmd.parse(msg).map_err(|errs| {
1034 errs.into_iter()
1035 .map(|err| err.to_string())
1036 .collect::<Vec<_>>()
1037 .join(", ")
1038 })
1039}
1040
1041#[cfg(test)]
1042mod tests {
1043 use super::*;
1044
1045 #[test]
1046 fn parse_cmds() {
1047 let expected: Result<(String, Vec<String>), String> = Ok(("help".to_string(), vec![]));
1048 assert_eq!(parse_cmd(r"help"), expected);
1049
1050 let expected: Result<(String, Vec<String>), String> = Ok(("say".to_string(), vec![
1051 "foo".to_string(),
1052 "bar".to_string(),
1053 ]));
1054 assert_eq!(parse_cmd(r"say foo bar"), expected);
1055 assert_eq!(parse_cmd(r#"say "foo" "bar""#), expected);
1056
1057 let expected: Result<(String, Vec<String>), String> =
1058 Ok(("say".to_string(), vec!["Hello World".to_string()]));
1059 assert_eq!(parse_cmd(r#"say "Hello World""#), expected);
1060
1061 let expected: Result<(String, Vec<String>), String> =
1064 Ok(("say".to_string(), vec!["Hello\nWorld".to_string()]));
1065 assert_eq!(parse_cmd(r#"say "Hello\nWorld""#), expected);
1066 }
1067}