guiTextEditCtrl.cc 45 KB

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