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