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.
23 #include "util/strfnd.h"
26 #include "util/string.h"
27 #include "util/numeric.h"
29 ChatBuffer::ChatBuffer(u32 scrollback):
30 m_scrollback(scrollback)
32 if (m_scrollback == 0)
34 m_empty_formatted_line.first = true;
37 void ChatBuffer::addLine(std::wstring name, std::wstring text)
39 ChatLine line(name, text);
40 m_unformatted.push_back(line);
44 // m_formatted is valid and must be kept valid
45 bool scrolled_at_bottom = (m_scroll == getBottomScrollPos());
46 u32 num_added = formatChatLine(line, m_cols, m_formatted);
47 if (scrolled_at_bottom)
48 m_scroll += num_added;
51 // Limit number of lines by m_scrollback
52 if (m_unformatted.size() > m_scrollback)
54 deleteOldest(m_unformatted.size() - m_scrollback);
58 void ChatBuffer::clear()
60 m_unformatted.clear();
65 u32 ChatBuffer::getLineCount() const
67 return m_unformatted.size();
70 const ChatLine& ChatBuffer::getLine(u32 index) const
72 assert(index < getLineCount()); // pre-condition
73 return m_unformatted[index];
76 void ChatBuffer::step(f32 dtime)
78 for (ChatLine &line : m_unformatted) {
83 void ChatBuffer::deleteOldest(u32 count)
85 bool at_bottom = (m_scroll == getBottomScrollPos());
87 u32 del_unformatted = 0;
88 u32 del_formatted = 0;
90 while (count > 0 && del_unformatted < m_unformatted.size())
94 // keep m_formatted in sync
95 if (del_formatted < m_formatted.size())
98 sanity_check(m_formatted[del_formatted].first);
100 while (del_formatted < m_formatted.size() &&
101 !m_formatted[del_formatted].first)
108 m_unformatted.erase(m_unformatted.begin(), m_unformatted.begin() + del_unformatted);
109 m_formatted.erase(m_formatted.begin(), m_formatted.begin() + del_formatted);
112 m_scroll = getBottomScrollPos();
114 scrollAbsolute(m_scroll - del_formatted);
117 void ChatBuffer::deleteByAge(f32 maxAge)
120 while (count < m_unformatted.size() && m_unformatted[count].age > maxAge)
125 u32 ChatBuffer::getColumns() const
130 u32 ChatBuffer::getRows() const
135 void ChatBuffer::reformat(u32 cols, u32 rows)
137 if (cols == 0 || rows == 0)
139 // Clear formatted buffer
145 else if (cols != m_cols || rows != m_rows)
147 // TODO: Avoid reformatting ALL lines (even invisible ones)
148 // each time the console size changes.
150 // Find out the scroll position in *unformatted* lines
151 u32 restore_scroll_unformatted = 0;
152 u32 restore_scroll_formatted = 0;
153 bool at_bottom = (m_scroll == getBottomScrollPos());
156 for (s32 i = 0; i < m_scroll; ++i)
158 if (m_formatted[i].first)
159 ++restore_scroll_unformatted;
163 // If number of columns change, reformat everything
167 for (u32 i = 0; i < m_unformatted.size(); ++i)
169 if (i == restore_scroll_unformatted)
170 restore_scroll_formatted = m_formatted.size();
171 formatChatLine(m_unformatted[i], cols, m_formatted);
175 // Update the console size
179 // Restore the scroll position
186 scrollAbsolute(restore_scroll_formatted);
191 const ChatFormattedLine& ChatBuffer::getFormattedLine(u32 row) const
193 s32 index = m_scroll + (s32) row;
194 if (index >= 0 && index < (s32) m_formatted.size())
195 return m_formatted[index];
197 return m_empty_formatted_line;
200 void ChatBuffer::scroll(s32 rows)
202 scrollAbsolute(m_scroll + rows);
205 void ChatBuffer::scrollAbsolute(s32 scroll)
207 s32 top = getTopScrollPos();
208 s32 bottom = getBottomScrollPos();
213 if (m_scroll > bottom)
217 void ChatBuffer::scrollBottom()
219 m_scroll = getBottomScrollPos();
222 void ChatBuffer::scrollTop()
224 m_scroll = getTopScrollPos();
227 u32 ChatBuffer::formatChatLine(const ChatLine& line, u32 cols,
228 std::vector<ChatFormattedLine>& destination) const
231 std::vector<ChatFormattedFragment> next_frags;
232 ChatFormattedLine next_line;
233 ChatFormattedFragment temp_frag;
236 u32 hanging_indentation = 0;
238 // Format the sender name and produce fragments
239 if (!line.name.empty()) {
240 temp_frag.text = L"<";
241 temp_frag.column = 0;
242 //temp_frag.bold = 0;
243 next_frags.push_back(temp_frag);
244 temp_frag.text = line.name;
245 temp_frag.column = 0;
246 //temp_frag.bold = 1;
247 next_frags.push_back(temp_frag);
248 temp_frag.text = L"> ";
249 temp_frag.column = 0;
250 //temp_frag.bold = 0;
251 next_frags.push_back(temp_frag);
254 std::wstring name_sanitized = line.name.c_str();
256 // Choose an indentation level
257 if (line.name.empty()) {
259 hanging_indentation = 0;
260 } else if (name_sanitized.size() + 3 <= cols/2) {
261 // Names shorter than about half the console width
262 hanging_indentation = line.name.size() + 3;
265 hanging_indentation = 2;
267 //EnrichedString line_text(line.text);
269 next_line.first = true;
270 bool text_processing = false;
272 // Produce fragments and layout them into lines
273 while (!next_frags.empty() || in_pos < line.text.size())
275 // Layout fragments into lines
276 while (!next_frags.empty())
278 ChatFormattedFragment& frag = next_frags[0];
279 if (frag.text.size() <= cols - out_column)
281 // Fragment fits into current line
282 frag.column = out_column;
283 next_line.fragments.push_back(frag);
284 out_column += frag.text.size();
285 next_frags.erase(next_frags.begin());
289 // Fragment does not fit into current line
291 temp_frag.text = frag.text.substr(0, cols - out_column);
292 temp_frag.column = out_column;
293 //temp_frag.bold = frag.bold;
294 next_line.fragments.push_back(temp_frag);
295 frag.text = frag.text.substr(cols - out_column);
298 if (out_column == cols || text_processing)
300 // End the current line
301 destination.push_back(next_line);
303 next_line.fragments.clear();
304 next_line.first = false;
306 out_column = text_processing ? hanging_indentation : 0;
311 if (in_pos < line.text.size())
313 u32 remaining_in_input = line.text.size() - in_pos;
314 u32 remaining_in_output = cols - out_column;
316 // Determine a fragment length <= the minimum of
317 // remaining_in_{in,out}put. Try to end the fragment
318 // on a word boundary.
319 u32 frag_length = 1, space_pos = 0;
320 while (frag_length < remaining_in_input &&
321 frag_length < remaining_in_output)
323 if (iswspace(line.text.getString()[in_pos + frag_length]))
324 space_pos = frag_length;
327 if (space_pos != 0 && frag_length < remaining_in_input)
328 frag_length = space_pos + 1;
330 temp_frag.text = line.text.substr(in_pos, frag_length);
331 temp_frag.column = 0;
332 //temp_frag.bold = 0;
333 next_frags.push_back(temp_frag);
334 in_pos += frag_length;
335 text_processing = true;
340 if (num_added == 0 || !next_line.fragments.empty())
342 destination.push_back(next_line);
349 s32 ChatBuffer::getTopScrollPos() const
351 s32 formatted_count = (s32) m_formatted.size();
352 s32 rows = (s32) m_rows;
356 if (formatted_count <= rows)
357 return formatted_count - rows;
362 s32 ChatBuffer::getBottomScrollPos() const
364 s32 formatted_count = (s32) m_formatted.size();
365 s32 rows = (s32) m_rows;
369 return formatted_count - rows;
372 void ChatBuffer::resize(u32 scrollback) {
373 m_scrollback = scrollback;
374 if (m_unformatted.size() > m_scrollback)
376 deleteOldest(m_unformatted.size() - m_scrollback);
381 ChatPrompt::ChatPrompt(const std::wstring &prompt, u32 history_limit):
383 m_history_limit(history_limit)
387 void ChatPrompt::input(wchar_t ch)
389 m_line.insert(m_cursor, 1, ch);
392 m_nick_completion_start = 0;
393 m_nick_completion_end = 0;
396 void ChatPrompt::input(const std::wstring &str)
398 m_line.insert(m_cursor, str);
399 m_cursor += str.size();
401 m_nick_completion_start = 0;
402 m_nick_completion_end = 0;
405 void ChatPrompt::addToHistory(std::wstring line)
408 m_history.push_back(line);
409 if (m_history.size() > m_history_limit)
410 m_history.erase(m_history.begin());
411 m_history_index = m_history.size();
414 void ChatPrompt::clear()
419 m_nick_completion_start = 0;
420 m_nick_completion_end = 0;
423 std::wstring ChatPrompt::replace(std::wstring line)
425 std::wstring old_line = m_line;
427 m_view = m_cursor = line.size();
429 m_nick_completion_start = 0;
430 m_nick_completion_end = 0;
434 void ChatPrompt::historyPrev()
436 if (m_history_index != 0)
439 replace(m_history[m_history_index]);
443 void ChatPrompt::historyNext()
445 if (m_history_index + 1 >= m_history.size())
447 m_history_index = m_history.size();
453 replace(m_history[m_history_index]);
457 void ChatPrompt::nickCompletion(const std::list<std::string>& names, bool backwards)
460 // (a) m_nick_completion_start == m_nick_completion_end == 0
461 // Then no previous nick completion is active.
462 // Get the word around the cursor and replace with any nick
463 // that has that word as a prefix.
464 // (b) else, continue a previous nick completion.
465 // m_nick_completion_start..m_nick_completion_end are the
466 // interval where the originally used prefix was. Cycle
467 // through the list of completions of that prefix.
468 u32 prefix_start = m_nick_completion_start;
469 u32 prefix_end = m_nick_completion_end;
470 bool initial = (prefix_end == 0);
473 // no previous nick completion is active
474 prefix_start = prefix_end = m_cursor;
475 while (prefix_start > 0 && !iswspace(m_line[prefix_start-1]))
477 while (prefix_end < m_line.size() && !iswspace(m_line[prefix_end]))
479 if (prefix_start == prefix_end)
482 std::wstring prefix = m_line.substr(prefix_start, prefix_end - prefix_start);
484 // find all names that start with the selected prefix
485 std::vector<std::wstring> completions;
486 for (const std::string &name : names) {
487 if (str_starts_with(narrow_to_wide(name), prefix, true)) {
488 std::wstring completion = narrow_to_wide(name);
489 if (prefix_start == 0)
491 completions.push_back(completion);
495 if (completions.empty())
498 // find a replacement string and the word that will be replaced
499 u32 word_end = prefix_end;
500 u32 replacement_index = 0;
503 while (word_end < m_line.size() && !iswspace(m_line[word_end]))
505 std::wstring word = m_line.substr(prefix_start, word_end - prefix_start);
507 // cycle through completions
508 for (u32 i = 0; i < completions.size(); ++i)
510 if (str_equal(word, completions[i], true))
513 replacement_index = i + completions.size() - 1;
515 replacement_index = i + 1;
516 replacement_index %= completions.size();
521 std::wstring replacement = completions[replacement_index];
522 if (word_end < m_line.size() && iswspace(m_line[word_end]))
525 // replace existing word with replacement word,
526 // place the cursor at the end and record the completion prefix
527 m_line.replace(prefix_start, word_end - prefix_start, replacement);
528 m_cursor = prefix_start + replacement.size();
530 m_nick_completion_start = prefix_start;
531 m_nick_completion_end = prefix_end;
534 void ChatPrompt::reformat(u32 cols)
536 if (cols <= m_prompt.size())
543 s32 length = m_line.size();
544 bool was_at_end = (m_view + m_cols >= length + 1);
545 m_cols = cols - m_prompt.size();
552 std::wstring ChatPrompt::getVisiblePortion() const
554 return m_prompt + m_line.substr(m_view, m_cols);
557 s32 ChatPrompt::getVisibleCursorPosition() const
559 return m_cursor - m_view + m_prompt.size();
562 void ChatPrompt::cursorOperation(CursorOp op, CursorOpDir dir, CursorOpScope scope)
564 s32 old_cursor = m_cursor;
565 s32 new_cursor = m_cursor;
567 s32 length = m_line.size();
568 s32 increment = (dir == CURSOROP_DIR_RIGHT) ? 1 : -1;
571 case CURSOROP_SCOPE_CHARACTER:
572 new_cursor += increment;
574 case CURSOROP_SCOPE_WORD:
575 if (dir == CURSOROP_DIR_RIGHT) {
576 // skip one word to the right
577 while (new_cursor < length && iswspace(m_line[new_cursor]))
579 while (new_cursor < length && !iswspace(m_line[new_cursor]))
581 while (new_cursor < length && iswspace(m_line[new_cursor]))
584 // skip one word to the left
585 while (new_cursor >= 1 && iswspace(m_line[new_cursor - 1]))
587 while (new_cursor >= 1 && !iswspace(m_line[new_cursor - 1]))
591 case CURSOROP_SCOPE_LINE:
592 new_cursor += increment * length;
594 case CURSOROP_SCOPE_SELECTION:
598 new_cursor = MYMAX(MYMIN(new_cursor, length), 0);
602 m_cursor = new_cursor;
605 case CURSOROP_DELETE:
606 if (m_cursor_len > 0) { // Delete selected text first
607 m_line.erase(m_cursor, m_cursor_len);
609 m_cursor = MYMIN(new_cursor, old_cursor);
610 m_line.erase(m_cursor, abs(new_cursor - old_cursor));
614 case CURSOROP_SELECT:
615 if (scope == CURSOROP_SCOPE_LINE) {
617 m_cursor_len = length;
619 m_cursor = MYMIN(new_cursor, old_cursor);
620 m_cursor_len += abs(new_cursor - old_cursor);
621 m_cursor_len = MYMIN(m_cursor_len, length - m_cursor);
628 m_nick_completion_start = 0;
629 m_nick_completion_end = 0;
632 void ChatPrompt::clampView()
634 s32 length = m_line.size();
635 if (length + 1 <= m_cols)
641 m_view = MYMIN(m_view, length + 1 - m_cols);
642 m_view = MYMIN(m_view, m_cursor);
643 m_view = MYMAX(m_view, m_cursor - m_cols + 1);
644 m_view = MYMAX(m_view, 0);
650 ChatBackend::ChatBackend():
651 m_console_buffer(500),
657 void ChatBackend::addMessage(std::wstring name, std::wstring text)
659 // Note: A message may consist of multiple lines, for example the MOTD.
660 text = translate_string(text);
662 while (!fnd.at_end())
664 std::wstring line = fnd.next(L"\n");
665 m_console_buffer.addLine(name, line);
666 m_recent_buffer.addLine(name, line);
670 void ChatBackend::addUnparsedMessage(std::wstring message)
672 // TODO: Remove the need to parse chat messages client-side, by sending
673 // separate name and text fields in TOCLIENT_CHAT_MESSAGE.
675 if (message.size() >= 2 && message[0] == L'<')
677 std::size_t closing = message.find_first_of(L'>', 1);
678 if (closing != std::wstring::npos &&
679 closing + 2 <= message.size() &&
680 message[closing+1] == L' ')
682 std::wstring name = message.substr(1, closing - 1);
683 std::wstring text = message.substr(closing + 2);
684 addMessage(name, text);
689 // Unable to parse, probably a server message.
690 addMessage(L"", message);
693 ChatBuffer& ChatBackend::getConsoleBuffer()
695 return m_console_buffer;
698 ChatBuffer& ChatBackend::getRecentBuffer()
700 return m_recent_buffer;
703 EnrichedString ChatBackend::getRecentChat()
705 EnrichedString result;
706 for (u32 i = 0; i < m_recent_buffer.getLineCount(); ++i)
708 const ChatLine& line = m_recent_buffer.getLine(i);
711 if (!line.name.empty()) {
721 ChatPrompt& ChatBackend::getPrompt()
726 void ChatBackend::reformat(u32 cols, u32 rows)
728 m_console_buffer.reformat(cols, rows);
730 // no need to reformat m_recent_buffer, its formatted lines
733 m_prompt.reformat(cols);
736 void ChatBackend::clearRecentChat()
738 m_recent_buffer.clear();
742 void ChatBackend::applySettings(Settings* settings) {
743 m_recent_buffer.resize(settings->getU32("recent_chat_size"));
746 void ChatBackend::step(float dtime)
748 m_recent_buffer.step(dtime);
749 m_recent_buffer.deleteByAge(60.0);
751 // no need to age messages in anything but m_recent_buffer
754 void ChatBackend::scroll(s32 rows)
756 m_console_buffer.scroll(rows);
759 void ChatBackend::scrollPageDown()
761 m_console_buffer.scroll(m_console_buffer.getRows());
764 void ChatBackend::scrollPageUp()
766 m_console_buffer.scroll(-(s32)m_console_buffer.getRows());