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