Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4279 lines
107 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //=============================================================================//
  7. #include <assert.h>
  8. #include <ctype.h>
  9. #include <stdio.h>
  10. #include <utlvector.h>
  11. #include <vgui/Cursor.h>
  12. #include <vgui/IInput.h>
  13. #include <vgui/IScheme.h>
  14. #include <vgui/ISystem.h>
  15. #include <vgui/ISurface.h>
  16. #include <vgui/ILocalize.h>
  17. #include <vgui/IPanel.h>
  18. #include <KeyValues.h>
  19. #include <vgui/MouseCode.h>
  20. #include <vgui_controls/Menu.h>
  21. #include <vgui_controls/ScrollBar.h>
  22. #include <vgui_controls/TextEntry.h>
  23. #include <vgui_controls/Controls.h>
  24. #include <vgui_controls/MenuItem.h>
  25. // memdbgon must be the last include file in a .cpp file!!!
  26. #include <tier0/memdbgon.h>
  27. enum
  28. {
  29. // maximum size of text buffer
  30. BUFFER_SIZE=999999,
  31. };
  32. using namespace vgui;
  33. static const int DRAW_OFFSET_X = 3,DRAW_OFFSET_Y = 1;
  34. DECLARE_BUILD_FACTORY( TextEntry );
  35. //-----------------------------------------------------------------------------
  36. // Purpose: Constructor
  37. //-----------------------------------------------------------------------------
  38. TextEntry::TextEntry(Panel *parent, const char *panelName) : BaseClass(parent, panelName)
  39. {
  40. SetTriplePressAllowed( true );
  41. _font = INVALID_FONT;
  42. _smallfont = INVALID_FONT;
  43. m_szComposition[ 0 ] = L'\0';
  44. m_bAllowNumericInputOnly = false;
  45. m_bAllowNonAsciiCharacters = false;
  46. _hideText = false;
  47. _editable = false;
  48. _verticalScrollbar = false;
  49. _cursorPos = 0;
  50. _currentStartIndex = 0;
  51. _horizScrollingAllowed = true;
  52. _cursorIsAtEnd = false;
  53. _putCursorAtEnd = false;
  54. _multiline = false;
  55. _cursorBlinkRate = 400;
  56. _mouseSelection = false;
  57. _mouseDragSelection = false;
  58. _vertScrollBar=NULL;
  59. _catchEnterKey = false;
  60. _maxCharCount = -1;
  61. _charCount = 0;
  62. _wrap = false; // don't wrap by default
  63. _sendNewLines = false; // don't pass on a newline msg by default
  64. _drawWidth = 0;
  65. m_bAutoProgressOnHittingCharLimit = false;
  66. m_pIMECandidates = NULL;
  67. m_hPreviousIME = input()->GetEnglishIMEHandle();
  68. m_bDrawLanguageIDAtLeft = false;
  69. m_nLangInset = 0;
  70. m_bUseFallbackFont = false;
  71. m_hFallbackFont = INVALID_FONT;
  72. //a -1 for _select[0] means that the selection is empty
  73. _select[0] = -1;
  74. _select[1] = -1;
  75. m_pEditMenu = NULL;
  76. //this really just inits it when in here
  77. ResetCursorBlink();
  78. SetCursor(dc_ibeam);
  79. SetEditable(true);
  80. // initialize the line break array
  81. m_LineBreaks.AddToTail(BUFFER_SIZE);
  82. _recalculateBreaksIndex = 0;
  83. _selectAllOnFirstFocus = false;
  84. _selectAllOnFocusAlways = false;
  85. //position the cursor so it is at the end of the text
  86. GotoTextEnd();
  87. // If keyboard focus is in an edit control, don't chain keyboard mappings up to parents since it could mess with typing in text.
  88. SetAllowKeyBindingChainToParent( false );
  89. REGISTER_COLOR_AS_OVERRIDABLE( _disabledFgColor, "disabledFgColor_override" );
  90. REGISTER_COLOR_AS_OVERRIDABLE( _disabledBgColor, "disabledBgColor_override" );
  91. REGISTER_COLOR_AS_OVERRIDABLE( _selectionColor, "selectionColor_override" );
  92. REGISTER_COLOR_AS_OVERRIDABLE( _selectionTextColor, "selectionTextColor_override" );
  93. REGISTER_COLOR_AS_OVERRIDABLE( _defaultSelectionBG2Color, "defaultSelectionBG2Color_override" );
  94. }
  95. TextEntry::~TextEntry()
  96. {
  97. delete m_pEditMenu;
  98. delete m_pIMECandidates;
  99. }
  100. //-----------------------------------------------------------------------------
  101. // Purpose:
  102. //-----------------------------------------------------------------------------
  103. void TextEntry::ApplySchemeSettings(IScheme *pScheme)
  104. {
  105. BaseClass::ApplySchemeSettings(pScheme);
  106. SetFgColor(GetSchemeColor("TextEntry.TextColor", pScheme));
  107. SetBgColor(GetSchemeColor("TextEntry.BgColor", pScheme));
  108. _cursorColor = GetSchemeColor("TextEntry.CursorColor", pScheme);
  109. _disabledFgColor = GetSchemeColor("TextEntry.DisabledTextColor", pScheme);
  110. _disabledBgColor = GetSchemeColor("TextEntry.DisabledBgColor", pScheme);
  111. _selectionTextColor = GetSchemeColor("TextEntry.SelectedTextColor", GetFgColor(), pScheme);
  112. _selectionColor = GetSchemeColor("TextEntry.SelectedBgColor", pScheme);
  113. _defaultSelectionBG2Color = GetSchemeColor("TextEntry.OutOfFocusSelectedBgColor", pScheme);
  114. _focusEdgeColor = GetSchemeColor("TextEntry.FocusEdgeColor", Color(0, 0, 0, 0), pScheme);
  115. SetBorder( pScheme->GetBorder("ButtonDepressedBorder"));
  116. if ( _font == INVALID_FONT ) _font = pScheme->GetFont("Default", IsProportional() );
  117. if ( _smallfont == INVALID_FONT ) _smallfont = pScheme->GetFont( "DefaultVerySmall", IsProportional() );
  118. SetFont( _font );
  119. }
  120. void TextEntry::SetSelectionTextColor( const Color& clr )
  121. {
  122. _selectionTextColor = clr;
  123. }
  124. void TextEntry::SetSelectionBgColor( const Color& clr )
  125. {
  126. _selectionColor = clr;
  127. }
  128. void TextEntry::SetSelectionUnfocusedBgColor( const Color& clr )
  129. {
  130. _defaultSelectionBG2Color = clr;
  131. }
  132. //-----------------------------------------------------------------------------
  133. // Purpose: sets the color of the background when the control is disabled
  134. //-----------------------------------------------------------------------------
  135. void TextEntry::SetDisabledBgColor(Color col)
  136. {
  137. _disabledBgColor = col;
  138. }
  139. //-----------------------------------------------------------------------------
  140. // Purpose: Sends a message if the data has changed
  141. // Turns off any selected text in the window if we are not using the edit menu
  142. //-----------------------------------------------------------------------------
  143. void TextEntry::OnKillFocus()
  144. {
  145. m_szComposition[ 0 ] = L'\0';
  146. HideIMECandidates();
  147. if (_dataChanged)
  148. {
  149. FireActionSignal();
  150. _dataChanged = false;
  151. }
  152. // check if we clicked the right mouse button or if it is down
  153. bool mouseRightClicked = input()->WasMousePressed(MOUSE_RIGHT);
  154. bool mouseRightUp = input()->WasMouseReleased(MOUSE_RIGHT);
  155. bool mouseRightDown = input()->IsMouseDown(MOUSE_RIGHT);
  156. if (mouseRightClicked || mouseRightDown || mouseRightUp )
  157. {
  158. int cursorX, cursorY;
  159. input()->GetCursorPos(cursorX, cursorY);
  160. // if we're right clicking within our window, we don't actually kill focus
  161. if (IsWithin(cursorX, cursorY))
  162. return;
  163. }
  164. // clear any selection
  165. SelectNone();
  166. // move the cursor to the start
  167. // GotoTextStart();
  168. PostActionSignal( new KeyValues( "TextKillFocus" ) );
  169. // chain
  170. BaseClass::OnKillFocus();
  171. }
  172. //-----------------------------------------------------------------------------
  173. // Purpose: Wipe line breaks after the size of a panel has been changed
  174. //-----------------------------------------------------------------------------
  175. void TextEntry::OnSizeChanged(int newWide, int newTall)
  176. {
  177. BaseClass::OnSizeChanged(newWide, newTall);
  178. // blow away the line breaks list
  179. _recalculateBreaksIndex = 0;
  180. m_LineBreaks.RemoveAll();
  181. m_LineBreaks.AddToTail(BUFFER_SIZE);
  182. // if we're bigger, see if we can scroll left to put more text in the window
  183. if (newWide > _drawWidth)
  184. {
  185. ScrollLeftForResize();
  186. }
  187. _drawWidth = newWide;
  188. InvalidateLayout();
  189. }
  190. //-----------------------------------------------------------------------------
  191. // Purpose: Set the text array - convert ANSI text to unicode and pass to unicode function
  192. //-----------------------------------------------------------------------------
  193. void TextEntry::SetText(const char *text)
  194. {
  195. if (!text)
  196. {
  197. text = "";
  198. }
  199. if (text[0] == '#')
  200. {
  201. // check for localization
  202. wchar_t *wsz = g_pVGuiLocalize->Find(text);
  203. if (wsz)
  204. {
  205. SetText(wsz);
  206. return;
  207. }
  208. }
  209. size_t len = strlen( text );
  210. if ( len < 1023 )
  211. {
  212. wchar_t unicode[ 1024 ];
  213. g_pVGuiLocalize->ConvertANSIToUnicode( text, unicode, sizeof( unicode ) );
  214. SetText( unicode );
  215. }
  216. else
  217. {
  218. size_t lenUnicode = ( len * sizeof( wchar_t ) + 4 );
  219. wchar_t *unicode = ( wchar_t * ) malloc( lenUnicode );
  220. g_pVGuiLocalize->ConvertANSIToUnicode( text, unicode, lenUnicode );
  221. SetText( unicode );
  222. free( unicode );
  223. }
  224. }
  225. //-----------------------------------------------------------------------------
  226. // Purpose: Set the text array
  227. // Using this function will cause all lineBreaks to be discarded.
  228. // This is because this fxn replaces the contents of the text buffer.
  229. // For modifying large buffers use insert functions.
  230. //-----------------------------------------------------------------------------
  231. void TextEntry::SetText(const wchar_t *wszText)
  232. {
  233. if (!wszText)
  234. {
  235. wszText = L"";
  236. }
  237. int textLen = wcslen(wszText);
  238. m_TextStream.RemoveAll();
  239. m_TextStream.EnsureCapacity(textLen);
  240. int missed_count = 0;
  241. for (int i = 0; i < textLen; i++)
  242. {
  243. if(wszText[i]=='\r') // don't insert \r characters
  244. {
  245. missed_count++;
  246. continue;
  247. }
  248. m_TextStream.AddToTail(wszText[i]);
  249. SetCharAt(wszText[i], i-missed_count);
  250. }
  251. GotoTextStart();
  252. SelectNone();
  253. // reset the data changed flag
  254. _dataChanged = false;
  255. // blow away the line breaks list
  256. _recalculateBreaksIndex = 0;
  257. m_LineBreaks.RemoveAll();
  258. m_LineBreaks.AddToTail(BUFFER_SIZE);
  259. InvalidateLayout();
  260. }
  261. //-----------------------------------------------------------------------------
  262. // Purpose: Sets the value of char at index position.
  263. //-----------------------------------------------------------------------------
  264. void TextEntry::SetCharAt(wchar_t ch, int index)
  265. {
  266. if ((ch == '\n') || (ch == '\0'))
  267. {
  268. // if its not at the end of the buffer it matters.
  269. // redo the linebreaks
  270. //if (index != m_TextStream.Count())
  271. {
  272. _recalculateBreaksIndex = 0;
  273. m_LineBreaks.RemoveAll();
  274. m_LineBreaks.AddToTail(BUFFER_SIZE);
  275. }
  276. }
  277. if (index < 0)
  278. return;
  279. if (index >= m_TextStream.Count())
  280. {
  281. m_TextStream.AddMultipleToTail(index - m_TextStream.Count() + 1);
  282. }
  283. m_TextStream[index] = ch;
  284. _dataChanged = true;
  285. }
  286. //-----------------------------------------------------------------------------
  287. // Purpose: Restarts the time of the next cursor blink
  288. //-----------------------------------------------------------------------------
  289. void TextEntry::ResetCursorBlink()
  290. {
  291. _cursorBlink=false;
  292. _cursorNextBlinkTime=system()->GetTimeMillis()+_cursorBlinkRate;
  293. }
  294. //-----------------------------------------------------------------------------
  295. // Purpose: Hides the text buffer so it will not be drawn
  296. //-----------------------------------------------------------------------------
  297. void TextEntry::SetTextHidden(bool bHideText)
  298. {
  299. _hideText = bHideText;
  300. Repaint();
  301. }
  302. //-----------------------------------------------------------------------------
  303. // Purpose: return character width
  304. //-----------------------------------------------------------------------------
  305. int getCharWidth(HFont font, wchar_t ch)
  306. {
  307. if (!iswcntrl(ch))
  308. {
  309. int a, b, c;
  310. surface()->GetCharABCwide(font, ch, a, b, c);
  311. return (a + b + c);
  312. }
  313. return 0;
  314. }
  315. //-----------------------------------------------------------------------------
  316. // Purpose: Given cursor's position in the text buffer, convert it to
  317. // the local window's x and y pixel coordinates
  318. // Input: cursorPos: cursor index
  319. // Output: cx, cy, the corresponding coords in the local window
  320. //-----------------------------------------------------------------------------
  321. void TextEntry::CursorToPixelSpace(int cursorPos, int &cx, int &cy)
  322. {
  323. int yStart = GetYStart();
  324. int x = DRAW_OFFSET_X, y = yStart;
  325. _pixelsIndent = 0;
  326. int lineBreakIndexIndex = 0;
  327. for (int i = GetStartDrawIndex(lineBreakIndexIndex); i < m_TextStream.Count(); i++)
  328. {
  329. wchar_t ch = m_TextStream[i];
  330. if (_hideText)
  331. {
  332. ch = '*';
  333. }
  334. // if we've found the position, break
  335. if (cursorPos == i)
  336. {
  337. // even if this is a line break entry for the cursor, the next insert
  338. // will be at this position, which will push the line break forward one
  339. // so don't push the cursor down a line here...
  340. /*if (!_putCursorAtEnd)
  341. {
  342. // if we've passed a line break go to that
  343. if (m_LineBreaks[lineBreakIndexIndex] == i)
  344. {
  345. // add another line
  346. AddAnotherLine(x,y);
  347. lineBreakIndexIndex++;
  348. }
  349. }*/
  350. break;
  351. }
  352. // if we've passed a line break go to that
  353. if (m_LineBreaks.Count() &&
  354. lineBreakIndexIndex < m_LineBreaks.Count() &&
  355. m_LineBreaks[lineBreakIndexIndex] == i)
  356. {
  357. // add another line
  358. AddAnotherLine(x,y);
  359. lineBreakIndexIndex++;
  360. }
  361. // add to the current position
  362. x += getCharWidth(_font, ch);
  363. }
  364. if ( m_bDrawLanguageIDAtLeft )
  365. {
  366. x += m_nLangInset;
  367. }
  368. cx = x;
  369. cy = y;
  370. }
  371. //-----------------------------------------------------------------------------
  372. // Purpose: Converts local pixel coordinates to an index in the text buffer
  373. // This function appears to be used only in response to mouse clicking
  374. // Input : cx -
  375. // cy - pixel location
  376. //-----------------------------------------------------------------------------
  377. int TextEntry::PixelToCursorSpace(int cx, int cy)
  378. {
  379. int w, h;
  380. GetSize(w, h);
  381. cx = clamp(cx, 0, w+100);
  382. cy = clamp(cy, 0, h);
  383. _putCursorAtEnd = false; // Start off assuming we clicked somewhere in the text
  384. int fontTall = surface()->GetFontTall(_font);
  385. // where to Start reading
  386. int yStart = GetYStart();
  387. int x = DRAW_OFFSET_X, y = yStart;
  388. _pixelsIndent = 0;
  389. int lineBreakIndexIndex = 0;
  390. int startIndex = GetStartDrawIndex(lineBreakIndexIndex);
  391. bool onRightLine = false;
  392. int i;
  393. for (i = startIndex; i < m_TextStream.Count(); i++)
  394. {
  395. wchar_t ch = m_TextStream[i];
  396. if (_hideText)
  397. {
  398. ch = '*';
  399. }
  400. // if we are on the right line but off the end of if put the cursor at the end of the line
  401. if (m_LineBreaks[lineBreakIndexIndex] == i )
  402. {
  403. // add another line
  404. AddAnotherLine(x,y);
  405. lineBreakIndexIndex++;
  406. if (onRightLine)
  407. {
  408. _putCursorAtEnd = true;
  409. return i;
  410. }
  411. }
  412. // check to see if we're on the right line
  413. if (cy < yStart)
  414. {
  415. // cursor is above panel
  416. onRightLine = true;
  417. _putCursorAtEnd = true; // this will make the text scroll up if needed
  418. }
  419. else if (cy >= y && (cy < (y + fontTall + DRAW_OFFSET_Y)))
  420. {
  421. onRightLine = true;
  422. }
  423. int wide = getCharWidth(_font, ch);
  424. // if we've found the position, break
  425. if (onRightLine)
  426. {
  427. if (cx > GetWide()) // off right side of window
  428. {
  429. }
  430. else if (cx < (DRAW_OFFSET_X + _pixelsIndent) || cy < yStart) // off left side of window
  431. {
  432. return i; // move cursor one to left
  433. }
  434. if (cx >= x && cx < (x + wide))
  435. {
  436. // check which side of the letter they're on
  437. if (cx < (x + (wide * 0.5))) // left side
  438. {
  439. return i;
  440. }
  441. else // right side
  442. {
  443. return i + 1;
  444. }
  445. }
  446. }
  447. x += wide;
  448. }
  449. return i;
  450. }
  451. //-----------------------------------------------------------------------------
  452. // Purpose: Draws a character in the panel
  453. // Input: ch - character to draw
  454. // font - font to use
  455. // x, y - pixel location to draw char at
  456. // Output: returns the width of the character drawn
  457. //-----------------------------------------------------------------------------
  458. int TextEntry::DrawChar(wchar_t ch, HFont font, int index, int x, int y)
  459. {
  460. // add to the current position
  461. int charWide = getCharWidth(font, ch);
  462. int fontTall=surface()->GetFontTall(font);
  463. if (!iswcntrl(ch))
  464. {
  465. // draw selection, if any
  466. int selection0 = -1, selection1 = -1;
  467. GetSelectedRange(selection0, selection1);
  468. if (index >= selection0 && index < selection1)
  469. {
  470. // draw background selection color
  471. VPANEL focus = input()->GetFocus();
  472. Color bgColor;
  473. bool hasFocus = HasFocus();
  474. bool childOfFocus = focus && ipanel()->HasParent(focus, GetVPanel());
  475. // if one of the children of the SectionedListPanel has focus, then 'we have focus' if we're selected
  476. if ( hasFocus || childOfFocus )
  477. {
  478. bgColor = _selectionColor;
  479. }
  480. else
  481. {
  482. bgColor =_defaultSelectionBG2Color;
  483. }
  484. surface()->DrawSetColor(bgColor);
  485. surface()->DrawFilledRect(x, y, x + charWide, y + 1 + fontTall);
  486. // reset text color
  487. surface()->DrawSetTextColor(_selectionTextColor);
  488. }
  489. if (index == selection1)
  490. {
  491. // we've come out of selection, reset the color
  492. surface()->DrawSetTextColor(GetFgColor());
  493. }
  494. surface()->DrawSetTextPos(x, y);
  495. surface()->DrawUnicodeChar(ch);
  496. return charWide;
  497. }
  498. return 0;
  499. }
  500. //-----------------------------------------------------------------------------
  501. // Purpose: Draw the cursor, cursor is not drawn when it is blinked gone
  502. // Input: x,y where to draw cursor
  503. // Output: returns true if cursor was drawn.
  504. //-----------------------------------------------------------------------------
  505. bool TextEntry::DrawCursor(int x, int y)
  506. {
  507. if (!_cursorBlink)
  508. {
  509. int cx, cy;
  510. CursorToPixelSpace(_cursorPos, cx, cy);
  511. surface()->DrawSetColor(_cursorColor);
  512. int fontTall=surface()->GetFontTall(_font);
  513. surface()->DrawFilledRect(cx, cy, cx + 1, cy + fontTall);
  514. return true;
  515. }
  516. return false;
  517. }
  518. bool TextEntry::NeedsEllipses( HFont font, int *pIndex )
  519. {
  520. Assert( pIndex );
  521. *pIndex = -1;
  522. int wide = DRAW_OFFSET_X; // buffer on left and right end of text.
  523. for ( int i = 0; i < m_TextStream.Count(); ++i )
  524. {
  525. wide += getCharWidth( font , m_TextStream[i] );
  526. if (wide > _drawWidth)
  527. {
  528. *pIndex = i;
  529. return true;
  530. }
  531. }
  532. return false;
  533. }
  534. //-----------------------------------------------------------------------------
  535. // Purpose: Draws the text in the panel
  536. //-----------------------------------------------------------------------------
  537. void TextEntry::PaintBackground()
  538. {
  539. BaseClass::PaintBackground();
  540. // draw background
  541. Color col;
  542. if (IsEnabled())
  543. {
  544. col = GetBgColor();
  545. }
  546. else
  547. {
  548. col = _disabledBgColor;
  549. }
  550. Color saveBgColor = col;
  551. int wide, tall;
  552. GetSize( wide, tall );
  553. // surface()->DrawSetColor(col);
  554. // surface()->DrawFilledRect(0, 0, wide, tall);
  555. // where to Start drawing
  556. int x = DRAW_OFFSET_X + _pixelsIndent, y = GetYStart();
  557. m_nLangInset = 0;
  558. int langlen = 0;
  559. wchar_t shortcode[ 5 ];
  560. shortcode[ 0 ] = L'\0';
  561. if ( m_bAllowNonAsciiCharacters )
  562. {
  563. input()->GetIMELanguageShortCode( shortcode, sizeof( shortcode ) );
  564. if ( shortcode[ 0 ] != L'\0' &&
  565. wcsicmp( shortcode, L"EN" ) )
  566. {
  567. m_nLangInset = 0;
  568. langlen = wcslen( shortcode );
  569. for ( int i = 0; i < langlen; ++i )
  570. {
  571. m_nLangInset += getCharWidth( _smallfont, shortcode[ i ] );
  572. }
  573. m_nLangInset += 4;
  574. if ( m_bDrawLanguageIDAtLeft )
  575. {
  576. x += m_nLangInset;
  577. }
  578. wide -= m_nLangInset;
  579. }
  580. }
  581. HFont useFont = _font;
  582. surface()->DrawSetTextFont(useFont);
  583. if (IsEnabled())
  584. {
  585. col = GetFgColor();
  586. }
  587. else
  588. {
  589. col = _disabledFgColor;
  590. }
  591. surface()->DrawSetTextColor(col);
  592. _pixelsIndent = 0;
  593. int lineBreakIndexIndex = 0;
  594. int startIndex = GetStartDrawIndex(lineBreakIndexIndex);
  595. int remembery = y;
  596. int oldEnd = m_TextStream.Count();
  597. int oldCursorPos = _cursorPos;
  598. int nCompStart = -1;
  599. int nCompEnd = -1;
  600. // FIXME: Should insert at cursor pos instead
  601. bool composing = m_bAllowNonAsciiCharacters && wcslen( m_szComposition ) > 0;
  602. bool invertcomposition = input()->GetShouldInvertCompositionString();
  603. if ( composing )
  604. {
  605. nCompStart = _cursorPos;
  606. wchar_t *s = m_szComposition;
  607. while ( *s != L'\0' )
  608. {
  609. m_TextStream.InsertBefore( _cursorPos, *s );
  610. ++s;
  611. ++_cursorPos;
  612. }
  613. nCompEnd = _cursorPos;
  614. }
  615. bool highlight_composition = ( nCompStart != -1 && nCompEnd != -1 ) ? true : false;
  616. // draw text with an elipsis
  617. if ( (!_multiline) && (!_horizScrollingAllowed) )
  618. {
  619. int endIndex = m_TextStream.Count();
  620. // In editable windows only do the ellipsis if we don't have focus.
  621. // In non editable windows do it all the time.
  622. if ( (!HasFocus() && (IsEditable())) || (!IsEditable()) )
  623. {
  624. int i = -1;
  625. // loop through all the characters and sum their widths
  626. bool addEllipses = NeedsEllipses( useFont, &i );
  627. if ( addEllipses &&
  628. !IsEditable() &&
  629. m_bUseFallbackFont &&
  630. INVALID_FONT != m_hFallbackFont )
  631. {
  632. // Switch to small font!!!
  633. useFont = m_hFallbackFont;
  634. surface()->DrawSetTextFont(useFont);
  635. addEllipses = NeedsEllipses( useFont, &i );
  636. }
  637. if (addEllipses)
  638. {
  639. int elipsisWidth = 3 * getCharWidth(useFont, '.');
  640. while (elipsisWidth > 0 && i >= 0)
  641. {
  642. elipsisWidth -= getCharWidth(useFont, m_TextStream[i]);
  643. i--;
  644. }
  645. endIndex = i + 1;
  646. }
  647. // if we take off less than the last 3 chars we have to make sure
  648. // we take off the last 3 chars so selected text will look right.
  649. if (m_TextStream.Count() - endIndex < 3 && m_TextStream.Count() - endIndex > 0 )
  650. {
  651. endIndex = m_TextStream.Count() - 3;
  652. }
  653. }
  654. // draw the text
  655. int i;
  656. for (i = startIndex; i < endIndex; i++)
  657. {
  658. wchar_t ch = m_TextStream[i];
  659. if (_hideText)
  660. {
  661. ch = '*';
  662. }
  663. bool iscompositionchar = false;
  664. if ( highlight_composition )
  665. {
  666. iscompositionchar = ( i >= nCompStart && i < nCompEnd ) ? true : false;
  667. if ( iscompositionchar )
  668. {
  669. // Set the underline color to the text color
  670. surface()->DrawSetColor( col );
  671. int w = getCharWidth( useFont, ch );
  672. if ( invertcomposition )
  673. {
  674. // Invert color
  675. surface()->DrawSetTextColor( saveBgColor );
  676. surface()->DrawSetColor( col );
  677. surface()->DrawFilledRect(x, 0, x+w, tall);
  678. // Set the underline color to the text color
  679. surface()->DrawSetColor( saveBgColor );
  680. }
  681. surface()->DrawFilledRect( x, tall - 2, x + w, tall - 1 );
  682. }
  683. }
  684. // draw the character and update xposition
  685. x += DrawChar(ch, useFont, i, x, y);
  686. // Restore color
  687. surface()->DrawSetTextColor(col);
  688. }
  689. if (endIndex < m_TextStream.Count()) // add an elipsis
  690. {
  691. x += DrawChar('.', useFont, i, x, y);
  692. i++;
  693. x += DrawChar('.', useFont, i, x, y);
  694. i++;
  695. x += DrawChar('.', useFont, i, x, y);
  696. i++;
  697. }
  698. }
  699. else
  700. {
  701. // draw the text
  702. for ( int i = startIndex; i < m_TextStream.Count(); i++)
  703. {
  704. wchar_t ch = m_TextStream[i];
  705. if (_hideText)
  706. {
  707. ch = '*';
  708. }
  709. // if we've passed a line break go to that
  710. if ( _multiline && m_LineBreaks[lineBreakIndexIndex] == i)
  711. {
  712. // add another line
  713. AddAnotherLine(x, y);
  714. lineBreakIndexIndex++;
  715. }
  716. bool iscompositionchar = false;
  717. if ( highlight_composition )
  718. {
  719. iscompositionchar = ( i >= nCompStart && i < nCompEnd ) ? true : false;
  720. if ( iscompositionchar )
  721. {
  722. // Set the underline color to the text color
  723. surface()->DrawSetColor( col );
  724. int w = getCharWidth( useFont, ch );
  725. if ( invertcomposition )
  726. {
  727. // Invert color
  728. surface()->DrawSetTextColor( saveBgColor );
  729. surface()->DrawFilledRect(x, 0, x+w, tall);
  730. // Set the underline color to the text color
  731. surface()->DrawSetColor( saveBgColor );
  732. }
  733. surface()->DrawFilledRect( x, tall - 2, x + w, tall - 1 );
  734. }
  735. }
  736. // draw the character and update xposition
  737. x += DrawChar(ch, useFont, i, x, y);
  738. // Restore color
  739. surface()->DrawSetTextColor(col);
  740. }
  741. }
  742. // custom border
  743. //!! need to replace this with scheme stuff (TextEntryBorder/TextEntrySelectedBorder)
  744. surface()->DrawSetColor(50, 50, 50, 255);
  745. if (IsEnabled() && IsEditable() && HasFocus())
  746. {
  747. // set a more distinct border color
  748. surface()->DrawSetColor(0, 0, 0, 255);
  749. DrawCursor (x, y);
  750. if ( composing )
  751. {
  752. LocalToScreen( x, y );
  753. input()->SetCandidateWindowPos( x, y );
  754. }
  755. }
  756. int newEnd = m_TextStream.Count();
  757. int remove = newEnd - oldEnd;
  758. if ( remove > 0 )
  759. {
  760. m_TextStream.RemoveMultiple( oldCursorPos, remove );
  761. }
  762. _cursorPos = oldCursorPos;
  763. if ( HasFocus() && m_bAllowNonAsciiCharacters && langlen > 0 )
  764. {
  765. wide += m_nLangInset;
  766. if ( m_bDrawLanguageIDAtLeft )
  767. {
  768. x = 0;
  769. }
  770. else
  771. {
  772. // Draw language identififer
  773. x = wide - m_nLangInset;
  774. }
  775. surface()->DrawSetColor( col );
  776. surface()->DrawFilledRect( x, 2, x + m_nLangInset-2, tall - 2 );
  777. saveBgColor[ 3 ] = 255;
  778. surface()->DrawSetTextColor( saveBgColor );
  779. x += 1;
  780. surface()->DrawSetTextFont(_smallfont);
  781. for ( int i = 0; i < langlen; ++i )
  782. {
  783. x += DrawChar( shortcode[ i ], _smallfont, i, x, remembery );
  784. }
  785. }
  786. }
  787. //-----------------------------------------------------------------------------
  788. // Purpose: Called when data changes or panel size changes
  789. //-----------------------------------------------------------------------------
  790. void TextEntry::PerformLayout()
  791. {
  792. BaseClass::PerformLayout();
  793. RecalculateLineBreaks();
  794. // recalculate scrollbar position
  795. if (_verticalScrollbar)
  796. {
  797. LayoutVerticalScrollBarSlider();
  798. }
  799. // force a Repaint
  800. Repaint();
  801. }
  802. // moves x,y to the Start of the next line of text
  803. void TextEntry::AddAnotherLine(int &cx, int &cy)
  804. {
  805. cx = DRAW_OFFSET_X + _pixelsIndent;
  806. cy += (surface()->GetFontTall(_font) + DRAW_OFFSET_Y);
  807. }
  808. //-----------------------------------------------------------------------------
  809. // Purpose: Recalculates line breaks
  810. //-----------------------------------------------------------------------------
  811. void TextEntry::RecalculateLineBreaks()
  812. {
  813. if (!_multiline || _hideText)
  814. return;
  815. if (m_TextStream.Count() < 1)
  816. return;
  817. HFont font = _font;
  818. // line break to our width -2 pixel to keep cursor blinking in window
  819. // (assumes borders are 1 pixel)
  820. int wide = GetWide()-2;
  821. // subtract the scrollbar width
  822. if (_vertScrollBar)
  823. {
  824. wide -= _vertScrollBar->GetWide();
  825. }
  826. int charWidth;
  827. int x = DRAW_OFFSET_X, y = DRAW_OFFSET_Y;
  828. int wordStartIndex = 0;
  829. int wordLength = 0;
  830. bool hasWord = false;
  831. bool justStartedNewLine = true;
  832. bool wordStartedOnNewLine = true;
  833. int startChar;
  834. if (_recalculateBreaksIndex <= 0)
  835. {
  836. m_LineBreaks.RemoveAll();
  837. startChar=0;
  838. }
  839. else
  840. {
  841. // remove the rest of the linebreaks list since its out of date.
  842. for (int i=_recalculateBreaksIndex+1; i < m_LineBreaks.Count(); ++i)
  843. {
  844. m_LineBreaks.Remove((int)i);
  845. --i; // removing shrinks the list!
  846. }
  847. startChar = m_LineBreaks[_recalculateBreaksIndex];
  848. }
  849. // handle the case where this char is a new line, in that case
  850. // we have already taken its break index into account above so skip it.
  851. if (m_TextStream[startChar] == '\r' || m_TextStream[startChar] == '\n')
  852. {
  853. startChar++;
  854. }
  855. // loop through all the characters
  856. int i;
  857. for (i = startChar; i < m_TextStream.Count(); ++i)
  858. {
  859. wchar_t ch = m_TextStream[i];
  860. // line break only on whitespace characters
  861. if (!iswspace(ch))
  862. {
  863. if (hasWord)
  864. {
  865. // append to the current word
  866. }
  867. else
  868. {
  869. // Start a new word
  870. wordStartIndex = i;
  871. hasWord = true;
  872. wordStartedOnNewLine = justStartedNewLine;
  873. wordLength = 0;
  874. }
  875. }
  876. else
  877. {
  878. // whitespace/punctuation character
  879. // end the word
  880. hasWord = false;
  881. }
  882. // get the width
  883. charWidth = getCharWidth(font, ch);
  884. if (!iswcntrl(ch))
  885. {
  886. justStartedNewLine = false;
  887. }
  888. // check to see if the word is past the end of the line [wordStartIndex, i)
  889. if ((x + charWidth) >= wide || ch == '\r' || ch == '\n')
  890. {
  891. // add another line
  892. AddAnotherLine(x,y);
  893. justStartedNewLine = true;
  894. hasWord = false;
  895. if (ch == '\r' || ch == '\n')
  896. {
  897. // set the break at the current character
  898. m_LineBreaks.AddToTail(i);
  899. }
  900. else if (wordStartedOnNewLine)
  901. {
  902. // word is longer than a line, so set the break at the current cursor
  903. m_LineBreaks.AddToTail(i);
  904. }
  905. else
  906. {
  907. // set it at the last word Start
  908. m_LineBreaks.AddToTail(wordStartIndex);
  909. // just back to reparse the next line of text
  910. i = wordStartIndex;
  911. }
  912. // reset word length
  913. wordLength = 0;
  914. }
  915. // add to the size
  916. x += charWidth;
  917. wordLength += charWidth;
  918. }
  919. _charCount = i-1;
  920. // end the list
  921. m_LineBreaks.AddToTail(BUFFER_SIZE);
  922. // set up the scrollbar
  923. LayoutVerticalScrollBarSlider();
  924. }
  925. //-----------------------------------------------------------------------------
  926. // Purpose: Recalculate where the vertical scroll bar slider should be
  927. // based on the current cursor line we are on.
  928. //-----------------------------------------------------------------------------
  929. void TextEntry::LayoutVerticalScrollBarSlider()
  930. {
  931. // set up the scrollbar
  932. if (_vertScrollBar)
  933. {
  934. int wide, tall;
  935. GetSize (wide, tall);
  936. // make sure we factor in insets
  937. int ileft, iright, itop, ibottom;
  938. GetInset(ileft, iright, itop, ibottom);
  939. // with a scroll bar we take off the inset
  940. wide -= iright;
  941. _vertScrollBar->SetPos(wide - _vertScrollBar->GetWide(), 0);
  942. // scrollbar is inside the borders.
  943. _vertScrollBar->SetSize(_vertScrollBar->GetWide(), tall - ibottom - itop);
  944. // calculate how many lines we can fully display
  945. int displayLines = tall / (surface()->GetFontTall(_font) + DRAW_OFFSET_Y);
  946. int numLines = m_LineBreaks.Count();
  947. if (numLines <= displayLines)
  948. {
  949. // disable the scrollbar
  950. _vertScrollBar->SetEnabled(false);
  951. _vertScrollBar->SetRange(0, numLines);
  952. _vertScrollBar->SetRangeWindow(numLines);
  953. _vertScrollBar->SetValue(0);
  954. }
  955. else
  956. {
  957. // set the scrollbars range
  958. _vertScrollBar->SetRange(0, numLines);
  959. _vertScrollBar->SetRangeWindow(displayLines);
  960. _vertScrollBar->SetEnabled(true);
  961. // this should make it scroll one line at a time
  962. _vertScrollBar->SetButtonPressedScrollValue(1);
  963. // set the value to view the last entries
  964. int val = _vertScrollBar->GetValue();
  965. int maxval = _vertScrollBar->GetValue() + displayLines;
  966. if (GetCursorLine() < val )
  967. {
  968. while (GetCursorLine() < val)
  969. {
  970. val--;
  971. }
  972. }
  973. else if (GetCursorLine() >= maxval)
  974. {
  975. while (GetCursorLine() >= maxval)
  976. {
  977. maxval++;
  978. }
  979. maxval -= displayLines;
  980. val = maxval;
  981. }
  982. else
  983. {
  984. //val = GetCursorLine();
  985. }
  986. _vertScrollBar->SetValue(val);
  987. _vertScrollBar->InvalidateLayout();
  988. _vertScrollBar->Repaint();
  989. }
  990. }
  991. }
  992. //-----------------------------------------------------------------------------
  993. // Purpose: Set boolean value of baseclass variables.
  994. //-----------------------------------------------------------------------------
  995. void TextEntry::SetEnabled(bool state)
  996. {
  997. BaseClass::SetEnabled(state);
  998. Repaint();
  999. }
  1000. //-----------------------------------------------------------------------------
  1001. // Purpose: Sets whether text wraps around multiple lines or not
  1002. // Input : state - true or false
  1003. //-----------------------------------------------------------------------------
  1004. void TextEntry::SetMultiline(bool state)
  1005. {
  1006. _multiline = state;
  1007. }
  1008. bool TextEntry::IsMultiline()
  1009. {
  1010. return _multiline;
  1011. }
  1012. //-----------------------------------------------------------------------------
  1013. // Purpose: sets whether or not the edit catches and stores ENTER key presses
  1014. //-----------------------------------------------------------------------------
  1015. void TextEntry::SetCatchEnterKey(bool state)
  1016. {
  1017. _catchEnterKey = state;
  1018. }
  1019. //-----------------------------------------------------------------------------
  1020. // Purpose: Sets whether a vertical scrollbar is visible
  1021. // Input : state - true or false
  1022. //-----------------------------------------------------------------------------
  1023. void TextEntry::SetVerticalScrollbar(bool state)
  1024. {
  1025. _verticalScrollbar = state;
  1026. if (_verticalScrollbar)
  1027. {
  1028. if (!_vertScrollBar)
  1029. {
  1030. _vertScrollBar = new ScrollBar(this, "ScrollBar", true);
  1031. _vertScrollBar->AddActionSignalTarget(this);
  1032. }
  1033. _vertScrollBar->SetVisible(true);
  1034. }
  1035. else if (_vertScrollBar)
  1036. {
  1037. _vertScrollBar->SetVisible(false);
  1038. }
  1039. InvalidateLayout();
  1040. }
  1041. //-----------------------------------------------------------------------------
  1042. // Purpose: sets _editable flag
  1043. // Input : state - true or false
  1044. //-----------------------------------------------------------------------------
  1045. void TextEntry::SetEditable(bool state)
  1046. {
  1047. if ( state )
  1048. {
  1049. SetDropEnabled( true, 1.0f );
  1050. }
  1051. else
  1052. {
  1053. SetDropEnabled( false );
  1054. }
  1055. _editable = state;
  1056. }
  1057. const wchar_t *UnlocalizeUnicode( wchar_t *unicode )
  1058. {
  1059. if ( !unicode )
  1060. return L"";
  1061. if ( *unicode == L'#' )
  1062. {
  1063. char lookup[ 512 ];
  1064. g_pVGuiLocalize->ConvertUnicodeToANSI( unicode + 1, lookup, sizeof( lookup ) );
  1065. return g_pVGuiLocalize->Find( lookup );
  1066. }
  1067. return unicode;
  1068. }
  1069. Menu * TextEntry::GetEditMenu()
  1070. {
  1071. return m_pEditMenu;
  1072. }
  1073. //-----------------------------------------------------------------------------
  1074. // Purpose: Create cut/copy/paste dropdown menu
  1075. //-----------------------------------------------------------------------------
  1076. void TextEntry::CreateEditMenu()
  1077. {
  1078. // create a drop down cut/copy/paste menu appropriate for this object's states
  1079. if (m_pEditMenu)
  1080. delete m_pEditMenu;
  1081. m_pEditMenu = new Menu(this, "EditMenu");
  1082. m_pEditMenu->SetFont( _font );
  1083. // add cut/copy/paste drop down options if its editable, just copy if it is not
  1084. if (_editable && !_hideText)
  1085. {
  1086. m_pEditMenu->AddMenuItem("#TextEntry_Cut", new KeyValues("DoCutSelected"), this);
  1087. }
  1088. if ( !_hideText )
  1089. {
  1090. m_pEditMenu->AddMenuItem("#TextEntry_Copy", new KeyValues("DoCopySelected"), this);
  1091. }
  1092. if (_editable)
  1093. {
  1094. m_pEditMenu->AddMenuItem("#TextEntry_Paste", new KeyValues("DoPaste"), this);
  1095. }
  1096. if ( m_bAllowNonAsciiCharacters )
  1097. {
  1098. IInput::LanguageItem *langs = NULL;
  1099. int count = input()->GetIMELanguageList( NULL, 0 );
  1100. if ( count > 0 )
  1101. {
  1102. langs = new IInput::LanguageItem[ count ];
  1103. input()->GetIMELanguageList( langs, count );
  1104. // Create a submenu
  1105. Menu *subMenu = new Menu( this, "LanguageMenu" );
  1106. subMenu->SetFont( _font );
  1107. for ( int i = 0; i < count; ++i )
  1108. {
  1109. int id = subMenu->AddCheckableMenuItem( "Language", UnlocalizeUnicode( langs[ i ].menuname ), new KeyValues( "DoLanguageChanged", "handle", langs[ i ].handleValue ), this );
  1110. if ( langs[ i ].active )
  1111. {
  1112. subMenu->SetMenuItemChecked( id, true );
  1113. }
  1114. }
  1115. m_pEditMenu->AddCascadingMenuItem( "Language", "#TextEntry_Language", "", this, subMenu );
  1116. delete[] langs;
  1117. }
  1118. IInput::ConversionModeItem *modes = NULL;
  1119. count = input()->GetIMEConversionModes( NULL, 0 );
  1120. // if count == 0 then native mode is the only mode...
  1121. if ( count > 0 )
  1122. {
  1123. modes = new IInput::ConversionModeItem[ count ];
  1124. input()->GetIMEConversionModes( modes, count );
  1125. // Create a submenu
  1126. Menu *subMenu = new Menu( this, "ConversionModeMenu" );
  1127. subMenu->SetFont( _font );
  1128. for ( int i = 0; i < count; ++i )
  1129. {
  1130. int id = subMenu->AddCheckableMenuItem( "ConversionMode", UnlocalizeUnicode( modes[ i ].menuname ), new KeyValues( "DoConversionModeChanged", "handle", modes[ i ].handleValue ), this );
  1131. if ( modes[ i ].active )
  1132. {
  1133. subMenu->SetMenuItemChecked( id, true );
  1134. }
  1135. }
  1136. m_pEditMenu->AddCascadingMenuItem( "ConversionMode", "#TextEntry_ConversionMode", "", this, subMenu );
  1137. delete[] modes;
  1138. }
  1139. IInput::SentenceModeItem *sentencemodes = NULL;
  1140. count = input()->GetIMESentenceModes( NULL, 0 );
  1141. // if count == 0 then native mode is the only mode...
  1142. if ( count > 0 )
  1143. {
  1144. sentencemodes = new IInput::SentenceModeItem[ count ];
  1145. input()->GetIMESentenceModes( sentencemodes, count );
  1146. // Create a submenu
  1147. Menu *subMenu = new Menu( this, "SentenceModeMenu" );
  1148. subMenu->SetFont( _font );
  1149. for ( int i = 0; i < count; ++i )
  1150. {
  1151. int id = subMenu->AddCheckableMenuItem( "SentenceMode", UnlocalizeUnicode( sentencemodes[ i ].menuname ), new KeyValues( "DoConversionModeChanged", "handle", modes[ i ].handleValue ), this );
  1152. if ( modes[ i ].active )
  1153. {
  1154. subMenu->SetMenuItemChecked( id, true );
  1155. }
  1156. }
  1157. m_pEditMenu->AddCascadingMenuItem( "SentenceMode", "#TextEntry_SentenceMode", "", this, subMenu );
  1158. delete[] sentencemodes;
  1159. }
  1160. }
  1161. m_pEditMenu->SetVisible(false);
  1162. m_pEditMenu->SetParent(this);
  1163. m_pEditMenu->AddActionSignalTarget(this);
  1164. }
  1165. //-----------------------------------------------------------------------------
  1166. // Purpsoe: Returns state of _editable flag
  1167. //-----------------------------------------------------------------------------
  1168. bool TextEntry::IsEditable()
  1169. {
  1170. return _editable && IsEnabled();
  1171. }
  1172. //-----------------------------------------------------------------------------
  1173. // Purpose: We want single line windows to scroll horizontally and select text
  1174. // in response to clicking and holding outside window
  1175. //-----------------------------------------------------------------------------
  1176. void TextEntry::OnMouseFocusTicked()
  1177. {
  1178. // if a button is down move the scrollbar slider the appropriate direction
  1179. if (_mouseDragSelection) // text is being selected via mouse clicking and dragging
  1180. {
  1181. OnCursorMoved(0,0); // we want the text to scroll as if we were dragging
  1182. }
  1183. }
  1184. //-----------------------------------------------------------------------------
  1185. // Purpose: If a cursor enters the window, we are not elegible for
  1186. // MouseFocusTicked events
  1187. //-----------------------------------------------------------------------------
  1188. void TextEntry::OnCursorEntered()
  1189. {
  1190. _mouseDragSelection = false; // outside of window dont recieve drag scrolling ticks
  1191. }
  1192. //-----------------------------------------------------------------------------
  1193. // Purpose: When the cursor is outside the window, if we are holding the mouse
  1194. // button down, then we want the window to scroll the text one char at a time
  1195. // using Ticks
  1196. //-----------------------------------------------------------------------------
  1197. void TextEntry::OnCursorExited() // outside of window recieve drag scrolling ticks
  1198. {
  1199. if (_mouseSelection)
  1200. _mouseDragSelection = true;
  1201. }
  1202. //-----------------------------------------------------------------------------
  1203. // Purpose: Handle selection of text by mouse
  1204. //-----------------------------------------------------------------------------
  1205. void TextEntry::OnCursorMoved(int ignX, int ignY)
  1206. {
  1207. if (_mouseSelection)
  1208. {
  1209. // update the cursor position
  1210. int x, y;
  1211. input()->GetCursorPos(x, y);
  1212. ScreenToLocal(x, y);
  1213. _cursorPos = PixelToCursorSpace(x, y);
  1214. // if we are at Start of buffer don't put cursor at end, this will keep
  1215. // window from scrolling up to a blank line
  1216. if (_cursorPos == 0)
  1217. _putCursorAtEnd = false;
  1218. // scroll if we went off left side
  1219. if (_cursorPos == _currentStartIndex)
  1220. {
  1221. if (_cursorPos > 0)
  1222. _cursorPos--;
  1223. ScrollLeft();
  1224. _cursorPos = _currentStartIndex;
  1225. }
  1226. if ( _cursorPos != _select[1])
  1227. {
  1228. _select[1] = _cursorPos;
  1229. Repaint();
  1230. }
  1231. }
  1232. }
  1233. //-----------------------------------------------------------------------------
  1234. // Purpose: Handle Mouse button down events.
  1235. //-----------------------------------------------------------------------------
  1236. void TextEntry::OnMousePressed(MouseCode code)
  1237. {
  1238. if (code == MOUSE_LEFT)
  1239. {
  1240. bool keepChecking = SelectCheck( true );
  1241. if ( !keepChecking )
  1242. {
  1243. BaseClass::OnMousePressed( code );
  1244. return;
  1245. }
  1246. // move the cursor to where the mouse was pressed
  1247. int x, y;
  1248. input()->GetCursorPos(x, y);
  1249. ScreenToLocal(x, y);
  1250. _cursorIsAtEnd = _putCursorAtEnd; // save this off before calling PixelToCursorSpace()
  1251. _cursorPos = PixelToCursorSpace(x, y);
  1252. // if we are at Start of buffer don't put cursor at end, this will keep
  1253. // window from scrolling up to a blank line
  1254. if (_cursorPos == 0)
  1255. _putCursorAtEnd = false;
  1256. // enter selection mode
  1257. input()->SetMouseCapture(GetVPanel());
  1258. _mouseSelection = true;
  1259. if (_select[0] < 0)
  1260. {
  1261. // if no initial selection position, Start selection position at cursor
  1262. _select[0] = _cursorPos;
  1263. }
  1264. _select[1] = _cursorPos;
  1265. ResetCursorBlink();
  1266. RequestFocus();
  1267. Repaint();
  1268. }
  1269. else if (code == MOUSE_RIGHT) // check for context menu open
  1270. {
  1271. CreateEditMenu();
  1272. Assert(m_pEditMenu);
  1273. OpenEditMenu();
  1274. }
  1275. }
  1276. //-----------------------------------------------------------------------------
  1277. // Purpose: Handle mouse button up events
  1278. //-----------------------------------------------------------------------------
  1279. void TextEntry::OnMouseReleased(MouseCode code)
  1280. {
  1281. _mouseSelection = false;
  1282. input()->SetMouseCapture(NULL);
  1283. // make sure something has been selected
  1284. int cx0, cx1;
  1285. if (GetSelectedRange(cx0, cx1))
  1286. {
  1287. if (cx1 - cx0 == 0)
  1288. {
  1289. // nullify selection
  1290. _select[0] = -1;
  1291. }
  1292. }
  1293. }
  1294. //-----------------------------------------------------------------------------
  1295. // Purpose:
  1296. // Input : code -
  1297. //-----------------------------------------------------------------------------
  1298. void TextEntry::OnMouseTriplePressed( MouseCode code )
  1299. {
  1300. BaseClass::OnMouseTriplePressed( code );
  1301. // left triple clicking on a word selects all
  1302. if (code == MOUSE_LEFT)
  1303. {
  1304. GotoTextEnd();
  1305. SelectAllText( false );
  1306. }
  1307. }
  1308. //-----------------------------------------------------------------------------
  1309. // Purpose: Handle mouse double clicks
  1310. //-----------------------------------------------------------------------------
  1311. void TextEntry::OnMouseDoublePressed(MouseCode code)
  1312. {
  1313. // left double clicking on a word selects the word
  1314. if (code == MOUSE_LEFT)
  1315. {
  1316. // move the cursor just as if you single clicked.
  1317. OnMousePressed(code);
  1318. // then find the start and end of the word we are in to highlight it.
  1319. int selectSpot[2];
  1320. GotoWordLeft();
  1321. selectSpot[0] = _cursorPos;
  1322. GotoWordRight();
  1323. selectSpot[1] = _cursorPos;
  1324. if (_cursorPos > 0)
  1325. {
  1326. if (iswspace(m_TextStream[_cursorPos - 1]))
  1327. {
  1328. selectSpot[1]--;
  1329. _cursorPos--;
  1330. }
  1331. _select[0] = selectSpot[0];
  1332. _select[1] = selectSpot[1];
  1333. _mouseSelection = true;
  1334. }
  1335. }
  1336. }
  1337. //-----------------------------------------------------------------------------
  1338. // Purpose: Turn off text selection code when mouse button is not down
  1339. //-----------------------------------------------------------------------------
  1340. void TextEntry::OnMouseCaptureLost()
  1341. {
  1342. _mouseSelection = false;
  1343. }
  1344. //-----------------------------------------------------------------------------
  1345. // Purpose: Only pass some keys upwards
  1346. // everything else we don't relay to the parent
  1347. //-----------------------------------------------------------------------------
  1348. void TextEntry::OnKeyCodePressed(KeyCode code)
  1349. {
  1350. // Pass enter on only if _catchEnterKey isn't set
  1351. if ( code == KEY_ENTER )
  1352. {
  1353. if ( !_catchEnterKey )
  1354. {
  1355. Panel::OnKeyCodePressed( code );
  1356. return;
  1357. }
  1358. }
  1359. // Forward on just a few key codes, everything else can be handled by TextEntry itself
  1360. switch ( code )
  1361. {
  1362. case KEY_F1:
  1363. case KEY_F2:
  1364. case KEY_F3:
  1365. case KEY_F4:
  1366. case KEY_F5:
  1367. case KEY_F6:
  1368. case KEY_F7:
  1369. case KEY_F8:
  1370. case KEY_F9:
  1371. case KEY_F10:
  1372. case KEY_F11:
  1373. case KEY_F12:
  1374. case KEY_ESCAPE:
  1375. case KEY_APP:
  1376. Panel::OnKeyCodePressed( code );
  1377. return;
  1378. }
  1379. // Pass on the joystick and mouse codes
  1380. if ( IsMouseCode(code) || IsNovintButtonCode(code) || IsJoystickCode(code) || IsJoystickButtonCode(code) ||
  1381. IsJoystickPOVCode(code) || IsJoystickAxisCode(code) )
  1382. {
  1383. Panel::OnKeyCodePressed( code );
  1384. return;
  1385. }
  1386. }
  1387. //-----------------------------------------------------------------------------
  1388. // Purpose: Masks which keys get chained up
  1389. // Maps keyboard input to text window functions.
  1390. //-----------------------------------------------------------------------------
  1391. void TextEntry::OnKeyCodeTyped(KeyCode code)
  1392. {
  1393. _cursorIsAtEnd = _putCursorAtEnd;
  1394. _putCursorAtEnd = false;
  1395. bool shift = (input()->IsKeyDown(KEY_LSHIFT) || input()->IsKeyDown(KEY_RSHIFT));
  1396. bool ctrl = (input()->IsKeyDown(KEY_LCONTROL) || input()->IsKeyDown(KEY_RCONTROL));
  1397. bool alt = (input()->IsKeyDown(KEY_LALT) || input()->IsKeyDown(KEY_RALT));
  1398. bool winkey = (input()->IsKeyDown(KEY_LWIN) || input()->IsKeyDown(KEY_RWIN));
  1399. bool fallThrough = false;
  1400. if ( ( ctrl || ( winkey && IsOSX() ) ) && !alt)
  1401. {
  1402. switch(code)
  1403. {
  1404. case KEY_A:
  1405. SelectAllText(false);
  1406. // move the cursor to the end
  1407. _cursorPos = _select[1];
  1408. break;
  1409. case KEY_INSERT:
  1410. case KEY_C:
  1411. {
  1412. CopySelected();
  1413. break;
  1414. }
  1415. case KEY_V:
  1416. {
  1417. DeleteSelected();
  1418. Paste();
  1419. break;
  1420. }
  1421. case KEY_X:
  1422. {
  1423. CopySelected();
  1424. DeleteSelected();
  1425. break;
  1426. }
  1427. case KEY_Z:
  1428. {
  1429. Undo();
  1430. break;
  1431. }
  1432. case KEY_RIGHT:
  1433. {
  1434. GotoWordRight();
  1435. break;
  1436. }
  1437. case KEY_LEFT:
  1438. {
  1439. GotoWordLeft();
  1440. break;
  1441. }
  1442. case KEY_ENTER:
  1443. {
  1444. // insert a newline
  1445. if (_multiline)
  1446. {
  1447. DeleteSelected();
  1448. SaveUndoState();
  1449. InsertChar('\n');
  1450. }
  1451. // fire newlines back to the main target if asked to
  1452. if(_sendNewLines)
  1453. {
  1454. PostActionSignal(new KeyValues("TextNewLine"));
  1455. }
  1456. break;
  1457. }
  1458. case KEY_HOME:
  1459. {
  1460. GotoTextStart();
  1461. break;
  1462. }
  1463. case KEY_END:
  1464. {
  1465. GotoTextEnd();
  1466. break;
  1467. }
  1468. case KEY_PAGEUP:
  1469. {
  1470. OnChangeIME( true );
  1471. }
  1472. break;
  1473. case KEY_PAGEDOWN:
  1474. {
  1475. OnChangeIME( false );
  1476. }
  1477. break;
  1478. case KEY_UP:
  1479. case KEY_DOWN:
  1480. if ( m_bAllowNonAsciiCharacters )
  1481. {
  1482. FlipToLastIME();
  1483. }
  1484. else
  1485. {
  1486. fallThrough = true;
  1487. }
  1488. break;
  1489. default:
  1490. {
  1491. fallThrough = true;
  1492. break;
  1493. }
  1494. }
  1495. }
  1496. else if (alt)
  1497. {
  1498. // do nothing with ALT-x keys
  1499. if ( !m_bAllowNonAsciiCharacters || ( code != KEY_BACKQUOTE ) )
  1500. {
  1501. fallThrough = true;
  1502. }
  1503. }
  1504. else
  1505. {
  1506. switch(code)
  1507. {
  1508. case KEY_TAB:
  1509. case KEY_LSHIFT:
  1510. case KEY_RSHIFT:
  1511. case KEY_ESCAPE:
  1512. {
  1513. fallThrough = true;
  1514. break;
  1515. }
  1516. case KEY_INSERT:
  1517. {
  1518. if (shift)
  1519. {
  1520. DeleteSelected();
  1521. Paste();
  1522. }
  1523. else
  1524. {
  1525. fallThrough = true;
  1526. }
  1527. break;
  1528. }
  1529. case KEY_DELETE:
  1530. {
  1531. if (shift)
  1532. {
  1533. // shift-delete is cut
  1534. CopySelected();
  1535. DeleteSelected();
  1536. }
  1537. else
  1538. {
  1539. Delete();
  1540. }
  1541. break;
  1542. }
  1543. case KEY_LEFT:
  1544. {
  1545. GotoLeft();
  1546. break;
  1547. }
  1548. case KEY_RIGHT:
  1549. {
  1550. GotoRight();
  1551. break;
  1552. }
  1553. case KEY_UP:
  1554. {
  1555. if (_multiline)
  1556. {
  1557. GotoUp();
  1558. }
  1559. else
  1560. {
  1561. fallThrough = true;
  1562. }
  1563. break;
  1564. }
  1565. case KEY_DOWN:
  1566. {
  1567. if (_multiline)
  1568. {
  1569. GotoDown();
  1570. }
  1571. else
  1572. {
  1573. fallThrough = true;
  1574. }
  1575. break;
  1576. }
  1577. case KEY_HOME:
  1578. {
  1579. if (_multiline)
  1580. {
  1581. GotoFirstOfLine();
  1582. }
  1583. else
  1584. {
  1585. GotoTextStart();
  1586. }
  1587. break;
  1588. }
  1589. case KEY_END:
  1590. {
  1591. GotoEndOfLine();
  1592. break;
  1593. }
  1594. case KEY_BACKSPACE:
  1595. {
  1596. int x0, x1;
  1597. if (GetSelectedRange(x0, x1))
  1598. {
  1599. // act just like delete if there is a selection
  1600. DeleteSelected();
  1601. }
  1602. else
  1603. {
  1604. Backspace();
  1605. }
  1606. break;
  1607. }
  1608. case KEY_ENTER:
  1609. {
  1610. // insert a newline
  1611. if (_multiline && _catchEnterKey)
  1612. {
  1613. DeleteSelected();
  1614. SaveUndoState();
  1615. InsertChar('\n');
  1616. }
  1617. else
  1618. {
  1619. fallThrough = true;
  1620. }
  1621. // fire newlines back to the main target if asked to
  1622. if(_sendNewLines)
  1623. {
  1624. PostActionSignal(new KeyValues("TextNewLine"));
  1625. }
  1626. break;
  1627. }
  1628. case KEY_PAGEUP:
  1629. {
  1630. int val = 0;
  1631. fallThrough = (!_multiline) && (!_vertScrollBar);
  1632. if (_vertScrollBar)
  1633. {
  1634. val = _vertScrollBar->GetValue();
  1635. }
  1636. // if there is a scroll bar scroll down one rangewindow
  1637. if (_multiline)
  1638. {
  1639. int displayLines = GetTall() / (surface()->GetFontTall(_font) + DRAW_OFFSET_Y);
  1640. // move the cursor down
  1641. for (int i=0; i < displayLines; i++)
  1642. {
  1643. GotoUp();
  1644. }
  1645. }
  1646. // if there is a scroll bar scroll down one rangewindow
  1647. if (_vertScrollBar)
  1648. {
  1649. int window = _vertScrollBar->GetRangeWindow();
  1650. int newval = _vertScrollBar->GetValue();
  1651. int linesToMove = window - (val - newval);
  1652. _vertScrollBar->SetValue(val - linesToMove - 1);
  1653. }
  1654. break;
  1655. }
  1656. case KEY_PAGEDOWN:
  1657. {
  1658. int val = 0;
  1659. fallThrough = (!_multiline) && (!_vertScrollBar);
  1660. if (_vertScrollBar)
  1661. {
  1662. val = _vertScrollBar->GetValue();
  1663. }
  1664. if (_multiline)
  1665. {
  1666. int displayLines = GetTall() / (surface()->GetFontTall(_font) + DRAW_OFFSET_Y);
  1667. // move the cursor down
  1668. for (int i=0; i < displayLines; i++)
  1669. {
  1670. GotoDown();
  1671. }
  1672. }
  1673. // if there is a scroll bar scroll down one rangewindow
  1674. if (_vertScrollBar)
  1675. {
  1676. int window = _vertScrollBar->GetRangeWindow();
  1677. int newval = _vertScrollBar->GetValue();
  1678. int linesToMove = window - (newval - val);
  1679. _vertScrollBar->SetValue(val + linesToMove + 1);
  1680. }
  1681. break;
  1682. }
  1683. case KEY_F1:
  1684. case KEY_F2:
  1685. case KEY_F3:
  1686. case KEY_F4:
  1687. case KEY_F5:
  1688. case KEY_F6:
  1689. case KEY_F7:
  1690. case KEY_F8:
  1691. case KEY_F9:
  1692. case KEY_F10:
  1693. case KEY_F11:
  1694. case KEY_F12:
  1695. {
  1696. fallThrough = true;
  1697. break;
  1698. }
  1699. default:
  1700. {
  1701. // return if any other char is pressed.
  1702. // as it will be a unicode char.
  1703. // and we don't want select[1] changed unless a char was pressed that this fxn handles
  1704. return;
  1705. }
  1706. }
  1707. }
  1708. // select[1] is the location in the line where the blinking cursor started
  1709. _select[1] = _cursorPos;
  1710. if (_dataChanged)
  1711. {
  1712. FireActionSignal();
  1713. }
  1714. // chain back on some keys
  1715. if (fallThrough)
  1716. {
  1717. _putCursorAtEnd=_cursorIsAtEnd; // keep state of cursor on fallthroughs
  1718. BaseClass::OnKeyCodeTyped(code);
  1719. }
  1720. }
  1721. //-----------------------------------------------------------------------------
  1722. // Purpose: Masks which keys get chained up
  1723. // Maps keyboard input to text window functions.
  1724. //-----------------------------------------------------------------------------
  1725. void TextEntry::OnKeyTyped(wchar_t unichar)
  1726. {
  1727. _cursorIsAtEnd = _putCursorAtEnd;
  1728. _putCursorAtEnd=false;
  1729. bool fallThrough = false;
  1730. // KeyCodes handle all non printable chars
  1731. if (iswcntrl(unichar) || unichar == 9 ) // tab key (code 9) is printable but handled elsewhere
  1732. return;
  1733. // do readonly keys
  1734. if (!IsEditable())
  1735. {
  1736. BaseClass::OnKeyTyped(unichar);
  1737. return;
  1738. }
  1739. if (unichar != 0)
  1740. {
  1741. DeleteSelected();
  1742. SaveUndoState();
  1743. InsertChar(unichar);
  1744. }
  1745. // select[1] is the location in the line where the blinking cursor started
  1746. _select[1] = _cursorPos;
  1747. if (_dataChanged)
  1748. {
  1749. FireActionSignal();
  1750. }
  1751. // chain back on some keys
  1752. if (fallThrough)
  1753. {
  1754. _putCursorAtEnd=_cursorIsAtEnd; // keep state of cursor on fallthroughs
  1755. BaseClass::OnKeyTyped(unichar);
  1756. }
  1757. }
  1758. //-----------------------------------------------------------------------------
  1759. // Purpose: Scrolls the list according to the mouse wheel movement
  1760. //-----------------------------------------------------------------------------
  1761. void TextEntry::OnMouseWheeled(int delta)
  1762. {
  1763. if (_vertScrollBar)
  1764. {
  1765. MoveScrollBar(delta);
  1766. }
  1767. else
  1768. {
  1769. // if we don't use the input, chain back
  1770. BaseClass::OnMouseWheeled(delta);
  1771. }
  1772. }
  1773. //-----------------------------------------------------------------------------
  1774. // Purpose: Scrolls the list
  1775. // Input : delta - amount to move scrollbar up
  1776. //-----------------------------------------------------------------------------
  1777. void TextEntry::MoveScrollBar(int delta)
  1778. {
  1779. if (_vertScrollBar)
  1780. {
  1781. int val = _vertScrollBar->GetValue();
  1782. val -= (delta * 3);
  1783. _vertScrollBar->SetValue(val);
  1784. }
  1785. }
  1786. //-----------------------------------------------------------------------------
  1787. // Purpose: Called every frame the entry has keyboard focus;
  1788. // blinks the text cursor
  1789. //-----------------------------------------------------------------------------
  1790. void TextEntry::OnKeyFocusTicked()
  1791. {
  1792. int time=system()->GetTimeMillis();
  1793. if(time>_cursorNextBlinkTime)
  1794. {
  1795. _cursorBlink=!_cursorBlink;
  1796. _cursorNextBlinkTime=time+_cursorBlinkRate;
  1797. Repaint();
  1798. }
  1799. }
  1800. Panel *TextEntry::GetDragPanel()
  1801. {
  1802. if ( input()->IsMouseDown( MOUSE_LEFT ) )
  1803. {
  1804. int x, y;
  1805. input()->GetCursorPos(x, y);
  1806. ScreenToLocal(x, y);
  1807. int cursor = PixelToCursorSpace(x, y);
  1808. int cx0, cx1;
  1809. bool check = GetSelectedRange( cx0, cx1 );
  1810. if ( check && cursor >= cx0 && cursor < cx1 )
  1811. {
  1812. // Don't deselect in this case!!!
  1813. return BaseClass::GetDragPanel();
  1814. }
  1815. return NULL;
  1816. }
  1817. return BaseClass::GetDragPanel();
  1818. }
  1819. void TextEntry::OnCreateDragData( KeyValues *msg )
  1820. {
  1821. BaseClass::OnCreateDragData( msg );
  1822. char txt[ 256 ];
  1823. GetText( txt, sizeof( txt ) );
  1824. int r0, r1;
  1825. if ( GetSelectedRange( r0, r1 ) && r0 != r1 )
  1826. {
  1827. int len = r1 - r0;
  1828. if ( len > 0 && r0 < 1024 )
  1829. {
  1830. char selection[ 512 ];
  1831. Q_strncpy( selection, &txt[ r0 ], len + 1 );
  1832. selection[ len ] = 0;
  1833. msg->SetString( "text", selection );
  1834. }
  1835. }
  1836. }
  1837. //-----------------------------------------------------------------------------
  1838. // Purpose: Check if we are selecting text (so we can highlight it)
  1839. //-----------------------------------------------------------------------------
  1840. bool TextEntry::SelectCheck( bool fromMouse /*=false*/ )
  1841. {
  1842. bool bret = true;
  1843. if (!HasFocus() || !(input()->IsKeyDown(KEY_LSHIFT) || input()->IsKeyDown(KEY_RSHIFT)))
  1844. {
  1845. bool deselect = true;
  1846. int cx0, cx1;
  1847. if ( fromMouse &&
  1848. GetDragPanel() != NULL )
  1849. {
  1850. // move the cursor to where the mouse was pressed
  1851. int x, y;
  1852. input()->GetCursorPos(x, y);
  1853. ScreenToLocal(x, y);
  1854. int cursor = PixelToCursorSpace(x, y);
  1855. bool check = GetSelectedRange( cx0, cx1 );
  1856. if ( check && cursor >= cx0 && cursor < cx1 )
  1857. {
  1858. // Don't deselect in this case!!!
  1859. deselect = false;
  1860. bret = false;
  1861. }
  1862. }
  1863. if ( deselect )
  1864. {
  1865. _select[0] = -1;
  1866. }
  1867. }
  1868. else if (_select[0] == -1)
  1869. {
  1870. _select[0] = _cursorPos;
  1871. }
  1872. return bret;
  1873. }
  1874. //-----------------------------------------------------------------------------
  1875. // Purpose: set the maximum number of chars in the text buffer
  1876. //-----------------------------------------------------------------------------
  1877. void TextEntry::SetMaximumCharCount(int maxChars)
  1878. {
  1879. _maxCharCount = maxChars;
  1880. }
  1881. //-----------------------------------------------------------------------------
  1882. // Purpose: data accessor
  1883. //-----------------------------------------------------------------------------
  1884. int TextEntry::GetMaximumCharCount()
  1885. {
  1886. return _maxCharCount;
  1887. }
  1888. //-----------------------------------------------------------------------------
  1889. // Purpose: data accessor
  1890. //-----------------------------------------------------------------------------
  1891. void TextEntry::SetAutoProgressOnHittingCharLimit(bool state)
  1892. {
  1893. m_bAutoProgressOnHittingCharLimit = state;
  1894. }
  1895. //-----------------------------------------------------------------------------
  1896. // Purpose: set whether to wrap the text buffer
  1897. //-----------------------------------------------------------------------------
  1898. void TextEntry::SetWrap(bool wrap)
  1899. {
  1900. _wrap = wrap;
  1901. }
  1902. //-----------------------------------------------------------------------------
  1903. // Purpose: set whether to pass newline msgs to parent
  1904. //-----------------------------------------------------------------------------
  1905. void TextEntry::SendNewLine(bool send)
  1906. {
  1907. _sendNewLines = send;
  1908. }
  1909. //-----------------------------------------------------------------------------
  1910. // Purpose: Tell if an index is a linebreakindex
  1911. //-----------------------------------------------------------------------------
  1912. bool TextEntry::IsLineBreak(int index)
  1913. {
  1914. for (int i=0; i<m_LineBreaks.Count(); ++i)
  1915. {
  1916. if (index == m_LineBreaks[i])
  1917. return true;
  1918. }
  1919. return false;
  1920. }
  1921. //-----------------------------------------------------------------------------
  1922. // Purpose: Move the cursor one character to the left, scroll the text
  1923. // horizontally if needed
  1924. //-----------------------------------------------------------------------------
  1925. void TextEntry::GotoLeft()
  1926. {
  1927. SelectCheck();
  1928. // if we are on a line break just move the cursor to the prev line
  1929. if (IsLineBreak(_cursorPos))
  1930. {
  1931. // if we're already on the prev line at the end dont put it on the end
  1932. if (!_cursorIsAtEnd)
  1933. _putCursorAtEnd = true;
  1934. }
  1935. // if we are not at Start decrement cursor
  1936. if (!_putCursorAtEnd && _cursorPos > 0)
  1937. {
  1938. _cursorPos--;
  1939. }
  1940. ScrollLeft();
  1941. ResetCursorBlink();
  1942. Repaint();
  1943. }
  1944. //-----------------------------------------------------------------------------
  1945. // Purpose: Move the cursor one character to the right, scroll the text
  1946. // horizontally if needed
  1947. //-----------------------------------------------------------------------------
  1948. void TextEntry::GotoRight()
  1949. {
  1950. SelectCheck();
  1951. // if we are on a line break just move the cursor to the next line
  1952. if (IsLineBreak(_cursorPos))
  1953. {
  1954. if (_cursorIsAtEnd)
  1955. {
  1956. _putCursorAtEnd = false;
  1957. }
  1958. else
  1959. {
  1960. // if we are not at end increment cursor
  1961. if (_cursorPos < m_TextStream.Count())
  1962. {
  1963. _cursorPos++;
  1964. }
  1965. }
  1966. }
  1967. else
  1968. {
  1969. // if we are not at end increment cursor
  1970. if (_cursorPos < m_TextStream.Count())
  1971. {
  1972. _cursorPos++;
  1973. }
  1974. // if we are on a line break move the cursor to end of line
  1975. if (IsLineBreak(_cursorPos))
  1976. {
  1977. if (!_cursorIsAtEnd)
  1978. _putCursorAtEnd = true;
  1979. }
  1980. }
  1981. // scroll right if we need to
  1982. ScrollRight();
  1983. ResetCursorBlink();
  1984. Repaint();
  1985. }
  1986. //-----------------------------------------------------------------------------
  1987. // Purpose: Find out what line the cursor is on
  1988. //-----------------------------------------------------------------------------
  1989. int TextEntry::GetCursorLine()
  1990. {
  1991. // find which line the cursor is on
  1992. int cursorLine;
  1993. for (cursorLine = 0; cursorLine < m_LineBreaks.Count(); cursorLine++)
  1994. {
  1995. if (_cursorPos < m_LineBreaks[cursorLine])
  1996. break;
  1997. }
  1998. if (_putCursorAtEnd) // correct for when cursor is at end of line rather than Start of next
  1999. {
  2000. // we are not at end of buffer, in which case there is no next line to be at the Start of
  2001. if (_cursorPos != m_TextStream.Count() )
  2002. cursorLine--;
  2003. }
  2004. return cursorLine;
  2005. }
  2006. //-----------------------------------------------------------------------------
  2007. // Purpose: Move the cursor one line up
  2008. //-----------------------------------------------------------------------------
  2009. void TextEntry::GotoUp()
  2010. {
  2011. SelectCheck();
  2012. if (_cursorIsAtEnd)
  2013. {
  2014. if ( (GetCursorLine() - 1 ) == 0) // we are on first line
  2015. {
  2016. // stay at end of line
  2017. _putCursorAtEnd = true;
  2018. return; // dont move the cursor
  2019. }
  2020. else
  2021. _cursorPos--;
  2022. }
  2023. int cx, cy;
  2024. CursorToPixelSpace(_cursorPos, cx, cy);
  2025. // move the cursor to the previous line
  2026. MoveCursor(GetCursorLine() - 1, cx);
  2027. }
  2028. //-----------------------------------------------------------------------------
  2029. // Purpose: Move the cursor one line down
  2030. //-----------------------------------------------------------------------------
  2031. void TextEntry::GotoDown()
  2032. {
  2033. SelectCheck();
  2034. if (_cursorIsAtEnd)
  2035. {
  2036. _cursorPos--;
  2037. if (_cursorPos < 0)
  2038. _cursorPos = 0;
  2039. }
  2040. int cx, cy;
  2041. CursorToPixelSpace(_cursorPos, cx, cy);
  2042. // move the cursor to the next line
  2043. MoveCursor(GetCursorLine() + 1, cx);
  2044. if (!_putCursorAtEnd && _cursorIsAtEnd )
  2045. {
  2046. _cursorPos++;
  2047. if (_cursorPos > m_TextStream.Count())
  2048. {
  2049. _cursorPos = m_TextStream.Count();
  2050. }
  2051. }
  2052. LayoutVerticalScrollBarSlider();
  2053. }
  2054. //-----------------------------------------------------------------------------
  2055. // Purpose: Set the starting ypixel positon for a walk through the window
  2056. //-----------------------------------------------------------------------------
  2057. int TextEntry::GetYStart()
  2058. {
  2059. if (_multiline)
  2060. {
  2061. // just Start from the top
  2062. return DRAW_OFFSET_Y;
  2063. }
  2064. int fontTall = surface()->GetFontTall(_font);
  2065. return (GetTall() / 2) - (fontTall / 2);
  2066. }
  2067. //-----------------------------------------------------------------------------
  2068. // Purpose: Move the cursor to a line, need to know how many pixels are in a line
  2069. //-----------------------------------------------------------------------------
  2070. void TextEntry::MoveCursor(int line, int pixelsAcross)
  2071. {
  2072. // clamp to a valid line
  2073. if (line < 0)
  2074. line = 0;
  2075. if (line >= m_LineBreaks.Count())
  2076. line = m_LineBreaks.Count() -1;
  2077. // walk the whole text set looking for our place
  2078. // work out where to Start checking
  2079. int yStart = GetYStart();
  2080. int x = DRAW_OFFSET_X, y = yStart;
  2081. int lineBreakIndexIndex = 0;
  2082. _pixelsIndent = 0;
  2083. int i;
  2084. for ( i = 0; i < m_TextStream.Count(); i++)
  2085. {
  2086. wchar_t ch = m_TextStream[i];
  2087. if (_hideText)
  2088. {
  2089. ch = '*';
  2090. }
  2091. // if we've passed a line break go to that
  2092. if (m_LineBreaks[lineBreakIndexIndex] == i)
  2093. {
  2094. if (lineBreakIndexIndex == line)
  2095. {
  2096. _putCursorAtEnd = true;
  2097. _cursorPos = i;
  2098. break;
  2099. }
  2100. // add another line
  2101. AddAnotherLine(x,y);
  2102. lineBreakIndexIndex++;
  2103. }
  2104. // add to the current position
  2105. int charWidth = getCharWidth(_font, ch);
  2106. if (line == lineBreakIndexIndex)
  2107. {
  2108. // check to see if we're in range
  2109. if ((x + (charWidth / 2)) > pixelsAcross)
  2110. {
  2111. // found position
  2112. _cursorPos = i;
  2113. break;
  2114. }
  2115. }
  2116. x += charWidth;
  2117. }
  2118. // if we never find the cursor it must be past the end
  2119. // of the text buffer, to let's just slap it on the end of the text buffer then.
  2120. if (i == m_TextStream.Count())
  2121. {
  2122. GotoTextEnd();
  2123. }
  2124. LayoutVerticalScrollBarSlider();
  2125. ResetCursorBlink();
  2126. Repaint();
  2127. }
  2128. //-----------------------------------------------------------------------------
  2129. // Purpose: Turn horizontal scrolling on or off.
  2130. // Horizontal scrolling is disabled in multline windows.
  2131. // Toggling this will disable it in single line windows as well.
  2132. //-----------------------------------------------------------------------------
  2133. void TextEntry::SetHorizontalScrolling(bool status)
  2134. {
  2135. _horizScrollingAllowed = status;
  2136. }
  2137. //-----------------------------------------------------------------------------
  2138. // Purpose: Horizontal scrolling function, not used in multiline windows
  2139. // Function will scroll the buffer to the left if the cursor is not in the window
  2140. // scroll left if we need to
  2141. //-----------------------------------------------------------------------------
  2142. void TextEntry::ScrollLeft()
  2143. {
  2144. if (_multiline) // early out
  2145. {
  2146. return;
  2147. }
  2148. if (!_horizScrollingAllowed) //early out
  2149. {
  2150. return;
  2151. }
  2152. if(_cursorPos < _currentStartIndex) // scroll left if we need to
  2153. {
  2154. if (_cursorPos < 0)// dont scroll past the Start of buffer
  2155. {
  2156. _cursorPos=0;
  2157. }
  2158. _currentStartIndex = _cursorPos;
  2159. }
  2160. LayoutVerticalScrollBarSlider();
  2161. }
  2162. //-----------------------------------------------------------------------------
  2163. // Purpose:
  2164. //-----------------------------------------------------------------------------
  2165. void TextEntry::ScrollLeftForResize()
  2166. {
  2167. if (_multiline) // early out
  2168. {
  2169. return;
  2170. }
  2171. if (!_horizScrollingAllowed) //early out
  2172. {
  2173. return;
  2174. }
  2175. while (_currentStartIndex > 0) // go until we hit leftmost
  2176. {
  2177. _currentStartIndex--;
  2178. int nVal = _currentStartIndex;
  2179. // check if the cursor is now off the screen
  2180. if (IsCursorOffRightSideOfWindow(_cursorPos))
  2181. {
  2182. _currentStartIndex++; // we've gone too far, return it
  2183. break;
  2184. }
  2185. // IsCursorOffRightSideOfWindow actually fixes the _currentStartIndex,
  2186. // so if our value changed that menas we really are off the screen
  2187. if (nVal != _currentStartIndex)
  2188. break;
  2189. }
  2190. LayoutVerticalScrollBarSlider();
  2191. }
  2192. //-----------------------------------------------------------------------------
  2193. // Purpose: Horizontal scrolling function, not used in multiline windows
  2194. // Scroll one char right until the cursor is visible in the window.
  2195. // We do this one char at a time because char width isn't a constant.
  2196. //-----------------------------------------------------------------------------
  2197. void TextEntry::ScrollRight()
  2198. {
  2199. if (!_horizScrollingAllowed)
  2200. return;
  2201. if (_multiline)
  2202. {
  2203. }
  2204. // check if cursor is off the right side of window
  2205. else if (IsCursorOffRightSideOfWindow(_cursorPos))
  2206. {
  2207. _currentStartIndex++; //scroll over
  2208. ScrollRight(); // scroll again, check if cursor is in window yet
  2209. }
  2210. LayoutVerticalScrollBarSlider();
  2211. }
  2212. //-----------------------------------------------------------------------------
  2213. // Purpose: Check and see if cursor position is off the right side of the window
  2214. // just compare cursor's pixel coords with the window size coords.
  2215. // Input: an integer cursor Position, if you pass _cursorPos fxn will tell you
  2216. // if current cursor is outside window.
  2217. // Output: true: cursor is outside right edge or window
  2218. // false: cursor is inside right edge
  2219. //-----------------------------------------------------------------------------
  2220. bool TextEntry::IsCursorOffRightSideOfWindow(int cursorPos)
  2221. {
  2222. int cx, cy;
  2223. CursorToPixelSpace(cursorPos, cx, cy);
  2224. int wx=GetWide()-1; //width of inside of window is GetWide()-1
  2225. if ( wx <= 0 )
  2226. return false;
  2227. return (cx >= wx);
  2228. }
  2229. //-----------------------------------------------------------------------------
  2230. // Purpose: Check and see if cursor position is off the left side of the window
  2231. // just compare cursor's pixel coords with the window size coords.
  2232. // Input: an integer cursor Position, if you pass _cursorPos fxn will tell you
  2233. // if current cursor is outside window.
  2234. // Output: true - cursor is outside left edge or window
  2235. // false - cursor is inside left edge
  2236. //-----------------------------------------------------------------------------
  2237. bool TextEntry::IsCursorOffLeftSideOfWindow(int cursorPos)
  2238. {
  2239. int cx, cy;
  2240. CursorToPixelSpace(cursorPos, cx, cy);
  2241. return (cx <= 0);
  2242. }
  2243. //-----------------------------------------------------------------------------
  2244. // Purpose: Move the cursor over to the Start of the next word to the right
  2245. //-----------------------------------------------------------------------------
  2246. void TextEntry::GotoWordRight()
  2247. {
  2248. SelectCheck();
  2249. // search right until we hit a whitespace character or a newline
  2250. while (++_cursorPos < m_TextStream.Count())
  2251. {
  2252. if (iswspace(m_TextStream[_cursorPos]))
  2253. break;
  2254. }
  2255. // search right until we hit an nonspace character
  2256. while (++_cursorPos < m_TextStream.Count())
  2257. {
  2258. if (!iswspace(m_TextStream[_cursorPos]))
  2259. break;
  2260. }
  2261. if (_cursorPos > m_TextStream.Count())
  2262. _cursorPos = m_TextStream.Count();
  2263. // now we are at the start of the next word
  2264. // scroll right if we need to
  2265. ScrollRight();
  2266. LayoutVerticalScrollBarSlider();
  2267. ResetCursorBlink();
  2268. Repaint();
  2269. }
  2270. //-----------------------------------------------------------------------------
  2271. // Purpose: Move the cursor over to the Start of the next word to the left
  2272. //-----------------------------------------------------------------------------
  2273. void TextEntry::GotoWordLeft()
  2274. {
  2275. SelectCheck();
  2276. if (_cursorPos < 1)
  2277. return;
  2278. // search left until we hit an nonspace character
  2279. while (--_cursorPos >= 0)
  2280. {
  2281. if (!iswspace(m_TextStream[_cursorPos]))
  2282. break;
  2283. }
  2284. // search left until we hit a whitespace character
  2285. while (--_cursorPos >= 0)
  2286. {
  2287. if (iswspace(m_TextStream[_cursorPos]))
  2288. {
  2289. break;
  2290. }
  2291. }
  2292. // we end one character off
  2293. _cursorPos++;
  2294. // now we are at the Start of the previous word
  2295. // scroll left if we need to
  2296. ScrollLeft();
  2297. LayoutVerticalScrollBarSlider();
  2298. ResetCursorBlink();
  2299. Repaint();
  2300. }
  2301. //-----------------------------------------------------------------------------
  2302. // Purpose: Move cursor to the Start of the text buffer
  2303. //-----------------------------------------------------------------------------
  2304. void TextEntry::GotoTextStart()
  2305. {
  2306. SelectCheck();
  2307. _cursorPos = 0; // set cursor to Start
  2308. _putCursorAtEnd = false;
  2309. _currentStartIndex=0; // scroll over to Start
  2310. LayoutVerticalScrollBarSlider();
  2311. ResetCursorBlink();
  2312. Repaint();
  2313. }
  2314. //-----------------------------------------------------------------------------
  2315. // Purpose: Move cursor to the end of the text buffer
  2316. //-----------------------------------------------------------------------------
  2317. void TextEntry::GotoTextEnd()
  2318. {
  2319. SelectCheck();
  2320. _cursorPos=m_TextStream.Count(); // set cursor to end of buffer
  2321. _putCursorAtEnd = true; // move cursor Start of next line
  2322. ScrollRight(); // scroll over until cursor is on screen
  2323. LayoutVerticalScrollBarSlider();
  2324. ResetCursorBlink();
  2325. Repaint();
  2326. }
  2327. //-----------------------------------------------------------------------------
  2328. // Purpose: Move cursor to the Start of the current line
  2329. //-----------------------------------------------------------------------------
  2330. void TextEntry::GotoFirstOfLine()
  2331. {
  2332. SelectCheck();
  2333. // to get to the Start of the line you have to take into account line wrap
  2334. // we have to figure out at which point the line wraps
  2335. // given the current cursor position, select[1], find the index that is the
  2336. // line Start to the left of the cursor
  2337. //_cursorPos = 0; //TODO: this is wrong, should go to first non-whitespace first, then to zero
  2338. _cursorPos = GetCurrentLineStart();
  2339. _putCursorAtEnd = false;
  2340. _currentStartIndex=_cursorPos;
  2341. LayoutVerticalScrollBarSlider();
  2342. ResetCursorBlink();
  2343. Repaint();
  2344. }
  2345. //-----------------------------------------------------------------------------
  2346. // Purpose: Get the index of the first char on the current line
  2347. //-----------------------------------------------------------------------------
  2348. int TextEntry::GetCurrentLineStart()
  2349. {
  2350. if (!_multiline) // quick out for non multline buffers
  2351. return _currentStartIndex;
  2352. int i;
  2353. if (IsLineBreak(_cursorPos))
  2354. {
  2355. for (i = 0; i < m_LineBreaks.Count(); ++i )
  2356. {
  2357. if (_cursorPos == m_LineBreaks[i])
  2358. break;
  2359. }
  2360. if (_cursorIsAtEnd)
  2361. {
  2362. if (i > 0)
  2363. {
  2364. return m_LineBreaks[i-1];
  2365. }
  2366. return m_LineBreaks[0];
  2367. }
  2368. else
  2369. return _cursorPos; // we are already at Start
  2370. }
  2371. for ( i = 0; i < m_LineBreaks.Count(); ++i )
  2372. {
  2373. if (_cursorPos < m_LineBreaks[i])
  2374. {
  2375. if (i == 0)
  2376. return 0;
  2377. else
  2378. return m_LineBreaks[i-1];
  2379. }
  2380. }
  2381. // if there were no line breaks, the first char in the line is the Start of the buffer
  2382. return 0;
  2383. }
  2384. //-----------------------------------------------------------------------------
  2385. // Purpose: Move cursor to the end of the current line
  2386. //-----------------------------------------------------------------------------
  2387. void TextEntry::GotoEndOfLine()
  2388. {
  2389. SelectCheck();
  2390. // to get to the end of the line you have to take into account line wrap in the buffer
  2391. // we have to figure out at which point the line wraps
  2392. // given the current cursor position, select[1], find the index that is the
  2393. // line end to the right of the cursor
  2394. //_cursorPos=m_TextStream.Count(); //TODO: this is wrong, should go to last non-whitespace, then to true EOL
  2395. _cursorPos = GetCurrentLineEnd();
  2396. _putCursorAtEnd = true;
  2397. ScrollRight();
  2398. LayoutVerticalScrollBarSlider();
  2399. ResetCursorBlink();
  2400. Repaint();
  2401. }
  2402. //-----------------------------------------------------------------------------
  2403. // Purpose: Get the index of the last char on the current line
  2404. //-----------------------------------------------------------------------------
  2405. int TextEntry::GetCurrentLineEnd()
  2406. {
  2407. int i;
  2408. if (IsLineBreak(_cursorPos) )
  2409. {
  2410. for ( i = 0; i < m_LineBreaks.Count()-1; ++i )
  2411. {
  2412. if (_cursorPos == m_LineBreaks[i])
  2413. break;
  2414. }
  2415. if (!_cursorIsAtEnd)
  2416. {
  2417. if (i == m_LineBreaks.Count()-2 )
  2418. m_TextStream.Count();
  2419. else
  2420. return m_LineBreaks[i+1];
  2421. }
  2422. else
  2423. return _cursorPos; // we are already at end
  2424. }
  2425. for ( i = 0; i < m_LineBreaks.Count()-1; i++ )
  2426. {
  2427. if ( _cursorPos < m_LineBreaks[i])
  2428. {
  2429. return m_LineBreaks[i];
  2430. }
  2431. }
  2432. return m_TextStream.Count();
  2433. }
  2434. //-----------------------------------------------------------------------------
  2435. // Purpose: Insert a character into the text buffer
  2436. //-----------------------------------------------------------------------------
  2437. void TextEntry::InsertChar(wchar_t ch)
  2438. {
  2439. // throw away redundant linefeed characters
  2440. if (ch == '\r')
  2441. return;
  2442. // no newline characters in single-line dialogs
  2443. if (!_multiline && ch == '\n')
  2444. return;
  2445. // no tab characters
  2446. if (ch == '\t')
  2447. return;
  2448. if (m_bAllowNumericInputOnly)
  2449. {
  2450. if (!iswdigit(ch) && ((char)ch != '.'))
  2451. {
  2452. surface()->PlaySound("Resource\\warning.wav");
  2453. return;
  2454. }
  2455. }
  2456. // check against unicode characters
  2457. if (!m_bAllowNonAsciiCharacters)
  2458. {
  2459. if (ch > 127)
  2460. return;
  2461. }
  2462. // don't add characters if the max char count has been reached
  2463. // ding at the user
  2464. if (_maxCharCount > -1 && m_TextStream.Count() >= _maxCharCount)
  2465. {
  2466. if (_maxCharCount>0 && _multiline && _wrap)
  2467. {
  2468. // if we wrap lines rather than stopping
  2469. while (m_TextStream.Count() > _maxCharCount)
  2470. {
  2471. if (_recalculateBreaksIndex==0)
  2472. {
  2473. // we can get called before this has been run for the first time :)
  2474. RecalculateLineBreaks();
  2475. }
  2476. if (m_LineBreaks[0]> m_TextStream.Count())
  2477. {
  2478. // if the line break is the past the end of the buffer recalc
  2479. _recalculateBreaksIndex=-1;
  2480. RecalculateLineBreaks();
  2481. }
  2482. if (m_LineBreaks[0]+1 < m_TextStream.Count())
  2483. {
  2484. // delete the line
  2485. m_TextStream.RemoveMultiple(0, m_LineBreaks[0]);
  2486. // in case we just deleted text from where the cursor is
  2487. if (_cursorPos> m_TextStream.Count())
  2488. {
  2489. _cursorPos = m_TextStream.Count();
  2490. }
  2491. else
  2492. { // shift the cursor up. don't let it wander past zero
  2493. _cursorPos-=m_LineBreaks[0]+1;
  2494. if (_cursorPos<0)
  2495. {
  2496. _cursorPos=0;
  2497. }
  2498. }
  2499. // move any selection area up
  2500. if(_select[0]>-1)
  2501. {
  2502. _select[0] -=m_LineBreaks[0]+1;
  2503. if(_select[0] <=0)
  2504. {
  2505. _select[0] =-1;
  2506. }
  2507. _select[1] -=m_LineBreaks[0]+1;
  2508. if(_select[1] <=0)
  2509. {
  2510. _select[1] =-1;
  2511. }
  2512. }
  2513. // now redraw the buffer
  2514. for (int i = m_TextStream.Count() - 1; i >= 0; i--)
  2515. {
  2516. SetCharAt(m_TextStream[i], i+1);
  2517. }
  2518. // redo all the line breaks
  2519. _recalculateBreaksIndex=-1;
  2520. RecalculateLineBreaks();
  2521. }
  2522. }
  2523. }
  2524. else
  2525. {
  2526. // make a sound
  2527. // we've hit the max character limit
  2528. surface()->PlaySound("Resource\\warning.wav");
  2529. return;
  2530. }
  2531. }
  2532. if (_wrap)
  2533. {
  2534. // when wrapping you always insert the new char at the end of the buffer
  2535. SetCharAt(ch, m_TextStream.Count());
  2536. _cursorPos=m_TextStream.Count();
  2537. }
  2538. else
  2539. {
  2540. // move chars right 1 starting from cursor, then replace cursorPos with char and increment cursor
  2541. for (int i = m_TextStream.Count()- 1; i >= _cursorPos; i--)
  2542. {
  2543. SetCharAt(m_TextStream[i], i+1);
  2544. }
  2545. SetCharAt(ch, _cursorPos);
  2546. _cursorPos++;
  2547. }
  2548. // if its a newline char we can't do the slider until we recalc the line breaks
  2549. if (ch == '\n')
  2550. {
  2551. RecalculateLineBreaks();
  2552. }
  2553. // see if we've hit the char limit
  2554. if (m_bAutoProgressOnHittingCharLimit && m_TextStream.Count() == _maxCharCount)
  2555. {
  2556. // move the next panel (most likely another TextEntry)
  2557. RequestFocusNext();
  2558. }
  2559. // scroll right if this pushed the cursor off screen
  2560. ScrollRight();
  2561. _dataChanged = true;
  2562. CalcBreakIndex();
  2563. LayoutVerticalScrollBarSlider();
  2564. ResetCursorBlink();
  2565. Repaint();
  2566. }
  2567. //-----------------------------------------------------------------------------
  2568. // Purpose: Get the lineBreakIndex index of the line before the cursor
  2569. // note _recalculateBreaksIndex < 0 flags RecalculateLineBreaks
  2570. // to figure it all out from scratch
  2571. //-----------------------------------------------------------------------------
  2572. void TextEntry::CalcBreakIndex()
  2573. {
  2574. // an optimization to handle when the cursor is at the end of the buffer.
  2575. // pays off if the buffer is large, and the search loop would be long.
  2576. if (_cursorPos == m_TextStream.Count())
  2577. {
  2578. // we know m_LineBreaks array always has at least one element in it (99999 sentinel)
  2579. // when there is just one line this will make recalc = -1 which is ok.
  2580. _recalculateBreaksIndex = m_LineBreaks.Count()-2;
  2581. return;
  2582. }
  2583. _recalculateBreaksIndex=0;
  2584. // find the line break just before the cursor position
  2585. while (_cursorPos > m_LineBreaks[_recalculateBreaksIndex])
  2586. ++_recalculateBreaksIndex;
  2587. // -1 is ok.
  2588. --_recalculateBreaksIndex;
  2589. }
  2590. //-----------------------------------------------------------------------------
  2591. // Purpose: Insert a string into the text buffer, this is just a series
  2592. // of char inserts because we have to check each char is ok to insert
  2593. //-----------------------------------------------------------------------------
  2594. void TextEntry::InsertString(const wchar_t *wszText)
  2595. {
  2596. SaveUndoState();
  2597. for (const wchar_t *ch = wszText; *ch != 0; ++ch)
  2598. {
  2599. InsertChar(*ch);
  2600. }
  2601. if (_dataChanged)
  2602. {
  2603. FireActionSignal();
  2604. }
  2605. }
  2606. //-----------------------------------------------------------------------------
  2607. // Purpose: Converts an ansi string to unicode and inserts it into the text stream
  2608. //-----------------------------------------------------------------------------
  2609. void TextEntry::InsertString(const char *text)
  2610. {
  2611. // check for to see if the string is in the localization tables
  2612. if (text[0] == '#')
  2613. {
  2614. wchar_t *wsz = g_pVGuiLocalize->Find(text);
  2615. if (wsz)
  2616. {
  2617. InsertString(wsz);
  2618. return;
  2619. }
  2620. }
  2621. // straight convert the ansi to unicode and insert
  2622. wchar_t unicode[1024];
  2623. g_pVGuiLocalize->ConvertANSIToUnicode(text, unicode, sizeof(unicode));
  2624. InsertString(unicode);
  2625. }
  2626. //-----------------------------------------------------------------------------
  2627. // Purpose: Handle the effect of user hitting backspace key
  2628. // we delete the char before the cursor and reformat the text so it
  2629. // behaves like in windows.
  2630. //-----------------------------------------------------------------------------
  2631. void TextEntry::Backspace()
  2632. {
  2633. if (!IsEditable())
  2634. return;
  2635. //if you are at the first position don't do anything
  2636. if(_cursorPos==0)
  2637. {
  2638. return;
  2639. }
  2640. //if the line is empty, don't do anything
  2641. if(m_TextStream.Count()==0)
  2642. {
  2643. return;
  2644. }
  2645. SaveUndoState();
  2646. //shift chars left one, starting at the cursor position, then make the line one smaller
  2647. for(int i=_cursorPos;i<m_TextStream.Count(); ++i)
  2648. {
  2649. SetCharAt(m_TextStream[i],i-1);
  2650. }
  2651. m_TextStream.Remove(m_TextStream.Count() - 1);
  2652. // As we hit the Start of the window, expose more chars so we can see what we are deleting
  2653. if (_cursorPos==_currentStartIndex)
  2654. {
  2655. // windows tabs over 6 chars
  2656. if (_currentStartIndex-6 >= 0) // dont scroll if there are not enough chars to scroll
  2657. {
  2658. _currentStartIndex-=6;
  2659. }
  2660. else
  2661. _currentStartIndex=0;
  2662. }
  2663. //move the cursor left one
  2664. _cursorPos--;
  2665. _dataChanged = true;
  2666. // recalculate linebreaks (the fast incremental linebreak function doesn't work in this case)
  2667. _recalculateBreaksIndex = 0;
  2668. m_LineBreaks.RemoveAll();
  2669. m_LineBreaks.AddToTail(BUFFER_SIZE);
  2670. LayoutVerticalScrollBarSlider();
  2671. ResetCursorBlink();
  2672. Repaint();
  2673. }
  2674. //-----------------------------------------------------------------------------
  2675. // Purpose: Deletes the current selection, if any, moving the cursor to the Start
  2676. // of the selection
  2677. //-----------------------------------------------------------------------------
  2678. void TextEntry::DeleteSelected()
  2679. {
  2680. if (!IsEditable())
  2681. return;
  2682. // if the line is empty, don't do anything
  2683. if (m_TextStream.Count() == 0)
  2684. return;
  2685. // get the range to delete
  2686. int x0, x1;
  2687. if (!GetSelectedRange(x0, x1))
  2688. {
  2689. // no selection, don't touch anything
  2690. return;
  2691. }
  2692. SaveUndoState();
  2693. // shift chars left one starting after cursor position, then make the line one smaller
  2694. int dif = x1 - x0;
  2695. for (int i = 0; i < dif; ++i)
  2696. {
  2697. m_TextStream.Remove(x0);
  2698. }
  2699. // clear any selection
  2700. SelectNone();
  2701. ResetCursorBlink();
  2702. // move the cursor to just after the deleted section
  2703. _cursorPos = x0;
  2704. _dataChanged = true;
  2705. _recalculateBreaksIndex = 0;
  2706. m_LineBreaks.RemoveAll();
  2707. m_LineBreaks.AddToTail(BUFFER_SIZE);
  2708. CalcBreakIndex();
  2709. LayoutVerticalScrollBarSlider();
  2710. }
  2711. //-----------------------------------------------------------------------------
  2712. // Purpose: Handle the effect of the user hitting the delete key
  2713. // removes the char in front of the cursor
  2714. //-----------------------------------------------------------------------------
  2715. void TextEntry::Delete()
  2716. {
  2717. if (!IsEditable())
  2718. return;
  2719. // if the line is empty, don't do anything
  2720. if (m_TextStream.Count() == 0)
  2721. return;
  2722. // get the range to delete
  2723. int x0, x1;
  2724. if (!GetSelectedRange(x0, x1))
  2725. {
  2726. // no selection, so just delete the one character
  2727. x0 = _cursorPos;
  2728. x1 = x0 + 1;
  2729. // if we're at the end of the line don't do anything
  2730. if (_cursorPos >= m_TextStream.Count())
  2731. return;
  2732. }
  2733. SaveUndoState();
  2734. // shift chars left one starting after cursor position, then make the line one smaller
  2735. int dif = x1 - x0;
  2736. for (int i = 0; i < dif; i++)
  2737. {
  2738. m_TextStream.Remove((int)x0);
  2739. }
  2740. ResetCursorBlink();
  2741. // clear any selection
  2742. SelectNone();
  2743. // move the cursor to just after the deleted section
  2744. _cursorPos = x0;
  2745. _dataChanged = true;
  2746. _recalculateBreaksIndex = 0;
  2747. m_LineBreaks.RemoveAll();
  2748. m_LineBreaks.AddToTail(BUFFER_SIZE);
  2749. CalcBreakIndex();
  2750. LayoutVerticalScrollBarSlider();
  2751. }
  2752. //-----------------------------------------------------------------------------
  2753. // Purpose: Declare a selection empty
  2754. //-----------------------------------------------------------------------------
  2755. void TextEntry::SelectNone()
  2756. {
  2757. // tag the selection as empty
  2758. _select[0] = -1;
  2759. Repaint();
  2760. }
  2761. //-----------------------------------------------------------------------------
  2762. // Purpose: Load in the selection range so cx0 is the Start and cx1 is the end
  2763. // from smallest to highest (right to left)
  2764. //-----------------------------------------------------------------------------
  2765. bool TextEntry::GetSelectedRange(int& cx0,int& cx1)
  2766. {
  2767. // if there is nothing selected return false
  2768. if (_select[0] == -1)
  2769. {
  2770. return false;
  2771. }
  2772. // sort the two position so cx0 is the smallest
  2773. cx0=_select[0];
  2774. cx1=_select[1];
  2775. int temp;
  2776. if(cx1<cx0){temp=cx0;cx0=cx1;cx1=temp;}
  2777. return true;
  2778. }
  2779. //-----------------------------------------------------------------------------
  2780. // Purpose: Opens the cut/copy/paste dropdown menu
  2781. //-----------------------------------------------------------------------------
  2782. void TextEntry::OpenEditMenu()
  2783. {
  2784. // get cursor position, this is local to this text edit window
  2785. int cursorX, cursorY;
  2786. input()->GetCursorPos(cursorX, cursorY);
  2787. /* !! disabled since it recursively gets panel pointers, potentially across dll boundaries,
  2788. and doesn't need to be necessary (it's just for handling windowed mode)
  2789. // find the frame that has no parent (the one on the desktop)
  2790. Panel *panel = this;
  2791. while ( panel->GetParent() != NULL)
  2792. {
  2793. panel = panel->GetParent();
  2794. }
  2795. panel->ScreenToLocal(cursorX, cursorY);
  2796. int x, y;
  2797. // get base panel's postition
  2798. panel->GetPos(x, y);
  2799. // adjust our cursor position accordingly
  2800. cursorX += x;
  2801. cursorY += y;
  2802. */
  2803. int x0, x1;
  2804. if (GetSelectedRange(x0, x1)) // there is something selected
  2805. {
  2806. m_pEditMenu->SetItemEnabled("&Cut", true);
  2807. m_pEditMenu->SetItemEnabled("C&opy", true);
  2808. }
  2809. else // there is nothing selected, disable cut/copy options
  2810. {
  2811. m_pEditMenu->SetItemEnabled("&Cut", false);
  2812. m_pEditMenu->SetItemEnabled("C&opy", false);
  2813. }
  2814. m_pEditMenu->SetVisible(true);
  2815. m_pEditMenu->RequestFocus();
  2816. // relayout the menu immediately so that we know it's size
  2817. m_pEditMenu->InvalidateLayout(true);
  2818. int menuWide, menuTall;
  2819. m_pEditMenu->GetSize(menuWide, menuTall);
  2820. // work out where the cursor is and therefore the best place to put the menu
  2821. int wide, tall;
  2822. surface()->GetScreenSize(wide, tall);
  2823. if (wide - menuWide > cursorX)
  2824. {
  2825. // menu hanging right
  2826. if (tall - menuTall > cursorY)
  2827. {
  2828. // menu hanging down
  2829. m_pEditMenu->SetPos(cursorX, cursorY);
  2830. }
  2831. else
  2832. {
  2833. // menu hanging up
  2834. m_pEditMenu->SetPos(cursorX, cursorY - menuTall);
  2835. }
  2836. }
  2837. else
  2838. {
  2839. // menu hanging left
  2840. if (tall - menuTall > cursorY)
  2841. {
  2842. // menu hanging down
  2843. m_pEditMenu->SetPos(cursorX - menuWide, cursorY);
  2844. }
  2845. else
  2846. {
  2847. // menu hanging up
  2848. m_pEditMenu->SetPos(cursorX - menuWide, cursorY - menuTall);
  2849. }
  2850. }
  2851. m_pEditMenu->RequestFocus();
  2852. }
  2853. //-----------------------------------------------------------------------------
  2854. // Purpose: Cuts the selected chars from the buffer and
  2855. // copies them into the clipboard
  2856. //-----------------------------------------------------------------------------
  2857. void TextEntry::CutSelected()
  2858. {
  2859. CopySelected();
  2860. DeleteSelected();
  2861. // have to request focus if we used the menu
  2862. RequestFocus();
  2863. if ( _dataChanged )
  2864. {
  2865. FireActionSignal();
  2866. }
  2867. }
  2868. //-----------------------------------------------------------------------------
  2869. // Purpose: Copies the selected chars into the clipboard
  2870. //-----------------------------------------------------------------------------
  2871. void TextEntry::CopySelected()
  2872. {
  2873. if (_hideText)
  2874. return;
  2875. int x0, x1;
  2876. if (GetSelectedRange(x0, x1))
  2877. {
  2878. CUtlVector<wchar_t> buf;
  2879. for (int i = x0; i < x1; i++)
  2880. {
  2881. if ( m_TextStream[i]=='\n')
  2882. {
  2883. buf.AddToTail( '\r' );
  2884. }
  2885. buf.AddToTail(m_TextStream[i]);
  2886. }
  2887. buf.AddToTail('\0');
  2888. system()->SetClipboardText(buf.Base(), buf.Count());
  2889. }
  2890. // have to request focus if we used the menu
  2891. RequestFocus();
  2892. if ( _dataChanged )
  2893. {
  2894. FireActionSignal();
  2895. }
  2896. }
  2897. //-----------------------------------------------------------------------------
  2898. // Purpose: Pastes the selected chars from the clipboard into the text buffer
  2899. // truncates if text is longer than our _maxCharCount
  2900. //-----------------------------------------------------------------------------
  2901. void TextEntry::Paste()
  2902. {
  2903. if (!IsEditable())
  2904. return;
  2905. CUtlVector<wchar_t> buf;
  2906. int bufferSize = system()->GetClipboardTextCount();
  2907. if (!m_bAutoProgressOnHittingCharLimit)
  2908. {
  2909. bufferSize = _maxCharCount > 0 ? _maxCharCount + 1 : system()->GetClipboardTextCount(); // +1 for terminator
  2910. }
  2911. buf.AddMultipleToTail(bufferSize);
  2912. int len = system()->GetClipboardText(0, buf.Base(), bufferSize * sizeof(wchar_t));
  2913. if (len < 1)
  2914. return;
  2915. SaveUndoState();
  2916. bool bHaveMovedFocusAwayFromCurrentEntry = false;
  2917. // insert all the characters
  2918. for (int i = 0; i < len && buf[i] != 0; i++)
  2919. {
  2920. if (m_bAutoProgressOnHittingCharLimit)
  2921. {
  2922. // see if we're about to hit the char limit
  2923. if (m_TextStream.Count() == _maxCharCount)
  2924. {
  2925. // move the next panel (most likely another TextEntry)
  2926. RequestFocusNext();
  2927. // copy the remainder into the clipboard
  2928. wchar_t *remainingText = &buf[i];
  2929. system()->SetClipboardText(remainingText, len - i - 1);
  2930. // set the next entry to paste
  2931. if (GetVParent() && ipanel()->GetCurrentKeyFocus(GetVParent()) != GetVPanel())
  2932. {
  2933. bHaveMovedFocusAwayFromCurrentEntry = true;
  2934. ipanel()->SendMessage(ipanel()->GetCurrentKeyFocus(GetVParent()), new KeyValues("DoPaste"), GetVPanel());
  2935. }
  2936. break;
  2937. }
  2938. }
  2939. // insert the character
  2940. InsertChar(buf[i]);
  2941. }
  2942. // restore the original clipboard text if neccessary
  2943. if (m_bAutoProgressOnHittingCharLimit)
  2944. {
  2945. system()->SetClipboardText(buf.Base(), bufferSize);
  2946. }
  2947. _dataChanged = true;
  2948. FireActionSignal();
  2949. if (!bHaveMovedFocusAwayFromCurrentEntry)
  2950. {
  2951. // have to request focus if we used the menu
  2952. RequestFocus();
  2953. }
  2954. }
  2955. //-----------------------------------------------------------------------------
  2956. // Purpose: Reverts back to last saved changes
  2957. //-----------------------------------------------------------------------------
  2958. void TextEntry::Undo()
  2959. {
  2960. _cursorPos = _undoCursorPos;
  2961. m_TextStream.CopyArray(m_UndoTextStream.Base(), m_UndoTextStream.Count());
  2962. InvalidateLayout();
  2963. Repaint();
  2964. SelectNone();
  2965. }
  2966. //-----------------------------------------------------------------------------
  2967. // Purpose: Saves the current state to the undo stack
  2968. //-----------------------------------------------------------------------------
  2969. void TextEntry::SaveUndoState()
  2970. {
  2971. _undoCursorPos = _cursorPos;
  2972. m_UndoTextStream.CopyArray(m_TextStream.Base(), m_TextStream.Count());
  2973. }
  2974. //-----------------------------------------------------------------------------
  2975. // Purpose: Returns the index in the text buffer of the
  2976. // character the drawing should Start at
  2977. //-----------------------------------------------------------------------------
  2978. int TextEntry::GetStartDrawIndex(int &lineBreakIndexIndex)
  2979. {
  2980. int startIndex = 0;
  2981. int numLines = m_LineBreaks.Count();
  2982. int startLine = 0;
  2983. // determine the Start point from the scroll bar
  2984. // do this only if we are not selecting text in the window with the mouse
  2985. if (_vertScrollBar && !_mouseDragSelection)
  2986. {
  2987. // skip to line indicated by scrollbar
  2988. startLine = _vertScrollBar->GetValue();
  2989. }
  2990. else
  2991. {
  2992. // check to see if the cursor is off the screen-multiline case
  2993. HFont font = _font;
  2994. int displayLines = GetTall() / (surface()->GetFontTall(font) + DRAW_OFFSET_Y);
  2995. if (displayLines < 1)
  2996. {
  2997. displayLines = 1;
  2998. }
  2999. if (numLines > displayLines)
  3000. {
  3001. int cursorLine = GetCursorLine();
  3002. startLine = _currentStartLine;
  3003. // see if that is visible
  3004. if (cursorLine < _currentStartLine)
  3005. {
  3006. // cursor is above visible area; scroll back
  3007. startLine = cursorLine;
  3008. if (_vertScrollBar)
  3009. {
  3010. MoveScrollBar( 1 ); // should be calibrated for speed
  3011. // adjust startline incase we hit a limit
  3012. startLine = _vertScrollBar->GetValue();
  3013. }
  3014. }
  3015. else if (cursorLine > (_currentStartLine + displayLines - 1))
  3016. {
  3017. // cursor is down below visible area; scroll forward
  3018. startLine = cursorLine - displayLines + 1;
  3019. if (_vertScrollBar)
  3020. {
  3021. MoveScrollBar( -1 );
  3022. startLine = _vertScrollBar->GetValue();
  3023. }
  3024. }
  3025. }
  3026. else if (!_multiline)
  3027. {
  3028. // check to see if cursor is off the right side of screen-single line case
  3029. // get cursor's x coordinate in pixel space
  3030. bool done = false;
  3031. while ( !done )
  3032. {
  3033. done = true;
  3034. int x = DRAW_OFFSET_X;
  3035. for (int i = _currentStartIndex; i < m_TextStream.Count(); i++)
  3036. {
  3037. done = false;
  3038. wchar_t ch = m_TextStream[i];
  3039. if (_hideText)
  3040. {
  3041. ch = '*';
  3042. }
  3043. // if we've found the position, break
  3044. if (_cursorPos == i)
  3045. {
  3046. break;
  3047. }
  3048. // add to the current position
  3049. x += getCharWidth(font, ch);
  3050. }
  3051. if ( x >= GetWide() )
  3052. {
  3053. _currentStartIndex++;
  3054. // Keep searching...
  3055. continue;
  3056. }
  3057. if ( x <= 0 )
  3058. {
  3059. // dont go past the Start of buffer
  3060. if (_currentStartIndex > 0)
  3061. _currentStartIndex--;
  3062. }
  3063. break;
  3064. }
  3065. }
  3066. }
  3067. if (startLine > 0)
  3068. {
  3069. lineBreakIndexIndex = startLine;
  3070. if (startLine && startLine < m_LineBreaks.Count())
  3071. {
  3072. startIndex = m_LineBreaks[startLine - 1];
  3073. }
  3074. }
  3075. if (!_horizScrollingAllowed)
  3076. return 0;
  3077. _currentStartLine = startLine;
  3078. if (_multiline)
  3079. return startIndex;
  3080. else
  3081. return _currentStartIndex;
  3082. }
  3083. // helper accessors for common gets
  3084. float TextEntry::GetValueAsFloat()
  3085. {
  3086. int nTextLength = GetTextLength() + 1;
  3087. char* txt = ( char* )_alloca( nTextLength * sizeof( char ) );
  3088. GetText( txt, nTextLength );
  3089. return V_atof( txt );
  3090. }
  3091. int TextEntry::GetValueAsInt()
  3092. {
  3093. int nTextLength = GetTextLength() + 1;
  3094. char* txt = ( char* )_alloca( nTextLength * sizeof( char ) );
  3095. GetText( txt, nTextLength );
  3096. return V_atoi( txt );
  3097. }
  3098. //-----------------------------------------------------------------------------
  3099. // Purpose: Get a string from text buffer
  3100. // Input: offset - index to Start reading from
  3101. // bufLenInBytes - length of string
  3102. //-----------------------------------------------------------------------------
  3103. void TextEntry::GetText(OUT_Z_BYTECAP(bufLenInBytes) char *buf, int bufLenInBytes)
  3104. {
  3105. Assert(bufLenInBytes >= sizeof(buf[0]));
  3106. if (m_TextStream.Count())
  3107. {
  3108. // temporarily null terminate the text stream so we can use the conversion function
  3109. int nullTerminatorIndex = m_TextStream.AddToTail((wchar_t)0);
  3110. g_pVGuiLocalize->ConvertUnicodeToANSI(m_TextStream.Base(), buf, bufLenInBytes);
  3111. m_TextStream.FastRemove(nullTerminatorIndex);
  3112. }
  3113. else
  3114. {
  3115. // no characters in the stream
  3116. buf[0] = 0;
  3117. }
  3118. }
  3119. //-----------------------------------------------------------------------------
  3120. // Purpose: Get a string from text buffer
  3121. // Input: offset - index to Start reading from
  3122. // bufLen - length of string
  3123. //-----------------------------------------------------------------------------
  3124. void TextEntry::GetText(OUT_Z_BYTECAP(bufLenInBytes) wchar_t *wbuf, int bufLenInBytes)
  3125. {
  3126. Assert(bufLenInBytes >= sizeof(wbuf[0]));
  3127. int len = m_TextStream.Count();
  3128. if (m_TextStream.Count())
  3129. {
  3130. int terminator = min(len, (bufLenInBytes / (int)sizeof(wchar_t)) - 1);
  3131. wcsncpy(wbuf, m_TextStream.Base(), terminator);
  3132. wbuf[terminator] = 0;
  3133. }
  3134. else
  3135. {
  3136. wbuf[0] = 0;
  3137. }
  3138. }
  3139. void TextEntry::GetTextRange( wchar_t *buf, int from, int numchars )
  3140. {
  3141. int len = m_TextStream.Count();
  3142. int cpChars = max( 0, min( numchars, len - from ) );
  3143. wcsncpy( buf, m_TextStream.Base() + max( 0, min( len, from ) ), cpChars );
  3144. buf[ cpChars ] = 0;
  3145. }
  3146. void TextEntry::GetTextRange( char *buf, int from, int numchars )
  3147. {
  3148. int len = m_TextStream.Count();
  3149. int cpChars = max( 0, min( numchars, len - from ) );
  3150. g_pVGuiLocalize->ConvertUnicodeToANSI( m_TextStream.Base() + max( 0, min( len, from ) ), buf, cpChars + 1 );
  3151. buf[ cpChars ] = 0;
  3152. }
  3153. //-----------------------------------------------------------------------------
  3154. // Purpose: Sends a message that the text has changed
  3155. //-----------------------------------------------------------------------------
  3156. void TextEntry::FireActionSignal()
  3157. {
  3158. PostActionSignal(new KeyValues("TextChanged"));
  3159. _dataChanged = false; // reset the data changed flag
  3160. InvalidateLayout();
  3161. }
  3162. //-----------------------------------------------------------------------------
  3163. // Purpose: Set the font of the buffer text
  3164. // Input: font to change to
  3165. //-----------------------------------------------------------------------------
  3166. void TextEntry::SetFont(HFont font)
  3167. {
  3168. _font = font;
  3169. InvalidateLayout();
  3170. Repaint();
  3171. }
  3172. //-----------------------------------------------------------------------------
  3173. // Purpose: Called when the scrollbar slider is moved
  3174. //-----------------------------------------------------------------------------
  3175. void TextEntry::OnSliderMoved()
  3176. {
  3177. Repaint();
  3178. }
  3179. //-----------------------------------------------------------------------------
  3180. // Purpose:
  3181. //-----------------------------------------------------------------------------
  3182. bool TextEntry::RequestInfo(KeyValues *outputData)
  3183. {
  3184. if (!stricmp(outputData->GetName(), "GetText"))
  3185. {
  3186. wchar_t wbuf[256];
  3187. GetText(wbuf, 255);
  3188. outputData->SetWString("text", wbuf);
  3189. return true;
  3190. }
  3191. else if (!stricmp(outputData->GetName(), "GetState"))
  3192. {
  3193. char buf[64];
  3194. GetText(buf, sizeof(buf));
  3195. outputData->SetInt("state", atoi(buf));
  3196. return true;
  3197. }
  3198. return BaseClass::RequestInfo(outputData);
  3199. }
  3200. //-----------------------------------------------------------------------------
  3201. // Purpose:
  3202. //-----------------------------------------------------------------------------
  3203. void TextEntry::OnSetText(const wchar_t *text)
  3204. {
  3205. SetText(text);
  3206. }
  3207. //-----------------------------------------------------------------------------
  3208. // Purpose: as above, but sets an integer
  3209. //-----------------------------------------------------------------------------
  3210. void TextEntry::OnSetState(int state)
  3211. {
  3212. char buf[64];
  3213. Q_snprintf(buf, sizeof(buf), "%d", state);
  3214. SetText(buf);
  3215. }
  3216. //-----------------------------------------------------------------------------
  3217. // Purpose:
  3218. //-----------------------------------------------------------------------------
  3219. void TextEntry::ApplySettings( KeyValues *inResourceData )
  3220. {
  3221. BaseClass::ApplySettings( inResourceData );
  3222. _font = scheme()->GetIScheme( GetScheme() )->GetFont( inResourceData->GetString( "font", "Default" ), IsProportional() );
  3223. SetFont( _font );
  3224. SetTextHidden((bool)inResourceData->GetInt("textHidden", 0));
  3225. SetEditable((bool)inResourceData->GetInt("editable", 1));
  3226. SetMaximumCharCount(inResourceData->GetInt("maxchars", -1));
  3227. SetAllowNumericInputOnly(inResourceData->GetInt("NumericInputOnly", 0));
  3228. SetAllowNonAsciiCharacters(inResourceData->GetInt("unicode", 0));
  3229. SelectAllOnFirstFocus(inResourceData->GetInt("selectallonfirstfocus", 0));
  3230. }
  3231. //-----------------------------------------------------------------------------
  3232. // Purpose:
  3233. //-----------------------------------------------------------------------------
  3234. void TextEntry::GetSettings( KeyValues *outResourceData )
  3235. {
  3236. BaseClass::GetSettings( outResourceData );
  3237. outResourceData->SetInt("textHidden", _hideText);
  3238. outResourceData->SetInt("editable", IsEditable());
  3239. outResourceData->SetInt("maxchars", GetMaximumCharCount());
  3240. outResourceData->SetInt("NumericInputOnly", m_bAllowNumericInputOnly);
  3241. outResourceData->SetInt("unicode", m_bAllowNonAsciiCharacters);
  3242. }
  3243. //-----------------------------------------------------------------------------
  3244. // Purpose:
  3245. //-----------------------------------------------------------------------------
  3246. const char *TextEntry::GetDescription()
  3247. {
  3248. static char buf[1024];
  3249. Q_snprintf(buf, sizeof(buf), "%s, bool textHidden, bool editable, bool unicode, bool NumericInputOnly, int maxchars", BaseClass::GetDescription());
  3250. return buf;
  3251. }
  3252. //-----------------------------------------------------------------------------
  3253. // Purpose: Get the number of lines in the window
  3254. //-----------------------------------------------------------------------------
  3255. int TextEntry::GetNumLines()
  3256. {
  3257. return m_LineBreaks.Count();
  3258. }
  3259. //-----------------------------------------------------------------------------
  3260. // Purpose: Sets the height of the text entry window so all text will fit inside
  3261. //-----------------------------------------------------------------------------
  3262. void TextEntry::SetToFullHeight()
  3263. {
  3264. PerformLayout();
  3265. int wide, tall;
  3266. GetSize(wide, tall);
  3267. tall = GetNumLines() * (surface()->GetFontTall(_font) + DRAW_OFFSET_Y) + DRAW_OFFSET_Y + 2;
  3268. SetSize (wide, tall);
  3269. PerformLayout();
  3270. }
  3271. //-----------------------------------------------------------------------------
  3272. // Purpose: Select all the text.
  3273. //-----------------------------------------------------------------------------
  3274. void TextEntry::SelectAllText( bool bResetCursorPos )
  3275. {
  3276. // if there's no text at all, select none
  3277. if ( m_TextStream.Count() == 0 )
  3278. {
  3279. _select[0] = -1;
  3280. }
  3281. else
  3282. {
  3283. _select[0] = 0;
  3284. }
  3285. _select[1] = m_TextStream.Count();
  3286. if ( bResetCursorPos )
  3287. {
  3288. _cursorPos = _select[1];
  3289. }
  3290. }
  3291. //-----------------------------------------------------------------------------
  3292. // Purpose: Select no text.
  3293. //-----------------------------------------------------------------------------
  3294. void TextEntry::SelectNoText()
  3295. {
  3296. _select[0] = -1;
  3297. _select[1] = 0;
  3298. }
  3299. //-----------------------------------------------------------------------------
  3300. // Purpose: Sets the width of the text entry window so all text will fit inside
  3301. //-----------------------------------------------------------------------------
  3302. void TextEntry::SetToFullWidth()
  3303. {
  3304. // probably be problems if you try using this on multi line buffers
  3305. // or buffers with clickable text in them.
  3306. if (_multiline)
  3307. return;
  3308. PerformLayout();
  3309. int wide = 2*DRAW_OFFSET_X; // buffer on left and right end of text.
  3310. // loop through all the characters and sum their widths
  3311. for (int i = 0; i < m_TextStream.Count(); ++i)
  3312. {
  3313. wide += getCharWidth(_font, m_TextStream[i]);
  3314. }
  3315. // height of one line of text
  3316. int tall = (surface()->GetFontTall(_font) + DRAW_OFFSET_Y) + DRAW_OFFSET_Y + 2;
  3317. SetSize (wide, tall);
  3318. PerformLayout();
  3319. }
  3320. //-----------------------------------------------------------------------------
  3321. // Purpose:
  3322. //-----------------------------------------------------------------------------
  3323. void TextEntry::SelectAllOnFirstFocus( bool status )
  3324. {
  3325. _selectAllOnFirstFocus = status;
  3326. }
  3327. void TextEntry::SelectAllOnFocusAlways( bool status )
  3328. {
  3329. _selectAllOnFirstFocus = status;
  3330. _selectAllOnFocusAlways = status;
  3331. }
  3332. //-----------------------------------------------------------------------------
  3333. // Purpose: called when the text entry receives focus
  3334. //-----------------------------------------------------------------------------
  3335. void TextEntry::OnSetFocus()
  3336. {
  3337. // see if we should highlight all on selection
  3338. if (_selectAllOnFirstFocus)
  3339. {
  3340. _select[1] = m_TextStream.Count();
  3341. _select[0] = _select[1] > 0 ? 0 : -1;
  3342. _cursorPos = _select[1]; // cursor at end of line
  3343. if ( !_selectAllOnFocusAlways )
  3344. {
  3345. _selectAllOnFirstFocus = false;
  3346. }
  3347. }
  3348. else if (input()->IsKeyDown(KEY_TAB) || input()->WasKeyReleased(KEY_TAB))
  3349. {
  3350. // if we've tabbed to this field then move to the end of the text
  3351. GotoTextEnd();
  3352. // clear any selection
  3353. SelectNone();
  3354. }
  3355. BaseClass::OnSetFocus();
  3356. }
  3357. //-----------------------------------------------------------------------------
  3358. // Purpose: Set the width we have to draw text in.
  3359. // Do not use in multiline windows.
  3360. //-----------------------------------------------------------------------------
  3361. void TextEntry::SetDrawWidth(int width)
  3362. {
  3363. _drawWidth = width;
  3364. }
  3365. //-----------------------------------------------------------------------------
  3366. // Purpose: Get the width we have to draw text in.
  3367. //-----------------------------------------------------------------------------
  3368. int TextEntry::GetDrawWidth()
  3369. {
  3370. return _drawWidth;
  3371. }
  3372. //-----------------------------------------------------------------------------
  3373. // Purpose: data accessor
  3374. //-----------------------------------------------------------------------------
  3375. void TextEntry::SetAllowNonAsciiCharacters(bool state)
  3376. {
  3377. m_bAllowNonAsciiCharacters = state;
  3378. }
  3379. //-----------------------------------------------------------------------------
  3380. // Purpose: data accessor
  3381. //-----------------------------------------------------------------------------
  3382. void TextEntry::SetAllowNumericInputOnly(bool state)
  3383. {
  3384. m_bAllowNumericInputOnly = state;
  3385. }
  3386. //-----------------------------------------------------------------------------
  3387. // Purpose:
  3388. // Input : forward -
  3389. //-----------------------------------------------------------------------------
  3390. void TextEntry::OnChangeIME( bool forward )
  3391. {
  3392. // Only change ime if Unicode aware
  3393. if ( m_bAllowNonAsciiCharacters )
  3394. {
  3395. input()->OnChangeIME( forward );
  3396. }
  3397. }
  3398. //-----------------------------------------------------------------------------
  3399. // Purpose:
  3400. // Input : handleValue -
  3401. //-----------------------------------------------------------------------------
  3402. void TextEntry::LanguageChanged( int handleValue )
  3403. {
  3404. input()->OnChangeIMEByHandle( handleValue );
  3405. }
  3406. //-----------------------------------------------------------------------------
  3407. // Purpose:
  3408. // Input : handleValue -
  3409. //-----------------------------------------------------------------------------
  3410. void TextEntry::ConversionModeChanged( int handleValue )
  3411. {
  3412. input()->OnChangeIMEConversionModeByHandle( handleValue );
  3413. }
  3414. //-----------------------------------------------------------------------------
  3415. // Purpose:
  3416. // Input : handleValue -
  3417. //-----------------------------------------------------------------------------
  3418. void TextEntry::SentenceModeChanged( int handleValue )
  3419. {
  3420. input()->OnChangeIMESentenceModeByHandle( handleValue );
  3421. }
  3422. //-----------------------------------------------------------------------------
  3423. // Purpose:
  3424. // Input : *compstr -
  3425. //-----------------------------------------------------------------------------
  3426. void TextEntry::CompositionString( const wchar_t *compstr )
  3427. {
  3428. wcsncpy( m_szComposition, compstr, sizeof( m_szComposition ) / sizeof( wchar_t ) - 1 );
  3429. m_szComposition[ sizeof( m_szComposition ) / sizeof( wchar_t ) - 1 ] = L'\0';
  3430. }
  3431. void TextEntry::ShowIMECandidates()
  3432. {
  3433. HideIMECandidates();
  3434. int c = input()->GetCandidateListCount();
  3435. if ( c == 0 )
  3436. {
  3437. return;
  3438. }
  3439. m_pIMECandidates = new Menu( this, "IMECandidatesMenu" );
  3440. int pageStart = input()->GetCandidateListPageStart();
  3441. int pageSize = input()->GetCandidateListPageSize();
  3442. int selected = input()->GetCandidateListSelectedItem();
  3443. int startAtOne = input()->CandidateListStartsAtOne() ? 1 : 0;
  3444. if ( ( selected < pageStart ) || ( selected >= pageStart + pageSize ) )
  3445. {
  3446. pageStart = ( selected / pageSize ) * pageSize;
  3447. input()->SetCandidateListPageStart( pageStart );
  3448. }
  3449. for ( int i = pageStart; i < pageStart + pageSize; ++i )
  3450. {
  3451. if ( i >= c )
  3452. continue;
  3453. bool isSelected = ( i == selected ) ? true : false;
  3454. wchar_t unicode[ 32 ];
  3455. input()->GetCandidate( i, unicode, sizeof( unicode ) );
  3456. wchar_t label[ 64 ];
  3457. _snwprintf( label, sizeof( label ) / sizeof( wchar_t ) - 1, L"%i %s", i - pageStart + startAtOne, unicode );
  3458. label[ sizeof( label ) / sizeof( wchar_t ) - 1 ] = L'\0';
  3459. int id = m_pIMECandidates->AddMenuItem( "Candidate", label, (KeyValues *)NULL, this );
  3460. if ( isSelected )
  3461. {
  3462. m_pIMECandidates->SetCurrentlyHighlightedItem( id );
  3463. }
  3464. }
  3465. m_pIMECandidates->SetVisible(true);
  3466. m_pIMECandidates->SetParent(this);
  3467. m_pIMECandidates->AddActionSignalTarget(this);
  3468. m_pIMECandidates->SetKeyBoardInputEnabled( false );
  3469. int cx, cy;
  3470. CursorToPixelSpace(_cursorPos, cx, cy);
  3471. cy = GetTall();
  3472. LocalToScreen( cx, cy );
  3473. //m_pIMECandidates->SetPos( cx, cy );
  3474. // relayout the menu immediately so that we know it's size
  3475. m_pIMECandidates->InvalidateLayout(true);
  3476. int menuWide, menuTall;
  3477. m_pIMECandidates->GetSize(menuWide, menuTall);
  3478. // work out where the cursor is and therefore the best place to put the menu
  3479. int wide, tall;
  3480. surface()->GetScreenSize(wide, tall);
  3481. if (wide - menuWide > cx)
  3482. {
  3483. // menu hanging right
  3484. if (tall - menuTall > cy)
  3485. {
  3486. // menu hanging down
  3487. m_pIMECandidates->SetPos(cx, cy);
  3488. }
  3489. else
  3490. {
  3491. // menu hanging up
  3492. m_pIMECandidates->SetPos(cx, cy - menuTall - GetTall());
  3493. }
  3494. }
  3495. else
  3496. {
  3497. // menu hanging left
  3498. if (tall - menuTall > cy)
  3499. {
  3500. // menu hanging down
  3501. m_pIMECandidates->SetPos(cx - menuWide, cy);
  3502. }
  3503. else
  3504. {
  3505. // menu hanging up
  3506. m_pIMECandidates->SetPos(cx - menuWide, cy - menuTall-GetTall());
  3507. }
  3508. }
  3509. }
  3510. void TextEntry::HideIMECandidates()
  3511. {
  3512. if ( m_pIMECandidates )
  3513. {
  3514. m_pIMECandidates->SetVisible( false );
  3515. }
  3516. delete m_pIMECandidates;
  3517. m_pIMECandidates = NULL;
  3518. }
  3519. void TextEntry::UpdateIMECandidates()
  3520. {
  3521. if ( !m_pIMECandidates )
  3522. return;
  3523. int c = input()->GetCandidateListCount();
  3524. if ( c == 0 )
  3525. {
  3526. HideIMECandidates();
  3527. return;
  3528. }
  3529. int oldCount = m_pIMECandidates->GetItemCount();
  3530. int newCount = input()->GetCandidateListPageSize();
  3531. if ( oldCount != newCount )
  3532. {
  3533. // Recreate the entire menu
  3534. ShowIMECandidates();
  3535. return;
  3536. }
  3537. int pageSize = input()->GetCandidateListPageSize();
  3538. int selected = input()->GetCandidateListSelectedItem();
  3539. int pageStart = input()->GetCandidateListPageStart();
  3540. if ( ( selected < pageStart ) || selected >= pageStart + pageSize )
  3541. {
  3542. pageStart = ( selected / pageSize ) * pageSize;
  3543. input()->SetCandidateListPageStart( pageStart );
  3544. }
  3545. int startAtOne = input()->CandidateListStartsAtOne() ? 1 : 0;
  3546. for ( int i = pageStart; i < pageStart + pageSize; ++i )
  3547. {
  3548. int id = m_pIMECandidates->GetMenuID( i - pageStart );
  3549. MenuItem *item = m_pIMECandidates->GetMenuItem( id );
  3550. if ( !item )
  3551. continue;
  3552. if ( i >= c )
  3553. {
  3554. item->SetVisible( false );
  3555. continue;
  3556. }
  3557. else
  3558. {
  3559. item->SetVisible( true );
  3560. }
  3561. bool isSelected = ( i == selected ) ? true : false;
  3562. wchar_t unicode[ 32 ];
  3563. input()->GetCandidate( i, unicode, sizeof( unicode ) );
  3564. wchar_t label[ 64 ];
  3565. _snwprintf( label, sizeof( label ) / sizeof( wchar_t ) - 1, L"%i %s", i - pageStart + startAtOne, unicode );
  3566. label[ sizeof( label ) / sizeof( wchar_t ) - 1 ] = L'\0';
  3567. item->SetText( label );
  3568. if ( isSelected )
  3569. {
  3570. m_pIMECandidates->SetCurrentlyHighlightedItem( id );
  3571. }
  3572. }
  3573. }
  3574. //-----------------------------------------------------------------------------
  3575. // Purpose:
  3576. //-----------------------------------------------------------------------------
  3577. void TextEntry::FlipToLastIME()
  3578. {
  3579. int hCurrentIME = input()->GetCurrentIMEHandle();
  3580. int hEnglishIME = input()->GetEnglishIMEHandle();
  3581. bool isEnglish = ( hCurrentIME == hEnglishIME ) ? true : false;
  3582. // If in english, flip back to previous
  3583. if ( isEnglish )
  3584. {
  3585. input()->OnChangeIMEByHandle( m_hPreviousIME );
  3586. }
  3587. else
  3588. {
  3589. // If not, remember language and flip to english...
  3590. m_hPreviousIME = hCurrentIME;
  3591. input()->OnChangeIMEByHandle( hEnglishIME );
  3592. }
  3593. }
  3594. void TextEntry::SetDrawLanguageIDAtLeft( bool state )
  3595. {
  3596. m_bDrawLanguageIDAtLeft = state;
  3597. }
  3598. bool TextEntry::GetDropContextMenu( Menu *menu, CUtlVector< KeyValues * >& msglist )
  3599. {
  3600. menu->AddMenuItem( "replace", "#TextEntry_ReplaceText", "replace", this );
  3601. menu->AddMenuItem( "append", "#TextEntry_AppendText", "append", this );
  3602. menu->AddMenuItem( "prepend", "#TextEntry_PrependText", "prepend", this );
  3603. return true;
  3604. }
  3605. bool TextEntry::IsDroppable( CUtlVector< KeyValues * >& msglist )
  3606. {
  3607. if ( msglist.Count() != 1 )
  3608. return false;
  3609. if ( !IsEnabled() )
  3610. return false;
  3611. KeyValues *msg = msglist[ 0 ];
  3612. const wchar_t *txt = msg->GetWString( "text", L"" );
  3613. if ( !txt || txt[ 0 ] == L'\0' )
  3614. return false;
  3615. return true;
  3616. }
  3617. void TextEntry::OnPanelDropped( CUtlVector< KeyValues * >& msglist )
  3618. {
  3619. if ( msglist.Count() != 1 )
  3620. return;
  3621. KeyValues *data = msglist[ 0 ];
  3622. const wchar_t *newText = data->GetWString( "text" );
  3623. if ( !newText || newText[ 0 ] == L'\0' )
  3624. return;
  3625. char const *cmd = data->GetString( "command" );
  3626. if ( !Q_stricmp( cmd, "replace" ) ||
  3627. !Q_stricmp( cmd, "default" ) )
  3628. {
  3629. SetText( newText );
  3630. _dataChanged = true;
  3631. FireActionSignal();
  3632. }
  3633. else if ( !Q_stricmp( cmd, "append" ) )
  3634. {
  3635. int newLen = wcslen( newText );
  3636. int curLen = m_TextStream.Count();
  3637. size_t outsize = sizeof( wchar_t ) * ( newLen + curLen + 1 );
  3638. wchar_t *out = (wchar_t *)_alloca( outsize );
  3639. Q_memset( out, 0, outsize );
  3640. wcsncpy( out, m_TextStream.Base(), curLen );
  3641. wcsncat( out, newText, wcslen( newText ) );
  3642. out[ newLen + curLen ] = L'\0';
  3643. SetText( out );
  3644. _dataChanged = true;
  3645. FireActionSignal();
  3646. }
  3647. else if ( !Q_stricmp( cmd, "prepend" ) )
  3648. {
  3649. int newLen = wcslen( newText );
  3650. int curLen = m_TextStream.Count();
  3651. size_t outsize = sizeof( wchar_t ) * ( newLen + curLen + 1 );
  3652. wchar_t *out = (wchar_t *)_alloca( outsize );
  3653. Q_memset( out, 0, outsize );
  3654. wcsncpy( out, newText, wcslen( newText ) );
  3655. wcsncat( out, m_TextStream.Base(), curLen );
  3656. out[ newLen + curLen ] = L'\0';
  3657. SetText( out );
  3658. _dataChanged = true;
  3659. FireActionSignal();
  3660. }
  3661. }
  3662. int TextEntry::GetTextLength() const
  3663. {
  3664. return m_TextStream.Count();
  3665. }
  3666. bool TextEntry::IsTextFullySelected() const
  3667. {
  3668. if ( _select[ 0 ] != 0 )
  3669. return false;
  3670. if ( _select[ 1 ] != GetTextLength() )
  3671. return false;
  3672. return true;
  3673. }
  3674. void TextEntry::SetUseFallbackFont( bool bState, HFont hFallback )
  3675. {
  3676. m_bUseFallbackFont = bState;
  3677. m_hFallbackFont = hFallback;
  3678. }