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