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.
25 #include "util/string.h"
26 #include "util/numeric.h"
28 ChatBuffer::ChatBuffer(u32 scrollback):
29 m_scrollback(scrollback),
35 m_empty_formatted_line()
37 if (m_scrollback == 0)
39 m_empty_formatted_line.first = true;
42 ChatBuffer::~ChatBuffer()
46 void ChatBuffer::addLine(std::wstring name, std::wstring text)
48 ChatLine line(name, text);
49 m_unformatted.push_back(line);
53 // m_formatted is valid and must be kept valid
54 bool scrolled_at_bottom = (m_scroll == getBottomScrollPos());
55 u32 num_added = formatChatLine(line, m_cols, m_formatted);
56 if (scrolled_at_bottom)
57 m_scroll += num_added;
60 // Limit number of lines by m_scrollback
61 if (m_unformatted.size() > m_scrollback)
63 deleteOldest(m_unformatted.size() - m_scrollback);
67 void ChatBuffer::clear()
69 m_unformatted.clear();
74 u32 ChatBuffer::getLineCount() const
76 return m_unformatted.size();
79 u32 ChatBuffer::getScrollback() const
84 const ChatLine& ChatBuffer::getLine(u32 index) const
86 assert(index < getLineCount());
87 return m_unformatted[index];
90 void ChatBuffer::step(f32 dtime)
92 for (u32 i = 0; i < m_unformatted.size(); ++i)
94 m_unformatted[i].age += dtime;
98 void ChatBuffer::deleteOldest(u32 count)
100 u32 del_unformatted = 0;
101 u32 del_formatted = 0;
103 while (count > 0 && del_unformatted < m_unformatted.size())
107 // keep m_formatted in sync
108 if (del_formatted < m_formatted.size())
110 assert(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);
124 void ChatBuffer::deleteByAge(f32 maxAge)
127 while (count < m_unformatted.size() && m_unformatted[count].age > maxAge)
132 u32 ChatBuffer::getColumns() const
137 u32 ChatBuffer::getRows() const
142 void ChatBuffer::reformat(u32 cols, u32 rows)
144 if (cols == 0 || rows == 0)
146 // Clear formatted buffer
152 else if (cols != m_cols || rows != m_rows)
154 // TODO: Avoid reformatting ALL lines (even inivisble ones)
155 // each time the console size changes.
157 // Find out the scroll position in *unformatted* lines
158 u32 restore_scroll_unformatted = 0;
159 u32 restore_scroll_formatted = 0;
160 bool at_bottom = (m_scroll == getBottomScrollPos());
163 for (s32 i = 0; i < m_scroll; ++i)
165 if (m_formatted[i].first)
166 ++restore_scroll_unformatted;
170 // If number of columns change, reformat everything
174 for (u32 i = 0; i < m_unformatted.size(); ++i)
176 if (i == restore_scroll_unformatted)
177 restore_scroll_formatted = m_formatted.size();
178 formatChatLine(m_unformatted[i], cols, m_formatted);
182 // Update the console size
186 // Restore the scroll position
193 scrollAbsolute(restore_scroll_formatted);
198 const ChatFormattedLine& ChatBuffer::getFormattedLine(u32 row) const
200 s32 index = m_scroll + (s32) row;
201 if (index >= 0 && index < (s32) m_formatted.size())
202 return m_formatted[index];
204 return m_empty_formatted_line;
207 void ChatBuffer::scroll(s32 rows)
209 scrollAbsolute(m_scroll + rows);
212 void ChatBuffer::scrollAbsolute(s32 scroll)
214 s32 top = getTopScrollPos();
215 s32 bottom = getBottomScrollPos();
220 if (m_scroll > bottom)
224 void ChatBuffer::scrollBottom()
226 m_scroll = getBottomScrollPos();
229 void ChatBuffer::scrollTop()
231 m_scroll = getTopScrollPos();
234 u32 ChatBuffer::formatChatLine(const ChatLine& line, u32 cols,
235 std::vector<ChatFormattedLine>& destination) const
238 std::vector<ChatFormattedFragment> next_frags;
239 ChatFormattedLine next_line;
240 ChatFormattedFragment temp_frag;
243 u32 hanging_indentation = 0;
245 // Format the sender name and produce fragments
246 if (!line.name.empty())
248 temp_frag.text = L"<";
249 temp_frag.column = 0;
250 //temp_frag.bold = 0;
251 next_frags.push_back(temp_frag);
252 temp_frag.text = line.name;
253 temp_frag.column = 0;
254 //temp_frag.bold = 1;
255 next_frags.push_back(temp_frag);
256 temp_frag.text = L"> ";
257 temp_frag.column = 0;
258 //temp_frag.bold = 0;
259 next_frags.push_back(temp_frag);
262 // Choose an indentation level
263 if (line.name.empty())
266 hanging_indentation = 0;
268 else if (line.name.size() + 3 <= cols/2)
270 // Names shorter than about half the console width
271 hanging_indentation = line.name.size() + 3;
276 hanging_indentation = 2;
279 next_line.first = true;
280 bool text_processing = false;
282 // Produce fragments and layout them into lines
283 while (!next_frags.empty() || in_pos < line.text.size())
285 // Layout fragments into lines
286 while (!next_frags.empty())
288 ChatFormattedFragment& frag = next_frags[0];
289 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());
299 // Fragment does not fit into current line
301 temp_frag.text = frag.text.substr(0, cols - out_column);
302 temp_frag.column = out_column;
303 //temp_frag.bold = frag.bold;
304 next_line.fragments.push_back(temp_frag);
305 frag.text = frag.text.substr(cols - out_column);
308 if (out_column == cols || text_processing)
310 // End the current line
311 destination.push_back(next_line);
313 next_line.fragments.clear();
314 next_line.first = false;
316 out_column = text_processing ? hanging_indentation : 0;
321 if (in_pos < line.text.size())
323 u32 remaining_in_input = line.text.size() - in_pos;
324 u32 remaining_in_output = cols - out_column;
326 // Determine a fragment length <= the minimum of
327 // remaining_in_{in,out}put. Try to end the fragment
328 // on a word boundary.
329 u32 frag_length = 1, space_pos = 0;
330 while (frag_length < remaining_in_input &&
331 frag_length < remaining_in_output)
333 if (isspace(line.text[in_pos + frag_length]))
334 space_pos = frag_length;
337 if (space_pos != 0 && frag_length < remaining_in_input)
338 frag_length = space_pos + 1;
340 temp_frag.text = line.text.substr(in_pos, frag_length);
341 temp_frag.column = 0;
342 //temp_frag.bold = 0;
343 next_frags.push_back(temp_frag);
344 in_pos += frag_length;
345 text_processing = true;
350 if (num_added == 0 || !next_line.fragments.empty())
352 destination.push_back(next_line);
359 s32 ChatBuffer::getTopScrollPos() const
361 s32 formatted_count = (s32) m_formatted.size();
362 s32 rows = (s32) m_rows;
365 else if (formatted_count <= rows)
366 return formatted_count - rows;
371 s32 ChatBuffer::getBottomScrollPos() const
373 s32 formatted_count = (s32) m_formatted.size();
374 s32 rows = (s32) m_rows;
378 return formatted_count - rows;
383 ChatPrompt::ChatPrompt(std::wstring prompt, u32 history_limit):
388 m_history_limit(history_limit),
392 m_nick_completion_start(0),
393 m_nick_completion_end(0)
397 ChatPrompt::~ChatPrompt()
401 void ChatPrompt::input(wchar_t ch)
403 m_line.insert(m_cursor, 1, ch);
406 m_nick_completion_start = 0;
407 m_nick_completion_end = 0;
410 std::wstring ChatPrompt::submit()
412 std::wstring line = m_line;
415 m_history.push_back(line);
416 if (m_history.size() > m_history_limit)
417 m_history.erase(m_history.begin());
418 m_history_index = m_history.size();
421 m_nick_completion_start = 0;
422 m_nick_completion_end = 0;
426 void ChatPrompt::clear()
431 m_nick_completion_start = 0;
432 m_nick_completion_end = 0;
435 void ChatPrompt::replace(std::wstring line)
438 m_view = m_cursor = line.size();
440 m_nick_completion_start = 0;
441 m_nick_completion_end = 0;
444 void ChatPrompt::historyPrev()
446 if (m_history_index != 0)
449 replace(m_history[m_history_index]);
453 void ChatPrompt::historyNext()
455 if (m_history_index + 1 >= m_history.size())
457 m_history_index = m_history.size();
463 replace(m_history[m_history_index]);
467 void ChatPrompt::nickCompletion(const std::list<std::wstring>& names, bool backwards)
470 // (a) m_nick_completion_start == m_nick_completion_end == 0
471 // Then no previous nick completion is active.
472 // Get the word around the cursor and replace with any nick
473 // that has that word as a prefix.
474 // (b) else, continue a previous nick completion.
475 // m_nick_completion_start..m_nick_completion_end are the
476 // interval where the originally used prefix was. Cycle
477 // through the list of completions of that prefix.
478 u32 prefix_start = m_nick_completion_start;
479 u32 prefix_end = m_nick_completion_end;
480 bool initial = (prefix_end == 0);
483 // no previous nick completion is active
484 prefix_start = prefix_end = m_cursor;
485 while (prefix_start > 0 && !isspace(m_line[prefix_start-1]))
487 while (prefix_end < m_line.size() && !isspace(m_line[prefix_end]))
489 if (prefix_start == prefix_end)
492 std::wstring prefix = m_line.substr(prefix_start, prefix_end - prefix_start);
494 // find all names that start with the selected prefix
495 std::vector<std::wstring> completions;
496 for (std::list<std::wstring>::const_iterator
498 i != names.end(); ++i)
500 if (str_starts_with(*i, prefix, true))
502 std::wstring completion = *i;
503 if (prefix_start == 0)
505 completions.push_back(completion);
508 if (completions.empty())
511 // find a replacement string and the word that will be replaced
512 u32 word_end = prefix_end;
513 u32 replacement_index = 0;
516 while (word_end < m_line.size() && !isspace(m_line[word_end]))
518 std::wstring word = m_line.substr(prefix_start, word_end - prefix_start);
520 // cycle through completions
521 for (u32 i = 0; i < completions.size(); ++i)
523 if (str_equal(word, completions[i], true))
526 replacement_index = i + completions.size() - 1;
528 replacement_index = i + 1;
529 replacement_index %= completions.size();
534 std::wstring replacement = completions[replacement_index] + L" ";
535 if (word_end < m_line.size() && isspace(word_end))
538 // replace existing word with replacement word,
539 // place the cursor at the end and record the completion prefix
540 m_line.replace(prefix_start, word_end - prefix_start, replacement);
541 m_cursor = prefix_start + replacement.size();
543 m_nick_completion_start = prefix_start;
544 m_nick_completion_end = prefix_end;
547 void ChatPrompt::reformat(u32 cols)
549 if (cols <= m_prompt.size())
556 s32 length = m_line.size();
557 bool was_at_end = (m_view + m_cols >= length + 1);
558 m_cols = cols - m_prompt.size();
565 std::wstring ChatPrompt::getVisiblePortion() const
567 return m_prompt + m_line.substr(m_view, m_cols);
570 s32 ChatPrompt::getVisibleCursorPosition() const
572 return m_cursor - m_view + m_prompt.size();
575 void ChatPrompt::cursorOperation(CursorOp op, CursorOpDir dir, CursorOpScope scope)
577 s32 old_cursor = m_cursor;
578 s32 new_cursor = m_cursor;
580 s32 length = m_line.size();
581 s32 increment = (dir == CURSOROP_DIR_RIGHT) ? 1 : -1;
583 if (scope == CURSOROP_SCOPE_CHARACTER)
585 new_cursor += increment;
587 else if (scope == CURSOROP_SCOPE_WORD)
591 // skip one word to the right
592 while (new_cursor < length && isspace(m_line[new_cursor]))
594 while (new_cursor < length && !isspace(m_line[new_cursor]))
596 while (new_cursor < length && isspace(m_line[new_cursor]))
601 // skip one word to the left
602 while (new_cursor >= 1 && isspace(m_line[new_cursor - 1]))
604 while (new_cursor >= 1 && !isspace(m_line[new_cursor - 1]))
608 else if (scope == CURSOROP_SCOPE_LINE)
610 new_cursor += increment * length;
613 new_cursor = MYMAX(MYMIN(new_cursor, length), 0);
615 if (op == CURSOROP_MOVE)
617 m_cursor = new_cursor;
619 else if (op == CURSOROP_DELETE)
621 if (new_cursor < old_cursor)
623 m_line.erase(new_cursor, old_cursor - new_cursor);
624 m_cursor = new_cursor;
626 else if (new_cursor > old_cursor)
628 m_line.erase(old_cursor, new_cursor - old_cursor);
629 m_cursor = old_cursor;
635 m_nick_completion_start = 0;
636 m_nick_completion_end = 0;
639 void ChatPrompt::clampView()
641 s32 length = m_line.size();
642 if (length + 1 <= m_cols)
648 m_view = MYMIN(m_view, length + 1 - m_cols);
649 m_view = MYMIN(m_view, m_cursor);
650 m_view = MYMAX(m_view, m_cursor - m_cols + 1);
651 m_view = MYMAX(m_view, 0);
657 ChatBackend::ChatBackend():
658 m_console_buffer(500),
664 ChatBackend::~ChatBackend()
668 void ChatBackend::addMessage(std::wstring name, std::wstring text)
670 // Note: A message may consist of multiple lines, for example the MOTD.
674 std::wstring line = fnd.next(L"\n");
675 m_console_buffer.addLine(name, line);
676 m_recent_buffer.addLine(name, line);
680 void ChatBackend::addUnparsedMessage(std::wstring message)
682 // TODO: Remove the need to parse chat messages client-side, by sending
683 // separate name and text fields in TOCLIENT_CHAT_MESSAGE.
685 if (message.size() >= 2 && message[0] == L'<')
687 std::size_t closing = message.find_first_of(L'>', 1);
688 if (closing != std::wstring::npos &&
689 closing + 2 <= message.size() &&
690 message[closing+1] == L' ')
692 std::wstring name = message.substr(1, closing - 1);
693 std::wstring text = message.substr(closing + 2);
694 addMessage(name, text);
699 // Unable to parse, probably a server message.
700 addMessage(L"", message);
703 ChatBuffer& ChatBackend::getConsoleBuffer()
705 return m_console_buffer;
708 ChatBuffer& ChatBackend::getRecentBuffer()
710 return m_recent_buffer;
713 std::wstring ChatBackend::getRecentChat()
715 std::wostringstream stream;
716 for (u32 i = 0; i < m_recent_buffer.getLineCount(); ++i)
718 const ChatLine& line = m_recent_buffer.getLine(i);
721 if (!line.name.empty())
722 stream << L"<" << line.name << L"> ";
728 ChatPrompt& ChatBackend::getPrompt()
733 void ChatBackend::reformat(u32 cols, u32 rows)
735 m_console_buffer.reformat(cols, rows);
737 // no need to reformat m_recent_buffer, its formatted lines
740 m_prompt.reformat(cols);
743 void ChatBackend::clearRecentChat()
745 m_recent_buffer.clear();
748 void ChatBackend::step(float dtime)
750 m_recent_buffer.step(dtime);
751 m_recent_buffer.deleteByAge(60.0);
753 // no need to age messages in anything but m_recent_buffer
756 void ChatBackend::scroll(s32 rows)
758 m_console_buffer.scroll(rows);
761 void ChatBackend::scrollPageDown()
763 m_console_buffer.scroll(m_console_buffer.getRows());
766 void ChatBackend::scrollPageUp()
768 m_console_buffer.scroll(-m_console_buffer.getRows());