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),
36 m_empty_formatted_line()
38 if (m_scrollback == 0)
40 m_empty_formatted_line.first = true;
43 ChatBuffer::~ChatBuffer()
47 void ChatBuffer::addLine(std::wstring name, std::wstring text)
49 ChatLine line(name, text);
50 m_unformatted.push_back(line);
54 // m_formatted is valid and must be kept valid
55 bool scrolled_at_bottom = (m_scroll == getBottomScrollPos());
56 u32 num_added = formatChatLine(line, m_cols, m_formatted);
57 if (scrolled_at_bottom)
58 m_scroll += num_added;
61 // Limit number of lines by m_scrollback
62 if (m_unformatted.size() > m_scrollback)
64 deleteOldest(m_unformatted.size() - m_scrollback);
68 void ChatBuffer::clear()
70 m_unformatted.clear();
75 u32 ChatBuffer::getLineCount() const
77 return m_unformatted.size();
80 u32 ChatBuffer::getScrollback() const
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 (u32 i = 0; i < m_unformatted.size(); ++i)
95 m_unformatted[i].age += dtime;
99 void ChatBuffer::deleteOldest(u32 count)
101 bool at_bottom = (m_scroll == getBottomScrollPos());
103 u32 del_unformatted = 0;
104 u32 del_formatted = 0;
106 while (count > 0 && del_unformatted < m_unformatted.size())
110 // keep m_formatted in sync
111 if (del_formatted < m_formatted.size())
114 sanity_check(m_formatted[del_formatted].first);
116 while (del_formatted < m_formatted.size() &&
117 !m_formatted[del_formatted].first)
124 m_unformatted.erase(m_unformatted.begin(), m_unformatted.begin() + del_unformatted);
125 m_formatted.erase(m_formatted.begin(), m_formatted.begin() + del_formatted);
128 m_scroll = getBottomScrollPos();
130 scrollAbsolute(m_scroll - del_formatted);
133 void ChatBuffer::deleteByAge(f32 maxAge)
136 while (count < m_unformatted.size() && m_unformatted[count].age > maxAge)
141 u32 ChatBuffer::getColumns() const
146 u32 ChatBuffer::getRows() const
151 void ChatBuffer::reformat(u32 cols, u32 rows)
153 if (cols == 0 || rows == 0)
155 // Clear formatted buffer
161 else if (cols != m_cols || rows != m_rows)
163 // TODO: Avoid reformatting ALL lines (even invisible ones)
164 // each time the console size changes.
166 // Find out the scroll position in *unformatted* lines
167 u32 restore_scroll_unformatted = 0;
168 u32 restore_scroll_formatted = 0;
169 bool at_bottom = (m_scroll == getBottomScrollPos());
172 for (s32 i = 0; i < m_scroll; ++i)
174 if (m_formatted[i].first)
175 ++restore_scroll_unformatted;
179 // If number of columns change, reformat everything
183 for (u32 i = 0; i < m_unformatted.size(); ++i)
185 if (i == restore_scroll_unformatted)
186 restore_scroll_formatted = m_formatted.size();
187 formatChatLine(m_unformatted[i], cols, m_formatted);
191 // Update the console size
195 // Restore the scroll position
202 scrollAbsolute(restore_scroll_formatted);
207 const ChatFormattedLine& ChatBuffer::getFormattedLine(u32 row) const
209 s32 index = m_scroll + (s32) row;
210 if (index >= 0 && index < (s32) m_formatted.size())
211 return m_formatted[index];
213 return m_empty_formatted_line;
216 void ChatBuffer::scroll(s32 rows)
218 scrollAbsolute(m_scroll + rows);
221 void ChatBuffer::scrollAbsolute(s32 scroll)
223 s32 top = getTopScrollPos();
224 s32 bottom = getBottomScrollPos();
229 if (m_scroll > bottom)
233 void ChatBuffer::scrollBottom()
235 m_scroll = getBottomScrollPos();
238 void ChatBuffer::scrollTop()
240 m_scroll = getTopScrollPos();
243 u32 ChatBuffer::formatChatLine(const ChatLine& line, u32 cols,
244 std::vector<ChatFormattedLine>& destination) const
247 std::vector<ChatFormattedFragment> next_frags;
248 ChatFormattedLine next_line;
249 ChatFormattedFragment temp_frag;
252 u32 hanging_indentation = 0;
254 // Format the sender name and produce fragments
255 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 std::wstring name_sanitized = line.name.c_str();
272 // Choose an indentation level
273 if (line.name.empty()) {
275 hanging_indentation = 0;
276 } else if (name_sanitized.size() + 3 <= cols/2) {
277 // Names shorter than about half the console width
278 hanging_indentation = line.name.size() + 3;
281 hanging_indentation = 2;
283 //EnrichedString line_text(line.text);
285 next_line.first = true;
286 bool text_processing = false;
288 // Produce fragments and layout them into lines
289 while (!next_frags.empty() || in_pos < line.text.size())
291 // Layout fragments into lines
292 while (!next_frags.empty())
294 ChatFormattedFragment& frag = next_frags[0];
295 if (frag.text.size() <= cols - out_column)
297 // Fragment fits into current line
298 frag.column = out_column;
299 next_line.fragments.push_back(frag);
300 out_column += frag.text.size();
301 next_frags.erase(next_frags.begin());
305 // Fragment does not fit into current line
307 temp_frag.text = frag.text.substr(0, cols - out_column);
308 temp_frag.column = out_column;
309 //temp_frag.bold = frag.bold;
310 next_line.fragments.push_back(temp_frag);
311 frag.text = frag.text.substr(cols - out_column);
314 if (out_column == cols || text_processing)
316 // End the current line
317 destination.push_back(next_line);
319 next_line.fragments.clear();
320 next_line.first = false;
322 out_column = text_processing ? hanging_indentation : 0;
327 if (in_pos < line.text.size())
329 u32 remaining_in_input = line.text.size() - in_pos;
330 u32 remaining_in_output = cols - out_column;
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 = 1, space_pos = 0;
336 while (frag_length < remaining_in_input &&
337 frag_length < remaining_in_output)
339 if (isspace(line.text.getString()[in_pos + frag_length]))
340 space_pos = frag_length;
343 if (space_pos != 0 && frag_length < remaining_in_input)
344 frag_length = space_pos + 1;
346 temp_frag.text = line.text.substr(in_pos, frag_length);
347 temp_frag.column = 0;
348 //temp_frag.bold = 0;
349 next_frags.push_back(temp_frag);
350 in_pos += frag_length;
351 text_processing = true;
356 if (num_added == 0 || !next_line.fragments.empty())
358 destination.push_back(next_line);
365 s32 ChatBuffer::getTopScrollPos() const
367 s32 formatted_count = (s32) m_formatted.size();
368 s32 rows = (s32) m_rows;
371 else if (formatted_count <= rows)
372 return formatted_count - rows;
377 s32 ChatBuffer::getBottomScrollPos() const
379 s32 formatted_count = (s32) m_formatted.size();
380 s32 rows = (s32) m_rows;
384 return formatted_count - rows;
389 ChatPrompt::ChatPrompt(std::wstring prompt, u32 history_limit):
394 m_history_limit(history_limit),
399 m_nick_completion_start(0),
400 m_nick_completion_end(0)
404 ChatPrompt::~ChatPrompt()
408 void ChatPrompt::input(wchar_t ch)
410 m_line.insert(m_cursor, 1, ch);
413 m_nick_completion_start = 0;
414 m_nick_completion_end = 0;
417 void ChatPrompt::input(const std::wstring &str)
419 m_line.insert(m_cursor, str);
420 m_cursor += str.size();
422 m_nick_completion_start = 0;
423 m_nick_completion_end = 0;
426 void ChatPrompt::addToHistory(std::wstring line)
429 m_history.push_back(line);
430 if (m_history.size() > m_history_limit)
431 m_history.erase(m_history.begin());
432 m_history_index = m_history.size();
435 void ChatPrompt::clear()
440 m_nick_completion_start = 0;
441 m_nick_completion_end = 0;
444 std::wstring ChatPrompt::replace(std::wstring line)
446 std::wstring old_line = m_line;
448 m_view = m_cursor = line.size();
450 m_nick_completion_start = 0;
451 m_nick_completion_end = 0;
455 void ChatPrompt::historyPrev()
457 if (m_history_index != 0)
460 replace(m_history[m_history_index]);
464 void ChatPrompt::historyNext()
466 if (m_history_index + 1 >= m_history.size())
468 m_history_index = m_history.size();
474 replace(m_history[m_history_index]);
478 void ChatPrompt::nickCompletion(const std::list<std::string>& names, bool backwards)
481 // (a) m_nick_completion_start == m_nick_completion_end == 0
482 // Then no previous nick completion is active.
483 // Get the word around the cursor and replace with any nick
484 // that has that word as a prefix.
485 // (b) else, continue a previous nick completion.
486 // m_nick_completion_start..m_nick_completion_end are the
487 // interval where the originally used prefix was. Cycle
488 // through the list of completions of that prefix.
489 u32 prefix_start = m_nick_completion_start;
490 u32 prefix_end = m_nick_completion_end;
491 bool initial = (prefix_end == 0);
494 // no previous nick completion is active
495 prefix_start = prefix_end = m_cursor;
496 while (prefix_start > 0 && !isspace(m_line[prefix_start-1]))
498 while (prefix_end < m_line.size() && !isspace(m_line[prefix_end]))
500 if (prefix_start == prefix_end)
503 std::wstring prefix = m_line.substr(prefix_start, prefix_end - prefix_start);
505 // find all names that start with the selected prefix
506 std::vector<std::wstring> completions;
507 for (std::list<std::string>::const_iterator
509 i != names.end(); ++i)
511 if (str_starts_with(narrow_to_wide(*i), prefix, true))
513 std::wstring completion = narrow_to_wide(*i);
514 if (prefix_start == 0)
516 completions.push_back(completion);
519 if (completions.empty())
522 // find a replacement string and the word that will be replaced
523 u32 word_end = prefix_end;
524 u32 replacement_index = 0;
527 while (word_end < m_line.size() && !isspace(m_line[word_end]))
529 std::wstring word = m_line.substr(prefix_start, word_end - prefix_start);
531 // cycle through completions
532 for (u32 i = 0; i < completions.size(); ++i)
534 if (str_equal(word, completions[i], true))
537 replacement_index = i + completions.size() - 1;
539 replacement_index = i + 1;
540 replacement_index %= completions.size();
545 std::wstring replacement = completions[replacement_index];
546 if (word_end < m_line.size() && isspace(word_end))
549 // replace existing word with replacement word,
550 // place the cursor at the end and record the completion prefix
551 m_line.replace(prefix_start, word_end - prefix_start, replacement);
552 m_cursor = prefix_start + replacement.size();
554 m_nick_completion_start = prefix_start;
555 m_nick_completion_end = prefix_end;
558 void ChatPrompt::reformat(u32 cols)
560 if (cols <= m_prompt.size())
567 s32 length = m_line.size();
568 bool was_at_end = (m_view + m_cols >= length + 1);
569 m_cols = cols - m_prompt.size();
576 std::wstring ChatPrompt::getVisiblePortion() const
578 return m_prompt + m_line.substr(m_view, m_cols);
581 s32 ChatPrompt::getVisibleCursorPosition() const
583 return m_cursor - m_view + m_prompt.size();
586 void ChatPrompt::cursorOperation(CursorOp op, CursorOpDir dir, CursorOpScope scope)
588 s32 old_cursor = m_cursor;
589 s32 new_cursor = m_cursor;
591 s32 length = m_line.size();
592 s32 increment = (dir == CURSOROP_DIR_RIGHT) ? 1 : -1;
595 case CURSOROP_SCOPE_CHARACTER:
596 new_cursor += increment;
598 case CURSOROP_SCOPE_WORD:
599 if (dir == CURSOROP_DIR_RIGHT) {
600 // skip one word to the right
601 while (new_cursor < length && isspace(m_line[new_cursor]))
603 while (new_cursor < length && !isspace(m_line[new_cursor]))
605 while (new_cursor < length && isspace(m_line[new_cursor]))
608 // skip one word to the left
609 while (new_cursor >= 1 && isspace(m_line[new_cursor - 1]))
611 while (new_cursor >= 1 && !isspace(m_line[new_cursor - 1]))
615 case CURSOROP_SCOPE_LINE:
616 new_cursor += increment * length;
618 case CURSOROP_SCOPE_SELECTION:
622 new_cursor = MYMAX(MYMIN(new_cursor, length), 0);
626 m_cursor = new_cursor;
629 case CURSOROP_DELETE:
630 if (m_cursor_len > 0) { // Delete selected text first
631 m_line.erase(m_cursor, m_cursor_len);
633 m_cursor = MYMIN(new_cursor, old_cursor);
634 m_line.erase(m_cursor, abs(new_cursor - old_cursor));
638 case CURSOROP_SELECT:
639 if (scope == CURSOROP_SCOPE_LINE) {
641 m_cursor_len = length;
643 m_cursor = MYMIN(new_cursor, old_cursor);
644 m_cursor_len += abs(new_cursor - old_cursor);
645 m_cursor_len = MYMIN(m_cursor_len, length - m_cursor);
652 m_nick_completion_start = 0;
653 m_nick_completion_end = 0;
656 void ChatPrompt::clampView()
658 s32 length = m_line.size();
659 if (length + 1 <= m_cols)
665 m_view = MYMIN(m_view, length + 1 - m_cols);
666 m_view = MYMIN(m_view, m_cursor);
667 m_view = MYMAX(m_view, m_cursor - m_cols + 1);
668 m_view = MYMAX(m_view, 0);
674 ChatBackend::ChatBackend():
675 m_console_buffer(500),
681 ChatBackend::~ChatBackend()
685 void ChatBackend::addMessage(std::wstring name, std::wstring text)
687 // Note: A message may consist of multiple lines, for example the MOTD.
689 while (!fnd.at_end())
691 std::wstring line = fnd.next(L"\n");
692 m_console_buffer.addLine(name, line);
693 m_recent_buffer.addLine(name, line);
697 void ChatBackend::addUnparsedMessage(std::wstring message)
699 // TODO: Remove the need to parse chat messages client-side, by sending
700 // separate name and text fields in TOCLIENT_CHAT_MESSAGE.
702 if (message.size() >= 2 && message[0] == L'<')
704 std::size_t closing = message.find_first_of(L'>', 1);
705 if (closing != std::wstring::npos &&
706 closing + 2 <= message.size() &&
707 message[closing+1] == L' ')
709 std::wstring name = message.substr(1, closing - 1);
710 std::wstring text = message.substr(closing + 2);
711 addMessage(name, text);
716 // Unable to parse, probably a server message.
717 addMessage(L"", message);
720 ChatBuffer& ChatBackend::getConsoleBuffer()
722 return m_console_buffer;
725 ChatBuffer& ChatBackend::getRecentBuffer()
727 return m_recent_buffer;
730 EnrichedString ChatBackend::getRecentChat()
732 EnrichedString result;
733 for (u32 i = 0; i < m_recent_buffer.getLineCount(); ++i)
735 const ChatLine& line = m_recent_buffer.getLine(i);
738 if (!line.name.empty()) {
748 ChatPrompt& ChatBackend::getPrompt()
753 void ChatBackend::reformat(u32 cols, u32 rows)
755 m_console_buffer.reformat(cols, rows);
757 // no need to reformat m_recent_buffer, its formatted lines
760 m_prompt.reformat(cols);
763 void ChatBackend::clearRecentChat()
765 m_recent_buffer.clear();
768 void ChatBackend::step(float dtime)
770 m_recent_buffer.step(dtime);
771 m_recent_buffer.deleteByAge(60.0);
773 // no need to age messages in anything but m_recent_buffer
776 void ChatBackend::scroll(s32 rows)
778 m_console_buffer.scroll(rows);
781 void ChatBackend::scrollPageDown()
783 m_console_buffer.scroll(m_console_buffer.getRows());
786 void ChatBackend::scrollPageUp()
788 m_console_buffer.scroll(-(s32)m_console_buffer.getRows());