guiTextEditCtrl.cc 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  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. }
  350. static EnumTable::Enums inputModeEnums[] =
  351. {
  352. { GuiTextEditCtrl::AllText, "AllText" },
  353. { GuiTextEditCtrl::Decimal, "Decimal" },
  354. { GuiTextEditCtrl::Number, "Number" },
  355. { GuiTextEditCtrl::Alpha, "Alpha" },
  356. { GuiTextEditCtrl::AlphaNumeric, "AlphaNumeric" }
  357. };
  358. static EnumTable gInputModeTable(5, &inputModeEnums[0]);
  359. void GuiTextEditCtrl::initPersistFields()
  360. {
  361. Parent::initPersistFields();
  362. addDepricatedField("validate");
  363. addDepricatedField("truncate");
  364. addDepricatedField("passwordMask");
  365. addDepricatedField("historySize");
  366. addDepricatedField("tabComplete");
  367. addGroup("Text Edit");
  368. addField("returnCommand", TypeString, Offset(mReturnCommand, GuiTextEditCtrl));
  369. addField("escapeCommand", TypeString, Offset(mEscapeCommand, GuiTextEditCtrl));
  370. addField("sinkAllKeyEvents", TypeBool, Offset(mSinkAllKeyEvents, GuiTextEditCtrl));
  371. addField("password", TypeBool, Offset(mPasswordText, GuiTextEditCtrl));
  372. addField("returnCausesTab", TypeBool, Offset(mReturnCausesTab, GuiTextEditCtrl));
  373. addProtectedField("maxLength", TypeS32, Offset(mMaxStrLen, GuiTextEditCtrl), &setMaxLengthProperty, &defaultProtectedGetFn, "The max number of characters that can be entered into the text edit box.");
  374. addProtectedField("inputMode", TypeEnum, Offset(mInputMode, GuiTextEditCtrl), &setInputMode, &getInputMode, &writeInputMode, 1, &gInputModeTable, "InputMode allows different characters to be entered.");
  375. addField("editCursor", TypeGuiCursor, Offset(mEditCursor, GuiTextEditCtrl));
  376. endGroup("Text Edit");
  377. }
  378. bool GuiTextEditCtrl::onAdd()
  379. {
  380. if ( ! Parent::onAdd() )
  381. return false;
  382. if( mText[0] )
  383. {
  384. setText(mText);
  385. }
  386. return true;
  387. }
  388. void GuiTextEditCtrl::onStaticModified(const char* slotName)
  389. {
  390. if(!dStricmp(slotName, "text"))
  391. setText(mText);
  392. }
  393. void GuiTextEditCtrl::inspectPostApply()
  394. {
  395. Parent::inspectPostApply();
  396. if (mTextID && *mTextID != 0)
  397. setTextID(mTextID);
  398. else
  399. setText(mText);
  400. }
  401. bool GuiTextEditCtrl::onWake()
  402. {
  403. if (! Parent::onWake())
  404. return false;
  405. if (mConsoleVariable[0])
  406. {
  407. const char *txt = Con::getVariable(mConsoleVariable);
  408. if (txt)
  409. {
  410. if (dStrlen(txt) > (U32)mMaxStrLen)
  411. {
  412. char* buf = new char[mMaxStrLen + 1];
  413. dStrncpy(buf, txt, mMaxStrLen);
  414. buf[mMaxStrLen] = 0;
  415. setScriptValue(buf);
  416. delete[] buf;
  417. }
  418. else
  419. setScriptValue(txt);
  420. }
  421. }
  422. // If this is the first awake text edit control, enable keyboard translation
  423. if (smNumAwake == 0)
  424. Platform::enableKeyboardTranslation();
  425. ++smNumAwake;
  426. mSuspendVerticalScrollJump = false;
  427. return true;
  428. }
  429. void GuiTextEditCtrl::onSleep()
  430. {
  431. Parent::onSleep();
  432. // If this is the last awake text edit control, disable keyboard translation
  433. --smNumAwake;
  434. if (smNumAwake == 0)
  435. Platform::disableKeyboardTranslation();
  436. }
  437. void GuiTextEditCtrl::execConsoleCallback()
  438. {
  439. setVariable(mTextBuffer.c_str());
  440. if ( mConsoleCommand[0] )
  441. {
  442. Con::evaluate( mConsoleCommand, false );
  443. }
  444. }
  445. const char* GuiTextEditCtrl::getText()
  446. {
  447. return mTextBuffer.c_str();
  448. }
  449. void GuiTextEditCtrl::setText( const UTF8 *txt )
  450. {
  451. setUpdate();
  452. enforceMaxLength();
  453. if (txt && txt[0] != 0)
  454. {
  455. Parent::setText(txt);
  456. mTextBuffer.assign(txt);
  457. }
  458. else
  459. mTextBuffer.clear();
  460. setVariable(mTextBuffer.c_str());
  461. }
  462. void GuiTextEditCtrl::setText( const UTF16* txt)
  463. {
  464. if(txt && txt[0] != 0)
  465. {
  466. UTF8* txt8 = convertUTF16toUTF8( txt );
  467. setText(txt8);
  468. delete[] txt8;
  469. }
  470. else
  471. {
  472. setText("");
  473. }
  474. }
  475. void GuiTextEditCtrl::enforceMaxLength()
  476. {
  477. int diff = mTextBuffer.length() - mMaxStrLen;
  478. if (diff > 0) {
  479. mTextBuffer.resize(mMaxStrLen);
  480. }
  481. }
  482. void GuiTextEditCtrl::setTextID(const char *id)
  483. {
  484. S32 n = Con::getIntVariable(id, -1);
  485. if (n != -1)
  486. {
  487. setTextID(n);
  488. }
  489. }
  490. void GuiTextEditCtrl::setTextID(S32 id)
  491. {
  492. const UTF8 *str = getGUIString(id);
  493. if (str)
  494. setText((const char*)str);
  495. }
  496. bool GuiTextEditCtrl::validate()
  497. {
  498. bool valid = true;
  499. if (isMethod("onValidate"))
  500. {
  501. valid = dAtob(Con::executef(this, 2, "onValidate"));
  502. }
  503. return valid;
  504. }
  505. const RectI GuiTextEditCtrl::getGlobalInnerRect()
  506. {
  507. Point2I offset = Point2I(mBounds.point.Zero);
  508. Point2I extent = Point2I(getExtent());
  509. RectI innerRect = getInnerRect(offset, extent, SelectedState, mProfile);
  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. mSelector.setTextLength(mTextBuffer.length());
  562. if(event.mouseClickCount > 2)
  563. {
  564. selectAllText();
  565. }
  566. else if(event.mouseClickCount > 1)
  567. {
  568. mSelector.selectWholeWord(mTextBuffer);
  569. }
  570. else
  571. {
  572. S32 newCursorPos = calculateIbeamPosition(event.mousePoint);
  573. if (event.modifier & SI_SHIFT)
  574. {
  575. modifySelectBlock(newCursorPos);
  576. }
  577. else
  578. {
  579. mSelector.setCursorPosition(newCursorPos);
  580. }
  581. }
  582. mouseLock();
  583. setFirstResponder();
  584. mSelector.resetCursorBlink();
  585. if( isMethod("onTouchDown") )
  586. {
  587. char buf[3][32];
  588. dSprintf(buf[0], 32, "%d", event.modifier);
  589. dSprintf(buf[1], 32, "%d %d", event.mousePoint.x, event.mousePoint.y);
  590. dSprintf(buf[2], 32, "%d", event.mouseClickCount);
  591. Con::executef(this, 4, "onTouchDown", buf[0], buf[1], buf[2]);
  592. }
  593. }
  594. void GuiTextEditCtrl::onTouchDragged( const GuiEvent &event )
  595. {
  596. if (!mVisible || !mAwake)
  597. return;
  598. mSuspendVerticalScrollJump = false;
  599. RectI globalInnerRect = getGlobalInnerRect();
  600. adjustScrollVelocity(event.mousePoint, globalInnerRect);
  601. if ((mTextWrap && event.mousePoint.y < globalInnerRect.point.y) ||
  602. (!mTextWrap && event.mousePoint.x < globalInnerRect.point.x))
  603. {
  604. modifySelectBlock(0);
  605. }
  606. else if ((mTextWrap && event.mousePoint.y > (globalInnerRect.point.y + globalInnerRect.extent.y)) ||
  607. (!mTextWrap && event.mousePoint.x > (globalInnerRect.point.x + globalInnerRect.extent.x)))
  608. {
  609. modifySelectBlock(mTextBuffer.length());
  610. }
  611. else
  612. {
  613. modifySelectBlock(calculateIbeamPosition(event.mousePoint, globalInnerRect));
  614. }
  615. // Notify Script.
  616. if( isMethod("onTouchDragged") )
  617. {
  618. char buf[3][32];
  619. dSprintf(buf[0], 32, "%d", event.modifier);
  620. dSprintf(buf[1], 32, "%d %d", event.mousePoint.x, event.mousePoint.y);
  621. dSprintf(buf[2], 32, "%d", event.mouseClickCount);
  622. Con::executef(this, 4, "onTouchDragged", buf[0], buf[1], buf[2]);
  623. }
  624. }
  625. void GuiTextEditCtrl::onTouchUp(const GuiEvent &event)
  626. {
  627. mScrollVelocity = 0;
  628. mSuspendVerticalScrollJump = false;
  629. mouseUnlock();
  630. if (!mVisible || !mAwake)
  631. return;
  632. // Notify Script.
  633. if( isMethod("onTouchUp") )
  634. {
  635. char buf[3][32];
  636. dSprintf(buf[0], 32, "%d", event.modifier);
  637. dSprintf(buf[1], 32, "%d %d", event.mousePoint.x, event.mousePoint.y);
  638. dSprintf(buf[2], 32, "%d", event.mouseClickCount);
  639. Con::executef(this, 4, "onTouchUp", buf[0], buf[1], buf[2]);
  640. }
  641. }
  642. void GuiTextEditCtrl::onMouseWheelUp(const GuiEvent& event)
  643. {
  644. if (!mVisible || !mAwake)
  645. return;
  646. if(mTextWrap && mTextOffsetY > 0)
  647. {
  648. mScrollVelocity = 0;
  649. mSuspendVerticalScrollJump = true;
  650. mTextOffsetY = getMax(mTextOffsetY - static_cast<S32>(mProfile->getFont(mFontSizeAdjust)->getHeight()), 0);
  651. return;
  652. }
  653. GuiControl* parent = getParent();
  654. if (parent)
  655. parent->onMouseWheelUp(event);
  656. }
  657. void GuiTextEditCtrl::onMouseWheelDown(const GuiEvent& event)
  658. {
  659. if (!mVisible || !mAwake)
  660. return;
  661. U32 blockHeight = mTextBlockList.size() * mProfile->getFont(mFontSizeAdjust)->getHeight();
  662. RectI innerRect = getGlobalInnerRect();
  663. S32 max = blockHeight - innerRect.extent.y;
  664. if (mTextWrap && innerRect.extent.y < blockHeight && mTextOffsetY < max)
  665. {
  666. mScrollVelocity = 0;
  667. mSuspendVerticalScrollJump = true;
  668. mTextOffsetY = getMin(mTextOffsetY + static_cast<S32>(mProfile->getFont(mFontSizeAdjust)->getHeight()), max);
  669. return;
  670. }
  671. GuiControl* parent = getParent();
  672. if (parent)
  673. parent->onMouseWheelDown(event);
  674. }
  675. void GuiTextEditCtrl::onTouchEnter(const GuiEvent& event)
  676. {
  677. if (!mActive)
  678. return;
  679. mMouseOver = true;
  680. Con::executef(this, 1, "onTouchEnter");
  681. //update
  682. setUpdate();
  683. }
  684. void GuiTextEditCtrl::onTouchLeave(const GuiEvent& event)
  685. {
  686. if (!mActive)
  687. return;
  688. mMouseOver = false;
  689. Con::executef(this, 1, "onTouchLeave");
  690. //update
  691. setUpdate();
  692. }
  693. void GuiTextEditCtrl::saveUndoState()
  694. {
  695. //save the current state
  696. mUndoText = mTextBuffer;
  697. mUndoSelector = mSelector;
  698. }
  699. void GuiTextEditCtrl::onCopy(bool andCut)
  700. {
  701. // Don't copy/cut password field!
  702. if(mPasswordText)
  703. return;
  704. if (mSelector.hasSelection())
  705. {
  706. //save the current state
  707. saveUndoState();
  708. //copy the text to the clipboard
  709. string subString = mSelector.getSelection(mTextBuffer);
  710. Platform::setClipboard(subString.c_str());
  711. //if we pressed the cut shortcut, we need to cut the selected text from the control...
  712. if (andCut)
  713. {
  714. mSelector.eraseSelection(mTextBuffer);
  715. }
  716. mSelector.clearSelection();
  717. }
  718. }
  719. void GuiTextEditCtrl::onPaste()
  720. {
  721. //first, make sure there's something in the clipboard to copy...
  722. string clipboard = Platform::getClipboard();
  723. if(clipboard.length() <= 0)
  724. return;
  725. //save the current state
  726. saveUndoState();
  727. //delete anything hilited
  728. if (mSelector.hasSelection())
  729. {
  730. mSelector.eraseSelection(mTextBuffer);
  731. mSelector.clearSelection();
  732. }
  733. U32 pos = mSelector.getCursorPos();
  734. mTextBuffer.insert(pos, clipboard);
  735. setText(mTextBuffer);
  736. pos += clipboard.length();
  737. mSelector.setCursorPosition(pos);
  738. execConsoleCallback();
  739. }
  740. void GuiTextEditCtrl::onUndo()
  741. {
  742. string tempText = mTextBuffer;
  743. GuiTextEditSelection tempSelector = mSelector;
  744. mTextBuffer = mUndoText;
  745. mSelector = mUndoSelector;
  746. mUndoText = tempText;
  747. mUndoSelector = tempSelector;
  748. }
  749. bool GuiTextEditCtrl::onKeyDown(const GuiEvent &event)
  750. {
  751. if(! isActive())
  752. return false;
  753. mSuspendVerticalScrollJump = false;
  754. S32 stringLen = mTextBuffer.length();
  755. mSelector.setTextLength(stringLen);
  756. setUpdate();
  757. bool result = false;
  758. if (event.modifier & SI_SHIFT)
  759. {
  760. result = handleKeyDownWithShift(event);
  761. }
  762. else if (event.modifier & SI_CTRL)
  763. {
  764. //When holding the ctrl key, events must be handled here or passed up.
  765. return handleKeyDownWithCtrl(event);
  766. }
  767. else if (event.modifier & SI_ALT)
  768. {
  769. result = handleKeyDownWithAlt(event);
  770. #if (defined(TORQUE_OS_OSX) || defined(TORQUE_OS_IOS))
  771. //Likewise, the cmd key must be handled here or passed up.
  772. return result;
  773. #endif
  774. }
  775. if(result || (!result && handleKeyDownWithNoModifier(event)))
  776. {
  777. return true;
  778. }
  779. if (handleCharacterInput(event) || mSinkAllKeyEvents)
  780. {
  781. return true;
  782. }
  783. return Parent::onKeyDown( event );
  784. }
  785. bool GuiTextEditCtrl::tabNext()
  786. {
  787. if (isMethod("onTab"))
  788. Con::executef(this, 2, "onTab", "0");
  789. GuiCanvas *root = getRoot();
  790. if (root)
  791. {
  792. root->tabNext();
  793. return true;
  794. }
  795. return false;
  796. }
  797. bool GuiTextEditCtrl::tabPrev()
  798. {
  799. if (isMethod("onTab"))
  800. Con::executef(this, 2, "onTab", "1");
  801. GuiCanvas *root = getRoot();
  802. if (root)
  803. {
  804. root->tabPrev();
  805. return true;
  806. }
  807. return false;
  808. }
  809. void GuiTextEditCtrl::setFirstResponder()
  810. {
  811. mSelector.setFirstResponder(true);
  812. Parent::setFirstResponder();
  813. #if !defined(TORQUE_OS_IOS) && !defined(TORQUE_OS_ANDROID)
  814. Platform::enableKeyboardTranslation();
  815. #endif
  816. }
  817. void GuiTextEditCtrl::onLoseFirstResponder()
  818. {
  819. Platform::disableKeyboardTranslation();
  820. //execute the validate command
  821. bool valid = validate();
  822. if (valid)
  823. {
  824. execAltConsoleCallback();
  825. }
  826. if( isMethod( "onLoseFirstResponder" ) )
  827. Con::executef( this, 2, "onLoseFirstResponder", valid);
  828. mSelector.setFirstResponder(false);
  829. mTextOffsetY = 0;
  830. mScrollVelocity = 0;
  831. if (!mTextWrap && mTextBlockList.size() > 0)
  832. {
  833. mTextBlockList.front().resetScroll();
  834. }
  835. // Redraw the control:
  836. setUpdate();
  837. }
  838. void GuiTextEditCtrl::parentResized(const Point2I &oldParentExtent, const Point2I &newParentExtent)
  839. {
  840. Parent::parentResized( oldParentExtent, newParentExtent );
  841. mTextOffsetY = 0;
  842. if (!mTextWrap && mTextBlockList.size() > 0)
  843. {
  844. mTextBlockList.front().resetScroll();
  845. }
  846. }
  847. GuiControlState GuiTextEditCtrl::getCurrentState()
  848. {
  849. if (!mActive)
  850. return GuiControlState::DisabledState;
  851. else if (isFirstResponder())
  852. return GuiControlState::SelectedState;
  853. else if (mMouseOver)
  854. return GuiControlState::HighlightState;
  855. else
  856. return GuiControlState::NormalState;
  857. }
  858. const ColorI& GuiTextEditCtrl::getCurrentFontColor()
  859. {
  860. auto currentState = getCurrentState();
  861. return mProfile->getFontColor(currentState);
  862. }
  863. void GuiTextEditCtrl::onPreRender()
  864. {
  865. mSelector.onPreRender(Platform::getVirtualMilliseconds());
  866. processScrollVelocity();
  867. }
  868. void GuiTextEditCtrl::onRender(Point2I offset, const RectI & updateRect)
  869. {
  870. GuiControlState currentState = getCurrentState();
  871. RectI ctrlRect = applyMargins(offset, mBounds.extent, currentState, mProfile);
  872. renderUniversalRect(ctrlRect, mProfile, currentState);
  873. //Render Text
  874. RectI fillRect = applyBorders(ctrlRect.point, ctrlRect.extent, NormalState, mProfile);
  875. RectI contentRect = applyPadding(fillRect.point, fillRect.extent, NormalState, mProfile);
  876. if (contentRect.isValidRect())
  877. {
  878. if (currentState != SelectedState)
  879. mSelector.clearSelection();
  880. string textBuffer = applyPasswordMasking();
  881. renderText(contentRect.point, contentRect.extent, textBuffer.c_str(), mProfile);
  882. //Render the childen
  883. renderChildControls(offset, contentRect, updateRect);
  884. }
  885. }
  886. void GuiTextEditCtrl::renderLineList(const Point2I& offset, const Point2I& extent, const S32 startOffsetY, const vector<string> lineList, GuiControlProfile* profile, const TextRotationOptions rot)
  887. {
  888. GFont* font = profile->getFont(mFontSizeAdjust);
  889. const S32 textHeight = font->getHeight();
  890. S32 totalWidth = extent.x;
  891. if (mTextBlockList.size() > lineList.size())
  892. {
  893. mTextBlockList.resize(lineList.size());
  894. }
  895. //Now print each line
  896. U32 ibeamPos = 0;
  897. S32 offsetY = startOffsetY - mTextOffsetY;
  898. for (U32 i = 0; i < lineList.size(); i++)
  899. {
  900. if(mTextBlockList.size() <= i)
  901. {
  902. mTextBlockList.push_back(GuiTextEditTextBlock());
  903. }
  904. Point2I start = Point2I(0, offsetY);
  905. Point2I blockExtent = Point2I(extent.x, textHeight);
  906. RectI blockBounds = RectI(start + offset + profile->mTextOffset, blockExtent);
  907. if (mOverrideFontColor)
  908. {
  909. dglSetBitmapModulation(getFontColor(profile, NormalState));
  910. }
  911. mTextBlockList[i].render(blockBounds, lineList[i], ibeamPos, mProfile, getCurrentState(), mSelector, getAlignmentType(), font, mOverrideFontColor);
  912. offsetY += textHeight;
  913. ibeamPos += lineList[i].length();
  914. }
  915. performScrollJumpY();
  916. }
  917. void GuiTextEditCtrl::processScrollVelocity()
  918. {
  919. if (mScrollVelocity == 0)
  920. {
  921. return;
  922. }
  923. U32 timeElapsed = Platform::getVirtualMilliseconds() - mTimeLastScrollProcess;
  924. S32 delta = mRound((F32)(timeElapsed * mScrollVelocity) / 1000);
  925. if (delta != 0)
  926. {
  927. RectI innerRect = getGlobalInnerRect();
  928. if (mTextWrap)
  929. {
  930. U32 max = (mTextBlockList.size() * mProfile->getFont(mFontSizeAdjust)->getHeight()) - innerRect.extent.y;
  931. mTextOffsetY = mClamp(mTextOffsetY + delta, 0, max);
  932. }
  933. else if(mTextBlockList.size() > 0)
  934. {
  935. mTextBlockList.front().processScrollVelocity(delta, innerRect.extent.x, mProfile->getFont(mFontSizeAdjust));
  936. }
  937. mTimeLastScrollProcess = Platform::getVirtualMilliseconds();
  938. S32 newCursorPos = calculateIbeamPosition(Canvas->getCursorPos());
  939. modifySelectBlock(newCursorPos);
  940. }
  941. }
  942. void GuiTextEditCtrl::performScrollJumpY()
  943. {
  944. if (mTextWrap && !mSuspendVerticalScrollJump && isFirstResponder() && mSelector.isCursorRendered())
  945. {
  946. RectI clipRect = dglGetClipRect();
  947. S32 areaStart = clipRect.point.y;
  948. S32 areaEnd = clipRect.point.y + clipRect.extent.y;
  949. RectI cursorRect = mSelector.getCursorRect();
  950. S32 lineTop = cursorRect.point.y;
  951. S32 lineBottom = lineTop + cursorRect.extent.y;
  952. S32 diff = 0;
  953. if (lineTop < areaStart)
  954. {
  955. diff = lineTop - areaStart;
  956. }
  957. else if (lineBottom > areaEnd)
  958. {
  959. diff = lineBottom - areaEnd;
  960. }
  961. mTextOffsetY += diff;
  962. }
  963. }
  964. void GuiTextEditCtrl::adjustScrollVelocity(const Point2I& globalMousePoint, const RectI& globalInnerRect)
  965. {
  966. RectI nonScrollArea = RectI(globalInnerRect);
  967. if (mTextWrap)
  968. {
  969. nonScrollArea.point.y += SCROLL_EDGE_SIZE;
  970. nonScrollArea.extent.y -= (2 * SCROLL_EDGE_SIZE);
  971. }
  972. else
  973. {
  974. nonScrollArea.point.x += SCROLL_EDGE_SIZE;
  975. nonScrollArea.extent.x -= (2 * SCROLL_EDGE_SIZE);
  976. }
  977. if (nonScrollArea.pointInRect(globalMousePoint))
  978. {
  979. mScrollVelocity = 0;
  980. }
  981. else if (globalInnerRect.pointInRect(globalMousePoint))
  982. {
  983. if (mScrollVelocity == 0)
  984. {
  985. mTimeLastScrollProcess = Platform::getVirtualMilliseconds();
  986. }
  987. mScrollVelocity = SCROLL_VELOCITY_PER_SEC;
  988. if ((mTextWrap && globalMousePoint.y < (globalInnerRect.point.y + SCROLL_EDGE_SIZE)) ||
  989. (!mTextWrap && globalMousePoint.x < (globalInnerRect.point.x + SCROLL_EDGE_SIZE)))
  990. {
  991. mScrollVelocity = -SCROLL_VELOCITY_PER_SEC;
  992. }
  993. }
  994. else
  995. {
  996. mScrollVelocity = 0;
  997. }
  998. }
  999. bool GuiTextEditCtrl::hasText()
  1000. {
  1001. return (mTextBuffer.length());
  1002. }
  1003. void GuiTextEditCtrl::keyDenied()
  1004. {
  1005. if (isMethod("onDenied"))
  1006. Con::executef(this, 1, "onDenied");
  1007. }
  1008. const char *GuiTextEditCtrl::getScriptValue()
  1009. {
  1010. return StringTable->insert(mTextBuffer.c_str());
  1011. }
  1012. void GuiTextEditCtrl::setScriptValue(const char *value)
  1013. {
  1014. mTextBuffer.assign(value);
  1015. mSelector.setTextLength(mTextBuffer.length());
  1016. }
  1017. GuiTextEditCtrl::InputMode GuiTextEditCtrl::getInputModeEnum(const char* label)
  1018. {
  1019. // Search for Mnemonic.
  1020. for (U32 i = 0; i < (sizeof(inputModeEnums) / sizeof(EnumTable::Enums)); i++)
  1021. {
  1022. if (dStricmp(inputModeEnums[i].label, label) == 0)
  1023. return (InputMode)inputModeEnums[i].index;
  1024. }
  1025. // Warn.
  1026. Con::warnf("GuiTextEditCtrl::getInputModeEnum() - Invalid mode of '%s'", label);
  1027. return (InputMode)-1;
  1028. }
  1029. const char* GuiTextEditCtrl::getInputModeDescription(const InputMode mode)
  1030. {
  1031. // Search for Mnemonic.
  1032. for (U32 i = 0; i < (sizeof(inputModeEnums) / sizeof(EnumTable::Enums)); i++)
  1033. {
  1034. if (inputModeEnums[i].index == mode)
  1035. return inputModeEnums[i].label;
  1036. }
  1037. // Warn.
  1038. Con::warnf("GuiTextEditCtrl::getInputModeDescription() - Invalid input mode.");
  1039. return StringTable->EmptyString;
  1040. }
  1041. //Returns true if valid, false if invalid
  1042. bool GuiTextEditCtrl::inputModeValidate(const U16 key, S32 cursorPos)
  1043. {
  1044. if (key == '-')
  1045. {
  1046. if (mInputMode == Alpha || mInputMode == AlphaNumeric)
  1047. {
  1048. return false;
  1049. }
  1050. else if (mInputMode == Decimal || mInputMode == Number)
  1051. {
  1052. //a minus sign only exists at the beginning, and only a single minus sign
  1053. if (cursorPos != 0 || (mInsertOn && mTextBuffer[0] == '-'))
  1054. {
  1055. return false;
  1056. }
  1057. }
  1058. }
  1059. else if (key >= '0' && key <= '9')
  1060. {
  1061. if (mInputMode == Alpha)
  1062. {
  1063. return false;
  1064. }
  1065. }
  1066. else if (key == '.')
  1067. {
  1068. if (mInputMode == Number || mInputMode == Alpha || mInputMode == AlphaNumeric)
  1069. {
  1070. return false;
  1071. }
  1072. else if (mInputMode == Decimal)
  1073. {
  1074. if (!mInsertOn && mTextBuffer[cursorPos] == '.')
  1075. {
  1076. return true;
  1077. }
  1078. const char* dot = dStrchr(mTextBuffer.c_str(), '.');
  1079. if (dot != NULL)
  1080. {
  1081. return false;
  1082. }
  1083. }
  1084. }
  1085. else if ((key >= 'A' && key <= 'Z') || (key >= 'a' && key <= 'z'))
  1086. {
  1087. if (mInputMode == Decimal || mInputMode == Number)
  1088. {
  1089. return false;
  1090. }
  1091. }
  1092. else if (key == 32)
  1093. {
  1094. if (mInputMode == Decimal || mInputMode == Number)
  1095. {
  1096. return false;
  1097. }
  1098. }
  1099. else if (mInputMode == Decimal || mInputMode == Number || mInputMode == Alpha || mInputMode == AlphaNumeric)
  1100. {
  1101. //The remaining characters only go with AllText
  1102. return false;
  1103. }
  1104. //Looks like we have a valid character!
  1105. return true;
  1106. }
  1107. void GuiTextEditCtrl::setMaxLength(S32 max)
  1108. {
  1109. mMaxStrLen = getMax(1, getMin(max, MAX_STRING_LENGTH));
  1110. }
  1111. void GuiTextEditCtrl::setInputMode(const InputMode mode)
  1112. {
  1113. if(mInputMode == mode)
  1114. return;
  1115. //Time to set the mode
  1116. mInputMode = mode;
  1117. //now let's parse that buffer and get rid of invalid characters
  1118. if (mode != AllText)
  1119. {
  1120. bool oldInsert = mInsertOn;
  1121. mInsertOn = false;
  1122. for (S32 i = 0; i < MAX_STRING_LENGTH; i++)
  1123. {
  1124. const UTF16 character = mTextBuffer[i];
  1125. if (character == '\0')
  1126. {
  1127. //Done and done.
  1128. break;
  1129. }
  1130. if (!inputModeValidate(character, i))
  1131. {
  1132. //Bad Character! Let's remove it.
  1133. mTextBuffer.erase(i, 1);
  1134. //Step it back
  1135. i--;
  1136. }
  1137. }
  1138. mInsertOn = oldInsert;
  1139. }
  1140. }
  1141. string GuiTextEditCtrl::applyPasswordMasking()
  1142. {
  1143. if (mPasswordText)
  1144. {
  1145. string passwordCover = string();
  1146. passwordCover.resize(mTextBuffer.length(), mPasswordMask[0]);
  1147. return passwordCover;
  1148. }
  1149. return mTextBuffer;
  1150. }
  1151. bool GuiTextEditCtrl::handleKeyDownWithShift(const GuiEvent& event)
  1152. {
  1153. switch (event.keyCode)
  1154. {
  1155. case KEY_TAB:
  1156. return tabPrev();
  1157. case KEY_HOME:
  1158. mSelector.selectTo(0);
  1159. return true;
  1160. case KEY_END:
  1161. mSelector.selectTo(mTextBuffer.length());
  1162. return true;
  1163. case KEY_LEFT:
  1164. return handleShiftArrowKey(GuiDirection::Left);
  1165. case KEY_RIGHT:
  1166. return handleShiftArrowKey(GuiDirection::Right);
  1167. case KEY_UP:
  1168. return handleShiftArrowKey(GuiDirection::Up);
  1169. case KEY_DOWN:
  1170. return handleShiftArrowKey(GuiDirection::Down);
  1171. }
  1172. return false;
  1173. }
  1174. bool GuiTextEditCtrl::handleKeyDownWithCtrl(const GuiEvent& event)
  1175. {
  1176. switch (event.keyCode)
  1177. {
  1178. #if !(defined(TORQUE_OS_OSX) || defined(TORQUE_OS_IOS))
  1179. // windows style cut / copy / paste / undo keybinds
  1180. case KEY_C:
  1181. case KEY_X:
  1182. onCopy(event.keyCode == KEY_X);
  1183. return true;
  1184. case KEY_V:
  1185. onPaste();
  1186. return true;
  1187. case KEY_Z:
  1188. onUndo();
  1189. return true;
  1190. #endif
  1191. case KEY_DELETE:
  1192. case KEY_BACKSPACE:
  1193. selectAllText();
  1194. handleBackSpace();
  1195. return true;
  1196. }
  1197. return false;
  1198. }
  1199. bool GuiTextEditCtrl::handleKeyDownWithAlt(const GuiEvent& event)
  1200. {
  1201. #if (defined(TORQUE_OS_OSX) || defined(TORQUE_OS_IOS))
  1202. // Added Mac cut/copy/paste/undo keys
  1203. // Mac command key maps to alt in torque.
  1204. switch(event.keyCode)
  1205. {
  1206. case KEY_C:
  1207. case KEY_X:
  1208. onCopy( event.keyCode==KEY_X );
  1209. return true;
  1210. case KEY_V:
  1211. onPaste();
  1212. return true;
  1213. case KEY_Z:
  1214. onUndo();
  1215. return true;
  1216. }
  1217. #endif
  1218. return false;
  1219. }
  1220. bool GuiTextEditCtrl::handleKeyDownWithNoModifier(const GuiEvent& event)
  1221. {
  1222. switch (event.keyCode)
  1223. {
  1224. case KEY_TAB:
  1225. return tabNext();
  1226. case KEY_ESCAPE:
  1227. if (mEscapeCommand && mEscapeCommand[0])
  1228. {
  1229. Con::evaluate(mEscapeCommand);
  1230. return true;
  1231. }
  1232. return false;
  1233. case KEY_RETURN:
  1234. case KEY_NUMPADENTER:
  1235. if (!validate())
  1236. {
  1237. return true;
  1238. }
  1239. return handleEnterKey();
  1240. case KEY_LEFT:
  1241. return handleArrowKey(GuiDirection::Left);
  1242. case KEY_RIGHT:
  1243. return handleArrowKey(GuiDirection::Right);
  1244. case KEY_UP:
  1245. return handleArrowKey(GuiDirection::Up);
  1246. case KEY_DOWN:
  1247. return handleArrowKey(GuiDirection::Down);
  1248. case KEY_DELETE:
  1249. return handleDelete();
  1250. case KEY_BACKSPACE:
  1251. return handleBackSpace();
  1252. case KEY_INSERT:
  1253. mInsertOn = !mInsertOn;
  1254. return true;
  1255. case KEY_HOME:
  1256. mSelector.setCursorPosition(0);
  1257. return true;
  1258. case KEY_END:
  1259. mSelector.setCursorPosition(mTextBuffer.length());
  1260. return true;
  1261. }
  1262. return false;
  1263. }
  1264. bool GuiTextEditCtrl::handleCharacterInput(const GuiEvent& event)
  1265. {
  1266. if (!mProfile->getFont(mFontSizeAdjust))
  1267. return false;
  1268. if (mProfile->getFont(mFontSizeAdjust)->isValidChar(event.ascii))
  1269. {
  1270. // Get the character ready to add to a UTF8 string.
  1271. string characterToInsert = string(1, event.ascii);
  1272. //Stop characters that aren't allowed based on InputMode
  1273. if (!inputModeValidate(event.ascii, mSelector.getCursorPos()))
  1274. {
  1275. keyDenied();
  1276. return true;
  1277. }
  1278. saveUndoState();
  1279. if (mSelector.hasSelection())
  1280. {
  1281. mSelector.eraseSelection(mTextBuffer);
  1282. }
  1283. if (mTextBuffer.length() < mMaxStrLen || !mInsertOn)
  1284. {
  1285. if (!mInsertOn)
  1286. {
  1287. mTextBuffer.erase(mSelector.getCursorPos(), 1);
  1288. }
  1289. mTextBuffer.insert(mSelector.getCursorPos(), characterToInsert);
  1290. mSelector.setTextLength(mTextBuffer.length());
  1291. mSelector.stepCursorForward();
  1292. setText(mTextBuffer);
  1293. }
  1294. else
  1295. keyDenied();
  1296. execConsoleCallback();
  1297. return true;
  1298. }
  1299. return false;
  1300. }
  1301. bool GuiTextEditCtrl::handleBackSpace()
  1302. {
  1303. if (mTextBuffer.length() == 0 || (mSelector.getCursorPos() == 0 && !mSelector.hasSelection()))
  1304. return true;
  1305. saveUndoState();
  1306. if (mSelector.hasSelection())
  1307. {
  1308. mSelector.eraseSelection(mTextBuffer);
  1309. }
  1310. else
  1311. {
  1312. mSelector.stepCursorBackward();
  1313. mTextBuffer.erase(mSelector.getCursorPos(), 1);
  1314. }
  1315. mSelector.setTextLength(mTextBuffer.length());
  1316. setText(mTextBuffer);
  1317. execConsoleCallback();
  1318. return true;
  1319. }
  1320. bool GuiTextEditCtrl::handleDelete()
  1321. {
  1322. if (mTextBuffer.length() == mSelector.getCursorPos() && !mSelector.hasSelection())
  1323. return true;
  1324. saveUndoState();
  1325. if (mSelector.hasSelection())
  1326. {
  1327. mSelector.eraseSelection(mTextBuffer);
  1328. }
  1329. else
  1330. {
  1331. mTextBuffer.erase(mSelector.getCursorPos(), 1);
  1332. }
  1333. mSelector.setTextLength(mTextBuffer.length());
  1334. setText(mTextBuffer);
  1335. execConsoleCallback();
  1336. return true;
  1337. }
  1338. bool GuiTextEditCtrl::handleEnterKey()
  1339. {
  1340. if (isMethod("onReturn"))
  1341. Con::executef(this, 1, "onReturn");
  1342. if (mReturnCausesTab)
  1343. {
  1344. tabNext();
  1345. }
  1346. if (mReturnCommand && mReturnCommand[0])
  1347. {
  1348. Con::evaluate(mReturnCommand);
  1349. }
  1350. return true;
  1351. }
  1352. bool GuiTextEditCtrl::handleArrowKey(GuiDirection direction)
  1353. {
  1354. if (direction == GuiDirection::Left)
  1355. {
  1356. mSelector.setCursorAtEOL(false);
  1357. mSelector.stepCursorBackward();
  1358. }
  1359. else if (direction == GuiDirection::Right)
  1360. {
  1361. mSelector.setCursorAtEOL(false);
  1362. mSelector.stepCursorForward();
  1363. }
  1364. else if (direction == GuiDirection::Up)
  1365. {
  1366. S32 newCursorPos = getLineAdjustedIbeamPosition(-mProfile->getFont(mFontSizeAdjust)->getHeight());
  1367. if (newCursorPos == mSelector.getCursorPos())
  1368. {
  1369. newCursorPos = 0;
  1370. }
  1371. mSelector.setCursorPosition(newCursorPos);
  1372. }
  1373. else if (direction == GuiDirection::Down)
  1374. {
  1375. S32 newCursorPos = getLineAdjustedIbeamPosition(mProfile->getFont(mFontSizeAdjust)->getHeight());
  1376. if (newCursorPos == mSelector.getCursorPos())
  1377. {
  1378. newCursorPos = mTextBuffer.length();
  1379. }
  1380. mSelector.setCursorPosition(newCursorPos);
  1381. }
  1382. setUpdate();
  1383. mSelector.resetCursorBlink();
  1384. return true;
  1385. }
  1386. bool GuiTextEditCtrl::handleShiftArrowKey(GuiDirection direction)
  1387. {
  1388. if (direction == GuiDirection::Left)
  1389. {
  1390. mSelector.setCursorAtEOL(false);
  1391. modifySelectBlock(mSelector.getCursorPos() - 1);
  1392. }
  1393. else if (direction == GuiDirection::Right)
  1394. {
  1395. mSelector.setCursorAtEOL(false);
  1396. modifySelectBlock(mSelector.getCursorPos() + 1);
  1397. }
  1398. else if (direction == GuiDirection::Up)
  1399. {
  1400. S32 newCursorPos = getLineAdjustedIbeamPosition(-mProfile->getFont(mFontSizeAdjust)->getHeight());
  1401. modifySelectBlock(newCursorPos);
  1402. }
  1403. else if (direction == GuiDirection::Down)
  1404. {
  1405. S32 newCursorPos = getLineAdjustedIbeamPosition(mProfile->getFont(mFontSizeAdjust)->getHeight());
  1406. modifySelectBlock(newCursorPos);
  1407. }
  1408. setUpdate();
  1409. mSelector.resetCursorBlink();
  1410. return true;
  1411. }
  1412. S32 GuiTextEditCtrl::getLineAdjustedIbeamPosition(S32 heightAdjustment)
  1413. {
  1414. Point2I centerPoint = mSelector.getCursorCenter();
  1415. centerPoint.y += heightAdjustment;
  1416. return calculateIbeamPosition(centerPoint);
  1417. }
  1418. void GuiTextEditCtrl::modifySelectBlock(const U32 target)
  1419. {
  1420. mSelector.setTextLength(mTextBuffer.length());
  1421. mSelector.selectTo(target);
  1422. setUpdate();
  1423. }
  1424. void GuiTextEditCtrl::selectAllText()
  1425. {
  1426. mSelector.setCursorPosition(0);
  1427. modifySelectBlock(mTextBuffer.length());
  1428. }
  1429. void GuiTextEditCtrl::getCursor(GuiCursor*& cursor, bool& showCursor, const GuiEvent& lastGuiEvent)
  1430. {
  1431. if (mEditCursor == NULL)
  1432. {
  1433. SimObject* obj;
  1434. obj = Sim::findObject("EditCursor");
  1435. mEditCursor = dynamic_cast<GuiCursor*>(obj);
  1436. }
  1437. if (mEditCursor != NULL)
  1438. {
  1439. cursor = mEditCursor;
  1440. }
  1441. }
  1442. #pragma endregion