xref: /haiku/src/apps/terminal/TermView.cpp (revision cb837539f5d245cedff238f8894c0ae326c2eaf5)
1 /*
2  * Copyright 2001-2014, Haiku, Inc.
3  * Copyright 2003-2004 Kian Duffy, myob@users.sourceforge.net
4  * Parts Copyright 1998-1999 Kazuho Okui and Takashi Murai.
5  * All rights reserved. Distributed under the terms of the MIT license.
6  *
7  * Authors:
8  *		Stefano Ceccherini, stefano.ceccherini@gmail.com
9  *		Kian Duffy, myob@users.sourceforge.net
10  *		Y.Hayakawa, hida@sawada.riec.tohoku.ac.jp
11  *		Jonathan Schleifer, js@webkeks.org
12  *		Simon South, simon@simonsouth.net
13  *		Ingo Weinhold, ingo_weinhold@gmx.de
14  *		Clemens Zeidler, haiku@Clemens-Zeidler.de
15  *		Siarzhuk Zharski, zharik@gmx.li
16  */
17 
18 
19 #include "TermView.h"
20 
21 #include <signal.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <termios.h>
25 
26 #include <algorithm>
27 #include <new>
28 #include <vector>
29 
30 #include <Alert.h>
31 #include <Application.h>
32 #include <Beep.h>
33 #include <Catalog.h>
34 #include <Clipboard.h>
35 #include <Debug.h>
36 #include <Directory.h>
37 #include <Dragger.h>
38 #include <Input.h>
39 #include <Locale.h>
40 #include <MenuItem.h>
41 #include <Message.h>
42 #include <MessageRunner.h>
43 #include <Node.h>
44 #include <Path.h>
45 #include <PopUpMenu.h>
46 #include <PropertyInfo.h>
47 #include <Region.h>
48 #include <Roster.h>
49 #include <ScrollBar.h>
50 #include <ScrollView.h>
51 #include <String.h>
52 #include <StringView.h>
53 #include <UTF8.h>
54 #include <Window.h>
55 
56 #include "ActiveProcessInfo.h"
57 #include "Colors.h"
58 #include "InlineInput.h"
59 #include "PrefHandler.h"
60 #include "Shell.h"
61 #include "ShellParameters.h"
62 #include "TermApp.h"
63 #include "TermConst.h"
64 #include "TerminalBuffer.h"
65 #include "TerminalCharClassifier.h"
66 #include "TermViewStates.h"
67 #include "VTkeymap.h"
68 
69 
70 #define ROWS_DEFAULT 25
71 #define COLUMNS_DEFAULT 80
72 
73 
74 #undef B_TRANSLATION_CONTEXT
75 #define B_TRANSLATION_CONTEXT "Terminal TermView"
76 
77 static property_info sPropList[] = {
78 	{ "encoding",
79 	{B_GET_PROPERTY, 0},
80 	{B_DIRECT_SPECIFIER, 0},
81 	"get terminal encoding"},
82 	{ "encoding",
83 	{B_SET_PROPERTY, 0},
84 	{B_DIRECT_SPECIFIER, 0},
85 	"set terminal encoding"},
86 	{ "tty",
87 	{B_GET_PROPERTY, 0},
88 	{B_DIRECT_SPECIFIER, 0},
89 	"get tty name."},
90 	{ 0  }
91 };
92 
93 
94 static const uint32 kUpdateSigWinch = 'Rwin';
95 static const uint32 kBlinkCursor = 'BlCr';
96 
97 static const bigtime_t kSyncUpdateGranularity = 100000;	// 0.1 s
98 
99 static const int32 kCursorBlinkIntervals = 3;
100 static const int32 kCursorVisibleIntervals = 2;
101 static const bigtime_t kCursorBlinkInterval = 500000;
102 
103 static const rgb_color kBlackColor = { 0, 0, 0, 255 };
104 static const rgb_color kWhiteColor = { 255, 255, 255, 255 };
105 
106 // secondary mouse button drop
107 const int32 kSecondaryMouseDropAction = 'SMDA';
108 
109 enum {
110 	kInsert,
111 	kChangeDirectory,
112 	kLinkFiles,
113 	kMoveFiles,
114 	kCopyFiles
115 };
116 
117 
118 template<typename Type>
119 static inline Type
120 restrict_value(const Type& value, const Type& min, const Type& max)
121 {
122 	return value < min ? min : (value > max ? max : value);
123 }
124 
125 
126 template<typename Type>
127 static inline Type
128 saturated_add(Type a, Type b)
129 {
130 	const Type max = (Type)(-1);
131 	return (max - a >= b ? a + b : max);
132 }
133 
134 
135 //	#pragma mark - TextBufferSyncLocker
136 
137 
138 class TermView::TextBufferSyncLocker {
139 public:
140 	TextBufferSyncLocker(TermView* view)
141 		:
142 		fView(view)
143 	{
144 		fView->fTextBuffer->Lock();
145 	}
146 
147 	~TextBufferSyncLocker()
148 	{
149 		fView->fTextBuffer->Unlock();
150 
151 		if (fView->fVisibleTextBufferChanged)
152 			fView->_VisibleTextBufferChanged();
153 	}
154 
155 private:
156 	TermView*	fView;
157 };
158 
159 
160 //	#pragma mark - TermView
161 
162 
163 TermView::TermView(BRect frame, const ShellParameters& shellParameters,
164 	int32 historySize)
165 	:
166 	BView(frame, "termview", B_FOLLOW_ALL,
167 		B_WILL_DRAW | B_FRAME_EVENTS | B_FULL_UPDATE_ON_RESIZE),
168 	fListener(NULL),
169 	fColumns(COLUMNS_DEFAULT),
170 	fRows(ROWS_DEFAULT),
171 	fEncoding(M_UTF8),
172 	fActive(false),
173 	fScrBufSize(historySize),
174 	fReportX10MouseEvent(false),
175 	fReportNormalMouseEvent(false),
176 	fReportButtonMouseEvent(false),
177 	fReportAnyMouseEvent(false),
178 	fEnableExtendedMouseCoordinates(false)
179 {
180 	status_t status = _InitObject(shellParameters);
181 	if (status != B_OK)
182 		throw status;
183 	SetTermSize(frame);
184 }
185 
186 
187 TermView::TermView(int rows, int columns,
188 	const ShellParameters& shellParameters, int32 historySize)
189 	:
190 	BView(BRect(0, 0, 0, 0), "termview", B_FOLLOW_ALL,
191 		B_WILL_DRAW | B_FRAME_EVENTS | B_FULL_UPDATE_ON_RESIZE),
192 	fListener(NULL),
193 	fColumns(columns),
194 	fRows(rows),
195 	fEncoding(M_UTF8),
196 	fActive(false),
197 	fScrBufSize(historySize),
198 	fReportX10MouseEvent(false),
199 	fReportNormalMouseEvent(false),
200 	fReportButtonMouseEvent(false),
201 	fReportAnyMouseEvent(false),
202 	fEnableExtendedMouseCoordinates(false)
203 {
204 	status_t status = _InitObject(shellParameters);
205 	if (status != B_OK)
206 		throw status;
207 
208 	ResizeToPreferred();
209 
210 	// TODO: Don't show the dragger, since replicant capabilities
211 	// don't work very well ATM.
212 	/*
213 	BRect rect(0, 0, 16, 16);
214 	rect.OffsetTo(Bounds().right - rect.Width(),
215 		Bounds().bottom - rect.Height());
216 
217 	SetFlags(Flags() | B_DRAW_ON_CHILDREN | B_FOLLOW_ALL);
218 	AddChild(new BDragger(rect, this,
219 		B_FOLLOW_RIGHT|B_FOLLOW_BOTTOM, B_WILL_DRAW));*/
220 }
221 
222 
223 TermView::TermView(BMessage* archive)
224 	:
225 	BView(archive),
226 	fListener(NULL),
227 	fColumns(COLUMNS_DEFAULT),
228 	fRows(ROWS_DEFAULT),
229 	fEncoding(M_UTF8),
230 	fActive(false),
231 	fScrBufSize(1000),
232 	fReportX10MouseEvent(false),
233 	fReportNormalMouseEvent(false),
234 	fReportButtonMouseEvent(false),
235 	fReportAnyMouseEvent(false),
236 	fEnableExtendedMouseCoordinates(false)
237 {
238 	BRect frame = Bounds();
239 
240 	if (archive->FindInt32("encoding", (int32*)&fEncoding) < B_OK)
241 		fEncoding = M_UTF8;
242 	if (archive->FindInt32("columns", (int32*)&fColumns) < B_OK)
243 		fColumns = COLUMNS_DEFAULT;
244 	if (archive->FindInt32("rows", (int32*)&fRows) < B_OK)
245 		fRows = ROWS_DEFAULT;
246 
247 	int32 argc = 0;
248 	if (archive->HasInt32("argc"))
249 		archive->FindInt32("argc", &argc);
250 
251 	const char **argv = new const char*[argc];
252 	for (int32 i = 0; i < argc; i++) {
253 		archive->FindString("argv", i, (const char**)&argv[i]);
254 	}
255 
256 	// TODO: Retrieve colors, history size, etc. from archive
257 	status_t status = _InitObject(ShellParameters(argc, argv));
258 	if (status != B_OK)
259 		throw status;
260 
261 	bool useRect = false;
262 	if ((archive->FindBool("use_rect", &useRect) == B_OK) && useRect)
263 		SetTermSize(frame);
264 
265 	delete[] argv;
266 }
267 
268 
269 /*!	Initializes the object for further use.
270 	The members fRows, fColumns, fEncoding, and fScrBufSize must
271 	already be initialized; they are not touched by this method.
272 */
273 status_t
274 TermView::_InitObject(const ShellParameters& shellParameters)
275 {
276 	SetFlags(Flags() | B_WILL_DRAW | B_FRAME_EVENTS
277 		| B_FULL_UPDATE_ON_RESIZE/* | B_INPUT_METHOD_AWARE*/);
278 
279 	fShell = NULL;
280 	fWinchRunner = NULL;
281 	fCursorBlinkRunner = NULL;
282 	fAutoScrollRunner = NULL;
283 	fResizeRunner = NULL;
284 	fResizeView = NULL;
285 	fCharClassifier = NULL;
286 	fFontWidth = 0;
287 	fFontHeight = 0;
288 	fFontAscent = 0;
289 	fEmulateBold = false;
290 	fAllowBold = true;
291 	fFrameResized = false;
292 	fResizeViewDisableCount = 0;
293 	fLastActivityTime = 0;
294 	fCursorState = 0;
295 	fCursorStyle = BLOCK_CURSOR;
296 	fCursorBlinking = true;
297 	fCursorHidden = false;
298 	fCursor = TermPos(0, 0);
299 	fTextBuffer = NULL;
300 	fVisibleTextBuffer = NULL;
301 	fVisibleTextBufferChanged = false;
302 	fScrollBar = NULL;
303 	fInline = NULL;
304 	fSelectForeColor = kWhiteColor;
305 	fSelectBackColor = kBlackColor;
306 	fScrollOffset = 0;
307 	fLastSyncTime = 0;
308 	fScrolledSinceLastSync = 0;
309 	fSyncRunner = NULL;
310 	fConsiderClockedSync = false;
311 	fSelection.SetHighlighter(this);
312 	fSelection.SetRange(TermPos(0, 0), TermPos(0, 0));
313 	fPrevPos = TermPos(-1, - 1);
314 	fKeymap = NULL;
315 	fKeymapChars = NULL;
316 	fUseOptionAsMetaKey = false;
317 	fInterpretMetaKey = true;
318 	fMetaKeySendsEscape = true;
319 	fReportX10MouseEvent = false;
320 	fReportNormalMouseEvent = false;
321 	fReportButtonMouseEvent = false;
322 	fReportAnyMouseEvent = false;
323 	fEnableExtendedMouseCoordinates = false;
324 	fMouseClipboard = be_clipboard;
325 	fDefaultState = new(std::nothrow) DefaultState(this);
326 	fSelectState = new(std::nothrow) SelectState(this);
327 	fHyperLinkState = new(std::nothrow) HyperLinkState(this);
328 	fHyperLinkMenuState = new(std::nothrow) HyperLinkMenuState(this);
329 	fActiveState = NULL;
330 
331 	fTextBuffer = new(std::nothrow) TerminalBuffer;
332 	if (fTextBuffer == NULL)
333 		return B_NO_MEMORY;
334 
335 	fVisibleTextBuffer = new(std::nothrow) BasicTerminalBuffer;
336 	if (fVisibleTextBuffer == NULL)
337 		return B_NO_MEMORY;
338 
339 	// TODO: Make the special word chars user-settable!
340 	fCharClassifier = new(std::nothrow) DefaultCharClassifier(
341 		kDefaultAdditionalWordCharacters);
342 	if (fCharClassifier == NULL)
343 		return B_NO_MEMORY;
344 
345 	status_t error = fTextBuffer->Init(fColumns, fRows, fScrBufSize);
346 	if (error != B_OK)
347 		return error;
348 	fTextBuffer->SetEncoding(fEncoding);
349 
350 	error = fVisibleTextBuffer->Init(fColumns, fRows + 2, 0);
351 	if (error != B_OK)
352 		return error;
353 
354 	fShell = new (std::nothrow) Shell();
355 	if (fShell == NULL)
356 		return B_NO_MEMORY;
357 
358 	SetTermFont(be_fixed_font);
359 
360 	// set the shell parameters' encoding
361 	ShellParameters modifiedShellParameters(shellParameters);
362 	modifiedShellParameters.SetEncoding(fEncoding);
363 
364 	error = fShell->Open(fRows, fColumns, modifiedShellParameters);
365 
366 	if (error < B_OK)
367 		return error;
368 
369 	error = _AttachShell(fShell);
370 	if (error < B_OK)
371 		return error;
372 
373 	fHighlights.AddItem(&fSelection);
374 
375 	if (fDefaultState == NULL || fSelectState == NULL || fHyperLinkState == NULL
376 		|| fHyperLinkMenuState == NULL) {
377 		return B_NO_MEMORY;
378 	}
379 
380 	SetLowColor(fTextBackColor);
381 	SetViewColor(B_TRANSPARENT_32_BIT);
382 
383 	_NextState(fDefaultState);
384 
385 	return B_OK;
386 }
387 
388 
389 TermView::~TermView()
390 {
391 	Shell* shell = fShell;
392 		// _DetachShell sets fShell to NULL
393 
394 	_DetachShell();
395 
396 	delete fDefaultState;
397 	delete fSelectState;
398 	delete fHyperLinkState;
399 	delete fHyperLinkMenuState;
400 	delete fSyncRunner;
401 	delete fAutoScrollRunner;
402 	delete fCharClassifier;
403 	delete fVisibleTextBuffer;
404 	delete fTextBuffer;
405 	delete shell;
406 }
407 
408 
409 bool
410 TermView::IsShellBusy() const
411 {
412 	return fShell != NULL && fShell->HasActiveProcesses();
413 }
414 
415 
416 bool
417 TermView::GetActiveProcessInfo(ActiveProcessInfo& _info) const
418 {
419 	if (fShell == NULL) {
420 		_info.Unset();
421 		return false;
422 	}
423 
424 	return fShell->GetActiveProcessInfo(_info);
425 }
426 
427 
428 bool
429 TermView::GetShellInfo(ShellInfo& _info) const
430 {
431 	if (fShell == NULL) {
432 		_info = ShellInfo();
433 		return false;
434 	}
435 
436 	_info = fShell->Info();
437 	return true;
438 }
439 
440 
441 /* static */
442 BArchivable *
443 TermView::Instantiate(BMessage* data)
444 {
445 	if (validate_instantiation(data, "TermView")) {
446 		TermView *view = new (std::nothrow) TermView(data);
447 		return view;
448 	}
449 
450 	return NULL;
451 }
452 
453 
454 status_t
455 TermView::Archive(BMessage* data, bool deep) const
456 {
457 	status_t status = BView::Archive(data, deep);
458 	if (status == B_OK)
459 		status = data->AddString("add_on", TERM_SIGNATURE);
460 	if (status == B_OK)
461 		status = data->AddInt32("encoding", (int32)fEncoding);
462 	if (status == B_OK)
463 		status = data->AddInt32("columns", (int32)fColumns);
464 	if (status == B_OK)
465 		status = data->AddInt32("rows", (int32)fRows);
466 
467 	if (data->ReplaceString("class", "TermView") != B_OK)
468 		data->AddString("class", "TermView");
469 
470 	return status;
471 }
472 
473 
474 rgb_color
475 TermView::ForegroundColor()
476 {
477 	return fSelectForeColor;
478 }
479 
480 
481 rgb_color
482 TermView::BackgroundColor()
483 {
484 	return fSelectBackColor;
485 }
486 
487 
488 inline int32
489 TermView::_LineAt(float y)
490 {
491 	int32 location = int32(y + fScrollOffset);
492 
493 	// Make sure negative offsets are rounded towards the lower neighbor, too.
494 	if (location < 0)
495 		location -= fFontHeight - 1;
496 
497 	return location / fFontHeight;
498 }
499 
500 
501 inline float
502 TermView::_LineOffset(int32 index)
503 {
504 	return index * fFontHeight - fScrollOffset;
505 }
506 
507 
508 // convert view coordinates to terminal text buffer position
509 TermPos
510 TermView::_ConvertToTerminal(const BPoint &p)
511 {
512 	return TermPos(p.x >= 0 ? (int32)p.x / fFontWidth : -1, _LineAt(p.y));
513 }
514 
515 
516 // convert terminal text buffer position to view coordinates
517 inline BPoint
518 TermView::_ConvertFromTerminal(const TermPos &pos)
519 {
520 	return BPoint(fFontWidth * pos.x, _LineOffset(pos.y));
521 }
522 
523 
524 inline void
525 TermView::_InvalidateTextRect(int32 x1, int32 y1, int32 x2, int32 y2)
526 {
527 	// assume the worst case with full-width characters - invalidate 2 cells
528 	BRect rect(x1 * fFontWidth, _LineOffset(y1),
529 		(x2 + 1) * fFontWidth * 2 - 1, _LineOffset(y2 + 1) - 1);
530 //debug_printf("Invalidate((%f, %f) - (%f, %f))\n", rect.left, rect.top,
531 //rect.right, rect.bottom);
532 	Invalidate(rect);
533 }
534 
535 
536 void
537 TermView::GetPreferredSize(float *width, float *height)
538 {
539 	if (width)
540 		*width = fColumns * fFontWidth - 1;
541 	if (height)
542 		*height = fRows * fFontHeight - 1;
543 }
544 
545 
546 const char *
547 TermView::TerminalName() const
548 {
549 	if (fShell == NULL)
550 		return NULL;
551 
552 	return fShell->TTYName();
553 }
554 
555 
556 //! Get width and height for terminal font
557 void
558 TermView::GetFontSize(float* _width, float* _height)
559 {
560 	*_width = fFontWidth;
561 	*_height = fFontHeight;
562 }
563 
564 
565 int
566 TermView::Rows() const
567 {
568 	return fRows;
569 }
570 
571 
572 int
573 TermView::Columns() const
574 {
575 	return fColumns;
576 }
577 
578 
579 //! Set number of rows and columns in terminal
580 BRect
581 TermView::SetTermSize(int rows, int columns, bool notifyShell)
582 {
583 	// if nothing changed, don't do anything
584 	if (rows == fRows && columns == fColumns)
585 		return BRect(0, 0, fColumns * fFontWidth, fRows * fFontHeight);
586 
587 //debug_printf("TermView::SetTermSize(%d, %d)\n", rows, columns);
588 	if (rows > 0)
589 		fRows = rows;
590 	if (columns > 0)
591 		fColumns = columns;
592 
593 	// To keep things simple, get rid of the selection first.
594 	_Deselect();
595 
596 	{
597 		BAutolock _(fTextBuffer);
598 		if (fTextBuffer->ResizeTo(columns, rows) != B_OK
599 			|| fVisibleTextBuffer->ResizeTo(columns, rows + 2, 0)
600 				!= B_OK) {
601 			return Bounds();
602 		}
603 	}
604 
605 //debug_printf("Invalidate()\n");
606 	Invalidate();
607 
608 	if (fScrollBar != NULL) {
609 		_UpdateScrollBarRange();
610 		fScrollBar->SetSteps(fFontHeight, fFontHeight * fRows);
611 	}
612 
613 	BRect rect(0, 0, fColumns * fFontWidth, fRows * fFontHeight);
614 
615 	// synchronize the visible text buffer
616 	{
617 		TextBufferSyncLocker _(this);
618 
619 		_SynchronizeWithTextBuffer(0, -1);
620 		int32 offset = _LineAt(0);
621 		fVisibleTextBuffer->SynchronizeWith(fTextBuffer, offset, offset,
622 			offset + rows + 2);
623 		fVisibleTextBufferChanged = true;
624 	}
625 
626 	if (notifyShell)
627 		fFrameResized = true;
628 
629 	return rect;
630 }
631 
632 
633 void
634 TermView::SetTermSize(BRect rect, bool notifyShell)
635 {
636 	int rows;
637 	int columns;
638 
639 	GetTermSizeFromRect(rect, &rows, &columns);
640 	SetTermSize(rows, columns, notifyShell);
641 }
642 
643 
644 void
645 TermView::GetTermSizeFromRect(const BRect &rect, int *_rows,
646 	int *_columns)
647 {
648 	int columns = int((rect.IntegerWidth() + 1) / fFontWidth);
649 	int rows = int((rect.IntegerHeight() + 1) / fFontHeight);
650 
651 	if (_rows)
652 		*_rows = rows;
653 	if (_columns)
654 		*_columns = columns;
655 }
656 
657 
658 void
659 TermView::SetTextColor(rgb_color fore, rgb_color back)
660 {
661 	fTextBackColor = back;
662 	fTextForeColor = fore;
663 
664 	SetLowColor(fTextBackColor);
665 }
666 
667 
668 void
669 TermView::SetCursorColor(rgb_color fore, rgb_color back)
670 {
671 	fCursorForeColor = fore;
672 	fCursorBackColor = back;
673 }
674 
675 
676 void
677 TermView::SetSelectColor(rgb_color fore, rgb_color back)
678 {
679 	fSelectForeColor = fore;
680 	fSelectBackColor = back;
681 }
682 
683 
684 void
685 TermView::SetTermColor(uint index, rgb_color color, bool dynamic)
686 {
687 	if (!dynamic) {
688 		if (index < kTermColorCount)
689 			fTextBuffer->SetPaletteColor(index, color);
690 		return;
691 	}
692 
693 	switch (index) {
694 		case 10:
695 			fTextForeColor = color;
696 			break;
697 		case 11:
698 			fTextBackColor = color;
699 			SetLowColor(fTextBackColor);
700 			break;
701 		case 110:
702 			fTextForeColor = PrefHandler::Default()->getRGB(
703 								PREF_TEXT_FORE_COLOR);
704 			break;
705 		case 111:
706 			fTextBackColor = PrefHandler::Default()->getRGB(
707 								PREF_TEXT_BACK_COLOR);
708 			SetLowColor(fTextBackColor);
709 			break;
710 		default:
711 			break;
712 	}
713 }
714 
715 
716 int
717 TermView::Encoding() const
718 {
719 	return fEncoding;
720 }
721 
722 
723 void
724 TermView::SetEncoding(int encoding)
725 {
726 	fEncoding = encoding;
727 
728 	if (fShell != NULL)
729 		fShell->SetEncoding(fEncoding);
730 
731 	BAutolock _(fTextBuffer);
732 	fTextBuffer->SetEncoding(fEncoding);
733 }
734 
735 
736 void
737 TermView::SetKeymap(const key_map* keymap, const char* chars)
738 {
739 	fKeymap = keymap;
740 	fKeymapChars = chars;
741 
742 	fKeymapTableForModifiers.Put(B_SHIFT_KEY,
743 		&fKeymap->shift_map);
744 	fKeymapTableForModifiers.Put(B_CAPS_LOCK,
745 		&fKeymap->caps_map);
746 	fKeymapTableForModifiers.Put(B_CAPS_LOCK | B_SHIFT_KEY,
747 		&fKeymap->caps_shift_map);
748 	fKeymapTableForModifiers.Put(B_CONTROL_KEY,
749 		&fKeymap->control_map);
750 }
751 
752 
753 void
754 TermView::SetUseOptionAsMetaKey(bool enable)
755 {
756 	fUseOptionAsMetaKey = enable && fKeymap != NULL && fKeymapChars != NULL;
757 }
758 
759 
760 void
761 TermView::SetMouseClipboard(BClipboard *clipboard)
762 {
763 	fMouseClipboard = clipboard;
764 }
765 
766 
767 void
768 TermView::GetTermFont(BFont *font) const
769 {
770 	if (font != NULL)
771 		*font = fHalfFont;
772 }
773 
774 
775 //! Sets font for terminal
776 void
777 TermView::SetTermFont(const BFont *font)
778 {
779 	float halfWidth = 0;
780 
781 	fHalfFont = font;
782 	fBoldFont = font;
783 	uint16 face = fBoldFont.Face();
784 	fBoldFont.SetFace(B_BOLD_FACE | (face & ~B_REGULAR_FACE));
785 
786 	fHalfFont.SetSpacing(B_FIXED_SPACING);
787 
788 	// calculate half font's max width
789 	// Not Bounding, check only A-Z (For case of fHalfFont is KanjiFont.)
790 	for (int c = 0x20; c <= 0x7e; c++) {
791 		char buf[4];
792 		sprintf(buf, "%c", c);
793 		float tmpWidth = fHalfFont.StringWidth(buf);
794 		if (tmpWidth > halfWidth)
795 			halfWidth = tmpWidth;
796 	}
797 
798 	fFontWidth = halfWidth;
799 
800 	font_height hh;
801 	fHalfFont.GetHeight(&hh);
802 
803 	int font_ascent = (int)hh.ascent;
804 	int font_descent =(int)hh.descent;
805 	int font_leading =(int)hh.leading;
806 
807 	if (font_leading == 0)
808 		font_leading = 1;
809 
810 	fFontAscent = font_ascent;
811 	fFontHeight = font_ascent + font_descent + font_leading + 1;
812 
813 	fCursorStyle = PrefHandler::Default() == NULL ? BLOCK_CURSOR
814 		: PrefHandler::Default()->getCursor(PREF_CURSOR_STYLE);
815 	bool blinking = PrefHandler::Default()->getBool(PREF_BLINK_CURSOR);
816 	SwitchCursorBlinking(blinking);
817 
818 	fEmulateBold = PrefHandler::Default() == NULL ? false
819 		: PrefHandler::Default()->getBool(PREF_EMULATE_BOLD);
820 
821 	fAllowBold = PrefHandler::Default() == NULL ? false
822 		: PrefHandler::Default()->getBool(PREF_ALLOW_BOLD);
823 
824 	_ScrollTo(0, false);
825 	if (fScrollBar != NULL)
826 		fScrollBar->SetSteps(fFontHeight, fFontHeight * fRows);
827 }
828 
829 
830 void
831 TermView::SetScrollBar(BScrollBar *scrollBar)
832 {
833 	fScrollBar = scrollBar;
834 	if (fScrollBar != NULL)
835 		fScrollBar->SetSteps(fFontHeight, fFontHeight * fRows);
836 }
837 
838 
839 void
840 TermView::SwitchCursorBlinking(bool blinkingOn)
841 {
842 	fCursorBlinking = blinkingOn;
843 	if (blinkingOn) {
844 		if (fCursorBlinkRunner == NULL) {
845 			BMessage blinkMessage(kBlinkCursor);
846 			fCursorBlinkRunner = new (std::nothrow) BMessageRunner(
847 				BMessenger(this), &blinkMessage, kCursorBlinkInterval);
848 		}
849 	} else {
850 		// make sure the cursor becomes visible
851 		fCursorState = 0;
852 		_InvalidateTextRect(fCursor.x, fCursor.y, fCursor.x, fCursor.y);
853 		delete fCursorBlinkRunner;
854 		fCursorBlinkRunner = NULL;
855 	}
856 }
857 
858 
859 void
860 TermView::Copy(BClipboard *clipboard)
861 {
862 	BAutolock _(fTextBuffer);
863 
864 	if (!_HasSelection())
865 		return;
866 
867 	BString copyStr;
868 	fTextBuffer->GetStringFromRegion(copyStr, fSelection.Start(),
869 		fSelection.End());
870 
871 	if (clipboard->Lock()) {
872 		BMessage *clipMsg = NULL;
873 		clipboard->Clear();
874 
875 		if ((clipMsg = clipboard->Data()) != NULL) {
876 			clipMsg->AddData("text/plain", B_MIME_TYPE, copyStr.String(),
877 				copyStr.Length());
878 			clipboard->Commit();
879 		}
880 		clipboard->Unlock();
881 	}
882 }
883 
884 
885 void
886 TermView::Paste(BClipboard *clipboard)
887 {
888 	if (clipboard->Lock()) {
889 		BMessage *clipMsg = clipboard->Data();
890 		const char* text;
891 		ssize_t numBytes;
892 		if (clipMsg->FindData("text/plain", B_MIME_TYPE,
893 				(const void**)&text, &numBytes) == B_OK ) {
894 			_WritePTY(text, numBytes);
895 		}
896 
897 		clipboard->Unlock();
898 
899 		_ScrollTo(0, true);
900 	}
901 }
902 
903 
904 void
905 TermView::SelectAll()
906 {
907 	BAutolock _(fTextBuffer);
908 
909 	_Select(TermPos(0, -fTextBuffer->HistorySize()),
910 		TermPos(0, fTextBuffer->Height()), false, true);
911 }
912 
913 
914 void
915 TermView::Clear()
916 {
917 	_Deselect();
918 
919 	{
920 		BAutolock _(fTextBuffer);
921 		fTextBuffer->Clear(true);
922 	}
923 	fVisibleTextBuffer->Clear(true);
924 
925 //debug_printf("Invalidate()\n");
926 	Invalidate();
927 
928 	_ScrollTo(0, false);
929 	if (fScrollBar) {
930 		fScrollBar->SetRange(0, 0);
931 		fScrollBar->SetProportion(1);
932 	}
933 }
934 
935 
936 //! Draw region
937 void
938 TermView::_InvalidateTextRange(TermPos start, TermPos end)
939 {
940 	if (end < start)
941 		std::swap(start, end);
942 
943 	if (start.y == end.y) {
944 		_InvalidateTextRect(start.x, start.y, end.x, end.y);
945 	} else {
946 		_InvalidateTextRect(start.x, start.y, fColumns, start.y);
947 
948 		if (end.y - start.y > 0)
949 			_InvalidateTextRect(0, start.y + 1, fColumns, end.y - 1);
950 
951 		_InvalidateTextRect(0, end.y, end.x, end.y);
952 	}
953 }
954 
955 
956 status_t
957 TermView::_AttachShell(Shell *shell)
958 {
959 	if (shell == NULL)
960 		return B_BAD_VALUE;
961 
962 	fShell = shell;
963 
964 	return fShell->AttachBuffer(TextBuffer());
965 }
966 
967 
968 void
969 TermView::_DetachShell()
970 {
971 	fShell->DetachBuffer();
972 	fShell = NULL;
973 }
974 
975 
976 void
977 TermView::_Activate()
978 {
979 	fActive = true;
980 	SwitchCursorBlinking(fCursorBlinking);
981 }
982 
983 
984 void
985 TermView::_Deactivate()
986 {
987 	// make sure the cursor becomes visible
988 	fCursorState = 0;
989 	_InvalidateTextRect(fCursor.x, fCursor.y, fCursor.x, fCursor.y);
990 
991 	SwitchCursorBlinking(false);
992 
993 	fActive = false;
994 }
995 
996 
997 //! Draw part of a line in the given view.
998 void
999 TermView::_DrawLinePart(float x1, float y1, uint32 attr, char *buf,
1000 	int32 width, Highlight* highlight, bool cursor, BView *inView)
1001 {
1002 	if (highlight != NULL)
1003 		attr = highlight->Highlighter()->AdjustTextAttributes(attr);
1004 
1005 	inView->SetFont(IS_BOLD(attr) && !fEmulateBold && fAllowBold
1006 		? &fBoldFont : &fHalfFont);
1007 
1008 	// Set pen point
1009 	float x2 = x1 + fFontWidth * width;
1010 	float y2 = y1 + fFontHeight;
1011 
1012 	rgb_color rgb_fore = fTextForeColor;
1013 	rgb_color rgb_back = fTextBackColor;
1014 
1015 	// color attribute
1016 	int forecolor = IS_FORECOLOR(attr);
1017 	int backcolor = IS_BACKCOLOR(attr);
1018 
1019 	if (IS_FORESET(attr))
1020 		rgb_fore = fTextBuffer->PaletteColor(forecolor);
1021 	if (IS_BACKSET(attr))
1022 		rgb_back = fTextBuffer->PaletteColor(backcolor);
1023 
1024 	// Selection check.
1025 	if (cursor) {
1026 		rgb_fore = fCursorForeColor;
1027 		rgb_back = fCursorBackColor;
1028 	} else if (highlight != NULL) {
1029 		rgb_fore = highlight->Highlighter()->ForegroundColor();
1030 		rgb_back = highlight->Highlighter()->BackgroundColor();
1031 	} else {
1032 		// Reverse attribute(If selected area, don't reverse color).
1033 		if (IS_INVERSE(attr)) {
1034 			rgb_color rgb_tmp = rgb_fore;
1035 			rgb_fore = rgb_back;
1036 			rgb_back = rgb_tmp;
1037 		}
1038 	}
1039 
1040 	// Fill color at Background color and set low color.
1041 	inView->SetHighColor(rgb_back);
1042 	inView->FillRect(BRect(x1, y1, x2 - 1, y2 - 1));
1043 	inView->SetLowColor(rgb_back);
1044 	inView->SetHighColor(rgb_fore);
1045 
1046 	// Draw character.
1047 	if (IS_BOLD(attr)) {
1048 		if (fEmulateBold) {
1049 			inView->MovePenTo(x1 - 1, y1 + fFontAscent - 1);
1050 			inView->DrawString((char *)buf);
1051 			inView->SetDrawingMode(B_OP_BLEND);
1052 		} else {
1053 			rgb_color bright = rgb_fore;
1054 
1055 			bright.red = saturated_add<uint8>(bright.red, 64);
1056 			bright.green = saturated_add<uint8>(bright.green, 64);
1057 			bright.blue = saturated_add<uint8>(bright.blue, 64);
1058 
1059 			inView->SetHighColor(bright);
1060 		}
1061 	}
1062 
1063 	inView->MovePenTo(x1, y1 + fFontAscent);
1064 	inView->DrawString((char *)buf);
1065 	inView->SetDrawingMode(B_OP_COPY);
1066 
1067 	// underline attribute
1068 	if (IS_UNDER(attr)) {
1069 		inView->MovePenTo(x1, y1 + fFontAscent);
1070 		inView->StrokeLine(BPoint(x1 , y1 + fFontAscent),
1071 			BPoint(x2 , y1 + fFontAscent));
1072 	}
1073 }
1074 
1075 
1076 /*!	Caller must have locked fTextBuffer.
1077 */
1078 void
1079 TermView::_DrawCursor()
1080 {
1081 	BRect rect(fFontWidth * fCursor.x, _LineOffset(fCursor.y), 0, 0);
1082 	rect.right = rect.left + fFontWidth - 1;
1083 	rect.bottom = rect.top + fFontHeight - 1;
1084 	int32 firstVisible = _LineAt(0);
1085 
1086 	UTF8Char character;
1087 	uint32 attr = 0;
1088 
1089 	bool cursorVisible = _IsCursorVisible();
1090 
1091 	if (cursorVisible) {
1092 		switch (fCursorStyle) {
1093 			case UNDERLINE_CURSOR:
1094 				rect.top = rect.bottom - 2;
1095 				break;
1096 			case IBEAM_CURSOR:
1097 				rect.right = rect.left + 1;
1098 				break;
1099 			case BLOCK_CURSOR:
1100 			default:
1101 				break;
1102 		}
1103 	}
1104 
1105 	Highlight* highlight = _CheckHighlightRegion(TermPos(fCursor.x, fCursor.y));
1106 	if (fVisibleTextBuffer->GetChar(fCursor.y - firstVisible, fCursor.x,
1107 			character, attr) == A_CHAR
1108 			&& (fCursorStyle == BLOCK_CURSOR || !cursorVisible)) {
1109 
1110 		int32 width = IS_WIDTH(attr) ? FULL_WIDTH : HALF_WIDTH;
1111 		char buffer[5];
1112 		int32 bytes = UTF8Char::ByteCount(character.bytes[0]);
1113 		memcpy(buffer, character.bytes, bytes);
1114 		buffer[bytes] = '\0';
1115 
1116 		_DrawLinePart(fCursor.x * fFontWidth, (int32)rect.top, attr, buffer,
1117 			width, highlight, cursorVisible, this);
1118 	} else {
1119 		if (highlight != NULL)
1120 			SetHighColor(highlight->Highlighter()->BackgroundColor());
1121 		else if (cursorVisible)
1122 			SetHighColor(fCursorBackColor );
1123 		else {
1124 			uint32 count = 0;
1125 			rgb_color rgb_back = fTextBackColor;
1126 			if (fTextBuffer->IsAlternateScreenActive())
1127 				// alternate screen uses cell attributes beyond the line ends
1128 				fTextBuffer->GetCellAttributes(
1129 						fCursor.y, fCursor.x, attr, count);
1130 			else
1131 				attr = fVisibleTextBuffer->GetLineColor(
1132 						fCursor.y - firstVisible);
1133 
1134 			if (IS_BACKSET(attr))
1135 				rgb_back = fTextBuffer->PaletteColor(IS_BACKCOLOR(attr));
1136 			SetHighColor(rgb_back);
1137 		}
1138 
1139 		if (IS_WIDTH(attr) && fCursorStyle != IBEAM_CURSOR)
1140 			rect.right += fFontWidth;
1141 
1142 		FillRect(rect);
1143 	}
1144 }
1145 
1146 
1147 bool
1148 TermView::_IsCursorVisible() const
1149 {
1150 	return !fCursorHidden && fCursorState < kCursorVisibleIntervals;
1151 }
1152 
1153 
1154 void
1155 TermView::_BlinkCursor()
1156 {
1157 	bool wasVisible = _IsCursorVisible();
1158 
1159 	if (!wasVisible && fInline && fInline->IsActive())
1160 		return;
1161 
1162 	bigtime_t now = system_time();
1163 	if (Window()->IsActive() && now - fLastActivityTime >= kCursorBlinkInterval)
1164 		fCursorState = (fCursorState + 1) % kCursorBlinkIntervals;
1165 	else
1166 		fCursorState = 0;
1167 
1168 	if (wasVisible != _IsCursorVisible())
1169 		_InvalidateTextRect(fCursor.x, fCursor.y, fCursor.x, fCursor.y);
1170 }
1171 
1172 
1173 void
1174 TermView::_ActivateCursor(bool invalidate)
1175 {
1176 	fLastActivityTime = system_time();
1177 	if (invalidate && fCursorState != 0)
1178 		_BlinkCursor();
1179 	else
1180 		fCursorState = 0;
1181 }
1182 
1183 
1184 //! Update scroll bar range and knob size.
1185 void
1186 TermView::_UpdateScrollBarRange()
1187 {
1188 	if (fScrollBar == NULL)
1189 		return;
1190 
1191 	int32 historySize;
1192 	{
1193 		BAutolock _(fTextBuffer);
1194 		historySize = fTextBuffer->HistorySize();
1195 	}
1196 
1197 	float viewHeight = fRows * fFontHeight;
1198 	float historyHeight = (float)historySize * fFontHeight;
1199 
1200 //debug_printf("TermView::_UpdateScrollBarRange(): history: %ld, range: %f - 0\n",
1201 //historySize, -historyHeight);
1202 
1203 	fScrollBar->SetRange(-historyHeight, 0);
1204 	if (historySize > 0)
1205 		fScrollBar->SetProportion(viewHeight / (viewHeight + historyHeight));
1206 }
1207 
1208 
1209 //!	Handler for SIGWINCH
1210 void
1211 TermView::_UpdateSIGWINCH()
1212 {
1213 	if (fFrameResized) {
1214 		fShell->UpdateWindowSize(fRows, fColumns);
1215 		fFrameResized = false;
1216 	}
1217 }
1218 
1219 
1220 void
1221 TermView::AttachedToWindow()
1222 {
1223 	fMouseButtons = 0;
1224 
1225 	_UpdateModifiers();
1226 
1227 	// update the terminal size because it may have changed while the TermView
1228 	// was detached from the window. On such conditions FrameResized was not
1229 	// called when the resize occured
1230 	SetTermSize(Bounds(), true);
1231 	MakeFocus(true);
1232 	if (fScrollBar) {
1233 		fScrollBar->SetSteps(fFontHeight, fFontHeight * fRows);
1234 		_UpdateScrollBarRange();
1235 	}
1236 
1237 	BMessenger thisMessenger(this);
1238 
1239 	BMessage message(kUpdateSigWinch);
1240 	fWinchRunner = new (std::nothrow) BMessageRunner(thisMessenger,
1241 		&message, 500000);
1242 
1243 	{
1244 		TextBufferSyncLocker _(this);
1245 		fTextBuffer->SetListener(thisMessenger);
1246 		_SynchronizeWithTextBuffer(0, -1);
1247 	}
1248 
1249 	be_clipboard->StartWatching(thisMessenger);
1250 }
1251 
1252 
1253 void
1254 TermView::DetachedFromWindow()
1255 {
1256 	be_clipboard->StopWatching(BMessenger(this));
1257 
1258 	 _NextState(fDefaultState);
1259 
1260 	delete fWinchRunner;
1261 	fWinchRunner = NULL;
1262 
1263 	delete fCursorBlinkRunner;
1264 	fCursorBlinkRunner = NULL;
1265 
1266 	delete fResizeRunner;
1267 	fResizeRunner = NULL;
1268 
1269 	{
1270 		BAutolock _(fTextBuffer);
1271 		fTextBuffer->UnsetListener();
1272 	}
1273 }
1274 
1275 
1276 void
1277 TermView::Draw(BRect updateRect)
1278 {
1279 	int32 x1 = (int32)(updateRect.left / fFontWidth);
1280 	int32 x2 = std::min((int)(updateRect.right / fFontWidth), fColumns - 1);
1281 
1282 	int32 firstVisible = _LineAt(0);
1283 	int32 y1 = _LineAt(updateRect.top);
1284 	int32 y2 = std::min(_LineAt(updateRect.bottom), (int32)fRows - 1);
1285 
1286 	// clear the area to the right of the line ends
1287 	if (y1 <= y2) {
1288 		float clearLeft = fColumns * fFontWidth;
1289 		if (clearLeft <= updateRect.right) {
1290 			BRect rect(clearLeft, updateRect.top, updateRect.right,
1291 				updateRect.bottom);
1292 			SetHighColor(fTextBackColor);
1293 			FillRect(rect);
1294 		}
1295 	}
1296 
1297 	// clear the area below the last line
1298 	if (y2 == fRows - 1) {
1299 		float clearTop = _LineOffset(fRows);
1300 		if (clearTop <= updateRect.bottom) {
1301 			BRect rect(updateRect.left, clearTop, updateRect.right,
1302 				updateRect.bottom);
1303 			SetHighColor(fTextBackColor);
1304 			FillRect(rect);
1305 		}
1306 	}
1307 
1308 	// draw the affected line parts
1309 	if (x1 <= x2) {
1310 		uint32 attr = 0;
1311 
1312 		for (int32 j = y1; j <= y2; j++) {
1313 			int32 k = x1;
1314 			char buf[fColumns * 4 + 1];
1315 
1316 			if (fVisibleTextBuffer->IsFullWidthChar(j - firstVisible, k))
1317 				k--;
1318 
1319 			if (k < 0)
1320 				k = 0;
1321 
1322 			for (int32 i = k; i <= x2;) {
1323 				int32 lastColumn = x2;
1324 				Highlight* highlight = _CheckHighlightRegion(j, i, lastColumn);
1325 					// This will clip lastColumn to the selection start or end
1326 					// to ensure the selection is not drawn at the same time as
1327 					// something else
1328 				int32 count = fVisibleTextBuffer->GetString(j - firstVisible, i,
1329 					lastColumn, buf, attr);
1330 
1331 // debug_printf("  fVisibleTextBuffer->GetString(%ld, %ld, %ld) -> (%ld, \"%.*s\"), highlight: %p\n",
1332 // j - firstVisible, i, lastColumn, count, (int)count, buf, highlight);
1333 
1334 				if (count == 0) {
1335 					// No chars to draw : we just fill the rectangle with the
1336 					// back color of the last char at the left
1337 					int nextColumn = lastColumn + 1;
1338 					BRect rect(fFontWidth * i, _LineOffset(j),
1339 						fFontWidth * nextColumn - 1, 0);
1340 					rect.bottom = rect.top + fFontHeight - 1;
1341 
1342 					rgb_color rgb_back = highlight != NULL
1343 						? highlight->Highlighter()->BackgroundColor()
1344 						: fTextBackColor;
1345 
1346 					if (fTextBuffer->IsAlternateScreenActive()) {
1347 						// alternate screen uses cell attributes
1348 						// beyond the line ends
1349 						uint32 count = 0;
1350 						fTextBuffer->GetCellAttributes(j, i, attr, count);
1351 						rect.right = rect.left + fFontWidth * count - 1;
1352 						nextColumn = i + count;
1353 					} else
1354 						attr = fVisibleTextBuffer->GetLineColor(j - firstVisible);
1355 
1356 					if (IS_BACKSET(attr)) {
1357 						int backcolor = IS_BACKCOLOR(attr);
1358 						rgb_back = fTextBuffer->PaletteColor(backcolor);
1359 					}
1360 
1361 					SetHighColor(rgb_back);
1362 					rgb_back = HighColor();
1363 					FillRect(rect);
1364 
1365 					// Go on to the next block
1366 					i = nextColumn;
1367 					continue;
1368 				}
1369 
1370 				// Note: full-width characters GetString()-ed always
1371 				// with count 1, so this hardcoding is safe. From the other
1372 				// side - drawing the whole string with one call render the
1373 				// characters not aligned to cells grid - that looks much more
1374 				// inaccurate for full-width strings than for half-width ones.
1375 				if (IS_WIDTH(attr))
1376 					count = FULL_WIDTH;
1377 
1378 				_DrawLinePart(fFontWidth * i, (int32)_LineOffset(j),
1379 					attr, buf, count, highlight, false, this);
1380 				i += count;
1381 			}
1382 		}
1383 	}
1384 
1385 	if (fInline && fInline->IsActive())
1386 		_DrawInlineMethodString();
1387 
1388 	if (fCursor >= TermPos(x1, y1) && fCursor <= TermPos(x2, y2))
1389 		_DrawCursor();
1390 }
1391 
1392 
1393 void
1394 TermView::_DoPrint(BRect updateRect)
1395 {
1396 #if 0
1397 	uint32 attr;
1398 	uchar buf[1024];
1399 
1400 	const int numLines = (int)((updateRect.Height()) / fFontHeight);
1401 
1402 	int y1 = (int)(updateRect.top) / fFontHeight;
1403 	y1 = y1 -(fScrBufSize - numLines * 2);
1404 	if (y1 < 0)
1405 		y1 = 0;
1406 
1407 	const int y2 = y1 + numLines -1;
1408 
1409 	const int x1 = (int)(updateRect.left) / fFontWidth;
1410 	const int x2 = (int)(updateRect.right) / fFontWidth;
1411 
1412 	for (int j = y1; j <= y2; j++) {
1413 		// If(x1, y1) Buffer is in string full width character,
1414 		// alignment start position.
1415 
1416 		int k = x1;
1417 		if (fTextBuffer->IsFullWidthChar(j, k))
1418 			k--;
1419 
1420 		if (k < 0)
1421 			k = 0;
1422 
1423 		for (int i = k; i <= x2;) {
1424 			int count = fTextBuffer->GetString(j, i, x2, buf, &attr);
1425 			if (count < 0) {
1426 				i += abs(count);
1427 				continue;
1428 			}
1429 
1430 			_DrawLinePart(fFontWidth * i, fFontHeight * j,
1431 				attr, buf, count, false, false, this);
1432 			i += count;
1433 		}
1434 	}
1435 #endif	// 0
1436 }
1437 
1438 
1439 void
1440 TermView::WindowActivated(bool active)
1441 {
1442 	BView::WindowActivated(active);
1443 	if (active && IsFocus()) {
1444 		if (!fActive)
1445 			_Activate();
1446 	} else {
1447 		if (fActive)
1448 			_Deactivate();
1449 	}
1450 
1451 	_UpdateModifiers();
1452 
1453 	fActiveState->WindowActivated(active);
1454 }
1455 
1456 
1457 void
1458 TermView::MakeFocus(bool focusState)
1459 {
1460 	BView::MakeFocus(focusState);
1461 
1462 	if (focusState && Window() && Window()->IsActive()) {
1463 		if (!fActive)
1464 			_Activate();
1465 	} else {
1466 		if (fActive)
1467 			_Deactivate();
1468 	}
1469 }
1470 
1471 
1472 void
1473 TermView::KeyDown(const char *bytes, int32 numBytes)
1474 {
1475 	_UpdateModifiers();
1476 
1477 	fActiveState->KeyDown(bytes, numBytes);
1478 }
1479 
1480 
1481 void
1482 TermView::FrameResized(float width, float height)
1483 {
1484 //debug_printf("TermView::FrameResized(%f, %f)\n", width, height);
1485 	int32 columns = (int32)((width + 1) / fFontWidth);
1486 	int32 rows = (int32)((height + 1) / fFontHeight);
1487 
1488 	if (columns == fColumns && rows == fRows)
1489 		return;
1490 
1491 	bool hasResizeView = fResizeRunner != NULL;
1492 	if (!hasResizeView) {
1493 		// show the current size in a view
1494 		fResizeView = new BStringView(BRect(100, 100, 300, 140), "size", "");
1495 		fResizeView->SetAlignment(B_ALIGN_CENTER);
1496 		fResizeView->SetFont(be_bold_font);
1497 		fResizeView->SetViewColor(fTextBackColor);
1498 		fResizeView->SetLowColor(fTextBackColor);
1499 		fResizeView->SetHighColor(fTextForeColor);
1500 
1501 		BMessage message(MSG_REMOVE_RESIZE_VIEW_IF_NEEDED);
1502 		fResizeRunner = new(std::nothrow) BMessageRunner(BMessenger(this),
1503 			&message, 25000LL);
1504 	}
1505 
1506 	BString text;
1507 	text << columns << " x " << rows;
1508 	fResizeView->SetText(text.String());
1509 	fResizeView->GetPreferredSize(&width, &height);
1510 	fResizeView->ResizeTo(width * 1.5, height * 1.5);
1511 	fResizeView->MoveTo((Bounds().Width() - fResizeView->Bounds().Width()) / 2,
1512 		(Bounds().Height()- fResizeView->Bounds().Height()) / 2);
1513 	if (!hasResizeView && fResizeViewDisableCount < 1)
1514 		AddChild(fResizeView);
1515 
1516 	if (fResizeViewDisableCount > 0)
1517 		fResizeViewDisableCount--;
1518 
1519 	SetTermSize(rows, columns, true);
1520 }
1521 
1522 
1523 void
1524 TermView::MessageReceived(BMessage *message)
1525 {
1526 	if (fActiveState->MessageReceived(message))
1527 		return;
1528 
1529 	entry_ref ref;
1530 	const char *ctrl_l = "\x0c";
1531 
1532 	// first check for any dropped message
1533 	if (message->WasDropped() && (message->what == B_SIMPLE_DATA
1534 			|| message->what == B_MIME_DATA)) {
1535 		char *text;
1536 		ssize_t numBytes;
1537 		//rgb_color *color;
1538 
1539 		int32 i = 0;
1540 
1541 		if (message->FindRef("refs", i++, &ref) == B_OK) {
1542 			// first check if secondary mouse button is pressed
1543 			int32 buttons = 0;
1544 			message->FindInt32("buttons", &buttons);
1545 
1546 			if (buttons == B_SECONDARY_MOUSE_BUTTON) {
1547 				// start popup menu
1548 				_SecondaryMouseButtonDropped(message);
1549 				return;
1550 			}
1551 
1552 			_DoFileDrop(ref);
1553 
1554 			while (message->FindRef("refs", i++, &ref) == B_OK) {
1555 				_WritePTY(" ", 1);
1556 				_DoFileDrop(ref);
1557 			}
1558 			return;
1559 #if 0
1560 		} else if (message->FindData("RGBColor", B_RGB_COLOR_TYPE,
1561 				(const void **)&color, &numBytes) == B_OK
1562 				&& numBytes == sizeof(color)) {
1563 			// TODO: handle color drop
1564 			// maybe only on replicants ?
1565 			return;
1566 #endif
1567 		} else if (message->FindData("text/plain", B_MIME_TYPE,
1568 				(const void **)&text, &numBytes) == B_OK) {
1569 			_WritePTY(text, numBytes);
1570 			return;
1571 		}
1572 	}
1573 
1574 	switch (message->what) {
1575 		case B_SIMPLE_DATA:
1576 		case B_REFS_RECEIVED:
1577 		{
1578 			// handle refs if they weren't dropped
1579 			int32 i = 0;
1580 			if (message->FindRef("refs", i++, &ref) == B_OK) {
1581 				_DoFileDrop(ref);
1582 
1583 				while (message->FindRef("refs", i++, &ref) == B_OK) {
1584 					_WritePTY(" ", 1);
1585 					_DoFileDrop(ref);
1586 				}
1587 			} else
1588 				BView::MessageReceived(message);
1589 			break;
1590 		}
1591 
1592 		case B_COPY:
1593 			Copy(be_clipboard);
1594 			break;
1595 
1596 		case B_PASTE:
1597 		{
1598 			int32 code;
1599 			if (message->FindInt32("index", &code) == B_OK)
1600 				Paste(be_clipboard);
1601 			break;
1602 		}
1603 
1604 		case B_CLIPBOARD_CHANGED:
1605 			// This message originates from the system clipboard. Overwrite
1606 			// the contents of the mouse clipboard with the ones from the
1607 			// system clipboard, in case it contains text data.
1608 			if (be_clipboard->Lock()) {
1609 				if (fMouseClipboard->Lock()) {
1610 					BMessage* clipMsgA = be_clipboard->Data();
1611 					const char* text;
1612 					ssize_t numBytes;
1613 					if (clipMsgA->FindData("text/plain", B_MIME_TYPE,
1614 							(const void**)&text, &numBytes) == B_OK ) {
1615 						fMouseClipboard->Clear();
1616 						BMessage* clipMsgB = fMouseClipboard->Data();
1617 						clipMsgB->AddData("text/plain", B_MIME_TYPE,
1618 							text, numBytes);
1619 						fMouseClipboard->Commit();
1620 					}
1621 					fMouseClipboard->Unlock();
1622 				}
1623 				be_clipboard->Unlock();
1624 			}
1625 			break;
1626 
1627 		case B_SELECT_ALL:
1628 			SelectAll();
1629 			break;
1630 
1631 		case B_SET_PROPERTY:
1632 		{
1633 			int32 i;
1634 			int32 encodingID;
1635 			BMessage specifier;
1636 			if (message->GetCurrentSpecifier(&i, &specifier) == B_OK
1637 				&& strcmp("encoding",
1638 					specifier.FindString("property", i)) == 0) {
1639 				message->FindInt32 ("data", &encodingID);
1640 				SetEncoding(encodingID);
1641 				message->SendReply(B_REPLY);
1642 			} else {
1643 				BView::MessageReceived(message);
1644 			}
1645 			break;
1646 		}
1647 
1648 		case B_GET_PROPERTY:
1649 		{
1650 			int32 i;
1651 			BMessage specifier;
1652 			if (message->GetCurrentSpecifier(&i, &specifier) == B_OK) {
1653 				if (strcmp("encoding",
1654 					specifier.FindString("property", i)) == 0) {
1655 					BMessage reply(B_REPLY);
1656 					reply.AddInt32("result", Encoding());
1657 					message->SendReply(&reply);
1658 				} else if (strcmp("tty",
1659 					specifier.FindString("property", i)) == 0) {
1660 					BMessage reply(B_REPLY);
1661 					reply.AddString("result", TerminalName());
1662 					message->SendReply(&reply);
1663 				} else
1664 					BView::MessageReceived(message);
1665 			} else
1666 				BView::MessageReceived(message);
1667 			break;
1668 		}
1669 
1670 		case B_MODIFIERS_CHANGED:
1671 		{
1672 			_UpdateModifiers();
1673 			break;
1674 		}
1675 
1676 		case B_INPUT_METHOD_EVENT:
1677 		{
1678 			int32 opcode;
1679 			if (message->FindInt32("be:opcode", &opcode) == B_OK) {
1680 				switch (opcode) {
1681 					case B_INPUT_METHOD_STARTED:
1682 					{
1683 						BMessenger messenger;
1684 						if (message->FindMessenger("be:reply_to",
1685 								&messenger) == B_OK) {
1686 							fInline = new (std::nothrow)
1687 								InlineInput(messenger);
1688 						}
1689 						break;
1690 					}
1691 
1692 					case B_INPUT_METHOD_STOPPED:
1693 						delete fInline;
1694 						fInline = NULL;
1695 						break;
1696 
1697 					case B_INPUT_METHOD_CHANGED:
1698 						if (fInline != NULL)
1699 							_HandleInputMethodChanged(message);
1700 						break;
1701 
1702 					case B_INPUT_METHOD_LOCATION_REQUEST:
1703 						if (fInline != NULL)
1704 							_HandleInputMethodLocationRequest();
1705 						break;
1706 
1707 					default:
1708 						break;
1709 				}
1710 			}
1711 			break;
1712 		}
1713 
1714 		case B_MOUSE_WHEEL_CHANGED:
1715 		{
1716 			// overridden to allow scrolling emulation in alternative screen
1717 			// mode
1718 			BAutolock locker(fTextBuffer);
1719 			float deltaY = 0;
1720 			if (fTextBuffer->IsAlternateScreenActive()
1721 				&& message->FindFloat("be:wheel_delta_y", &deltaY) == B_OK
1722 				&& deltaY != 0) {
1723 				// We are in alternative screen mode and have a vertical delta
1724 				// we can work with -- emulate scrolling via terminal escape
1725 				// sequences.
1726 				locker.Unlock();
1727 
1728 				// scroll pagewise, if one of Option, Command, or Control is
1729 				// pressed
1730 				int32 steps;
1731 				const char* stepString;
1732 				if ((modifiers() & B_SHIFT_KEY) != 0) {
1733 					// pagewise
1734 					stepString = deltaY > 0
1735 						? PAGE_DOWN_KEY_CODE : PAGE_UP_KEY_CODE;
1736 					steps = abs((int)deltaY);
1737 				} else {
1738 					// three lines per step
1739 					stepString = deltaY > 0
1740 						? DOWN_ARROW_KEY_CODE : UP_ARROW_KEY_CODE;
1741 					steps = 3 * abs((int)deltaY);
1742 				}
1743 
1744 				// We want to do only a single write(), so compose a string
1745 				// repeating the sequence as often as required by the delta.
1746 				BString toWrite;
1747 				for (int32 i = 0; i <steps; i++)
1748 					toWrite << stepString;
1749 
1750 				_WritePTY(toWrite.String(), toWrite.Length());
1751 			} else {
1752 				// let the BView's implementation handle the standard scrolling
1753 				locker.Unlock();
1754 				BView::MessageReceived(message);
1755 			}
1756 
1757 			break;
1758 		}
1759 
1760 		case MENU_CLEAR_ALL:
1761 			Clear();
1762 			fShell->Write(ctrl_l, 1);
1763 			break;
1764 		case kBlinkCursor:
1765 			_BlinkCursor();
1766 			break;
1767 		case kUpdateSigWinch:
1768 			_UpdateSIGWINCH();
1769 			break;
1770 		case kSecondaryMouseDropAction:
1771 			_DoSecondaryMouseDropAction(message);
1772 			break;
1773 		case MSG_TERMINAL_BUFFER_CHANGED:
1774 		{
1775 			TextBufferSyncLocker _(this);
1776 			_SynchronizeWithTextBuffer(0, -1);
1777 			break;
1778 		}
1779 		case MSG_SET_TERMINAL_TITLE:
1780 		{
1781 			const char* title;
1782 			if (message->FindString("title", &title) == B_OK) {
1783 				if (fListener != NULL)
1784 					fListener->SetTermViewTitle(this, title);
1785 			}
1786 			break;
1787 		}
1788 		case MSG_SET_TERMINAL_COLORS:
1789 		{
1790 			int32 count  = 0;
1791 			if (message->FindInt32("count", &count) != B_OK)
1792 				break;
1793 			bool dynamic  = false;
1794 			if (message->FindBool("dynamic", &dynamic) != B_OK)
1795 				break;
1796 			for (int i = 0; i < count; i++) {
1797 				uint8 index = 0;
1798 				if (message->FindUInt8("index", i, &index) != B_OK)
1799 					break;
1800 
1801 				ssize_t bytes = 0;
1802 				rgb_color* color = 0;
1803 				if (message->FindData("color", B_RGB_COLOR_TYPE,
1804 							i, (const void**)&color, &bytes) != B_OK)
1805 					break;
1806 				SetTermColor(index, *color, dynamic);
1807 			}
1808 			break;
1809 		}
1810 		case MSG_RESET_TERMINAL_COLORS:
1811 		{
1812 			int32 count  = 0;
1813 			if (message->FindInt32("count", &count) != B_OK)
1814 				break;
1815 			bool dynamic  = false;
1816 			if (message->FindBool("dynamic", &dynamic) != B_OK)
1817 				break;
1818 			for (int i = 0; i < count; i++) {
1819 				uint8 index = 0;
1820 				if (message->FindUInt8("index", i, &index) != B_OK)
1821 					break;
1822 
1823 				SetTermColor(index,
1824 					TermApp::DefaultPalette()[index], dynamic);
1825 			}
1826 			break;
1827 		}
1828 		case MSG_SET_CURSOR_STYLE:
1829 		{
1830 			int32 style = BLOCK_CURSOR;
1831 			if (message->FindInt32("style", &style) == B_OK)
1832 				fCursorStyle = style;
1833 
1834 			bool blinking = fCursorBlinking;
1835 			if (message->FindBool("blinking", &blinking) == B_OK)
1836 				SwitchCursorBlinking(blinking);
1837 
1838 			bool hidden = fCursorHidden;
1839 			if (message->FindBool("hidden", &hidden) == B_OK)
1840 				fCursorHidden = hidden;
1841 			break;
1842 		}
1843 		case MSG_ENABLE_META_KEY:
1844 		{
1845 			bool enable;
1846 			if (message->FindBool("enableInterpretMetaKey", &enable) == B_OK)
1847 				fInterpretMetaKey = enable;
1848 
1849 			if (message->FindBool("enableMetaKeySendsEscape", &enable) == B_OK)
1850 				fMetaKeySendsEscape = enable;
1851 			break;
1852 		}
1853 		case MSG_REPORT_MOUSE_EVENT:
1854 		{
1855 			bool value;
1856 			if (message->FindBool("reportX10MouseEvent", &value) == B_OK)
1857 				fReportX10MouseEvent = value;
1858 
1859 			if (message->FindBool("reportNormalMouseEvent", &value) == B_OK)
1860 				fReportNormalMouseEvent = value;
1861 
1862 			if (message->FindBool("reportButtonMouseEvent", &value) == B_OK)
1863 				fReportButtonMouseEvent = value;
1864 
1865 			if (message->FindBool("reportAnyMouseEvent", &value) == B_OK)
1866 				fReportAnyMouseEvent = value;
1867 
1868 			if (message->FindBool(
1869 				"enableExtendedMouseCoordinates", &value) == B_OK)
1870 				fEnableExtendedMouseCoordinates = value;
1871 			break;
1872 		}
1873 		case MSG_REMOVE_RESIZE_VIEW_IF_NEEDED:
1874 		{
1875 			BPoint point;
1876 			uint32 buttons;
1877 			GetMouse(&point, &buttons, false);
1878 			if (buttons != 0)
1879 				break;
1880 
1881 			if (fResizeView != NULL) {
1882 				fResizeView->RemoveSelf();
1883 				delete fResizeView;
1884 				fResizeView = NULL;
1885 			}
1886 			delete fResizeRunner;
1887 			fResizeRunner = NULL;
1888 			break;
1889 		}
1890 
1891 		case MSG_QUIT_TERMNAL:
1892 		{
1893 			int32 reason;
1894 			if (message->FindInt32("reason", &reason) != B_OK)
1895 				reason = 0;
1896 			if (fListener != NULL)
1897 				fListener->NotifyTermViewQuit(this, reason);
1898 			break;
1899 		}
1900 		default:
1901 			BView::MessageReceived(message);
1902 			break;
1903 	}
1904 }
1905 
1906 
1907 status_t
1908 TermView::GetSupportedSuites(BMessage* message)
1909 {
1910 	BPropertyInfo propInfo(sPropList);
1911 	message->AddString("suites", "suite/vnd.naan-termview");
1912 	message->AddFlat("messages", &propInfo);
1913 	return BView::GetSupportedSuites(message);
1914 }
1915 
1916 
1917 void
1918 TermView::ScrollTo(BPoint where)
1919 {
1920 //debug_printf("TermView::ScrollTo(): %f -> %f\n", fScrollOffset, where.y);
1921 	float diff = where.y - fScrollOffset;
1922 	if (diff == 0)
1923 		return;
1924 
1925 	float bottom = Bounds().bottom;
1926 	int32 oldFirstLine = _LineAt(0);
1927 	int32 oldLastLine = _LineAt(bottom);
1928 	int32 newFirstLine = _LineAt(diff);
1929 	int32 newLastLine = _LineAt(bottom + diff);
1930 
1931 	fScrollOffset = where.y;
1932 
1933 	// invalidate the current cursor position before scrolling
1934 	_InvalidateTextRect(fCursor.x, fCursor.y, fCursor.x, fCursor.y);
1935 
1936 	// scroll contents
1937 	BRect destRect(Frame().OffsetToCopy(Bounds().LeftTop()));
1938 	BRect sourceRect(destRect.OffsetByCopy(0, diff));
1939 //debug_printf("CopyBits(((%f, %f) - (%f, %f)) -> (%f, %f) - (%f, %f))\n",
1940 //sourceRect.left, sourceRect.top, sourceRect.right, sourceRect.bottom,
1941 //destRect.left, destRect.top, destRect.right, destRect.bottom);
1942 	CopyBits(sourceRect, destRect);
1943 
1944 	// sync visible text buffer with text buffer
1945 	if (newFirstLine != oldFirstLine || newLastLine != oldLastLine) {
1946 		if (newFirstLine != oldFirstLine)
1947 {
1948 //debug_printf("fVisibleTextBuffer->ScrollBy(%ld)\n", newFirstLine - oldFirstLine);
1949 			fVisibleTextBuffer->ScrollBy(newFirstLine - oldFirstLine);
1950 }
1951 		TextBufferSyncLocker _(this);
1952 		if (diff < 0)
1953 			_SynchronizeWithTextBuffer(newFirstLine, oldFirstLine - 1);
1954 		else
1955 			_SynchronizeWithTextBuffer(oldLastLine + 1, newLastLine);
1956 	}
1957 }
1958 
1959 
1960 void
1961 TermView::TargetedByScrollView(BScrollView *scrollView)
1962 {
1963 	BView::TargetedByScrollView(scrollView);
1964 
1965 	SetScrollBar(scrollView ? scrollView->ScrollBar(B_VERTICAL) : NULL);
1966 }
1967 
1968 
1969 BHandler*
1970 TermView::ResolveSpecifier(BMessage* message, int32 index, BMessage* specifier,
1971 	int32 what, const char* property)
1972 {
1973 	BHandler* target = this;
1974 	BPropertyInfo propInfo(sPropList);
1975 	if (propInfo.FindMatch(message, index, specifier, what, property) < B_OK) {
1976 		target = BView::ResolveSpecifier(message, index, specifier, what,
1977 			property);
1978 	}
1979 
1980 	return target;
1981 }
1982 
1983 
1984 void
1985 TermView::_SecondaryMouseButtonDropped(BMessage* message)
1986 {
1987 	// Launch menu to choose what is to do with the message data
1988 	BPoint point;
1989 	if (message->FindPoint("_drop_point_", &point) != B_OK)
1990 		return;
1991 
1992 	BMessage* insertMessage = new BMessage(*message);
1993 	insertMessage->what = kSecondaryMouseDropAction;
1994 	insertMessage->AddInt8("action", kInsert);
1995 
1996 	BMessage* cdMessage = new BMessage(*message);
1997 	cdMessage->what = kSecondaryMouseDropAction;
1998 	cdMessage->AddInt8("action", kChangeDirectory);
1999 
2000 	BMessage* lnMessage = new BMessage(*message);
2001 	lnMessage->what = kSecondaryMouseDropAction;
2002 	lnMessage->AddInt8("action", kLinkFiles);
2003 
2004 	BMessage* mvMessage = new BMessage(*message);
2005 	mvMessage->what = kSecondaryMouseDropAction;
2006 	mvMessage->AddInt8("action", kMoveFiles);
2007 
2008 	BMessage* cpMessage = new BMessage(*message);
2009 	cpMessage->what = kSecondaryMouseDropAction;
2010 	cpMessage->AddInt8("action", kCopyFiles);
2011 
2012 	BMenuItem* insertItem = new BMenuItem(
2013 		B_TRANSLATE("Insert path"), insertMessage);
2014 	BMenuItem* cdItem = new BMenuItem(
2015 		B_TRANSLATE("Change directory"), cdMessage);
2016 	BMenuItem* lnItem = new BMenuItem(
2017 		B_TRANSLATE("Create link here"), lnMessage);
2018 	BMenuItem* mvItem = new BMenuItem(B_TRANSLATE("Move here"), mvMessage);
2019 	BMenuItem* cpItem = new BMenuItem(B_TRANSLATE("Copy here"), cpMessage);
2020 	BMenuItem* chItem = new BMenuItem(B_TRANSLATE("Cancel"), NULL);
2021 
2022 	// if the refs point to different directorys disable the cd menu item
2023 	bool differentDirs = false;
2024 	BDirectory firstDir;
2025 	entry_ref ref;
2026 	int i = 0;
2027 	while (message->FindRef("refs", i++, &ref) == B_OK) {
2028 		BNode node(&ref);
2029 		BEntry entry(&ref);
2030 		BDirectory dir;
2031 		if (node.IsDirectory())
2032 			dir.SetTo(&ref);
2033 		else
2034 			entry.GetParent(&dir);
2035 
2036 		if (i == 1) {
2037 			node_ref nodeRef;
2038 			dir.GetNodeRef(&nodeRef);
2039 			firstDir.SetTo(&nodeRef);
2040 		} else if (firstDir != dir) {
2041 			differentDirs = true;
2042 			break;
2043 		}
2044 	}
2045 	if (differentDirs)
2046 		cdItem->SetEnabled(false);
2047 
2048 	BPopUpMenu *menu = new BPopUpMenu(
2049 		"Secondary mouse button drop menu");
2050 	menu->SetAsyncAutoDestruct(true);
2051 	menu->AddItem(insertItem);
2052 	menu->AddSeparatorItem();
2053 	menu->AddItem(cdItem);
2054 	menu->AddItem(lnItem);
2055 	menu->AddItem(mvItem);
2056 	menu->AddItem(cpItem);
2057 	menu->AddSeparatorItem();
2058 	menu->AddItem(chItem);
2059 	menu->SetTargetForItems(this);
2060 	menu->Go(point, true, true, true);
2061 }
2062 
2063 
2064 void
2065 TermView::_DoSecondaryMouseDropAction(BMessage* message)
2066 {
2067 	int8 action = -1;
2068 	message->FindInt8("action", &action);
2069 
2070 	BString outString = "";
2071 	BString itemString = "";
2072 
2073 	switch (action) {
2074 		case kInsert:
2075 			break;
2076 		case kChangeDirectory:
2077 			outString = "cd ";
2078 			break;
2079 		case kLinkFiles:
2080 			outString = "ln -s ";
2081 			break;
2082 		case kMoveFiles:
2083 			outString = "mv ";
2084 			break;
2085 		case kCopyFiles:
2086 			outString = "cp ";
2087 			break;
2088 
2089 		default:
2090 			return;
2091 	}
2092 
2093 	bool listContainsDirectory = false;
2094 	entry_ref ref;
2095 	int32 i = 0;
2096 	while (message->FindRef("refs", i++, &ref) == B_OK) {
2097 		BEntry ent(&ref);
2098 		BNode node(&ref);
2099 		BPath path(&ent);
2100 		BString string(path.Path());
2101 
2102 		if (node.IsDirectory())
2103 			listContainsDirectory = true;
2104 
2105 		if (i > 1)
2106 			itemString += " ";
2107 
2108 		if (action == kChangeDirectory) {
2109 			if (!node.IsDirectory()) {
2110 				int32 slash = string.FindLast("/");
2111 				string.Truncate(slash);
2112 			}
2113 			string.CharacterEscape(kShellEscapeCharacters, '\\');
2114 			itemString += string;
2115 			break;
2116 		}
2117 		string.CharacterEscape(kShellEscapeCharacters, '\\');
2118 		itemString += string;
2119 	}
2120 
2121 	if (listContainsDirectory && action == kCopyFiles)
2122 		outString += "-R ";
2123 
2124 	outString += itemString;
2125 
2126 	if (action == kLinkFiles || action == kMoveFiles || action == kCopyFiles)
2127 		outString += " .";
2128 
2129 	if (action != kInsert)
2130 		outString += "\n";
2131 
2132 	_WritePTY(outString.String(), outString.Length());
2133 }
2134 
2135 
2136 //! Gets dropped file full path and display it at cursor position.
2137 void
2138 TermView::_DoFileDrop(entry_ref& ref)
2139 {
2140 	BEntry ent(&ref);
2141 	BPath path(&ent);
2142 	BString string(path.Path());
2143 
2144 	string.CharacterEscape(kShellEscapeCharacters, '\\');
2145 	_WritePTY(string.String(), string.Length());
2146 }
2147 
2148 
2149 /*!	Text buffer must already be locked.
2150 */
2151 void
2152 TermView::_SynchronizeWithTextBuffer(int32 visibleDirtyTop,
2153 	int32 visibleDirtyBottom)
2154 {
2155 	TerminalBufferDirtyInfo& info = fTextBuffer->DirtyInfo();
2156 	int32 linesScrolled = info.linesScrolled;
2157 
2158 //debug_printf("TermView::_SynchronizeWithTextBuffer(): dirty: %ld - %ld, "
2159 //"scrolled: %ld, visible dirty: %ld - %ld\n", info.dirtyTop, info.dirtyBottom,
2160 //info.linesScrolled, visibleDirtyTop, visibleDirtyBottom);
2161 
2162 	bigtime_t now = system_time();
2163 	bigtime_t timeElapsed = now - fLastSyncTime;
2164 	if (timeElapsed > 2 * kSyncUpdateGranularity) {
2165 		// last sync was ages ago
2166 		fLastSyncTime = now;
2167 		fScrolledSinceLastSync = linesScrolled;
2168 	}
2169 
2170 	if (fSyncRunner == NULL) {
2171 		// We consider clocked syncing when more than a full screen height has
2172 		// been scrolled in less than a sync update period. Once we're
2173 		// actively considering it, the same condition will convince us to
2174 		// actually do it.
2175 		if (fScrolledSinceLastSync + linesScrolled <= fRows) {
2176 			// Condition doesn't hold yet. Reset if time is up, or otherwise
2177 			// keep counting.
2178 			if (timeElapsed > kSyncUpdateGranularity) {
2179 				fConsiderClockedSync = false;
2180 				fLastSyncTime = now;
2181 				fScrolledSinceLastSync = linesScrolled;
2182 			} else
2183 				fScrolledSinceLastSync += linesScrolled;
2184 		} else if (fConsiderClockedSync) {
2185 			// We are convinced -- create the sync runner.
2186 			fLastSyncTime = now;
2187 			fScrolledSinceLastSync = 0;
2188 
2189 			BMessage message(MSG_TERMINAL_BUFFER_CHANGED);
2190 			fSyncRunner = new(std::nothrow) BMessageRunner(BMessenger(this),
2191 				&message, kSyncUpdateGranularity);
2192 			if (fSyncRunner != NULL && fSyncRunner->InitCheck() == B_OK)
2193 				return;
2194 
2195 			delete fSyncRunner;
2196 			fSyncRunner = NULL;
2197 		} else {
2198 			// Looks interesting so far. Reset the counts and consider clocked
2199 			// syncing.
2200 			fConsiderClockedSync = true;
2201 			fLastSyncTime = now;
2202 			fScrolledSinceLastSync = 0;
2203 		}
2204 	} else if (timeElapsed < kSyncUpdateGranularity) {
2205 		// sync time not passed yet -- keep counting
2206 		fScrolledSinceLastSync += linesScrolled;
2207 		return;
2208 	}
2209 
2210 	if (fScrolledSinceLastSync + linesScrolled <= fRows) {
2211 		// time's up, but not enough happened
2212 		delete fSyncRunner;
2213 		fSyncRunner = NULL;
2214 		fLastSyncTime = now;
2215 		fScrolledSinceLastSync = linesScrolled;
2216 	} else {
2217 		// Things are still rolling, but the sync time's up.
2218 		fLastSyncTime = now;
2219 		fScrolledSinceLastSync = 0;
2220 	}
2221 
2222 	fVisibleTextBufferChanged = true;
2223 
2224 	// Simple case first -- complete invalidation.
2225 	if (info.invalidateAll) {
2226 		Invalidate();
2227 		_UpdateScrollBarRange();
2228 		_Deselect();
2229 
2230 		fCursor = fTextBuffer->Cursor();
2231 		_ActivateCursor(false);
2232 
2233 		int32 offset = _LineAt(0);
2234 		fVisibleTextBuffer->SynchronizeWith(fTextBuffer, offset, offset,
2235 			offset + fTextBuffer->Height() + 2);
2236 
2237 		info.Reset();
2238 		return;
2239 	}
2240 
2241 	BRect bounds = Bounds();
2242 	int32 firstVisible = _LineAt(0);
2243 	int32 lastVisible = _LineAt(bounds.bottom);
2244 	int32 historySize = fTextBuffer->HistorySize();
2245 
2246 	bool doScroll = false;
2247 	if (linesScrolled > 0) {
2248 		_UpdateScrollBarRange();
2249 
2250 		visibleDirtyTop -= linesScrolled;
2251 		visibleDirtyBottom -= linesScrolled;
2252 
2253 		if (firstVisible < 0) {
2254 			firstVisible -= linesScrolled;
2255 			lastVisible -= linesScrolled;
2256 
2257 			float scrollOffset;
2258 			if (firstVisible < -historySize) {
2259 				firstVisible = -historySize;
2260 				doScroll = true;
2261 				scrollOffset = -historySize * fFontHeight;
2262 				// We need to invalidate the lower linesScrolled lines of the
2263 				// visible text buffer, since those will be scrolled up and
2264 				// need to be replaced. We just use visibleDirty{Top,Bottom}
2265 				// for that purpose. Unless invoked from ScrollTo() (i.e.
2266 				// user-initiated scrolling) those are unused. In the unlikely
2267 				// case that the user is scrolling at the same time we may
2268 				// invalidate too many lines, since we have to extend the given
2269 				// region.
2270 				// Note that in the firstVisible == 0 case the new lines are
2271 				// already in the dirty region, so they will be updated anyway.
2272 				if (visibleDirtyTop <= visibleDirtyBottom) {
2273 					if (lastVisible < visibleDirtyTop)
2274 						visibleDirtyTop = lastVisible;
2275 					if (visibleDirtyBottom < lastVisible + linesScrolled)
2276 						visibleDirtyBottom = lastVisible + linesScrolled;
2277 				} else {
2278 					visibleDirtyTop = lastVisible + 1;
2279 					visibleDirtyBottom = lastVisible + linesScrolled;
2280 				}
2281 			} else
2282 				scrollOffset = fScrollOffset - linesScrolled * fFontHeight;
2283 
2284 			_ScrollTo(scrollOffset, false);
2285 		} else
2286 			doScroll = true;
2287 
2288 		if (doScroll && lastVisible >= firstVisible
2289 			&& !(info.IsDirtyRegionValid() && firstVisible >= info.dirtyTop
2290 				&& lastVisible <= info.dirtyBottom)) {
2291 			// scroll manually
2292 			float scrollBy = linesScrolled * fFontHeight;
2293 			BRect destRect(Frame().OffsetToCopy(B_ORIGIN));
2294 			BRect sourceRect(destRect.OffsetByCopy(0, scrollBy));
2295 
2296 			// invalidate the current cursor position before scrolling
2297 			_InvalidateTextRect(fCursor.x, fCursor.y, fCursor.x, fCursor.y);
2298 
2299 //debug_printf("CopyBits(((%f, %f) - (%f, %f)) -> (%f, %f) - (%f, %f))\n",
2300 //sourceRect.left, sourceRect.top, sourceRect.right, sourceRect.bottom,
2301 //destRect.left, destRect.top, destRect.right, destRect.bottom);
2302 			CopyBits(sourceRect, destRect);
2303 
2304 			fVisibleTextBuffer->ScrollBy(linesScrolled);
2305 		}
2306 
2307 		// move highlights
2308 		for (int32 i = 0; Highlight* highlight = fHighlights.ItemAt(i); i++) {
2309 			if (highlight->IsEmpty())
2310 				continue;
2311 
2312 			highlight->ScrollRange(linesScrolled);
2313 			if (highlight == &fSelection) {
2314 				fInitialSelectionStart.y -= linesScrolled;
2315 				fInitialSelectionEnd.y -= linesScrolled;
2316 			}
2317 
2318 			if (highlight->Start().y < -historySize) {
2319 				if (highlight == &fSelection)
2320 					_Deselect();
2321 				else
2322 					_ClearHighlight(highlight);
2323 			}
2324 		}
2325 	}
2326 
2327 	// invalidate dirty region
2328 	if (info.IsDirtyRegionValid()) {
2329 		_InvalidateTextRect(0, info.dirtyTop, fTextBuffer->Width() - 1,
2330 			info.dirtyBottom);
2331 
2332 		// clear the selection, if affected
2333 		if (!fSelection.IsEmpty()) {
2334 			// TODO: We're clearing the selection more often than necessary --
2335 			// to avoid that, we'd also need to track the x coordinates of the
2336 			// dirty range.
2337 			int32 selectionBottom = fSelection.End().x > 0
2338 				? fSelection.End().y : fSelection.End().y - 1;
2339 			if (fSelection.Start().y <= info.dirtyBottom
2340 				&& info.dirtyTop <= selectionBottom) {
2341 				_Deselect();
2342 			}
2343 		}
2344 	}
2345 
2346 	if (visibleDirtyTop <= visibleDirtyBottom)
2347 		info.ExtendDirtyRegion(visibleDirtyTop, visibleDirtyBottom);
2348 
2349 	if (linesScrolled != 0 || info.IsDirtyRegionValid()) {
2350 		fVisibleTextBuffer->SynchronizeWith(fTextBuffer, firstVisible,
2351 			info.dirtyTop, info.dirtyBottom);
2352 	}
2353 
2354 	// invalidate cursor, if it changed
2355 	TermPos cursor = fTextBuffer->Cursor();
2356 	if (fCursor != cursor || linesScrolled != 0) {
2357 		// Before we scrolled we did already invalidate the old cursor.
2358 		if (!doScroll)
2359 			_InvalidateTextRect(fCursor.x, fCursor.y, fCursor.x, fCursor.y);
2360 		fCursor = cursor;
2361 		_InvalidateTextRect(fCursor.x, fCursor.y, fCursor.x, fCursor.y);
2362 		_ActivateCursor(false);
2363 	}
2364 
2365 	info.Reset();
2366 }
2367 
2368 
2369 void
2370 TermView::_VisibleTextBufferChanged()
2371 {
2372 	if (!fVisibleTextBufferChanged)
2373 		return;
2374 
2375 	fVisibleTextBufferChanged = false;
2376 	fActiveState->VisibleTextBufferChanged();
2377 }
2378 
2379 
2380 /*!	Write strings to PTY device. If encoding system isn't UTF8, change
2381 	encoding to UTF8 before writing PTY.
2382 */
2383 void
2384 TermView::_WritePTY(const char* text, int32 numBytes)
2385 {
2386 	if (fEncoding != M_UTF8) {
2387 		while (numBytes > 0) {
2388 			char buffer[1024];
2389 			int32 bufferSize = sizeof(buffer);
2390 			int32 sourceSize = numBytes;
2391 			int32 state = 0;
2392 			if (convert_to_utf8(fEncoding, text, &sourceSize, buffer,
2393 					&bufferSize, &state) != B_OK || bufferSize == 0) {
2394 				break;
2395 			}
2396 
2397 			fShell->Write(buffer, bufferSize);
2398 			text += sourceSize;
2399 			numBytes -= sourceSize;
2400 		}
2401 	} else {
2402 		fShell->Write(text, numBytes);
2403 	}
2404 }
2405 
2406 
2407 //! Returns the square of the actual pixel distance between both points
2408 float
2409 TermView::_MouseDistanceSinceLastClick(BPoint where)
2410 {
2411 	return (fLastClickPoint.x - where.x) * (fLastClickPoint.x - where.x)
2412 		+ (fLastClickPoint.y - where.y) * (fLastClickPoint.y - where.y);
2413 }
2414 
2415 
2416 void
2417 TermView::_SendMouseEvent(int32 buttons, int32 mode, int32 x, int32 y,
2418 	bool motion)
2419 {
2420 	if (!fEnableExtendedMouseCoordinates) {
2421 		char xtermButtons;
2422 		if (buttons == B_PRIMARY_MOUSE_BUTTON)
2423 			xtermButtons = 32 + 0;
2424 		else if (buttons == B_SECONDARY_MOUSE_BUTTON)
2425 			xtermButtons = 32 + 1;
2426 		else if (buttons == B_TERTIARY_MOUSE_BUTTON)
2427 			xtermButtons = 32 + 2;
2428 		else
2429 			xtermButtons = 32 + 3;
2430 
2431 		if (motion)
2432 			xtermButtons += 32;
2433 
2434 		char xtermX = x + 1 + 32;
2435 		char xtermY = y + 1 + 32;
2436 
2437 		char destBuffer[6];
2438 		destBuffer[0] = '\033';
2439 		destBuffer[1] = '[';
2440 		destBuffer[2] = 'M';
2441 		destBuffer[3] = xtermButtons;
2442 		destBuffer[4] = xtermX;
2443 		destBuffer[5] = xtermY;
2444 		fShell->Write(destBuffer, 6);
2445 	} else {
2446 		char xtermButtons;
2447 		if (buttons == B_PRIMARY_MOUSE_BUTTON)
2448 			xtermButtons = 0;
2449 		else if (buttons == B_SECONDARY_MOUSE_BUTTON)
2450 			xtermButtons = 1;
2451 		else if (buttons == B_TERTIARY_MOUSE_BUTTON)
2452 			xtermButtons = 2;
2453 		else
2454 			xtermButtons = 3;
2455 
2456 		if (motion)
2457 			xtermButtons += 32;
2458 
2459 		int16 xtermX = x + 1;
2460 		int16 xtermY = y + 1;
2461 
2462 		char destBuffer[13];
2463 		destBuffer[0] = '\033';
2464 		destBuffer[1] = '[';
2465 		destBuffer[2] = '<';
2466 		destBuffer[3] = xtermButtons + '0';
2467 		destBuffer[4] = ';';
2468 		destBuffer[5] = xtermX / 100 % 10 + '0';
2469 		destBuffer[6] = xtermX / 10 % 10 + '0';
2470 		destBuffer[7] = xtermX % 10 + '0';
2471 		destBuffer[8] = ';';
2472 		destBuffer[9] = xtermY / 100 % 10 + '0';
2473 		destBuffer[10] = xtermY / 10 % 10 + '0';
2474 		destBuffer[11] = xtermY % 10 + '0';
2475 		// No support for button press/release
2476 		destBuffer[12] = 'M';
2477 		fShell->Write(destBuffer, 13);
2478 	}
2479 }
2480 
2481 
2482 void
2483 TermView::MouseDown(BPoint where)
2484 {
2485 	if (!IsFocus())
2486 		MakeFocus();
2487 
2488 	_UpdateModifiers();
2489 
2490 	BMessage* currentMessage = Window()->CurrentMessage();
2491 	int32 buttons = currentMessage->GetInt32("buttons", 0);
2492 
2493 	fActiveState->MouseDown(where, buttons, fModifiers);
2494 
2495 	fMouseButtons = buttons;
2496 	fLastClickPoint = where;
2497 }
2498 
2499 
2500 void
2501 TermView::MouseMoved(BPoint where, uint32 transit, const BMessage *message)
2502 {
2503 	_UpdateModifiers();
2504 
2505 	fActiveState->MouseMoved(where, transit, message, fModifiers);
2506 }
2507 
2508 
2509 void
2510 TermView::MouseUp(BPoint where)
2511 {
2512 	_UpdateModifiers();
2513 
2514 	int32 buttons = Window()->CurrentMessage()->GetInt32("buttons", 0);
2515 
2516 	fActiveState->MouseUp(where, buttons);
2517 
2518 	fMouseButtons = buttons;
2519 }
2520 
2521 
2522 //! Select a range of text.
2523 void
2524 TermView::_Select(TermPos start, TermPos end, bool inclusive,
2525 	bool setInitialSelection)
2526 {
2527 	TextBufferSyncLocker _(this);
2528 
2529 	_SynchronizeWithTextBuffer(0, -1);
2530 
2531 	if (end < start)
2532 		std::swap(start, end);
2533 
2534 	if (inclusive)
2535 		end.x++;
2536 
2537 //debug_printf("TermView::_Select(): (%ld, %ld) - (%ld, %ld)\n", start.x,
2538 //start.y, end.x, end.y);
2539 
2540 	if (start.x < 0)
2541 		start.x = 0;
2542 	if (end.x >= fColumns)
2543 		end.x = fColumns;
2544 
2545 	TermPos minPos(0, -fTextBuffer->HistorySize());
2546 	TermPos maxPos(0, fTextBuffer->Height());
2547 	start = restrict_value(start, minPos, maxPos);
2548 	end = restrict_value(end, minPos, maxPos);
2549 
2550 	// if the end is past the end of the line, select the line break, too
2551 	if (fTextBuffer->LineLength(end.y) < end.x
2552 			&& end.y < fTextBuffer->Height()) {
2553 		end.y++;
2554 		end.x = 0;
2555 	}
2556 
2557 	if (fTextBuffer->IsFullWidthChar(start.y, start.x)) {
2558 		start.x--;
2559 		if (start.x < 0)
2560 			start.x = 0;
2561 	}
2562 
2563 	if (fTextBuffer->IsFullWidthChar(end.y, end.x)) {
2564 		end.x++;
2565 		if (end.x >= fColumns)
2566 			end.x = fColumns;
2567 	}
2568 
2569 	if (!fSelection.IsEmpty())
2570 		_InvalidateTextRange(fSelection.Start(), fSelection.End());
2571 
2572 	fSelection.SetRange(start, end);
2573 
2574 	if (setInitialSelection) {
2575 		fInitialSelectionStart = fSelection.Start();
2576 		fInitialSelectionEnd = fSelection.End();
2577 	}
2578 
2579 	_InvalidateTextRange(fSelection.Start(), fSelection.End());
2580 }
2581 
2582 
2583 //! Extend selection (shift + mouse click).
2584 void
2585 TermView::_ExtendSelection(TermPos pos, bool inclusive,
2586 	bool useInitialSelection)
2587 {
2588 	if (!useInitialSelection && !_HasSelection())
2589 		return;
2590 
2591 	TermPos start = fSelection.Start();
2592 	TermPos end = fSelection.End();
2593 
2594 	if (useInitialSelection) {
2595 		start = fInitialSelectionStart;
2596 		end = fInitialSelectionEnd;
2597 	}
2598 
2599 	if (inclusive) {
2600 		if (pos >= start && pos >= end)
2601 			pos.x++;
2602 	}
2603 
2604 	if (pos < start)
2605 		_Select(pos, end, false, !useInitialSelection);
2606 	else if (pos > end)
2607 		_Select(start, pos, false, !useInitialSelection);
2608 	else if (useInitialSelection)
2609 		_Select(start, end, false, false);
2610 }
2611 
2612 
2613 // clear the selection.
2614 void
2615 TermView::_Deselect()
2616 {
2617 //debug_printf("TermView::_Deselect(): has selection: %d\n", _HasSelection());
2618 	if (_ClearHighlight(&fSelection)) {
2619 		fInitialSelectionStart.SetTo(0, 0);
2620 		fInitialSelectionEnd.SetTo(0, 0);
2621 	}
2622 }
2623 
2624 
2625 bool
2626 TermView::_HasSelection() const
2627 {
2628 	return !fSelection.IsEmpty();
2629 }
2630 
2631 
2632 void
2633 TermView::_SelectWord(BPoint where, bool extend, bool useInitialSelection)
2634 {
2635 	BAutolock _(fTextBuffer);
2636 
2637 	TermPos pos = _ConvertToTerminal(where);
2638 	TermPos start, end;
2639 	if (!fTextBuffer->FindWord(pos, fCharClassifier, true, start, end))
2640 		return;
2641 
2642 	if (extend) {
2643 		if (start
2644 				< (useInitialSelection
2645 					? fInitialSelectionStart : fSelection.Start())) {
2646 			_ExtendSelection(start, false, useInitialSelection);
2647 		} else if (end
2648 				> (useInitialSelection
2649 					? fInitialSelectionEnd : fSelection.End())) {
2650 			_ExtendSelection(end, false, useInitialSelection);
2651 		} else if (useInitialSelection)
2652 			_Select(start, end, false, false);
2653 	} else
2654 		_Select(start, end, false, !useInitialSelection);
2655 }
2656 
2657 
2658 void
2659 TermView::_SelectLine(BPoint where, bool extend, bool useInitialSelection)
2660 {
2661 	TermPos start = TermPos(0, _ConvertToTerminal(where).y);
2662 	TermPos end = TermPos(0, start.y + 1);
2663 
2664 	if (extend) {
2665 		if (start
2666 				< (useInitialSelection
2667 					? fInitialSelectionStart : fSelection.Start())) {
2668 			_ExtendSelection(start, false, useInitialSelection);
2669 		} else if (end
2670 				> (useInitialSelection
2671 					? fInitialSelectionEnd : fSelection.End())) {
2672 			_ExtendSelection(end, false, useInitialSelection);
2673 		} else if (useInitialSelection)
2674 			_Select(start, end, false, false);
2675 	} else
2676 		_Select(start, end, false, !useInitialSelection);
2677 }
2678 
2679 
2680 void
2681 TermView::_AddHighlight(Highlight* highlight)
2682 {
2683 	fHighlights.AddItem(highlight);
2684 
2685 	if (!highlight->IsEmpty())
2686 		_InvalidateTextRange(highlight->Start(), highlight->End());
2687 }
2688 
2689 
2690 void
2691 TermView::_RemoveHighlight(Highlight* highlight)
2692 {
2693 	if (!highlight->IsEmpty())
2694 		_InvalidateTextRange(highlight->Start(), highlight->End());
2695 
2696 	fHighlights.RemoveItem(highlight);
2697 }
2698 
2699 
2700 bool
2701 TermView::_ClearHighlight(Highlight* highlight)
2702 {
2703 	if (highlight->IsEmpty())
2704 		return false;
2705 
2706 	_InvalidateTextRange(highlight->Start(), highlight->End());
2707 
2708 	highlight->SetRange(TermPos(0, 0), TermPos(0, 0));
2709 	return true;
2710 }
2711 
2712 
2713 TermView::Highlight*
2714 TermView::_CheckHighlightRegion(const TermPos &pos) const
2715 {
2716 	for (int32 i = 0; Highlight* highlight = fHighlights.ItemAt(i); i++) {
2717 		if (highlight->RangeContains(pos))
2718 			return highlight;
2719 	}
2720 
2721 	return NULL;
2722 }
2723 
2724 
2725 TermView::Highlight*
2726 TermView::_CheckHighlightRegion(int32 row, int32 firstColumn,
2727 	int32& lastColumn) const
2728 {
2729 	Highlight* nextHighlight = NULL;
2730 
2731 	for (int32 i = 0; Highlight* highlight = fHighlights.ItemAt(i); i++) {
2732 		if (highlight->IsEmpty())
2733 			continue;
2734 
2735 		if (row == highlight->Start().y && firstColumn < highlight->Start().x
2736 				&& lastColumn >= highlight->Start().x) {
2737 			// region starts before the highlight, but intersects with it
2738 			if (nextHighlight == NULL
2739 				|| highlight->Start().x < nextHighlight->Start().x) {
2740 				nextHighlight = highlight;
2741 			}
2742 			continue;
2743 		}
2744 
2745 		if (row == highlight->End().y && firstColumn < highlight->End().x
2746 				&& lastColumn >= highlight->End().x) {
2747 			// region starts in the highlight, but exceeds the end
2748 			lastColumn = highlight->End().x - 1;
2749 			return highlight;
2750 		}
2751 
2752 		TermPos pos(firstColumn, row);
2753 		if (highlight->RangeContains(pos))
2754 			return highlight;
2755 	}
2756 
2757 	if (nextHighlight != NULL)
2758 		lastColumn = nextHighlight->Start().x - 1;
2759 	return NULL;
2760 }
2761 
2762 
2763 void
2764 TermView::GetFrameSize(float *width, float *height)
2765 {
2766 	int32 historySize;
2767 	{
2768 		BAutolock _(fTextBuffer);
2769 		historySize = fTextBuffer->HistorySize();
2770 	}
2771 
2772 	if (width != NULL)
2773 		*width = fColumns * fFontWidth;
2774 
2775 	if (height != NULL)
2776 		*height = (fRows + historySize) * fFontHeight;
2777 }
2778 
2779 
2780 // Find a string, and select it if found
2781 bool
2782 TermView::Find(const BString &str, bool forwardSearch, bool matchCase,
2783 	bool matchWord)
2784 {
2785 	TextBufferSyncLocker _(this);
2786 	_SynchronizeWithTextBuffer(0, -1);
2787 
2788 	TermPos start;
2789 	if (_HasSelection()) {
2790 		if (forwardSearch)
2791 			start = fSelection.End();
2792 		else
2793 			start = fSelection.Start();
2794 	} else {
2795 		// search from the very beginning/end
2796 		if (forwardSearch)
2797 			start = TermPos(0, -fTextBuffer->HistorySize());
2798 		else
2799 			start = TermPos(0, fTextBuffer->Height());
2800 	}
2801 
2802 	TermPos matchStart, matchEnd;
2803 	if (!fTextBuffer->Find(str.String(), start, forwardSearch, matchCase,
2804 			matchWord, matchStart, matchEnd)) {
2805 		return false;
2806 	}
2807 
2808 	_Select(matchStart, matchEnd, false, true);
2809 	_ScrollToRange(fSelection.Start(), fSelection.End());
2810 
2811 	return true;
2812 }
2813 
2814 
2815 //! Get the selected text and copy to str
2816 void
2817 TermView::GetSelection(BString &str)
2818 {
2819 	str.SetTo("");
2820 	BAutolock _(fTextBuffer);
2821 	fTextBuffer->GetStringFromRegion(str, fSelection.Start(), fSelection.End());
2822 }
2823 
2824 
2825 bool
2826 TermView::CheckShellGone() const
2827 {
2828 	if (!fShell)
2829 		return false;
2830 
2831 	// check, if the shell does still live
2832 	pid_t pid = fShell->ProcessID();
2833 	team_info info;
2834 	return get_team_info(pid, &info) == B_BAD_TEAM_ID;
2835 }
2836 
2837 
2838 void
2839 TermView::InitiateDrag()
2840 {
2841 	BAutolock _(fTextBuffer);
2842 
2843 	BString copyStr("");
2844 	fTextBuffer->GetStringFromRegion(copyStr, fSelection.Start(),
2845 		fSelection.End());
2846 
2847 	BMessage message(B_MIME_DATA);
2848 	message.AddData("text/plain", B_MIME_TYPE, copyStr.String(),
2849 		copyStr.Length());
2850 
2851 	BPoint start = _ConvertFromTerminal(fSelection.Start());
2852 	BPoint end = _ConvertFromTerminal(fSelection.End());
2853 
2854 	BRect rect;
2855 	if (fSelection.Start().y == fSelection.End().y)
2856 		rect.Set(start.x, start.y, end.x + fFontWidth, end.y + fFontHeight);
2857 	else
2858 		rect.Set(0, start.y, fColumns * fFontWidth, end.y + fFontHeight);
2859 
2860 	rect = rect & Bounds();
2861 
2862 	DragMessage(&message, rect);
2863 }
2864 
2865 
2866 void
2867 TermView::_ScrollTo(float y, bool scrollGfx)
2868 {
2869 	if (!scrollGfx)
2870 		fScrollOffset = y;
2871 
2872 	if (fScrollBar != NULL)
2873 		fScrollBar->SetValue(y);
2874 	else
2875 		ScrollTo(BPoint(0, y));
2876 }
2877 
2878 
2879 void
2880 TermView::_ScrollToRange(TermPos start, TermPos end)
2881 {
2882 	if (start > end)
2883 		std::swap(start, end);
2884 
2885 	float startY = _LineOffset(start.y);
2886 	float endY = _LineOffset(end.y) + fFontHeight - 1;
2887 	float height = Bounds().Height();
2888 
2889 	if (endY - startY > height) {
2890 		// The range is greater than the height. Scroll to the closest border.
2891 
2892 		// already as good as it gets?
2893 		if (startY <= 0 && endY >= height)
2894 			return;
2895 
2896 		if (startY > 0) {
2897 			// scroll down to align the start with the top of the view
2898 			_ScrollTo(fScrollOffset + startY, true);
2899 		} else {
2900 			// scroll up to align the end with the bottom of the view
2901 			_ScrollTo(fScrollOffset + endY - height, true);
2902 		}
2903 	} else {
2904 		// The range is smaller than the height.
2905 
2906 		// already visible?
2907 		if (startY >= 0 && endY <= height)
2908 			return;
2909 
2910 		if (startY < 0) {
2911 			// scroll up to make the start visible
2912 			_ScrollTo(fScrollOffset + startY, true);
2913 		} else {
2914 			// scroll down to make the end visible
2915 			_ScrollTo(fScrollOffset + endY - height, true);
2916 		}
2917 	}
2918 }
2919 
2920 
2921 void
2922 TermView::DisableResizeView(int32 disableCount)
2923 {
2924 	fResizeViewDisableCount += disableCount;
2925 }
2926 
2927 
2928 void
2929 TermView::_DrawInlineMethodString()
2930 {
2931 	if (!fInline || !fInline->String())
2932 		return;
2933 
2934 	const int32 numChars = BString(fInline->String()).CountChars();
2935 
2936 	BPoint startPoint = _ConvertFromTerminal(fCursor);
2937 	BPoint endPoint = startPoint;
2938 	endPoint.x += fFontWidth * numChars;
2939 	endPoint.y += fFontHeight + 1;
2940 
2941 	BRect eraseRect(startPoint, endPoint);
2942 
2943 	PushState();
2944 	SetHighColor(fTextForeColor);
2945 	FillRect(eraseRect);
2946 	PopState();
2947 
2948 	BPoint loc = _ConvertFromTerminal(fCursor);
2949 	loc.y += fFontHeight;
2950 	SetFont(&fHalfFont);
2951 	SetHighColor(fTextBackColor);
2952 	SetLowColor(fTextForeColor);
2953 	DrawString(fInline->String(), loc);
2954 }
2955 
2956 
2957 void
2958 TermView::_HandleInputMethodChanged(BMessage *message)
2959 {
2960 	const char *string = NULL;
2961 	if (message->FindString("be:string", &string) < B_OK || string == NULL)
2962 		return;
2963 
2964 	_ActivateCursor(false);
2965 
2966 	if (IsFocus())
2967 		be_app->ObscureCursor();
2968 
2969 	// If we find the "be:confirmed" boolean (and the boolean is true),
2970 	// it means it's over for now, so the current InlineInput object
2971 	// should become inactive. We will probably receive a
2972 	// B_INPUT_METHOD_STOPPED message after this one.
2973 	bool confirmed;
2974 	if (message->FindBool("be:confirmed", &confirmed) != B_OK)
2975 		confirmed = false;
2976 
2977 	fInline->SetString("");
2978 
2979 	Invalidate();
2980 	// TODO: Debug only
2981 	snooze(100000);
2982 
2983 	fInline->SetString(string);
2984 	fInline->ResetClauses();
2985 
2986 	if (!confirmed && !fInline->IsActive())
2987 		fInline->SetActive(true);
2988 
2989 	// Get the clauses, and pass them to the InlineInput object
2990 	// TODO: Find out if what we did it's ok, currently we don't consider
2991 	// clauses at all, while the bebook says we should; though the visual
2992 	// effect we obtained seems correct. Weird.
2993 	int32 clauseCount = 0;
2994 	int32 clauseStart;
2995 	int32 clauseEnd;
2996 	while (message->FindInt32("be:clause_start", clauseCount, &clauseStart)
2997 			== B_OK
2998 		&& message->FindInt32("be:clause_end", clauseCount, &clauseEnd)
2999 			== B_OK) {
3000 		if (!fInline->AddClause(clauseStart, clauseEnd))
3001 			break;
3002 		clauseCount++;
3003 	}
3004 
3005 	if (confirmed) {
3006 		fInline->SetString("");
3007 		_ActivateCursor(true);
3008 
3009 		// now we need to feed ourselves the individual characters as if the
3010 		// user would have pressed them now - this lets KeyDown() pick out all
3011 		// the special characters like B_BACKSPACE, cursor keys and the like:
3012 		const char* currPos = string;
3013 		const char* prevPos = currPos;
3014 		while (*currPos != '\0') {
3015 			if ((*currPos & 0xC0) == 0xC0) {
3016 				// found the start of an UTF-8 char, we collect while it lasts
3017 				++currPos;
3018 				while ((*currPos & 0xC0) == 0x80)
3019 					++currPos;
3020 			} else if ((*currPos & 0xC0) == 0x80) {
3021 				// illegal: character starts with utf-8 intermediate byte, skip it
3022 				prevPos = ++currPos;
3023 			} else {
3024 				// single byte character/code, just feed that
3025 				++currPos;
3026 			}
3027 			KeyDown(prevPos, currPos - prevPos);
3028 			prevPos = currPos;
3029 		}
3030 	} else {
3031 		// temporarily show transient state of inline input
3032 		int32 selectionStart = 0;
3033 		int32 selectionEnd = 0;
3034 		message->FindInt32("be:selection", 0, &selectionStart);
3035 		message->FindInt32("be:selection", 1, &selectionEnd);
3036 
3037 		fInline->SetSelectionOffset(selectionStart);
3038 		fInline->SetSelectionLength(selectionEnd - selectionStart);
3039 	}
3040 	Invalidate();
3041 }
3042 
3043 
3044 void
3045 TermView::_HandleInputMethodLocationRequest()
3046 {
3047 	BMessage message(B_INPUT_METHOD_EVENT);
3048 	message.AddInt32("be:opcode", B_INPUT_METHOD_LOCATION_REQUEST);
3049 
3050 	BString string(fInline->String());
3051 
3052 	const int32 &limit = string.CountChars();
3053 	BPoint where = _ConvertFromTerminal(fCursor);
3054 	where.y += fFontHeight;
3055 
3056 	for (int32 i = 0; i < limit; i++) {
3057 		// Add the location of the UTF8 characters
3058 
3059 		where.x += fFontWidth;
3060 		ConvertToScreen(&where);
3061 
3062 		message.AddPoint("be:location_reply", where);
3063 		message.AddFloat("be:height_reply", fFontHeight);
3064 	}
3065 
3066 	fInline->Method()->SendMessage(&message);
3067 }
3068 
3069 
3070 void
3071 TermView::_CancelInputMethod()
3072 {
3073 	if (!fInline)
3074 		return;
3075 
3076 	InlineInput *inlineInput = fInline;
3077 	fInline = NULL;
3078 
3079 	if (inlineInput->IsActive() && Window()) {
3080 		Invalidate();
3081 
3082 		BMessage message(B_INPUT_METHOD_EVENT);
3083 		message.AddInt32("be:opcode", B_INPUT_METHOD_STOPPED);
3084 		inlineInput->Method()->SendMessage(&message);
3085 	}
3086 
3087 	delete inlineInput;
3088 }
3089 
3090 
3091 void
3092 TermView::_UpdateModifiers()
3093 {
3094 	// TODO: This method is a general work-around for missing or out-of-order
3095 	// B_MODIFIERS_CHANGED messages. This should really be fixed where it is
3096 	// broken (app server?).
3097 	int32 oldModifiers = fModifiers;
3098 	fModifiers = modifiers();
3099 	if (fModifiers != oldModifiers && fActiveState != NULL)
3100 		fActiveState->ModifiersChanged(oldModifiers, fModifiers);
3101 }
3102 
3103 
3104 void
3105 TermView::_NextState(State* state)
3106 {
3107 	if (state != fActiveState) {
3108 		if (fActiveState != NULL)
3109 			fActiveState->Exited();
3110 		fActiveState = state;
3111 		fActiveState->Entered();
3112 	}
3113 }
3114 
3115 
3116 // #pragma mark - Listener
3117 
3118 
3119 TermView::Listener::~Listener()
3120 {
3121 }
3122 
3123 
3124 void
3125 TermView::Listener::NotifyTermViewQuit(TermView* view, int32 reason)
3126 {
3127 }
3128 
3129 
3130 void
3131 TermView::Listener::SetTermViewTitle(TermView* view, const char* title)
3132 {
3133 }
3134 
3135 
3136 void
3137 TermView::Listener::PreviousTermView(TermView* view)
3138 {
3139 }
3140 
3141 
3142 void
3143 TermView::Listener::NextTermView(TermView* view)
3144 {
3145 }
3146 
3147 
3148 // #pragma mark -
3149 
3150 
3151 #ifdef USE_DEBUG_SNAPSHOTS
3152 
3153 void
3154 TermView::MakeDebugSnapshots()
3155 {
3156 	BAutolock _(fTextBuffer);
3157 	time_t timeStamp = time(NULL);
3158 	fTextBuffer->MakeLinesSnapshots(timeStamp, ".TextBuffer.dump");
3159 	fVisibleTextBuffer->MakeLinesSnapshots(timeStamp, ".VisualTextBuffer.dump");
3160 }
3161 
3162 
3163 void
3164 TermView::StartStopDebugCapture()
3165 {
3166 	BAutolock _(fTextBuffer);
3167 	fTextBuffer->StartStopDebugCapture();
3168 }
3169 
3170 #endif
3171