guiTextEditCtrl.cc 45 KB

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