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