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.
22 #include "util/strfnd.h"
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()); // pre-condition
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 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())
109 // keep m_formatted in sync
110 if (del_formatted < m_formatted.size())
113 sanity_check(m_formatted[del_formatted].first);
115 while (del_formatted < m_formatted.size() &&
116 !m_formatted[del_formatted].first)
123 m_unformatted.erase(m_unformatted.begin(), m_unformatted.begin() + del_unformatted);
124 m_formatted.erase(m_formatted.begin(), m_formatted.begin() + del_formatted);
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::getColumns() const
145 u32 ChatBuffer::getRows() const
150 void ChatBuffer::reformat(u32 cols, u32 rows)
152 if (cols == 0 || rows == 0)
154 // Clear formatted buffer
160 else if (cols != m_cols || rows != m_rows)
162 // TODO: Avoid reformatting ALL lines (even invisible ones)
163 // each time the console size changes.
165 // Find out the scroll position in *unformatted* lines
166 u32 restore_scroll_unformatted = 0;
167 u32 restore_scroll_formatted = 0;
168 bool at_bottom = (m_scroll == getBottomScrollPos());
171 for (s32 i = 0; i < m_scroll; ++i)
173 if (m_formatted[i].first)
174 ++restore_scroll_unformatted;
178 // If number of columns change, reformat everything
182 for (u32 i = 0; i < m_unformatted.size(); ++i)
184 if (i == restore_scroll_unformatted)
185 restore_scroll_formatted = m_formatted.size();
186 formatChatLine(m_unformatted[i], cols, m_formatted);
190 // Update the console size
194 // Restore the scroll position
201 scrollAbsolute(restore_scroll_formatted);
206 const ChatFormattedLine& ChatBuffer::getFormattedLine(u32 row) const
208 s32 index = m_scroll + (s32) row;
209 if (index >= 0 && index < (s32) m_formatted.size())
210 return m_formatted[index];
212 return m_empty_formatted_line;
215 void ChatBuffer::scroll(s32 rows)
217 scrollAbsolute(m_scroll + rows);
220 void ChatBuffer::scrollAbsolute(s32 scroll)
222 s32 top = getTopScrollPos();
223 s32 bottom = getBottomScrollPos();
228 if (m_scroll > bottom)
232 void ChatBuffer::scrollBottom()
234 m_scroll = getBottomScrollPos();
237 void ChatBuffer::scrollTop()
239 m_scroll = getTopScrollPos();
242 u32 ChatBuffer::formatChatLine(const ChatLine& line, u32 cols,
243 std::vector<ChatFormattedLine>& destination) const
246 std::vector<ChatFormattedFragment> next_frags;
247 ChatFormattedLine next_line;
248 ChatFormattedFragment temp_frag;
251 u32 hanging_indentation = 0;
253 // Format the sender name and produce fragments
254 if (!line.name.empty())
256 temp_frag.text = L"<";
257 temp_frag.column = 0;
258 //temp_frag.bold = 0;
259 next_frags.push_back(temp_frag);
260 temp_frag.text = line.name;
261 temp_frag.column = 0;
262 //temp_frag.bold = 1;
263 next_frags.push_back(temp_frag);
264 temp_frag.text = L"> ";
265 temp_frag.column = 0;
266 //temp_frag.bold = 0;
267 next_frags.push_back(temp_frag);
270 // Choose an indentation level
271 if (line.name.empty())
274 hanging_indentation = 0;
276 else if (line.name.size() + 3 <= cols/2)
278 // Names shorter than about half the console width
279 hanging_indentation = line.name.size() + 3;
284 hanging_indentation = 2;
287 next_line.first = true;
288 bool text_processing = false;
290 // Produce fragments and layout them into lines
291 while (!next_frags.empty() || in_pos < line.text.size())
293 // Layout fragments into lines
294 while (!next_frags.empty())
296 ChatFormattedFragment& frag = next_frags[0];
297 if (frag.text.size() <= cols - out_column)
299 // Fragment fits into current line
300 frag.column = out_column;
301 next_line.fragments.push_back(frag);
302 out_column += frag.text.size();
303 next_frags.erase(next_frags.begin());
307 // Fragment does not fit into current line
309 temp_frag.text = frag.text.substr(0, cols - out_column);
310 temp_frag.column = out_column;
311 //temp_frag.bold = frag.bold;
312 next_line.fragments.push_back(temp_frag);
313 frag.text = frag.text.substr(cols - out_column);
316 if (out_column == cols || text_processing)
318 // End the current line
319 destination.push_back(next_line);
321 next_line.fragments.clear();
322 next_line.first = false;
324 out_column = text_processing ? hanging_indentation : 0;
329 if (in_pos < line.text.size())
331 u32 remaining_in_input = line.text.size() - in_pos;
332 u32 remaining_in_output = cols - out_column;
334 // Determine a fragment length <= the minimum of
335 // remaining_in_{in,out}put. Try to end the fragment
336 // on a word boundary.
337 u32 frag_length = 1, space_pos = 0;
338 while (frag_length < remaining_in_input &&
339 frag_length < remaining_in_output)
341 if (isspace(line.text[in_pos + frag_length]))
342 space_pos = frag_length;
345 if (space_pos != 0 && frag_length < remaining_in_input)
346 frag_length = space_pos + 1;
348 temp_frag.text = line.text.substr(in_pos, frag_length);
349 temp_frag.column = 0;
350 //temp_frag.bold = 0;
351 next_frags.push_back(temp_frag);
352 in_pos += frag_length;
353 text_processing = true;
358 if (num_added == 0 || !next_line.fragments.empty())
360 destination.push_back(next_line);
367 s32 ChatBuffer::getTopScrollPos() const
369 s32 formatted_count = (s32) m_formatted.size();
370 s32 rows = (s32) m_rows;
373 else if (formatted_count <= rows)
374 return formatted_count - rows;
379 s32 ChatBuffer::getBottomScrollPos() const
381 s32 formatted_count = (s32) m_formatted.size();
382 s32 rows = (s32) m_rows;
386 return formatted_count - rows;
391 ChatPrompt::ChatPrompt(std::wstring prompt, u32 history_limit):
396 m_history_limit(history_limit),
401 m_nick_completion_start(0),
402 m_nick_completion_end(0)
406 ChatPrompt::~ChatPrompt()
410 void ChatPrompt::input(wchar_t ch)
412 m_line.insert(m_cursor, 1, ch);
415 m_nick_completion_start = 0;
416 m_nick_completion_end = 0;
419 void ChatPrompt::input(const std::wstring &str)
421 m_line.insert(m_cursor, str);
422 m_cursor += str.size();
424 m_nick_completion_start = 0;
425 m_nick_completion_end = 0;
428 void ChatPrompt::addToHistory(std::wstring line)
431 m_history.push_back(line);
432 if (m_history.size() > m_history_limit)
433 m_history.erase(m_history.begin());
434 m_history_index = m_history.size();
437 void ChatPrompt::clear()
442 m_nick_completion_start = 0;
443 m_nick_completion_end = 0;
446 std::wstring ChatPrompt::replace(std::wstring line)
448 std::wstring old_line = m_line;
450 m_view = m_cursor = line.size();
452 m_nick_completion_start = 0;
453 m_nick_completion_end = 0;
457 void ChatPrompt::historyPrev()
459 if (m_history_index != 0)
462 replace(m_history[m_history_index]);
466 void ChatPrompt::historyNext()
468 if (m_history_index + 1 >= m_history.size())
470 m_history_index = m_history.size();
476 replace(m_history[m_history_index]);
480 void ChatPrompt::nickCompletion(const std::list<std::string>& names, bool backwards)
483 // (a) m_nick_completion_start == m_nick_completion_end == 0
484 // Then no previous nick completion is active.
485 // Get the word around the cursor and replace with any nick
486 // that has that word as a prefix.
487 // (b) else, continue a previous nick completion.
488 // m_nick_completion_start..m_nick_completion_end are the
489 // interval where the originally used prefix was. Cycle
490 // through the list of completions of that prefix.
491 u32 prefix_start = m_nick_completion_start;
492 u32 prefix_end = m_nick_completion_end;
493 bool initial = (prefix_end == 0);
496 // no previous nick completion is active
497 prefix_start = prefix_end = m_cursor;
498 while (prefix_start > 0 && !isspace(m_line[prefix_start-1]))
500 while (prefix_end < m_line.size() && !isspace(m_line[prefix_end]))
502 if (prefix_start == prefix_end)
505 std::wstring prefix = m_line.substr(prefix_start, prefix_end - prefix_start);
507 // find all names that start with the selected prefix
508 std::vector<std::wstring> completions;
509 for (std::list<std::string>::const_iterator
511 i != names.end(); ++i)
513 if (str_starts_with(narrow_to_wide(*i), prefix, true))
515 std::wstring completion = narrow_to_wide(*i);
516 if (prefix_start == 0)
518 completions.push_back(completion);
521 if (completions.empty())
524 // find a replacement string and the word that will be replaced
525 u32 word_end = prefix_end;
526 u32 replacement_index = 0;
529 while (word_end < m_line.size() && !isspace(m_line[word_end]))
531 std::wstring word = m_line.substr(prefix_start, word_end - prefix_start);
533 // cycle through completions
534 for (u32 i = 0; i < completions.size(); ++i)
536 if (str_equal(word, completions[i], true))
539 replacement_index = i + completions.size() - 1;
541 replacement_index = i + 1;
542 replacement_index %= completions.size();
547 std::wstring replacement = completions[replacement_index];
548 if (word_end < m_line.size() && isspace(word_end))
551 // replace existing word with replacement word,
552 // place the cursor at the end and record the completion prefix
553 m_line.replace(prefix_start, word_end - prefix_start, replacement);
554 m_cursor = prefix_start + replacement.size();
556 m_nick_completion_start = prefix_start;
557 m_nick_completion_end = prefix_end;
560 void ChatPrompt::reformat(u32 cols)
562 if (cols <= m_prompt.size())
569 s32 length = m_line.size();
570 bool was_at_end = (m_view + m_cols >= length + 1);
571 m_cols = cols - m_prompt.size();
578 std::wstring ChatPrompt::getVisiblePortion() const
580 return m_prompt + m_line.substr(m_view, m_cols);
583 s32 ChatPrompt::getVisibleCursorPosition() const
585 return m_cursor - m_view + m_prompt.size();
588 void ChatPrompt::cursorOperation(CursorOp op, CursorOpDir dir, CursorOpScope scope)
590 s32 old_cursor = m_cursor;
591 s32 new_cursor = m_cursor;
593 s32 length = m_line.size();
594 s32 increment = (dir == CURSOROP_DIR_RIGHT) ? 1 : -1;
597 case CURSOROP_SCOPE_CHARACTER:
598 new_cursor += increment;
600 case CURSOROP_SCOPE_WORD:
601 if (dir == CURSOROP_DIR_RIGHT) {
602 // skip one word to the right
603 while (new_cursor < length && isspace(m_line[new_cursor]))
605 while (new_cursor < length && !isspace(m_line[new_cursor]))
607 while (new_cursor < length && isspace(m_line[new_cursor]))
610 // skip one word to the left
611 while (new_cursor >= 1 && isspace(m_line[new_cursor - 1]))
613 while (new_cursor >= 1 && !isspace(m_line[new_cursor - 1]))
617 case CURSOROP_SCOPE_LINE:
618 new_cursor += increment * length;
620 case CURSOROP_SCOPE_SELECTION:
624 new_cursor = MYMAX(MYMIN(new_cursor, length), 0);
628 m_cursor = new_cursor;
631 case CURSOROP_DELETE:
632 if (m_cursor_len > 0) { // Delete selected text first
633 m_line.erase(m_cursor, m_cursor_len);
635 m_cursor = MYMIN(new_cursor, old_cursor);
636 m_line.erase(m_cursor, abs(new_cursor - old_cursor));
640 case CURSOROP_SELECT:
641 if (scope == CURSOROP_SCOPE_LINE) {
643 m_cursor_len = length;
645 m_cursor = MYMIN(new_cursor, old_cursor);
646 m_cursor_len += abs(new_cursor - old_cursor);
647 m_cursor_len = MYMIN(m_cursor_len, length - m_cursor);
654 m_nick_completion_start = 0;
655 m_nick_completion_end = 0;
658 void ChatPrompt::clampView()
660 s32 length = m_line.size();
661 if (length + 1 <= m_cols)
667 m_view = MYMIN(m_view, length + 1 - m_cols);
668 m_view = MYMIN(m_view, m_cursor);
669 m_view = MYMAX(m_view, m_cursor - m_cols + 1);
670 m_view = MYMAX(m_view, 0);
676 ChatBackend::ChatBackend():
677 m_console_buffer(500),
683 ChatBackend::~ChatBackend()
687 void ChatBackend::addMessage(std::wstring name, std::wstring text)
689 name = unescape_enriched(name);
690 text = unescape_enriched(text);
692 // Note: A message may consist of multiple lines, for example the MOTD.
694 while (!fnd.at_end())
696 std::wstring line = fnd.next(L"\n");
697 m_console_buffer.addLine(name, line);
698 m_recent_buffer.addLine(name, line);
702 void ChatBackend::addUnparsedMessage(std::wstring message)
704 // TODO: Remove the need to parse chat messages client-side, by sending
705 // separate name and text fields in TOCLIENT_CHAT_MESSAGE.
707 if (message.size() >= 2 && message[0] == L'<')
709 std::size_t closing = message.find_first_of(L'>', 1);
710 if (closing != std::wstring::npos &&
711 closing + 2 <= message.size() &&
712 message[closing+1] == L' ')
714 std::wstring name = message.substr(1, closing - 1);
715 std::wstring text = message.substr(closing + 2);
716 addMessage(name, text);
721 // Unable to parse, probably a server message.
722 addMessage(L"", message);
725 ChatBuffer& ChatBackend::getConsoleBuffer()
727 return m_console_buffer;
730 ChatBuffer& ChatBackend::getRecentBuffer()
732 return m_recent_buffer;
735 std::wstring ChatBackend::getRecentChat()
737 std::wostringstream stream;
738 for (u32 i = 0; i < m_recent_buffer.getLineCount(); ++i)
740 const ChatLine& line = m_recent_buffer.getLine(i);
743 if (!line.name.empty())
744 stream << L"<" << line.name << L"> ";
750 ChatPrompt& ChatBackend::getPrompt()
755 void ChatBackend::reformat(u32 cols, u32 rows)
757 m_console_buffer.reformat(cols, rows);
759 // no need to reformat m_recent_buffer, its formatted lines
762 m_prompt.reformat(cols);
765 void ChatBackend::clearRecentChat()
767 m_recent_buffer.clear();
770 void ChatBackend::step(float dtime)
772 m_recent_buffer.step(dtime);
773 m_recent_buffer.deleteByAge(60.0);
775 // no need to age messages in anything but m_recent_buffer
778 void ChatBackend::scroll(s32 rows)
780 m_console_buffer.scroll(rows);
783 void ChatBackend::scrollPageDown()
785 m_console_buffer.scroll(m_console_buffer.getRows());
788 void ChatBackend::scrollPageUp()
790 m_console_buffer.scroll(-(s32)m_console_buffer.getRows());