guiTextEditCtrl.cc 44 KB

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