xref: /haiku/src/apps/terminal/BasicTerminalBuffer.cpp (revision 3b07762c548ec4016dea480d1061577cd15ec614)
1 /*
2  * Copyright 2013, Haiku, Inc. All rights reserved.
3  * Copyright 2008-2010, Ingo Weinhold, ingo_weinhold@gmx.de.
4  * Distributed under the terms of the MIT License.
5  *
6  * Authors:
7  *		Ingo Weinhold, ingo_weinhold@gmx.de
8  *		Siarzhuk Zharski, zharik@gmx.li
9  */
10 
11 #include "BasicTerminalBuffer.h"
12 
13 #include <alloca.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <fcntl.h>
17 #include <string.h>
18 
19 #include <algorithm>
20 
21 #include <StackOrHeapArray.h>
22 #include <String.h>
23 
24 #include "TermConst.h"
25 #include "TerminalCharClassifier.h"
26 #include "TerminalLine.h"
27 
28 
29 static const UTF8Char kSpaceChar(' ');
30 
31 // Soft size limits for the terminal buffer. The constants defined in
32 // TermConst.h are rather for the Terminal in general (i.e. the GUI).
33 static const int32 kMinRowCount = 2;
34 static const int32 kMaxRowCount = 1024;
35 static const int32 kMinColumnCount = 4;
36 static const int32 kMaxColumnCount = 1024;
37 
38 
39 #define ALLOC_LINE_ON_STACK(width)	\
40 	((TerminalLine*)alloca(sizeof(TerminalLine)	\
41 		+ sizeof(TerminalCell) * ((width) - 1)))
42 
43 
44 static inline int32
45 restrict_value(int32 value, int32 min, int32 max)
46 {
47 	return value < min ? min : (value > max ? max : value);
48 }
49 
50 
51 // #pragma mark - private inline methods
52 
53 
54 inline int32
55 BasicTerminalBuffer::_LineIndex(int32 index) const
56 {
57 	return (index + fScreenOffset) % fHeight;
58 }
59 
60 
61 inline TerminalLine*
62 BasicTerminalBuffer::_LineAt(int32 index) const
63 {
64 	return fScreen[_LineIndex(index)];
65 }
66 
67 
68 inline TerminalLine*
69 BasicTerminalBuffer::_HistoryLineAt(int32 index, TerminalLine* lineBuffer) const
70 {
71 	if (index >= fHeight)
72 		return NULL;
73 
74 	if (index < 0 && fHistory != NULL)
75 		return fHistory->GetTerminalLineAt(-index - 1, lineBuffer);
76 
77 	return _LineAt(index + fHeight);
78 }
79 
80 
81 inline void
82 BasicTerminalBuffer::_Invalidate(int32 top, int32 bottom)
83 {
84 //debug_printf("%p->BasicTerminalBuffer::_Invalidate(%ld, %ld)\n", this, top, bottom);
85 	fDirtyInfo.ExtendDirtyRegion(top, bottom);
86 
87 	if (!fDirtyInfo.messageSent) {
88 		NotifyListener();
89 		fDirtyInfo.messageSent = true;
90 	}
91 }
92 
93 
94 inline void
95 BasicTerminalBuffer::_CursorChanged()
96 {
97 	if (!fDirtyInfo.messageSent) {
98 		NotifyListener();
99 		fDirtyInfo.messageSent = true;
100 	}
101 }
102 
103 
104 // #pragma mark - public methods
105 
106 
107 BasicTerminalBuffer::BasicTerminalBuffer()
108 	:
109 	fWidth(0),
110 	fHeight(0),
111 	fScrollTop(0),
112 	fScrollBottom(0),
113 	fScreen(NULL),
114 	fScreenOffset(0),
115 	fHistory(NULL),
116 	fAttributes(0),
117 	fSoftWrappedCursor(false),
118 	fOverwriteMode(false),
119 	fAlternateScreenActive(false),
120 	fOriginMode(false),
121 	fSavedOriginMode(false),
122 	fTabStops(NULL),
123 	fEncoding(M_UTF8),
124 	fCaptureFile(-1)
125 {
126 }
127 
128 
129 BasicTerminalBuffer::~BasicTerminalBuffer()
130 {
131 	delete fHistory;
132 	_FreeLines(fScreen, fHeight);
133 	delete[] fTabStops;
134 
135 	if (fCaptureFile >= 0)
136 		close(fCaptureFile);
137 }
138 
139 
140 status_t
141 BasicTerminalBuffer::Init(int32 width, int32 height, int32 historySize)
142 {
143 	status_t error;
144 
145 	fWidth = width;
146 	fHeight = height;
147 
148 	fScrollTop = 0;
149 	fScrollBottom = fHeight - 1;
150 
151 	fCursor.x = 0;
152 	fCursor.y = 0;
153 	fSoftWrappedCursor = false;
154 
155 	fScreenOffset = 0;
156 
157 	fOverwriteMode = true;
158 	fAlternateScreenActive = false;
159 	fOriginMode = fSavedOriginMode = false;
160 
161 	fScreen = _AllocateLines(width, height);
162 	if (fScreen == NULL)
163 		return B_NO_MEMORY;
164 
165 	if (historySize > 0) {
166 		fHistory = new(std::nothrow) HistoryBuffer;
167 		if (fHistory == NULL)
168 			return B_NO_MEMORY;
169 
170 		error = fHistory->Init(width, historySize);
171 		if (error != B_OK)
172 			return error;
173 	}
174 
175 	error = _ResetTabStops(fWidth);
176 	if (error != B_OK)
177 		return error;
178 
179 	for (int32 i = 0; i < fHeight; i++)
180 		fScreen[i]->Clear();
181 
182 	fDirtyInfo.Reset();
183 
184 	return B_OK;
185 }
186 
187 
188 status_t
189 BasicTerminalBuffer::ResizeTo(int32 width, int32 height)
190 {
191 	return ResizeTo(width, height, fHistory != NULL ? fHistory->Capacity() : 0);
192 }
193 
194 
195 status_t
196 BasicTerminalBuffer::ResizeTo(int32 width, int32 height, int32 historyCapacity)
197 {
198 	if (height < kMinRowCount || height > kMaxRowCount
199 			|| width < kMinColumnCount || width > kMaxColumnCount) {
200 		return B_BAD_VALUE;
201 	}
202 
203 	if (width == fWidth && height == fHeight)
204 		return SetHistoryCapacity(historyCapacity);
205 
206 	if (fAlternateScreenActive)
207 		return _ResizeSimple(width, height, historyCapacity);
208 
209 	return _ResizeRewrap(width, height, historyCapacity);
210 }
211 
212 
213 status_t
214 BasicTerminalBuffer::SetHistoryCapacity(int32 historyCapacity)
215 {
216 	return _ResizeHistory(fWidth, historyCapacity);
217 }
218 
219 
220 void
221 BasicTerminalBuffer::Clear(bool resetCursor)
222 {
223 	fSoftWrappedCursor = false;
224 	fScreenOffset = 0;
225 	_ClearLines(0, fHeight - 1);
226 
227 	if (resetCursor)
228 		fCursor.SetTo(0, 0);
229 
230 	if (fHistory != NULL)
231 		fHistory->Clear();
232 
233 	fDirtyInfo.linesScrolled = 0;
234 	_Invalidate(0, fHeight - 1);
235 }
236 
237 
238 void
239 BasicTerminalBuffer::SynchronizeWith(const BasicTerminalBuffer* other,
240 	int32 offset, int32 dirtyTop, int32 dirtyBottom)
241 {
242 //debug_printf("BasicTerminalBuffer::SynchronizeWith(%p, %ld, %ld - %ld)\n",
243 //other, offset, dirtyTop, dirtyBottom);
244 
245 	// intersect the visible region with the dirty region
246 	int32 first = 0;
247 	int32 last = fHeight - 1;
248 	dirtyTop -= offset;
249 	dirtyBottom -= offset;
250 
251 	if (first > dirtyBottom || dirtyTop > last)
252 		return;
253 
254 	if (first < dirtyTop)
255 		first = dirtyTop;
256 	if (last > dirtyBottom)
257 		last = dirtyBottom;
258 
259 	// update the dirty lines
260 //debug_printf("  updating: %ld - %ld\n", first, last);
261 	for (int32 i = first; i <= last; i++) {
262 		TerminalLine* destLine = _LineAt(i);
263 		TerminalLine* sourceLine = other->_HistoryLineAt(i + offset, destLine);
264 		if (sourceLine != NULL) {
265 			if (sourceLine != destLine) {
266 				destLine->length = sourceLine->length;
267 				destLine->attributes = sourceLine->attributes;
268 				destLine->softBreak = sourceLine->softBreak;
269 				if (destLine->length > 0) {
270 					memcpy(destLine->cells, sourceLine->cells,
271 						fWidth * sizeof(TerminalCell));
272 				}
273 			} else {
274 				// The source line was a history line and has been copied
275 				// directly into destLine.
276 			}
277 		} else
278 			destLine->Clear(fAttributes, fWidth);
279 	}
280 }
281 
282 
283 bool
284 BasicTerminalBuffer::IsFullWidthChar(int32 row, int32 column) const
285 {
286 	TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
287 	TerminalLine* line = _HistoryLineAt(row, lineBuffer);
288 	return line != NULL && column > 0 && column < line->length
289 		&& (line->cells[column - 1].attributes & A_WIDTH) != 0;
290 }
291 
292 
293 int
294 BasicTerminalBuffer::GetChar(int32 row, int32 column, UTF8Char& character,
295 	uint32& attributes) const
296 {
297 	TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
298 	TerminalLine* line = _HistoryLineAt(row, lineBuffer);
299 	if (line == NULL)
300 		return NO_CHAR;
301 
302 	if (column < 0 || column >= line->length)
303 		return NO_CHAR;
304 
305 	if (column > 0 && (line->cells[column - 1].attributes & A_WIDTH) != 0)
306 		return IN_STRING;
307 
308 	TerminalCell& cell = line->cells[column];
309 	character = cell.character;
310 	attributes = cell.attributes;
311 	return A_CHAR;
312 }
313 
314 
315 void
316 BasicTerminalBuffer::GetCellAttributes(int32 row, int32 column,
317 	uint32& attributes, uint32& count) const
318 {
319 	count = 0;
320 	TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
321 	TerminalLine* line = _HistoryLineAt(row, lineBuffer);
322 	if (line == NULL || column < 0)
323 		return;
324 
325 	int32 c = column;
326 	for (; c < fWidth; c++) {
327 		TerminalCell& cell = line->cells[c];
328 		if (c > column && attributes != cell.attributes)
329 			break;
330 		attributes = cell.attributes;
331 	}
332 	count = c - column;
333 }
334 
335 
336 int32
337 BasicTerminalBuffer::GetString(int32 row, int32 firstColumn, int32 lastColumn,
338 	char* buffer, uint32& attributes) const
339 {
340 	TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
341 	TerminalLine* line = _HistoryLineAt(row, lineBuffer);
342 	if (line == NULL)
343 		return 0;
344 
345 	if (lastColumn >= line->length)
346 		lastColumn = line->length - 1;
347 
348 	int32 column = firstColumn;
349 	if (column <= lastColumn)
350 		attributes = line->cells[column].attributes;
351 
352 	for (; column <= lastColumn; column++) {
353 		TerminalCell& cell = line->cells[column];
354 		if (cell.attributes != attributes)
355 			break;
356 
357 		int32 bytes = cell.character.ByteCount();
358 		for (int32 i = 0; i < bytes; i++)
359 			*buffer++ = cell.character.bytes[i];
360 	}
361 
362 	*buffer = '\0';
363 
364 	return column - firstColumn;
365 }
366 
367 
368 void
369 BasicTerminalBuffer::GetStringFromRegion(BString& string, const TermPos& start,
370 	const TermPos& end) const
371 {
372 //debug_printf("BasicTerminalBuffer::GetStringFromRegion((%ld, %ld), (%ld, %ld))\n",
373 //start.x, start.y, end.x, end.y);
374 	if (start >= end)
375 		return;
376 
377 	TermPos pos(start);
378 
379 	if (IsFullWidthChar(pos.y, pos.x))
380 		pos.x--;
381 
382 	// get all but the last line
383 	while (pos.y < end.y) {
384 		TerminalLine* line = _GetPartialLineString(string, pos.y, pos.x,
385 			fWidth);
386 		if (line != NULL && !line->softBreak)
387 			string.Append('\n', 1);
388 		pos.x = 0;
389 		pos.y++;
390 	}
391 
392 	// get the last line, if not empty
393 	if (end.x > 0)
394 		_GetPartialLineString(string, end.y, pos.x, end.x);
395 }
396 
397 
398 bool
399 BasicTerminalBuffer::FindWord(const TermPos& pos,
400 	TerminalCharClassifier* classifier, bool findNonWords, TermPos& _start,
401 	TermPos& _end) const
402 {
403 	int32 x = pos.x;
404 	int32 y = pos.y;
405 
406 	TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
407 	TerminalLine* line = _HistoryLineAt(y, lineBuffer);
408 	if (line == NULL || x < 0 || x >= fWidth)
409 		return false;
410 
411 	if (x >= line->length) {
412 		// beyond the end of the line -- select all space
413 		if (!findNonWords)
414 			return false;
415 
416 		_start.SetTo(line->length, y);
417 		_end.SetTo(fWidth, y);
418 		return true;
419 	}
420 
421 	if (x > 0 && IS_WIDTH(line->cells[x - 1].attributes))
422 		x--;
423 
424 	// get the char type at the given position
425 	int type = classifier->Classify(line->cells[x].character);
426 
427 	// check whether we are supposed to find words only
428 	if (type != CHAR_TYPE_WORD_CHAR && !findNonWords)
429 		return false;
430 
431 	// find the beginning
432 	TermPos start(x, y);
433 	TermPos end(x + (IS_WIDTH(line->cells[x].attributes)
434 				? FULL_WIDTH : HALF_WIDTH), y);
435 	for (;;) {
436 		TermPos previousPos = start;
437 		if (!_PreviousLinePos(lineBuffer, line, previousPos)
438 			|| classifier->Classify(line->cells[previousPos.x].character)
439 				!= type) {
440 			break;
441 		}
442 
443 		start = previousPos;
444 	}
445 
446 	// find the end
447 	line = _HistoryLineAt(end.y, lineBuffer);
448 
449 	for (;;) {
450 		TermPos nextPos = end;
451 		if (!_NormalizeLinePos(lineBuffer, line, nextPos))
452 			break;
453 
454 		if (classifier->Classify(line->cells[nextPos.x].character) != type)
455 			break;
456 
457 		nextPos.x += IS_WIDTH(line->cells[nextPos.x].attributes)
458 			? FULL_WIDTH : HALF_WIDTH;
459 		end = nextPos;
460 	}
461 
462 	_start = start;
463 	_end = end;
464 	return true;
465 }
466 
467 
468 bool
469 BasicTerminalBuffer::PreviousLinePos(TermPos& pos) const
470 {
471 	TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
472 	TerminalLine* line = _HistoryLineAt(pos.y, lineBuffer);
473 	if (line == NULL || pos.x < 0 || pos.x >= fWidth)
474 		return false;
475 
476 	return _PreviousLinePos(lineBuffer, line, pos);
477 }
478 
479 
480 bool
481 BasicTerminalBuffer::NextLinePos(TermPos& pos, bool normalize) const
482 {
483 	TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
484 	TerminalLine* line = _HistoryLineAt(pos.y, lineBuffer);
485 	if (line == NULL || pos.x < 0 || pos.x > fWidth)
486 		return false;
487 
488 	if (!_NormalizeLinePos(lineBuffer, line, pos))
489 		return false;
490 
491 	pos.x += IS_WIDTH(line->cells[pos.x].attributes) ? FULL_WIDTH : HALF_WIDTH;
492 	return !normalize || _NormalizeLinePos(lineBuffer, line, pos);
493 }
494 
495 
496 int32
497 BasicTerminalBuffer::LineLength(int32 index) const
498 {
499 	TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
500 	TerminalLine* line = _HistoryLineAt(index, lineBuffer);
501 	return line != NULL ? line->length : 0;
502 }
503 
504 
505 int32
506 BasicTerminalBuffer::GetLineColor(int32 index) const
507 {
508 	TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
509 	TerminalLine* line = _HistoryLineAt(index, lineBuffer);
510 	return line != NULL ? line->attributes : 0;
511 }
512 
513 
514 bool
515 BasicTerminalBuffer::Find(const char* _pattern, const TermPos& start,
516 	bool forward, bool caseSensitive, bool matchWord, TermPos& _matchStart,
517 	TermPos& _matchEnd) const
518 {
519 //debug_printf("BasicTerminalBuffer::Find(\"%s\", (%ld, %ld), forward: %d, case: %d, "
520 //"word: %d)\n", _pattern, start.x, start.y, forward, caseSensitive, matchWord);
521 	// normalize pos, so that _NextChar() and _PreviousChar() are happy
522 	TermPos pos(start);
523 	TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
524 	TerminalLine* line = _HistoryLineAt(pos.y, lineBuffer);
525 	if (line != NULL) {
526 		if (forward) {
527 			while (line != NULL && pos.x >= line->length && line->softBreak) {
528 				pos.x = 0;
529 				pos.y++;
530 				line = _HistoryLineAt(pos.y, lineBuffer);
531 			}
532 		} else {
533 			if (pos.x > line->length)
534 				pos.x = line->length;
535 		}
536 	}
537 
538 	int32 patternByteLen = strlen(_pattern);
539 
540 	// convert pattern to UTF8Char array
541 	BStackOrHeapArray<UTF8Char, 64> pattern(patternByteLen);
542 	int32 patternLen = 0;
543 	while (*_pattern != '\0') {
544 		int32 charLen = UTF8Char::ByteCount(*_pattern);
545 		if (charLen > 0) {
546 			pattern[patternLen].SetTo(_pattern, charLen);
547 
548 			// if not case sensitive, convert to lower case
549 			if (!caseSensitive && charLen == 1)
550 				pattern[patternLen] = pattern[patternLen].ToLower();
551 
552 			patternLen++;
553 			_pattern += charLen;
554 		} else
555 			_pattern++;
556 	}
557 //debug_printf("  pattern byte len: %ld, pattern len: %ld\n", patternByteLen, patternLen);
558 
559 	if (patternLen == 0)
560 		return false;
561 
562 	// reverse pattern, if searching backward
563 	if (!forward) {
564 		for (int32 i = 0; i < patternLen / 2; i++)
565 			std::swap(pattern[i], pattern[patternLen - i - 1]);
566 	}
567 
568 	// search loop
569 	int32 matchIndex = 0;
570 	TermPos matchStart;
571 	while (true) {
572 //debug_printf("    (%ld, %ld): matchIndex: %ld\n", pos.x, pos.y, matchIndex);
573 		TermPos previousPos(pos);
574 		UTF8Char c;
575 		if (!(forward ? _NextChar(pos, c) : _PreviousChar(pos, c)))
576 			return false;
577 
578 		if (caseSensitive ? (c == pattern[matchIndex])
579 				: (c.ToLower() == pattern[matchIndex])) {
580 			if (matchIndex == 0)
581 				matchStart = previousPos;
582 
583 			matchIndex++;
584 
585 			if (matchIndex == patternLen) {
586 //debug_printf("      match!\n");
587 				// compute the match range
588 				TermPos matchEnd(pos);
589 				if (!forward)
590 					std::swap(matchStart, matchEnd);
591 
592 				// check word match
593 				if (matchWord) {
594 					TermPos tempPos(matchStart);
595 					if ((_PreviousChar(tempPos, c) && !c.IsSpace())
596 						|| (_NextChar(tempPos = matchEnd, c) && !c.IsSpace())) {
597 //debug_printf("      but no word match!\n");
598 						continue;
599 					}
600 				}
601 
602 				_matchStart = matchStart;
603 				_matchEnd = matchEnd;
604 //debug_printf("  -> (%ld, %ld) - (%ld, %ld)\n", matchStart.x, matchStart.y,
605 //matchEnd.x, matchEnd.y);
606 				return true;
607 			}
608 		} else if (matchIndex > 0) {
609 			// continue after the position where we started matching
610 			pos = matchStart;
611 			if (forward)
612 				_NextChar(pos, c);
613 			else
614 				_PreviousChar(pos, c);
615 			matchIndex = 0;
616 		}
617 	}
618 }
619 
620 
621 void
622 BasicTerminalBuffer::InsertChar(UTF8Char c)
623 {
624 //debug_printf("BasicTerminalBuffer::InsertChar('%.*s' (%d), %#lx)\n",
625 //(int)c.ByteCount(), c.bytes, c.bytes[0], attributes);
626 	int32 width = c.IsFullWidth() ? FULL_WIDTH : HALF_WIDTH;
627 
628 	if (fSoftWrappedCursor || (fCursor.x + width) > fWidth)
629 		_SoftBreakLine();
630 	else
631 		_PadLineToCursor();
632 
633 	fSoftWrappedCursor = false;
634 
635 	if (!fOverwriteMode)
636 		_InsertGap(width);
637 
638 	TerminalLine* line = _LineAt(fCursor.y);
639 	line->cells[fCursor.x].character = c;
640 	line->cells[fCursor.x].attributes
641 		= fAttributes | (width == FULL_WIDTH ? A_WIDTH : 0);
642 
643 	if (line->length < fCursor.x + width)
644 		line->length = fCursor.x + width;
645 
646 	_Invalidate(fCursor.y, fCursor.y);
647 
648 	fCursor.x += width;
649 
650 // TODO: Deal correctly with full-width chars! We must take care not to
651 // overwrite half of a full-width char. This holds also for other methods.
652 
653 	if (fCursor.x == fWidth) {
654 		fCursor.x -= width;
655 		fSoftWrappedCursor = true;
656 	}
657 }
658 
659 
660 void
661 BasicTerminalBuffer::FillScreen(UTF8Char c, uint32 attributes)
662 {
663 	uint32 width = HALF_WIDTH;
664 	if (c.IsFullWidth()) {
665 		attributes |= A_WIDTH;
666 		width = FULL_WIDTH;
667 	}
668 
669 	fSoftWrappedCursor = false;
670 
671 	for (int32 y = 0; y < fHeight; y++) {
672 		TerminalLine *line = _LineAt(y);
673 		for (int32 x = 0; x < fWidth / (int32)width; x++) {
674 			line->cells[x].character = c;
675 			line->cells[x].attributes = attributes;
676 		}
677 		line->length = fWidth / width;
678 	}
679 
680 	_Invalidate(0, fHeight - 1);
681 }
682 
683 
684 void
685 BasicTerminalBuffer::InsertCR()
686 {
687 	TerminalLine* line = _LineAt(fCursor.y);
688 
689 	line->attributes = fAttributes;
690 	line->softBreak = false;
691 	fSoftWrappedCursor = false;
692 	fCursor.x = 0;
693 	_Invalidate(fCursor.y, fCursor.y);
694 	_CursorChanged();
695 }
696 
697 
698 void
699 BasicTerminalBuffer::InsertLF()
700 {
701 	fSoftWrappedCursor = false;
702 
703 	// If we're at the end of the scroll region, scroll. Otherwise just advance
704 	// the cursor.
705 	if (fCursor.y == fScrollBottom) {
706 		_Scroll(fScrollTop, fScrollBottom, 1);
707 	} else {
708 		if (fCursor.y < fHeight - 1)
709 			fCursor.y++;
710 		_CursorChanged();
711 	}
712 }
713 
714 
715 void
716 BasicTerminalBuffer::InsertRI()
717 {
718 	fSoftWrappedCursor = false;
719 
720 	// If we're at the beginning of the scroll region, scroll. Otherwise just
721 	// reverse the cursor.
722 	if (fCursor.y == fScrollTop) {
723 		_Scroll(fScrollTop, fScrollBottom, -1);
724 	} else {
725 		if (fCursor.y > 0)
726 			fCursor.y--;
727 		_CursorChanged();
728 	}
729 }
730 
731 
732 void
733 BasicTerminalBuffer::InsertTab()
734 {
735 	int32 x;
736 
737 	fSoftWrappedCursor = false;
738 
739 	// Find the next tab stop
740 	for (x = fCursor.x + 1; x < fWidth && !fTabStops[x]; x++)
741 		;
742 	// Ensure x stayx within the line bounds
743 	x = restrict_value(x, 0, fWidth - 1);
744 
745 	if (x != fCursor.x) {
746 		TerminalLine* line = _LineAt(fCursor.y);
747 		for (int32 i = fCursor.x; i <= x; i++) {
748 			line->cells[i].character = ' ';
749 			line->cells[i].attributes = fAttributes;
750 		}
751 		fCursor.x = x;
752 		if (line->length < fCursor.x)
753 			line->length = fCursor.x;
754 		_CursorChanged();
755 	}
756 }
757 
758 
759 void
760 BasicTerminalBuffer::InsertLines(int32 numLines)
761 {
762 	if (fCursor.y >= fScrollTop && fCursor.y < fScrollBottom) {
763 		fSoftWrappedCursor = false;
764 		_Scroll(fCursor.y, fScrollBottom, -numLines);
765 	}
766 }
767 
768 
769 void
770 BasicTerminalBuffer::SetInsertMode(int flag)
771 {
772 	fOverwriteMode = flag == MODE_OVER;
773 }
774 
775 
776 void
777 BasicTerminalBuffer::InsertSpace(int32 num)
778 {
779 // TODO: Deal with full-width chars!
780 	if (fCursor.x + num > fWidth)
781 		num = fWidth - fCursor.x;
782 
783 	if (num > 0) {
784 		fSoftWrappedCursor = false;
785 		_PadLineToCursor();
786 		_InsertGap(num);
787 
788 		TerminalLine* line = _LineAt(fCursor.y);
789 		for (int32 i = fCursor.x; i < fCursor.x + num; i++) {
790 			line->cells[i].character = kSpaceChar;
791 			line->cells[i].attributes = line->cells[fCursor.x - 1].attributes;
792 		}
793 		line->attributes = fAttributes;
794 
795 		_Invalidate(fCursor.y, fCursor.y);
796 	}
797 }
798 
799 
800 void
801 BasicTerminalBuffer::EraseCharsFrom(int32 first, int32 numChars)
802 {
803 	TerminalLine* line = _LineAt(fCursor.y);
804 
805 	int32 end = min_c(first + numChars, fWidth);
806 	for (int32 i = first; i < end; i++)
807 		line->cells[i].attributes = fAttributes;
808 
809 	line->attributes = fAttributes;
810 
811 	fSoftWrappedCursor = false;
812 
813 	end = min_c(first + numChars, line->length);
814 	if (first > 0 && IS_WIDTH(line->cells[first - 1].attributes))
815 		first--;
816 	if (end > 0 && IS_WIDTH(line->cells[end - 1].attributes))
817 		end++;
818 
819 	for (int32 i = first; i < end; i++) {
820 		line->cells[i].character = kSpaceChar;
821 		line->cells[i].attributes = fAttributes;
822 	}
823 
824 	_Invalidate(fCursor.y, fCursor.y);
825 }
826 
827 
828 void
829 BasicTerminalBuffer::EraseAbove()
830 {
831 	// Clear the preceding lines.
832 	if (fCursor.y > 0)
833 		_ClearLines(0, fCursor.y - 1);
834 
835 	fSoftWrappedCursor = false;
836 
837 	// Delete the chars on the cursor line before (and including) the cursor.
838 	TerminalLine* line = _LineAt(fCursor.y);
839 	if (fCursor.x < line->length) {
840 		int32 to = fCursor.x;
841 		if (IS_WIDTH(line->cells[fCursor.x].attributes))
842 			to++;
843 		for (int32 i = 0; i <= to; i++) {
844 			line->cells[i].attributes = fAttributes;
845 			line->cells[i].character = kSpaceChar;
846 		}
847 	} else
848 		line->Clear(fAttributes, fWidth);
849 
850 	_Invalidate(fCursor.y, fCursor.y);
851 }
852 
853 
854 void
855 BasicTerminalBuffer::EraseBelow()
856 {
857 	fSoftWrappedCursor = false;
858 
859 	// Clear the following lines.
860 	if (fCursor.y < fHeight - 1)
861 		_ClearLines(fCursor.y + 1, fHeight - 1);
862 
863 	// Delete the chars on the cursor line after (and including) the cursor.
864 	DeleteColumns();
865 }
866 
867 
868 void
869 BasicTerminalBuffer::EraseAll()
870 {
871 	fSoftWrappedCursor = false;
872 	_Scroll(0, fHeight - 1, fHeight);
873 }
874 
875 
876 void
877 BasicTerminalBuffer::DeleteChars(int32 numChars)
878 {
879 	fSoftWrappedCursor = false;
880 
881 	TerminalLine* line = _LineAt(fCursor.y);
882 	if (fCursor.x < line->length) {
883 		if (fCursor.x + numChars < line->length) {
884 			int32 left = line->length - fCursor.x - numChars;
885 			memmove(line->cells + fCursor.x, line->cells + fCursor.x + numChars,
886 				left * sizeof(TerminalCell));
887 			line->length = fCursor.x + left;
888 			// process BCE on freed tail cells
889 			for (int i = 0; i < numChars; i++)
890 				line->cells[fCursor.x + left + i].attributes = fAttributes;
891 		} else {
892 			// process BCE on freed tail cells
893 			for (int i = 0; i < line->length - fCursor.x; i++)
894 				line->cells[fCursor.x + i].attributes = fAttributes;
895 			// remove all remaining chars
896 			line->length = fCursor.x;
897 		}
898 
899 		_Invalidate(fCursor.y, fCursor.y);
900 	}
901 }
902 
903 
904 void
905 BasicTerminalBuffer::DeleteColumnsFrom(int32 first)
906 {
907 	fSoftWrappedCursor = false;
908 
909 	TerminalLine* line = _LineAt(fCursor.y);
910 
911 	for (int32 i = first; i < fWidth; i++)
912 		line->cells[i].attributes = fAttributes;
913 
914 	if (first <= line->length) {
915 		line->length = first;
916 		line->attributes = fAttributes;
917 	}
918 	_Invalidate(fCursor.y, fCursor.y);
919 }
920 
921 
922 void
923 BasicTerminalBuffer::DeleteLines(int32 numLines)
924 {
925 	if (fCursor.y >= fScrollTop && fCursor.y <= fScrollBottom) {
926 		fSoftWrappedCursor = false;
927 		_Scroll(fCursor.y, fScrollBottom, numLines);
928 	}
929 }
930 
931 
932 void
933 BasicTerminalBuffer::SaveCursor()
934 {
935 	fSavedCursors.push(fCursor);
936 }
937 
938 
939 void
940 BasicTerminalBuffer::RestoreCursor()
941 {
942 	if (fSavedCursors.size() == 0)
943 		return;
944 
945 	_SetCursor(fSavedCursors.top().x, fSavedCursors.top().y, true);
946 	fSavedCursors.pop();
947 }
948 
949 
950 void
951 BasicTerminalBuffer::SetScrollRegion(int32 top, int32 bottom)
952 {
953 	fScrollTop = restrict_value(top, 0, fHeight - 1);
954 	fScrollBottom = restrict_value(bottom, fScrollTop, fHeight - 1);
955 
956 	// also sets the cursor position
957 	_SetCursor(0, 0, false);
958 }
959 
960 
961 void
962 BasicTerminalBuffer::SetOriginMode(bool enabled)
963 {
964 	fOriginMode = enabled;
965 	_SetCursor(0, 0, false);
966 }
967 
968 
969 void
970 BasicTerminalBuffer::SaveOriginMode()
971 {
972 	fSavedOriginMode = fOriginMode;
973 }
974 
975 
976 void
977 BasicTerminalBuffer::RestoreOriginMode()
978 {
979 	fOriginMode = fSavedOriginMode;
980 }
981 
982 
983 void
984 BasicTerminalBuffer::SetTabStop(int32 x)
985 {
986 	x = restrict_value(x, 0, fWidth - 1);
987 	fTabStops[x] = true;
988 }
989 
990 
991 void
992 BasicTerminalBuffer::ClearTabStop(int32 x)
993 {
994 	x = restrict_value(x, 0, fWidth - 1);
995 	fTabStops[x] = false;
996 }
997 
998 
999 void
1000 BasicTerminalBuffer::ClearAllTabStops()
1001 {
1002 	for (int32 i = 0; i < fWidth; i++)
1003 		fTabStops[i] = false;
1004 }
1005 
1006 
1007 void
1008 BasicTerminalBuffer::NotifyListener()
1009 {
1010 	// Implemented by derived classes.
1011 }
1012 
1013 
1014 // #pragma mark - private methods
1015 
1016 
1017 void
1018 BasicTerminalBuffer::_SetCursor(int32 x, int32 y, bool absolute)
1019 {
1020 //debug_printf("BasicTerminalBuffer::_SetCursor(%d, %d)\n", x, y);
1021 	fSoftWrappedCursor = false;
1022 
1023 	x = restrict_value(x, 0, fWidth - 1);
1024 	if (fOriginMode && !absolute) {
1025 		y += fScrollTop;
1026 		y = restrict_value(y, fScrollTop, fScrollBottom);
1027 	} else {
1028 		y = restrict_value(y, 0, fHeight - 1);
1029 	}
1030 
1031 	if (x != fCursor.x || y != fCursor.y) {
1032 		fCursor.x = x;
1033 		fCursor.y = y;
1034 		_CursorChanged();
1035 	}
1036 }
1037 
1038 
1039 void
1040 BasicTerminalBuffer::_InvalidateAll()
1041 {
1042 	fDirtyInfo.invalidateAll = true;
1043 
1044 	if (!fDirtyInfo.messageSent) {
1045 		NotifyListener();
1046 		fDirtyInfo.messageSent = true;
1047 	}
1048 }
1049 
1050 
1051 /* static */ TerminalLine**
1052 BasicTerminalBuffer::_AllocateLines(int32 width, int32 count)
1053 {
1054 	TerminalLine** lines = (TerminalLine**)malloc(sizeof(TerminalLine*) * count);
1055 	if (lines == NULL)
1056 		return NULL;
1057 
1058 	for (int32 i = 0; i < count; i++) {
1059 		const int32 size = sizeof(TerminalLine)
1060 			+ sizeof(TerminalCell) * (width - 1);
1061 		lines[i] = (TerminalLine*)malloc(size);
1062 		if (lines[i] == NULL) {
1063 			_FreeLines(lines, i);
1064 			return NULL;
1065 		}
1066 		memset(lines[i], 0, size);
1067 	}
1068 
1069 	return lines;
1070 }
1071 
1072 
1073 /* static */ void
1074 BasicTerminalBuffer::_FreeLines(TerminalLine** lines, int32 count)
1075 {
1076 	if (lines != NULL) {
1077 		for (int32 i = 0; i < count; i++)
1078 			free(lines[i]);
1079 
1080 		free(lines);
1081 	}
1082 }
1083 
1084 
1085 void
1086 BasicTerminalBuffer::_ClearLines(int32 first, int32 last)
1087 {
1088 	int32 firstCleared = -1;
1089 	int32 lastCleared = -1;
1090 
1091 	for (int32 i = first; i <= last; i++) {
1092 		TerminalLine* line = _LineAt(i);
1093 		if (line->length > 0) {
1094 			if (firstCleared == -1)
1095 				firstCleared = i;
1096 			lastCleared = i;
1097 		}
1098 
1099 		line->Clear(fAttributes, fWidth);
1100 	}
1101 
1102 	if (firstCleared >= 0)
1103 		_Invalidate(firstCleared, lastCleared);
1104 }
1105 
1106 
1107 status_t
1108 BasicTerminalBuffer::_ResizeHistory(int32 width, int32 historyCapacity)
1109 {
1110 	if (width == fWidth && historyCapacity == HistoryCapacity())
1111 		return B_OK;
1112 
1113 	if (historyCapacity <= 0) {
1114 		// new history capacity is 0 -- delete the old history object
1115 		delete fHistory;
1116 		fHistory = NULL;
1117 
1118 		return B_OK;
1119 	}
1120 
1121 	HistoryBuffer* history = new(std::nothrow) HistoryBuffer;
1122 	if (history == NULL)
1123 		return B_NO_MEMORY;
1124 
1125 	status_t error = history->Init(width, historyCapacity);
1126 	if (error != B_OK) {
1127 		delete history;
1128 		return error;
1129 	}
1130 
1131 	// Transfer the lines from the old history to the new one.
1132 	if (fHistory != NULL) {
1133 		int32 historySize = min_c(HistorySize(), historyCapacity);
1134 		TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
1135 		for (int32 i = historySize - 1; i >= 0; i--) {
1136 			TerminalLine* line = fHistory->GetTerminalLineAt(i, lineBuffer);
1137 			if (line->length > width)
1138 				_TruncateLine(line, width);
1139 			history->AddLine(line);
1140 		}
1141 	}
1142 
1143 	delete fHistory;
1144 	fHistory = history;
1145 
1146 	return B_OK;
1147 }
1148 
1149 
1150 status_t
1151 BasicTerminalBuffer::_ResizeSimple(int32 width, int32 height,
1152 	int32 historyCapacity)
1153 {
1154 //debug_printf("BasicTerminalBuffer::_ResizeSimple(): (%ld, %ld) -> "
1155 //"(%ld, %ld)\n", fWidth, fHeight, width, height);
1156 	if (width == fWidth && height == fHeight)
1157 		return B_OK;
1158 
1159 	if (width != fWidth || historyCapacity != HistoryCapacity()) {
1160 		status_t error = _ResizeHistory(width, historyCapacity);
1161 		if (error != B_OK)
1162 			return error;
1163 	}
1164 
1165 	TerminalLine** lines = _AllocateLines(width, height);
1166 	if (lines == NULL)
1167 		return B_NO_MEMORY;
1168 		// NOTE: If width or history capacity changed, the object will be in
1169 		// an invalid state, since the history will already use the new values.
1170 
1171 	int32 endLine = min_c(fHeight, height);
1172 	int32 firstLine = 0;
1173 
1174 	if (height < fHeight) {
1175 		if (endLine <= fCursor.y) {
1176 			endLine = fCursor.y + 1;
1177 			firstLine = endLine - height;
1178 		}
1179 
1180 		// push the first lines to the history
1181 		if (fHistory != NULL) {
1182 			for (int32 i = 0; i < firstLine; i++) {
1183 				TerminalLine* line = _LineAt(i);
1184 				if (width < fWidth)
1185 					_TruncateLine(line, width);
1186 				fHistory->AddLine(line);
1187 			}
1188 		}
1189 	}
1190 
1191 	// copy the lines we keep
1192 	for (int32 i = firstLine; i < endLine; i++) {
1193 		TerminalLine* sourceLine = _LineAt(i);
1194 		TerminalLine* destLine = lines[i - firstLine];
1195 		if (width < fWidth)
1196 			_TruncateLine(sourceLine, width);
1197 		memcpy(destLine, sourceLine, (int32)sizeof(TerminalLine)
1198 			+ (sourceLine->length - 1) * (int32)sizeof(TerminalCell));
1199 	}
1200 
1201 	// clear the remaining lines
1202 	for (int32 i = endLine - firstLine; i < height; i++)
1203 		lines[i]->Clear(fAttributes, width);
1204 
1205 	_FreeLines(fScreen, fHeight);
1206 	fScreen = lines;
1207 
1208 	if (fWidth != width) {
1209 		status_t error = _ResetTabStops(width);
1210 		if (error != B_OK)
1211 			return error;
1212 	}
1213 
1214 	fWidth = width;
1215 	fHeight = height;
1216 
1217 	fScrollTop = 0;
1218 	fScrollBottom = fHeight - 1;
1219 	fOriginMode = fSavedOriginMode = false;
1220 
1221 	fScreenOffset = 0;
1222 
1223 	if (fCursor.x > width)
1224 		fCursor.x = width;
1225 	fCursor.y -= firstLine;
1226 	fSoftWrappedCursor = false;
1227 
1228 	return B_OK;
1229 }
1230 
1231 
1232 status_t
1233 BasicTerminalBuffer::_ResizeRewrap(int32 width, int32 height,
1234 	int32 historyCapacity)
1235 {
1236 //debug_printf("BasicTerminalBuffer::_ResizeRewrap(): (%ld, %ld, history: %ld) -> "
1237 //"(%ld, %ld, history: %ld)\n", fWidth, fHeight, HistoryCapacity(), width, height,
1238 //historyCapacity);
1239 
1240 	// The width stays the same. _ResizeSimple() does exactly what we need.
1241 	if (width == fWidth)
1242 		return _ResizeSimple(width, height, historyCapacity);
1243 
1244 	// The width changes. We have to allocate a new line array, a new history
1245 	// and re-wrap all lines.
1246 
1247 	TerminalLine** screen = _AllocateLines(width, height);
1248 	if (screen == NULL)
1249 		return B_NO_MEMORY;
1250 
1251 	HistoryBuffer* history = NULL;
1252 
1253 	if (historyCapacity > 0) {
1254 		history = new(std::nothrow) HistoryBuffer;
1255 		if (history == NULL) {
1256 			_FreeLines(screen, height);
1257 			return B_NO_MEMORY;
1258 		}
1259 
1260 		status_t error = history->Init(width, historyCapacity);
1261 		if (error != B_OK) {
1262 			_FreeLines(screen, height);
1263 			delete history;
1264 			return error;
1265 		}
1266 	}
1267 
1268 	int32 historySize = HistorySize();
1269 	int32 totalLines = historySize + fHeight;
1270 
1271 	// re-wrap
1272 	TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
1273 	TermPos cursor;
1274 	int32 destIndex = 0;
1275 	int32 sourceIndex = 0;
1276 	int32 sourceX = 0;
1277 	int32 destTotalLines = 0;
1278 	int32 destScreenOffset = 0;
1279 	int32 maxDestTotalLines = INT_MAX;
1280 	bool newDestLine = true;
1281 	bool cursorSeen = false;
1282 	TerminalLine* sourceLine = _HistoryLineAt(-historySize, lineBuffer);
1283 
1284 	while (sourceIndex < totalLines) {
1285 		TerminalLine* destLine = screen[destIndex];
1286 
1287 		if (newDestLine) {
1288 			// Clear a new dest line before using it. If we're about to
1289 			// overwrite an previously written line, we push it to the
1290 			// history first, though.
1291 			if (history != NULL && destTotalLines >= height)
1292 				history->AddLine(screen[destIndex]);
1293 			destLine->Clear(fAttributes, width);
1294 			newDestLine = false;
1295 		}
1296 
1297 		int32 sourceLeft = sourceLine->length - sourceX;
1298 		int32 destLeft = width - destLine->length;
1299 //debug_printf("    source: %ld, left: %ld, dest: %ld, left: %ld\n",
1300 //sourceIndex, sourceLeft, destIndex, destLeft);
1301 
1302 		if (sourceIndex == historySize && sourceX == 0) {
1303 			destScreenOffset = destTotalLines;
1304 			if (destLeft == 0 && sourceLeft > 0)
1305 				destScreenOffset++;
1306 			maxDestTotalLines = destScreenOffset + height;
1307 //debug_printf("      destScreenOffset: %ld\n", destScreenOffset);
1308 		}
1309 
1310 		int32 toCopy = min_c(sourceLeft, destLeft);
1311 		// If the last cell to copy is the first cell of a
1312 		// full-width char, don't copy it yet.
1313 		if (toCopy > 0 && IS_WIDTH(
1314 				sourceLine->cells[sourceX + toCopy - 1].attributes)) {
1315 //debug_printf("      -> last char is full-width -- don't copy it\n");
1316 			toCopy--;
1317 		}
1318 
1319 		// translate the cursor position
1320 		if (fCursor.y + historySize == sourceIndex
1321 			&& fCursor.x >= sourceX
1322 			&& (fCursor.x < sourceX + toCopy
1323 				|| (destLeft >= sourceLeft
1324 					&& sourceX + sourceLeft <= fCursor.x))) {
1325 			cursor.x = destLine->length + fCursor.x - sourceX;
1326 			cursor.y = destTotalLines;
1327 
1328 			if (cursor.x >= width) {
1329 				// The cursor was in free space after the official end
1330 				// of line.
1331 				cursor.x = width - 1;
1332 			}
1333 //debug_printf("      cursor: (%ld, %ld)\n", cursor.x, cursor.y);
1334 
1335 			cursorSeen = true;
1336 		}
1337 
1338 		if (toCopy > 0) {
1339 			memcpy(destLine->cells + destLine->length,
1340 				sourceLine->cells + sourceX, toCopy * sizeof(TerminalCell));
1341 			destLine->length += toCopy;
1342 		}
1343 
1344 		destLine->attributes = sourceLine->attributes;
1345 
1346 		bool nextDestLine = false;
1347 		if (toCopy == sourceLeft) {
1348 			if (!sourceLine->softBreak)
1349 				nextDestLine = true;
1350 			sourceIndex++;
1351 			sourceX = 0;
1352 			sourceLine = _HistoryLineAt(sourceIndex - historySize,
1353 				lineBuffer);
1354 		} else {
1355 			destLine->softBreak = true;
1356 			nextDestLine = true;
1357 			sourceX += toCopy;
1358 		}
1359 
1360 		if (nextDestLine) {
1361 			destIndex = (destIndex + 1) % height;
1362 			destTotalLines++;
1363 			newDestLine = true;
1364 			if (cursorSeen && destTotalLines >= maxDestTotalLines)
1365 				break;
1366 		}
1367 	}
1368 
1369 	// If the last source line had a soft break, the last dest line
1370 	// won't have been counted yet.
1371 	if (!newDestLine) {
1372 		destIndex = (destIndex + 1) % height;
1373 		destTotalLines++;
1374 	}
1375 
1376 //debug_printf("  total lines: %ld -> %ld\n", totalLines, destTotalLines);
1377 
1378 	if (destTotalLines - destScreenOffset > height)
1379 		destScreenOffset = destTotalLines - height;
1380 
1381 	cursor.y -= destScreenOffset;
1382 
1383 	// When there are less lines (starting with the screen offset) than
1384 	// there's room in the screen, clear the remaining screen lines.
1385 	for (int32 i = destTotalLines; i < destScreenOffset + height; i++) {
1386 		// Move the line we're going to clear to the history, if that's a
1387 		// line we've written earlier.
1388 		TerminalLine* line = screen[i % height];
1389 		if (history != NULL && i >= height)
1390 			history->AddLine(line);
1391 		line->Clear(fAttributes, width);
1392 	}
1393 
1394 	// Update the values
1395 	_FreeLines(fScreen, fHeight);
1396 	delete fHistory;
1397 
1398 	fScreen = screen;
1399 	fHistory = history;
1400 
1401 	if (fWidth != width) {
1402 		status_t error = _ResetTabStops(width);
1403 		if (error != B_OK)
1404 			return error;
1405 	}
1406 
1407 //debug_printf("  cursor: (%ld, %ld) -> (%ld, %ld)\n", fCursor.x, fCursor.y,
1408 //cursor.x, cursor.y);
1409 	fCursor.x = cursor.x;
1410 	fCursor.y = cursor.y;
1411 	fSoftWrappedCursor = false;
1412 //debug_printf("  screen offset: %ld -> %ld\n", fScreenOffset, destScreenOffset % height);
1413 	fScreenOffset = destScreenOffset % height;
1414 //debug_printf("  height %ld -> %ld\n", fHeight, height);
1415 //debug_printf("  width %ld -> %ld\n", fWidth, width);
1416 	fHeight = height;
1417 	fWidth = width;
1418 
1419 	fScrollTop = 0;
1420 	fScrollBottom = fHeight - 1;
1421 	fOriginMode = fSavedOriginMode = false;
1422 
1423 	return B_OK;
1424 }
1425 
1426 
1427 status_t
1428 BasicTerminalBuffer::_ResetTabStops(int32 width)
1429 {
1430 	if (fTabStops != NULL)
1431 		delete[] fTabStops;
1432 
1433 	fTabStops = new(std::nothrow) bool[width];
1434 	if (fTabStops == NULL)
1435 		return B_NO_MEMORY;
1436 
1437 	for (int32 i = 0; i < width; i++)
1438 		fTabStops[i] = (i % TAB_WIDTH) == 0;
1439 	return B_OK;
1440 }
1441 
1442 
1443 void
1444 BasicTerminalBuffer::_Scroll(int32 top, int32 bottom, int32 numLines)
1445 {
1446 	if (numLines == 0)
1447 		return;
1448 
1449 	if (numLines > 0) {
1450 		// scroll text up
1451 		if (top == 0) {
1452 			// The lines scrolled out of the screen range are transferred to
1453 			// the history.
1454 
1455 			// add the lines to the history
1456 			if (fHistory != NULL) {
1457 				int32 toHistory = min_c(numLines, bottom - top + 1);
1458 				for (int32 i = 0; i < toHistory; i++)
1459 					fHistory->AddLine(_LineAt(i));
1460 
1461 				if (toHistory < numLines)
1462 					fHistory->AddEmptyLines(numLines - toHistory);
1463 			}
1464 
1465 			if (numLines >= bottom - top + 1) {
1466 				// all lines are scrolled out of range -- just clear them
1467 				_ClearLines(top, bottom);
1468 			} else if (bottom == fHeight - 1) {
1469 				// full screen scroll -- update the screen offset and clear new
1470 				// lines
1471 				fScreenOffset = (fScreenOffset + numLines) % fHeight;
1472 				for (int32 i = bottom - numLines + 1; i <= bottom; i++)
1473 					_LineAt(i)->Clear(fAttributes, fWidth);
1474 			} else {
1475 				// Partial screen scroll. We move the screen offset anyway, but
1476 				// have to move the unscrolled lines to their new location.
1477 				// TODO: It may be more efficient to actually move the scrolled
1478 				// lines only (might depend on the number of scrolled/unscrolled
1479 				// lines).
1480 				for (int32 i = fHeight - 1; i > bottom; i--) {
1481 					std::swap(fScreen[_LineIndex(i)],
1482 						fScreen[_LineIndex(i + numLines)]);
1483 				}
1484 
1485 				// update the screen offset and clear the new lines
1486 				fScreenOffset = (fScreenOffset + numLines) % fHeight;
1487 				for (int32 i = bottom - numLines + 1; i <= bottom; i++)
1488 					_LineAt(i)->Clear(fAttributes, fWidth);
1489 			}
1490 
1491 			// scroll/extend dirty range
1492 
1493 			if (fDirtyInfo.dirtyTop != INT_MAX) {
1494 				// If the top or bottom of the dirty region are above the
1495 				// bottom of the scroll region, we have to scroll them up.
1496 				if (fDirtyInfo.dirtyTop <= bottom) {
1497 					fDirtyInfo.dirtyTop -= numLines;
1498 					if (fDirtyInfo.dirtyBottom <= bottom)
1499 						fDirtyInfo.dirtyBottom -= numLines;
1500 				}
1501 
1502 				// numLines above the bottom become dirty
1503 				_Invalidate(bottom - numLines + 1, bottom);
1504 			}
1505 
1506 			fDirtyInfo.linesScrolled += numLines;
1507 
1508 			// invalidate new empty lines
1509 			_Invalidate(bottom + 1 - numLines, bottom);
1510 
1511 			// In case only part of the screen was scrolled, we invalidate also
1512 			// the lines below the scroll region. Those remain unchanged, but
1513 			// we can't convey that they have not been scrolled via
1514 			// TerminalBufferDirtyInfo. So we need to force the view to sync
1515 			// them again.
1516 			if (bottom < fHeight - 1)
1517 				_Invalidate(bottom + 1, fHeight - 1);
1518 		} else if (numLines >= bottom - top + 1) {
1519 			// all lines are completely scrolled out of range -- just clear
1520 			// them
1521 			_ClearLines(top, bottom);
1522 		} else {
1523 			// partial scroll -- clear the lines scrolled out of range and move
1524 			// the other ones
1525 			for (int32 i = top + numLines; i <= bottom; i++) {
1526 				int32 lineToDrop = _LineIndex(i - numLines);
1527 				int32 lineToKeep = _LineIndex(i);
1528 				fScreen[lineToDrop]->Clear(fAttributes, fWidth);
1529 				std::swap(fScreen[lineToDrop], fScreen[lineToKeep]);
1530 			}
1531 			// clear any lines between the two swapped ranges above
1532 			for (int32 i = bottom - numLines + 1; i < top + numLines; i++)
1533 				_LineAt(i)->Clear(fAttributes, fWidth);
1534 
1535 			_Invalidate(top, bottom);
1536 		}
1537 	} else {
1538 		// scroll text down
1539 		numLines = -numLines;
1540 
1541 		if (numLines >= bottom - top + 1) {
1542 			// all lines are completely scrolled out of range -- just clear
1543 			// them
1544 			_ClearLines(top, bottom);
1545 		} else {
1546 			// partial scroll -- clear the lines scrolled out of range and move
1547 			// the other ones
1548 // TODO: When scrolling the whole screen, we could just update fScreenOffset and
1549 // clear the respective lines.
1550 			for (int32 i = bottom - numLines; i >= top; i--) {
1551 				int32 lineToKeep = _LineIndex(i);
1552 				int32 lineToDrop = _LineIndex(i + numLines);
1553 				fScreen[lineToDrop]->Clear(fAttributes, fWidth);
1554 				std::swap(fScreen[lineToDrop], fScreen[lineToKeep]);
1555 			}
1556 			// clear any lines between the two swapped ranges above
1557 			for (int32 i = bottom - numLines + 1; i < top + numLines; i++)
1558 				_LineAt(i)->Clear(fAttributes, fWidth);
1559 
1560 			_Invalidate(top, bottom);
1561 		}
1562 	}
1563 }
1564 
1565 
1566 void
1567 BasicTerminalBuffer::_SoftBreakLine()
1568 {
1569 	TerminalLine* line = _LineAt(fCursor.y);
1570 	line->softBreak = true;
1571 
1572 	fCursor.x = 0;
1573 	if (fCursor.y == fScrollBottom)
1574 		_Scroll(fScrollTop, fScrollBottom, 1);
1575 	else
1576 		fCursor.y++;
1577 }
1578 
1579 
1580 void
1581 BasicTerminalBuffer::_PadLineToCursor()
1582 {
1583 	TerminalLine* line = _LineAt(fCursor.y);
1584 	if (line->length < fCursor.x)
1585 		for (int32 i = line->length; i < fCursor.x; i++)
1586 			line->cells[i].character = kSpaceChar;
1587 }
1588 
1589 
1590 /*static*/ void
1591 BasicTerminalBuffer::_TruncateLine(TerminalLine* line, int32 length)
1592 {
1593 	if (line->length <= length)
1594 		return;
1595 
1596 	if (length > 0 && IS_WIDTH(line->cells[length - 1].attributes))
1597 		length--;
1598 
1599 	line->length = length;
1600 }
1601 
1602 
1603 void
1604 BasicTerminalBuffer::_InsertGap(int32 width)
1605 {
1606 // ASSERT(fCursor.x + width <= fWidth)
1607 	TerminalLine* line = _LineAt(fCursor.y);
1608 
1609 	int32 toMove = min_c(line->length - fCursor.x, fWidth - fCursor.x - width);
1610 	if (toMove > 0) {
1611 		memmove(line->cells + fCursor.x + width,
1612 			line->cells + fCursor.x, toMove * sizeof(TerminalCell));
1613 	}
1614 
1615 	line->length = min_c(line->length + width, fWidth);
1616 }
1617 
1618 
1619 /*!	\a endColumn is not inclusive.
1620 */
1621 TerminalLine*
1622 BasicTerminalBuffer::_GetPartialLineString(BString& string, int32 row,
1623 	int32 startColumn, int32 endColumn) const
1624 {
1625 	TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
1626 	TerminalLine* line = _HistoryLineAt(row, lineBuffer);
1627 	if (line == NULL)
1628 		return NULL;
1629 
1630 	if (endColumn > line->length)
1631 		endColumn = line->length;
1632 
1633 	for (int32 x = startColumn; x < endColumn; x++) {
1634 		const TerminalCell& cell = line->cells[x];
1635 		string.Append(cell.character.bytes, cell.character.ByteCount());
1636 
1637 		if (IS_WIDTH(cell.attributes))
1638 			x++;
1639 	}
1640 
1641 	return line;
1642 }
1643 
1644 
1645 /*!	Decrement \a pos and return the char at that location.
1646 */
1647 bool
1648 BasicTerminalBuffer::_PreviousChar(TermPos& pos, UTF8Char& c) const
1649 {
1650 	pos.x--;
1651 
1652 	TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
1653 	TerminalLine* line = _HistoryLineAt(pos.y, lineBuffer);
1654 
1655 	while (true) {
1656 		if (pos.x < 0) {
1657 			pos.y--;
1658 			line = _HistoryLineAt(pos.y, lineBuffer);
1659 			if (line == NULL)
1660 				return false;
1661 
1662 			pos.x = line->length;
1663 			if (line->softBreak) {
1664 				pos.x--;
1665 			} else {
1666 				c = '\n';
1667 				return true;
1668 			}
1669 		} else {
1670 			c = line->cells[pos.x].character;
1671 			return true;
1672 		}
1673 	}
1674 }
1675 
1676 
1677 /*!	Return the char at \a pos and increment it.
1678 */
1679 bool
1680 BasicTerminalBuffer::_NextChar(TermPos& pos, UTF8Char& c) const
1681 {
1682 	TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
1683 	TerminalLine* line = _HistoryLineAt(pos.y, lineBuffer);
1684 	if (line == NULL)
1685 		return false;
1686 
1687 	if (pos.x >= line->length) {
1688 		c = '\n';
1689 		pos.x = 0;
1690 		pos.y++;
1691 		return true;
1692 	}
1693 
1694 	c = line->cells[pos.x].character;
1695 
1696 	pos.x++;
1697 	while (line != NULL && pos.x >= line->length && line->softBreak) {
1698 		pos.x = 0;
1699 		pos.y++;
1700 		line = _HistoryLineAt(pos.y, lineBuffer);
1701 	}
1702 
1703 	return true;
1704 }
1705 
1706 
1707 bool
1708 BasicTerminalBuffer::_PreviousLinePos(TerminalLine* lineBuffer,
1709 	TerminalLine*& line, TermPos& pos) const
1710 {
1711 	if (--pos.x < 0) {
1712 		// Hit the beginning of the line -- continue at the end of the
1713 		// previous line, if it soft-breaks.
1714 		pos.y--;
1715 		if ((line = _HistoryLineAt(pos.y, lineBuffer)) == NULL
1716 				|| !line->softBreak || line->length == 0) {
1717 			return false;
1718 		}
1719 		pos.x = line->length - 1;
1720 	}
1721 	if (pos.x > 0 && IS_WIDTH(line->cells[pos.x - 1].attributes))
1722 		pos.x--;
1723 
1724 	return true;
1725 }
1726 
1727 
1728 bool
1729 BasicTerminalBuffer::_NormalizeLinePos(TerminalLine* lineBuffer,
1730 	TerminalLine*& line, TermPos& pos) const
1731 {
1732 	if (pos.x < line->length)
1733 		return true;
1734 
1735 	// Hit the end of the line -- if it soft-breaks continue with the
1736 	// next line.
1737 	if (!line->softBreak)
1738 		return false;
1739 
1740 	pos.y++;
1741 	pos.x = 0;
1742 	line = _HistoryLineAt(pos.y, lineBuffer);
1743 	return line != NULL;
1744 }
1745 
1746 
1747 #ifdef USE_DEBUG_SNAPSHOTS
1748 
1749 void
1750 BasicTerminalBuffer::MakeLinesSnapshots(time_t timeStamp, const char* fileName)
1751 {
1752 	BString str("/var/log/");
1753 	struct tm* ts = gmtime(&timeStamp);
1754 	str << ts->tm_hour << ts->tm_min << ts->tm_sec;
1755 	str << fileName;
1756 	FILE* fileOut = fopen(str.String(), "w");
1757 
1758 	bool dumpHistory = false;
1759 	do {
1760 		if (dumpHistory && fHistory == NULL) {
1761 			fprintf(fileOut, "> History is empty <\n");
1762 			break;
1763 		}
1764 
1765 		int countLines = dumpHistory ? fHistory->Size() : fHeight;
1766 		fprintf(fileOut, "> %s lines dump begin <\n",
1767 					dumpHistory ? "History" : "Terminal");
1768 
1769 		TerminalLine* lineBuffer = ALLOC_LINE_ON_STACK(fWidth);
1770 		for (int i = 0; i < countLines; i++) {
1771 			TerminalLine* line = dumpHistory
1772 				? fHistory->GetTerminalLineAt(i, lineBuffer)
1773 					: fScreen[_LineIndex(i)];
1774 
1775 			if (line == NULL) {
1776 				fprintf(fileOut, "line: %d is NULL!!!\n", i);
1777 				continue;
1778 			}
1779 
1780 			fprintf(fileOut, "%02" B_PRId16 ":%02" B_PRId16 ":%08" B_PRIx32 ":\n",
1781 					i, line->length, line->attributes);
1782 			for (int j = 0; j < line->length; j++)
1783 				if (line->cells[j].character.bytes[0] != 0)
1784 					fwrite(line->cells[j].character.bytes, 1,
1785 						line->cells[j].character.ByteCount(), fileOut);
1786 
1787 			fprintf(fileOut, "\n");
1788 			for (int s = 28; s >= 0; s -= 4) {
1789 				for (int j = 0; j < fWidth; j++)
1790 					fprintf(fileOut, "%01" B_PRIx32,
1791 						(line->cells[j].attributes >> s) & 0x0F);
1792 
1793 				fprintf(fileOut, "\n");
1794 			}
1795 
1796 			fprintf(fileOut, "\n");
1797 		}
1798 
1799 		fprintf(fileOut, "> %s lines dump finished <\n",
1800 					dumpHistory ? "History" : "Terminal");
1801 
1802 		dumpHistory = !dumpHistory;
1803 	} while (dumpHistory);
1804 
1805 	fclose(fileOut);
1806 }
1807 
1808 
1809 void
1810 BasicTerminalBuffer::StartStopDebugCapture()
1811 {
1812 	if (fCaptureFile >= 0) {
1813 		close(fCaptureFile);
1814 		fCaptureFile = -1;
1815 		return;
1816 	}
1817 
1818 	time_t timeStamp = time(NULL);
1819 	BString str("/var/log/");
1820 	struct tm* ts = gmtime(&timeStamp);
1821 	str << ts->tm_hour << ts->tm_min << ts->tm_sec;
1822 	str << ".Capture.log";
1823 	fCaptureFile = open(str.String(), O_CREAT | O_WRONLY,
1824 			S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
1825 }
1826 
1827 
1828 void
1829 BasicTerminalBuffer::CaptureChar(char ch)
1830 {
1831 	if (fCaptureFile >= 0)
1832 		write(fCaptureFile, &ch, 1);
1833 }
1834 
1835 #endif
1836