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