guiTextEditCtrl.cc 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676
  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)
  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);
  59. movingStartPoint.x += renderTextSection(movingStartPoint, lengthOfPreBlockText, lengthOfHighlightBlockText, profile, currentState, font, true);
  60. movingStartPoint.x += renderTextSection(movingStartPoint, lengthOfPreBlockText + lengthOfHighlightBlockText, lengthOfPostBlockText, profile, currentState, font);
  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)
  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. dglSetBitmapModulation(profile->mFontColorTextSL);
  79. RectI highlightRect = RectI(pointToDraw.x, pointToDraw.y, blockStrWidth, mGlobalBounds.extent.y);
  80. dglDrawRectFill(highlightRect, profile->mFillColorTextSL);
  81. }
  82. else
  83. {
  84. const ColorI& fontColor = profile->getFontColor(currentState);
  85. dglSetBitmapModulation(fontColor);
  86. }
  87. dglDrawText(font, pointToDraw, sectionText.c_str(), profile->mFontColors);
  88. return blockStrWidth;
  89. }
  90. return 0;
  91. }
  92. void GuiTextEditTextBlock::performScrollJumpX(const S32 targetX, const S32 areaStart, const S32 areaEnd)
  93. {
  94. S32 diff = 0;
  95. if (targetX < areaStart)
  96. {
  97. diff = targetX - areaStart;
  98. }
  99. else if (targetX > areaEnd)
  100. {
  101. diff = targetX - areaEnd;
  102. }
  103. mTextScrollX += diff;
  104. }
  105. U32 GuiTextEditTextBlock::calculateIbeamPositionInLine(const S32 targetX, GFont* font)
  106. {
  107. if (mText.length() == 0)
  108. return mLineStartIbeamValue;
  109. S32 curX = getGlobalTextStart().x;
  110. U32 result = mText.length();
  111. for (U32 count = 0; count < mText.length(); count++)
  112. {
  113. char c = mText[count];
  114. if (!font->isValidChar(c))
  115. continue;
  116. S32 backDiff = mAbs(curX - targetX);
  117. curX += font->getCharXIncrement(c);
  118. if (curX > targetX)
  119. {
  120. S32 forwardDiff = mAbs(curX - targetX);
  121. if (backDiff < forwardDiff)
  122. result = count;
  123. else
  124. result = count + 1;
  125. break;
  126. }
  127. }
  128. return result;
  129. }
  130. void GuiTextEditTextBlock::processScrollVelocity(const S32 delta, const S32 extentX, GFont* font)
  131. {
  132. U32 max = font->getStrWidth(mText.c_str()) - extentX;
  133. mTextScrollX = mClamp(mTextScrollX + delta, 0, max);
  134. }
  135. void GuiTextEditTextBlock::processTextAlignment(const string line, GFont* font, AlignmentType align)
  136. {
  137. if (align == AlignmentType::LeftAlign ||
  138. mGlobalBounds.extent.x < font->getStrWidth(line.c_str()))
  139. {
  140. mTextOffsetX = 0;
  141. }
  142. else if (align == AlignmentType::RightAlign)
  143. {
  144. mTextOffsetX = mGlobalBounds.extent.x - font->getStrWidth(line.c_str());
  145. }
  146. else if (align == AlignmentType::CenterAlign)
  147. {
  148. mTextOffsetX = (S32)mRound((mGlobalBounds.extent.x - font->getStrWidth(line.c_str())) / 2);
  149. }
  150. }
  151. #pragma endregion
  152. #pragma region GuiTextEditSelection
  153. GuiTextEditSelection::GuiTextEditSelection()
  154. {
  155. mBlockStart = 0;
  156. mBlockEnd = 0;
  157. mCursorPos = 0;
  158. mCursorOn = false;
  159. mNumFramesElapsed = 0;
  160. mCursorAtEOL = false;
  161. mIsFirstResponder = false;
  162. mGlobalUnadjustedCursorRect.set(0, 0, 0, 0);
  163. mCursorRendered = false;
  164. mNumFramesElapsed = 0;
  165. mTimeLastCursorFlipped = 0;
  166. mCursorOn = false;
  167. }
  168. bool GuiTextEditSelection::renderIbeam(const Point2I& startPoint, const Point2I& extent, const string line, const U32 start, const U32 end, GuiControlProfile* profile, GFont* font)
  169. {
  170. if (!mIsFirstResponder || !mCursorOn ||
  171. (mCursorAtEOL && mCursorPos == start && mCursorPos != 0) ||
  172. (!mCursorAtEOL && mCursorPos == end && mCursorPos != mTextLength) ||
  173. (mCursorPos < start || mCursorPos > end))
  174. {
  175. return false;
  176. }
  177. string blockText = line.substr(0, mCursorPos - start);
  178. U32 blockStrWidth = font->getStrWidth(blockText.c_str());
  179. RectI ibeamRect = RectI(startPoint.x + blockStrWidth - 1, startPoint.y, 2, extent.y);
  180. setCursorRect(ibeamRect);
  181. RectI clipRect = dglGetClipRect();
  182. if (clipRect.point.x > ibeamRect.point.x)
  183. {
  184. ibeamRect.point.x = clipRect.point.x;
  185. }
  186. else if ((clipRect.point.x + clipRect.extent.x) < (ibeamRect.point.x + ibeamRect.extent.x))
  187. {
  188. ibeamRect.point.x = (clipRect.point.x + clipRect.extent.x) - ibeamRect.extent.x;
  189. }
  190. dglDrawRectFill(ibeamRect, profile->mCursorColor);
  191. return true;
  192. }
  193. void GuiTextEditSelection::selectTo(const U32 target)
  194. {
  195. S32 safeTarget = mClamp(target, 0, mTextLength);
  196. if (mBlockStart == mBlockEnd)
  197. {
  198. mBlockAnchor = mBlockStart = mBlockEnd = mCursorPos;
  199. }
  200. if (safeTarget > mBlockAnchor)
  201. {
  202. mBlockStart = mBlockAnchor;
  203. mBlockEnd = mCursorPos = safeTarget;
  204. }
  205. else if (safeTarget < mBlockAnchor)
  206. {
  207. mBlockStart = mCursorPos = safeTarget;
  208. mBlockEnd = mBlockAnchor;
  209. }
  210. else
  211. {
  212. mCursorPos = mBlockStart = mBlockEnd = safeTarget;
  213. }
  214. }
  215. void GuiTextEditSelection::eraseSelection(string& fullText)
  216. {
  217. if (hasSelection())
  218. {
  219. fullText.erase(mBlockStart, mBlockEnd - mBlockStart);
  220. mCursorPos = mBlockStart;
  221. mTextLength = fullText.length();
  222. clearSelection();
  223. }
  224. }
  225. void GuiTextEditSelection::onPreRender(const U32 time)
  226. {
  227. if (mIsFirstResponder)
  228. {
  229. U32 timeElapsed = time - mTimeLastCursorFlipped;
  230. mNumFramesElapsed++;
  231. if ((timeElapsed > 400) && (mNumFramesElapsed > 3))
  232. {
  233. mCursorOn = !mCursorOn;
  234. mTimeLastCursorFlipped = time;
  235. mNumFramesElapsed = 0;
  236. }
  237. }
  238. }
  239. void GuiTextEditSelection::resetCursorBlink()
  240. {
  241. mCursorOn = true;
  242. mNumFramesElapsed = 0;
  243. mTimeLastCursorFlipped = Platform::getVirtualMilliseconds();
  244. }
  245. void GuiTextEditSelection::selectWholeWord(const string& text)
  246. {
  247. bool selectingSpace = (mCursorPos < text.length() && text[mCursorPos] == ' ');
  248. for (S32 i = mCursorPos; i >= 0; i--)
  249. {
  250. if (i == 0)
  251. {
  252. mBlockStart = 0;
  253. break;
  254. }
  255. if ((!selectingSpace && text[i - 1] == ' ') ||
  256. (selectingSpace && text[i - 1] != ' '))
  257. {
  258. mBlockStart = i;
  259. break;
  260. }
  261. }
  262. mBlockAnchor = mBlockStart;
  263. bool foundSpace = false;
  264. for (S32 j = mCursorPos; j <= (text.length() + 1); j++)
  265. {
  266. if (j == (text.length() + 1))
  267. {
  268. mBlockEnd = j;
  269. break;
  270. }
  271. if (!foundSpace && text[j] == ' ')
  272. {
  273. foundSpace = true;
  274. }
  275. else if (foundSpace && text[j] != ' ')
  276. {
  277. mBlockEnd = j;
  278. break;
  279. }
  280. }
  281. mCursorPos = mBlockEnd;
  282. mCursorAtEOL = true;
  283. }
  284. GuiTextEditSelection::GuiTextEditSelection(const GuiTextEditSelection& selector)
  285. {
  286. mBlockAnchor = selector.mBlockAnchor;
  287. mBlockStart = selector.mBlockStart;
  288. mBlockEnd = selector.mBlockEnd;
  289. mCursorPos = selector.mCursorPos;
  290. mCursorAtEOL = selector.mCursorAtEOL;
  291. mIsFirstResponder = selector.mIsFirstResponder;
  292. mGlobalUnadjustedCursorRect = selector.mGlobalUnadjustedCursorRect;
  293. mCursorRendered = selector.mCursorRendered;
  294. mTextLength = selector.mTextLength;
  295. mNumFramesElapsed = 0;
  296. mTimeLastCursorFlipped = Platform::getVirtualMilliseconds();
  297. mCursorOn = true;
  298. }
  299. void GuiTextEditSelection::stepCursorForward()
  300. {
  301. if (hasSelection())
  302. {
  303. setCursorPosition(mBlockEnd);
  304. }
  305. else
  306. {
  307. setCursorPosition(mCursorPos + 1);
  308. }
  309. }
  310. void GuiTextEditSelection::stepCursorBackward()
  311. {
  312. if (hasSelection())
  313. {
  314. setCursorPosition(mBlockStart);
  315. }
  316. else
  317. {
  318. setCursorPosition(mCursorPos - 1);
  319. }
  320. }
  321. #pragma endregion
  322. #pragma region GuiTextEditCtrl
  323. IMPLEMENT_CONOBJECT(GuiTextEditCtrl);
  324. U32 GuiTextEditCtrl::smNumAwake = 0;
  325. GuiTextEditCtrl::GuiTextEditCtrl()
  326. {
  327. mInsertOn = true;
  328. mMouseOver = false;
  329. mPasswordText = false;
  330. mReturnCausesTab = false;
  331. mSinkAllKeyEvents = false;
  332. mActive = true;
  333. mSelector = GuiTextEditSelection();
  334. mUndoSelector = GuiTextEditSelection();
  335. mUndoText = string();
  336. mTextOffsetY = 0;
  337. mReturnCommand = StringTable->EmptyString;
  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. mScrollVelocity = 0;
  346. }
  347. static EnumTable::Enums inputModeEnums[] =
  348. {
  349. { GuiTextEditCtrl::AllText, "AllText" },
  350. { GuiTextEditCtrl::Decimal, "Decimal" },
  351. { GuiTextEditCtrl::Number, "Number" },
  352. { GuiTextEditCtrl::Alpha, "Alpha" },
  353. { GuiTextEditCtrl::AlphaNumeric, "AlphaNumeric" }
  354. };
  355. static EnumTable gInputModeTable(5, &inputModeEnums[0]);
  356. void GuiTextEditCtrl::initPersistFields()
  357. {
  358. Parent::initPersistFields();
  359. addDepricatedField("validate");
  360. addDepricatedField("truncate");
  361. addDepricatedField("passwordMask");
  362. addDepricatedField("historySize");
  363. addDepricatedField("tabComplete");
  364. addGroup("Text Edit");
  365. addField("returnCommand", TypeString, Offset(mReturnCommand, GuiTextEditCtrl));
  366. addField("escapeCommand", TypeString, Offset(mEscapeCommand, GuiTextEditCtrl));
  367. addField("sinkAllKeyEvents", TypeBool, Offset(mSinkAllKeyEvents, GuiTextEditCtrl));
  368. addField("password", TypeBool, Offset(mPasswordText, GuiTextEditCtrl));
  369. addField("returnCausesTab", TypeBool, Offset(mReturnCausesTab, GuiTextEditCtrl));
  370. addProtectedField("maxLength", TypeS32, Offset(mMaxStrLen, GuiTextEditCtrl), &setMaxLengthProperty, &defaultProtectedGetFn, "The max number of characters that can be entered into the text edit box.");
  371. addProtectedField("inputMode", TypeEnum, Offset(mInputMode, GuiTextEditCtrl), &setInputMode, &getInputMode, &writeInputMode, 1, &gInputModeTable, "InputMode allows different characters to be entered.");
  372. addField("editCursor", TypeGuiCursor, Offset(mEditCursor, GuiTextEditCtrl));
  373. endGroup("Text Edit");
  374. }
  375. bool GuiTextEditCtrl::onAdd()
  376. {
  377. if ( ! Parent::onAdd() )
  378. return false;
  379. if( mText[0] )
  380. {
  381. setText(mText);
  382. }
  383. return true;
  384. }
  385. void GuiTextEditCtrl::onStaticModified(const char* slotName)
  386. {
  387. if(!dStricmp(slotName, "text"))
  388. setText(mText);
  389. }
  390. void GuiTextEditCtrl::inspectPostApply()
  391. {
  392. Parent::inspectPostApply();
  393. if (mTextID && *mTextID != 0)
  394. setTextID(mTextID);
  395. else
  396. setText(mText);
  397. }
  398. bool GuiTextEditCtrl::onWake()
  399. {
  400. if (! Parent::onWake())
  401. return false;
  402. if (mConsoleVariable[0])
  403. {
  404. const char *txt = Con::getVariable(mConsoleVariable);
  405. if (txt)
  406. {
  407. if (dStrlen(txt) > (U32)mMaxStrLen)
  408. {
  409. char* buf = new char[mMaxStrLen + 1];
  410. dStrncpy(buf, txt, mMaxStrLen);
  411. buf[mMaxStrLen] = 0;
  412. setScriptValue(buf);
  413. delete[] buf;
  414. }
  415. else
  416. setScriptValue(txt);
  417. }
  418. }
  419. // If this is the first awake text edit control, enable keyboard translation
  420. if (smNumAwake == 0)
  421. Platform::enableKeyboardTranslation();
  422. ++smNumAwake;
  423. mSuspendVerticalScrollJump = false;
  424. return true;
  425. }
  426. void GuiTextEditCtrl::onSleep()
  427. {
  428. Parent::onSleep();
  429. // If this is the last awake text edit control, disable keyboard translation
  430. --smNumAwake;
  431. if (smNumAwake == 0)
  432. Platform::disableKeyboardTranslation();
  433. }
  434. void GuiTextEditCtrl::execConsoleCallback()
  435. {
  436. setVariable(mTextBuffer.c_str());
  437. if ( mConsoleCommand[0] )
  438. {
  439. Con::evaluate( mConsoleCommand, false );
  440. }
  441. }
  442. const char* GuiTextEditCtrl::getText()
  443. {
  444. return mTextBuffer.c_str();
  445. }
  446. void GuiTextEditCtrl::setText( const UTF8 *txt )
  447. {
  448. setUpdate();
  449. enforceMaxLength();
  450. if (txt && txt[0] != 0)
  451. {
  452. Parent::setText(txt);
  453. mTextBuffer.assign(txt);
  454. }
  455. else
  456. mTextBuffer.clear();
  457. setVariable(mTextBuffer.c_str());
  458. }
  459. void GuiTextEditCtrl::setText( const UTF16* txt)
  460. {
  461. if(txt && txt[0] != 0)
  462. {
  463. UTF8* txt8 = convertUTF16toUTF8( txt );
  464. setText(txt8);
  465. delete[] txt8;
  466. }
  467. else
  468. {
  469. setText("");
  470. }
  471. }
  472. void GuiTextEditCtrl::enforceMaxLength()
  473. {
  474. int diff = mTextBuffer.length() - mMaxStrLen;
  475. if (diff > 0) {
  476. mTextBuffer.resize(mMaxStrLen);
  477. }
  478. }
  479. void GuiTextEditCtrl::setTextID(const char *id)
  480. {
  481. S32 n = Con::getIntVariable(id, -1);
  482. if (n != -1)
  483. {
  484. setTextID(n);
  485. }
  486. }
  487. void GuiTextEditCtrl::setTextID(S32 id)
  488. {
  489. const UTF8 *str = getGUIString(id);
  490. if (str)
  491. setText((const char*)str);
  492. }
  493. bool GuiTextEditCtrl::validate()
  494. {
  495. bool valid = true;
  496. if (isMethod("onValidate"))
  497. {
  498. valid = dAtob(Con::executef(this, 2, "onValidate"));
  499. }
  500. return valid;
  501. }
  502. const RectI GuiTextEditCtrl::getGlobalInnerRect()
  503. {
  504. Point2I offset = Point2I(mBounds.point.Zero);
  505. Point2I extent = Point2I(getExtent());
  506. RectI innerRect = getInnerRect(offset, extent, SelectedState, mProfile);
  507. Point2I globalCtrlOffset = localToGlobalCoord(innerRect.point);
  508. RectI globalInnerRect(globalCtrlOffset, innerRect.extent);
  509. return globalInnerRect;
  510. }
  511. S32 GuiTextEditCtrl::calculateIbeamPosition(const Point2I& globalMousePoint)
  512. {
  513. if (mTextBuffer.length() == 0)
  514. return 0;
  515. RectI globalInnerRect = getGlobalInnerRect();
  516. return calculateIbeamPosition(globalMousePoint, globalInnerRect);
  517. }
  518. S32 GuiTextEditCtrl::calculateIbeamPosition(const Point2I& globalMousePoint, const RectI& globalInnerRect)
  519. {
  520. if (mTextBuffer.length() == 0 || mTextBlockList.size() == 0)
  521. return 0;
  522. string textBuffer = applyPasswordMasking();
  523. GFont* font = mProfile->getFont(mFontSizeAdjust);
  524. if (!mTextWrap)
  525. {
  526. return mTextBlockList.front().calculateIbeamPositionInLine(globalMousePoint.x, font);
  527. }
  528. else
  529. {
  530. RectI firstLineBounds = mTextBlockList.front().getGlobalBounds();
  531. S32 textStartY = firstLineBounds.point.y;
  532. if (textStartY > globalMousePoint.y)
  533. return 0;
  534. U32 height = firstLineBounds.extent.y;
  535. if ((textStartY + (mTextBlockList.size() * height)) < globalMousePoint.y)
  536. return mTextBuffer.length();
  537. S32 curY = textStartY;
  538. for (auto block : mTextBlockList)
  539. {
  540. curY += height;
  541. if (curY > globalMousePoint.y)
  542. {
  543. U32 pos = block.calculateIbeamPositionInLine(globalMousePoint.x, font);
  544. mSelector.setCursorAtEOL(block.calculateCursorAtEOL(pos));
  545. return pos + block.getStartValue();
  546. }
  547. }
  548. mSelector.setCursorAtEOL(true);
  549. return mTextBlockList.back().calculateIbeamPositionInLine(globalMousePoint.x, font);
  550. }
  551. }
  552. void GuiTextEditCtrl::onTouchDown( const GuiEvent &event )
  553. {
  554. mScrollVelocity = 0;
  555. mSuspendVerticalScrollJump = false;
  556. if (!mVisible || !mAwake)
  557. return;
  558. mSelector.setTextLength(mTextBuffer.length());
  559. if(event.mouseClickCount > 2)
  560. {
  561. selectAllText();
  562. }
  563. else if(event.mouseClickCount > 1)
  564. {
  565. mSelector.selectWholeWord(mTextBuffer);
  566. }
  567. else
  568. {
  569. S32 newCursorPos = calculateIbeamPosition(event.mousePoint);
  570. if (event.modifier & SI_SHIFT)
  571. {
  572. modifySelectBlock(newCursorPos);
  573. }
  574. else
  575. {
  576. mSelector.setCursorPosition(newCursorPos);
  577. }
  578. }
  579. mouseLock();
  580. setFirstResponder();
  581. mSelector.resetCursorBlink();
  582. if( isMethod("onTouchDown") )
  583. {
  584. char buf[3][32];
  585. dSprintf(buf[0], 32, "%d", event.modifier);
  586. dSprintf(buf[1], 32, "%d %d", event.mousePoint.x, event.mousePoint.y);
  587. dSprintf(buf[2], 32, "%d", event.mouseClickCount);
  588. Con::executef(this, 4, "onTouchDown", buf[0], buf[1], buf[2]);
  589. }
  590. }
  591. void GuiTextEditCtrl::onTouchDragged( const GuiEvent &event )
  592. {
  593. if (!mVisible || !mAwake)
  594. return;
  595. mSuspendVerticalScrollJump = false;
  596. RectI globalInnerRect = getGlobalInnerRect();
  597. adjustScrollVelocity(event.mousePoint, globalInnerRect);
  598. if ((mTextWrap && event.mousePoint.y < globalInnerRect.point.y) ||
  599. (!mTextWrap && event.mousePoint.x < globalInnerRect.point.x))
  600. {
  601. modifySelectBlock(0);
  602. }
  603. else if ((mTextWrap && event.mousePoint.y > (globalInnerRect.point.y + globalInnerRect.extent.y)) ||
  604. (!mTextWrap && event.mousePoint.x > (globalInnerRect.point.x + globalInnerRect.extent.x)))
  605. {
  606. modifySelectBlock(mTextBuffer.length());
  607. }
  608. else
  609. {
  610. modifySelectBlock(calculateIbeamPosition(event.mousePoint, globalInnerRect));
  611. }
  612. // Notify Script.
  613. if( isMethod("onTouchDragged") )
  614. {
  615. char buf[3][32];
  616. dSprintf(buf[0], 32, "%d", event.modifier);
  617. dSprintf(buf[1], 32, "%d %d", event.mousePoint.x, event.mousePoint.y);
  618. dSprintf(buf[2], 32, "%d", event.mouseClickCount);
  619. Con::executef(this, 4, "onTouchDragged", buf[0], buf[1], buf[2]);
  620. }
  621. }
  622. void GuiTextEditCtrl::onTouchUp(const GuiEvent &event)
  623. {
  624. mScrollVelocity = 0;
  625. mSuspendVerticalScrollJump = false;
  626. mouseUnlock();
  627. if (!mVisible || !mAwake)
  628. return;
  629. // Notify Script.
  630. if( isMethod("onTouchUp") )
  631. {
  632. char buf[3][32];
  633. dSprintf(buf[0], 32, "%d", event.modifier);
  634. dSprintf(buf[1], 32, "%d %d", event.mousePoint.x, event.mousePoint.y);
  635. dSprintf(buf[2], 32, "%d", event.mouseClickCount);
  636. Con::executef(this, 4, "onTouchUp", buf[0], buf[1], buf[2]);
  637. }
  638. }
  639. void GuiTextEditCtrl::onMouseWheelUp(const GuiEvent& event)
  640. {
  641. if (!mVisible || !mAwake)
  642. return;
  643. if(mTextWrap && mTextOffsetY > 0)
  644. {
  645. mScrollVelocity = 0;
  646. mSuspendVerticalScrollJump = true;
  647. mTextOffsetY = getMax(mTextOffsetY - static_cast<S32>(mProfile->getFont(mFontSizeAdjust)->getHeight()), 0);
  648. return;
  649. }
  650. GuiControl* parent = getParent();
  651. if (parent)
  652. parent->onMouseWheelUp(event);
  653. }
  654. void GuiTextEditCtrl::onMouseWheelDown(const GuiEvent& event)
  655. {
  656. if (!mVisible || !mAwake)
  657. return;
  658. U32 blockHeight = mTextBlockList.size() * mProfile->getFont(mFontSizeAdjust)->getHeight();
  659. RectI innerRect = getGlobalInnerRect();
  660. S32 max = blockHeight - innerRect.extent.y;
  661. if (mTextWrap && innerRect.extent.y < blockHeight && mTextOffsetY < max)
  662. {
  663. mScrollVelocity = 0;
  664. mSuspendVerticalScrollJump = true;
  665. mTextOffsetY = getMin(mTextOffsetY + static_cast<S32>(mProfile->getFont(mFontSizeAdjust)->getHeight()), max);
  666. return;
  667. }
  668. GuiControl* parent = getParent();
  669. if (parent)
  670. parent->onMouseWheelDown(event);
  671. }
  672. void GuiTextEditCtrl::onTouchEnter(const GuiEvent& event)
  673. {
  674. if (!mActive)
  675. return;
  676. mMouseOver = true;
  677. Con::executef(this, 1, "onTouchEnter");
  678. //update
  679. setUpdate();
  680. }
  681. void GuiTextEditCtrl::onTouchLeave(const GuiEvent& event)
  682. {
  683. if (!mActive)
  684. return;
  685. mMouseOver = false;
  686. Con::executef(this, 1, "onTouchLeave");
  687. //update
  688. setUpdate();
  689. }
  690. void GuiTextEditCtrl::saveUndoState()
  691. {
  692. //save the current state
  693. mUndoText = mTextBuffer;
  694. mUndoSelector = mSelector;
  695. }
  696. void GuiTextEditCtrl::onCopy(bool andCut)
  697. {
  698. // Don't copy/cut password field!
  699. if(mPasswordText)
  700. return;
  701. if (mSelector.hasSelection())
  702. {
  703. //save the current state
  704. saveUndoState();
  705. //copy the text to the clipboard
  706. string subString = mSelector.getSelection(mTextBuffer);
  707. Platform::setClipboard(subString.c_str());
  708. //if we pressed the cut shortcut, we need to cut the selected text from the control...
  709. if (andCut)
  710. {
  711. mSelector.eraseSelection(mTextBuffer);
  712. }
  713. mSelector.clearSelection();
  714. }
  715. }
  716. void GuiTextEditCtrl::onPaste()
  717. {
  718. //first, make sure there's something in the clipboard to copy...
  719. string clipboard = Platform::getClipboard();
  720. if(clipboard.length() <= 0)
  721. return;
  722. //save the current state
  723. saveUndoState();
  724. //delete anything hilited
  725. if (mSelector.hasSelection())
  726. {
  727. mSelector.eraseSelection(mTextBuffer);
  728. mSelector.clearSelection();
  729. }
  730. U32 pos = mSelector.getCursorPos();
  731. mTextBuffer.insert(pos, clipboard);
  732. setText(mTextBuffer);
  733. pos += clipboard.length();
  734. mSelector.setCursorPosition(pos);
  735. execConsoleCallback();
  736. }
  737. void GuiTextEditCtrl::onUndo()
  738. {
  739. string tempText = mTextBuffer;
  740. GuiTextEditSelection tempSelector = mSelector;
  741. mTextBuffer = mUndoText;
  742. mSelector = mUndoSelector;
  743. mUndoText = tempText;
  744. mUndoSelector = tempSelector;
  745. }
  746. bool GuiTextEditCtrl::onKeyDown(const GuiEvent &event)
  747. {
  748. if(! isActive())
  749. return false;
  750. mSuspendVerticalScrollJump = false;
  751. S32 stringLen = mTextBuffer.length();
  752. mSelector.setTextLength(stringLen);
  753. setUpdate();
  754. bool result = false;
  755. if (event.modifier & SI_SHIFT)
  756. {
  757. result = handleKeyDownWithShift(event);
  758. }
  759. else if (event.modifier & SI_CTRL)
  760. {
  761. //When holding the ctrl key, events must be handled here or passed up.
  762. return handleKeyDownWithCtrl(event);
  763. }
  764. else if (event.modifier & SI_ALT)
  765. {
  766. result = handleKeyDownWithAlt(event);
  767. #if (defined(TORQUE_OS_OSX) || defined(TORQUE_OS_IOS))
  768. //Likewise, the cmd key must be handled here or passed up.
  769. return result;
  770. #endif
  771. }
  772. if(result || (!result && handleKeyDownWithNoModifier(event)))
  773. {
  774. return true;
  775. }
  776. if (handleCharacterInput(event) || mSinkAllKeyEvents)
  777. {
  778. return true;
  779. }
  780. return Parent::onKeyDown( event );
  781. }
  782. bool GuiTextEditCtrl::tabNext()
  783. {
  784. if (isMethod("onTab"))
  785. Con::executef(this, 2, "onTab", "0");
  786. GuiCanvas *root = getRoot();
  787. if (root)
  788. {
  789. root->tabNext();
  790. return true;
  791. }
  792. return false;
  793. }
  794. bool GuiTextEditCtrl::tabPrev()
  795. {
  796. if (isMethod("onTab"))
  797. Con::executef(this, 2, "onTab", "1");
  798. GuiCanvas *root = getRoot();
  799. if (root)
  800. {
  801. root->tabPrev();
  802. return true;
  803. }
  804. return false;
  805. }
  806. void GuiTextEditCtrl::setFirstResponder()
  807. {
  808. mSelector.setFirstResponder(true);
  809. Parent::setFirstResponder();
  810. #if !defined(TORQUE_OS_IOS) && !defined(TORQUE_OS_ANDROID)
  811. Platform::enableKeyboardTranslation();
  812. #endif
  813. }
  814. void GuiTextEditCtrl::onLoseFirstResponder()
  815. {
  816. Platform::disableKeyboardTranslation();
  817. //execute the validate command
  818. bool valid = validate();
  819. if (valid)
  820. {
  821. execAltConsoleCallback();
  822. }
  823. if( isMethod( "onLoseFirstResponder" ) )
  824. Con::executef( this, 2, "onLoseFirstResponder", valid);
  825. mSelector.setFirstResponder(false);
  826. mTextOffsetY = 0;
  827. mScrollVelocity = 0;
  828. if (!mTextWrap && mTextBlockList.size() > 0)
  829. {
  830. mTextBlockList.front().resetScroll();
  831. }
  832. // Redraw the control:
  833. setUpdate();
  834. }
  835. void GuiTextEditCtrl::parentResized(const Point2I &oldParentExtent, const Point2I &newParentExtent)
  836. {
  837. Parent::parentResized( oldParentExtent, newParentExtent );
  838. mTextOffsetY = 0;
  839. if (!mTextWrap && mTextBlockList.size() > 0)
  840. {
  841. mTextBlockList.front().resetScroll();
  842. }
  843. }
  844. GuiControlState GuiTextEditCtrl::getCurrentState()
  845. {
  846. if (!mActive)
  847. return GuiControlState::DisabledState;
  848. else if (isFirstResponder())
  849. return GuiControlState::SelectedState;
  850. else if (mMouseOver)
  851. return GuiControlState::HighlightState;
  852. else
  853. return GuiControlState::NormalState;
  854. }
  855. const ColorI& GuiTextEditCtrl::getCurrentFontColor()
  856. {
  857. auto currentState = getCurrentState();
  858. return mProfile->getFontColor(currentState);
  859. }
  860. void GuiTextEditCtrl::onPreRender()
  861. {
  862. mSelector.onPreRender(Platform::getVirtualMilliseconds());
  863. processScrollVelocity();
  864. }
  865. void GuiTextEditCtrl::onRender(Point2I offset, const RectI & updateRect)
  866. {
  867. GuiControlState currentState = getCurrentState();
  868. RectI ctrlRect = applyMargins(offset, mBounds.extent, currentState, mProfile);
  869. renderUniversalRect(ctrlRect, mProfile, currentState);
  870. //Render Text
  871. RectI fillRect = applyBorders(ctrlRect.point, ctrlRect.extent, NormalState, mProfile);
  872. RectI contentRect = applyPadding(fillRect.point, fillRect.extent, NormalState, mProfile);
  873. if (contentRect.isValidRect())
  874. {
  875. if (currentState != SelectedState)
  876. mSelector.clearSelection();
  877. string textBuffer = applyPasswordMasking();
  878. renderText(contentRect.point, contentRect.extent, textBuffer.c_str(), mProfile);
  879. //Render the childen
  880. renderChildControls(offset, contentRect, updateRect);
  881. }
  882. }
  883. void GuiTextEditCtrl::renderLineList(const Point2I& offset, const Point2I& extent, const S32 startOffsetY, const vector<string> lineList, GuiControlProfile* profile, const TextRotationOptions rot)
  884. {
  885. GFont* font = profile->getFont(mFontSizeAdjust);
  886. const S32 textHeight = font->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, getAlignmentType(), font);
  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->getFont(mFontSizeAdjust)->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->getFont(mFontSizeAdjust));
  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 (mEscapeCommand && mEscapeCommand[0])
  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->getFont(mFontSizeAdjust))
  1260. return false;
  1261. if (mProfile->getFont(mFontSizeAdjust)->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. if (isMethod("onReturn"))
  1334. Con::executef(this, 1, "onReturn");
  1335. if (mReturnCausesTab)
  1336. {
  1337. tabNext();
  1338. }
  1339. if (mReturnCommand && mReturnCommand[0])
  1340. {
  1341. Con::evaluate(mReturnCommand);
  1342. }
  1343. return true;
  1344. }
  1345. bool GuiTextEditCtrl::handleArrowKey(GuiDirection direction)
  1346. {
  1347. if (direction == GuiDirection::Left)
  1348. {
  1349. mSelector.setCursorAtEOL(false);
  1350. mSelector.stepCursorBackward();
  1351. }
  1352. else if (direction == GuiDirection::Right)
  1353. {
  1354. mSelector.setCursorAtEOL(false);
  1355. mSelector.stepCursorForward();
  1356. }
  1357. else if (direction == GuiDirection::Up)
  1358. {
  1359. S32 newCursorPos = getLineAdjustedIbeamPosition(-mProfile->getFont(mFontSizeAdjust)->getHeight());
  1360. if (newCursorPos == mSelector.getCursorPos())
  1361. {
  1362. newCursorPos = 0;
  1363. }
  1364. mSelector.setCursorPosition(newCursorPos);
  1365. }
  1366. else if (direction == GuiDirection::Down)
  1367. {
  1368. S32 newCursorPos = getLineAdjustedIbeamPosition(mProfile->getFont(mFontSizeAdjust)->getHeight());
  1369. if (newCursorPos == mSelector.getCursorPos())
  1370. {
  1371. newCursorPos = mTextBuffer.length();
  1372. }
  1373. mSelector.setCursorPosition(newCursorPos);
  1374. }
  1375. setUpdate();
  1376. mSelector.resetCursorBlink();
  1377. return true;
  1378. }
  1379. bool GuiTextEditCtrl::handleShiftArrowKey(GuiDirection direction)
  1380. {
  1381. if (direction == GuiDirection::Left)
  1382. {
  1383. mSelector.setCursorAtEOL(false);
  1384. modifySelectBlock(mSelector.getCursorPos() - 1);
  1385. }
  1386. else if (direction == GuiDirection::Right)
  1387. {
  1388. mSelector.setCursorAtEOL(false);
  1389. modifySelectBlock(mSelector.getCursorPos() + 1);
  1390. }
  1391. else if (direction == GuiDirection::Up)
  1392. {
  1393. S32 newCursorPos = getLineAdjustedIbeamPosition(-mProfile->getFont(mFontSizeAdjust)->getHeight());
  1394. modifySelectBlock(newCursorPos);
  1395. }
  1396. else if (direction == GuiDirection::Down)
  1397. {
  1398. S32 newCursorPos = getLineAdjustedIbeamPosition(mProfile->getFont(mFontSizeAdjust)->getHeight());
  1399. modifySelectBlock(newCursorPos);
  1400. }
  1401. setUpdate();
  1402. mSelector.resetCursorBlink();
  1403. return true;
  1404. }
  1405. S32 GuiTextEditCtrl::getLineAdjustedIbeamPosition(S32 heightAdjustment)
  1406. {
  1407. Point2I centerPoint = mSelector.getCursorCenter();
  1408. centerPoint.y += heightAdjustment;
  1409. return calculateIbeamPosition(centerPoint);
  1410. }
  1411. void GuiTextEditCtrl::modifySelectBlock(const U32 target)
  1412. {
  1413. mSelector.setTextLength(mTextBuffer.length());
  1414. mSelector.selectTo(target);
  1415. setUpdate();
  1416. }
  1417. void GuiTextEditCtrl::selectAllText()
  1418. {
  1419. mSelector.setCursorPosition(0);
  1420. modifySelectBlock(mTextBuffer.length());
  1421. }
  1422. void GuiTextEditCtrl::getCursor(GuiCursor*& cursor, bool& showCursor, const GuiEvent& lastGuiEvent)
  1423. {
  1424. if (mEditCursor == NULL)
  1425. {
  1426. SimObject* obj;
  1427. obj = Sim::findObject("EditCursor");
  1428. mEditCursor = dynamic_cast<GuiCursor*>(obj);
  1429. }
  1430. if (mEditCursor != NULL)
  1431. {
  1432. cursor = mEditCursor;
  1433. }
  1434. }
  1435. #pragma endregion