xref: /haiku/src/apps/terminal/TermWindow.cpp (revision b0944c78b074a8110bd98e060415d0e8f38a7f65)
1 /*
2  * Copyright 2007-2013, Haiku, Inc. All rights reserved.
3  * Copyright (c) 2004 Daniel Furrer <assimil8or@users.sourceforge.net>
4  * Copyright (c) 2003-2004 Kian Duffy <myob@users.sourceforge.net>
5  * Copyright (C) 1998,99 Kazuho Okui and Takashi Murai.
6  *
7  * Distributed under the terms of the MIT license.
8  *
9  * Authors:
10  *		Kian Duffy, myob@users.sourceforge.net
11  *		Daniel Furrer, assimil8or@users.sourceforge.net
12  *		John Scipione, jscipione@gmail.com
13  *		Siarzhuk Zharski, zharik@gmx.li
14  */
15 
16 #include "TermWindow.h"
17 
18 #include <new>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <time.h>
23 
24 #include <Alert.h>
25 #include <Application.h>
26 #include <Catalog.h>
27 #include <CharacterSet.h>
28 #include <CharacterSetRoster.h>
29 #include <Clipboard.h>
30 #include <Dragger.h>
31 #include <File.h>
32 #include <FindDirectory.h>
33 #include <LayoutBuilder.h>
34 #include <LayoutUtils.h>
35 #include <Locale.h>
36 #include <Menu.h>
37 #include <MenuBar.h>
38 #include <MenuItem.h>
39 #include <Path.h>
40 #include <PopUpMenu.h>
41 #include <PrintJob.h>
42 #include <Rect.h>
43 #include <Roster.h>
44 #include <Screen.h>
45 #include <ScrollBar.h>
46 #include <ScrollView.h>
47 #include <String.h>
48 #include <UTF8.h>
49 
50 #include <AutoLocker.h>
51 
52 #include "ActiveProcessInfo.h"
53 #include "Arguments.h"
54 #include "AppearPrefView.h"
55 #include "FindWindow.h"
56 #include "Globals.h"
57 #include "PrefWindow.h"
58 #include "PrefHandler.h"
59 #include "SetTitleDialog.h"
60 #include "ShellParameters.h"
61 #include "TermConst.h"
62 #include "TermScrollView.h"
63 #include "TitlePlaceholderMapper.h"
64 
65 
66 const static int32 kMaxTabs = 6;
67 const static int32 kTermViewOffset = 3;
68 
69 const static int32 kMinimumFontSize = 8;
70 const static int32 kMaximumFontSize = 36;
71 
72 // messages constants
73 static const uint32 kNewTab = 'NTab';
74 static const uint32 kCloseView = 'ClVw';
75 static const uint32 kCloseOtherViews = 'CloV';
76 static const uint32 kIncreaseFontSize = 'InFs';
77 static const uint32 kDecreaseFontSize = 'DcFs';
78 static const uint32 kSetActiveTab = 'STab';
79 static const uint32 kUpdateTitles = 'UPti';
80 static const uint32 kEditTabTitle = 'ETti';
81 static const uint32 kEditWindowTitle = 'EWti';
82 static const uint32 kTabTitleChanged = 'TTch';
83 static const uint32 kWindowTitleChanged = 'WTch';
84 static const uint32 kUpdateSwitchTerminalsMenuItem = 'Ustm';
85 
86 using namespace BPrivate ; // BCharacterSet stuff
87 
88 #undef B_TRANSLATION_CONTEXT
89 #define B_TRANSLATION_CONTEXT "Terminal TermWindow"
90 
91 // actually an arrow
92 #define UTF8_ENTER "\xe2\x86\xb5"
93 
94 
95 // #pragma mark - TermViewContainerView
96 
97 
98 class TermViewContainerView : public BView {
99 public:
100 	TermViewContainerView(TermView* termView)
101 		:
102 		BView(BRect(), "term view container", B_FOLLOW_ALL, 0),
103 		fTermView(termView)
104 	{
105 		termView->MoveTo(kTermViewOffset, kTermViewOffset);
106 		BRect frame(termView->Frame());
107 		ResizeTo(frame.right + kTermViewOffset, frame.bottom + kTermViewOffset);
108 		AddChild(termView);
109 	}
110 
111 	TermView* GetTermView() const	{ return fTermView; }
112 
113 	virtual void GetPreferredSize(float* _width, float* _height)
114 	{
115 		float width, height;
116 		fTermView->GetPreferredSize(&width, &height);
117 		*_width = width + 2 * kTermViewOffset;
118 		*_height = height + 2 * kTermViewOffset;
119 	}
120 
121 private:
122 	TermView*	fTermView;
123 };
124 
125 
126 // #pragma mark - SessionID
127 
128 
129 TermWindow::SessionID::SessionID(int32 id)
130 	:
131 	fID(id)
132 {
133 }
134 
135 
136 TermWindow::SessionID::SessionID(const BMessage& message, const char* field)
137 {
138 	if (message.FindInt32(field, &fID) != B_OK)
139 		fID = -1;
140 }
141 
142 
143 status_t
144 TermWindow::SessionID::AddToMessage(BMessage& message, const char* field) const
145 {
146 	return message.AddInt32(field, fID);
147 }
148 
149 
150 // #pragma mark - Session
151 
152 
153 struct TermWindow::Session {
154 	SessionID				id;
155 	int32					index;
156 	Title					title;
157 	TermViewContainerView*	containerView;
158 
159 	Session(SessionID id, int32 index, TermViewContainerView* containerView)
160 		:
161 		id(id),
162 		index(index),
163 		containerView(containerView)
164 	{
165 		title.title = B_TRANSLATE("Shell ");
166 		title.title << index;
167 		title.patternUserDefined = false;
168 	}
169 };
170 
171 
172 // #pragma mark - TermWindow
173 
174 
175 TermWindow::TermWindow(const BString& title, Arguments* args)
176 	:
177 	BWindow(BRect(0, 0, 0, 0), title, B_DOCUMENT_WINDOW,
178 		B_CURRENT_WORKSPACE | B_QUIT_ON_WINDOW_CLOSE),
179 	fTitleUpdateRunner(this, BMessage(kUpdateTitles), 1000000),
180 	fNextSessionID(0),
181 	fTabView(NULL),
182 	fMenuBar(NULL),
183 	fSwitchTerminalsMenuItem(NULL),
184 	fEncodingMenu(NULL),
185 	fPrintSettings(NULL),
186 	fPrefWindow(NULL),
187 	fFindPanel(NULL),
188 	fSavedFrame(0, 0, -1, -1),
189 	fSetWindowTitleDialog(NULL),
190 	fSetTabTitleDialog(NULL),
191 	fFindString(""),
192 	fFindNextMenuItem(NULL),
193 	fFindPreviousMenuItem(NULL),
194 	fFindSelection(false),
195 	fForwardSearch(false),
196 	fMatchCase(false),
197 	fMatchWord(false),
198 	fFullScreen(false)
199 {
200 	// register this terminal
201 	fTerminalRoster.Register(Team(), this);
202 	fTerminalRoster.SetListener(this);
203 	int32 id = fTerminalRoster.ID();
204 
205 	// apply the title settings
206 	fTitle.pattern = title;
207 	if (fTitle.pattern.Length() == 0) {
208 		fTitle.pattern = B_TRANSLATE_SYSTEM_NAME("Terminal");
209 
210 		if (id >= 0)
211 			fTitle.pattern << " " << id + 1;
212 
213 		fTitle.patternUserDefined = false;
214 	} else
215 		fTitle.patternUserDefined = true;
216 
217 	fTitle.title = fTitle.pattern;
218 	fTitle.pattern = title;
219 
220 	_TitleSettingsChanged();
221 
222 	// get the saved window position and workspaces
223 	BRect frame;
224 	uint32 workspaces;
225 	if (_LoadWindowPosition(&frame, &workspaces) == B_OK) {
226 		// apply
227 		MoveTo(frame.LeftTop());
228 		ResizeTo(frame.Width(), frame.Height());
229 		SetWorkspaces(workspaces);
230 	} else {
231 		// use computed defaults
232 		int i = id / 16;
233 		int j = id % 16;
234 		int k = (j * 16) + (i * 64) + 50;
235 		int l = (j * 16)  + 50;
236 
237 		MoveTo(k, l);
238 	}
239 
240 	// init the GUI and add a tab
241 	_InitWindow();
242 	_AddTab(args);
243 
244 	// Announce our window as no longer minimized. That's not true, since it's
245 	// still hidden at this point, but it will be shown very soon.
246 	fTerminalRoster.SetWindowInfo(false, Workspaces());
247 }
248 
249 
250 TermWindow::~TermWindow()
251 {
252 	fTerminalRoster.Unregister();
253 
254 	_FinishTitleDialog();
255 
256 	if (fPrefWindow)
257 		fPrefWindow->PostMessage(B_QUIT_REQUESTED);
258 
259 	if (fFindPanel && fFindPanel->Lock()) {
260 		fFindPanel->Quit();
261 		fFindPanel = NULL;
262 	}
263 
264 	PrefHandler::DeleteDefault();
265 
266 	for (int32 i = 0; Session* session = _SessionAt(i); i++)
267 		delete session;
268 }
269 
270 
271 void
272 TermWindow::SessionChanged()
273 {
274 	_UpdateSessionTitle(fTabView->Selection());
275 }
276 
277 
278 void
279 TermWindow::_InitWindow()
280 {
281 	// make menu bar
282 	_SetupMenu();
283 
284 	// shortcuts to switch tabs
285 	for (int32 i = 0; i < 9; i++) {
286 		BMessage* message = new BMessage(kSetActiveTab);
287 		message->AddInt32("index", i);
288 		AddShortcut('1' + i, B_COMMAND_KEY, message);
289 	}
290 
291 	AddShortcut(B_LEFT_ARROW, B_COMMAND_KEY | B_SHIFT_KEY,
292 		new BMessage(MSG_MOVE_TAB_LEFT));
293 	AddShortcut(B_RIGHT_ARROW, B_COMMAND_KEY | B_SHIFT_KEY,
294 		new BMessage(MSG_MOVE_TAB_RIGHT));
295 
296 	BRect textFrame = Bounds();
297 	textFrame.top = fMenuBar->Bounds().bottom + 1.0;
298 
299 	fTabView = new SmartTabView(textFrame, "tab view", B_WIDTH_FROM_WIDEST);
300 	fTabView->SetListener(this);
301 	AddChild(fTabView);
302 
303 	// Make the scroll view one pixel wider than the tab view container view, so
304 	// the scroll bar will look good.
305 	fTabView->SetInsets(0, 0, -1, 0);
306 }
307 
308 
309 bool
310 TermWindow::_CanClose(int32 index)
311 {
312 	bool warnOnExit = PrefHandler::Default()->getBool(PREF_WARN_ON_EXIT);
313 
314 	if (!warnOnExit)
315 		return true;
316 
317 	uint32 busyProcessCount = 0;
318 	BString busyProcessNames;
319 		// all names, separated by "\n\t"
320 
321 	if (index != -1) {
322 		ShellInfo shellInfo;
323 		ActiveProcessInfo info;
324 		TermView* termView = _TermViewAt(index);
325 		if (termView->GetShellInfo(shellInfo)
326 			&& termView->GetActiveProcessInfo(info)
327 			&& (info.ID() != shellInfo.ProcessID()
328 				|| !shellInfo.IsDefaultShell())) {
329 			busyProcessCount++;
330 			busyProcessNames = info.Name();
331 		}
332 	} else {
333 		for (int32 i = 0; i < fSessions.CountItems(); i++) {
334 			ShellInfo shellInfo;
335 			ActiveProcessInfo info;
336 			TermView* termView = _TermViewAt(i);
337 			if (termView->GetShellInfo(shellInfo)
338 				&& termView->GetActiveProcessInfo(info)
339 				&& (info.ID() != shellInfo.ProcessID()
340 					|| !shellInfo.IsDefaultShell())) {
341 				if (++busyProcessCount > 1)
342 					busyProcessNames << "\n\t";
343 				busyProcessNames << info.Name();
344 			}
345 		}
346 	}
347 
348 	if (busyProcessCount == 0)
349 		return true;
350 
351 	BString alertMessage;
352 	if (busyProcessCount == 1) {
353 		// Only one pending process. Select the alert text depending on whether
354 		// the terminal will be closed.
355 		alertMessage = index == -1 || fSessions.CountItems() == 1
356 			? B_TRANSLATE("The process \"%1\" is still running.\n"
357 				"If you close the Terminal, the process will be killed.")
358 			: B_TRANSLATE("The process \"%1\" is still running.\n"
359 				"If you close the tab, the process will be killed.");
360 	} else {
361 		// multiple pending processes
362 		alertMessage = B_TRANSLATE(
363 			"The following processes are still running:\n\n"
364 			"\t%1\n\n"
365 			"If you close the Terminal, the processes will be killed.");
366 	}
367 
368 	alertMessage.ReplaceFirst("%1", busyProcessNames);
369 
370 	BAlert* alert = new BAlert(B_TRANSLATE("Really close?"),
371 		alertMessage, B_TRANSLATE("Close"), B_TRANSLATE("Cancel"), NULL,
372 		B_WIDTH_AS_USUAL, B_WARNING_ALERT);
373 	alert->SetShortcut(1, B_ESCAPE);
374 	return alert->Go() == 0;
375 }
376 
377 
378 bool
379 TermWindow::QuitRequested()
380 {
381 	_FinishTitleDialog();
382 
383 	if (!_CanClose(-1))
384 		return false;
385 
386 	_SaveWindowPosition();
387 
388 	return BWindow::QuitRequested();
389 }
390 
391 
392 void
393 TermWindow::MenusBeginning()
394 {
395 	TermView* view = _ActiveTermView();
396 
397 	// Syncronize Encode Menu Pop-up menu and Preference.
398 	const BCharacterSet* charset
399 		= BCharacterSetRoster::GetCharacterSetByConversionID(view->Encoding());
400 	if (charset != NULL) {
401 		BString name(charset->GetPrintName());
402 		const char* mime = charset->GetMIMEName();
403 		if (mime)
404 			name << " (" << mime << ")";
405 
406 		BMenuItem* item = fEncodingMenu->FindItem(name);
407 		if (item != NULL)
408 			item->SetMarked(true);
409 	}
410 
411 	BFont font;
412 	view->GetTermFont(&font);
413 
414 	float size = font.Size();
415 
416 	fDecreaseFontSizeMenuItem->SetEnabled(size > kMinimumFontSize);
417 	fIncreaseFontSizeMenuItem->SetEnabled(size < kMaximumFontSize);
418 
419 	BWindow::MenusBeginning();
420 }
421 
422 
423 /* static */
424 BMenu*
425 TermWindow::_MakeEncodingMenu()
426 {
427 	BMenu* menu = new (std::nothrow) BMenu(B_TRANSLATE("Text encoding"));
428 	if (menu == NULL)
429 		return NULL;
430 
431 	BCharacterSetRoster roster;
432 	BCharacterSet charset;
433 	while (roster.GetNextCharacterSet(&charset) == B_OK) {
434 		int encoding = M_UTF8;
435 		const char* mime = charset.GetMIMEName();
436 		if (mime == NULL || strcasecmp(mime, "UTF-8") != 0)
437 			encoding = charset.GetConversionID();
438 
439 		// filter out currently (???) not supported USC-2 and UTF-16
440 		if (encoding == B_UTF16_CONVERSION || encoding == B_UNICODE_CONVERSION)
441 			continue;
442 
443 		BString name(charset.GetPrintName());
444 		if (mime)
445 			name << " (" << mime << ")";
446 
447 		BMessage *message = new BMessage(MENU_ENCODING);
448 		if (message != NULL) {
449 			message->AddInt32("op", (int32)encoding);
450 			menu->AddItem(new BMenuItem(name, message));
451 		}
452 	}
453 
454 	menu->SetRadioMode(true);
455 
456 	return menu;
457 }
458 
459 
460 void
461 TermWindow::_SetupMenu()
462 {
463 	fFontSizeMenu = _MakeFontSizeMenu(MSG_HALF_SIZE_CHANGED,
464 		PrefHandler::Default()->getInt32(PREF_HALF_FONT_SIZE));
465 	fIncreaseFontSizeMenuItem = new BMenuItem(B_TRANSLATE("Increase"),
466 		new BMessage(kIncreaseFontSize), '+', B_COMMAND_KEY);
467 	fDecreaseFontSizeMenuItem = new BMenuItem(B_TRANSLATE("Decrease"),
468 		new BMessage(kDecreaseFontSize), '-', B_COMMAND_KEY);
469 	fFontSizeMenu->AddSeparatorItem();
470 	fFontSizeMenu->AddItem(fIncreaseFontSizeMenuItem);
471 	fFontSizeMenu->AddItem(fDecreaseFontSizeMenuItem);
472 
473 	BLayoutBuilder::Menu<>(fMenuBar = new BMenuBar(Bounds(), "mbar"))
474 		// Terminal
475 		.AddMenu(B_TRANSLATE_COMMENT("Terminal", "The title for the main window"
476 				" menubar entry related to terminal sessions"))
477 			.AddItem(B_TRANSLATE("Switch Terminals"), MENU_SWITCH_TERM, B_TAB)
478 				.GetItem(fSwitchTerminalsMenuItem)
479 			.AddItem(B_TRANSLATE("New Terminal"), MENU_NEW_TERM, 'N')
480 			.AddItem(B_TRANSLATE("New tab"), kNewTab, 'T')
481 			.AddSeparator()
482 			.AddItem(B_TRANSLATE("Page setup" B_UTF8_ELLIPSIS), MENU_PAGE_SETUP)
483 			.AddItem(B_TRANSLATE("Print"), MENU_PRINT, 'P')
484 			.AddSeparator()
485 			.AddItem(B_TRANSLATE("Close window"), B_QUIT_REQUESTED, 'W',
486 				B_SHIFT_KEY)
487 			.AddItem(B_TRANSLATE("Close active tab"), kCloseView, 'W')
488 			.AddItem(B_TRANSLATE("Quit"), B_QUIT_REQUESTED, 'Q')
489 		.End()
490 
491 		// Edit
492 		.AddMenu(B_TRANSLATE("Edit"))
493 			.AddItem(B_TRANSLATE("Copy"), B_COPY, 'C')
494 			.AddItem(B_TRANSLATE("Paste"), B_PASTE, 'V')
495 			.AddSeparator()
496 			.AddItem(B_TRANSLATE("Select all"), B_SELECT_ALL, 'A')
497 			.AddItem(B_TRANSLATE("Clear all"), MENU_CLEAR_ALL, 'L')
498 			.AddSeparator()
499 			.AddItem(B_TRANSLATE("Find" B_UTF8_ELLIPSIS), MENU_FIND_STRING, 'F')
500 			.AddItem(B_TRANSLATE("Find previous"), MENU_FIND_PREVIOUS, 'G',
501 					B_SHIFT_KEY)
502 				.GetItem(fFindPreviousMenuItem)
503 				.SetEnabled(false)
504 			.AddItem(B_TRANSLATE("Find next"), MENU_FIND_NEXT, 'G')
505 				.GetItem(fFindNextMenuItem)
506 				.SetEnabled(false)
507 			.AddSeparator()
508 			.AddItem(B_TRANSLATE("Window title" B_UTF8_ELLIPSIS),
509 				kEditWindowTitle)
510 		.End()
511 
512 		// Settings
513 		.AddMenu(B_TRANSLATE("Settings"))
514 			.AddItem(_MakeWindowSizeMenu())
515 			.AddItem(fEncodingMenu = _MakeEncodingMenu())
516 			.AddItem(fFontSizeMenu)
517 			.AddSeparator()
518 			.AddItem(B_TRANSLATE("Settings" B_UTF8_ELLIPSIS), MENU_PREF_OPEN)
519 			.AddSeparator()
520 			.AddItem(B_TRANSLATE("Save as default"), SAVE_AS_DEFAULT)
521 		.End()
522 	;
523 
524 	AddChild(fMenuBar);
525 
526 	_UpdateSwitchTerminalsMenuItem();
527 
528 #ifdef USE_DEBUG_SNAPSHOTS
529 	AddShortcut('S', B_COMMAND_KEY | B_CONTROL_KEY,
530 		new BMessage(SHORTCUT_DEBUG_SNAPSHOTS));
531 	AddShortcut('C', B_COMMAND_KEY | B_CONTROL_KEY,
532 		new BMessage(SHORTCUT_DEBUG_CAPTURE));
533 #endif
534 }
535 
536 
537 status_t
538 TermWindow::_GetWindowPositionFile(BFile* file, uint32 openMode)
539 {
540 	BPath path;
541 	status_t status = find_directory(B_USER_SETTINGS_DIRECTORY, &path, true);
542 	if (status != B_OK)
543 		return status;
544 
545 	status = path.Append("Terminal");
546 	if (status != B_OK)
547 		return status;
548 
549 	status = path.Append("Windows");
550 	if (status != B_OK)
551 		return status;
552 
553 	return file->SetTo(path.Path(), openMode);
554 }
555 
556 
557 status_t
558 TermWindow::_LoadWindowPosition(BRect* frame, uint32* workspaces)
559 {
560 	status_t status;
561 	BMessage position;
562 
563 	BFile file;
564 	status = _GetWindowPositionFile(&file, B_READ_ONLY);
565 	if (status != B_OK)
566 		return status;
567 
568 	status = position.Unflatten(&file);
569 
570 	file.Unset();
571 
572 	if (status != B_OK)
573 		return status;
574 
575 	int32 id = fTerminalRoster.ID();
576 	status = position.FindRect("rect", id, frame);
577 	if (status != B_OK)
578 		return status;
579 
580 	int32 _workspaces;
581 	status = position.FindInt32("workspaces", id, &_workspaces);
582 	if (status != B_OK)
583 		return status;
584 	if (modifiers() & B_SHIFT_KEY)
585 		*workspaces = _workspaces;
586 	else
587 		*workspaces = B_CURRENT_WORKSPACE;
588 
589 	return B_OK;
590 }
591 
592 
593 status_t
594 TermWindow::_SaveWindowPosition()
595 {
596 	BFile file;
597 	BMessage originalSettings;
598 
599 	// Read the settings file if it exists and is a valid BMessage.
600 	status_t status = _GetWindowPositionFile(&file, B_READ_ONLY);
601 	if (status == B_OK) {
602 		status = originalSettings.Unflatten(&file);
603 		file.Unset();
604 
605 		if (status != B_OK)
606 			status = originalSettings.MakeEmpty();
607 
608 		if (status != B_OK)
609 			return status;
610 	}
611 
612 	// Replace the settings
613 	int32 id = fTerminalRoster.ID();
614 	BRect rect(Frame());
615 	if (originalSettings.ReplaceRect("rect", id, rect) != B_OK)
616 		originalSettings.AddRect("rect", rect);
617 
618 	int32 workspaces = Workspaces();
619 	if (originalSettings.ReplaceInt32("workspaces", id, workspaces) != B_OK)
620 		originalSettings.AddInt32("workspaces", workspaces);
621 
622 	// Resave the whole thing
623 	status = _GetWindowPositionFile (&file,
624 		B_WRITE_ONLY | B_CREATE_FILE | B_ERASE_FILE);
625 	if (status != B_OK)
626 		return status;
627 
628 	return originalSettings.Flatten(&file);
629 }
630 
631 
632 void
633 TermWindow::_GetPreferredFont(BFont& font)
634 {
635 	// Default to be_fixed_font
636 	font = be_fixed_font;
637 
638 	const char* family
639 		= PrefHandler::Default()->getString(PREF_HALF_FONT_FAMILY);
640 	const char* style
641 		= PrefHandler::Default()->getString(PREF_HALF_FONT_STYLE);
642 	const char* size = PrefHandler::Default()->getString(PREF_HALF_FONT_SIZE);
643 
644 	font.SetFamilyAndStyle(family, style);
645 	font.SetSize(atoi(size));
646 
647 	// mark the font size menu item
648 	for (int32 i = 0; i < fFontSizeMenu->CountItems(); i++) {
649 		BMenuItem* item = fFontSizeMenu->ItemAt(i);
650 		if (item == NULL)
651 			continue;
652 
653 		item->SetMarked(false);
654 		if (strcmp(item->Label(), size) == 0)
655 			item->SetMarked(true);
656 	}
657 }
658 
659 
660 void
661 TermWindow::MessageReceived(BMessage *message)
662 {
663 	int32 encodingId;
664 	bool findresult;
665 
666 	switch (message->what) {
667 		case B_COPY:
668 			_ActiveTermView()->Copy(be_clipboard);
669 			break;
670 
671 		case B_PASTE:
672 			_ActiveTermView()->Paste(be_clipboard);
673 			break;
674 
675 #ifdef USE_DEBUG_SNAPSHOTS
676 		case SHORTCUT_DEBUG_SNAPSHOTS:
677 			_ActiveTermView()->MakeDebugSnapshots();
678 			break;
679 
680 		case SHORTCUT_DEBUG_CAPTURE:
681 			_ActiveTermView()->StartStopDebugCapture();
682 			break;
683 #endif
684 
685 		case B_SELECT_ALL:
686 			_ActiveTermView()->SelectAll();
687 			break;
688 
689 		case MENU_CLEAR_ALL:
690 			_ActiveTermView()->Clear();
691 			break;
692 
693 		case MENU_SWITCH_TERM:
694 			_SwitchTerminal();
695 			break;
696 
697 		case MENU_NEW_TERM:
698 		{
699 			// Set our current working directory to that of the active tab, so
700 			// that the new terminal and its shell inherit it.
701 			// Note: That's a bit lame. We should rather fork() and change the
702 			// CWD in the child, but since ATM there aren't any side effects of
703 			// changing our CWD, we save ourselves the trouble.
704 			ActiveProcessInfo activeProcessInfo;
705 			if (_ActiveTermView()->GetActiveProcessInfo(activeProcessInfo))
706 				chdir(activeProcessInfo.CurrentDirectory());
707 
708 			app_info info;
709 			be_app->GetAppInfo(&info);
710 
711 			// try launching two different ways to work around possible problems
712 			if (be_roster->Launch(&info.ref) != B_OK)
713 				be_roster->Launch(TERM_SIGNATURE);
714 			break;
715 		}
716 
717 		case MENU_PREF_OPEN:
718 			if (!fPrefWindow) {
719 				fPrefWindow = new PrefWindow(this);
720 			} else
721 				fPrefWindow->Activate();
722 			break;
723 
724 		case MSG_PREF_CLOSED:
725 			fPrefWindow = NULL;
726 			break;
727 
728 		case MSG_WINDOW_TITLE_SETTING_CHANGED:
729 		case MSG_TAB_TITLE_SETTING_CHANGED:
730 			_TitleSettingsChanged();
731 			break;
732 
733 		case MENU_FIND_STRING:
734 			if (fFindPanel == NULL) {
735 				fFindPanel = new FindWindow(this, fFindString, fFindSelection,
736 					fMatchWord, fMatchCase, fForwardSearch);
737 
738 				fFindPanel->CenterIn(Frame());
739 				_MoveWindowInScreen(fFindPanel);
740 				fFindPanel->Show();
741 			} else
742 				fFindPanel->Activate();
743 			break;
744 
745 		case MSG_FIND:
746 		{
747 			fFindPanel->PostMessage(B_QUIT_REQUESTED);
748 			message->FindBool("findselection", &fFindSelection);
749 			if (!fFindSelection)
750 				message->FindString("findstring", &fFindString);
751 			else
752 				_ActiveTermView()->GetSelection(fFindString);
753 
754 			if (fFindString.Length() == 0) {
755 				const char* errorMsg = !fFindSelection
756 					? B_TRANSLATE("No search string was entered.")
757 					: B_TRANSLATE("Nothing is selected.");
758 				BAlert* alert = new BAlert(B_TRANSLATE("Find failed"),
759 					errorMsg, B_TRANSLATE("OK"), NULL, NULL,
760 					B_WIDTH_AS_USUAL, B_WARNING_ALERT);
761 				alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
762 
763 				alert->Go();
764 				fFindPreviousMenuItem->SetEnabled(false);
765 				fFindNextMenuItem->SetEnabled(false);
766 				break;
767 			}
768 
769 			message->FindBool("forwardsearch", &fForwardSearch);
770 			message->FindBool("matchcase", &fMatchCase);
771 			message->FindBool("matchword", &fMatchWord);
772 			findresult = _ActiveTermView()->Find(fFindString, fForwardSearch,
773 				fMatchCase, fMatchWord);
774 
775 			if (!findresult) {
776 				BAlert* alert = new BAlert(B_TRANSLATE("Find failed"),
777 					B_TRANSLATE("Text not found."),
778 					B_TRANSLATE("OK"), NULL, NULL,
779 					B_WIDTH_AS_USUAL, B_WARNING_ALERT);
780 				alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
781 				alert->Go();
782 				fFindPreviousMenuItem->SetEnabled(false);
783 				fFindNextMenuItem->SetEnabled(false);
784 				break;
785 			}
786 
787 			// Enable the menu items Find Next and Find Previous
788 			fFindPreviousMenuItem->SetEnabled(true);
789 			fFindNextMenuItem->SetEnabled(true);
790 			break;
791 		}
792 
793 		case MENU_FIND_NEXT:
794 		case MENU_FIND_PREVIOUS:
795 			findresult = _ActiveTermView()->Find(fFindString,
796 				(message->what == MENU_FIND_NEXT) == fForwardSearch,
797 				fMatchCase, fMatchWord);
798 			if (!findresult) {
799 				BAlert* alert = new BAlert(B_TRANSLATE("Find failed"),
800 					B_TRANSLATE("Not found."), B_TRANSLATE("OK"),
801 					NULL, NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT);
802 				alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
803 				alert->Go();
804 			}
805 			break;
806 
807 		case MSG_FIND_CLOSED:
808 			fFindPanel = NULL;
809 			break;
810 
811 		case MENU_ENCODING:
812 			if (message->FindInt32("op", &encodingId) == B_OK)
813 				_ActiveTermView()->SetEncoding(encodingId);
814 			break;
815 
816 		case MSG_COLS_CHANGED:
817 		{
818 			int32 columns, rows;
819 			if (message->FindInt32("columns", &columns) != B_OK
820 				|| message->FindInt32("rows", &rows) != B_OK) {
821 				break;
822 			}
823 
824 			for (int32 i = 0; i < fTabView->CountTabs(); i++) {
825 				TermView* view = _TermViewAt(i);
826 				view->SetTermSize(rows, columns, true);
827 				_ResizeView(view);
828 			}
829 			break;
830 		}
831 
832 		case MSG_HALF_FONT_CHANGED:
833 		case MSG_FULL_FONT_CHANGED:
834 		{
835 			BFont font;
836 			_GetPreferredFont(font);
837 			for (int32 i = 0; i < fTabView->CountTabs(); i++) {
838 				TermView* view = _TermViewAt(i);
839 				view->SetTermFont(&font);
840 				_ResizeView(view);
841 			}
842 			break;
843 		}
844 
845 		case MSG_HALF_SIZE_CHANGED:
846 		case MSG_FULL_SIZE_CHANGED:
847 		{
848 			const char* size = NULL;
849 			if (message->FindString("font_size", &size) != B_OK)
850 				break;
851 
852 			// mark the font size menu item
853 			for (int32 i = 0; i < fFontSizeMenu->CountItems(); i++) {
854 				BMenuItem* item = fFontSizeMenu->ItemAt(i);
855 				if (item == NULL)
856 					continue;
857 
858 				item->SetMarked(false);
859 				if (strcmp(item->Label(), size) == 0)
860 					item->SetMarked(true);
861 			}
862 
863 			BFont font;
864 			_ActiveTermView()->GetTermFont(&font);
865 			font.SetSize(atoi(size));
866 			PrefHandler::Default()->setInt32(PREF_HALF_FONT_SIZE,
867 				(int32)atoi(size));
868 			for (int32 i = 0; i < fTabView->CountTabs(); i++) {
869 				TermView* view = _TermViewAt(i);
870 				_TermViewAt(i)->SetTermFont(&font);
871 				_ResizeView(view);
872 			}
873 			break;
874 		}
875 
876 		case FULLSCREEN:
877 			if (!fSavedFrame.IsValid()) { // go fullscreen
878 				_ActiveTermView()->DisableResizeView();
879 				float mbHeight = fMenuBar->Bounds().Height() + 1;
880 				fSavedFrame = Frame();
881 				BScreen screen(this);
882 
883 				for (int32 i = fTabView->CountTabs() - 1; i >= 0 ; i--)
884 					_TermViewAt(i)->ScrollBar()->ResizeBy(0,
885 						(B_H_SCROLL_BAR_HEIGHT - 1));
886 
887 				fMenuBar->Hide();
888 				fTabView->ResizeBy(0, mbHeight);
889 				fTabView->MoveBy(0, -mbHeight);
890 				fSavedLook = Look();
891 				// done before ResizeTo to work around a Dano bug
892 				// (not erasing the decor)
893 				SetLook(B_NO_BORDER_WINDOW_LOOK);
894 				ResizeTo(screen.Frame().Width() + 1, screen.Frame().Height() + 1);
895 				MoveTo(screen.Frame().left, screen.Frame().top);
896 				SetFlags(Flags() | (B_NOT_RESIZABLE | B_NOT_MOVABLE));
897 				fFullScreen = true;
898 			} else { // exit fullscreen
899 				_ActiveTermView()->DisableResizeView();
900 				float mbHeight = fMenuBar->Bounds().Height() + 1;
901 				fMenuBar->Show();
902 
903 				for (int32 i = fTabView->CountTabs() - 1; i >= 0 ; i--)
904 					_TermViewAt(i)->ScrollBar()->ResizeBy(0,
905 						-(B_H_SCROLL_BAR_HEIGHT - 1));
906 
907 				ResizeTo(fSavedFrame.Width(), fSavedFrame.Height());
908 				MoveTo(fSavedFrame.left, fSavedFrame.top);
909 				fTabView->ResizeBy(0, -mbHeight);
910 				fTabView->MoveBy(0, mbHeight);
911 				SetLook(fSavedLook);
912 				fSavedFrame = BRect(0, 0, -1, -1);
913 				SetFlags(Flags() & ~(B_NOT_RESIZABLE | B_NOT_MOVABLE));
914 				fFullScreen = false;
915 			}
916 			break;
917 
918 		case MSG_FONT_CHANGED:
919 			PostMessage(MSG_HALF_FONT_CHANGED);
920 			break;
921 
922 		case MSG_COLOR_CHANGED:
923 		case MSG_COLOR_SCHEME_CHANGED:
924 		{
925 			_SetTermColors(_ActiveTermViewContainerView());
926 			_ActiveTermViewContainerView()->Invalidate();
927 			_ActiveTermView()->Invalidate();
928 			break;
929 		}
930 
931 		case SAVE_AS_DEFAULT:
932 		{
933 			BPath path;
934 			if (PrefHandler::GetDefaultPath(path) == B_OK)
935 				PrefHandler::Default()->SaveAsText(path.Path(),
936 					PREFFILE_MIMETYPE);
937 			break;
938 		}
939 		case MENU_PAGE_SETUP:
940 			_DoPageSetup();
941 			break;
942 
943 		case MENU_PRINT:
944 			_DoPrint();
945 			break;
946 
947 		case MSG_CHECK_CHILDREN:
948 			_CheckChildren();
949 			break;
950 
951 		case MSG_MOVE_TAB_LEFT:
952 		case MSG_MOVE_TAB_RIGHT:
953 			_NavigateTab(_IndexOfTermView(_ActiveTermView()),
954 				message->what == MSG_MOVE_TAB_LEFT ? -1 : 1, true);
955 			break;
956 
957 		case kTabTitleChanged:
958 		{
959 			// tab title changed message from SetTitleDialog
960 			SessionID sessionID(*message, "session");
961 			if (Session* session = _SessionForID(sessionID)) {
962 				BString title;
963 				if (message->FindString("title", &title) == B_OK) {
964 					session->title.pattern = title;
965 					session->title.patternUserDefined = true;
966 				} else {
967 					session->title.pattern.Truncate(0);
968 					session->title.patternUserDefined = false;
969 				}
970 				_UpdateSessionTitle(_IndexOfSession(session));
971 			}
972 			break;
973 		}
974 
975 		case kWindowTitleChanged:
976 		{
977 			// window title changed message from SetTitleDialog
978 			BString title;
979 			if (message->FindString("title", &title) == B_OK) {
980 				fTitle.pattern = title;
981 				fTitle.patternUserDefined = true;
982 			} else {
983 				fTitle.pattern
984 					= PrefHandler::Default()->getString(PREF_WINDOW_TITLE);
985 				fTitle.patternUserDefined = false;
986 			}
987 
988 			_UpdateSessionTitle(fTabView->Selection());
989 				// updates the window title as a side effect
990 
991 			break;
992 		}
993 
994 		case kSetActiveTab:
995 		{
996 			int32 index;
997 			if (message->FindInt32("index", &index) == B_OK
998 					&& index >= 0 && index < fSessions.CountItems()) {
999 				fTabView->Select(index);
1000 			}
1001 			break;
1002 		}
1003 
1004 		case kNewTab:
1005 			_NewTab();
1006 			break;
1007 
1008 		case kCloseView:
1009 		{
1010 			int32 index = -1;
1011 			SessionID sessionID(*message, "session");
1012 			if (sessionID.IsValid()) {
1013 				if (Session* session = _SessionForID(sessionID))
1014 					index = _IndexOfSession(session);
1015 			} else
1016 				index = _IndexOfTermView(_ActiveTermView());
1017 
1018 			if (index >= 0)
1019 				_RemoveTab(index);
1020 
1021 			break;
1022 		}
1023 
1024 		case kCloseOtherViews:
1025 		{
1026 			Session* session = _SessionForID(SessionID(*message, "session"));
1027 			if (session == NULL)
1028 				break;
1029 
1030 			int32 count = fSessions.CountItems();
1031 			for (int32 i = count - 1; i >= 0; i--) {
1032 				if (_SessionAt(i) != session)
1033 					_RemoveTab(i);
1034 			}
1035 
1036 			break;
1037 		}
1038 
1039 		case kIncreaseFontSize:
1040 		case kDecreaseFontSize:
1041 		{
1042 			BFont font;
1043 			_ActiveTermView()->GetTermFont(&font);
1044 			float size = font.Size();
1045 
1046 			if (message->what == kIncreaseFontSize) {
1047 				if (size < 12)
1048 					size += 1;
1049 				else if (size < 24)
1050 					size += 2;
1051 				else
1052 					size += 4;
1053 			} else {
1054 				if (size <= 12)
1055 					size -= 1;
1056 				else if (size <= 24)
1057 					size -= 2;
1058 				else
1059 					size -= 4;
1060 			}
1061 
1062 			// constrain the font size
1063 			if (size < kMinimumFontSize)
1064 				size = kMinimumFontSize;
1065 			if (size > kMaximumFontSize)
1066 				size = kMaximumFontSize;
1067 
1068 			// mark the font size menu item
1069 			for (int32 i = 0; i < fFontSizeMenu->CountItems(); i++) {
1070 				BMenuItem* item = fFontSizeMenu->ItemAt(i);
1071 				if (item == NULL)
1072 					continue;
1073 
1074 				item->SetMarked(false);
1075 				if (atoi(item->Label()) == size)
1076 					item->SetMarked(true);
1077 			}
1078 
1079 			font.SetSize(size);
1080 			PrefHandler::Default()->setInt32(PREF_HALF_FONT_SIZE, (int32)size);
1081 			for (int32 i = 0; i < fTabView->CountTabs(); i++) {
1082 				TermView* view = _TermViewAt(i);
1083 				_TermViewAt(i)->SetTermFont(&font);
1084 				_ResizeView(view);
1085 			}
1086 			break;
1087 		}
1088 
1089 		case kUpdateTitles:
1090 			_UpdateTitles();
1091 			break;
1092 
1093 		case kEditTabTitle:
1094 		{
1095 			SessionID sessionID(*message, "session");
1096 			if (Session* session = _SessionForID(sessionID))
1097 				_OpenSetTabTitleDialog(_IndexOfSession(session));
1098 			break;
1099 		}
1100 
1101 		case kEditWindowTitle:
1102 			_OpenSetWindowTitleDialog();
1103 			break;
1104 
1105 		case kUpdateSwitchTerminalsMenuItem:
1106 			_UpdateSwitchTerminalsMenuItem();
1107 			break;
1108 
1109 		default:
1110 			BWindow::MessageReceived(message);
1111 			break;
1112 	}
1113 }
1114 
1115 
1116 void
1117 TermWindow::WindowActivated(bool activated)
1118 {
1119 	if (activated)
1120 		_UpdateSwitchTerminalsMenuItem();
1121 }
1122 
1123 
1124 void
1125 TermWindow::_SetTermColors(TermViewContainerView* containerView)
1126 {
1127 	PrefHandler* handler = PrefHandler::Default();
1128 	rgb_color background = handler->getRGB(PREF_TEXT_BACK_COLOR);
1129 
1130 	containerView->SetViewColor(background);
1131 
1132 	TermView *termView = containerView->GetTermView();
1133 	termView->SetTextColor(handler->getRGB(PREF_TEXT_FORE_COLOR), background);
1134 
1135 	termView->SetCursorColor(handler->getRGB(PREF_CURSOR_FORE_COLOR),
1136 		handler->getRGB(PREF_CURSOR_BACK_COLOR));
1137 	termView->SetSelectColor(handler->getRGB(PREF_SELECT_FORE_COLOR),
1138 		handler->getRGB(PREF_SELECT_BACK_COLOR));
1139 }
1140 
1141 
1142 status_t
1143 TermWindow::_DoPageSetup()
1144 {
1145 	BPrintJob job("PageSetup");
1146 
1147 	// display the page configure panel
1148 	status_t status = job.ConfigPage();
1149 
1150 	// save a pointer to the settings
1151 	fPrintSettings = job.Settings();
1152 
1153 	return status;
1154 }
1155 
1156 
1157 void
1158 TermWindow::_DoPrint()
1159 {
1160 	BPrintJob job("Print");
1161 	if (fPrintSettings)
1162 		job.SetSettings(new BMessage(*fPrintSettings));
1163 
1164 	if (job.ConfigJob() != B_OK)
1165 		return;
1166 
1167 	BRect pageRect = job.PrintableRect();
1168 	BRect curPageRect = pageRect;
1169 
1170 	int pHeight = (int)pageRect.Height();
1171 	int pWidth = (int)pageRect.Width();
1172 	float w, h;
1173 	_ActiveTermView()->GetFrameSize(&w, &h);
1174 	int xPages = (int)ceil(w / pWidth);
1175 	int yPages = (int)ceil(h / pHeight);
1176 
1177 	job.BeginJob();
1178 
1179 	// loop through and draw each page, and write to spool
1180 	for (int x = 0; x < xPages; x++) {
1181 		for (int y = 0; y < yPages; y++) {
1182 			curPageRect.OffsetTo(x * pWidth, y * pHeight);
1183 			job.DrawView(_ActiveTermView(), curPageRect, B_ORIGIN);
1184 			job.SpoolPage();
1185 
1186 			if (!job.CanContinue()) {
1187 				// It is likely that the only way that the job was cancelled is
1188 				// because the user hit 'Cancel' in the page setup window, in
1189 				// which case, the user does *not* need to be told that it was
1190 				// cancelled.
1191 				// He/she will simply expect that it was done.
1192 				return;
1193 			}
1194 		}
1195 	}
1196 
1197 	job.CommitJob();
1198 }
1199 
1200 
1201 void
1202 TermWindow::_NewTab()
1203 {
1204 	if (fTabView->CountTabs() < kMaxTabs) {
1205 		ActiveProcessInfo info;
1206 		if (_ActiveTermView()->GetActiveProcessInfo(info))
1207 			_AddTab(NULL, info.CurrentDirectory());
1208 		else
1209 			_AddTab(NULL);
1210 	}
1211 }
1212 
1213 
1214 void
1215 TermWindow::_AddTab(Arguments* args, const BString& currentDirectory)
1216 {
1217 	int argc = 0;
1218 	const char* const* argv = NULL;
1219 	if (args != NULL)
1220 		args->GetShellArguments(argc, argv);
1221 	ShellParameters shellParameters(argc, argv, currentDirectory);
1222 
1223 	try {
1224 		TermView* view = new TermView(
1225 			PrefHandler::Default()->getInt32(PREF_ROWS),
1226 			PrefHandler::Default()->getInt32(PREF_COLS),
1227 			shellParameters,
1228 			PrefHandler::Default()->getInt32(PREF_HISTORY_SIZE));
1229 		view->SetListener(this);
1230 
1231 		TermViewContainerView* containerView = new TermViewContainerView(view);
1232 		BScrollView* scrollView = new TermScrollView("scrollView",
1233 			containerView, view, fSessions.IsEmpty());
1234 		if (!fFullScreen)
1235 			scrollView->ScrollBar(B_VERTICAL)
1236 				->ResizeBy(0, -(B_H_SCROLL_BAR_HEIGHT - 1));
1237 
1238 		if (fSessions.IsEmpty())
1239 			fTabView->SetScrollView(scrollView);
1240 
1241 		Session* session = new Session(_NewSessionID(), _NewSessionIndex(),
1242 			containerView);
1243 		fSessions.AddItem(session);
1244 
1245 		BFont font;
1246 		_GetPreferredFont(font);
1247 		view->SetTermFont(&font);
1248 
1249 		int width, height;
1250 		view->GetFontSize(&width, &height);
1251 
1252 		float minimumHeight = -1;
1253 		if (fMenuBar != NULL)
1254 			minimumHeight += fMenuBar->Bounds().Height() + 1;
1255 
1256 		if (fTabView != NULL && fTabView->CountTabs() > 0)
1257 			minimumHeight += fTabView->TabHeight() + 1;
1258 
1259 		SetSizeLimits(MIN_COLS * width - 1, MAX_COLS * width - 1,
1260 			minimumHeight + MIN_ROWS * height - 1,
1261 			minimumHeight + MAX_ROWS * height - 1);
1262 			// TODO: The size limit computation is apparently broken, since
1263 			// the terminal can be resized smaller than MIN_ROWS/MIN_COLS!
1264 
1265 		// If it's the first time we're called, setup the window
1266 		if (fTabView != NULL && fTabView->CountTabs() == 0) {
1267 			float viewWidth, viewHeight;
1268 			containerView->GetPreferredSize(&viewWidth, &viewHeight);
1269 
1270 			// Resize Window
1271 			ResizeTo(viewWidth + B_V_SCROLL_BAR_WIDTH,
1272 				viewHeight + fMenuBar->Bounds().Height() + 1);
1273 				// NOTE: Width is one pixel too small, since the scroll view
1274 				// is one pixel wider than its parent.
1275 		}
1276 
1277 		BTab* tab = new BTab;
1278 		fTabView->AddTab(scrollView, tab);
1279 		view->SetScrollBar(scrollView->ScrollBar(B_VERTICAL));
1280 		view->SetMouseClipboard(gMouseClipboard);
1281 
1282 		const BCharacterSet* charset
1283 			= BCharacterSetRoster::FindCharacterSetByName(
1284 				PrefHandler::Default()->getString(PREF_TEXT_ENCODING));
1285 		if (charset != NULL)
1286 			view->SetEncoding(charset->GetConversionID());
1287 
1288 		_SetTermColors(containerView);
1289 
1290 		int32 tabIndex = fTabView->CountTabs() - 1;
1291 		fTabView->Select(tabIndex);
1292 
1293 		_UpdateSessionTitle(tabIndex);
1294 	} catch (...) {
1295 		// most probably out of memory. That's bad.
1296 		// TODO: Should cleanup, I guess
1297 
1298 		// Quit the application if we don't have a shell already
1299 		if (fTabView->CountTabs() == 0) {
1300 			fprintf(stderr, "Terminal couldn't open a shell\n");
1301 			PostMessage(B_QUIT_REQUESTED);
1302 		}
1303 	}
1304 }
1305 
1306 
1307 void
1308 TermWindow::_RemoveTab(int32 index)
1309 {
1310 	_FinishTitleDialog();
1311 		// always close to avoid confusion
1312 
1313 	if (fSessions.CountItems() > 1) {
1314 		if (!_CanClose(index))
1315 			return;
1316 		if (Session* session = (Session*)fSessions.RemoveItem(index)) {
1317 			if (fSessions.CountItems() == 1) {
1318 				fTabView->SetScrollView(dynamic_cast<BScrollView*>(
1319 					_SessionAt(0)->containerView->Parent()));
1320 			}
1321 
1322 			delete session;
1323 			delete fTabView->RemoveTab(index);
1324 		}
1325 	} else
1326 		PostMessage(B_QUIT_REQUESTED);
1327 }
1328 
1329 
1330 void
1331 TermWindow::_NavigateTab(int32 index, int32 direction, bool move)
1332 {
1333 	int32 count = fSessions.CountItems();
1334 	if (count <= 1 || index < 0 || index >= count)
1335 		return;
1336 
1337 	int32 newIndex = (index + direction + count) % count;
1338 	if (newIndex == index)
1339 		return;
1340 
1341 	if (move) {
1342 		// move the given tab to the new index
1343 		Session* session = (Session*)fSessions.RemoveItem(index);
1344 		fSessions.AddItem(session, newIndex);
1345 		fTabView->MoveTab(index, newIndex);
1346 	}
1347 
1348 	// activate the respective tab
1349 	fTabView->Select(newIndex);
1350 }
1351 
1352 
1353 TermViewContainerView*
1354 TermWindow::_ActiveTermViewContainerView() const
1355 {
1356 	return _TermViewContainerViewAt(fTabView->Selection());
1357 }
1358 
1359 
1360 TermViewContainerView*
1361 TermWindow::_TermViewContainerViewAt(int32 index) const
1362 {
1363 	if (Session* session = _SessionAt(index))
1364 		return session->containerView;
1365 	return NULL;
1366 }
1367 
1368 
1369 TermView*
1370 TermWindow::_ActiveTermView() const
1371 {
1372 	return _ActiveTermViewContainerView()->GetTermView();
1373 }
1374 
1375 
1376 TermView*
1377 TermWindow::_TermViewAt(int32 index) const
1378 {
1379 	TermViewContainerView* view = _TermViewContainerViewAt(index);
1380 	return view != NULL ? view->GetTermView() : NULL;
1381 }
1382 
1383 
1384 int32
1385 TermWindow::_IndexOfTermView(TermView* termView) const
1386 {
1387 	if (!termView)
1388 		return -1;
1389 
1390 	// find the view
1391 	int32 count = fTabView->CountTabs();
1392 	for (int32 i = count - 1; i >= 0; i--) {
1393 		if (termView == _TermViewAt(i))
1394 			return i;
1395 	}
1396 
1397 	return -1;
1398 }
1399 
1400 
1401 TermWindow::Session*
1402 TermWindow::_SessionAt(int32 index) const
1403 {
1404 	return (Session*)fSessions.ItemAt(index);
1405 }
1406 
1407 
1408 TermWindow::Session*
1409 TermWindow::_SessionForID(const SessionID& sessionID) const
1410 {
1411 	for (int32 i = 0; Session* session = _SessionAt(i); i++) {
1412 		if (session->id == sessionID)
1413 			return session;
1414 	}
1415 
1416 	return NULL;
1417 }
1418 
1419 
1420 int32
1421 TermWindow::_IndexOfSession(Session* session) const
1422 {
1423 	return fSessions.IndexOf(session);
1424 }
1425 
1426 
1427 void
1428 TermWindow::_CheckChildren()
1429 {
1430 	int32 count = fSessions.CountItems();
1431 	for (int32 i = count - 1; i >= 0; i--) {
1432 		Session* session = _SessionAt(i);
1433 		if (session->containerView->GetTermView()->CheckShellGone())
1434 			NotifyTermViewQuit(session->containerView->GetTermView(), 0);
1435 	}
1436 }
1437 
1438 
1439 void
1440 TermWindow::Zoom(BPoint leftTop, float width, float height)
1441 {
1442 	_ActiveTermView()->DisableResizeView();
1443 	BWindow::Zoom(leftTop, width, height);
1444 }
1445 
1446 
1447 void
1448 TermWindow::FrameResized(float newWidth, float newHeight)
1449 {
1450 	BWindow::FrameResized(newWidth, newHeight);
1451 
1452 	TermView* view = _ActiveTermView();
1453 	PrefHandler::Default()->setInt32(PREF_COLS, view->Columns());
1454 	PrefHandler::Default()->setInt32(PREF_ROWS, view->Rows());
1455 }
1456 
1457 
1458 void
1459 TermWindow::WorkspacesChanged(uint32 oldWorkspaces, uint32 newWorkspaces)
1460 {
1461 	fTerminalRoster.SetWindowInfo(IsMinimized(), Workspaces());
1462 }
1463 
1464 
1465 void
1466 TermWindow::WorkspaceActivated(int32 workspace, bool state)
1467 {
1468 	fTerminalRoster.SetWindowInfo(IsMinimized(), Workspaces());
1469 }
1470 
1471 
1472 void
1473 TermWindow::Minimize(bool minimize)
1474 {
1475 	BWindow::Minimize(minimize);
1476 	fTerminalRoster.SetWindowInfo(IsMinimized(), Workspaces());
1477 }
1478 
1479 
1480 void
1481 TermWindow::TabSelected(SmartTabView* tabView, int32 index)
1482 {
1483 	SessionChanged();
1484 }
1485 
1486 
1487 void
1488 TermWindow::TabDoubleClicked(SmartTabView* tabView, BPoint point, int32 index)
1489 {
1490 	if (index >= 0) {
1491 		// clicked on a tab -- open the title dialog
1492 		_OpenSetTabTitleDialog(index);
1493 	} else {
1494 		// not clicked on a tab -- create a new one
1495 		_NewTab();
1496 	}
1497 }
1498 
1499 
1500 void
1501 TermWindow::TabMiddleClicked(SmartTabView* tabView, BPoint point, int32 index)
1502 {
1503 	if (index >= 0)
1504 		_RemoveTab(index);
1505 }
1506 
1507 
1508 void
1509 TermWindow::TabRightClicked(SmartTabView* tabView, BPoint point, int32 index)
1510 {
1511 	if (index < 0)
1512 		return;
1513 
1514 	TermView* termView = _TermViewAt(index);
1515 	if (termView == NULL)
1516 		return;
1517 
1518 	BMessage* closeMessage = new BMessage(kCloseView);
1519 	_SessionAt(index)->id.AddToMessage(*closeMessage, "session");
1520 
1521 	BMessage* closeOthersMessage = new BMessage(kCloseOtherViews);
1522 	_SessionAt(index)->id.AddToMessage(*closeOthersMessage, "session");
1523 
1524 	BMessage* editTitleMessage = new BMessage(kEditTabTitle);
1525 	_SessionAt(index)->id.AddToMessage(*editTitleMessage, "session");
1526 
1527 	BPopUpMenu* popUpMenu = new BPopUpMenu("tab menu");
1528 	BLayoutBuilder::Menu<>(popUpMenu)
1529 		.AddItem(B_TRANSLATE("Close tab"), closeMessage)
1530 		.AddItem(B_TRANSLATE("Close other tabs"), closeOthersMessage)
1531 		.AddSeparator()
1532 		.AddItem(B_TRANSLATE("Edit tab title" B_UTF8_ELLIPSIS),
1533 			editTitleMessage)
1534 	;
1535 
1536 	popUpMenu->SetAsyncAutoDestruct(true);
1537 	popUpMenu->SetTargetForItems(BMessenger(this));
1538 
1539 	BPoint screenWhere = tabView->ConvertToScreen(point);
1540 	BRect mouseRect(screenWhere, screenWhere);
1541 	mouseRect.InsetBy(-4.0, -4.0);
1542 	popUpMenu->Go(screenWhere, true, true, mouseRect, true);
1543 }
1544 
1545 
1546 void
1547 TermWindow::NotifyTermViewQuit(TermView* view, int32 reason)
1548 {
1549 	// Since the notification can come from the view, we send a message to
1550 	// ourselves to avoid deleting the caller synchronously.
1551 	if (Session* session = _SessionAt(_IndexOfTermView(view))) {
1552 		BMessage message(kCloseView);
1553 		session->id.AddToMessage(message, "session");
1554 		message.AddInt32("reason", reason);
1555 		PostMessage(&message);
1556 	}
1557 }
1558 
1559 
1560 void
1561 TermWindow::SetTermViewTitle(TermView* view, const char* title)
1562 {
1563 	int32 index = _IndexOfTermView(view);
1564 	if (Session* session = _SessionAt(index)) {
1565 		session->title.pattern = title;
1566 		session->title.patternUserDefined = true;
1567 		_UpdateSessionTitle(index);
1568 	}
1569 }
1570 
1571 
1572 void
1573 TermWindow::TitleChanged(SetTitleDialog* dialog, const BString& title,
1574 	bool titleUserDefined)
1575 {
1576 	if (dialog == fSetTabTitleDialog) {
1577 		// tab title
1578 		BMessage message(kTabTitleChanged);
1579 		fSetTabTitleSession.AddToMessage(message, "session");
1580 		if (titleUserDefined)
1581 			message.AddString("title", title);
1582 
1583 		PostMessage(&message);
1584 	} else if (dialog == fSetWindowTitleDialog) {
1585 		// window title
1586 		BMessage message(kWindowTitleChanged);
1587 		if (titleUserDefined)
1588 			message.AddString("title", title);
1589 
1590 		PostMessage(&message);
1591 	}
1592 }
1593 
1594 
1595 void
1596 TermWindow::SetTitleDialogDone(SetTitleDialog* dialog)
1597 {
1598 	if (dialog == fSetTabTitleDialog) {
1599 		fSetTabTitleSession = SessionID();
1600 		fSetTabTitleDialog = NULL;
1601 			// assuming this is atomic
1602 	}
1603 }
1604 
1605 
1606 void
1607 TermWindow::TerminalInfosUpdated(TerminalRoster* roster)
1608 {
1609 	PostMessage(kUpdateSwitchTerminalsMenuItem);
1610 }
1611 
1612 
1613 void
1614 TermWindow::PreviousTermView(TermView* view)
1615 {
1616 	_NavigateTab(_IndexOfTermView(view), -1, false);
1617 }
1618 
1619 
1620 void
1621 TermWindow::NextTermView(TermView* view)
1622 {
1623 	_NavigateTab(_IndexOfTermView(view), 1, false);
1624 }
1625 
1626 
1627 void
1628 TermWindow::_ResizeView(TermView *view)
1629 {
1630 	int fontWidth, fontHeight;
1631 	view->GetFontSize(&fontWidth, &fontHeight);
1632 
1633 	float minimumHeight = -1;
1634 	if (fMenuBar != NULL)
1635 		minimumHeight += fMenuBar->Bounds().Height() + 1;
1636 
1637 	if (fTabView != NULL && fTabView->CountTabs() > 1)
1638 		minimumHeight += fTabView->TabHeight() + 1;
1639 
1640 	SetSizeLimits(MIN_COLS * fontWidth - 1, MAX_COLS * fontWidth - 1,
1641 		minimumHeight + MIN_ROWS * fontHeight - 1,
1642 		minimumHeight + MAX_ROWS * fontHeight - 1);
1643 
1644 	float width;
1645 	float height;
1646 	view->Parent()->GetPreferredSize(&width, &height);
1647 
1648 	width += B_V_SCROLL_BAR_WIDTH;
1649 		// NOTE: Width is one pixel too small, since the scroll view
1650 		// is one pixel wider than its parent.
1651 	if (fMenuBar != NULL)
1652 		height += fMenuBar->Bounds().Height() + 1;
1653 	if (fTabView != NULL && fTabView->CountTabs() > 1)
1654 		height += fTabView->TabHeight() + 1;
1655 
1656 	ResizeTo(width, height);
1657 	view->Invalidate();
1658 }
1659 
1660 
1661 /* static */ BMenu*
1662 TermWindow::_MakeWindowSizeMenu()
1663 {
1664 	BMenu* menu = new (std::nothrow) BMenu(B_TRANSLATE("Window size"));
1665 	if (menu == NULL)
1666 		return NULL;
1667 
1668 	const int32 windowSizes[4][2] = {
1669 		{ 80, 25 },
1670 		{ 80, 40 },
1671 		{ 132, 25 },
1672 		{ 132, 40 }
1673 	};
1674 
1675 	const int32 sizeNum = sizeof(windowSizes) / sizeof(windowSizes[0]);
1676 	for (int32 i = 0; i < sizeNum; i++) {
1677 		char label[32];
1678 		int32 columns = windowSizes[i][0];
1679 		int32 rows = windowSizes[i][1];
1680 		snprintf(label, sizeof(label), "%" B_PRId32 "x%" B_PRId32, columns, rows);
1681 		BMessage* message = new BMessage(MSG_COLS_CHANGED);
1682 		message->AddInt32("columns", columns);
1683 		message->AddInt32("rows", rows);
1684 		menu->AddItem(new BMenuItem(label, message));
1685 	}
1686 
1687 	menu->AddSeparatorItem();
1688 	menu->AddItem(new BMenuItem(B_TRANSLATE("Full screen"),
1689 		new BMessage(FULLSCREEN), B_ENTER));
1690 
1691 	return menu;
1692 }
1693 
1694 
1695 /*static*/ BMenu*
1696 TermWindow::_MakeFontSizeMenu(uint32 command, uint8 defaultSize)
1697 {
1698 	BMenu* menu = new (std::nothrow) BMenu(B_TRANSLATE("Font size"));
1699 	if (menu == NULL)
1700 		return NULL;
1701 
1702 	int32 sizes[] = {
1703 		8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 28, 32, 36, 0
1704 	};
1705 
1706 	bool found = false;
1707 
1708 	for (uint32 i = 0; sizes[i]; i++) {
1709 		BString string;
1710 		string << sizes[i];
1711 		BMessage* message = new BMessage(command);
1712 		message->AddString("font_size", string);
1713 		BMenuItem* item = new BMenuItem(string.String(), message);
1714 		menu->AddItem(item);
1715 		if (sizes[i] == defaultSize) {
1716 			item->SetMarked(true);
1717 			found = true;
1718 		}
1719 	}
1720 
1721 	if (!found) {
1722 		for (uint32 i = 0; sizes[i]; i++) {
1723 			if (sizes[i] > defaultSize) {
1724 				BString string;
1725 				string << defaultSize;
1726 				BMessage* message = new BMessage(command);
1727 				message->AddString("font_size", string);
1728 				BMenuItem* item = new BMenuItem(string.String(), message);
1729 				item->SetMarked(true);
1730 				menu->AddItem(item, i);
1731 				break;
1732 			}
1733 		}
1734 	}
1735 
1736 	return menu;
1737 }
1738 
1739 
1740 void
1741 TermWindow::_UpdateSwitchTerminalsMenuItem()
1742 {
1743 	fSwitchTerminalsMenuItem->SetEnabled(_FindSwitchTerminalTarget() >= 0);
1744 }
1745 
1746 
1747 void
1748 TermWindow::_TitleSettingsChanged()
1749 {
1750 	if (!fTitle.patternUserDefined)
1751 		fTitle.pattern = PrefHandler::Default()->getString(PREF_WINDOW_TITLE);
1752 
1753 	fSessionTitlePattern = PrefHandler::Default()->getString(PREF_TAB_TITLE);
1754 
1755 	_UpdateTitles();
1756 }
1757 
1758 
1759 void
1760 TermWindow::_UpdateTitles()
1761 {
1762 	int32 sessionCount = fSessions.CountItems();
1763 	for (int32 i = 0; i < sessionCount; i++)
1764 		_UpdateSessionTitle(i);
1765 }
1766 
1767 
1768 void
1769 TermWindow::_UpdateSessionTitle(int32 index)
1770 {
1771 	Session* session = _SessionAt(index);
1772 	if (session == NULL)
1773 		return;
1774 
1775 	// get the shell and active process infos
1776 	ShellInfo shellInfo;
1777 	ActiveProcessInfo activeProcessInfo;
1778 	TermView* termView = _TermViewAt(index);
1779 	if (!termView->GetShellInfo(shellInfo)
1780 		|| !termView->GetActiveProcessInfo(activeProcessInfo)) {
1781 		return;
1782 	}
1783 
1784 	// evaluate the session title pattern
1785 	BString sessionTitlePattern = session->title.patternUserDefined
1786 		? session->title.pattern : fSessionTitlePattern;
1787 	TabTitlePlaceholderMapper tabMapper(shellInfo, activeProcessInfo,
1788 		session->index);
1789 	const BString& sessionTitle = PatternEvaluator::Evaluate(
1790 		sessionTitlePattern, tabMapper);
1791 
1792 	// set the tab title
1793 	if (sessionTitle != session->title.title) {
1794 		session->title.title = sessionTitle;
1795 		fTabView->TabAt(index)->SetLabel(session->title.title);
1796 		fTabView->Invalidate();
1797 			// Invalidate the complete tab view, since other tabs might change
1798 			// their positions.
1799 	}
1800 
1801 	// If this is the active tab, also recompute the window title.
1802 	if (index != fTabView->Selection())
1803 		return;
1804 
1805 	// evaluate the window title pattern
1806 	WindowTitlePlaceholderMapper windowMapper(shellInfo, activeProcessInfo,
1807 		fTerminalRoster.CountTerminals() > 1
1808 			? fTerminalRoster.ID() + 1 : 0, sessionTitle);
1809 	const BString& windowTitle = PatternEvaluator::Evaluate(fTitle.pattern,
1810 		windowMapper);
1811 
1812 	// set the window title
1813 	if (windowTitle != fTitle.title) {
1814 		fTitle.title = windowTitle;
1815 		SetTitle(fTitle.title);
1816 	}
1817 
1818 	// If fullscreen, add a tooltip with the title and a keyboard shortcut hint
1819 	if (fFullScreen) {
1820 		BString toolTip(fTitle.title);
1821 		toolTip += "\n(";
1822 		toolTip += B_TRANSLATE("Full screen");
1823 		toolTip += " (ALT " UTF8_ENTER "))";
1824 		termView->SetToolTip(toolTip.String());
1825 	} else
1826 		termView->SetToolTip((const char *)NULL);
1827 }
1828 
1829 
1830 void
1831 TermWindow::_OpenSetTabTitleDialog(int32 index)
1832 {
1833 	// If a dialog is active, finish it.
1834 	_FinishTitleDialog();
1835 
1836 	BString toolTip = BString(B_TRANSLATE(
1837 		"The pattern specifying the current tab title. The following "
1838 			"placeholders\n"
1839 		"can be used:\n")) << kTooTipSetTabTitlePlaceholders;
1840 	fSetTabTitleDialog = new SetTitleDialog(
1841 		B_TRANSLATE("Set tab title"), B_TRANSLATE("Tab title:"),
1842 		toolTip);
1843 
1844 	Session* session = _SessionAt(index);
1845 	bool userDefined = session->title.patternUserDefined;
1846 	const BString& title = userDefined
1847 		? session->title.pattern : fSessionTitlePattern;
1848 	fSetTabTitleSession = session->id;
1849 
1850 	// place the dialog window directly under the tab, but keep it on screen
1851 	BPoint location = fTabView->ConvertToScreen(
1852 		fTabView->TabFrame(index).LeftBottom() + BPoint(0, 1));
1853 	fSetTabTitleDialog->MoveTo(location);
1854 	_MoveWindowInScreen(fSetTabTitleDialog);
1855 
1856 	fSetTabTitleDialog->Go(title, userDefined, this);
1857 }
1858 
1859 
1860 void
1861 TermWindow::_OpenSetWindowTitleDialog()
1862 {
1863 	// If a dialog is active, finish it.
1864 	_FinishTitleDialog();
1865 
1866 	BString toolTip = BString(B_TRANSLATE(
1867 		"The pattern specifying the window title. The following placeholders\n"
1868 		"can be used:\n")) << kTooTipSetTabTitlePlaceholders;
1869 	fSetWindowTitleDialog = new SetTitleDialog(B_TRANSLATE("Set window title"),
1870 		B_TRANSLATE("Window title:"), toolTip);
1871 
1872 	// center the dialog in the window frame, but keep it on screen
1873 	fSetWindowTitleDialog->CenterIn(Frame());
1874 	_MoveWindowInScreen(fSetWindowTitleDialog);
1875 
1876 	fSetWindowTitleDialog->Go(fTitle.pattern, fTitle.patternUserDefined, this);
1877 }
1878 
1879 
1880 void
1881 TermWindow::_FinishTitleDialog()
1882 {
1883 	SetTitleDialog* oldDialog = fSetTabTitleDialog;
1884 	if (oldDialog != NULL && oldDialog->Lock()) {
1885 		// might have been unset in the meantime, so recheck
1886 		if (fSetTabTitleDialog == oldDialog) {
1887 			oldDialog->Finish();
1888 				// this also unsets the variables
1889 		}
1890 		oldDialog->Unlock();
1891 		return;
1892 	}
1893 
1894 	oldDialog = fSetWindowTitleDialog;
1895 	if (oldDialog != NULL && oldDialog->Lock()) {
1896 		// might have been unset in the meantime, so recheck
1897 		if (fSetWindowTitleDialog == oldDialog) {
1898 			oldDialog->Finish();
1899 				// this also unsets the variable
1900 		}
1901 		oldDialog->Unlock();
1902 		return;
1903 	}
1904 }
1905 
1906 
1907 void
1908 TermWindow::_SwitchTerminal()
1909 {
1910 	team_id teamID = _FindSwitchTerminalTarget();
1911 	if (teamID < 0)
1912 		return;
1913 
1914 	BMessenger app(TERM_SIGNATURE, teamID);
1915 	app.SendMessage(MSG_ACTIVATE_TERM);
1916 }
1917 
1918 
1919 team_id
1920 TermWindow::_FindSwitchTerminalTarget()
1921 {
1922 	AutoLocker<TerminalRoster> rosterLocker(fTerminalRoster);
1923 
1924 	team_id myTeamID = Team();
1925 
1926 	int32 numTerms = fTerminalRoster.CountTerminals();
1927 	if (numTerms <= 1)
1928 		return -1;
1929 
1930 	// Find our position in the Terminal teams.
1931 	int32 i;
1932 
1933 	for (i = 0; i < numTerms; i++) {
1934 		if (myTeamID == fTerminalRoster.TerminalAt(i)->team)
1935 			break;
1936 	}
1937 
1938 	if (i == numTerms) {
1939 		// we didn't find ourselves -- that shouldn't happen
1940 		return -1;
1941 	}
1942 
1943 	uint32 currentWorkspace = 1L << current_workspace();
1944 
1945 	while (true) {
1946 		if (--i < 0)
1947 			i = numTerms - 1;
1948 
1949 		const TerminalRoster::Info* info = fTerminalRoster.TerminalAt(i);
1950 		if (info->team == myTeamID) {
1951 			// That's ourselves again. We've run through the complete list.
1952 			return -1;
1953 		}
1954 
1955 		if (!info->minimized && (info->workspaces & currentWorkspace) != 0)
1956 			return info->team;
1957 	}
1958 }
1959 
1960 
1961 TermWindow::SessionID
1962 TermWindow::_NewSessionID()
1963 {
1964 	return fNextSessionID++;
1965 }
1966 
1967 
1968 int32
1969 TermWindow::_NewSessionIndex()
1970 {
1971 	for (int32 id = 1; ; id++) {
1972 		bool used = false;
1973 
1974 		for (int32 i = 0;
1975 			Session* session = _SessionAt(i); i++) {
1976 			if (id == session->index) {
1977 				used = true;
1978 				break;
1979 			}
1980 		}
1981 
1982 		if (!used)
1983 			return id;
1984 	}
1985 }
1986 
1987 
1988 void
1989 TermWindow::_MoveWindowInScreen(BWindow* window)
1990 {
1991 	BRect frame = window->Frame();
1992 	BSize screenSize(BScreen(window).Frame().Size());
1993 	window->MoveTo(BLayoutUtils::MoveIntoFrame(frame, screenSize).LeftTop());
1994 }
1995