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