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;
374 ChatPrompt::ChatPrompt(const std::wstring &prompt, u32 history_limit):
376 m_history_limit(history_limit)
380 void ChatPrompt::input(wchar_t ch)
382 m_line.insert(m_cursor, 1, ch);
385 m_nick_completion_start = 0;
386 m_nick_completion_end = 0;
389 void ChatPrompt::input(const std::wstring &str)
391 m_line.insert(m_cursor, str);
392 m_cursor += str.size();
394 m_nick_completion_start = 0;
395 m_nick_completion_end = 0;
398 void ChatPrompt::addToHistory(std::wstring line)
401 m_history.push_back(line);
402 if (m_history.size() > m_history_limit)
403 m_history.erase(m_history.begin());
404 m_history_index = m_history.size();
407 void ChatPrompt::clear()
412 m_nick_completion_start = 0;
413 m_nick_completion_end = 0;
416 std::wstring ChatPrompt::replace(std::wstring line)
418 std::wstring old_line = m_line;
420 m_view = m_cursor = line.size();
422 m_nick_completion_start = 0;
423 m_nick_completion_end = 0;
427 void ChatPrompt::historyPrev()
429 if (m_history_index != 0)
432 replace(m_history[m_history_index]);
436 void ChatPrompt::historyNext()
438 if (m_history_index + 1 >= m_history.size())
440 m_history_index = m_history.size();
446 replace(m_history[m_history_index]);
450 void ChatPrompt::nickCompletion(const std::list<std::string>& names, bool backwards)
453 // (a) m_nick_completion_start == m_nick_completion_end == 0
454 // Then no previous nick completion is active.
455 // Get the word around the cursor and replace with any nick
456 // that has that word as a prefix.
457 // (b) else, continue a previous nick completion.
458 // m_nick_completion_start..m_nick_completion_end are the
459 // interval where the originally used prefix was. Cycle
460 // through the list of completions of that prefix.
461 u32 prefix_start = m_nick_completion_start;
462 u32 prefix_end = m_nick_completion_end;
463 bool initial = (prefix_end == 0);
466 // no previous nick completion is active
467 prefix_start = prefix_end = m_cursor;
468 while (prefix_start > 0 && !iswspace(m_line[prefix_start-1]))
470 while (prefix_end < m_line.size() && !iswspace(m_line[prefix_end]))
472 if (prefix_start == prefix_end)
475 std::wstring prefix = m_line.substr(prefix_start, prefix_end - prefix_start);
477 // find all names that start with the selected prefix
478 std::vector<std::wstring> completions;
479 for (const std::string &name : names) {
480 if (str_starts_with(narrow_to_wide(name), prefix, true)) {
481 std::wstring completion = narrow_to_wide(name);
482 if (prefix_start == 0)
484 completions.push_back(completion);
488 if (completions.empty())
491 // find a replacement string and the word that will be replaced
492 u32 word_end = prefix_end;
493 u32 replacement_index = 0;
496 while (word_end < m_line.size() && !iswspace(m_line[word_end]))
498 std::wstring word = m_line.substr(prefix_start, word_end - prefix_start);
500 // cycle through completions
501 for (u32 i = 0; i < completions.size(); ++i)
503 if (str_equal(word, completions[i], true))
506 replacement_index = i + completions.size() - 1;
508 replacement_index = i + 1;
509 replacement_index %= completions.size();
514 std::wstring replacement = completions[replacement_index];
515 if (word_end < m_line.size() && iswspace(m_line[word_end]))
518 // replace existing word with replacement word,
519 // place the cursor at the end and record the completion prefix
520 m_line.replace(prefix_start, word_end - prefix_start, replacement);
521 m_cursor = prefix_start + replacement.size();
523 m_nick_completion_start = prefix_start;
524 m_nick_completion_end = prefix_end;
527 void ChatPrompt::reformat(u32 cols)
529 if (cols <= m_prompt.size())
536 s32 length = m_line.size();
537 bool was_at_end = (m_view + m_cols >= length + 1);
538 m_cols = cols - m_prompt.size();
545 std::wstring ChatPrompt::getVisiblePortion() const
547 return m_prompt + m_line.substr(m_view, m_cols);
550 s32 ChatPrompt::getVisibleCursorPosition() const
552 return m_cursor - m_view + m_prompt.size();
555 void ChatPrompt::cursorOperation(CursorOp op, CursorOpDir dir, CursorOpScope scope)
557 s32 old_cursor = m_cursor;
558 s32 new_cursor = m_cursor;
560 s32 length = m_line.size();
561 s32 increment = (dir == CURSOROP_DIR_RIGHT) ? 1 : -1;
564 case CURSOROP_SCOPE_CHARACTER:
565 new_cursor += increment;
567 case CURSOROP_SCOPE_WORD:
568 if (dir == CURSOROP_DIR_RIGHT) {
569 // skip one word to the right
570 while (new_cursor < length && iswspace(m_line[new_cursor]))
572 while (new_cursor < length && !iswspace(m_line[new_cursor]))
574 while (new_cursor < length && iswspace(m_line[new_cursor]))
577 // skip one word to the left
578 while (new_cursor >= 1 && iswspace(m_line[new_cursor - 1]))
580 while (new_cursor >= 1 && !iswspace(m_line[new_cursor - 1]))
584 case CURSOROP_SCOPE_LINE:
585 new_cursor += increment * length;
587 case CURSOROP_SCOPE_SELECTION:
591 new_cursor = MYMAX(MYMIN(new_cursor, length), 0);
595 m_cursor = new_cursor;
598 case CURSOROP_DELETE:
599 if (m_cursor_len > 0) { // Delete selected text first
600 m_line.erase(m_cursor, m_cursor_len);
602 m_cursor = MYMIN(new_cursor, old_cursor);
603 m_line.erase(m_cursor, abs(new_cursor - old_cursor));
607 case CURSOROP_SELECT:
608 if (scope == CURSOROP_SCOPE_LINE) {
610 m_cursor_len = length;
612 m_cursor = MYMIN(new_cursor, old_cursor);
613 m_cursor_len += abs(new_cursor - old_cursor);
614 m_cursor_len = MYMIN(m_cursor_len, length - m_cursor);
621 m_nick_completion_start = 0;
622 m_nick_completion_end = 0;
625 void ChatPrompt::clampView()
627 s32 length = m_line.size();
628 if (length + 1 <= m_cols)
634 m_view = MYMIN(m_view, length + 1 - m_cols);
635 m_view = MYMIN(m_view, m_cursor);
636 m_view = MYMAX(m_view, m_cursor - m_cols + 1);
637 m_view = MYMAX(m_view, 0);
643 ChatBackend::ChatBackend():
644 m_console_buffer(500),
650 void ChatBackend::addMessage(std::wstring name, std::wstring text)
652 // Note: A message may consist of multiple lines, for example the MOTD.
653 text = translate_string(text);
655 while (!fnd.at_end())
657 std::wstring line = fnd.next(L"\n");
658 m_console_buffer.addLine(name, line);
659 m_recent_buffer.addLine(name, line);
663 void ChatBackend::addUnparsedMessage(std::wstring message)
665 // TODO: Remove the need to parse chat messages client-side, by sending
666 // separate name and text fields in TOCLIENT_CHAT_MESSAGE.
668 if (message.size() >= 2 && message[0] == L'<')
670 std::size_t closing = message.find_first_of(L'>', 1);
671 if (closing != std::wstring::npos &&
672 closing + 2 <= message.size() &&
673 message[closing+1] == L' ')
675 std::wstring name = message.substr(1, closing - 1);
676 std::wstring text = message.substr(closing + 2);
677 addMessage(name, text);
682 // Unable to parse, probably a server message.
683 addMessage(L"", message);
686 ChatBuffer& ChatBackend::getConsoleBuffer()
688 return m_console_buffer;
691 ChatBuffer& ChatBackend::getRecentBuffer()
693 return m_recent_buffer;
696 EnrichedString ChatBackend::getRecentChat()
698 EnrichedString result;
699 for (u32 i = 0; i < m_recent_buffer.getLineCount(); ++i)
701 const ChatLine& line = m_recent_buffer.getLine(i);
704 if (!line.name.empty()) {
714 ChatPrompt& ChatBackend::getPrompt()
719 void ChatBackend::reformat(u32 cols, u32 rows)
721 m_console_buffer.reformat(cols, rows);
723 // no need to reformat m_recent_buffer, its formatted lines
726 m_prompt.reformat(cols);
729 void ChatBackend::clearRecentChat()
731 m_recent_buffer.clear();
734 void ChatBackend::step(float dtime)
736 m_recent_buffer.step(dtime);
737 m_recent_buffer.deleteByAge(60.0);
739 // no need to age messages in anything but m_recent_buffer
742 void ChatBackend::scroll(s32 rows)
744 m_console_buffer.scroll(rows);
747 void ChatBackend::scrollPageDown()
749 m_console_buffer.scroll(m_console_buffer.getRows());
752 void ChatBackend::scrollPageUp()
754 m_console_buffer.scroll(-(s32)m_console_buffer.getRows());