Counter Strike : Global Offensive Source Code
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.

4282 lines
107 KiB

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