3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28 #include "util/strfnd.h"
29 #include "util/string.h"
30 #include "util/numeric.h"
32 ChatBuffer::ChatBuffer(u32 scrollback):
33 m_scrollback(scrollback)
35 if (m_scrollback == 0)
37 m_empty_formatted_line.first = true;
39 m_cache_clickable_chat_weblinks = false;
40 // Curses mode cannot access g_settings here
41 if (g_settings != nullptr) {
42 m_cache_clickable_chat_weblinks = g_settings->getBool("clickable_chat_weblinks");
43 if (m_cache_clickable_chat_weblinks) {
44 std::string colorval = g_settings->get("chat_weblink_color");
45 parseColorString(colorval, m_cache_chat_weblink_color, false, 255);
46 m_cache_chat_weblink_color.setAlpha(255);
51 void ChatBuffer::addLine(const std::wstring &name, const std::wstring &text)
53 m_lines_modified = true;
55 ChatLine line(name, text);
56 m_unformatted.push_back(line);
59 // m_formatted is valid and must be kept valid
60 bool scrolled_at_bottom = (m_scroll == getBottomScrollPos());
61 u32 num_added = formatChatLine(line, m_cols, m_formatted);
62 if (scrolled_at_bottom)
63 m_scroll += num_added;
66 // Limit number of lines by m_scrollback
67 if (m_unformatted.size() > m_scrollback) {
68 deleteOldest(m_unformatted.size() - m_scrollback);
72 void ChatBuffer::clear()
74 m_unformatted.clear();
77 m_lines_modified = true;
80 u32 ChatBuffer::getLineCount() const
82 return m_unformatted.size();
85 const ChatLine& ChatBuffer::getLine(u32 index) const
87 assert(index < getLineCount()); // pre-condition
88 return m_unformatted[index];
91 void ChatBuffer::step(f32 dtime)
93 for (ChatLine &line : m_unformatted) {
98 void ChatBuffer::deleteOldest(u32 count)
100 bool at_bottom = (m_scroll == getBottomScrollPos());
102 u32 del_unformatted = 0;
103 u32 del_formatted = 0;
105 while (count > 0 && del_unformatted < m_unformatted.size()) {
108 // keep m_formatted in sync
109 if (del_formatted < m_formatted.size()) {
110 sanity_check(m_formatted[del_formatted].first);
112 while (del_formatted < m_formatted.size() &&
113 !m_formatted[del_formatted].first)
120 m_unformatted.erase(m_unformatted.begin(), m_unformatted.begin() + del_unformatted);
121 m_formatted.erase(m_formatted.begin(), m_formatted.begin() + del_formatted);
123 if (del_unformatted > 0)
124 m_lines_modified = true;
127 m_scroll = getBottomScrollPos();
129 scrollAbsolute(m_scroll - del_formatted);
132 void ChatBuffer::deleteByAge(f32 maxAge)
135 while (count < m_unformatted.size() && m_unformatted[count].age > maxAge)
140 u32 ChatBuffer::getRows() const
145 void ChatBuffer::reformat(u32 cols, u32 rows)
147 if (cols == 0 || rows == 0)
149 // Clear formatted buffer
155 else if (cols != m_cols || rows != m_rows)
157 // TODO: Avoid reformatting ALL lines (even invisible ones)
158 // each time the console size changes.
160 // Find out the scroll position in *unformatted* lines
161 u32 restore_scroll_unformatted = 0;
162 u32 restore_scroll_formatted = 0;
163 bool at_bottom = (m_scroll == getBottomScrollPos());
166 for (s32 i = 0; i < m_scroll; ++i)
168 if (m_formatted[i].first)
169 ++restore_scroll_unformatted;
173 // If number of columns change, reformat everything
177 for (u32 i = 0; i < m_unformatted.size(); ++i)
179 if (i == restore_scroll_unformatted)
180 restore_scroll_formatted = m_formatted.size();
181 formatChatLine(m_unformatted[i], cols, m_formatted);
185 // Update the console size
189 // Restore the scroll position
196 scrollAbsolute(restore_scroll_formatted);
201 const ChatFormattedLine& ChatBuffer::getFormattedLine(u32 row) const
203 s32 index = m_scroll + (s32) row;
204 if (index >= 0 && index < (s32) m_formatted.size())
205 return m_formatted[index];
207 return m_empty_formatted_line;
210 void ChatBuffer::scroll(s32 rows)
212 scrollAbsolute(m_scroll + rows);
215 void ChatBuffer::scrollAbsolute(s32 scroll)
217 s32 top = getTopScrollPos();
218 s32 bottom = getBottomScrollPos();
223 if (m_scroll > bottom)
227 void ChatBuffer::scrollBottom()
229 m_scroll = getBottomScrollPos();
232 u32 ChatBuffer::formatChatLine(const ChatLine& line, u32 cols,
233 std::vector<ChatFormattedLine>& destination) const
236 std::vector<ChatFormattedFragment> next_frags;
237 ChatFormattedLine next_line;
238 ChatFormattedFragment temp_frag;
241 u32 hanging_indentation = 0;
243 // Format the sender name and produce fragments
244 if (!line.name.empty()) {
245 temp_frag.text = L"<";
246 temp_frag.column = 0;
247 //temp_frag.bold = 0;
248 next_frags.push_back(temp_frag);
249 temp_frag.text = line.name;
250 temp_frag.column = 0;
251 //temp_frag.bold = 1;
252 next_frags.push_back(temp_frag);
253 temp_frag.text = L"> ";
254 temp_frag.column = 0;
255 //temp_frag.bold = 0;
256 next_frags.push_back(temp_frag);
259 std::wstring name_sanitized = line.name.c_str();
261 // Choose an indentation level
262 if (line.name.empty()) {
264 hanging_indentation = 0;
265 } else if (name_sanitized.size() + 3 <= cols/2) {
266 // Names shorter than about half the console width
267 hanging_indentation = line.name.size() + 3;
270 hanging_indentation = 2;
272 //EnrichedString line_text(line.text);
274 next_line.first = true;
275 // Set/use forced newline after the last frag in each line
276 bool mark_newline = false;
278 // Produce fragments and layout them into lines
279 while (!next_frags.empty() || in_pos < line.text.size()) {
280 mark_newline = false; // now using this to USE line-end frag
282 // Layout fragments into lines
283 while (!next_frags.empty()) {
284 ChatFormattedFragment& frag = next_frags[0];
286 // Force newline after this frag, if marked
287 if (frag.column == INT_MAX)
290 if (frag.text.size() <= cols - out_column) {
291 // Fragment fits into current line
292 frag.column = out_column;
293 next_line.fragments.push_back(frag);
294 out_column += frag.text.size();
295 next_frags.erase(next_frags.begin());
297 // Fragment does not fit into current line
299 temp_frag.text = frag.text.substr(0, cols - out_column);
300 temp_frag.column = out_column;
301 temp_frag.weblink = frag.weblink;
303 next_line.fragments.push_back(temp_frag);
304 frag.text = frag.text.substr(cols - out_column);
309 if (out_column == cols || mark_newline) {
310 // End the current line
311 destination.push_back(next_line);
313 next_line.fragments.clear();
314 next_line.first = false;
316 out_column = hanging_indentation;
317 mark_newline = false;
321 // Produce fragment(s) for next formatted line
322 if (!(in_pos < line.text.size()))
325 const std::wstring &linestring = line.text.getString();
326 u32 remaining_in_output = cols - out_column;
327 size_t http_pos = std::wstring::npos;
328 mark_newline = false; // now using this to SET line-end frag
330 // Construct all frags for next output line
331 while (!mark_newline) {
332 // Determine a fragment length <= the minimum of
333 // remaining_in_{in,out}put. Try to end the fragment
334 // on a word boundary.
335 u32 frag_length = 0, space_pos = 0;
336 u32 remaining_in_input = line.text.size() - in_pos;
338 if (m_cache_clickable_chat_weblinks) {
339 // Note: unsigned(-1) on fail
340 http_pos = linestring.find(L"https://", in_pos);
341 if (http_pos == std::wstring::npos)
342 http_pos = linestring.find(L"http://", in_pos);
343 if (http_pos != std::wstring::npos)
347 while (frag_length < remaining_in_input &&
348 frag_length < remaining_in_output) {
349 if (iswspace(linestring[in_pos + frag_length]))
350 space_pos = frag_length;
354 if (http_pos >= remaining_in_output) {
355 // Http not in range, grab until space or EOL, halt as normal.
356 // Note this works because (http_pos = npos) is unsigned(-1)
359 } else if (http_pos == 0) {
360 // At http, grab ALL until FIRST whitespace or end marker. loop.
361 // If at end of string, next loop will be empty string to mark end of weblink.
363 frag_length = 6; // Frag is at least "http://"
365 // Chars to mark end of weblink
366 // TODO? replace this with a safer (slower) regex whitelist?
367 static const std::wstring delim_chars = L"\'\";";
368 wchar_t tempchar = linestring[in_pos+frag_length];
369 while (frag_length < remaining_in_input &&
370 !iswspace(tempchar) &&
371 delim_chars.find(tempchar) == std::wstring::npos) {
373 tempchar = linestring[in_pos+frag_length];
376 space_pos = frag_length - 1;
377 // This frag may need to be force-split. That's ok, urls aren't "words"
378 if (frag_length >= remaining_in_output) {
382 // Http in range, grab until http, loop
384 space_pos = http_pos - 1;
385 frag_length = http_pos;
388 // Include trailing space in current frag
389 if (space_pos != 0 && frag_length < remaining_in_input)
390 frag_length = space_pos + 1;
392 temp_frag.text = line.text.substr(in_pos, frag_length);
393 // A hack so this frag remembers mark_newline for the layout phase
394 temp_frag.column = mark_newline ? INT_MAX : 0;
397 // Discard color stuff from the source frag
398 temp_frag.text = EnrichedString(temp_frag.text.getString());
399 temp_frag.text.setDefaultColor(m_cache_chat_weblink_color);
400 // Set weblink in the frag meta
401 temp_frag.weblink = wide_to_utf8(temp_frag.text.getString());
403 temp_frag.weblink.clear();
405 next_frags.push_back(temp_frag);
406 in_pos += frag_length;
407 remaining_in_output -= std::min(frag_length, remaining_in_output);
412 if (num_added == 0 || !next_line.fragments.empty()) {
413 destination.push_back(next_line);
420 s32 ChatBuffer::getTopScrollPos() const
422 s32 formatted_count = (s32) m_formatted.size();
423 s32 rows = (s32) m_rows;
427 if (formatted_count <= rows)
428 return formatted_count - rows;
433 s32 ChatBuffer::getBottomScrollPos() const
435 s32 formatted_count = (s32) m_formatted.size();
436 s32 rows = (s32) m_rows;
440 return formatted_count - rows;
443 void ChatBuffer::resize(u32 scrollback)
445 m_scrollback = scrollback;
446 if (m_unformatted.size() > m_scrollback)
447 deleteOldest(m_unformatted.size() - m_scrollback);
451 ChatPrompt::ChatPrompt(const std::wstring &prompt, u32 history_limit):
453 m_history_limit(history_limit)
457 void ChatPrompt::input(wchar_t ch)
459 m_line.insert(m_cursor, 1, ch);
462 m_nick_completion_start = 0;
463 m_nick_completion_end = 0;
466 void ChatPrompt::input(const std::wstring &str)
468 m_line.insert(m_cursor, str);
469 m_cursor += str.size();
471 m_nick_completion_start = 0;
472 m_nick_completion_end = 0;
475 void ChatPrompt::addToHistory(const std::wstring &line)
478 (m_history.size() == 0 || m_history.back() != line)) {
479 // Remove all duplicates
480 m_history.erase(std::remove(m_history.begin(), m_history.end(),
481 line), m_history.end());
483 m_history.push_back(line);
485 if (m_history.size() > m_history_limit)
486 m_history.erase(m_history.begin());
487 m_history_index = m_history.size();
490 void ChatPrompt::clear()
495 m_nick_completion_start = 0;
496 m_nick_completion_end = 0;
499 std::wstring ChatPrompt::replace(const std::wstring &line)
501 std::wstring old_line = m_line;
503 m_view = m_cursor = line.size();
505 m_nick_completion_start = 0;
506 m_nick_completion_end = 0;
510 void ChatPrompt::historyPrev()
512 if (m_history_index != 0)
515 replace(m_history[m_history_index]);
519 void ChatPrompt::historyNext()
521 if (m_history_index + 1 >= m_history.size())
523 m_history_index = m_history.size();
529 replace(m_history[m_history_index]);
533 void ChatPrompt::nickCompletion(const std::list<std::string>& names, bool backwards)
536 // (a) m_nick_completion_start == m_nick_completion_end == 0
537 // Then no previous nick completion is active.
538 // Get the word around the cursor and replace with any nick
539 // that has that word as a prefix.
540 // (b) else, continue a previous nick completion.
541 // m_nick_completion_start..m_nick_completion_end are the
542 // interval where the originally used prefix was. Cycle
543 // through the list of completions of that prefix.
544 u32 prefix_start = m_nick_completion_start;
545 u32 prefix_end = m_nick_completion_end;
546 bool initial = (prefix_end == 0);
549 // no previous nick completion is active
550 prefix_start = prefix_end = m_cursor;
551 while (prefix_start > 0 && !iswspace(m_line[prefix_start-1]))
553 while (prefix_end < m_line.size() && !iswspace(m_line[prefix_end]))
555 if (prefix_start == prefix_end)
558 std::wstring prefix = m_line.substr(prefix_start, prefix_end - prefix_start);
560 // find all names that start with the selected prefix
561 std::vector<std::wstring> completions;
562 for (const std::string &name : names) {
563 std::wstring completion = utf8_to_wide(name);
564 if (str_starts_with(completion, prefix, true)) {
565 if (prefix_start == 0)
567 completions.push_back(completion);
571 if (completions.empty())
574 // find a replacement string and the word that will be replaced
575 u32 word_end = prefix_end;
576 u32 replacement_index = 0;
579 while (word_end < m_line.size() && !iswspace(m_line[word_end]))
581 std::wstring word = m_line.substr(prefix_start, word_end - prefix_start);
583 // cycle through completions
584 for (u32 i = 0; i < completions.size(); ++i)
586 if (str_equal(word, completions[i], true))
589 replacement_index = i + completions.size() - 1;
591 replacement_index = i + 1;
592 replacement_index %= completions.size();
597 std::wstring replacement = completions[replacement_index];
598 if (word_end < m_line.size() && iswspace(m_line[word_end]))
601 // replace existing word with replacement word,
602 // place the cursor at the end and record the completion prefix
603 m_line.replace(prefix_start, word_end - prefix_start, replacement);
604 m_cursor = prefix_start + replacement.size();
606 m_nick_completion_start = prefix_start;
607 m_nick_completion_end = prefix_end;
610 void ChatPrompt::reformat(u32 cols)
612 if (cols <= m_prompt.size())
619 s32 length = m_line.size();
620 bool was_at_end = (m_view + m_cols >= length + 1);
621 m_cols = cols - m_prompt.size();
628 std::wstring ChatPrompt::getVisiblePortion() const
630 return m_prompt + m_line.substr(m_view, m_cols);
633 s32 ChatPrompt::getVisibleCursorPosition() const
635 return m_cursor - m_view + m_prompt.size();
638 void ChatPrompt::cursorOperation(CursorOp op, CursorOpDir dir, CursorOpScope scope)
640 s32 old_cursor = m_cursor;
641 s32 new_cursor = m_cursor;
643 s32 length = m_line.size();
644 s32 increment = (dir == CURSOROP_DIR_RIGHT) ? 1 : -1;
647 case CURSOROP_SCOPE_CHARACTER:
648 new_cursor += increment;
650 case CURSOROP_SCOPE_WORD:
651 if (dir == CURSOROP_DIR_RIGHT) {
652 // skip one word to the right
653 while (new_cursor < length && iswspace(m_line[new_cursor]))
655 while (new_cursor < length && !iswspace(m_line[new_cursor]))
657 while (new_cursor < length && iswspace(m_line[new_cursor]))
660 // skip one word to the left
661 while (new_cursor >= 1 && iswspace(m_line[new_cursor - 1]))
663 while (new_cursor >= 1 && !iswspace(m_line[new_cursor - 1]))
667 case CURSOROP_SCOPE_LINE:
668 new_cursor += increment * length;
670 case CURSOROP_SCOPE_SELECTION:
674 new_cursor = MYMAX(MYMIN(new_cursor, length), 0);
678 m_cursor = new_cursor;
681 case CURSOROP_DELETE:
682 if (m_cursor_len > 0) { // Delete selected text first
683 m_line.erase(m_cursor, m_cursor_len);
685 m_cursor = MYMIN(new_cursor, old_cursor);
686 m_line.erase(m_cursor, abs(new_cursor - old_cursor));
690 case CURSOROP_SELECT:
691 if (scope == CURSOROP_SCOPE_LINE) {
693 m_cursor_len = length;
695 m_cursor = MYMIN(new_cursor, old_cursor);
696 m_cursor_len += abs(new_cursor - old_cursor);
697 m_cursor_len = MYMIN(m_cursor_len, length - m_cursor);
704 m_nick_completion_start = 0;
705 m_nick_completion_end = 0;
708 void ChatPrompt::clampView()
710 s32 length = m_line.size();
711 if (length + 1 <= m_cols)
717 m_view = MYMIN(m_view, length + 1 - m_cols);
718 m_view = MYMIN(m_view, m_cursor);
719 m_view = MYMAX(m_view, m_cursor - m_cols + 1);
720 m_view = MYMAX(m_view, 0);
726 ChatBackend::ChatBackend():
727 m_console_buffer(500),
733 void ChatBackend::addMessage(const std::wstring &name, std::wstring text)
735 // Note: A message may consist of multiple lines, for example the MOTD.
736 text = translate_string(text);
738 while (!fnd.at_end())
740 std::wstring line = fnd.next(L"\n");
741 m_console_buffer.addLine(name, line);
742 m_recent_buffer.addLine(name, line);
746 void ChatBackend::addUnparsedMessage(std::wstring message)
748 // TODO: Remove the need to parse chat messages client-side, by sending
749 // separate name and text fields in TOCLIENT_CHAT_MESSAGE.
751 if (message.size() >= 2 && message[0] == L'<')
753 std::size_t closing = message.find_first_of(L'>', 1);
754 if (closing != std::wstring::npos &&
755 closing + 2 <= message.size() &&
756 message[closing+1] == L' ')
758 std::wstring name = message.substr(1, closing - 1);
759 std::wstring text = message.substr(closing + 2);
760 addMessage(name, text);
765 // Unable to parse, probably a server message.
766 addMessage(L"", message);
769 ChatBuffer& ChatBackend::getConsoleBuffer()
771 return m_console_buffer;
774 ChatBuffer& ChatBackend::getRecentBuffer()
776 return m_recent_buffer;
779 EnrichedString ChatBackend::getRecentChat() const
781 EnrichedString result;
782 for (u32 i = 0; i < m_recent_buffer.getLineCount(); ++i) {
783 const ChatLine& line = m_recent_buffer.getLine(i);
786 if (!line.name.empty()) {
796 ChatPrompt& ChatBackend::getPrompt()
801 void ChatBackend::reformat(u32 cols, u32 rows)
803 m_console_buffer.reformat(cols, rows);
805 // no need to reformat m_recent_buffer, its formatted lines
808 m_prompt.reformat(cols);
811 void ChatBackend::clearRecentChat()
813 m_recent_buffer.clear();
817 void ChatBackend::applySettings()
819 u32 recent_lines = g_settings->getU32("recent_chat_messages");
820 recent_lines = rangelim(recent_lines, 2, 20);
821 m_recent_buffer.resize(recent_lines);
824 void ChatBackend::step(float dtime)
826 m_recent_buffer.step(dtime);
827 m_recent_buffer.deleteByAge(60.0);
829 // no need to age messages in anything but m_recent_buffer
832 void ChatBackend::scroll(s32 rows)
834 m_console_buffer.scroll(rows);
837 void ChatBackend::scrollPageDown()
839 m_console_buffer.scroll(m_console_buffer.getRows());
842 void ChatBackend::scrollPageUp()
844 m_console_buffer.scroll(-(s32)m_console_buffer.getRows());