guiTextEditCtrl.cc 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "console/consoleTypes.h"
  23. #include "console/console.h"
  24. #include "graphics/gColor.h"
  25. #include "graphics/dgl.h"
  26. #include "gui/guiCanvas.h"
  27. #include "gui/guiTextEditCtrl.h"
  28. #include "gui/guiDefaultControlRender.h"
  29. #include "memory/frameAllocator.h"
  30. #include "string/unicode.h"
  31. #include <vector>
  32. #include <string>
  33. #include "guiTextEditCtrl_ScriptBinding.h"
  34. #pragma region GuiTextEditTextBlock
  35. GuiTextEditTextBlock::GuiTextEditTextBlock()
  36. {
  37. mGlobalBounds.set(0, 0, 0, 0);
  38. mTextOffsetX = 0;
  39. mTextScrollX = 0;
  40. mText = string();
  41. mLineStartIbeamValue = 0;
  42. }
  43. void GuiTextEditTextBlock::render(const RectI& bounds, string line, U32 ibeamStartValue, GuiControlProfile* profile, GuiControlState currentState, GuiTextEditSelection& selector, AlignmentType align, GFont* font, bool overrideFontColor)
  44. {
  45. mGlobalBounds.set(bounds.point, bounds.extent);
  46. mText.assign(line);
  47. mLineStartIbeamValue = ibeamStartValue;
  48. RectI clipRect = dglGetClipRect();
  49. if (mGlobalBounds.overlaps(clipRect))
  50. {
  51. const U32 selStart = selector.getSelStart();
  52. const U32 selEnd = selector.getSelEnd();
  53. U32 lengthOfPreBlockText = mClamp(selStart - mLineStartIbeamValue, 0, line.length());
  54. U32 lengthOfPostBlockText = mClamp(line.length() - (selEnd - mLineStartIbeamValue), 0, line.length());
  55. U32 lengthOfHighlightBlockText = mClamp(line.length() - (lengthOfPreBlockText + lengthOfPostBlockText), 0, line.length());
  56. processTextAlignment(line, font, align);
  57. Point2I movingStartPoint = getGlobalTextStart();
  58. movingStartPoint.x += renderTextSection(movingStartPoint, 0, lengthOfPreBlockText, profile, currentState, font, false, overrideFontColor);
  59. movingStartPoint.x += renderTextSection(movingStartPoint, lengthOfPreBlockText, lengthOfHighlightBlockText, profile, currentState, font, true, overrideFontColor);
  60. movingStartPoint.x += renderTextSection(movingStartPoint, lengthOfPreBlockText + lengthOfHighlightBlockText, lengthOfPostBlockText, profile, currentState, font, false, overrideFontColor);
  61. }
  62. Point2I textStartPoint = getGlobalTextStart();
  63. if (selector.renderIbeam(textStartPoint, mGlobalBounds.extent, line, mLineStartIbeamValue, mLineStartIbeamValue + line.length(), profile, font))
  64. {
  65. Point2I cursorCenter = selector.getCursorCenter();
  66. performScrollJumpX(cursorCenter.x, clipRect.point.x, clipRect.point.x + clipRect.extent.x);
  67. }
  68. }
  69. U32 GuiTextEditTextBlock::renderTextSection(const Point2I& startPoint, const U32 subStrStart, const U32 subStrLen, GuiControlProfile* profile, const GuiControlState currentState, GFont* font, bool isSelectedText, bool overrideFontColor)
  70. {
  71. if (subStrLen != 0)
  72. {
  73. string sectionText = mText.substr(subStrStart, subStrLen);
  74. U32 blockStrWidth = font->getStrWidth(sectionText.c_str());
  75. Point2I pointToDraw = Point2I(startPoint.x, startPoint.y);
  76. if (isSelectedText)
  77. {
  78. if (!overrideFontColor)
  79. {
  80. dglSetBitmapModulation(profile->mFontColorTextSL);
  81. }
  82. RectI highlightRect = RectI(pointToDraw.x, pointToDraw.y, blockStrWidth, mGlobalBounds.extent.y);
  83. dglDrawRectFill(highlightRect, profile->mFillColorTextSL);
  84. }
  85. else if(!overrideFontColor)
  86. {
  87. const ColorI& fontColor = profile->getFontColor(currentState);
  88. dglSetBitmapModulation(fontColor);
  89. }
  90. dglDrawText(font, pointToDraw, sectionText.c_str(), profile->mFontColors);
  91. return blockStrWidth;
  92. }
  93. return 0;
  94. }
  95. void GuiTextEditTextBlock::performScrollJumpX(const S32 targetX, const S32 areaStart, const S32 areaEnd)
  96. {
  97. S32 diff = 0;
  98. if (targetX < areaStart)
  99. {
  100. diff = targetX - areaStart;
  101. }
  102. else if (targetX > areaEnd)
  103. {
  104. diff = targetX - areaEnd;
  105. }
  106. mTextScrollX += diff;
  107. }
  108. U32 GuiTextEditTextBlock::calculateIbeamPositionInLine(const S32 targetX, GFont* font)
  109. {
  110. if (mText.length() == 0)
  111. return mLineStartIbeamValue;
  112. S32 curX = getGlobalTextStart().x;
  113. U32 result = mText.length();
  114. for (U32 count = 0; count < mText.length(); count++)
  115. {
  116. char c = mText[count];
  117. if (!font->isValidChar(c))
  118. continue;
  119. S32 backDiff = mAbs(curX - targetX);
  120. curX += font->getCharXIncrement(c);
  121. if (curX > targetX)
  122. {
  123. S32 forwardDiff = mAbs(curX - targetX);
  124. if (backDiff < forwardDiff)
  125. result = count;
  126. else
  127. result = count + 1;
  128. break;
  129. }
  130. }
  131. return result;
  132. }
  133. void GuiTextEditTextBlock::processScrollVelocity(const S32 delta, const S32 extentX, GFont* font)
  134. {
  135. U32 max = font->getStrWidth(mText.c_str()) - extentX;
  136. mTextScrollX = mClamp(mTextScrollX + delta, 0, max);
  137. }
  138. void GuiTextEditTextBlock::processTextAlignment(const string line, GFont* font, AlignmentType align)
  139. {
  140. if (align == AlignmentType::LeftAlign ||
  141. mGlobalBounds.extent.x < font->getStrWidth(line.c_str()))
  142. {
  143. mTextOffsetX = 0;
  144. }
  145. else if (align == AlignmentType::RightAlign)
  146. {
  147. mTextOffsetX = mGlobalBounds.extent.x - font->getStrWidth(line.c_str());
  148. }
  149. else if (align == AlignmentType::CenterAlign)
  150. {
  151. mTextOffsetX = (S32)mRound((mGlobalBounds.extent.x - font->getStrWidth(line.c_str())) / 2);
  152. }
  153. }
  154. #pragma endregion
  155. #pragma region GuiTextEditSelection
  156. GuiTextEditSelection::GuiTextEditSelection()
  157. {
  158. mBlockStart = 0;
  159. mBlockEnd = 0;
  160. mCursorPos = 0;
  161. mCursorOn = false;
  162. mNumFramesElapsed = 0;
  163. mCursorAtEOL = false;
  164. mIsFirstResponder = false;
  165. mGlobalUnadjustedCursorRect.set(0, 0, 0, 0);
  166. mCursorRendered = false;
  167. mNumFramesElapsed = 0;
  168. mTimeLastCursorFlipped = 0;
  169. mCursorOn = false;
  170. }
  171. bool GuiTextEditSelection::renderIbeam(const Point2I& startPoint, const Point2I& extent, const string line, const U32 start, const U32 end, GuiControlProfile* profile, GFont* font)
  172. {
  173. if (!mIsFirstResponder || !mCursorOn ||
  174. (mCursorAtEOL && mCursorPos == start && mCursorPos != 0) ||
  175. (!mCursorAtEOL && mCursorPos == end && mCursorPos != mTextLength) ||
  176. (mCursorPos < start || mCursorPos > end))
  177. {
  178. return false;
  179. }
  180. string blockText = line.substr(0, mCursorPos - start);
  181. U32 blockStrWidth = font->getStrWidth(blockText.c_str());
  182. RectI ibeamRect = RectI(startPoint.x + blockStrWidth - 1, startPoint.y, 2, extent.y);
  183. setCursorRect(ibeamRect);
  184. RectI clipRect = dglGetClipRect();
  185. if (clipRect.point.x > ibeamRect.point.x)
  186. {
  187. ibeamRect.point.x = clipRect.point.x;
  188. }
  189. else if ((clipRect.point.x + clipRect.extent.x) < (ibeamRect.point.x + ibeamRect.extent.x))
  190. {
  191. ibeamRect.point.x = (clipRect.point.x + clipRect.extent.x) - ibeamRect.extent.x;
  192. }
  193. dglDrawRectFill(ibeamRect, profile->mCursorColor);
  194. return true;
  195. }
  196. void GuiTextEditSelection::selectTo(const U32 target)
  197. {
  198. S32 safeTarget = mClamp(target, 0, mTextLength);
  199. if (mBlockStart == mBlockEnd)
  200. {
  201. mBlockAnchor = mBlockStart = mBlockEnd = mCursorPos;
  202. }
  203. if (safeTarget > mBlockAnchor)
  204. {
  205. mBlockStart = mBlockAnchor;
  206. mBlockEnd = mCursorPos = safeTarget;
  207. }
  208. else if (safeTarget < mBlockAnchor)
  209. {
  210. mBlockStart = mCursorPos = safeTarget;
  211. mBlockEnd = mBlockAnchor;
  212. }
  213. else
  214. {
  215. mCursorPos = mBlockStart = mBlockEnd = safeTarget;
  216. }
  217. }
  218. void GuiTextEditSelection::eraseSelection(string& fullText)
  219. {
  220. if (hasSelection())
  221. {
  222. fullText.erase(mBlockStart, mBlockEnd - mBlockStart);
  223. mCursorPos = mBlockStart;
  224. mTextLength = fullText.length();
  225. clearSelection();
  226. }
  227. }
  228. void GuiTextEditSelection::onPreRender(const U32 time)
  229. {
  230. if (mIsFirstResponder)
  231. {
  232. U32 timeElapsed = time - mTimeLastCursorFlipped;
  233. mNumFramesElapsed++;
  234. if ((timeElapsed > 400) && (mNumFramesElapsed > 3))
  235. {
  236. mCursorOn = !mCursorOn;
  237. mTimeLastCursorFlipped = time;
  238. mNumFramesElapsed = 0;
  239. }
  240. }
  241. }
  242. void GuiTextEditSelection::resetCursorBlink()
  243. {
  244. mCursorOn = true;
  245. mNumFramesElapsed = 0;
  246. mTimeLastCursorFlipped = Platform::getVirtualMilliseconds();
  247. }
  248. void GuiTextEditSelection::selectWholeWord(const string& text)
  249. {
  250. bool selectingSpace = (mCursorPos < text.length() && text[mCursorPos] == ' ');
  251. for (S32 i = mCursorPos; i >= 0; i--)
  252. {
  253. if (i == 0)
  254. {
  255. mBlockStart = 0;
  256. break;
  257. }
  258. if ((!selectingSpace && text[i - 1] == ' ') ||
  259. (selectingSpace && text[i - 1] != ' '))
  260. {
  261. mBlockStart = i;
  262. break;
  263. }
  264. }
  265. mBlockAnchor = mBlockStart;
  266. bool foundSpace = false;
  267. for (S32 j = mCursorPos; j <= (text.length() + 1); j++)
  268. {
  269. if (j == (text.length() + 1))
  270. {
  271. mBlockEnd = j;
  272. break;
  273. }
  274. if (!foundSpace && text[j] == ' ')
  275. {
  276. foundSpace = true;
  277. }
  278. else if (foundSpace && text[j] != ' ')
  279. {
  280. mBlockEnd = j;
  281. break;
  282. }
  283. }
  284. mCursorPos = mBlockEnd;
  285. mCursorAtEOL = true;
  286. }
  287. GuiTextEditSelection::GuiTextEditSelection(const GuiTextEditSelection& selector)
  288. {
  289. mBlockAnchor = selector.mBlockAnchor;
  290. mBlockStart = selector.mBlockStart;
  291. mBlockEnd = selector.mBlockEnd;
  292. mCursorPos = selector.mCursorPos;
  293. mCursorAtEOL = selector.mCursorAtEOL;
  294. mIsFirstResponder = selector.mIsFirstResponder;
  295. mGlobalUnadjustedCursorRect = selector.mGlobalUnadjustedCursorRect;
  296. mCursorRendered = selector.mCursorRendered;
  297. mTextLength = selector.mTextLength;
  298. mNumFramesElapsed = 0;
  299. mTimeLastCursorFlipped = Platform::getVirtualMilliseconds();
  300. mCursorOn = true;
  301. }
  302. void GuiTextEditSelection::stepCursorForward()
  303. {
  304. if (hasSelection())
  305. {
  306. setCursorPosition(mBlockEnd);
  307. }
  308. else
  309. {
  310. setCursorPosition(mCursorPos + 1);
  311. }
  312. }
  313. void GuiTextEditSelection::stepCursorBackward()
  314. {
  315. if (hasSelection())
  316. {
  317. setCursorPosition(mBlockStart);
  318. }
  319. else
  320. {
  321. setCursorPosition(mCursorPos - 1);
  322. }
  323. }
  324. #pragma endregion
  325. #pragma region GuiTextEditCtrl
  326. IMPLEMENT_CONOBJECT(GuiTextEditCtrl);
  327. U32 GuiTextEditCtrl::smNumAwake = 0;
  328. GuiTextEditCtrl::GuiTextEditCtrl()
  329. {
  330. mInsertOn = true;
  331. mMouseOver = false;
  332. mPasswordText = false;
  333. mReturnCausesTab = false;
  334. mSinkAllKeyEvents = false;
  335. mActive = true;
  336. mSelector = GuiTextEditSelection();
  337. mUndoSelector = GuiTextEditSelection();
  338. mUndoText = string();
  339. mTextOffsetY = 0;
  340. mReturnCommand = StringTable->EmptyString;
  341. mEscapeCommand = StringTable->EmptyString;
  342. mPasswordMask = StringTable->insert( "*" );
  343. mEditCursor = NULL;
  344. mMaxStrLen = MAX_STRING_LENGTH;
  345. mInputMode = AllText;
  346. mSuspendVerticalScrollJump = false;
  347. mTextBlockList = TextBlockList();
  348. mScrollVelocity = 0;
  349. mIsContainer = false;
  350. mBounds.extent.set(220, 30);
  351. }
  352. static EnumTable::Enums inputModeEnums[] =
  353. {
  354. { GuiTextEditCtrl::AllText, "AllText" },
  355. { GuiTextEditCtrl::Decimal, "Decimal" },
  356. { GuiTextEditCtrl::Number, "Number" },
  357. { GuiTextEditCtrl::Alpha, "Alpha" },
  358. { GuiTextEditCtrl::AlphaNumeric, "AlphaNumeric" }
  359. };
  360. static EnumTable gInputModeTable(5, &inputModeEnums[0]);
  361. void GuiTextEditCtrl::initPersistFields()
  362. {
  363. Parent::initPersistFields();
  364. addDepricatedField("validate");
  365. addDepricatedField("truncate");
  366. addDepricatedField("passwordMask");
  367. addDepricatedField("historySize");
  368. addDepricatedField("tabComplete");
  369. addGroup("Text Edit");
  370. addField("returnCommand", TypeString, Offset(mReturnCommand, GuiTextEditCtrl));
  371. addField("escapeCommand", TypeString, Offset(mEscapeCommand, GuiTextEditCtrl));
  372. addField("sinkAllKeyEvents", TypeBool, Offset(mSinkAllKeyEvents, GuiTextEditCtrl), &writeSinkAllKeyEventsFn);
  373. addField("password", TypeBool, Offset(mPasswordText, GuiTextEditCtrl), &writePasswordFn);
  374. addField("returnCausesTab", TypeBool, Offset(mReturnCausesTab, GuiTextEditCtrl), &writeReturnCausesTabFn);
  375. addProtectedField("maxLength", TypeS32, Offset(mMaxStrLen, GuiTextEditCtrl), &setMaxLengthProperty, &defaultProtectedGetFn, "The max number of characters that can be entered into the text edit box.");
  376. addProtectedField("inputMode", TypeEnum, Offset(mInputMode, GuiTextEditCtrl), &setInputMode, &getInputMode, &writeInputMode, 1, &gInputModeTable, "InputMode allows different characters to be entered.");
  377. addField("editCursor", TypeGuiCursor, Offset(mEditCursor, GuiTextEditCtrl));
  378. endGroup("Text Edit");
  379. }
  380. bool GuiTextEditCtrl::onAdd()
  381. {
  382. if ( ! Parent::onAdd() )
  383. return false;
  384. if( mText[0] )
  385. {
  386. setText(mText);
  387. }
  388. return true;
  389. }
  390. void GuiTextEditCtrl::onStaticModified(const char* slotName)
  391. {
  392. if(!dStricmp(slotName, "text"))
  393. setText(mText);
  394. }
  395. void GuiTextEditCtrl::inspectPostApply()
  396. {
  397. Parent::inspectPostApply();
  398. if (mTextID && *mTextID != 0)
  399. setTextID(mTextID);
  400. else
  401. setText(mText);
  402. }
  403. bool GuiTextEditCtrl::onWake()
  404. {
  405. if (! Parent::onWake())
  406. return false;
  407. if (mConsoleVariable[0])
  408. {
  409. const char *txt = Con::getVariable(mConsoleVariable);
  410. if (txt)
  411. {
  412. if (dStrlen(txt) > (U32)mMaxStrLen)
  413. {
  414. char* buf = new char[mMaxStrLen + 1];
  415. dStrncpy(buf, txt, mMaxStrLen);
  416. buf[mMaxStrLen] = 0;
  417. setScriptValue(buf);
  418. delete[] buf;
  419. }
  420. else
  421. setScriptValue(txt);
  422. }
  423. }
  424. // If this is the first awake text edit control, enable keyboard translation
  425. if (smNumAwake == 0)
  426. Platform::enableKeyboardTranslation();
  427. ++smNumAwake;
  428. mSuspendVerticalScrollJump = false;
  429. return true;
  430. }
  431. void GuiTextEditCtrl::onSleep()
  432. {
  433. Parent::onSleep();
  434. // If this is the last awake text edit control, disable keyboard translation
  435. --smNumAwake;
  436. if (smNumAwake == 0)
  437. Platform::disableKeyboardTranslation();
  438. }
  439. void GuiTextEditCtrl::execConsoleCallback()
  440. {
  441. setVariable(mTextBuffer.c_str());
  442. if ( mConsoleCommand[0] )
  443. {
  444. Con::evaluate( mConsoleCommand, false );
  445. }
  446. }
  447. const char* GuiTextEditCtrl::getText()
  448. {
  449. return mTextBuffer.c_str();
  450. }
  451. void GuiTextEditCtrl::setText( const UTF8 *txt )
  452. {
  453. setUpdate();
  454. enforceMaxLength();
  455. if (txt && txt[0] != 0)
  456. {
  457. Parent::setText(txt);
  458. mTextBuffer.assign(txt);
  459. }
  460. else
  461. mTextBuffer.clear();
  462. setVariable(mTextBuffer.c_str());
  463. }
  464. void GuiTextEditCtrl::setText( const UTF16* txt)
  465. {
  466. if(txt && txt[0] != 0)
  467. {
  468. UTF8* txt8 = convertUTF16toUTF8( txt );
  469. setText(txt8);
  470. delete[] txt8;
  471. }
  472. else
  473. {
  474. setText("");
  475. }
  476. }
  477. void GuiTextEditCtrl::enforceMaxLength()
  478. {
  479. int diff = mTextBuffer.length() - mMaxStrLen;
  480. if (diff > 0) {
  481. mTextBuffer.resize(mMaxStrLen);
  482. }
  483. }
  484. void GuiTextEditCtrl::setTextID(const char *id)
  485. {
  486. S32 n = Con::getIntVariable(id, -1);
  487. if (n != -1)
  488. {
  489. setTextID(n);
  490. }
  491. }
  492. void GuiTextEditCtrl::setTextID(S32 id)
  493. {
  494. const UTF8 *str = getGUIString(id);
  495. if (str)
  496. setText((const char*)str);
  497. }
  498. bool GuiTextEditCtrl::validate()
  499. {
  500. bool valid = true;
  501. if (isMethod("onValidate"))
  502. {
  503. valid = dAtob(Con::executef(this, 2, "onValidate"));
  504. }
  505. return valid;
  506. }
  507. const RectI GuiTextEditCtrl::getGlobalInnerRect()
  508. {
  509. RectI innerRect = getInnerRect(SelectedState);
  510. Point2I globalCtrlOffset = localToGlobalCoord(innerRect.point);
  511. RectI globalInnerRect(globalCtrlOffset, innerRect.extent);
  512. return globalInnerRect;
  513. }
  514. S32 GuiTextEditCtrl::calculateIbeamPosition(const Point2I& globalMousePoint)
  515. {
  516. if (mTextBuffer.length() == 0)
  517. return 0;
  518. RectI globalInnerRect = getGlobalInnerRect();
  519. return calculateIbeamPosition(globalMousePoint, globalInnerRect);
  520. }
  521. S32 GuiTextEditCtrl::calculateIbeamPosition(const Point2I& globalMousePoint, const RectI& globalInnerRect)
  522. {
  523. if (mTextBuffer.length() == 0 || mTextBlockList.size() == 0)
  524. return 0;
  525. string textBuffer = applyPasswordMasking();
  526. GFont* font = mProfile->getFont(mFontSizeAdjust);
  527. if (!mTextWrap)
  528. {
  529. return mTextBlockList.front().calculateIbeamPositionInLine(globalMousePoint.x, font);
  530. }
  531. else
  532. {
  533. RectI firstLineBounds = mTextBlockList.front().getGlobalBounds();
  534. S32 textStartY = firstLineBounds.point.y;
  535. if (textStartY > globalMousePoint.y)
  536. return 0;
  537. U32 height = firstLineBounds.extent.y;
  538. if ((textStartY + (mTextBlockList.size() * height)) < globalMousePoint.y)
  539. return mTextBuffer.length();
  540. S32 curY = textStartY;
  541. for (auto block : mTextBlockList)
  542. {
  543. curY += height;
  544. if (curY > globalMousePoint.y)
  545. {
  546. U32 pos = block.calculateIbeamPositionInLine(globalMousePoint.x, font);
  547. mSelector.setCursorAtEOL(block.calculateCursorAtEOL(pos));
  548. return pos + block.getStartValue();
  549. }
  550. }
  551. mSelector.setCursorAtEOL(true);
  552. return mTextBlockList.back().calculateIbeamPositionInLine(globalMousePoint.x, font);
  553. }
  554. }
  555. void GuiTextEditCtrl::onTouchDown( const GuiEvent &event )
  556. {
  557. mScrollVelocity = 0;
  558. mSuspendVerticalScrollJump = false;
  559. if (!mVisible || !mAwake)
  560. return;
  561. mouseLock();
  562. setFirstResponder();
  563. mSelector.resetCursorBlink();
  564. mSelector.setTextLength(mTextBuffer.length());
  565. if(event.mouseClickCount == 2)
  566. {
  567. mSelector.selectWholeWord(mTextBuffer);
  568. }
  569. else if (event.mouseClickCount < 2)
  570. {
  571. S32 newCursorPos = calculateIbeamPosition(event.mousePoint);
  572. if (event.modifier & SI_SHIFT)
  573. {
  574. modifySelectBlock(newCursorPos);
  575. }
  576. else
  577. {
  578. mSelector.setCursorPosition(newCursorPos);
  579. }
  580. }
  581. if( isMethod("onTouchDown") )
  582. {
  583. char buf[3][32];
  584. dSprintf(buf[0], 32, "%d", event.modifier);
  585. dSprintf(buf[1], 32, "%d %d", event.mousePoint.x, event.mousePoint.y);
  586. dSprintf(buf[2], 32, "%d", event.mouseClickCount);
  587. Con::executef(this, 4, "onTouchDown", buf[0], buf[1], buf[2]);
  588. }
  589. }
  590. void GuiTextEditCtrl::onTouchDragged( const GuiEvent &event )
  591. {
  592. if (!mVisible || !mAwake)
  593. return;
  594. mSuspendVerticalScrollJump = false;
  595. RectI globalInnerRect = getGlobalInnerRect();
  596. adjustScrollVelocity(event.mousePoint, globalInnerRect);
  597. if ((mTextWrap && event.mousePoint.y < globalInnerRect.point.y) ||
  598. (!mTextWrap && event.mousePoint.x < globalInnerRect.point.x))
  599. {
  600. modifySelectBlock(0);
  601. }
  602. else if ((mTextWrap && event.mousePoint.y > (globalInnerRect.point.y + globalInnerRect.extent.y)) ||
  603. (!mTextWrap && event.mousePoint.x > (globalInnerRect.point.x + globalInnerRect.extent.x)))
  604. {
  605. modifySelectBlock(mTextBuffer.length());
  606. }
  607. else
  608. {
  609. modifySelectBlock(calculateIbeamPosition(event.mousePoint, globalInnerRect));
  610. }
  611. // Notify Script.
  612. if( isMethod("onTouchDragged") )
  613. {
  614. char buf[3][32];
  615. dSprintf(buf[0], 32, "%d", event.modifier);
  616. dSprintf(buf[1], 32, "%d %d", event.mousePoint.x, event.mousePoint.y);
  617. dSprintf(buf[2], 32, "%d", event.mouseClickCount);
  618. Con::executef(this, 4, "onTouchDragged", buf[0], buf[1], buf[2]);
  619. }
  620. }
  621. void GuiTextEditCtrl::onTouchUp(const GuiEvent &event)
  622. {
  623. mScrollVelocity = 0;
  624. mSuspendVerticalScrollJump = false;
  625. mouseUnlock();
  626. if (!mVisible || !mAwake)
  627. return;
  628. // Notify Script.
  629. if( isMethod("onTouchUp") )
  630. {
  631. char buf[3][32];
  632. dSprintf(buf[0], 32, "%d", event.modifier);
  633. dSprintf(buf[1], 32, "%d %d", event.mousePoint.x, event.mousePoint.y);
  634. dSprintf(buf[2], 32, "%d", event.mouseClickCount);
  635. Con::executef(this, 4, "onTouchUp", buf[0], buf[1], buf[2]);
  636. }
  637. }
  638. void GuiTextEditCtrl::onMouseWheelUp(const GuiEvent& event)
  639. {
  640. if (!mVisible || !mAwake)
  641. return;
  642. if(mTextWrap && mTextOffsetY > 0)
  643. {
  644. mScrollVelocity = 0;
  645. mSuspendVerticalScrollJump = true;
  646. mTextOffsetY = getMax(mTextOffsetY - static_cast<S32>(mProfile->getFont(mFontSizeAdjust)->getHeight()), 0);
  647. return;
  648. }
  649. GuiControl* parent = getParent();
  650. if (parent)
  651. parent->onMouseWheelUp(event);
  652. }
  653. void GuiTextEditCtrl::onMouseWheelDown(const GuiEvent& event)
  654. {
  655. if (!mVisible || !mAwake)
  656. return;
  657. U32 blockHeight = mTextBlockList.size() * mProfile->getFont(mFontSizeAdjust)->getHeight();
  658. RectI innerRect = getGlobalInnerRect();
  659. S32 max = blockHeight - innerRect.extent.y;
  660. if (mTextWrap && innerRect.extent.y < blockHeight && mTextOffsetY < max)
  661. {
  662. mScrollVelocity = 0;
  663. mSuspendVerticalScrollJump = true;
  664. mTextOffsetY = getMin(mTextOffsetY + static_cast<S32>(mProfile->getFont(mFontSizeAdjust)->getHeight()), max);
  665. return;
  666. }
  667. GuiControl* parent = getParent();
  668. if (parent)
  669. parent->onMouseWheelDown(event);
  670. }
  671. void GuiTextEditCtrl::onTouchEnter(const GuiEvent& event)
  672. {
  673. if (!mActive)
  674. return;
  675. mMouseOver = true;
  676. Con::executef(this, 1, "onTouchEnter");
  677. //update
  678. setUpdate();
  679. }
  680. void GuiTextEditCtrl::onTouchLeave(const GuiEvent& event)
  681. {
  682. if (!mActive)
  683. return;
  684. mMouseOver = false;
  685. Con::executef(this, 1, "onTouchLeave");
  686. //update
  687. setUpdate();
  688. }
  689. void GuiTextEditCtrl::saveUndoState()
  690. {
  691. //save the current state
  692. mUndoText = mTextBuffer;
  693. mUndoSelector = mSelector;
  694. }
  695. void GuiTextEditCtrl::onCopy(bool andCut)
  696. {
  697. // Don't copy/cut password field!
  698. if(mPasswordText)
  699. return;
  700. if (mSelector.hasSelection())
  701. {
  702. //save the current state
  703. saveUndoState();
  704. //copy the text to the clipboard
  705. string subString = mSelector.getSelection(mTextBuffer);
  706. Platform::setClipboard(subString.c_str());
  707. //if we pressed the cut shortcut, we need to cut the selected text from the control...
  708. if (andCut)
  709. {
  710. mSelector.eraseSelection(mTextBuffer);
  711. }
  712. mSelector.clearSelection();
  713. }
  714. }
  715. void GuiTextEditCtrl::onPaste()
  716. {
  717. //first, make sure there's something in the clipboard to copy...
  718. string clipboard = Platform::getClipboard();
  719. if(clipboard.length() <= 0)
  720. return;
  721. //save the current state
  722. saveUndoState();
  723. //delete anything hilited
  724. if (mSelector.hasSelection())
  725. {
  726. mSelector.eraseSelection(mTextBuffer);
  727. mSelector.clearSelection();
  728. }
  729. U32 pos = mSelector.getCursorPos();
  730. mTextBuffer.insert(pos, clipboard);
  731. setText(mTextBuffer);
  732. pos += clipboard.length();
  733. mSelector.setCursorPosition(pos);
  734. execConsoleCallback();
  735. }
  736. void GuiTextEditCtrl::onUndo()
  737. {
  738. string tempText = mTextBuffer;
  739. GuiTextEditSelection tempSelector = mSelector;
  740. mTextBuffer = mUndoText;
  741. mSelector = mUndoSelector;
  742. mUndoText = tempText;
  743. mUndoSelector = tempSelector;
  744. }
  745. bool GuiTextEditCtrl::onKeyDown(const GuiEvent &event)
  746. {
  747. if(! isActive())
  748. return false;
  749. mSuspendVerticalScrollJump = false;
  750. S32 stringLen = mTextBuffer.length();
  751. mSelector.setTextLength(stringLen);
  752. setUpdate();
  753. bool result = false;
  754. if (event.modifier & SI_SHIFT)
  755. {
  756. result = handleKeyDownWithShift(event);
  757. }
  758. else if (event.modifier & SI_CTRL)
  759. {
  760. //When holding the ctrl key, events must be handled here or passed up.
  761. return handleKeyDownWithCtrl(event);
  762. }
  763. else if (event.modifier & SI_ALT)
  764. {
  765. result = handleKeyDownWithAlt(event);
  766. #if (defined(TORQUE_OS_OSX) || defined(TORQUE_OS_IOS))
  767. //Likewise, the cmd key must be handled here or passed up.
  768. return result;
  769. #endif
  770. }
  771. if(result || (!result && handleKeyDownWithNoModifier(event)))
  772. {
  773. return true;
  774. }
  775. if (handleCharacterInput(event) || mSinkAllKeyEvents)
  776. {
  777. return true;
  778. }
  779. return Parent::onKeyDown( event );
  780. }
  781. bool GuiTextEditCtrl::tabNext()
  782. {
  783. if (isMethod("onTab"))
  784. Con::executef(this, 2, "onTab", "0");
  785. GuiCanvas *root = getRoot();
  786. if (root)
  787. {
  788. root->tabNext();
  789. return true;
  790. }
  791. return false;
  792. }
  793. bool GuiTextEditCtrl::tabPrev()
  794. {
  795. if (isMethod("onTab"))
  796. Con::executef(this, 2, "onTab", "1");
  797. GuiCanvas *root = getRoot();
  798. if (root)
  799. {
  800. root->tabPrev();
  801. return true;
  802. }
  803. return false;
  804. }
  805. void GuiTextEditCtrl::onFocus(bool foundFirstResponder)
  806. {
  807. Parent::onFocus(foundFirstResponder);
  808. mTextOnFocus = mText;
  809. }
  810. void GuiTextEditCtrl::setFirstResponder()
  811. {
  812. if(!isFirstResponder())
  813. {
  814. mTextOnFocus = mText;
  815. }
  816. selectAllText();
  817. if(mTextBuffer.length() == 0)
  818. {
  819. mSelector.selectTo(mTextBuffer.length());
  820. }
  821. mSelector.setFirstResponder(true);
  822. Parent::setFirstResponder();
  823. #if !defined(TORQUE_OS_IOS) && !defined(TORQUE_OS_ANDROID)
  824. Platform::enableKeyboardTranslation();
  825. #endif
  826. }
  827. void GuiTextEditCtrl::onLoseFirstResponder()
  828. {
  829. Platform::disableKeyboardTranslation();
  830. //execute the validate command
  831. bool valid = validate();
  832. if (valid)
  833. {
  834. execAltConsoleCallback();
  835. }
  836. if( isMethod( "onLoseFirstResponder" ) )
  837. Con::executef( this, 2, "onLoseFirstResponder", valid);
  838. if (isMethod("onBlur"))
  839. Con::executef(this, 2, "onBlur", valid);
  840. mSelector.setFirstResponder(false);
  841. mTextOffsetY = 0;
  842. mScrollVelocity = 0;
  843. if (!mTextWrap && mTextBlockList.size() > 0)
  844. {
  845. mTextBlockList.front().resetScroll();
  846. }
  847. // Redraw the control:
  848. setUpdate();
  849. }
  850. void GuiTextEditCtrl::parentResized(const Point2I &oldParentExtent, const Point2I &newParentExtent)
  851. {
  852. Parent::parentResized( oldParentExtent, newParentExtent );
  853. mTextOffsetY = 0;
  854. if (!mTextWrap && mTextBlockList.size() > 0)
  855. {
  856. mTextBlockList.front().resetScroll();
  857. }
  858. }
  859. GuiControlState GuiTextEditCtrl::getCurrentState()
  860. {
  861. if (!mActive)
  862. return GuiControlState::DisabledState;
  863. else if (isFirstResponder())
  864. return GuiControlState::SelectedState;
  865. else if (mMouseOver)
  866. return GuiControlState::HighlightState;
  867. else
  868. return GuiControlState::NormalState;
  869. }
  870. const ColorI& GuiTextEditCtrl::getCurrentFontColor()
  871. {
  872. auto currentState = getCurrentState();
  873. return mProfile->getFontColor(currentState);
  874. }
  875. void GuiTextEditCtrl::onPreRender()
  876. {
  877. mSelector.onPreRender(Platform::getVirtualMilliseconds());
  878. processScrollVelocity();
  879. }
  880. void GuiTextEditCtrl::onRender(Point2I offset, const RectI & updateRect)
  881. {
  882. GuiControlState currentState = getCurrentState();
  883. RectI ctrlRect = applyMargins(offset, mBounds.extent, currentState, mProfile);
  884. renderUniversalRect(ctrlRect, mProfile, currentState);
  885. //Render Text
  886. RectI fillRect = applyBorders(ctrlRect.point, ctrlRect.extent, NormalState, mProfile);
  887. RectI contentRect = applyPadding(fillRect.point, fillRect.extent, NormalState, mProfile);
  888. if (contentRect.isValidRect())
  889. {
  890. if (currentState != SelectedState)
  891. mSelector.clearSelection();
  892. string textBuffer = applyPasswordMasking();
  893. renderText(contentRect.point, contentRect.extent, textBuffer.c_str(), mProfile);
  894. //Render the childen
  895. renderChildControls(offset, contentRect, updateRect);
  896. }
  897. }
  898. void GuiTextEditCtrl::renderLineList(const Point2I& offset, const Point2I& extent, const S32 startOffsetY, const vector<string> lineList, GuiControlProfile* profile, const TextRotationOptions rot)
  899. {
  900. GFont* font = profile->getFont(mFontSizeAdjust);
  901. const S32 textHeight = font->getHeight();
  902. S32 totalWidth = extent.x;
  903. if (mTextBlockList.size() > lineList.size())
  904. {
  905. mTextBlockList.resize(lineList.size());
  906. }
  907. //Now print each line
  908. U32 ibeamPos = 0;
  909. S32 offsetY = startOffsetY - mTextOffsetY;
  910. for (U32 i = 0; i < lineList.size(); i++)
  911. {
  912. if(mTextBlockList.size() <= i)
  913. {
  914. mTextBlockList.push_back(GuiTextEditTextBlock());
  915. }
  916. Point2I start = Point2I(0, offsetY);
  917. Point2I blockExtent = Point2I(extent.x, textHeight);
  918. RectI blockBounds = RectI(start + offset + profile->mTextOffset, blockExtent);
  919. if (mOverrideFontColor)
  920. {
  921. dglSetBitmapModulation(getFontColor(profile, NormalState));
  922. }
  923. mTextBlockList[i].render(blockBounds, lineList[i], ibeamPos, mProfile, getCurrentState(), mSelector, getAlignmentType(), font, mOverrideFontColor);
  924. offsetY += textHeight;
  925. ibeamPos += lineList[i].length();
  926. }
  927. performScrollJumpY();
  928. }
  929. void GuiTextEditCtrl::processScrollVelocity()
  930. {
  931. if (mScrollVelocity == 0)
  932. {
  933. return;
  934. }
  935. U32 timeElapsed = Platform::getVirtualMilliseconds() - mTimeLastScrollProcess;
  936. S32 delta = mRound((F32)(timeElapsed * mScrollVelocity) / 1000);
  937. if (delta != 0)
  938. {
  939. RectI innerRect = getGlobalInnerRect();
  940. if (mTextWrap)
  941. {
  942. U32 max = (mTextBlockList.size() * mProfile->getFont(mFontSizeAdjust)->getHeight()) - innerRect.extent.y;
  943. mTextOffsetY = mClamp(mTextOffsetY + delta, 0, max);
  944. }
  945. else if(mTextBlockList.size() > 0)
  946. {
  947. mTextBlockList.front().processScrollVelocity(delta, innerRect.extent.x, mProfile->getFont(mFontSizeAdjust));
  948. }
  949. mTimeLastScrollProcess = Platform::getVirtualMilliseconds();
  950. S32 newCursorPos = calculateIbeamPosition(Canvas->getCursorPos());
  951. modifySelectBlock(newCursorPos);
  952. }
  953. }
  954. void GuiTextEditCtrl::performScrollJumpY()
  955. {
  956. if (mTextWrap && !mSuspendVerticalScrollJump && isFirstResponder() && mSelector.isCursorRendered())
  957. {
  958. RectI clipRect = dglGetClipRect();
  959. S32 areaStart = clipRect.point.y;
  960. S32 areaEnd = clipRect.point.y + clipRect.extent.y;
  961. RectI cursorRect = mSelector.getCursorRect();
  962. S32 lineTop = cursorRect.point.y;
  963. S32 lineBottom = lineTop + cursorRect.extent.y;
  964. S32 diff = 0;
  965. if (lineTop < areaStart)
  966. {
  967. diff = lineTop - areaStart;
  968. }
  969. else if (lineBottom > areaEnd)
  970. {
  971. diff = lineBottom - areaEnd;
  972. }
  973. mTextOffsetY += diff;
  974. }
  975. }
  976. void GuiTextEditCtrl::adjustScrollVelocity(const Point2I& globalMousePoint, const RectI& globalInnerRect)
  977. {
  978. RectI nonScrollArea = RectI(globalInnerRect);
  979. if (mTextWrap)
  980. {
  981. nonScrollArea.point.y += SCROLL_EDGE_SIZE;
  982. nonScrollArea.extent.y -= (2 * SCROLL_EDGE_SIZE);
  983. }
  984. else
  985. {
  986. nonScrollArea.point.x += SCROLL_EDGE_SIZE;
  987. nonScrollArea.extent.x -= (2 * SCROLL_EDGE_SIZE);
  988. }
  989. if (nonScrollArea.pointInRect(globalMousePoint))
  990. {
  991. mScrollVelocity = 0;
  992. }
  993. else if (globalInnerRect.pointInRect(globalMousePoint))
  994. {
  995. if (mScrollVelocity == 0)
  996. {
  997. mTimeLastScrollProcess = Platform::getVirtualMilliseconds();
  998. }
  999. mScrollVelocity = SCROLL_VELOCITY_PER_SEC;
  1000. if ((mTextWrap && globalMousePoint.y < (globalInnerRect.point.y + SCROLL_EDGE_SIZE)) ||
  1001. (!mTextWrap && globalMousePoint.x < (globalInnerRect.point.x + SCROLL_EDGE_SIZE)))
  1002. {
  1003. mScrollVelocity = -SCROLL_VELOCITY_PER_SEC;
  1004. }
  1005. }
  1006. else
  1007. {
  1008. mScrollVelocity = 0;
  1009. }
  1010. }
  1011. bool GuiTextEditCtrl::hasText()
  1012. {
  1013. return (mTextBuffer.length());
  1014. }
  1015. void GuiTextEditCtrl::keyDenied()
  1016. {
  1017. if (isMethod("onDenied"))
  1018. Con::executef(this, 1, "onDenied");
  1019. }
  1020. const char *GuiTextEditCtrl::getScriptValue()
  1021. {
  1022. return StringTable->insert(mTextBuffer.c_str());
  1023. }
  1024. void GuiTextEditCtrl::setScriptValue(const char *value)
  1025. {
  1026. mTextBuffer.assign(value);
  1027. mSelector.setTextLength(mTextBuffer.length());
  1028. }
  1029. GuiTextEditCtrl::InputMode GuiTextEditCtrl::getInputModeEnum(const char* label)
  1030. {
  1031. // Search for Mnemonic.
  1032. for (U32 i = 0; i < (sizeof(inputModeEnums) / sizeof(EnumTable::Enums)); i++)
  1033. {
  1034. if (dStricmp(inputModeEnums[i].label, label) == 0)
  1035. return (InputMode)inputModeEnums[i].index;
  1036. }
  1037. // Warn.
  1038. Con::warnf("GuiTextEditCtrl::getInputModeEnum() - Invalid mode of '%s'", label);
  1039. return (InputMode)-1;
  1040. }
  1041. const char* GuiTextEditCtrl::getInputModeDescription(const InputMode mode)
  1042. {
  1043. // Search for Mnemonic.
  1044. for (U32 i = 0; i < (sizeof(inputModeEnums) / sizeof(EnumTable::Enums)); i++)
  1045. {
  1046. if (inputModeEnums[i].index == mode)
  1047. return inputModeEnums[i].label;
  1048. }
  1049. // Warn.
  1050. Con::warnf("GuiTextEditCtrl::getInputModeDescription() - Invalid input mode.");
  1051. return StringTable->EmptyString;
  1052. }
  1053. //Returns true if valid, false if invalid
  1054. bool GuiTextEditCtrl::inputModeValidate(const U16 key, S32 cursorPos)
  1055. {
  1056. if (key == '-')
  1057. {
  1058. if (mInputMode == Alpha || mInputMode == AlphaNumeric)
  1059. {
  1060. return false;
  1061. }
  1062. else if (mInputMode == Decimal || mInputMode == Number)
  1063. {
  1064. //a minus sign only exists at the beginning, and only a single minus sign
  1065. if (cursorPos != 0 || (mInsertOn && mTextBuffer[0] == '-'))
  1066. {
  1067. return false;
  1068. }
  1069. }
  1070. }
  1071. else if (key >= '0' && key <= '9')
  1072. {
  1073. if (mInputMode == Alpha)
  1074. {
  1075. return false;
  1076. }
  1077. }
  1078. else if (key == '.')
  1079. {
  1080. if (mInputMode == Number || mInputMode == Alpha || mInputMode == AlphaNumeric)
  1081. {
  1082. return false;
  1083. }
  1084. else if (mInputMode == Decimal)
  1085. {
  1086. if (!mInsertOn && mTextBuffer[cursorPos] == '.')
  1087. {
  1088. return true;
  1089. }
  1090. const char* dot = dStrchr(mTextBuffer.c_str(), '.');
  1091. if (dot != NULL)
  1092. {
  1093. return false;
  1094. }
  1095. }
  1096. }
  1097. else if ((key >= 'A' && key <= 'Z') || (key >= 'a' && key <= 'z'))
  1098. {
  1099. if (mInputMode == Decimal || mInputMode == Number)
  1100. {
  1101. return false;
  1102. }
  1103. }
  1104. else if (key == 32)
  1105. {
  1106. if (mInputMode == Decimal || mInputMode == Number)
  1107. {
  1108. return false;
  1109. }
  1110. }
  1111. else if (mInputMode == Decimal || mInputMode == Number || mInputMode == Alpha || mInputMode == AlphaNumeric)
  1112. {
  1113. //The remaining characters only go with AllText
  1114. return false;
  1115. }
  1116. //Looks like we have a valid character!
  1117. return true;
  1118. }
  1119. void GuiTextEditCtrl::setMaxLength(S32 max)
  1120. {
  1121. mMaxStrLen = getMax(1, getMin(max, MAX_STRING_LENGTH));
  1122. }
  1123. void GuiTextEditCtrl::setInputMode(const InputMode mode)
  1124. {
  1125. if(mInputMode == mode)
  1126. return;
  1127. //Time to set the mode
  1128. mInputMode = mode;
  1129. //now let's parse that buffer and get rid of invalid characters
  1130. if (mode != AllText)
  1131. {
  1132. bool oldInsert = mInsertOn;
  1133. mInsertOn = false;
  1134. for (S32 i = 0; i < MAX_STRING_LENGTH; i++)
  1135. {
  1136. const UTF16 character = mTextBuffer[i];
  1137. if (character == '\0')
  1138. {
  1139. //Done and done.
  1140. break;
  1141. }
  1142. if (!inputModeValidate(character, i))
  1143. {
  1144. //Bad Character! Let's remove it.
  1145. mTextBuffer.erase(i, 1);
  1146. //Step it back
  1147. i--;
  1148. }
  1149. }
  1150. mInsertOn = oldInsert;
  1151. }
  1152. }
  1153. string GuiTextEditCtrl::applyPasswordMasking()
  1154. {
  1155. if (mPasswordText)
  1156. {
  1157. string passwordCover = string();
  1158. passwordCover.resize(mTextBuffer.length(), mPasswordMask[0]);
  1159. return passwordCover;
  1160. }
  1161. return mTextBuffer;
  1162. }
  1163. bool GuiTextEditCtrl::handleKeyDownWithShift(const GuiEvent& event)
  1164. {
  1165. switch (event.keyCode)
  1166. {
  1167. case KEY_TAB:
  1168. return tabPrev();
  1169. case KEY_HOME:
  1170. mSelector.selectTo(0);
  1171. return true;
  1172. case KEY_END:
  1173. mSelector.selectTo(mTextBuffer.length());
  1174. return true;
  1175. case KEY_LEFT:
  1176. return handleShiftArrowKey(GuiDirection::Left);
  1177. case KEY_RIGHT:
  1178. return handleShiftArrowKey(GuiDirection::Right);
  1179. case KEY_UP:
  1180. return handleShiftArrowKey(GuiDirection::Up);
  1181. case KEY_DOWN:
  1182. return handleShiftArrowKey(GuiDirection::Down);
  1183. }
  1184. return false;
  1185. }
  1186. bool GuiTextEditCtrl::handleKeyDownWithCtrl(const GuiEvent& event)
  1187. {
  1188. switch (event.keyCode)
  1189. {
  1190. #if !(defined(TORQUE_OS_OSX) || defined(TORQUE_OS_IOS))
  1191. // windows style cut / copy / paste / undo keybinds
  1192. case KEY_C:
  1193. case KEY_X:
  1194. onCopy(event.keyCode == KEY_X);
  1195. return true;
  1196. case KEY_V:
  1197. onPaste();
  1198. return true;
  1199. case KEY_Z:
  1200. onUndo();
  1201. return true;
  1202. #endif
  1203. case KEY_DELETE:
  1204. case KEY_BACKSPACE:
  1205. selectAllText();
  1206. handleBackSpace();
  1207. return true;
  1208. }
  1209. return false;
  1210. }
  1211. bool GuiTextEditCtrl::handleKeyDownWithAlt(const GuiEvent& event)
  1212. {
  1213. #if (defined(TORQUE_OS_OSX) || defined(TORQUE_OS_IOS))
  1214. // Added Mac cut/copy/paste/undo keys
  1215. // Mac command key maps to alt in torque.
  1216. switch(event.keyCode)
  1217. {
  1218. case KEY_C:
  1219. case KEY_X:
  1220. onCopy( event.keyCode==KEY_X );
  1221. return true;
  1222. case KEY_V:
  1223. onPaste();
  1224. return true;
  1225. case KEY_Z:
  1226. onUndo();
  1227. return true;
  1228. }
  1229. #endif
  1230. return false;
  1231. }
  1232. bool GuiTextEditCtrl::handleKeyDownWithNoModifier(const GuiEvent& event)
  1233. {
  1234. switch (event.keyCode)
  1235. {
  1236. case KEY_TAB:
  1237. return tabNext();
  1238. case KEY_ESCAPE:
  1239. return handleEscapeKey();
  1240. case KEY_RETURN:
  1241. case KEY_NUMPADENTER:
  1242. if (!validate())
  1243. {
  1244. return true;
  1245. }
  1246. return handleEnterKey();
  1247. case KEY_LEFT:
  1248. return handleArrowKey(GuiDirection::Left);
  1249. case KEY_RIGHT:
  1250. return handleArrowKey(GuiDirection::Right);
  1251. case KEY_UP:
  1252. return handleArrowKey(GuiDirection::Up);
  1253. case KEY_DOWN:
  1254. return handleArrowKey(GuiDirection::Down);
  1255. case KEY_DELETE:
  1256. return handleDelete();
  1257. case KEY_BACKSPACE:
  1258. return handleBackSpace();
  1259. case KEY_INSERT:
  1260. mInsertOn = !mInsertOn;
  1261. return true;
  1262. case KEY_HOME:
  1263. mSelector.setCursorPosition(0);
  1264. return true;
  1265. case KEY_END:
  1266. mSelector.setCursorPosition(mTextBuffer.length());
  1267. return true;
  1268. }
  1269. return false;
  1270. }
  1271. bool GuiTextEditCtrl::handleCharacterInput(const GuiEvent& event)
  1272. {
  1273. if (!mProfile->getFont(mFontSizeAdjust))
  1274. return false;
  1275. if (mProfile->getFont(mFontSizeAdjust)->isValidChar(event.ascii))
  1276. {
  1277. // Get the character ready to add to a UTF8 string.
  1278. string characterToInsert = string(1, event.ascii);
  1279. //Stop characters that aren't allowed based on InputMode
  1280. if (!inputModeValidate(event.ascii, mSelector.getCursorPos()))
  1281. {
  1282. keyDenied();
  1283. return true;
  1284. }
  1285. saveUndoState();
  1286. if (mSelector.hasSelection())
  1287. {
  1288. mSelector.eraseSelection(mTextBuffer);
  1289. }
  1290. if (mTextBuffer.length() < mMaxStrLen || !mInsertOn)
  1291. {
  1292. if (!mInsertOn)
  1293. {
  1294. mTextBuffer.erase(mSelector.getCursorPos(), 1);
  1295. }
  1296. mTextBuffer.insert(mSelector.getCursorPos(), characterToInsert);
  1297. mSelector.setTextLength(mTextBuffer.length());
  1298. mSelector.stepCursorForward();
  1299. setText(mTextBuffer);
  1300. }
  1301. else
  1302. keyDenied();
  1303. execConsoleCallback();
  1304. return true;
  1305. }
  1306. return false;
  1307. }
  1308. bool GuiTextEditCtrl::handleBackSpace()
  1309. {
  1310. if (mTextBuffer.length() == 0 || (mSelector.getCursorPos() == 0 && !mSelector.hasSelection()))
  1311. return true;
  1312. saveUndoState();
  1313. if (mSelector.hasSelection())
  1314. {
  1315. mSelector.eraseSelection(mTextBuffer);
  1316. }
  1317. else
  1318. {
  1319. mSelector.stepCursorBackward();
  1320. mTextBuffer.erase(mSelector.getCursorPos(), 1);
  1321. }
  1322. mSelector.setTextLength(mTextBuffer.length());
  1323. setText(mTextBuffer);
  1324. execConsoleCallback();
  1325. return true;
  1326. }
  1327. bool GuiTextEditCtrl::handleDelete()
  1328. {
  1329. if (mTextBuffer.length() == mSelector.getCursorPos() && !mSelector.hasSelection())
  1330. return true;
  1331. saveUndoState();
  1332. if (mSelector.hasSelection())
  1333. {
  1334. mSelector.eraseSelection(mTextBuffer);
  1335. }
  1336. else
  1337. {
  1338. mTextBuffer.erase(mSelector.getCursorPos(), 1);
  1339. }
  1340. mSelector.setTextLength(mTextBuffer.length());
  1341. setText(mTextBuffer);
  1342. execConsoleCallback();
  1343. return true;
  1344. }
  1345. bool GuiTextEditCtrl::handleEscapeKey()
  1346. {
  1347. if(isMethod("onEscape"))
  1348. Con::executef(this, 1, "onEscape");
  1349. bool preventDefault = false;
  1350. if (mEscapeCommand && mEscapeCommand[0])
  1351. {
  1352. preventDefault = Con::evaluate(mEscapeCommand);
  1353. }
  1354. if(!preventDefault)
  1355. {
  1356. setText(mTextOnFocus);
  1357. GuiControl* parent = getParent();
  1358. if (parent)
  1359. {
  1360. parent->onFocus(false);
  1361. }
  1362. }
  1363. return true;
  1364. }
  1365. bool GuiTextEditCtrl::handleEnterKey()
  1366. {
  1367. if (isMethod("onReturn"))
  1368. Con::executef(this, 1, "onReturn");
  1369. bool preventDefault = false;
  1370. if (mReturnCommand && mReturnCommand[0])
  1371. {
  1372. preventDefault = Con::evaluate(mReturnCommand);
  1373. }
  1374. if (mReturnCausesTab)
  1375. {
  1376. tabNext();
  1377. }
  1378. else if (!preventDefault)
  1379. {
  1380. GuiControl* parent = getParent();
  1381. if (parent)
  1382. {
  1383. parent->onFocus(false);
  1384. }
  1385. }
  1386. return true;
  1387. }
  1388. bool GuiTextEditCtrl::handleArrowKey(GuiDirection direction)
  1389. {
  1390. if (direction == GuiDirection::Left)
  1391. {
  1392. mSelector.setCursorAtEOL(false);
  1393. mSelector.stepCursorBackward();
  1394. }
  1395. else if (direction == GuiDirection::Right)
  1396. {
  1397. mSelector.setCursorAtEOL(false);
  1398. mSelector.stepCursorForward();
  1399. }
  1400. else if (direction == GuiDirection::Up)
  1401. {
  1402. S32 newCursorPos = getLineAdjustedIbeamPosition(-mProfile->getFont(mFontSizeAdjust)->getHeight());
  1403. if (newCursorPos == mSelector.getCursorPos())
  1404. {
  1405. newCursorPos = 0;
  1406. }
  1407. mSelector.setCursorPosition(newCursorPos);
  1408. }
  1409. else if (direction == GuiDirection::Down)
  1410. {
  1411. S32 newCursorPos = getLineAdjustedIbeamPosition(mProfile->getFont(mFontSizeAdjust)->getHeight());
  1412. if (newCursorPos == mSelector.getCursorPos())
  1413. {
  1414. newCursorPos = mTextBuffer.length();
  1415. }
  1416. mSelector.setCursorPosition(newCursorPos);
  1417. }
  1418. setUpdate();
  1419. mSelector.resetCursorBlink();
  1420. return true;
  1421. }
  1422. bool GuiTextEditCtrl::handleShiftArrowKey(GuiDirection direction)
  1423. {
  1424. if (direction == GuiDirection::Left)
  1425. {
  1426. mSelector.setCursorAtEOL(false);
  1427. modifySelectBlock(mSelector.getCursorPos() - 1);
  1428. }
  1429. else if (direction == GuiDirection::Right)
  1430. {
  1431. mSelector.setCursorAtEOL(false);
  1432. modifySelectBlock(mSelector.getCursorPos() + 1);
  1433. }
  1434. else if (direction == GuiDirection::Up)
  1435. {
  1436. S32 newCursorPos = getLineAdjustedIbeamPosition(-mProfile->getFont(mFontSizeAdjust)->getHeight());
  1437. if (newCursorPos == mSelector.getCursorPos())
  1438. {
  1439. newCursorPos = 0;
  1440. }
  1441. modifySelectBlock(newCursorPos);
  1442. }
  1443. else if (direction == GuiDirection::Down)
  1444. {
  1445. S32 newCursorPos = getLineAdjustedIbeamPosition(mProfile->getFont(mFontSizeAdjust)->getHeight());
  1446. if (newCursorPos == mSelector.getCursorPos())
  1447. {
  1448. newCursorPos = mTextBuffer.length();
  1449. }
  1450. modifySelectBlock(newCursorPos);
  1451. }
  1452. setUpdate();
  1453. mSelector.resetCursorBlink();
  1454. return true;
  1455. }
  1456. S32 GuiTextEditCtrl::getLineAdjustedIbeamPosition(S32 heightAdjustment)
  1457. {
  1458. Point2I centerPoint = mSelector.getCursorCenter();
  1459. centerPoint.y += heightAdjustment;
  1460. return calculateIbeamPosition(centerPoint);
  1461. }
  1462. void GuiTextEditCtrl::modifySelectBlock(const U32 target)
  1463. {
  1464. mSelector.setTextLength(mTextBuffer.length());
  1465. mSelector.selectTo(target);
  1466. setUpdate();
  1467. }
  1468. void GuiTextEditCtrl::selectAllText()
  1469. {
  1470. mSelector.setCursorPosition(0);
  1471. modifySelectBlock(mTextBuffer.length());
  1472. }
  1473. void GuiTextEditCtrl::getCursor(GuiCursor*& cursor, bool& showCursor, const GuiEvent& lastGuiEvent)
  1474. {
  1475. if (mEditCursor == NULL)
  1476. {
  1477. SimObject* obj;
  1478. obj = Sim::findObject("EditCursor");
  1479. mEditCursor = dynamic_cast<GuiCursor*>(obj);
  1480. }
  1481. if (mEditCursor != NULL)
  1482. {
  1483. cursor = mEditCursor;
  1484. }
  1485. }
  1486. #pragma endregion