No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TMP_InputField.cs 179KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796
  1. //#define TMP_DEBUG_MODE
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Threading;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using UnityEngine;
  9. using UnityEngine.UI;
  10. using UnityEngine.Events;
  11. using UnityEngine.EventSystems;
  12. using UnityEngine.Serialization;
  13. namespace TMPro
  14. {
  15. /// <summary>
  16. /// Editable text input field.
  17. /// </summary>
  18. [AddComponentMenu("UI/TextMeshPro - Input Field", 11)]
  19. [HelpURL("https://docs.unity3d.com/Packages/com.unity.textmeshpro@3.2")]
  20. public class TMP_InputField : Selectable,
  21. IUpdateSelectedHandler,
  22. IBeginDragHandler,
  23. IDragHandler,
  24. IEndDragHandler,
  25. IPointerClickHandler,
  26. ISubmitHandler,
  27. ICancelHandler,
  28. ICanvasElement,
  29. ILayoutElement,
  30. IScrollHandler
  31. {
  32. // Setting the content type acts as a shortcut for setting a combination of InputType, CharacterValidation, LineType, and TouchScreenKeyboardType
  33. public enum ContentType
  34. {
  35. Standard,
  36. Autocorrected,
  37. IntegerNumber,
  38. DecimalNumber,
  39. Alphanumeric,
  40. Name,
  41. EmailAddress,
  42. Password,
  43. Pin,
  44. Custom
  45. }
  46. public enum InputType
  47. {
  48. Standard,
  49. AutoCorrect,
  50. Password,
  51. }
  52. public enum CharacterValidation
  53. {
  54. None,
  55. Digit,
  56. Integer,
  57. Decimal,
  58. Alphanumeric,
  59. Name,
  60. Regex,
  61. EmailAddress,
  62. CustomValidator
  63. }
  64. public enum LineType
  65. {
  66. SingleLine,
  67. MultiLineSubmit,
  68. MultiLineNewline
  69. }
  70. public delegate char OnValidateInput(string text, int charIndex, char addedChar);
  71. [Serializable]
  72. public class SubmitEvent : UnityEvent<string> { }
  73. [Serializable]
  74. public class OnChangeEvent : UnityEvent<string> { }
  75. [Serializable]
  76. public class SelectionEvent : UnityEvent<string> { }
  77. [Serializable]
  78. public class TextSelectionEvent : UnityEvent<string, int, int> { }
  79. [Serializable]
  80. public class TouchScreenKeyboardEvent : UnityEvent<TouchScreenKeyboard.Status> { }
  81. protected TouchScreenKeyboard m_SoftKeyboard;
  82. static private readonly char[] kSeparators = { ' ', '.', ',', '\t', '\r', '\n' };
  83. #if UNITY_ANDROID
  84. static private bool s_IsQuestDeviceEvaluated = false;
  85. #endif // if UNITY_ANDROID
  86. static private bool s_IsQuestDevice = false;
  87. #region Exposed properties
  88. /// <summary>
  89. /// Text Text used to display the input's value.
  90. /// </summary>
  91. protected RectTransform m_RectTransform;
  92. [SerializeField]
  93. protected RectTransform m_TextViewport;
  94. protected RectMask2D m_TextComponentRectMask;
  95. protected RectMask2D m_TextViewportRectMask;
  96. //private Rect m_CachedViewportRect;
  97. [SerializeField]
  98. protected TMP_Text m_TextComponent;
  99. protected RectTransform m_TextComponentRectTransform;
  100. [SerializeField]
  101. protected Graphic m_Placeholder;
  102. [SerializeField]
  103. protected Scrollbar m_VerticalScrollbar;
  104. [SerializeField]
  105. protected TMP_ScrollbarEventHandler m_VerticalScrollbarEventHandler;
  106. //private bool m_ForceDeactivation;
  107. private bool m_IsDrivenByLayoutComponents = false;
  108. [SerializeField]
  109. private LayoutGroup m_LayoutGroup;
  110. private IScrollHandler m_IScrollHandlerParent;
  111. /// <summary>
  112. /// Used to keep track of scroll position
  113. /// </summary>
  114. private float m_ScrollPosition;
  115. /// <summary>
  116. ///
  117. /// </summary>
  118. [SerializeField]
  119. protected float m_ScrollSensitivity = 1.0f;
  120. //[SerializeField]
  121. //protected TMP_Text m_PlaceholderTextComponent;
  122. [SerializeField]
  123. private ContentType m_ContentType = ContentType.Standard;
  124. /// <summary>
  125. /// Type of data expected by the input field.
  126. /// </summary>
  127. [SerializeField]
  128. private InputType m_InputType = InputType.Standard;
  129. /// <summary>
  130. /// The character used to hide text in password field.
  131. /// </summary>
  132. [SerializeField]
  133. private char m_AsteriskChar = '*';
  134. /// <summary>
  135. /// Keyboard type applies to mobile keyboards that get shown.
  136. /// </summary>
  137. [SerializeField]
  138. private TouchScreenKeyboardType m_KeyboardType = TouchScreenKeyboardType.Default;
  139. [SerializeField]
  140. private LineType m_LineType = LineType.SingleLine;
  141. /// <summary>
  142. /// Should hide mobile input field part of the virtual keyboard.
  143. /// </summary>
  144. [SerializeField]
  145. private bool m_HideMobileInput = false;
  146. /// <summary>
  147. /// Should hide soft / virtual keyboard.
  148. /// </summary>
  149. [SerializeField]
  150. private bool m_HideSoftKeyboard = false;
  151. /// <summary>
  152. /// What kind of validation to use with the input field's data.
  153. /// </summary>
  154. [SerializeField]
  155. private CharacterValidation m_CharacterValidation = CharacterValidation.None;
  156. /// <summary>
  157. /// The Regex expression used for validating the text input.
  158. /// </summary>
  159. [SerializeField]
  160. private string m_RegexValue = string.Empty;
  161. /// <summary>
  162. /// The point sized used by the placeholder and input text object.
  163. /// </summary>
  164. [SerializeField]
  165. private float m_GlobalPointSize = 14;
  166. /// <summary>
  167. /// Maximum number of characters allowed before input no longer works.
  168. /// </summary>
  169. [SerializeField]
  170. private int m_CharacterLimit = 0;
  171. /// <summary>
  172. /// Event delegates triggered when the input field submits its data.
  173. /// </summary>
  174. [SerializeField]
  175. private SubmitEvent m_OnEndEdit = new SubmitEvent();
  176. /// <summary>
  177. /// Event delegates triggered when the input field submits its data.
  178. /// </summary>
  179. [SerializeField]
  180. private SubmitEvent m_OnSubmit = new SubmitEvent();
  181. /// <summary>
  182. /// Event delegates triggered when the input field is focused.
  183. /// </summary>
  184. [SerializeField]
  185. private SelectionEvent m_OnSelect = new SelectionEvent();
  186. /// <summary>
  187. /// Event delegates triggered when the input field focus is lost.
  188. /// </summary>
  189. [SerializeField]
  190. private SelectionEvent m_OnDeselect = new SelectionEvent();
  191. /// <summary>
  192. /// Event delegates triggered when the text is selected / highlighted.
  193. /// </summary>
  194. [SerializeField]
  195. private TextSelectionEvent m_OnTextSelection = new TextSelectionEvent();
  196. /// <summary>
  197. /// Event delegates triggered when text is no longer select / highlighted.
  198. /// </summary>
  199. [SerializeField]
  200. private TextSelectionEvent m_OnEndTextSelection = new TextSelectionEvent();
  201. /// <summary>
  202. /// Event delegates triggered when the input field changes its data.
  203. /// </summary>
  204. [SerializeField]
  205. private OnChangeEvent m_OnValueChanged = new OnChangeEvent();
  206. /// <summary>
  207. /// Event delegates triggered when the status of the TouchScreenKeyboard changes.
  208. /// </summary>
  209. [SerializeField]
  210. private TouchScreenKeyboardEvent m_OnTouchScreenKeyboardStatusChanged = new TouchScreenKeyboardEvent();
  211. /// <summary>
  212. /// Custom validation callback.
  213. /// </summary>
  214. [SerializeField]
  215. private OnValidateInput m_OnValidateInput;
  216. [SerializeField]
  217. private Color m_CaretColor = new Color(50f / 255f, 50f / 255f, 50f / 255f, 1f);
  218. [SerializeField]
  219. private bool m_CustomCaretColor = false;
  220. [SerializeField]
  221. private Color m_SelectionColor = new Color(168f / 255f, 206f / 255f, 255f / 255f, 192f / 255f);
  222. /// <summary>
  223. /// Input field's value.
  224. /// </summary>
  225. [SerializeField]
  226. [TextArea(5, 10)]
  227. protected string m_Text = string.Empty;
  228. [SerializeField]
  229. [Range(0f, 4f)]
  230. private float m_CaretBlinkRate = 0.85f;
  231. [SerializeField]
  232. [Range(1, 5)]
  233. private int m_CaretWidth = 1;
  234. [SerializeField]
  235. private bool m_ReadOnly = false;
  236. [SerializeField]
  237. private bool m_RichText = true;
  238. #endregion
  239. protected int m_StringPosition = 0;
  240. protected int m_StringSelectPosition = 0;
  241. protected int m_CaretPosition = 0;
  242. protected int m_CaretSelectPosition = 0;
  243. private RectTransform caretRectTrans = null;
  244. protected UIVertex[] m_CursorVerts = null;
  245. private CanvasRenderer m_CachedInputRenderer;
  246. private Vector2 m_LastPosition;
  247. [NonSerialized]
  248. protected Mesh m_Mesh;
  249. private bool m_AllowInput = false;
  250. //bool m_HasLostFocus = false;
  251. private bool m_ShouldActivateNextUpdate = false;
  252. private bool m_UpdateDrag = false;
  253. private bool m_DragPositionOutOfBounds = false;
  254. private const float kHScrollSpeed = 0.05f;
  255. private const float kVScrollSpeed = 0.10f;
  256. protected bool m_CaretVisible;
  257. private Coroutine m_BlinkCoroutine = null;
  258. private float m_BlinkStartTime = 0.0f;
  259. private Coroutine m_DragCoroutine = null;
  260. private string m_OriginalText = "";
  261. private bool m_WasCanceled = false;
  262. private bool m_HasDoneFocusTransition = false;
  263. private WaitForSecondsRealtime m_WaitForSecondsRealtime;
  264. private bool m_PreventCallback = false;
  265. private bool m_TouchKeyboardAllowsInPlaceEditing = false;
  266. private bool m_IsTextComponentUpdateRequired = false;
  267. private bool m_HasTextBeenRemoved = false;
  268. private float m_PointerDownClickStartTime;
  269. private float m_KeyDownStartTime;
  270. private float m_DoubleClickDelay = 0.5f;
  271. private bool m_IsApplePlatform = false;
  272. // Doesn't include dot and @ on purpose! See usage for details.
  273. const string kEmailSpecialCharacters = "!#$%&'*+-/=?^_`{|}~";
  274. const string kOculusQuestDeviceModel = "Oculus Quest";
  275. private BaseInput inputSystem
  276. {
  277. get
  278. {
  279. if (EventSystem.current && EventSystem.current.currentInputModule)
  280. return EventSystem.current.currentInputModule.input;
  281. return null;
  282. }
  283. }
  284. private string compositionString
  285. {
  286. get { return inputSystem != null ? inputSystem.compositionString : Input.compositionString; }
  287. }
  288. private bool m_IsCompositionActive = false;
  289. private bool m_ShouldUpdateIMEWindowPosition = false;
  290. private int m_PreviousIMEInsertionLine = 0;
  291. private int compositionLength
  292. {
  293. get
  294. {
  295. if (m_ReadOnly)
  296. return 0;
  297. return compositionString.Length;
  298. }
  299. }
  300. protected TMP_InputField()
  301. {
  302. SetTextComponentWrapMode();
  303. }
  304. protected Mesh mesh
  305. {
  306. get
  307. {
  308. if (m_Mesh == null)
  309. m_Mesh = new Mesh();
  310. return m_Mesh;
  311. }
  312. }
  313. /// <summary>
  314. /// Should the inputfield be automatically activated upon selection.
  315. /// </summary>
  316. public virtual bool shouldActivateOnSelect
  317. {
  318. set
  319. {
  320. m_ShouldActivateOnSelect = value;
  321. }
  322. get
  323. {
  324. return m_ShouldActivateOnSelect && Application.platform != RuntimePlatform.tvOS;
  325. }
  326. }
  327. /// <summary>
  328. /// Should the mobile keyboard input be hidden.
  329. /// </summary>
  330. public bool shouldHideMobileInput
  331. {
  332. get
  333. {
  334. switch (Application.platform)
  335. {
  336. case RuntimePlatform.Android:
  337. case RuntimePlatform.IPhonePlayer:
  338. case RuntimePlatform.tvOS:
  339. #if UNITY_2022_1_OR_NEWER
  340. case RuntimePlatform.WebGLPlayer:
  341. #endif
  342. return m_HideMobileInput;
  343. default:
  344. return true;
  345. }
  346. }
  347. set
  348. {
  349. switch(Application.platform)
  350. {
  351. case RuntimePlatform.Android:
  352. case RuntimePlatform.IPhonePlayer:
  353. case RuntimePlatform.tvOS:
  354. #if UNITY_2022_1_OR_NEWER
  355. case RuntimePlatform.WebGLPlayer:
  356. #endif
  357. SetPropertyUtility.SetStruct(ref m_HideMobileInput, value);
  358. break;
  359. default:
  360. m_HideMobileInput = true;
  361. break;
  362. }
  363. }
  364. }
  365. public bool shouldHideSoftKeyboard
  366. {
  367. get
  368. {
  369. switch (Application.platform)
  370. {
  371. case RuntimePlatform.Android:
  372. case RuntimePlatform.IPhonePlayer:
  373. case RuntimePlatform.tvOS:
  374. #if UNITY_XR_VISIONOS_SUPPORTED
  375. case RuntimePlatform.VisionOS:
  376. #endif
  377. case RuntimePlatform.WSAPlayerX86:
  378. case RuntimePlatform.WSAPlayerX64:
  379. case RuntimePlatform.WSAPlayerARM:
  380. #if UNITY_2020_2_OR_NEWER
  381. case RuntimePlatform.PS4:
  382. #if !(UNITY_2020_2_1 || UNITY_2020_2_2)
  383. case RuntimePlatform.PS5:
  384. #endif
  385. #endif
  386. #if UNITY_2019_4_OR_NEWER
  387. case RuntimePlatform.GameCoreXboxOne:
  388. case RuntimePlatform.GameCoreXboxSeries:
  389. #endif
  390. case RuntimePlatform.Switch:
  391. #if UNITY_2022_1_OR_NEWER
  392. case RuntimePlatform.WebGLPlayer:
  393. #endif
  394. return m_HideSoftKeyboard;
  395. default:
  396. return true;
  397. }
  398. }
  399. set
  400. {
  401. switch (Application.platform)
  402. {
  403. case RuntimePlatform.Android:
  404. case RuntimePlatform.IPhonePlayer:
  405. case RuntimePlatform.tvOS:
  406. #if UNITY_XR_VISIONOS_SUPPORTED
  407. case RuntimePlatform.VisionOS:
  408. #endif
  409. case RuntimePlatform.WSAPlayerX86:
  410. case RuntimePlatform.WSAPlayerX64:
  411. case RuntimePlatform.WSAPlayerARM:
  412. #if UNITY_2020_2_OR_NEWER
  413. case RuntimePlatform.PS4:
  414. #if !(UNITY_2020_2_1 || UNITY_2020_2_2)
  415. case RuntimePlatform.PS5:
  416. #endif
  417. #endif
  418. #if UNITY_2019_4_OR_NEWER
  419. case RuntimePlatform.GameCoreXboxOne:
  420. case RuntimePlatform.GameCoreXboxSeries:
  421. #endif
  422. case RuntimePlatform.Switch:
  423. #if UNITY_2022_1_OR_NEWER
  424. case RuntimePlatform.WebGLPlayer:
  425. #endif
  426. SetPropertyUtility.SetStruct(ref m_HideSoftKeyboard, value);
  427. break;
  428. default:
  429. m_HideSoftKeyboard = true;
  430. break;
  431. }
  432. if (m_HideSoftKeyboard == true && m_SoftKeyboard != null && TouchScreenKeyboard.isSupported && m_SoftKeyboard.active)
  433. {
  434. m_SoftKeyboard.active = false;
  435. m_SoftKeyboard = null;
  436. }
  437. }
  438. }
  439. private bool isKeyboardUsingEvents()
  440. {
  441. switch (Application.platform)
  442. {
  443. case RuntimePlatform.Android:
  444. return InPlaceEditing() && m_HideSoftKeyboard;
  445. case RuntimePlatform.IPhonePlayer:
  446. case RuntimePlatform.tvOS:
  447. #if UNITY_XR_VISIONOS_SUPPORTED
  448. case RuntimePlatform.VisionOS:
  449. #endif
  450. return m_HideSoftKeyboard;
  451. #if UNITY_2020_2_OR_NEWER
  452. case RuntimePlatform.PS4:
  453. #if !(UNITY_2020_2_1 || UNITY_2020_2_2)
  454. case RuntimePlatform.PS5:
  455. #endif
  456. #endif
  457. #if UNITY_2019_4_OR_NEWER
  458. case RuntimePlatform.GameCoreXboxOne:
  459. case RuntimePlatform.GameCoreXboxSeries:
  460. #endif
  461. case RuntimePlatform.Switch:
  462. return false;
  463. #if UNITY_2022_1_OR_NEWER
  464. case RuntimePlatform.WebGLPlayer:
  465. return m_SoftKeyboard == null || !m_SoftKeyboard.active;
  466. #endif
  467. default:
  468. return true;
  469. }
  470. }
  471. private bool isUWP()
  472. {
  473. return Application.platform == RuntimePlatform.WSAPlayerX86 || Application.platform == RuntimePlatform.WSAPlayerX64 || Application.platform == RuntimePlatform.WSAPlayerARM;
  474. }
  475. /// <summary>
  476. /// Input field's current text value. This is not necessarily the same as what is visible on screen.
  477. /// </summary>
  478. /// <remarks>
  479. /// Note that null is invalid value for InputField.text.
  480. /// </remarks>
  481. /// <example>
  482. /// <code>
  483. /// using UnityEngine;
  484. /// using System.Collections;
  485. /// using UnityEngine.UI; // Required when Using UI elements.
  486. ///
  487. /// public class Example : MonoBehaviour
  488. /// {
  489. /// public InputField mainInputField;
  490. ///
  491. /// public void Start()
  492. /// {
  493. /// mainInputField.text = "Enter Text Here...";
  494. /// }
  495. /// }
  496. /// </code>
  497. /// </example>
  498. public string text
  499. {
  500. get
  501. {
  502. return m_Text;
  503. }
  504. set
  505. {
  506. SetText(value);
  507. }
  508. }
  509. /// <summary>
  510. /// Set Input field's current text value without invoke onValueChanged. This is not necessarily the same as what is visible on screen.
  511. /// </summary>
  512. public void SetTextWithoutNotify(string input)
  513. {
  514. SetText(input, false);
  515. }
  516. void SetText(string value, bool sendCallback = true)
  517. {
  518. if (this.text == value)
  519. return;
  520. if (value == null)
  521. value = "";
  522. value = value.Replace("\0", string.Empty); // remove embedded nulls
  523. m_Text = value;
  524. /*
  525. if (m_LineType == LineType.SingleLine)
  526. value = value.Replace("\n", "").Replace("\t", "");
  527. // If we have an input validator, validate the input and apply the character limit at the same time.
  528. if (onValidateInput != null || characterValidation != CharacterValidation.None)
  529. {
  530. m_Text = "";
  531. OnValidateInput validatorMethod = onValidateInput ?? Validate;
  532. m_CaretPosition = m_CaretSelectPosition = value.Length;
  533. int charactersToCheck = characterLimit > 0 ? Math.Min(characterLimit, value.Length) : value.Length;
  534. for (int i = 0; i < charactersToCheck; ++i)
  535. {
  536. char c = validatorMethod(m_Text, m_Text.Length, value[i]);
  537. if (c != 0)
  538. m_Text += c;
  539. }
  540. }
  541. else
  542. {
  543. m_Text = characterLimit > 0 && value.Length > characterLimit ? value.Substring(0, characterLimit) : value;
  544. }
  545. */
  546. #if UNITY_EDITOR
  547. if (!Application.isPlaying)
  548. {
  549. SendOnValueChangedAndUpdateLabel();
  550. return;
  551. }
  552. #endif
  553. if (m_SoftKeyboard != null)
  554. m_SoftKeyboard.text = m_Text;
  555. if (m_StringPosition > m_Text.Length)
  556. m_StringPosition = m_StringSelectPosition = m_Text.Length;
  557. else if (m_StringSelectPosition > m_Text.Length)
  558. m_StringSelectPosition = m_Text.Length;
  559. m_forceRectTransformAdjustment = true;
  560. m_IsTextComponentUpdateRequired = true;
  561. UpdateLabel();
  562. if (sendCallback)
  563. SendOnValueChanged();
  564. }
  565. public bool isFocused
  566. {
  567. get { return m_AllowInput; }
  568. }
  569. public float caretBlinkRate
  570. {
  571. get { return m_CaretBlinkRate; }
  572. set
  573. {
  574. if (SetPropertyUtility.SetStruct(ref m_CaretBlinkRate, value))
  575. {
  576. if (m_AllowInput)
  577. SetCaretActive();
  578. }
  579. }
  580. }
  581. public int caretWidth { get { return m_CaretWidth; } set { if (SetPropertyUtility.SetStruct(ref m_CaretWidth, value)) MarkGeometryAsDirty(); } }
  582. public RectTransform textViewport { get { return m_TextViewport; } set { SetPropertyUtility.SetClass(ref m_TextViewport, value); } }
  583. public TMP_Text textComponent
  584. {
  585. get { return m_TextComponent; }
  586. set
  587. {
  588. if (SetPropertyUtility.SetClass(ref m_TextComponent, value))
  589. {
  590. SetTextComponentWrapMode();
  591. }
  592. }
  593. }
  594. //public TMP_Text placeholderTextComponent { get { return m_PlaceholderTextComponent; } set { SetPropertyUtility.SetClass(ref m_PlaceholderTextComponent, value); } }
  595. public Graphic placeholder { get { return m_Placeholder; } set { SetPropertyUtility.SetClass(ref m_Placeholder, value); } }
  596. public Scrollbar verticalScrollbar
  597. {
  598. get { return m_VerticalScrollbar; }
  599. set
  600. {
  601. if (m_VerticalScrollbar != null)
  602. m_VerticalScrollbar.onValueChanged.RemoveListener(OnScrollbarValueChange);
  603. SetPropertyUtility.SetClass(ref m_VerticalScrollbar, value);
  604. if (m_VerticalScrollbar)
  605. {
  606. m_VerticalScrollbar.onValueChanged.AddListener(OnScrollbarValueChange);
  607. }
  608. }
  609. }
  610. public float scrollSensitivity { get { return m_ScrollSensitivity; } set { if (SetPropertyUtility.SetStruct(ref m_ScrollSensitivity, value)) MarkGeometryAsDirty(); } }
  611. public Color caretColor { get { return customCaretColor ? m_CaretColor : textComponent.color; } set { if (SetPropertyUtility.SetColor(ref m_CaretColor, value)) MarkGeometryAsDirty(); } }
  612. public bool customCaretColor { get { return m_CustomCaretColor; } set { if (m_CustomCaretColor != value) { m_CustomCaretColor = value; MarkGeometryAsDirty(); } } }
  613. public Color selectionColor { get { return m_SelectionColor; } set { if (SetPropertyUtility.SetColor(ref m_SelectionColor, value)) MarkGeometryAsDirty(); } }
  614. public SubmitEvent onEndEdit { get { return m_OnEndEdit; } set { SetPropertyUtility.SetClass(ref m_OnEndEdit, value); } }
  615. public SubmitEvent onSubmit { get { return m_OnSubmit; } set { SetPropertyUtility.SetClass(ref m_OnSubmit, value); } }
  616. public SelectionEvent onSelect { get { return m_OnSelect; } set { SetPropertyUtility.SetClass(ref m_OnSelect, value); } }
  617. public SelectionEvent onDeselect { get { return m_OnDeselect; } set { SetPropertyUtility.SetClass(ref m_OnDeselect, value); } }
  618. public TextSelectionEvent onTextSelection { get { return m_OnTextSelection; } set { SetPropertyUtility.SetClass(ref m_OnTextSelection, value); } }
  619. public TextSelectionEvent onEndTextSelection { get { return m_OnEndTextSelection; } set { SetPropertyUtility.SetClass(ref m_OnEndTextSelection, value); } }
  620. public OnChangeEvent onValueChanged { get { return m_OnValueChanged; } set { SetPropertyUtility.SetClass(ref m_OnValueChanged, value); } }
  621. public TouchScreenKeyboardEvent onTouchScreenKeyboardStatusChanged { get { return m_OnTouchScreenKeyboardStatusChanged; } set { SetPropertyUtility.SetClass(ref m_OnTouchScreenKeyboardStatusChanged, value); } }
  622. public OnValidateInput onValidateInput { get { return m_OnValidateInput; } set { SetPropertyUtility.SetClass(ref m_OnValidateInput, value); } }
  623. public int characterLimit
  624. {
  625. get { return m_CharacterLimit; }
  626. set
  627. {
  628. if (SetPropertyUtility.SetStruct(ref m_CharacterLimit, Math.Max(0, value)))
  629. {
  630. UpdateLabel();
  631. if (m_SoftKeyboard != null)
  632. m_SoftKeyboard.characterLimit = value;
  633. }
  634. }
  635. }
  636. //public bool isInteractableControl { set { if ( } }
  637. /// <summary>
  638. /// Set the point size on both Placeholder and Input text object.
  639. /// </summary>
  640. public float pointSize
  641. {
  642. get { return m_GlobalPointSize; }
  643. set
  644. {
  645. if (SetPropertyUtility.SetStruct(ref m_GlobalPointSize, Math.Max(0, value)))
  646. {
  647. SetGlobalPointSize(m_GlobalPointSize);
  648. UpdateLabel();
  649. }
  650. }
  651. }
  652. /// <summary>
  653. /// Sets the Font Asset on both Placeholder and Input child objects.
  654. /// </summary>
  655. public TMP_FontAsset fontAsset
  656. {
  657. get { return m_GlobalFontAsset; }
  658. set
  659. {
  660. if (SetPropertyUtility.SetClass(ref m_GlobalFontAsset, value))
  661. {
  662. SetGlobalFontAsset(m_GlobalFontAsset);
  663. UpdateLabel();
  664. }
  665. }
  666. }
  667. [SerializeField]
  668. protected TMP_FontAsset m_GlobalFontAsset;
  669. /// <summary>
  670. /// Determines if the whole text will be selected when focused.
  671. /// </summary>
  672. public bool onFocusSelectAll
  673. {
  674. get { return m_OnFocusSelectAll; }
  675. set { m_OnFocusSelectAll = value; }
  676. }
  677. [SerializeField]
  678. protected bool m_OnFocusSelectAll = true;
  679. protected bool m_isSelectAll;
  680. /// <summary>
  681. /// Determines if the text and caret position as well as selection will be reset when the input field is deactivated.
  682. /// </summary>
  683. public bool resetOnDeActivation
  684. {
  685. get { return m_ResetOnDeActivation; }
  686. set { m_ResetOnDeActivation = value; }
  687. }
  688. [SerializeField]
  689. protected bool m_ResetOnDeActivation = true;
  690. private bool m_SelectionStillActive = false;
  691. private bool m_ReleaseSelection = false;
  692. private KeyCode m_LastKeyCode;
  693. private GameObject m_PreviouslySelectedObject;
  694. /// <summary>
  695. /// Determines if the text selection will remain visible when the input field looses focus and is deactivated.
  696. /// </summary>
  697. public bool keepTextSelectionVisible
  698. {
  699. get { return m_KeepTextSelectionVisible; }
  700. set { m_KeepTextSelectionVisible = value; }
  701. }
  702. [SerializeField]
  703. private bool m_KeepTextSelectionVisible;
  704. /// <summary>
  705. /// Controls whether the original text is restored when pressing "ESC".
  706. /// </summary>
  707. public bool restoreOriginalTextOnEscape
  708. {
  709. get { return m_RestoreOriginalTextOnEscape; }
  710. set { m_RestoreOriginalTextOnEscape = value; }
  711. }
  712. [SerializeField]
  713. private bool m_RestoreOriginalTextOnEscape = true;
  714. /// <summary>
  715. /// Is Rich Text editing allowed?
  716. /// </summary>
  717. public bool isRichTextEditingAllowed
  718. {
  719. get { return m_isRichTextEditingAllowed; }
  720. set { m_isRichTextEditingAllowed = value; }
  721. }
  722. [SerializeField]
  723. protected bool m_isRichTextEditingAllowed = false;
  724. // Content Type related
  725. public ContentType contentType { get { return m_ContentType; } set { if (SetPropertyUtility.SetStruct(ref m_ContentType, value)) EnforceContentType(); } }
  726. public LineType lineType
  727. {
  728. get { return m_LineType; }
  729. set
  730. {
  731. if (SetPropertyUtility.SetStruct(ref m_LineType, value))
  732. {
  733. SetToCustomIfContentTypeIsNot(ContentType.Standard, ContentType.Autocorrected);
  734. SetTextComponentWrapMode();
  735. }
  736. }
  737. }
  738. /// <summary>
  739. /// Limits the number of lines of text in the Input Field.
  740. /// </summary>
  741. public int lineLimit
  742. {
  743. get { return m_LineLimit; }
  744. set
  745. {
  746. if (m_LineType == LineType.SingleLine)
  747. m_LineLimit = 1;
  748. else
  749. SetPropertyUtility.SetStruct(ref m_LineLimit, value);
  750. }
  751. }
  752. [SerializeField]
  753. protected int m_LineLimit = 0;
  754. /// <summary>
  755. /// The type of input expected. See InputField.InputType.
  756. /// </summary>
  757. public InputType inputType { get { return m_InputType; } set { if (SetPropertyUtility.SetStruct(ref m_InputType, value)) SetToCustom(); } }
  758. /// <summary>
  759. /// The TouchScreenKeyboard being used to edit the Input Field.
  760. /// </summary>
  761. public TouchScreenKeyboard touchScreenKeyboard { get { return m_SoftKeyboard; } }
  762. /// <summary>
  763. /// They type of mobile keyboard that will be used.
  764. /// </summary>
  765. public TouchScreenKeyboardType keyboardType
  766. {
  767. get { return m_KeyboardType; }
  768. set
  769. {
  770. if (SetPropertyUtility.SetStruct(ref m_KeyboardType, value))
  771. SetToCustom();
  772. }
  773. }
  774. /// <summary>
  775. /// Determines if the keyboard is opened in alert mode.
  776. /// </summary>
  777. public bool isAlert;
  778. /// <summary>
  779. /// The type of validation to perform on a character
  780. /// </summary>
  781. public CharacterValidation characterValidation { get { return m_CharacterValidation; } set { if (SetPropertyUtility.SetStruct(ref m_CharacterValidation, value)) SetToCustom(); } }
  782. /// <summary>
  783. /// Sets the Input Validation to use a Custom Input Validation script.
  784. /// </summary>
  785. public TMP_InputValidator inputValidator
  786. {
  787. get { return m_InputValidator; }
  788. set { if (SetPropertyUtility.SetClass(ref m_InputValidator, value)) SetToCustom(CharacterValidation.CustomValidator); }
  789. }
  790. [SerializeField]
  791. protected TMP_InputValidator m_InputValidator = null;
  792. public bool readOnly { get { return m_ReadOnly; } set { m_ReadOnly = value; } }
  793. [SerializeField]
  794. private bool m_ShouldActivateOnSelect = true;
  795. public bool richText { get { return m_RichText; } set { m_RichText = value; SetTextComponentRichTextMode(); } }
  796. // Derived property
  797. public bool multiLine { get { return m_LineType == LineType.MultiLineNewline || lineType == LineType.MultiLineSubmit; } }
  798. // Not shown in Inspector.
  799. public char asteriskChar { get { return m_AsteriskChar; } set { if (SetPropertyUtility.SetStruct(ref m_AsteriskChar, value)) UpdateLabel(); } }
  800. public bool wasCanceled { get { return m_WasCanceled; } }
  801. protected void ClampStringPos(ref int pos)
  802. {
  803. if (pos <= 0)
  804. pos = 0;
  805. else if (pos > text.Length)
  806. pos = text.Length;
  807. }
  808. protected void ClampCaretPos(ref int pos)
  809. {
  810. if (pos > m_TextComponent.textInfo.characterCount - 1)
  811. pos = m_TextComponent.textInfo.characterCount - 1;
  812. if (pos <= 0)
  813. pos = 0;
  814. }
  815. int ClampArrayIndex(int index)
  816. {
  817. if (index < 0)
  818. return 0;
  819. return index;
  820. }
  821. /// <summary>
  822. /// Current position of the cursor.
  823. /// Getters are public Setters are protected
  824. /// </summary>
  825. protected int caretPositionInternal { get { return m_CaretPosition + compositionLength; } set { m_CaretPosition = value; ClampCaretPos(ref m_CaretPosition); } }
  826. protected int stringPositionInternal { get { return m_StringPosition + compositionLength; } set { m_StringPosition = value; ClampStringPos(ref m_StringPosition); } }
  827. protected int caretSelectPositionInternal { get { return m_CaretSelectPosition + compositionLength; } set { m_CaretSelectPosition = value; ClampCaretPos(ref m_CaretSelectPosition); } }
  828. protected int stringSelectPositionInternal { get { return m_StringSelectPosition + compositionLength; } set { m_StringSelectPosition = value; ClampStringPos(ref m_StringSelectPosition); } }
  829. private bool hasSelection { get { return stringPositionInternal != stringSelectPositionInternal; } }
  830. private bool m_isSelected;
  831. private bool m_IsStringPositionDirty;
  832. private bool m_IsCaretPositionDirty;
  833. private bool m_forceRectTransformAdjustment;
  834. // Primary to track when an user presses on the X to close the keyboard in the HoloLens
  835. private bool m_IsKeyboardBeingClosedInHoloLens = false;
  836. /// <summary>
  837. /// Get: Returns the focus position as thats the position that moves around even during selection.
  838. /// Set: Set both the anchor and focus position such that a selection doesn't happen
  839. /// </summary>
  840. public int caretPosition
  841. {
  842. get => caretSelectPositionInternal;
  843. set { selectionAnchorPosition = value; selectionFocusPosition = value; UpdateStringIndexFromCaretPosition(); }
  844. }
  845. /// <summary>
  846. /// Get: Returns the fixed position of selection
  847. /// Set: If compositionString is 0 set the fixed position
  848. /// </summary>
  849. public int selectionAnchorPosition
  850. {
  851. get
  852. {
  853. return caretPositionInternal;
  854. }
  855. set
  856. {
  857. if (compositionLength != 0)
  858. return;
  859. caretPositionInternal = value;
  860. m_IsStringPositionDirty = true;
  861. }
  862. }
  863. /// <summary>
  864. /// Get: Returns the variable position of selection
  865. /// Set: If compositionString is 0 set the variable position
  866. /// </summary>
  867. public int selectionFocusPosition
  868. {
  869. get
  870. {
  871. return caretSelectPositionInternal;
  872. }
  873. set
  874. {
  875. if (compositionLength != 0)
  876. return;
  877. caretSelectPositionInternal = value;
  878. m_IsStringPositionDirty = true;
  879. }
  880. }
  881. /// <summary>
  882. ///
  883. /// </summary>
  884. public int stringPosition
  885. {
  886. get => stringSelectPositionInternal;
  887. set { selectionStringAnchorPosition = value; selectionStringFocusPosition = value; UpdateCaretPositionFromStringIndex(); }
  888. }
  889. /// <summary>
  890. /// The fixed position of the selection in the raw string which may contains rich text.
  891. /// </summary>
  892. public int selectionStringAnchorPosition
  893. {
  894. get
  895. {
  896. return stringPositionInternal;
  897. }
  898. set
  899. {
  900. if (compositionLength != 0)
  901. return;
  902. stringPositionInternal = value;
  903. m_IsCaretPositionDirty = true;
  904. }
  905. }
  906. /// <summary>
  907. /// The variable position of the selection in the raw string which may contains rich text.
  908. /// </summary>
  909. public int selectionStringFocusPosition
  910. {
  911. get
  912. {
  913. return stringSelectPositionInternal;
  914. }
  915. set
  916. {
  917. if (compositionLength != 0)
  918. return;
  919. stringSelectPositionInternal = value;
  920. m_IsCaretPositionDirty = true;
  921. }
  922. }
  923. #if UNITY_EDITOR
  924. // Remember: This is NOT related to text validation!
  925. // This is Unity's own OnValidate method which is invoked when changing values in the Inspector.
  926. protected override void OnValidate()
  927. {
  928. base.OnValidate();
  929. EnforceContentType();
  930. m_CharacterLimit = Math.Max(0, m_CharacterLimit);
  931. //This can be invoked before OnEnabled is called. So we shouldn't be accessing other objects, before OnEnable is called.
  932. if (!IsActive())
  933. return;
  934. SetTextComponentRichTextMode();
  935. UpdateLabel();
  936. if (m_AllowInput)
  937. SetCaretActive();
  938. }
  939. #endif // if UNITY_EDITOR
  940. #if UNITY_ANDROID
  941. protected override void Awake()
  942. {
  943. base.Awake();
  944. if (s_IsQuestDeviceEvaluated)
  945. return;
  946. // Used for Oculus Quest 1 and 2 software keyboard regression.
  947. // TouchScreenKeyboard.isInPlaceEditingAllowed is always returning true in these devices and would prevent the software keyboard from showing up if that value was used.
  948. s_IsQuestDevice = SystemInfo.deviceModel == kOculusQuestDeviceModel;
  949. s_IsQuestDeviceEvaluated = true;
  950. }
  951. #endif // if UNITY_ANDROID
  952. protected override void OnEnable()
  953. {
  954. //Debug.Log("*** OnEnable() *** - " + this.name);
  955. base.OnEnable();
  956. if (m_Text == null)
  957. m_Text = string.Empty;
  958. m_IsApplePlatform = SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX || SystemInfo.operatingSystem.Contains("iOS") || SystemInfo.operatingSystem.Contains("tvOS");
  959. // Check if Input Field is driven by any layout components
  960. ILayoutController layoutController = GetComponent<ILayoutController>();
  961. if (layoutController != null)
  962. {
  963. m_IsDrivenByLayoutComponents = true;
  964. m_LayoutGroup = GetComponent<LayoutGroup>();
  965. }
  966. else
  967. m_IsDrivenByLayoutComponents = false;
  968. if (Application.isPlaying)
  969. {
  970. if (m_CachedInputRenderer == null && m_TextComponent != null)
  971. {
  972. GameObject go = new GameObject("Caret", typeof(TMP_SelectionCaret));
  973. go.hideFlags = HideFlags.DontSave;
  974. go.transform.SetParent(m_TextComponent.transform.parent);
  975. go.transform.SetAsFirstSibling();
  976. go.layer = gameObject.layer;
  977. caretRectTrans = go.GetComponent<RectTransform>();
  978. m_CachedInputRenderer = go.GetComponent<CanvasRenderer>();
  979. m_CachedInputRenderer.SetMaterial(Graphic.defaultGraphicMaterial, Texture2D.whiteTexture);
  980. // Needed as if any layout is present we want the caret to always be the same as the text area.
  981. go.AddComponent<LayoutElement>().ignoreLayout = true;
  982. AssignPositioningIfNeeded();
  983. }
  984. }
  985. m_RectTransform = GetComponent<RectTransform>();
  986. // Check if parent component has IScrollHandler
  987. IScrollHandler[] scrollHandlers = GetComponentsInParent<IScrollHandler>();
  988. if (scrollHandlers.Length > 1)
  989. m_IScrollHandlerParent = scrollHandlers[1] as ScrollRect;
  990. // Get a reference to the RectMask 2D on the Viewport Text Area object.
  991. if (m_TextViewport != null)
  992. {
  993. m_TextViewportRectMask = m_TextViewport.GetComponent<RectMask2D>();
  994. UpdateMaskRegions();
  995. }
  996. // If we have a cached renderer then we had OnDisable called so just restore the material.
  997. if (m_CachedInputRenderer != null)
  998. m_CachedInputRenderer.SetMaterial(Graphic.defaultGraphicMaterial, Texture2D.whiteTexture);
  999. if (m_TextComponent != null)
  1000. {
  1001. m_TextComponent.RegisterDirtyVerticesCallback(MarkGeometryAsDirty);
  1002. m_TextComponent.RegisterDirtyVerticesCallback(UpdateLabel);
  1003. // Cache reference to Vertical Scrollbar RectTransform and add listener.
  1004. if (m_VerticalScrollbar != null)
  1005. {
  1006. m_VerticalScrollbar.onValueChanged.AddListener(OnScrollbarValueChange);
  1007. }
  1008. UpdateLabel();
  1009. }
  1010. #if UNITY_2019_1_OR_NEWER
  1011. m_TouchKeyboardAllowsInPlaceEditing = TouchScreenKeyboard.isInPlaceEditingAllowed;
  1012. #endif
  1013. // Subscribe to event fired when text object has been regenerated.
  1014. TMPro_EventManager.TEXT_CHANGED_EVENT.Add(ON_TEXT_CHANGED);
  1015. }
  1016. protected override void OnDisable()
  1017. {
  1018. // the coroutine will be terminated, so this will ensure it restarts when we are next activated
  1019. m_BlinkCoroutine = null;
  1020. DeactivateInputField();
  1021. if (m_TextComponent != null)
  1022. {
  1023. m_TextComponent.UnregisterDirtyVerticesCallback(MarkGeometryAsDirty);
  1024. m_TextComponent.UnregisterDirtyVerticesCallback(UpdateLabel);
  1025. if (m_VerticalScrollbar != null)
  1026. m_VerticalScrollbar.onValueChanged.RemoveListener(OnScrollbarValueChange);
  1027. }
  1028. CanvasUpdateRegistry.UnRegisterCanvasElementForRebuild(this);
  1029. // Clear needs to be called otherwise sync never happens as the object is disabled.
  1030. if (m_CachedInputRenderer != null)
  1031. m_CachedInputRenderer.Clear();
  1032. if (m_Mesh != null)
  1033. DestroyImmediate(m_Mesh);
  1034. m_Mesh = null;
  1035. // Unsubscribe to event triggered when text object has been regenerated
  1036. TMPro_EventManager.TEXT_CHANGED_EVENT.Remove(ON_TEXT_CHANGED);
  1037. base.OnDisable();
  1038. }
  1039. /// <summary>
  1040. /// Method used to update the tracking of the caret position when the text object has been regenerated.
  1041. /// </summary>
  1042. /// <param name="obj"></param>
  1043. private void ON_TEXT_CHANGED(UnityEngine.Object obj)
  1044. {
  1045. bool isThisObject = obj == m_TextComponent;
  1046. if (isThisObject && !m_IsStringPositionDirty)
  1047. {
  1048. if (Application.isPlaying && compositionLength == 0)
  1049. {
  1050. UpdateCaretPositionFromStringIndex();
  1051. #if TMP_DEBUG_MODE
  1052. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  1053. #endif
  1054. }
  1055. if (m_VerticalScrollbar)
  1056. UpdateScrollbar();
  1057. }
  1058. }
  1059. IEnumerator CaretBlink()
  1060. {
  1061. // Always ensure caret is initially visible since it can otherwise be confusing for a moment.
  1062. m_CaretVisible = true;
  1063. yield return null;
  1064. while ((isFocused || m_SelectionStillActive) && m_CaretBlinkRate > 0)
  1065. {
  1066. // the blink rate is expressed as a frequency
  1067. float blinkPeriod = 1f / m_CaretBlinkRate;
  1068. // the caret should be ON if we are in the first half of the blink period
  1069. bool blinkState = (Time.unscaledTime - m_BlinkStartTime) % blinkPeriod < blinkPeriod / 2;
  1070. if (m_CaretVisible != blinkState)
  1071. {
  1072. m_CaretVisible = blinkState;
  1073. if (!hasSelection)
  1074. MarkGeometryAsDirty();
  1075. }
  1076. // Then wait again.
  1077. yield return null;
  1078. }
  1079. m_BlinkCoroutine = null;
  1080. }
  1081. void SetCaretVisible()
  1082. {
  1083. if (!m_AllowInput)
  1084. return;
  1085. m_CaretVisible = true;
  1086. m_BlinkStartTime = Time.unscaledTime;
  1087. SetCaretActive();
  1088. }
  1089. // SetCaretActive will not set the caret immediately visible - it will wait for the next time to blink.
  1090. // However, it will handle things correctly if the blink speed changed from zero to non-zero or non-zero to zero.
  1091. void SetCaretActive()
  1092. {
  1093. if (!m_AllowInput)
  1094. return;
  1095. if (m_CaretBlinkRate > 0.0f)
  1096. {
  1097. if (m_BlinkCoroutine == null)
  1098. m_BlinkCoroutine = StartCoroutine(CaretBlink());
  1099. }
  1100. else
  1101. {
  1102. m_CaretVisible = true;
  1103. }
  1104. }
  1105. protected void OnFocus()
  1106. {
  1107. if (m_OnFocusSelectAll)
  1108. SelectAll();
  1109. }
  1110. protected void SelectAll()
  1111. {
  1112. m_isSelectAll = true;
  1113. stringPositionInternal = text.Length;
  1114. stringSelectPositionInternal = 0;
  1115. }
  1116. /// <summary>
  1117. /// Move to the end of the text.
  1118. /// </summary>
  1119. /// <param name="shift"></param>
  1120. public void MoveTextEnd(bool shift)
  1121. {
  1122. if (m_isRichTextEditingAllowed)
  1123. {
  1124. int position = text.Length;
  1125. if (shift)
  1126. {
  1127. stringSelectPositionInternal = position;
  1128. }
  1129. else
  1130. {
  1131. stringPositionInternal = position;
  1132. stringSelectPositionInternal = stringPositionInternal;
  1133. }
  1134. }
  1135. else
  1136. {
  1137. int position = m_TextComponent.textInfo.characterCount - 1;
  1138. if (shift)
  1139. {
  1140. caretSelectPositionInternal = position;
  1141. stringSelectPositionInternal = GetStringIndexFromCaretPosition(position);
  1142. }
  1143. else
  1144. {
  1145. caretPositionInternal = caretSelectPositionInternal = position;
  1146. stringSelectPositionInternal = stringPositionInternal = GetStringIndexFromCaretPosition(position);
  1147. }
  1148. }
  1149. UpdateLabel();
  1150. }
  1151. /// <summary>
  1152. /// Move to the start of the text.
  1153. /// </summary>
  1154. /// <param name="shift"></param>
  1155. public void MoveTextStart(bool shift)
  1156. {
  1157. if (m_isRichTextEditingAllowed)
  1158. {
  1159. int position = 0;
  1160. if (shift)
  1161. {
  1162. stringSelectPositionInternal = position;
  1163. }
  1164. else
  1165. {
  1166. stringPositionInternal = position;
  1167. stringSelectPositionInternal = stringPositionInternal;
  1168. }
  1169. }
  1170. else
  1171. {
  1172. int position = 0;
  1173. if (shift)
  1174. {
  1175. caretSelectPositionInternal = position;
  1176. stringSelectPositionInternal = GetStringIndexFromCaretPosition(position);
  1177. }
  1178. else
  1179. {
  1180. caretPositionInternal = caretSelectPositionInternal = position;
  1181. stringSelectPositionInternal = stringPositionInternal = GetStringIndexFromCaretPosition(position);
  1182. }
  1183. }
  1184. UpdateLabel();
  1185. }
  1186. /// <summary>
  1187. /// Move to the end of the current line of text.
  1188. /// </summary>
  1189. /// <param name="shift"></param>
  1190. public void MoveToEndOfLine(bool shift, bool ctrl)
  1191. {
  1192. // Get the line the caret is currently located on.
  1193. int currentLine = m_TextComponent.textInfo.characterInfo[caretPositionInternal].lineNumber;
  1194. // Get the last character of the given line.
  1195. int characterIndex = ctrl == true ? m_TextComponent.textInfo.characterCount - 1 : m_TextComponent.textInfo.lineInfo[currentLine].lastCharacterIndex;
  1196. int position = m_TextComponent.textInfo.characterInfo[characterIndex].index;
  1197. if (shift)
  1198. {
  1199. stringSelectPositionInternal = position;
  1200. caretSelectPositionInternal = characterIndex;
  1201. }
  1202. else
  1203. {
  1204. stringPositionInternal = position;
  1205. stringSelectPositionInternal = stringPositionInternal;
  1206. caretSelectPositionInternal = caretPositionInternal = characterIndex;
  1207. }
  1208. UpdateLabel();
  1209. }
  1210. /// <summary>
  1211. /// Move to the start of the current line of text.
  1212. /// </summary>
  1213. /// <param name="shift"></param>
  1214. public void MoveToStartOfLine(bool shift, bool ctrl)
  1215. {
  1216. // Get the line the caret is currently located on.
  1217. int currentLine = m_TextComponent.textInfo.characterInfo[caretPositionInternal].lineNumber;
  1218. // Get the first character of the given line.
  1219. int characterIndex = ctrl == true ? 0 : m_TextComponent.textInfo.lineInfo[currentLine].firstCharacterIndex;
  1220. int position = 0;
  1221. if (characterIndex > 0)
  1222. position = m_TextComponent.textInfo.characterInfo[characterIndex - 1].index + m_TextComponent.textInfo.characterInfo[characterIndex - 1].stringLength;
  1223. if (shift)
  1224. {
  1225. stringSelectPositionInternal = position;
  1226. caretSelectPositionInternal = characterIndex;
  1227. }
  1228. else
  1229. {
  1230. stringPositionInternal = position;
  1231. stringSelectPositionInternal = stringPositionInternal;
  1232. caretSelectPositionInternal = caretPositionInternal = characterIndex;
  1233. }
  1234. UpdateLabel();
  1235. }
  1236. static string clipboard
  1237. {
  1238. get
  1239. {
  1240. return GUIUtility.systemCopyBuffer;
  1241. }
  1242. set
  1243. {
  1244. GUIUtility.systemCopyBuffer = value;
  1245. }
  1246. }
  1247. private bool InPlaceEditing()
  1248. {
  1249. if (m_TouchKeyboardAllowsInPlaceEditing)
  1250. return true;
  1251. if (isUWP())
  1252. return !TouchScreenKeyboard.isSupported;
  1253. if (TouchScreenKeyboard.isSupported && shouldHideSoftKeyboard)
  1254. return true;
  1255. if (TouchScreenKeyboard.isSupported && shouldHideSoftKeyboard == false && shouldHideMobileInput == false)
  1256. return false;
  1257. return true;
  1258. }
  1259. // In-place editing can change state if a hardware keyboard becomes available or is hidden while the input field is activated.
  1260. private bool InPlaceEditingChanged()
  1261. {
  1262. return !s_IsQuestDevice && m_TouchKeyboardAllowsInPlaceEditing != TouchScreenKeyboard.isInPlaceEditingAllowed;
  1263. }
  1264. // Returns true if the TouchScreenKeyboard should be used. On Android and Chrome OS, we only want to use the
  1265. // TouchScreenKeyboard if in-place editing is not allowed (i.e. when we do not have a hardware keyboard available).
  1266. private bool TouchScreenKeyboardShouldBeUsed()
  1267. {
  1268. RuntimePlatform platform = Application.platform;
  1269. switch (platform)
  1270. {
  1271. case RuntimePlatform.Android:
  1272. if (s_IsQuestDevice)
  1273. return TouchScreenKeyboard.isSupported;
  1274. return !TouchScreenKeyboard.isInPlaceEditingAllowed;
  1275. default:
  1276. return TouchScreenKeyboard.isSupported;
  1277. }
  1278. }
  1279. void UpdateKeyboardStringPosition()
  1280. {
  1281. // On iOS/tvOS we only update SoftKeyboard selection when we know that it might have changed by touch/pointer interactions with InputField
  1282. // Setting the TouchScreenKeyboard selection here instead of LateUpdate so that we wouldn't override
  1283. // TouchScreenKeyboard selection when it's changed with cmd+a/ctrl+a/arrow/etc. in the TouchScreenKeyboard
  1284. // This is only applicable for iOS/tvOS as we have instance of TouchScreenKeyboard even when external keyboard is connected
  1285. if (m_HideMobileInput && m_SoftKeyboard != null && m_SoftKeyboard.canSetSelection &&
  1286. (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.tvOS))
  1287. {
  1288. var selectionStart = Mathf.Min(caretSelectPositionInternal, caretPositionInternal);
  1289. var selectionLength = Mathf.Abs(caretSelectPositionInternal - caretPositionInternal);
  1290. m_SoftKeyboard.selection = new RangeInt(selectionStart, selectionLength);
  1291. }
  1292. }
  1293. void UpdateStringPositionFromKeyboard()
  1294. {
  1295. // TODO: Might want to add null check here.
  1296. var selectionRange = m_SoftKeyboard.selection;
  1297. //if (selectionRange.start == 0 && selectionRange.length == 0)
  1298. // return;
  1299. var selectionStart = selectionRange.start;
  1300. var selectionEnd = selectionRange.end;
  1301. var stringPositionChanged = false;
  1302. if (stringPositionInternal != selectionStart)
  1303. {
  1304. stringPositionChanged = true;
  1305. stringPositionInternal = selectionStart;
  1306. caretPositionInternal = GetCaretPositionFromStringIndex(stringPositionInternal);
  1307. }
  1308. if (stringSelectPositionInternal != selectionEnd)
  1309. {
  1310. stringSelectPositionInternal = selectionEnd;
  1311. stringPositionChanged = true;
  1312. caretSelectPositionInternal = GetCaretPositionFromStringIndex(stringSelectPositionInternal);
  1313. }
  1314. if (stringPositionChanged)
  1315. {
  1316. m_BlinkStartTime = Time.unscaledTime;
  1317. UpdateLabel();
  1318. }
  1319. }
  1320. /// <summary>
  1321. /// Update the text based on input.
  1322. /// </summary>
  1323. // TODO: Make LateUpdate a coroutine instead. Allows us to control the update to only be when the field is active.
  1324. protected virtual void LateUpdate()
  1325. {
  1326. // Only activate if we are not already activated.
  1327. if (m_ShouldActivateNextUpdate)
  1328. {
  1329. if (!isFocused)
  1330. {
  1331. ActivateInputFieldInternal();
  1332. m_ShouldActivateNextUpdate = false;
  1333. return;
  1334. }
  1335. // Reset as we are already activated.
  1336. m_ShouldActivateNextUpdate = false;
  1337. }
  1338. // If the device's state changed in a way that affects whether we should use a touchscreen keyboard or not,
  1339. // then deactivate the input field.
  1340. if (isFocused && InPlaceEditingChanged())
  1341. DeactivateInputField();
  1342. // Handle double click to reset / deselect Input Field when ResetOnActivation is false.
  1343. if (!isFocused && m_SelectionStillActive)
  1344. {
  1345. GameObject selectedObject = EventSystem.current != null ? EventSystem.current.currentSelectedGameObject : null;
  1346. if (selectedObject == null && m_ResetOnDeActivation)
  1347. {
  1348. ReleaseSelection();
  1349. return;
  1350. }
  1351. if (selectedObject != null && selectedObject != this.gameObject)
  1352. {
  1353. if (selectedObject == m_PreviouslySelectedObject)
  1354. return;
  1355. m_PreviouslySelectedObject = selectedObject;
  1356. // Special handling for Vertical Scrollbar
  1357. if (m_VerticalScrollbar && selectedObject == m_VerticalScrollbar.gameObject)
  1358. {
  1359. // Do not release selection
  1360. return;
  1361. }
  1362. // Release selection for all objects when ResetOnDeActivation is true
  1363. if (m_ResetOnDeActivation)
  1364. {
  1365. ReleaseSelection();
  1366. return;
  1367. }
  1368. // Release current selection of selected object is another Input Field
  1369. if (m_KeepTextSelectionVisible == false && selectedObject.GetComponent<TMP_InputField>() != null)
  1370. ReleaseSelection();
  1371. return;
  1372. }
  1373. #if ENABLE_INPUT_SYSTEM
  1374. if (m_ProcessingEvent != null && m_ProcessingEvent.rawType == EventType.MouseDown && m_ProcessingEvent.button == 0)
  1375. {
  1376. // Check for Double Click
  1377. bool isDoubleClick = false;
  1378. float timeStamp = Time.unscaledTime;
  1379. if (m_KeyDownStartTime + m_DoubleClickDelay > timeStamp)
  1380. isDoubleClick = true;
  1381. m_KeyDownStartTime = timeStamp;
  1382. if (isDoubleClick)
  1383. {
  1384. //m_StringPosition = m_StringSelectPosition = 0;
  1385. //m_CaretPosition = m_CaretSelectPosition = 0;
  1386. //m_TextComponent.rectTransform.localPosition = m_DefaultTransformPosition;
  1387. //if (caretRectTrans != null)
  1388. // caretRectTrans.localPosition = Vector3.zero;
  1389. ReleaseSelection();
  1390. return;
  1391. }
  1392. }
  1393. #else
  1394. if (Input.GetKeyDown(KeyCode.Mouse0))
  1395. {
  1396. // Check for Double Click
  1397. bool isDoubleClick = false;
  1398. float timeStamp = Time.unscaledTime;
  1399. if (m_KeyDownStartTime + m_DoubleClickDelay > timeStamp)
  1400. isDoubleClick = true;
  1401. m_KeyDownStartTime = timeStamp;
  1402. if (isDoubleClick)
  1403. {
  1404. //m_StringPosition = m_StringSelectPosition = 0;
  1405. //m_CaretPosition = m_CaretSelectPosition = 0;
  1406. //m_TextComponent.rectTransform.localPosition = m_DefaultTransformPosition;
  1407. //if (caretRectTrans != null)
  1408. // caretRectTrans.localPosition = Vector3.zero;
  1409. ReleaseSelection();
  1410. return;
  1411. }
  1412. }
  1413. #endif
  1414. }
  1415. UpdateMaskRegions();
  1416. if (InPlaceEditing() && isKeyboardUsingEvents() || !isFocused)
  1417. {
  1418. return;
  1419. }
  1420. AssignPositioningIfNeeded();
  1421. if (m_SoftKeyboard == null || m_SoftKeyboard.status != TouchScreenKeyboard.Status.Visible)
  1422. {
  1423. if (m_SoftKeyboard != null)
  1424. {
  1425. if (!m_ReadOnly)
  1426. text = m_SoftKeyboard.text;
  1427. TouchScreenKeyboard.Status status = m_SoftKeyboard.status;
  1428. // Special handling for UWP - Hololens which does not support Canceled status
  1429. if (m_LastKeyCode != KeyCode.Return && status == TouchScreenKeyboard.Status.Done && isUWP())
  1430. {
  1431. status = TouchScreenKeyboard.Status.Canceled;
  1432. // The HoloLen's X button will not be acting as an ESC Key (TMBP-98)
  1433. m_IsKeyboardBeingClosedInHoloLens = true;
  1434. }
  1435. switch (status)
  1436. {
  1437. case TouchScreenKeyboard.Status.LostFocus:
  1438. SendTouchScreenKeyboardStatusChanged();
  1439. break;
  1440. case TouchScreenKeyboard.Status.Canceled:
  1441. m_ReleaseSelection = true;
  1442. m_WasCanceled = true;
  1443. SendTouchScreenKeyboardStatusChanged();
  1444. break;
  1445. case TouchScreenKeyboard.Status.Done:
  1446. m_ReleaseSelection = true;
  1447. SendTouchScreenKeyboardStatusChanged();
  1448. OnSubmit(null);
  1449. break;
  1450. }
  1451. }
  1452. OnDeselect(null);
  1453. return;
  1454. }
  1455. string val = m_SoftKeyboard.text;
  1456. if (m_Text != val)
  1457. {
  1458. if (m_ReadOnly)
  1459. {
  1460. m_SoftKeyboard.text = m_Text;
  1461. }
  1462. else
  1463. {
  1464. m_Text = "";
  1465. for (int i = 0; i < val.Length; ++i)
  1466. {
  1467. char c = val[i];
  1468. bool hasValidateUpdatedText = false;
  1469. if (c == '\r' || c == 3)
  1470. c = '\n';
  1471. if (onValidateInput != null)
  1472. c = onValidateInput(m_Text, m_Text.Length, c);
  1473. else if (characterValidation != CharacterValidation.None)
  1474. {
  1475. string textBeforeValidate = m_Text;
  1476. c = Validate(m_Text, m_Text.Length, c);
  1477. hasValidateUpdatedText = textBeforeValidate != m_Text;
  1478. }
  1479. if (lineType != LineType.MultiLineNewline && c == '\n')
  1480. {
  1481. UpdateLabel();
  1482. OnSubmit(null);
  1483. OnDeselect(null);
  1484. return;
  1485. }
  1486. // In the case of a Custom Validator, the user is expected to modify the m_Text where as such we do not append c.
  1487. // However we will append c if the user did not modify the m_Text (UUM-42147)
  1488. if (c != 0 && (characterValidation != CharacterValidation.CustomValidator || !hasValidateUpdatedText))
  1489. m_Text += c;
  1490. }
  1491. if (characterLimit > 0 && m_Text.Length > characterLimit)
  1492. m_Text = m_Text.Substring(0, characterLimit);
  1493. UpdateStringPositionFromKeyboard();
  1494. // Set keyboard text before updating label, as we might have changed it with validation
  1495. // and update label will take the old value from keyboard if we don't change it here
  1496. if (m_Text != val)
  1497. m_SoftKeyboard.text = m_Text;
  1498. SendOnValueChangedAndUpdateLabel();
  1499. }
  1500. }
  1501. // On iOS/tvOS we always have TouchScreenKeyboard instance even when using external keyboard
  1502. // so we keep track of the caret position there
  1503. else if (m_HideMobileInput && m_SoftKeyboard != null && m_SoftKeyboard.canSetSelection &&
  1504. Application.platform != RuntimePlatform.IPhonePlayer && Application.platform != RuntimePlatform.tvOS)
  1505. {
  1506. var selectionStart = Mathf.Min(caretSelectPositionInternal, caretPositionInternal);
  1507. var selectionLength = Mathf.Abs(caretSelectPositionInternal - caretPositionInternal);
  1508. m_SoftKeyboard.selection = new RangeInt(selectionStart, selectionLength);
  1509. }
  1510. else if (m_HideMobileInput && Application.platform == RuntimePlatform.Android ||
  1511. m_SoftKeyboard.canSetSelection && (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.tvOS))
  1512. {
  1513. UpdateStringPositionFromKeyboard();
  1514. }
  1515. //else if (m_HideMobileInput) // m_Keyboard.canSetSelection
  1516. //{
  1517. // int length = stringPositionInternal < stringSelectPositionInternal ? stringSelectPositionInternal - stringPositionInternal : stringPositionInternal - stringSelectPositionInternal;
  1518. // m_SoftKeyboard.selection = new RangeInt(stringPositionInternal < stringSelectPositionInternal ? stringPositionInternal : stringSelectPositionInternal, length);
  1519. //}
  1520. //else if (!m_HideMobileInput) // m_Keyboard.canGetSelection)
  1521. //{
  1522. // UpdateStringPositionFromKeyboard();
  1523. //}
  1524. if (m_SoftKeyboard != null && m_SoftKeyboard.status != TouchScreenKeyboard.Status.Visible)
  1525. {
  1526. if (m_SoftKeyboard.status == TouchScreenKeyboard.Status.Canceled)
  1527. m_WasCanceled = true;
  1528. OnDeselect(null);
  1529. }
  1530. }
  1531. private bool MayDrag(PointerEventData eventData)
  1532. {
  1533. return IsActive() &&
  1534. IsInteractable() &&
  1535. eventData.button == PointerEventData.InputButton.Left &&
  1536. m_TextComponent != null &&
  1537. (m_SoftKeyboard == null || shouldHideSoftKeyboard || shouldHideMobileInput);
  1538. }
  1539. public virtual void OnBeginDrag(PointerEventData eventData)
  1540. {
  1541. if (!MayDrag(eventData))
  1542. return;
  1543. m_UpdateDrag = true;
  1544. }
  1545. public virtual void OnDrag(PointerEventData eventData)
  1546. {
  1547. if (!MayDrag(eventData))
  1548. return;
  1549. CaretPosition insertionSide;
  1550. int insertionIndex = TMP_TextUtilities.GetCursorIndexFromPosition(m_TextComponent, eventData.position, eventData.pressEventCamera, out insertionSide);
  1551. if (m_isRichTextEditingAllowed)
  1552. {
  1553. if (insertionSide == CaretPosition.Left)
  1554. {
  1555. stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index;
  1556. }
  1557. else if (insertionSide == CaretPosition.Right)
  1558. {
  1559. stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index + m_TextComponent.textInfo.characterInfo[insertionIndex].stringLength;
  1560. }
  1561. }
  1562. else
  1563. {
  1564. if (insertionSide == CaretPosition.Left)
  1565. {
  1566. stringSelectPositionInternal = insertionIndex == 0
  1567. ? m_TextComponent.textInfo.characterInfo[0].index
  1568. : m_TextComponent.textInfo.characterInfo[insertionIndex - 1].index + m_TextComponent.textInfo.characterInfo[insertionIndex - 1].stringLength;
  1569. }
  1570. else if (insertionSide == CaretPosition.Right)
  1571. {
  1572. stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index + m_TextComponent.textInfo.characterInfo[insertionIndex].stringLength;
  1573. }
  1574. }
  1575. caretSelectPositionInternal = GetCaretPositionFromStringIndex(stringSelectPositionInternal);
  1576. MarkGeometryAsDirty();
  1577. m_DragPositionOutOfBounds = !RectTransformUtility.RectangleContainsScreenPoint(textViewport, eventData.position, eventData.pressEventCamera);
  1578. if (m_DragPositionOutOfBounds && m_DragCoroutine == null)
  1579. m_DragCoroutine = StartCoroutine(MouseDragOutsideRect(eventData));
  1580. UpdateKeyboardStringPosition();
  1581. eventData.Use();
  1582. #if TMP_DEBUG_MODE
  1583. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  1584. #endif
  1585. }
  1586. IEnumerator MouseDragOutsideRect(PointerEventData eventData)
  1587. {
  1588. while (m_UpdateDrag && m_DragPositionOutOfBounds)
  1589. {
  1590. Vector2 localMousePos;
  1591. RectTransformUtility.ScreenPointToLocalPointInRectangle(textViewport, eventData.position, eventData.pressEventCamera, out localMousePos);
  1592. Rect rect = textViewport.rect;
  1593. if (multiLine)
  1594. {
  1595. if (localMousePos.y > rect.yMax)
  1596. MoveUp(true, true);
  1597. else if (localMousePos.y < rect.yMin)
  1598. MoveDown(true, true);
  1599. }
  1600. else
  1601. {
  1602. if (localMousePos.x < rect.xMin)
  1603. MoveLeft(true, false);
  1604. else if (localMousePos.x > rect.xMax)
  1605. MoveRight(true, false);
  1606. }
  1607. UpdateLabel();
  1608. float delay = multiLine ? kVScrollSpeed : kHScrollSpeed;
  1609. if (m_WaitForSecondsRealtime == null)
  1610. m_WaitForSecondsRealtime = new WaitForSecondsRealtime(delay);
  1611. else
  1612. m_WaitForSecondsRealtime.waitTime = delay;
  1613. yield return m_WaitForSecondsRealtime;
  1614. }
  1615. m_DragCoroutine = null;
  1616. }
  1617. public virtual void OnEndDrag(PointerEventData eventData)
  1618. {
  1619. if (!MayDrag(eventData))
  1620. return;
  1621. m_UpdateDrag = false;
  1622. }
  1623. public override void OnPointerDown(PointerEventData eventData)
  1624. {
  1625. if (!MayDrag(eventData))
  1626. return;
  1627. EventSystem.current.SetSelectedGameObject(gameObject, eventData);
  1628. bool hadFocusBefore = m_AllowInput;
  1629. base.OnPointerDown(eventData);
  1630. if (InPlaceEditing() == false)
  1631. {
  1632. if (m_SoftKeyboard == null || !m_SoftKeyboard.active)
  1633. {
  1634. OnSelect(eventData);
  1635. return;
  1636. }
  1637. }
  1638. #if ENABLE_INPUT_SYSTEM
  1639. Event.PopEvent(m_ProcessingEvent);
  1640. bool shift = m_ProcessingEvent != null && (m_ProcessingEvent.modifiers & EventModifiers.Shift) != 0;
  1641. #else
  1642. bool shift = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
  1643. #endif
  1644. // Check for Double Click
  1645. bool isDoubleClick = false;
  1646. float timeStamp = Time.unscaledTime;
  1647. if (m_PointerDownClickStartTime + m_DoubleClickDelay > timeStamp)
  1648. isDoubleClick = true;
  1649. m_PointerDownClickStartTime = timeStamp;
  1650. // Only set caret position if we didn't just get focus now.
  1651. // Otherwise it will overwrite the select all on focus.
  1652. if (hadFocusBefore || !m_OnFocusSelectAll)
  1653. {
  1654. CaretPosition insertionSide;
  1655. int insertionIndex = TMP_TextUtilities.GetCursorIndexFromPosition(m_TextComponent, eventData.position, eventData.pressEventCamera, out insertionSide);
  1656. if (shift)
  1657. {
  1658. if (m_isRichTextEditingAllowed)
  1659. {
  1660. if (insertionSide == CaretPosition.Left)
  1661. {
  1662. stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index;
  1663. }
  1664. else if (insertionSide == CaretPosition.Right)
  1665. {
  1666. stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index + m_TextComponent.textInfo.characterInfo[insertionIndex].stringLength;
  1667. }
  1668. }
  1669. else
  1670. {
  1671. if (insertionSide == CaretPosition.Left)
  1672. {
  1673. stringSelectPositionInternal = insertionIndex == 0
  1674. ? m_TextComponent.textInfo.characterInfo[0].index
  1675. : m_TextComponent.textInfo.characterInfo[insertionIndex - 1].index + m_TextComponent.textInfo.characterInfo[insertionIndex - 1].stringLength;
  1676. }
  1677. else if (insertionSide == CaretPosition.Right)
  1678. {
  1679. stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index + m_TextComponent.textInfo.characterInfo[insertionIndex].stringLength;
  1680. }
  1681. }
  1682. }
  1683. else
  1684. {
  1685. if (m_isRichTextEditingAllowed)
  1686. {
  1687. if (insertionSide == CaretPosition.Left)
  1688. {
  1689. stringPositionInternal = stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index;
  1690. }
  1691. else if (insertionSide == CaretPosition.Right)
  1692. {
  1693. stringPositionInternal = stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index + m_TextComponent.textInfo.characterInfo[insertionIndex].stringLength;
  1694. }
  1695. }
  1696. else
  1697. {
  1698. if (insertionSide == CaretPosition.Left)
  1699. {
  1700. stringPositionInternal = stringSelectPositionInternal = insertionIndex == 0
  1701. ? m_TextComponent.textInfo.characterInfo[0].index
  1702. : m_TextComponent.textInfo.characterInfo[insertionIndex - 1].index + m_TextComponent.textInfo.characterInfo[insertionIndex - 1].stringLength;
  1703. }
  1704. else if (insertionSide == CaretPosition.Right)
  1705. {
  1706. stringPositionInternal = stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index + m_TextComponent.textInfo.characterInfo[insertionIndex].stringLength;
  1707. }
  1708. }
  1709. }
  1710. if (isDoubleClick)
  1711. {
  1712. int wordIndex = TMP_TextUtilities.FindIntersectingWord(m_TextComponent, eventData.position, eventData.pressEventCamera);
  1713. if (wordIndex != -1)
  1714. {
  1715. // TODO: Should behavior be different if rich text editing is enabled or not?
  1716. // Select current word
  1717. caretPositionInternal = m_TextComponent.textInfo.wordInfo[wordIndex].firstCharacterIndex;
  1718. caretSelectPositionInternal = m_TextComponent.textInfo.wordInfo[wordIndex].lastCharacterIndex + 1;
  1719. stringPositionInternal = m_TextComponent.textInfo.characterInfo[caretPositionInternal].index;
  1720. stringSelectPositionInternal = m_TextComponent.textInfo.characterInfo[caretSelectPositionInternal - 1].index + m_TextComponent.textInfo.characterInfo[caretSelectPositionInternal - 1].stringLength;
  1721. }
  1722. else
  1723. {
  1724. // Select current character
  1725. caretPositionInternal = insertionIndex;
  1726. caretSelectPositionInternal = caretPositionInternal + 1;
  1727. stringPositionInternal = m_TextComponent.textInfo.characterInfo[insertionIndex].index;
  1728. stringSelectPositionInternal = stringPositionInternal + m_TextComponent.textInfo.characterInfo[insertionIndex].stringLength;
  1729. }
  1730. }
  1731. else
  1732. {
  1733. caretPositionInternal = caretSelectPositionInternal = GetCaretPositionFromStringIndex(stringPositionInternal);
  1734. }
  1735. m_isSelectAll = false;
  1736. }
  1737. UpdateLabel();
  1738. UpdateKeyboardStringPosition();
  1739. eventData.Use();
  1740. #if TMP_DEBUG_MODE
  1741. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  1742. #endif
  1743. }
  1744. protected enum EditState
  1745. {
  1746. Continue,
  1747. Finish
  1748. }
  1749. protected EditState KeyPressed(Event evt)
  1750. {
  1751. var currentEventModifiers = evt.modifiers;
  1752. bool ctrl = m_IsApplePlatform ? (currentEventModifiers & EventModifiers.Command) != 0 : (currentEventModifiers & EventModifiers.Control) != 0;
  1753. bool shift = (currentEventModifiers & EventModifiers.Shift) != 0;
  1754. bool alt = (currentEventModifiers & EventModifiers.Alt) != 0;
  1755. bool ctrlOnly = ctrl && !alt && !shift;
  1756. m_LastKeyCode = evt.keyCode;
  1757. switch (evt.keyCode)
  1758. {
  1759. case KeyCode.Backspace:
  1760. {
  1761. Backspace();
  1762. return EditState.Continue;
  1763. }
  1764. case KeyCode.Delete:
  1765. {
  1766. DeleteKey();
  1767. return EditState.Continue;
  1768. }
  1769. case KeyCode.Home:
  1770. {
  1771. MoveToStartOfLine(shift, ctrl);
  1772. return EditState.Continue;
  1773. }
  1774. case KeyCode.End:
  1775. {
  1776. MoveToEndOfLine(shift, ctrl);
  1777. return EditState.Continue;
  1778. }
  1779. // Select All
  1780. case KeyCode.A:
  1781. {
  1782. if (ctrlOnly)
  1783. {
  1784. SelectAll();
  1785. return EditState.Continue;
  1786. }
  1787. break;
  1788. }
  1789. // Copy
  1790. case KeyCode.C:
  1791. {
  1792. if (ctrlOnly)
  1793. {
  1794. if (inputType != InputType.Password)
  1795. clipboard = GetSelectedString();
  1796. else
  1797. clipboard = "";
  1798. return EditState.Continue;
  1799. }
  1800. break;
  1801. }
  1802. // Paste
  1803. case KeyCode.V:
  1804. {
  1805. if (ctrlOnly)
  1806. {
  1807. Append(clipboard);
  1808. return EditState.Continue;
  1809. }
  1810. break;
  1811. }
  1812. // Cut
  1813. case KeyCode.X:
  1814. {
  1815. if (ctrlOnly)
  1816. {
  1817. if (inputType != InputType.Password)
  1818. clipboard = GetSelectedString();
  1819. else
  1820. clipboard = "";
  1821. Delete();
  1822. UpdateTouchKeyboardFromEditChanges();
  1823. SendOnValueChangedAndUpdateLabel();
  1824. return EditState.Continue;
  1825. }
  1826. break;
  1827. }
  1828. case KeyCode.LeftArrow:
  1829. {
  1830. MoveLeft(shift, ctrl);
  1831. return EditState.Continue;
  1832. }
  1833. case KeyCode.RightArrow:
  1834. {
  1835. MoveRight(shift, ctrl);
  1836. return EditState.Continue;
  1837. }
  1838. case KeyCode.UpArrow:
  1839. {
  1840. MoveUp(shift);
  1841. return EditState.Continue;
  1842. }
  1843. case KeyCode.DownArrow:
  1844. {
  1845. MoveDown(shift);
  1846. return EditState.Continue;
  1847. }
  1848. case KeyCode.PageUp:
  1849. {
  1850. MovePageUp(shift);
  1851. return EditState.Continue;
  1852. }
  1853. case KeyCode.PageDown:
  1854. {
  1855. MovePageDown(shift);
  1856. return EditState.Continue;
  1857. }
  1858. // Submit
  1859. case KeyCode.Return:
  1860. case KeyCode.KeypadEnter:
  1861. {
  1862. if (lineType != LineType.MultiLineNewline)
  1863. {
  1864. m_ReleaseSelection = true;
  1865. return EditState.Finish;
  1866. }
  1867. else
  1868. {
  1869. TMP_TextInfo textInfo = m_TextComponent.textInfo;
  1870. if (m_LineLimit > 0 && textInfo != null && textInfo.lineCount >= m_LineLimit)
  1871. {
  1872. m_ReleaseSelection = true;
  1873. return EditState.Finish;
  1874. }
  1875. }
  1876. break;
  1877. }
  1878. case KeyCode.Escape:
  1879. {
  1880. m_ReleaseSelection = true;
  1881. m_WasCanceled = true;
  1882. return EditState.Finish;
  1883. }
  1884. }
  1885. char c = evt.character;
  1886. // Don't allow return chars or tabulator key to be entered into single line fields.
  1887. if (!multiLine && (c == '\t' || c == '\r' || c == '\n'))
  1888. return EditState.Continue;
  1889. // Convert carriage return and end-of-text characters to newline.
  1890. if (c == '\r' || c == 3)
  1891. c = '\n';
  1892. // Convert Shift Enter to Vertical tab
  1893. if (shift && c == '\n')
  1894. c = '\v';
  1895. if (IsValidChar(c))
  1896. {
  1897. Append(c);
  1898. }
  1899. if (c == 0)
  1900. {
  1901. if (compositionLength > 0)
  1902. {
  1903. UpdateLabel();
  1904. }
  1905. }
  1906. return EditState.Continue;
  1907. }
  1908. protected virtual bool IsValidChar(char c)
  1909. {
  1910. // Delete key on mac
  1911. if (c == 127)
  1912. return false;
  1913. // Accept newline and tab
  1914. if (c == '\t' || c == '\n')
  1915. return true;
  1916. // Control characters (not printable)
  1917. if (c < 32)
  1918. return false;
  1919. return true;
  1920. // With the addition of Dynamic support, I think this will best be handled by the text component.
  1921. //return m_TextComponent.font.HasCharacter(c, true);
  1922. }
  1923. /// <summary>
  1924. /// Handle the specified event.
  1925. /// </summary>
  1926. private Event m_ProcessingEvent = new Event();
  1927. public void ProcessEvent(Event e)
  1928. {
  1929. KeyPressed(e);
  1930. }
  1931. /// <summary>
  1932. ///
  1933. /// </summary>
  1934. /// <param name="eventData"></param>
  1935. public virtual void OnUpdateSelected(BaseEventData eventData)
  1936. {
  1937. if (!isFocused)
  1938. return;
  1939. bool consumedEvent = false;
  1940. EditState editState = EditState.Continue;
  1941. while (Event.PopEvent(m_ProcessingEvent))
  1942. {
  1943. //Debug.Log("Event: " + m_ProcessingEvent.ToString() + " IsCompositionActive= " + m_IsCompositionActive + " Composition Length: " + compositionLength);
  1944. EventType eventType = m_ProcessingEvent.rawType;
  1945. if (eventType == EventType.KeyUp)
  1946. continue;
  1947. if (eventType == EventType.KeyDown)
  1948. {
  1949. consumedEvent = true;
  1950. // Special handling on OSX which produces more events which need to be suppressed.
  1951. if (m_IsCompositionActive && compositionLength == 0)
  1952. {
  1953. // Suppress other events related to navigation or termination of composition sequence.
  1954. if (m_ProcessingEvent.character == 0 && m_ProcessingEvent.modifiers == EventModifiers.None)
  1955. continue;
  1956. }
  1957. editState = KeyPressed(m_ProcessingEvent);
  1958. if (editState == EditState.Finish)
  1959. {
  1960. if (!m_WasCanceled)
  1961. SendOnSubmit();
  1962. DeactivateInputField();
  1963. break;
  1964. }
  1965. m_IsTextComponentUpdateRequired = true;
  1966. UpdateLabel();
  1967. continue;
  1968. }
  1969. switch (eventType)
  1970. {
  1971. case EventType.ValidateCommand:
  1972. case EventType.ExecuteCommand:
  1973. switch (m_ProcessingEvent.commandName)
  1974. {
  1975. case "SelectAll":
  1976. SelectAll();
  1977. consumedEvent = true;
  1978. break;
  1979. }
  1980. break;
  1981. }
  1982. }
  1983. if (consumedEvent)
  1984. {
  1985. UpdateLabel();
  1986. eventData.Use();
  1987. }
  1988. }
  1989. /// <summary>
  1990. ///
  1991. /// </summary>
  1992. /// <param name="eventData"></param>
  1993. public virtual void OnScroll(PointerEventData eventData)
  1994. {
  1995. // Return if Single Line
  1996. if (m_LineType == LineType.SingleLine)
  1997. {
  1998. if (m_IScrollHandlerParent != null)
  1999. m_IScrollHandlerParent.OnScroll(eventData);
  2000. return;
  2001. }
  2002. if (m_TextComponent.preferredHeight < m_TextViewport.rect.height)
  2003. return;
  2004. float scrollDirection = -eventData.scrollDelta.y;
  2005. // Determine the current scroll position of the text within the viewport
  2006. m_ScrollPosition = GetScrollPositionRelativeToViewport();
  2007. m_ScrollPosition += (1f / m_TextComponent.textInfo.lineCount) * scrollDirection * m_ScrollSensitivity;
  2008. m_ScrollPosition = Mathf.Clamp01(m_ScrollPosition);
  2009. AdjustTextPositionRelativeToViewport(m_ScrollPosition);
  2010. if (m_VerticalScrollbar)
  2011. {
  2012. m_VerticalScrollbar.value = m_ScrollPosition;
  2013. }
  2014. //Debug.Log(GetInstanceID() + "- Scroll Position:" + m_ScrollPosition);
  2015. }
  2016. float GetScrollPositionRelativeToViewport()
  2017. {
  2018. // Determine the current scroll position of the text within the viewport
  2019. Rect viewportRect = m_TextViewport.rect;
  2020. float scrollPosition = (m_TextComponent.textInfo.lineInfo[0].ascender + m_TextComponent.margin.y + m_TextComponent.margin.w - viewportRect.yMax + m_TextComponent.rectTransform.anchoredPosition.y) / ( m_TextComponent.preferredHeight - viewportRect.height);
  2021. scrollPosition = (int)((scrollPosition * 1000) + 0.5f) / 1000.0f;
  2022. return scrollPosition;
  2023. }
  2024. private string GetSelectedString()
  2025. {
  2026. if (!hasSelection)
  2027. return "";
  2028. int startPos = stringPositionInternal;
  2029. int endPos = stringSelectPositionInternal;
  2030. // Ensure pos is always less then selPos to make the code simpler
  2031. if (startPos > endPos)
  2032. {
  2033. int temp = startPos;
  2034. startPos = endPos;
  2035. endPos = temp;
  2036. }
  2037. //for (int i = m_CaretPosition; i < m_CaretSelectPosition; i++)
  2038. //{
  2039. // Debug.Log("Character [" + m_TextComponent.textInfo.characterInfo[i].character + "] using Style [" + m_TextComponent.textInfo.characterInfo[i].style + "] has been selected.");
  2040. //}
  2041. return text.Substring(startPos, endPos - startPos);
  2042. }
  2043. private int FindNextWordBegin()
  2044. {
  2045. if (stringSelectPositionInternal + 1 >= text.Length)
  2046. return text.Length;
  2047. int spaceLoc = text.IndexOfAny(kSeparators, stringSelectPositionInternal + 1);
  2048. if (spaceLoc == -1)
  2049. spaceLoc = text.Length;
  2050. else
  2051. spaceLoc++;
  2052. return spaceLoc;
  2053. }
  2054. private void MoveRight(bool shift, bool ctrl)
  2055. {
  2056. if (hasSelection && !shift)
  2057. {
  2058. // By convention, if we have a selection and move right without holding shift,
  2059. // we just place the cursor at the end.
  2060. stringPositionInternal = stringSelectPositionInternal = Mathf.Max(stringPositionInternal, stringSelectPositionInternal);
  2061. caretPositionInternal = caretSelectPositionInternal = GetCaretPositionFromStringIndex(stringSelectPositionInternal);
  2062. #if TMP_DEBUG_MODE
  2063. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  2064. #endif
  2065. return;
  2066. }
  2067. int position;
  2068. if (ctrl)
  2069. position = FindNextWordBegin();
  2070. else
  2071. {
  2072. if (m_isRichTextEditingAllowed)
  2073. {
  2074. // Special handling for Surrogate pairs and Diacritical marks.
  2075. if (stringSelectPositionInternal < text.Length && char.IsHighSurrogate(text[stringSelectPositionInternal]))
  2076. position = stringSelectPositionInternal + 2;
  2077. else
  2078. position = stringSelectPositionInternal + 1;
  2079. }
  2080. else
  2081. {
  2082. // Special handling for <CR><LF>
  2083. if (m_TextComponent.textInfo.characterInfo[caretSelectPositionInternal].character == '\r' && m_TextComponent.textInfo.characterInfo[caretSelectPositionInternal + 1].character == '\n')
  2084. position = m_TextComponent.textInfo.characterInfo[caretSelectPositionInternal + 1].index + m_TextComponent.textInfo.characterInfo[caretSelectPositionInternal + 1].stringLength;
  2085. else
  2086. position = m_TextComponent.textInfo.characterInfo[caretSelectPositionInternal].index + m_TextComponent.textInfo.characterInfo[caretSelectPositionInternal].stringLength;
  2087. }
  2088. }
  2089. if (shift)
  2090. {
  2091. stringSelectPositionInternal = position;
  2092. caretSelectPositionInternal = GetCaretPositionFromStringIndex(stringSelectPositionInternal);
  2093. }
  2094. else
  2095. {
  2096. stringSelectPositionInternal = stringPositionInternal = position;
  2097. // Only increase caret position as we cross character boundary.
  2098. if (stringPositionInternal >= m_TextComponent.textInfo.characterInfo[caretPositionInternal].index + m_TextComponent.textInfo.characterInfo[caretPositionInternal].stringLength)
  2099. caretSelectPositionInternal = caretPositionInternal = GetCaretPositionFromStringIndex(stringSelectPositionInternal);
  2100. }
  2101. #if TMP_DEBUG_MODE
  2102. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  2103. #endif
  2104. }
  2105. private int FindPrevWordBegin()
  2106. {
  2107. if (stringSelectPositionInternal - 2 < 0)
  2108. return 0;
  2109. int spaceLoc = text.LastIndexOfAny(kSeparators, stringSelectPositionInternal - 2);
  2110. if (spaceLoc == -1)
  2111. spaceLoc = 0;
  2112. else
  2113. spaceLoc++;
  2114. return spaceLoc;
  2115. }
  2116. private void MoveLeft(bool shift, bool ctrl)
  2117. {
  2118. if (hasSelection && !shift)
  2119. {
  2120. // By convention, if we have a selection and move left without holding shift,
  2121. // we just place the cursor at the start.
  2122. stringPositionInternal = stringSelectPositionInternal = Mathf.Min(stringPositionInternal, stringSelectPositionInternal);
  2123. caretPositionInternal = caretSelectPositionInternal = GetCaretPositionFromStringIndex(stringSelectPositionInternal);
  2124. #if TMP_DEBUG_MODE
  2125. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  2126. #endif
  2127. return;
  2128. }
  2129. int position;
  2130. if (ctrl)
  2131. position = FindPrevWordBegin();
  2132. else
  2133. {
  2134. if (m_isRichTextEditingAllowed)
  2135. {
  2136. // Special handling for Surrogate pairs and Diacritical marks.
  2137. if (stringSelectPositionInternal > 0 && char.IsLowSurrogate(text[stringSelectPositionInternal - 1]))
  2138. position = stringSelectPositionInternal - 2;
  2139. else
  2140. position = stringSelectPositionInternal - 1;
  2141. }
  2142. else
  2143. {
  2144. position = caretSelectPositionInternal < 1
  2145. ? m_TextComponent.textInfo.characterInfo[0].index
  2146. : m_TextComponent.textInfo.characterInfo[caretSelectPositionInternal - 1].index;
  2147. // Special handling for <CR><LF>
  2148. if (position > 0 && m_TextComponent.textInfo.characterInfo[caretSelectPositionInternal - 1].character == '\n' && m_TextComponent.textInfo.characterInfo[caretSelectPositionInternal - 2].character == '\r')
  2149. position = m_TextComponent.textInfo.characterInfo[caretSelectPositionInternal - 2].index;
  2150. }
  2151. }
  2152. if (shift)
  2153. {
  2154. stringSelectPositionInternal = position;
  2155. caretSelectPositionInternal = GetCaretPositionFromStringIndex(stringSelectPositionInternal);
  2156. }
  2157. else
  2158. {
  2159. stringSelectPositionInternal = stringPositionInternal = position;
  2160. // Only decrease caret position as we cross character boundary.
  2161. if (caretPositionInternal > 0 && stringPositionInternal <= m_TextComponent.textInfo.characterInfo[caretPositionInternal - 1].index)
  2162. caretSelectPositionInternal = caretPositionInternal = GetCaretPositionFromStringIndex(stringSelectPositionInternal);
  2163. }
  2164. #if TMP_DEBUG_MODE
  2165. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  2166. #endif
  2167. }
  2168. private int LineUpCharacterPosition(int originalPos, bool goToFirstChar)
  2169. {
  2170. if (originalPos >= m_TextComponent.textInfo.characterCount)
  2171. originalPos -= 1;
  2172. TMP_CharacterInfo originChar = m_TextComponent.textInfo.characterInfo[originalPos];
  2173. int originLine = originChar.lineNumber;
  2174. // We are on the first line return first character
  2175. if (originLine - 1 < 0)
  2176. return goToFirstChar ? 0 : originalPos;
  2177. int endCharIdx = m_TextComponent.textInfo.lineInfo[originLine].firstCharacterIndex - 1;
  2178. int closest = -1;
  2179. float distance = TMP_Math.FLOAT_MAX;
  2180. float range = 0;
  2181. for (int i = m_TextComponent.textInfo.lineInfo[originLine - 1].firstCharacterIndex; i < endCharIdx; ++i)
  2182. {
  2183. TMP_CharacterInfo currentChar = m_TextComponent.textInfo.characterInfo[i];
  2184. float d = originChar.origin - currentChar.origin;
  2185. float r = d / (currentChar.xAdvance - currentChar.origin);
  2186. if (r >= 0 && r <= 1)
  2187. {
  2188. if (r < 0.5f)
  2189. return i;
  2190. else
  2191. return i + 1;
  2192. }
  2193. d = Mathf.Abs(d);
  2194. if (d < distance)
  2195. {
  2196. closest = i;
  2197. distance = d;
  2198. range = r;
  2199. }
  2200. }
  2201. if (closest == -1) return endCharIdx;
  2202. //Debug.Log("Returning nearest character with Range = " + range);
  2203. if (range < 0.5f)
  2204. return closest;
  2205. else
  2206. return closest + 1;
  2207. }
  2208. private int LineDownCharacterPosition(int originalPos, bool goToLastChar)
  2209. {
  2210. if (originalPos >= m_TextComponent.textInfo.characterCount)
  2211. return m_TextComponent.textInfo.characterCount - 1; // text.Length;
  2212. TMP_CharacterInfo originChar = m_TextComponent.textInfo.characterInfo[originalPos];
  2213. int originLine = originChar.lineNumber;
  2214. //// We are on the last line return last character
  2215. if (originLine + 1 >= m_TextComponent.textInfo.lineCount)
  2216. return goToLastChar ? m_TextComponent.textInfo.characterCount - 1 : originalPos;
  2217. // Need to determine end line for next line.
  2218. int endCharIdx = m_TextComponent.textInfo.lineInfo[originLine + 1].lastCharacterIndex;
  2219. int closest = -1;
  2220. float distance = TMP_Math.FLOAT_MAX;
  2221. float range = 0;
  2222. for (int i = m_TextComponent.textInfo.lineInfo[originLine + 1].firstCharacterIndex; i < endCharIdx; ++i)
  2223. {
  2224. TMP_CharacterInfo currentChar = m_TextComponent.textInfo.characterInfo[i];
  2225. float d = originChar.origin - currentChar.origin;
  2226. float r = d / (currentChar.xAdvance - currentChar.origin);
  2227. if (r >= 0 && r <= 1)
  2228. {
  2229. if (r < 0.5f)
  2230. return i;
  2231. else
  2232. return i + 1;
  2233. }
  2234. d = Mathf.Abs(d);
  2235. if (d < distance)
  2236. {
  2237. closest = i;
  2238. distance = d;
  2239. range = r;
  2240. }
  2241. }
  2242. if (closest == -1) return endCharIdx;
  2243. //Debug.Log("Returning nearest character with Range = " + range);
  2244. if (range < 0.5f)
  2245. return closest;
  2246. else
  2247. return closest + 1;
  2248. }
  2249. private int PageUpCharacterPosition(int originalPos, bool goToFirstChar)
  2250. {
  2251. if (originalPos >= m_TextComponent.textInfo.characterCount)
  2252. originalPos -= 1;
  2253. TMP_CharacterInfo originChar = m_TextComponent.textInfo.characterInfo[originalPos];
  2254. int originLine = originChar.lineNumber;
  2255. // We are on the first line return first character
  2256. if (originLine - 1 < 0)
  2257. return goToFirstChar ? 0 : originalPos;
  2258. float viewportHeight = m_TextViewport.rect.height;
  2259. int newLine = originLine - 1;
  2260. // Iterate through each subsequent line to find the first baseline that is not visible in the viewport.
  2261. for (; newLine > 0; newLine--)
  2262. {
  2263. if (m_TextComponent.textInfo.lineInfo[newLine].baseline > m_TextComponent.textInfo.lineInfo[originLine].baseline + viewportHeight)
  2264. break;
  2265. }
  2266. int endCharIdx = m_TextComponent.textInfo.lineInfo[newLine].lastCharacterIndex;
  2267. int closest = -1;
  2268. float distance = TMP_Math.FLOAT_MAX;
  2269. float range = 0;
  2270. for (int i = m_TextComponent.textInfo.lineInfo[newLine].firstCharacterIndex; i < endCharIdx; ++i)
  2271. {
  2272. TMP_CharacterInfo currentChar = m_TextComponent.textInfo.characterInfo[i];
  2273. float d = originChar.origin - currentChar.origin;
  2274. float r = d / (currentChar.xAdvance - currentChar.origin);
  2275. if (r >= 0 && r <= 1)
  2276. {
  2277. if (r < 0.5f)
  2278. return i;
  2279. else
  2280. return i + 1;
  2281. }
  2282. d = Mathf.Abs(d);
  2283. if (d < distance)
  2284. {
  2285. closest = i;
  2286. distance = d;
  2287. range = r;
  2288. }
  2289. }
  2290. if (closest == -1) return endCharIdx;
  2291. //Debug.Log("Returning nearest character with Range = " + range);
  2292. if (range < 0.5f)
  2293. return closest;
  2294. else
  2295. return closest + 1;
  2296. }
  2297. private int PageDownCharacterPosition(int originalPos, bool goToLastChar)
  2298. {
  2299. if (originalPos >= m_TextComponent.textInfo.characterCount)
  2300. return m_TextComponent.textInfo.characterCount - 1;
  2301. TMP_CharacterInfo originChar = m_TextComponent.textInfo.characterInfo[originalPos];
  2302. int originLine = originChar.lineNumber;
  2303. // We are on the last line return last character
  2304. if (originLine + 1 >= m_TextComponent.textInfo.lineCount)
  2305. return goToLastChar ? m_TextComponent.textInfo.characterCount - 1 : originalPos;
  2306. float viewportHeight = m_TextViewport.rect.height;
  2307. int newLine = originLine + 1;
  2308. // Iterate through each subsequent line to find the first baseline that is not visible in the viewport.
  2309. for (; newLine < m_TextComponent.textInfo.lineCount - 1; newLine++)
  2310. {
  2311. if (m_TextComponent.textInfo.lineInfo[newLine].baseline < m_TextComponent.textInfo.lineInfo[originLine].baseline - viewportHeight)
  2312. break;
  2313. }
  2314. // Need to determine end line for next line.
  2315. int endCharIdx = m_TextComponent.textInfo.lineInfo[newLine].lastCharacterIndex;
  2316. int closest = -1;
  2317. float distance = TMP_Math.FLOAT_MAX;
  2318. float range = 0;
  2319. for (int i = m_TextComponent.textInfo.lineInfo[newLine].firstCharacterIndex; i < endCharIdx; ++i)
  2320. {
  2321. TMP_CharacterInfo currentChar = m_TextComponent.textInfo.characterInfo[i];
  2322. float d = originChar.origin - currentChar.origin;
  2323. float r = d / (currentChar.xAdvance - currentChar.origin);
  2324. if (r >= 0 && r <= 1)
  2325. {
  2326. if (r < 0.5f)
  2327. return i;
  2328. else
  2329. return i + 1;
  2330. }
  2331. d = Mathf.Abs(d);
  2332. if (d < distance)
  2333. {
  2334. closest = i;
  2335. distance = d;
  2336. range = r;
  2337. }
  2338. }
  2339. if (closest == -1) return endCharIdx;
  2340. if (range < 0.5f)
  2341. return closest;
  2342. else
  2343. return closest + 1;
  2344. }
  2345. private void MoveDown(bool shift)
  2346. {
  2347. MoveDown(shift, true);
  2348. }
  2349. private void MoveDown(bool shift, bool goToLastChar)
  2350. {
  2351. if (hasSelection && !shift)
  2352. {
  2353. // If we have a selection and press down without shift,
  2354. // set caret to end of selection before we move it down.
  2355. caretPositionInternal = caretSelectPositionInternal = Mathf.Max(caretPositionInternal, caretSelectPositionInternal);
  2356. }
  2357. int position = multiLine ? LineDownCharacterPosition(caretSelectPositionInternal, goToLastChar) : m_TextComponent.textInfo.characterCount - 1; // text.Length;
  2358. if (shift)
  2359. {
  2360. caretSelectPositionInternal = position;
  2361. stringSelectPositionInternal = GetStringIndexFromCaretPosition(caretSelectPositionInternal);
  2362. }
  2363. else
  2364. {
  2365. caretSelectPositionInternal = caretPositionInternal = position;
  2366. stringSelectPositionInternal = stringPositionInternal = GetStringIndexFromCaretPosition(caretSelectPositionInternal);
  2367. }
  2368. #if TMP_DEBUG_MODE
  2369. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  2370. #endif
  2371. }
  2372. private void MoveUp(bool shift)
  2373. {
  2374. MoveUp(shift, true);
  2375. }
  2376. private void MoveUp(bool shift, bool goToFirstChar)
  2377. {
  2378. if (hasSelection && !shift)
  2379. {
  2380. // If we have a selection and press up without shift,
  2381. // set caret position to start of selection before we move it up.
  2382. caretPositionInternal = caretSelectPositionInternal = Mathf.Min(caretPositionInternal, caretSelectPositionInternal);
  2383. }
  2384. int position = multiLine ? LineUpCharacterPosition(caretSelectPositionInternal, goToFirstChar) : 0;
  2385. if (shift)
  2386. {
  2387. caretSelectPositionInternal = position;
  2388. stringSelectPositionInternal = GetStringIndexFromCaretPosition(caretSelectPositionInternal);
  2389. }
  2390. else
  2391. {
  2392. caretSelectPositionInternal = caretPositionInternal = position;
  2393. stringSelectPositionInternal = stringPositionInternal = GetStringIndexFromCaretPosition(caretSelectPositionInternal);
  2394. }
  2395. #if TMP_DEBUG_MODE
  2396. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  2397. #endif
  2398. }
  2399. private void MovePageUp(bool shift)
  2400. {
  2401. MovePageUp(shift, true);
  2402. }
  2403. private void MovePageUp(bool shift, bool goToFirstChar)
  2404. {
  2405. if (hasSelection && !shift)
  2406. {
  2407. // If we have a selection and press up without shift,
  2408. // set caret position to start of selection before we move it up.
  2409. caretPositionInternal = caretSelectPositionInternal = Mathf.Min(caretPositionInternal, caretSelectPositionInternal);
  2410. }
  2411. int position = multiLine ? PageUpCharacterPosition(caretSelectPositionInternal, goToFirstChar) : 0;
  2412. if (shift)
  2413. {
  2414. caretSelectPositionInternal = position;
  2415. stringSelectPositionInternal = GetStringIndexFromCaretPosition(caretSelectPositionInternal);
  2416. }
  2417. else
  2418. {
  2419. caretSelectPositionInternal = caretPositionInternal = position;
  2420. stringSelectPositionInternal = stringPositionInternal = GetStringIndexFromCaretPosition(caretSelectPositionInternal);
  2421. }
  2422. // Scroll to top of viewport
  2423. //int currentLine = m_TextComponent.textInfo.characterInfo[position].lineNumber;
  2424. //float lineAscender = m_TextComponent.textInfo.lineInfo[currentLine].ascender;
  2425. // Adjust text area up or down if not in single line mode.
  2426. if (m_LineType != LineType.SingleLine)
  2427. {
  2428. float offset = m_TextViewport.rect.height; // m_TextViewport.rect.yMax - (m_TextComponent.rectTransform.anchoredPosition.y + lineAscender);
  2429. float topTextBounds = m_TextComponent.rectTransform.position.y + m_TextComponent.textBounds.max.y;
  2430. float topViewportBounds = m_TextViewport.position.y + m_TextViewport.rect.yMax;
  2431. offset = topViewportBounds > topTextBounds + offset ? offset : topViewportBounds - topTextBounds;
  2432. m_TextComponent.rectTransform.anchoredPosition += new Vector2(0, offset);
  2433. AssignPositioningIfNeeded();
  2434. }
  2435. #if TMP_DEBUG_MODE
  2436. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  2437. #endif
  2438. }
  2439. private void MovePageDown(bool shift)
  2440. {
  2441. MovePageDown(shift, true);
  2442. }
  2443. private void MovePageDown(bool shift, bool goToLastChar)
  2444. {
  2445. if (hasSelection && !shift)
  2446. {
  2447. // If we have a selection and press down without shift,
  2448. // set caret to end of selection before we move it down.
  2449. caretPositionInternal = caretSelectPositionInternal = Mathf.Max(caretPositionInternal, caretSelectPositionInternal);
  2450. }
  2451. int position = multiLine ? PageDownCharacterPosition(caretSelectPositionInternal, goToLastChar) : m_TextComponent.textInfo.characterCount - 1;
  2452. if (shift)
  2453. {
  2454. caretSelectPositionInternal = position;
  2455. stringSelectPositionInternal = GetStringIndexFromCaretPosition(caretSelectPositionInternal);
  2456. }
  2457. else
  2458. {
  2459. caretSelectPositionInternal = caretPositionInternal = position;
  2460. stringSelectPositionInternal = stringPositionInternal = GetStringIndexFromCaretPosition(caretSelectPositionInternal);
  2461. }
  2462. // Scroll to top of viewport
  2463. //int currentLine = m_TextComponent.textInfo.characterInfo[position].lineNumber;
  2464. //float lineAscender = m_TextComponent.textInfo.lineInfo[currentLine].ascender;
  2465. // Adjust text area up or down if not in single line mode.
  2466. if (m_LineType != LineType.SingleLine)
  2467. {
  2468. float offset = m_TextViewport.rect.height; // m_TextViewport.rect.yMax - (m_TextComponent.rectTransform.anchoredPosition.y + lineAscender);
  2469. float bottomTextBounds = m_TextComponent.rectTransform.position.y + m_TextComponent.textBounds.min.y;
  2470. float bottomViewportBounds = m_TextViewport.position.y + m_TextViewport.rect.yMin;
  2471. offset = bottomViewportBounds > bottomTextBounds + offset ? offset : bottomViewportBounds - bottomTextBounds;
  2472. m_TextComponent.rectTransform.anchoredPosition += new Vector2(0, offset);
  2473. AssignPositioningIfNeeded();
  2474. }
  2475. #if TMP_DEBUG_MODE
  2476. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  2477. #endif
  2478. }
  2479. private void Delete()
  2480. {
  2481. if (m_ReadOnly)
  2482. return;
  2483. if (m_StringPosition == m_StringSelectPosition)
  2484. return;
  2485. if (m_isRichTextEditingAllowed || m_isSelectAll)
  2486. {
  2487. // Handling of Delete when Rich Text is allowed.
  2488. if (m_StringPosition < m_StringSelectPosition)
  2489. {
  2490. m_Text = text.Remove(m_StringPosition, m_StringSelectPosition - m_StringPosition);
  2491. m_StringSelectPosition = m_StringPosition;
  2492. }
  2493. else
  2494. {
  2495. m_Text = text.Remove(m_StringSelectPosition, m_StringPosition - m_StringSelectPosition);
  2496. m_StringPosition = m_StringSelectPosition;
  2497. }
  2498. if (m_isSelectAll)
  2499. {
  2500. m_CaretPosition = m_CaretSelectPosition = 0;
  2501. m_isSelectAll = false;
  2502. }
  2503. }
  2504. else
  2505. {
  2506. if (m_CaretPosition < m_CaretSelectPosition)
  2507. {
  2508. int index = ClampArrayIndex(m_CaretSelectPosition - 1);
  2509. m_StringPosition = m_TextComponent.textInfo.characterInfo[m_CaretPosition].index;
  2510. m_StringSelectPosition = m_TextComponent.textInfo.characterInfo[index].index + m_TextComponent.textInfo.characterInfo[index].stringLength;
  2511. m_Text = text.Remove(m_StringPosition, m_StringSelectPosition - m_StringPosition);
  2512. m_StringSelectPosition = m_StringPosition;
  2513. m_CaretSelectPosition = m_CaretPosition;
  2514. }
  2515. else
  2516. {
  2517. int index = ClampArrayIndex(m_CaretPosition - 1);
  2518. m_StringPosition = m_TextComponent.textInfo.characterInfo[index].index + m_TextComponent.textInfo.characterInfo[index].stringLength;
  2519. m_StringSelectPosition = m_TextComponent.textInfo.characterInfo[m_CaretSelectPosition].index;
  2520. m_Text = text.Remove(m_StringSelectPosition, m_StringPosition - m_StringSelectPosition);
  2521. m_StringPosition = m_StringSelectPosition;
  2522. m_CaretPosition = m_CaretSelectPosition;
  2523. }
  2524. }
  2525. #if TMP_DEBUG_MODE
  2526. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  2527. #endif
  2528. }
  2529. /// <summary>
  2530. /// Handling of DEL key
  2531. /// </summary>
  2532. private void DeleteKey()
  2533. {
  2534. if (m_ReadOnly)
  2535. return;
  2536. if (hasSelection)
  2537. {
  2538. m_HasTextBeenRemoved = true;
  2539. Delete();
  2540. UpdateTouchKeyboardFromEditChanges();
  2541. SendOnValueChangedAndUpdateLabel();
  2542. }
  2543. else
  2544. {
  2545. if (m_isRichTextEditingAllowed)
  2546. {
  2547. if (stringPositionInternal < text.Length)
  2548. {
  2549. // Special handling for Surrogate Pairs
  2550. if (char.IsHighSurrogate(text[stringPositionInternal]))
  2551. m_Text = text.Remove(stringPositionInternal, 2);
  2552. else
  2553. m_Text = text.Remove(stringPositionInternal, 1);
  2554. m_HasTextBeenRemoved = true;
  2555. UpdateTouchKeyboardFromEditChanges();
  2556. SendOnValueChangedAndUpdateLabel();
  2557. }
  2558. }
  2559. else
  2560. {
  2561. if (caretPositionInternal < m_TextComponent.textInfo.characterCount - 1)
  2562. {
  2563. int numberOfCharactersToRemove = m_TextComponent.textInfo.characterInfo[caretPositionInternal].stringLength;
  2564. // Special handling for <CR><LF>
  2565. if (m_TextComponent.textInfo.characterInfo[caretPositionInternal].character == '\r' && m_TextComponent.textInfo.characterInfo[caretPositionInternal + 1].character == '\n')
  2566. numberOfCharactersToRemove += m_TextComponent.textInfo.characterInfo[caretPositionInternal + 1].stringLength;
  2567. // Adjust string position to skip any potential rich text tags.
  2568. int nextCharacterStringPosition = m_TextComponent.textInfo.characterInfo[caretPositionInternal].index;
  2569. m_Text = text.Remove(nextCharacterStringPosition, numberOfCharactersToRemove);
  2570. m_HasTextBeenRemoved = true;
  2571. SendOnValueChangedAndUpdateLabel();
  2572. }
  2573. }
  2574. }
  2575. #if TMP_DEBUG_MODE
  2576. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  2577. #endif
  2578. }
  2579. /// <summary>
  2580. /// Handling of Backspace key
  2581. /// </summary>
  2582. private void Backspace()
  2583. {
  2584. if (m_ReadOnly)
  2585. return;
  2586. if (hasSelection)
  2587. {
  2588. m_HasTextBeenRemoved = true;
  2589. Delete();
  2590. UpdateTouchKeyboardFromEditChanges();
  2591. SendOnValueChangedAndUpdateLabel();
  2592. }
  2593. else
  2594. {
  2595. if (m_isRichTextEditingAllowed)
  2596. {
  2597. if (stringPositionInternal > 0)
  2598. {
  2599. int numberOfCharactersToRemove = 1;
  2600. // Special handling for Surrogate pairs and Diacritical marks
  2601. if (char.IsLowSurrogate(text[stringPositionInternal - 1]))
  2602. numberOfCharactersToRemove = 2;
  2603. stringSelectPositionInternal = stringPositionInternal = stringPositionInternal - numberOfCharactersToRemove;
  2604. m_Text = text.Remove(stringPositionInternal, numberOfCharactersToRemove);
  2605. caretSelectPositionInternal = caretPositionInternal = caretPositionInternal - 1;
  2606. m_HasTextBeenRemoved = true;
  2607. UpdateTouchKeyboardFromEditChanges();
  2608. SendOnValueChangedAndUpdateLabel();
  2609. }
  2610. }
  2611. else
  2612. {
  2613. if (caretPositionInternal > 0)
  2614. {
  2615. int caretPositionIndex = caretPositionInternal - 1;
  2616. int numberOfCharactersToRemove = m_TextComponent.textInfo.characterInfo[caretPositionIndex].stringLength;
  2617. // Special handling for <CR><LR>
  2618. if (caretPositionIndex > 0 && m_TextComponent.textInfo.characterInfo[caretPositionIndex].character == '\n' && m_TextComponent.textInfo.characterInfo[caretPositionIndex - 1].character == '\r')
  2619. {
  2620. numberOfCharactersToRemove += m_TextComponent.textInfo.characterInfo[caretPositionIndex - 1].stringLength;
  2621. caretPositionIndex -= 1;
  2622. }
  2623. // Delete the previous character
  2624. m_Text = text.Remove(m_TextComponent.textInfo.characterInfo[caretPositionIndex].index, numberOfCharactersToRemove);
  2625. // Get new adjusted string position
  2626. stringSelectPositionInternal = stringPositionInternal = caretPositionInternal < 1
  2627. ? m_TextComponent.textInfo.characterInfo[0].index
  2628. : m_TextComponent.textInfo.characterInfo[caretPositionIndex].index;
  2629. caretSelectPositionInternal = caretPositionInternal = caretPositionIndex;
  2630. }
  2631. m_HasTextBeenRemoved = true;
  2632. UpdateTouchKeyboardFromEditChanges();
  2633. SendOnValueChangedAndUpdateLabel();
  2634. }
  2635. }
  2636. #if TMP_DEBUG_MODE
  2637. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  2638. #endif
  2639. }
  2640. /// <summary>
  2641. /// Append the specified text to the end of the current.
  2642. /// </summary>
  2643. protected virtual void Append(string input)
  2644. {
  2645. if (m_ReadOnly)
  2646. return;
  2647. if (InPlaceEditing() == false)
  2648. return;
  2649. for (int i = 0, imax = input.Length; i < imax; ++i)
  2650. {
  2651. char c = input[i];
  2652. if (c >= ' ' || c == '\t' || c == '\r' || c == '\n')
  2653. {
  2654. Append(c);
  2655. }
  2656. }
  2657. }
  2658. protected virtual void Append(char input)
  2659. {
  2660. if (m_ReadOnly)
  2661. return;
  2662. if (InPlaceEditing() == false)
  2663. return;
  2664. // If we have an input validator, validate the input first
  2665. int insertionPosition = Mathf.Min(stringPositionInternal, stringSelectPositionInternal);
  2666. //Get the text based on selection for validation instead of whole text(case 1253193).
  2667. var validateText = text;
  2668. if (selectionFocusPosition != selectionAnchorPosition)
  2669. {
  2670. m_HasTextBeenRemoved = true;
  2671. if (m_isRichTextEditingAllowed || m_isSelectAll)
  2672. {
  2673. // Handling of Delete when Rich Text is allowed.
  2674. if (m_StringPosition < m_StringSelectPosition)
  2675. validateText = text.Remove(m_StringPosition, m_StringSelectPosition - m_StringPosition);
  2676. else
  2677. validateText = text.Remove(m_StringSelectPosition, m_StringPosition - m_StringSelectPosition);
  2678. }
  2679. else
  2680. {
  2681. if (m_CaretPosition < m_CaretSelectPosition)
  2682. {
  2683. m_StringPosition = m_TextComponent.textInfo.characterInfo[m_CaretPosition].index;
  2684. m_StringSelectPosition = m_TextComponent.textInfo.characterInfo[m_CaretSelectPosition - 1].index + m_TextComponent.textInfo.characterInfo[m_CaretSelectPosition - 1].stringLength;
  2685. validateText = text.Remove(m_StringPosition, m_StringSelectPosition - m_StringPosition);
  2686. }
  2687. else
  2688. {
  2689. m_StringPosition = m_TextComponent.textInfo.characterInfo[m_CaretPosition - 1].index + m_TextComponent.textInfo.characterInfo[m_CaretPosition - 1].stringLength;
  2690. m_StringSelectPosition = m_TextComponent.textInfo.characterInfo[m_CaretSelectPosition].index;
  2691. validateText = text.Remove(m_StringSelectPosition, m_StringPosition - m_StringSelectPosition);
  2692. }
  2693. }
  2694. }
  2695. if (onValidateInput != null)
  2696. {
  2697. input = onValidateInput(validateText, insertionPosition, input);
  2698. }
  2699. else if (characterValidation == CharacterValidation.CustomValidator)
  2700. {
  2701. input = Validate(validateText, insertionPosition, input);
  2702. if (input == 0) return;
  2703. SendOnValueChanged();
  2704. UpdateLabel();
  2705. return;
  2706. }
  2707. else if (characterValidation != CharacterValidation.None)
  2708. {
  2709. input = Validate(validateText, insertionPosition, input);
  2710. }
  2711. // If the input is invalid, skip it
  2712. if (input == 0)
  2713. return;
  2714. // Append the character and update the label
  2715. Insert(input);
  2716. }
  2717. // Insert the character and update the label.
  2718. private void Insert(char c)
  2719. {
  2720. if (m_ReadOnly)
  2721. return;
  2722. //Debug.Log("Inserting character " + m_IsCompositionActive);
  2723. string replaceString = c.ToString();
  2724. Delete();
  2725. // Can't go past the character limit
  2726. if (characterLimit > 0 && text.Length >= characterLimit)
  2727. return;
  2728. m_Text = text.Insert(m_StringPosition, replaceString);
  2729. if (!char.IsHighSurrogate(c))
  2730. m_CaretSelectPosition = m_CaretPosition += 1;
  2731. m_StringSelectPosition = m_StringPosition += 1;
  2732. UpdateTouchKeyboardFromEditChanges();
  2733. SendOnValueChanged();
  2734. #if TMP_DEBUG_MODE
  2735. Debug.Log("Caret Position: " + caretPositionInternal + " Selection Position: " + caretSelectPositionInternal + " String Position: " + stringPositionInternal + " String Select Position: " + stringSelectPositionInternal);
  2736. #endif
  2737. }
  2738. private void UpdateTouchKeyboardFromEditChanges()
  2739. {
  2740. // Update the TouchKeyboard's text from edit changes
  2741. // if in-place editing is allowed
  2742. if (m_SoftKeyboard != null && InPlaceEditing())
  2743. {
  2744. m_SoftKeyboard.text = m_Text;
  2745. }
  2746. }
  2747. private void SendOnValueChangedAndUpdateLabel()
  2748. {
  2749. UpdateLabel();
  2750. SendOnValueChanged();
  2751. }
  2752. private void SendOnValueChanged()
  2753. {
  2754. if (onValueChanged != null)
  2755. onValueChanged.Invoke(text);
  2756. }
  2757. /// <summary>
  2758. /// Submit the input field's text.
  2759. /// </summary>
  2760. protected void SendOnEndEdit()
  2761. {
  2762. if (onEndEdit != null)
  2763. onEndEdit.Invoke(m_Text);
  2764. }
  2765. protected void SendOnSubmit()
  2766. {
  2767. if (onSubmit != null)
  2768. onSubmit.Invoke(m_Text);
  2769. }
  2770. protected void SendOnFocus()
  2771. {
  2772. if (onSelect != null)
  2773. onSelect.Invoke(m_Text);
  2774. }
  2775. protected void SendOnFocusLost()
  2776. {
  2777. if (onDeselect != null)
  2778. onDeselect.Invoke(m_Text);
  2779. }
  2780. protected void SendOnTextSelection()
  2781. {
  2782. m_isSelected = true;
  2783. if (onTextSelection != null)
  2784. onTextSelection.Invoke(m_Text, stringPositionInternal, stringSelectPositionInternal);
  2785. }
  2786. protected void SendOnEndTextSelection()
  2787. {
  2788. if (!m_isSelected) return;
  2789. if (onEndTextSelection != null)
  2790. onEndTextSelection.Invoke(m_Text, stringPositionInternal, stringSelectPositionInternal);
  2791. m_isSelected = false;
  2792. }
  2793. protected void SendTouchScreenKeyboardStatusChanged()
  2794. {
  2795. if (m_SoftKeyboard != null && onTouchScreenKeyboardStatusChanged != null)
  2796. onTouchScreenKeyboardStatusChanged.Invoke(m_SoftKeyboard.status);
  2797. }
  2798. /// <summary>
  2799. /// Update the visual text Text.
  2800. /// </summary>
  2801. protected void UpdateLabel()
  2802. {
  2803. if (m_TextComponent != null && m_TextComponent.font != null && m_PreventCallback == false)
  2804. {
  2805. // Prevent callback from the text component as we assign new text. This is to prevent a recursive call.
  2806. m_PreventCallback = true;
  2807. string fullText;
  2808. if (compositionLength > 0 && m_ReadOnly == false)
  2809. {
  2810. //Input.imeCompositionMode = IMECompositionMode.On;
  2811. // Handle selections
  2812. Delete();
  2813. if (m_RichText)
  2814. fullText = text.Substring(0, m_StringPosition) + "<u>" + compositionString + "</u>" + text.Substring(m_StringPosition);
  2815. else
  2816. fullText = text.Substring(0, m_StringPosition) + compositionString + text.Substring(m_StringPosition);
  2817. m_IsCompositionActive = true;
  2818. //Debug.Log("[" + Time.frameCount + "] Handling IME Input");
  2819. }
  2820. else
  2821. {
  2822. fullText = text;
  2823. m_IsCompositionActive = false;
  2824. m_ShouldUpdateIMEWindowPosition = true;
  2825. }
  2826. //Debug.Log("Handling IME Input... [" + compositionString + "] of length [" + compositionLength + "] at StringPosition [" + m_StringPosition + "] IsActive [" + m_IsCompositionActive + "]");
  2827. string processed;
  2828. if (inputType == InputType.Password)
  2829. processed = new string(asteriskChar, fullText.Length);
  2830. else
  2831. processed = fullText;
  2832. bool isEmpty = string.IsNullOrEmpty(fullText);
  2833. if (m_Placeholder != null)
  2834. m_Placeholder.enabled = isEmpty;
  2835. if (!isEmpty && m_ReadOnly == false)
  2836. {
  2837. SetCaretVisible();
  2838. }
  2839. m_TextComponent.text = processed + "\u200B"; // Extra space is added for Caret tracking.
  2840. // Rebuild layout if using Layout components.
  2841. if (m_IsDrivenByLayoutComponents)
  2842. LayoutRebuilder.MarkLayoutForRebuild(m_RectTransform);
  2843. // Special handling to limit the number of lines of text in the Input Field.
  2844. if (m_LineLimit > 0)
  2845. {
  2846. m_TextComponent.ForceMeshUpdate();
  2847. TMP_TextInfo textInfo = m_TextComponent.textInfo;
  2848. // Check if text exceeds maximum number of lines.
  2849. if (textInfo != null && textInfo.lineCount > m_LineLimit)
  2850. {
  2851. int lastValidCharacterIndex = textInfo.lineInfo[m_LineLimit - 1].lastCharacterIndex;
  2852. int characterStringIndex = textInfo.characterInfo[lastValidCharacterIndex].index + textInfo.characterInfo[lastValidCharacterIndex].stringLength;
  2853. text = processed.Remove(characterStringIndex, processed.Length - characterStringIndex);
  2854. m_TextComponent.text = text + "\u200B";
  2855. }
  2856. }
  2857. if (m_IsTextComponentUpdateRequired || m_VerticalScrollbar && !(m_IsCaretPositionDirty && m_IsStringPositionDirty))
  2858. {
  2859. m_IsTextComponentUpdateRequired = false;
  2860. m_TextComponent.ForceMeshUpdate();
  2861. }
  2862. MarkGeometryAsDirty();
  2863. m_PreventCallback = false;
  2864. }
  2865. }
  2866. void UpdateScrollbar()
  2867. {
  2868. // Update Scrollbar
  2869. if (m_VerticalScrollbar)
  2870. {
  2871. Rect viewportRect = m_TextViewport.rect;
  2872. float size = viewportRect.height / m_TextComponent.preferredHeight;
  2873. m_VerticalScrollbar.size = size;
  2874. m_VerticalScrollbar.value = GetScrollPositionRelativeToViewport();
  2875. //Debug.Log(GetInstanceID() + "- UpdateScrollbar() - Updating Scrollbar... Value: " + m_VerticalScrollbar.value);
  2876. }
  2877. }
  2878. /// <summary>
  2879. /// Function to update the vertical position of the text container when OnValueChanged event is received from the Scrollbar.
  2880. /// </summary>
  2881. /// <param name="value"></param>
  2882. void OnScrollbarValueChange(float value)
  2883. {
  2884. //if (m_IsUpdatingScrollbarValues)
  2885. //{
  2886. // m_IsUpdatingScrollbarValues = false;
  2887. // return;
  2888. //}
  2889. if (value < 0 || value > 1) return;
  2890. AdjustTextPositionRelativeToViewport(value);
  2891. m_ScrollPosition = value;
  2892. //Debug.Log(GetInstanceID() + "- OnScrollbarValueChange() - Scrollbar value is: " + value + " Transform POS: " + m_TextComponent.rectTransform.anchoredPosition);
  2893. }
  2894. void UpdateMaskRegions()
  2895. {
  2896. // TODO: Figure out a better way to handle adding an offset to the masking region
  2897. // This region is defined by the RectTransform of the GameObject that contains the RectMask2D component.
  2898. /*
  2899. // Update Masking Region
  2900. if (m_TextViewportRectMask != null)
  2901. {
  2902. Rect viewportRect = m_TextViewportRectMask.canvasRect;
  2903. if (viewportRect != m_CachedViewportRect)
  2904. {
  2905. m_CachedViewportRect = viewportRect;
  2906. viewportRect.min -= m_TextViewport.offsetMin * 0.5f;
  2907. viewportRect.max -= m_TextViewport.offsetMax * 0.5f;
  2908. if (m_CachedInputRenderer != null)
  2909. m_CachedInputRenderer.EnableRectClipping(viewportRect);
  2910. if (m_TextComponent.canvasRenderer != null)
  2911. m_TextComponent.canvasRenderer.EnableRectClipping(viewportRect);
  2912. if (m_Placeholder != null && m_Placeholder.enabled)
  2913. m_Placeholder.canvasRenderer.EnableRectClipping(viewportRect);
  2914. }
  2915. }
  2916. */
  2917. }
  2918. /// <summary>
  2919. /// Adjusts the relative position of the body of the text relative to the viewport.
  2920. /// </summary>
  2921. /// <param name="relativePosition"></param>
  2922. void AdjustTextPositionRelativeToViewport (float relativePosition)
  2923. {
  2924. if (m_TextViewport == null)
  2925. return;
  2926. TMP_TextInfo textInfo = m_TextComponent.textInfo;
  2927. // Check to make sure we have valid data and lines to query.
  2928. if (textInfo == null || textInfo.lineInfo == null || textInfo.lineCount == 0 || textInfo.lineCount > textInfo.lineInfo.Length) return;
  2929. float verticalAlignmentOffset = 0;
  2930. float textHeight = m_TextComponent.preferredHeight;
  2931. switch (m_TextComponent.verticalAlignment)
  2932. {
  2933. case VerticalAlignmentOptions.Top:
  2934. verticalAlignmentOffset = 0;
  2935. break;
  2936. case VerticalAlignmentOptions.Middle:
  2937. verticalAlignmentOffset = 0.5f;
  2938. break;
  2939. case VerticalAlignmentOptions.Bottom:
  2940. verticalAlignmentOffset = 1.0f;
  2941. break;
  2942. case VerticalAlignmentOptions.Baseline:
  2943. break;
  2944. case VerticalAlignmentOptions.Geometry:
  2945. verticalAlignmentOffset = 0.5f;
  2946. textHeight = m_TextComponent.bounds.size.y;
  2947. break;
  2948. case VerticalAlignmentOptions.Capline:
  2949. verticalAlignmentOffset = 0.5f;
  2950. break;
  2951. }
  2952. m_TextComponent.rectTransform.anchoredPosition = new Vector2(m_TextComponent.rectTransform.anchoredPosition.x, (textHeight - m_TextViewport.rect.height) * (relativePosition - verticalAlignmentOffset));
  2953. AssignPositioningIfNeeded();
  2954. //Debug.Log("Text height: " + m_TextComponent.preferredHeight + " Viewport height: " + m_TextViewport.rect.height + " Adjusted RectTransform anchordedPosition:" + m_TextComponent.rectTransform.anchoredPosition + " Text Bounds: " + m_TextComponent.bounds.ToString("f3"));
  2955. }
  2956. private int GetCaretPositionFromStringIndex(int stringIndex)
  2957. {
  2958. int count = m_TextComponent.textInfo.characterCount;
  2959. for (int i = 0; i < count; i++)
  2960. {
  2961. if (m_TextComponent.textInfo.characterInfo[i].index >= stringIndex)
  2962. return i;
  2963. }
  2964. return count;
  2965. }
  2966. /// <summary>
  2967. /// Returns / places the caret before the given character at the string index.
  2968. /// </summary>
  2969. /// <param name="stringIndex"></param>
  2970. /// <returns></returns>
  2971. private int GetMinCaretPositionFromStringIndex(int stringIndex)
  2972. {
  2973. int count = m_TextComponent.textInfo.characterCount;
  2974. for (int i = 0; i < count; i++)
  2975. {
  2976. if (stringIndex < m_TextComponent.textInfo.characterInfo[i].index + m_TextComponent.textInfo.characterInfo[i].stringLength)
  2977. return i;
  2978. }
  2979. return count;
  2980. }
  2981. /// <summary>
  2982. /// Returns / places the caret after the given character at the string index.
  2983. /// </summary>
  2984. /// <param name="stringIndex"></param>
  2985. /// <returns></returns>
  2986. private int GetMaxCaretPositionFromStringIndex(int stringIndex)
  2987. {
  2988. int count = m_TextComponent.textInfo.characterCount;
  2989. for (int i = 0; i < count; i++)
  2990. {
  2991. if (m_TextComponent.textInfo.characterInfo[i].index >= stringIndex)
  2992. return i;
  2993. }
  2994. return count;
  2995. }
  2996. private int GetStringIndexFromCaretPosition(int caretPosition)
  2997. {
  2998. // Clamp values between 0 and character count.
  2999. ClampCaretPos(ref caretPosition);
  3000. return m_TextComponent.textInfo.characterInfo[caretPosition].index;
  3001. }
  3002. void UpdateStringIndexFromCaretPosition()
  3003. {
  3004. stringPositionInternal = GetStringIndexFromCaretPosition(m_CaretPosition);
  3005. stringSelectPositionInternal = GetStringIndexFromCaretPosition(m_CaretSelectPosition);
  3006. m_IsStringPositionDirty = false;
  3007. }
  3008. void UpdateCaretPositionFromStringIndex()
  3009. {
  3010. caretPositionInternal = GetCaretPositionFromStringIndex(stringPositionInternal);
  3011. caretSelectPositionInternal = GetCaretPositionFromStringIndex(stringSelectPositionInternal);
  3012. m_IsCaretPositionDirty = false;
  3013. }
  3014. public void ForceLabelUpdate()
  3015. {
  3016. UpdateLabel();
  3017. }
  3018. private void MarkGeometryAsDirty()
  3019. {
  3020. #if UNITY_EDITOR
  3021. if (!Application.isPlaying || UnityEditor.PrefabUtility.IsPartOfPrefabAsset(this))
  3022. return;
  3023. #endif
  3024. CanvasUpdateRegistry.RegisterCanvasElementForGraphicRebuild(this);
  3025. }
  3026. public virtual void Rebuild(CanvasUpdate update)
  3027. {
  3028. switch (update)
  3029. {
  3030. case CanvasUpdate.LatePreRender:
  3031. UpdateGeometry();
  3032. break;
  3033. }
  3034. }
  3035. public virtual void LayoutComplete()
  3036. { }
  3037. public virtual void GraphicUpdateComplete()
  3038. { }
  3039. private void UpdateGeometry()
  3040. {
  3041. #if UNITY_EDITOR
  3042. if (!Application.isPlaying)
  3043. return;
  3044. #endif
  3045. // No need to draw a cursor on mobile as its handled by the devices keyboard with the exception of UWP.
  3046. if (InPlaceEditing() == false && isUWP() == false)
  3047. return;
  3048. if (m_CachedInputRenderer == null)
  3049. return;
  3050. OnFillVBO(mesh);
  3051. m_CachedInputRenderer.SetMesh(mesh);
  3052. }
  3053. /// <summary>
  3054. /// Method to keep the Caret RectTransform properties in sync with the text object's RectTransform
  3055. /// </summary>
  3056. private void AssignPositioningIfNeeded()
  3057. {
  3058. if (m_TextComponent != null && caretRectTrans != null &&
  3059. (caretRectTrans.localPosition != m_TextComponent.rectTransform.localPosition ||
  3060. caretRectTrans.localRotation != m_TextComponent.rectTransform.localRotation ||
  3061. caretRectTrans.localScale != m_TextComponent.rectTransform.localScale ||
  3062. caretRectTrans.anchorMin != m_TextComponent.rectTransform.anchorMin ||
  3063. caretRectTrans.anchorMax != m_TextComponent.rectTransform.anchorMax ||
  3064. caretRectTrans.anchoredPosition != m_TextComponent.rectTransform.anchoredPosition ||
  3065. caretRectTrans.sizeDelta != m_TextComponent.rectTransform.sizeDelta ||
  3066. caretRectTrans.pivot != m_TextComponent.rectTransform.pivot))
  3067. {
  3068. caretRectTrans.localPosition = m_TextComponent.rectTransform.localPosition;
  3069. caretRectTrans.localRotation = m_TextComponent.rectTransform.localRotation;
  3070. caretRectTrans.localScale = m_TextComponent.rectTransform.localScale;
  3071. caretRectTrans.anchorMin = m_TextComponent.rectTransform.anchorMin;
  3072. caretRectTrans.anchorMax = m_TextComponent.rectTransform.anchorMax;
  3073. caretRectTrans.anchoredPosition = m_TextComponent.rectTransform.anchoredPosition;
  3074. caretRectTrans.sizeDelta = m_TextComponent.rectTransform.sizeDelta;
  3075. caretRectTrans.pivot = m_TextComponent.rectTransform.pivot;
  3076. }
  3077. }
  3078. private void OnFillVBO(Mesh vbo)
  3079. {
  3080. using (var helper = new VertexHelper())
  3081. {
  3082. if (!isFocused && !m_SelectionStillActive)
  3083. {
  3084. helper.FillMesh(vbo);
  3085. return;
  3086. }
  3087. if (m_IsStringPositionDirty)
  3088. UpdateStringIndexFromCaretPosition();
  3089. if (m_IsCaretPositionDirty)
  3090. UpdateCaretPositionFromStringIndex();
  3091. if (!hasSelection)
  3092. {
  3093. GenerateCaret(helper, Vector2.zero);
  3094. SendOnEndTextSelection();
  3095. }
  3096. else
  3097. {
  3098. GenerateHighlight(helper, Vector2.zero);
  3099. SendOnTextSelection();
  3100. }
  3101. helper.FillMesh(vbo);
  3102. }
  3103. }
  3104. private void GenerateCaret(VertexHelper vbo, Vector2 roundingOffset)
  3105. {
  3106. if (m_CaretVisible == false || m_TextComponent.canvas == null || m_ReadOnly)
  3107. return;
  3108. if (m_CursorVerts == null)
  3109. {
  3110. CreateCursorVerts();
  3111. }
  3112. // TODO: Optimize to only update the caret position when needed.
  3113. Vector2 startPosition = Vector2.zero;
  3114. float height = 0;
  3115. TMP_CharacterInfo currentCharacter;
  3116. // Make sure caret position does not exceed characterInfo array size or less than zero.
  3117. if (caretPositionInternal >= m_TextComponent.textInfo.characterInfo.Length || caretPositionInternal < 0)
  3118. return;
  3119. int currentLine = m_TextComponent.textInfo.characterInfo[caretPositionInternal].lineNumber;
  3120. // Caret is positioned at the origin for the first character of each lines and at the advance for subsequent characters.
  3121. if (caretPositionInternal == m_TextComponent.textInfo.lineInfo[currentLine].firstCharacterIndex)
  3122. {
  3123. currentCharacter = m_TextComponent.textInfo.characterInfo[caretPositionInternal];
  3124. height = currentCharacter.ascender - currentCharacter.descender;
  3125. if (m_TextComponent.verticalAlignment == VerticalAlignmentOptions.Geometry)
  3126. startPosition = new Vector2(currentCharacter.origin, 0 - height / 2);
  3127. else
  3128. startPosition = new Vector2(currentCharacter.origin, currentCharacter.descender);
  3129. }
  3130. else
  3131. {
  3132. currentCharacter = m_TextComponent.textInfo.characterInfo[caretPositionInternal - 1];
  3133. height = currentCharacter.ascender - currentCharacter.descender;
  3134. if (m_TextComponent.verticalAlignment == VerticalAlignmentOptions.Geometry)
  3135. startPosition = new Vector2(currentCharacter.xAdvance, 0 - height / 2);
  3136. else
  3137. startPosition = new Vector2(currentCharacter.xAdvance, currentCharacter.descender);
  3138. }
  3139. if (m_SoftKeyboard != null && compositionLength == 0)
  3140. {
  3141. int selectionStart = m_StringPosition;
  3142. int softKeyboardStringLength = m_SoftKeyboard.text == null ? 0 : m_SoftKeyboard.text.Length;
  3143. if (selectionStart < 0)
  3144. selectionStart = 0;
  3145. if (selectionStart > softKeyboardStringLength)
  3146. selectionStart = softKeyboardStringLength;
  3147. m_SoftKeyboard.selection = new RangeInt(selectionStart, 0);
  3148. }
  3149. // Adjust the position of the RectTransform based on the caret position in the viewport (only if we have focus).
  3150. if (isFocused && startPosition != m_LastPosition || m_forceRectTransformAdjustment || m_HasTextBeenRemoved)
  3151. AdjustRectTransformRelativeToViewport(startPosition, height, currentCharacter.isVisible);
  3152. m_LastPosition = startPosition;
  3153. // Clamp Caret height
  3154. float top = startPosition.y + height;
  3155. float bottom = top - height;
  3156. // Compute the width of the caret which is based on the line height of the primary font asset.
  3157. //float width = m_CaretWidth;
  3158. TMP_FontAsset fontAsset = m_TextComponent.font;
  3159. float baseScale = (m_TextComponent.fontSize / fontAsset.m_FaceInfo.pointSize * fontAsset.m_FaceInfo.scale);
  3160. float width = m_CaretWidth * fontAsset.faceInfo.lineHeight * baseScale * 0.05f;
  3161. m_CursorVerts[0].position = new Vector3(startPosition.x, bottom, 0.0f);
  3162. m_CursorVerts[1].position = new Vector3(startPosition.x, top, 0.0f);
  3163. m_CursorVerts[2].position = new Vector3(startPosition.x + width, top, 0.0f);
  3164. m_CursorVerts[3].position = new Vector3(startPosition.x + width, bottom, 0.0f);
  3165. // Set Vertex Color for the caret color.
  3166. m_CursorVerts[0].color = caretColor;
  3167. m_CursorVerts[1].color = caretColor;
  3168. m_CursorVerts[2].color = caretColor;
  3169. m_CursorVerts[3].color = caretColor;
  3170. vbo.AddUIVertexQuad(m_CursorVerts);
  3171. // Update position of IME window when necessary.
  3172. if (m_ShouldUpdateIMEWindowPosition || currentLine != m_PreviousIMEInsertionLine)
  3173. {
  3174. m_ShouldUpdateIMEWindowPosition = false;
  3175. m_PreviousIMEInsertionLine = currentLine;
  3176. // Calculate position of IME Window in screen space.
  3177. Camera cameraRef;
  3178. if (m_TextComponent.canvas.renderMode == RenderMode.ScreenSpaceOverlay)
  3179. cameraRef = null;
  3180. else
  3181. {
  3182. cameraRef = m_TextComponent.canvas.worldCamera;
  3183. if (cameraRef == null)
  3184. cameraRef = Camera.current;
  3185. }
  3186. Vector3 cursorPosition = m_CachedInputRenderer.gameObject.transform.TransformPoint(m_CursorVerts[0].position);
  3187. Vector2 screenPosition = RectTransformUtility.WorldToScreenPoint(cameraRef, cursorPosition);
  3188. screenPosition.y = Screen.height - screenPosition.y;
  3189. if (inputSystem != null)
  3190. inputSystem.compositionCursorPos = screenPosition;
  3191. //Debug.Log("[" + Time.frameCount + "] Updating IME Window position Cursor Pos: (" + cursorPosition + ") Screen Pos: (" + screenPosition + ") with Composition Length: " + compositionLength);
  3192. }
  3193. //#if TMP_DEBUG_MODE
  3194. //Debug.Log("Caret position updated at frame: " + Time.frameCount);
  3195. //#endif
  3196. }
  3197. private void CreateCursorVerts()
  3198. {
  3199. m_CursorVerts = new UIVertex[4];
  3200. for (int i = 0; i < m_CursorVerts.Length; i++)
  3201. {
  3202. m_CursorVerts[i] = UIVertex.simpleVert;
  3203. m_CursorVerts[i].uv0 = Vector2.zero;
  3204. }
  3205. }
  3206. private void GenerateHighlight(VertexHelper vbo, Vector2 roundingOffset)
  3207. {
  3208. // Update Masking Region
  3209. UpdateMaskRegions();
  3210. // Make sure caret position does not exceed characterInfo array size.
  3211. //if (caretSelectPositionInternal >= m_TextComponent.textInfo.characterInfo.Length)
  3212. // return;
  3213. TMP_TextInfo textInfo = m_TextComponent.textInfo;
  3214. // Return if character count is zero as there is nothing to highlight.
  3215. if (textInfo.characterCount == 0)
  3216. return;
  3217. m_CaretPosition = GetCaretPositionFromStringIndex(stringPositionInternal);
  3218. m_CaretSelectPosition = GetCaretPositionFromStringIndex(stringSelectPositionInternal);
  3219. if (m_SoftKeyboard != null && compositionLength == 0)
  3220. {
  3221. int stringPosition = m_CaretPosition < m_CaretSelectPosition ? textInfo.characterInfo[m_CaretPosition].index : textInfo.characterInfo[m_CaretSelectPosition].index;
  3222. int length = m_CaretPosition < m_CaretSelectPosition ? stringSelectPositionInternal - stringPosition : stringPositionInternal - stringPosition;
  3223. m_SoftKeyboard.selection = new RangeInt(stringPosition, length);
  3224. }
  3225. // Adjust text RectTranform position to make sure it is visible in viewport.
  3226. Vector2 caretPosition;
  3227. float height = 0;
  3228. if (m_CaretSelectPosition < textInfo.characterCount)
  3229. {
  3230. caretPosition = new Vector2(textInfo.characterInfo[m_CaretSelectPosition].origin, textInfo.characterInfo[m_CaretSelectPosition].descender);
  3231. height = textInfo.characterInfo[m_CaretSelectPosition].ascender - textInfo.characterInfo[m_CaretSelectPosition].descender;
  3232. }
  3233. else
  3234. {
  3235. caretPosition = new Vector2(textInfo.characterInfo[m_CaretSelectPosition - 1].xAdvance, textInfo.characterInfo[m_CaretSelectPosition - 1].descender);
  3236. height = textInfo.characterInfo[m_CaretSelectPosition - 1].ascender - textInfo.characterInfo[m_CaretSelectPosition - 1].descender;
  3237. }
  3238. // TODO: Don't adjust the position of the RectTransform if Reset On Deactivation is disabled
  3239. // and we just selected the Input Field again.
  3240. AdjustRectTransformRelativeToViewport(caretPosition, height, true);
  3241. int startChar = Mathf.Max(0, m_CaretPosition);
  3242. int endChar = Mathf.Max(0, m_CaretSelectPosition);
  3243. // Ensure pos is always less then selPos to make the code simpler
  3244. if (startChar > endChar)
  3245. {
  3246. int temp = startChar;
  3247. startChar = endChar;
  3248. endChar = temp;
  3249. }
  3250. endChar -= 1;
  3251. //Debug.Log("Updating Highlight... Caret Position: " + startChar + " Caret Select POS: " + endChar);
  3252. int currentLineIndex = textInfo.characterInfo[startChar].lineNumber;
  3253. int nextLineStartIdx = textInfo.lineInfo[currentLineIndex].lastCharacterIndex;
  3254. UIVertex vert = UIVertex.simpleVert;
  3255. vert.uv0 = Vector2.zero;
  3256. vert.color = selectionColor;
  3257. int currentChar = startChar;
  3258. while (currentChar <= endChar && currentChar < textInfo.characterCount)
  3259. {
  3260. if (currentChar == nextLineStartIdx || currentChar == endChar)
  3261. {
  3262. TMP_CharacterInfo startCharInfo = textInfo.characterInfo[startChar];
  3263. TMP_CharacterInfo endCharInfo = textInfo.characterInfo[currentChar];
  3264. // Extra check to handle Carriage Return
  3265. if (currentChar > 0 && endCharInfo.character == '\n' && textInfo.characterInfo[currentChar - 1].character == '\r')
  3266. endCharInfo = textInfo.characterInfo[currentChar - 1];
  3267. Vector2 startPosition = new Vector2(startCharInfo.origin, textInfo.lineInfo[currentLineIndex].ascender);
  3268. Vector2 endPosition = new Vector2(endCharInfo.xAdvance, textInfo.lineInfo[currentLineIndex].descender);
  3269. var startIndex = vbo.currentVertCount;
  3270. vert.position = new Vector3(startPosition.x, endPosition.y, 0.0f);
  3271. vbo.AddVert(vert);
  3272. vert.position = new Vector3(endPosition.x, endPosition.y, 0.0f);
  3273. vbo.AddVert(vert);
  3274. vert.position = new Vector3(endPosition.x, startPosition.y, 0.0f);
  3275. vbo.AddVert(vert);
  3276. vert.position = new Vector3(startPosition.x, startPosition.y, 0.0f);
  3277. vbo.AddVert(vert);
  3278. vbo.AddTriangle(startIndex, startIndex + 1, startIndex + 2);
  3279. vbo.AddTriangle(startIndex + 2, startIndex + 3, startIndex + 0);
  3280. startChar = currentChar + 1;
  3281. currentLineIndex++;
  3282. if (currentLineIndex < textInfo.lineCount)
  3283. nextLineStartIdx = textInfo.lineInfo[currentLineIndex].lastCharacterIndex;
  3284. }
  3285. currentChar++;
  3286. }
  3287. //#if TMP_DEBUG_MODE
  3288. // Debug.Log("Text selection updated at frame: " + Time.frameCount);
  3289. //#endif
  3290. }
  3291. /// <summary>
  3292. ///
  3293. /// </summary>
  3294. /// <param name="startPosition"></param>
  3295. /// <param name="height"></param>
  3296. /// <param name="isCharVisible"></param>
  3297. private void AdjustRectTransformRelativeToViewport(Vector2 startPosition, float height, bool isCharVisible)
  3298. {
  3299. //Debug.Log("Adjusting transform position relative to viewport.");
  3300. if (m_TextViewport == null)
  3301. return;
  3302. Vector3 localPosition = transform.localPosition;
  3303. Vector3 textComponentLocalPosition = m_TextComponent.rectTransform.localPosition;
  3304. Vector3 textViewportLocalPosition = m_TextViewport.localPosition;
  3305. Rect textViewportRect = m_TextViewport.rect;
  3306. Vector2 caretPosition = new Vector2(startPosition.x + textComponentLocalPosition.x + textViewportLocalPosition.x + localPosition.x, startPosition.y + textComponentLocalPosition.y + textViewportLocalPosition.y + localPosition.y);
  3307. Rect viewportWSRect = new Rect(localPosition.x + textViewportLocalPosition.x + textViewportRect.x, localPosition.y + textViewportLocalPosition.y + textViewportRect.y, textViewportRect.width, textViewportRect.height);
  3308. // Adjust the position of the RectTransform based on the caret position in the viewport.
  3309. float rightOffset = viewportWSRect.xMax - (caretPosition.x + m_TextComponent.margin.z + m_CaretWidth);
  3310. if (rightOffset < 0f)
  3311. {
  3312. if (!multiLine || (multiLine && isCharVisible))
  3313. {
  3314. //Debug.Log("Shifting text to the LEFT by " + rightOffset.ToString("f3"));
  3315. m_TextComponent.rectTransform.anchoredPosition += new Vector2(rightOffset, 0);
  3316. AssignPositioningIfNeeded();
  3317. }
  3318. }
  3319. float leftOffset = (caretPosition.x - m_TextComponent.margin.x) - viewportWSRect.xMin;
  3320. if (leftOffset < 0f)
  3321. {
  3322. //Debug.Log("Shifting text to the RIGHT by " + leftOffset.ToString("f3"));
  3323. m_TextComponent.rectTransform.anchoredPosition += new Vector2(-leftOffset, 0);
  3324. AssignPositioningIfNeeded();
  3325. }
  3326. // Adjust text area up or down if not in single line mode.
  3327. if (m_LineType != LineType.SingleLine)
  3328. {
  3329. float topOffset = viewportWSRect.yMax - (caretPosition.y + height);
  3330. if (topOffset < -0.0001f)
  3331. {
  3332. //Debug.Log("Shifting text to Up " + topOffset.ToString("f3"));
  3333. m_TextComponent.rectTransform.anchoredPosition += new Vector2(0, topOffset);
  3334. AssignPositioningIfNeeded();
  3335. }
  3336. float bottomOffset = caretPosition.y - viewportWSRect.yMin;
  3337. if (bottomOffset < 0f)
  3338. {
  3339. //Debug.Log("Shifting text to Down " + bottomOffset.ToString("f3"));
  3340. m_TextComponent.rectTransform.anchoredPosition -= new Vector2(0, bottomOffset);
  3341. AssignPositioningIfNeeded();
  3342. }
  3343. }
  3344. // Special handling of backspace/text being removed
  3345. if (m_HasTextBeenRemoved)
  3346. {
  3347. float anchoredPositionX = m_TextComponent.rectTransform.anchoredPosition.x;
  3348. float firstCharPosition = localPosition.x + textViewportLocalPosition.x + textComponentLocalPosition.x + m_TextComponent.textInfo.characterInfo[0].origin - m_TextComponent.margin.x;
  3349. int lastCharacterIndex = ClampArrayIndex(m_TextComponent.textInfo.characterCount - 1);
  3350. float lastCharPosition = localPosition.x + textViewportLocalPosition.x + textComponentLocalPosition.x + m_TextComponent.textInfo.characterInfo[lastCharacterIndex].origin + m_TextComponent.margin.z + m_CaretWidth;
  3351. if (anchoredPositionX > 0.0001f && firstCharPosition > viewportWSRect.xMin)
  3352. {
  3353. float offset = viewportWSRect.xMin - firstCharPosition;
  3354. if (anchoredPositionX < -offset)
  3355. offset = -anchoredPositionX;
  3356. m_TextComponent.rectTransform.anchoredPosition += new Vector2(offset, 0);
  3357. AssignPositioningIfNeeded();
  3358. }
  3359. else if (anchoredPositionX < -0.0001f && lastCharPosition < viewportWSRect.xMax)
  3360. {
  3361. float offset = viewportWSRect.xMax - lastCharPosition;
  3362. if (-anchoredPositionX < offset)
  3363. offset = -anchoredPositionX;
  3364. m_TextComponent.rectTransform.anchoredPosition += new Vector2(offset, 0);
  3365. AssignPositioningIfNeeded();
  3366. }
  3367. m_HasTextBeenRemoved = false;
  3368. }
  3369. m_forceRectTransformAdjustment = false;
  3370. }
  3371. /// <summary>
  3372. /// Validate the specified input.
  3373. /// </summary>
  3374. protected char Validate(string text, int pos, char ch)
  3375. {
  3376. // Validation is disabled
  3377. if (characterValidation == CharacterValidation.None || !enabled)
  3378. return ch;
  3379. if (characterValidation == CharacterValidation.Integer || characterValidation == CharacterValidation.Decimal)
  3380. {
  3381. // Integer and decimal
  3382. bool cursorBeforeDash = (pos == 0 && text.Length > 0 && text[0] == '-');
  3383. bool selectionAtStart = stringPositionInternal == 0 || stringSelectPositionInternal == 0;
  3384. if (!cursorBeforeDash)
  3385. {
  3386. if (ch >= '0' && ch <= '9') return ch;
  3387. if (ch == '-' && (pos == 0 || selectionAtStart)) return ch;
  3388. var separator = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
  3389. if (ch == Convert.ToChar(separator) && characterValidation == CharacterValidation.Decimal && !text.Contains(separator)) return ch;
  3390. }
  3391. }
  3392. else if (characterValidation == CharacterValidation.Digit)
  3393. {
  3394. if (ch >= '0' && ch <= '9') return ch;
  3395. }
  3396. else if (characterValidation == CharacterValidation.Alphanumeric)
  3397. {
  3398. // All alphanumeric characters
  3399. if (ch >= 'A' && ch <= 'Z') return ch;
  3400. if (ch >= 'a' && ch <= 'z') return ch;
  3401. if (ch >= '0' && ch <= '9') return ch;
  3402. }
  3403. else if (characterValidation == CharacterValidation.Name)
  3404. {
  3405. char prevChar = (text.Length > 0) ? text[Mathf.Clamp(pos - 1, 0, text.Length - 1)] : ' ';
  3406. char lastChar = (text.Length > 0) ? text[Mathf.Clamp(pos, 0, text.Length - 1)] : ' ';
  3407. char nextChar = (text.Length > 0) ? text[Mathf.Clamp(pos + 1, 0, text.Length - 1)] : '\n';
  3408. if (char.IsLetter(ch))
  3409. {
  3410. // First letter is always capitalized
  3411. if (char.IsLower(ch) && pos == 0)
  3412. return char.ToUpper(ch);
  3413. // Letter following a space or hyphen is always capitalized
  3414. if (char.IsLower(ch) && (prevChar == ' ' || prevChar == '-'))
  3415. return char.ToUpper(ch);
  3416. // Uppercase letters are only allowed after spaces, apostrophes, hyphens or lowercase letter
  3417. if (char.IsUpper(ch) && pos > 0 && prevChar != ' ' && prevChar != '\'' && prevChar != '-' && !char.IsLower(prevChar))
  3418. return char.ToLower(ch);
  3419. // Do not allow uppercase characters to be inserted before another uppercase character
  3420. if (char.IsUpper(ch) && char.IsUpper(lastChar))
  3421. return (char)0;
  3422. // If character was already in correct case, return it as-is.
  3423. // Also, letters that are neither upper nor lower case are always allowed.
  3424. return ch;
  3425. }
  3426. else if (ch == '\'')
  3427. {
  3428. // Don't allow more than one apostrophe
  3429. if (lastChar != ' ' && lastChar != '\'' && nextChar != '\'' && !text.Contains("'"))
  3430. return ch;
  3431. }
  3432. // Allow inserting a hyphen after a character
  3433. if (char.IsLetter(prevChar) && ch == '-' && lastChar != '-')
  3434. {
  3435. return ch;
  3436. }
  3437. if ((ch == ' ' || ch == '-') && pos != 0)
  3438. {
  3439. // Don't allow more than one space in a row
  3440. if (prevChar != ' ' && prevChar != '\'' && prevChar != '-' &&
  3441. lastChar != ' ' && lastChar != '\'' && lastChar != '-' &&
  3442. nextChar != ' ' && nextChar != '\'' && nextChar != '-')
  3443. return ch;
  3444. }
  3445. }
  3446. else if (characterValidation == CharacterValidation.EmailAddress)
  3447. {
  3448. // From StackOverflow about allowed characters in email addresses:
  3449. // Uppercase and lowercase English letters (a-z, A-Z)
  3450. // Digits 0 to 9
  3451. // Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  3452. // Character . (dot, period, full stop) provided that it is not the first or last character,
  3453. // and provided also that it does not appear two or more times consecutively.
  3454. if (ch >= 'A' && ch <= 'Z') return ch;
  3455. if (ch >= 'a' && ch <= 'z') return ch;
  3456. if (ch >= '0' && ch <= '9') return ch;
  3457. if (ch == '@' && text.IndexOf('@') == -1) return ch;
  3458. if (kEmailSpecialCharacters.IndexOf(ch) != -1) return ch;
  3459. if (ch == '.')
  3460. {
  3461. char lastChar = (text.Length > 0) ? text[Mathf.Clamp(pos, 0, text.Length - 1)] : ' ';
  3462. char nextChar = (text.Length > 0) ? text[Mathf.Clamp(pos + 1, 0, text.Length - 1)] : '\n';
  3463. if (lastChar != '.' && nextChar != '.')
  3464. return ch;
  3465. }
  3466. }
  3467. else if (characterValidation == CharacterValidation.Regex)
  3468. {
  3469. // Regex expression
  3470. if (Regex.IsMatch(ch.ToString(), m_RegexValue))
  3471. {
  3472. return ch;
  3473. }
  3474. }
  3475. else if (characterValidation == CharacterValidation.CustomValidator)
  3476. {
  3477. if (m_InputValidator != null)
  3478. {
  3479. char c = m_InputValidator.Validate(ref text, ref pos, ch);
  3480. m_Text = text;
  3481. stringSelectPositionInternal = stringPositionInternal = pos;
  3482. return c;
  3483. }
  3484. }
  3485. return (char)0;
  3486. }
  3487. public void ActivateInputField()
  3488. {
  3489. if (m_TextComponent == null || m_TextComponent.font == null || !IsActive() || !IsInteractable())
  3490. return;
  3491. if (isFocused)
  3492. {
  3493. if (m_SoftKeyboard != null && !m_SoftKeyboard.active)
  3494. {
  3495. m_SoftKeyboard.active = true;
  3496. m_SoftKeyboard.text = m_Text;
  3497. }
  3498. }
  3499. m_ShouldActivateNextUpdate = true;
  3500. }
  3501. private void ActivateInputFieldInternal()
  3502. {
  3503. if (EventSystem.current == null)
  3504. return;
  3505. if (EventSystem.current.currentSelectedGameObject != gameObject)
  3506. EventSystem.current.SetSelectedGameObject(gameObject);
  3507. // Cache the value of isInPlaceEditingAllowed, because on UWP this involves calling into native code
  3508. // The value only needs to be updated once when the TouchKeyboard is opened.
  3509. m_TouchKeyboardAllowsInPlaceEditing = !s_IsQuestDevice && TouchScreenKeyboard.isInPlaceEditingAllowed;
  3510. if (TouchScreenKeyboardShouldBeUsed() && shouldHideSoftKeyboard == false)
  3511. {
  3512. if (inputSystem != null && inputSystem.touchSupported)
  3513. {
  3514. TouchScreenKeyboard.hideInput = shouldHideMobileInput;
  3515. }
  3516. if (shouldHideSoftKeyboard == false && m_ReadOnly == false)
  3517. {
  3518. m_SoftKeyboard = (inputType == InputType.Password) ?
  3519. TouchScreenKeyboard.Open(m_Text, keyboardType, false, multiLine, true, isAlert, "", characterLimit) :
  3520. TouchScreenKeyboard.Open(m_Text, keyboardType, inputType == InputType.AutoCorrect, multiLine, false, isAlert, "", characterLimit);
  3521. OnFocus();
  3522. // Opening the soft keyboard sets its selection to the end of the text.
  3523. // As such, we set the selection to match the Input Field's internal selection.
  3524. if (m_SoftKeyboard != null && m_SoftKeyboard.canSetSelection)
  3525. {
  3526. int length = stringPositionInternal < stringSelectPositionInternal ? stringSelectPositionInternal - stringPositionInternal : stringPositionInternal - stringSelectPositionInternal;
  3527. m_SoftKeyboard.selection = new RangeInt(stringPositionInternal < stringSelectPositionInternal ? stringPositionInternal : stringSelectPositionInternal, length);
  3528. }
  3529. //}
  3530. }
  3531. }
  3532. else
  3533. {
  3534. if (!TouchScreenKeyboardShouldBeUsed() && m_ReadOnly == false && inputSystem != null)
  3535. inputSystem.imeCompositionMode = IMECompositionMode.On;
  3536. OnFocus();
  3537. }
  3538. m_AllowInput = true;
  3539. m_OriginalText = text;
  3540. m_WasCanceled = false;
  3541. SetCaretVisible();
  3542. UpdateLabel();
  3543. }
  3544. public override void OnSelect(BaseEventData eventData)
  3545. {
  3546. //Debug.Log("OnSelect()");
  3547. base.OnSelect(eventData);
  3548. SendOnFocus();
  3549. if (shouldActivateOnSelect)
  3550. ActivateInputField();
  3551. }
  3552. public virtual void OnPointerClick(PointerEventData eventData)
  3553. {
  3554. //Debug.Log("Pointer Click Event...");
  3555. if (eventData.button != PointerEventData.InputButton.Left)
  3556. return;
  3557. ActivateInputField();
  3558. }
  3559. public void OnControlClick()
  3560. {
  3561. //Debug.Log("Input Field control click...");
  3562. }
  3563. public void ReleaseSelection()
  3564. {
  3565. m_SelectionStillActive = false;
  3566. m_ReleaseSelection = false;
  3567. m_PreviouslySelectedObject = null;
  3568. MarkGeometryAsDirty();
  3569. SendOnEndEdit();
  3570. SendOnEndTextSelection();
  3571. }
  3572. public void DeactivateInputField(bool clearSelection = false)
  3573. {
  3574. //Debug.Log("Deactivate Input Field...");
  3575. // Not activated do nothing.
  3576. if (!m_AllowInput)
  3577. return;
  3578. m_HasDoneFocusTransition = false;
  3579. m_AllowInput = false;
  3580. if (m_Placeholder != null)
  3581. m_Placeholder.enabled = string.IsNullOrEmpty(m_Text);
  3582. if (m_TextComponent != null && IsInteractable())
  3583. {
  3584. if (m_WasCanceled && m_RestoreOriginalTextOnEscape && !m_IsKeyboardBeingClosedInHoloLens)
  3585. text = m_OriginalText;
  3586. if (m_SoftKeyboard != null)
  3587. {
  3588. m_SoftKeyboard.active = false;
  3589. m_SoftKeyboard = null;
  3590. }
  3591. m_SelectionStillActive = true;
  3592. if (m_ResetOnDeActivation || m_ReleaseSelection || clearSelection)
  3593. {
  3594. //m_StringPosition = m_StringSelectPosition = 0;
  3595. //m_CaretPosition = m_CaretSelectPosition = 0;
  3596. //m_TextComponent.rectTransform.localPosition = m_DefaultTransformPosition;
  3597. if (m_VerticalScrollbar == null)
  3598. ReleaseSelection();
  3599. }
  3600. if (inputSystem != null)
  3601. inputSystem.imeCompositionMode = IMECompositionMode.Auto;
  3602. m_IsKeyboardBeingClosedInHoloLens = false;
  3603. }
  3604. MarkGeometryAsDirty();
  3605. }
  3606. public override void OnDeselect(BaseEventData eventData)
  3607. {
  3608. DeactivateInputField();
  3609. base.OnDeselect(eventData);
  3610. SendOnFocusLost();
  3611. }
  3612. public virtual void OnSubmit(BaseEventData eventData)
  3613. {
  3614. //Debug.Log("OnSubmit()");
  3615. if (!IsActive() || !IsInteractable())
  3616. return;
  3617. if (!isFocused)
  3618. m_ShouldActivateNextUpdate = true;
  3619. SendOnSubmit();
  3620. DeactivateInputField();
  3621. eventData?.Use();
  3622. }
  3623. public virtual void OnCancel(BaseEventData eventData)
  3624. {
  3625. if (!IsActive() || !IsInteractable())
  3626. return;
  3627. if (!isFocused)
  3628. m_ShouldActivateNextUpdate = true;
  3629. m_WasCanceled = true;
  3630. DeactivateInputField();
  3631. eventData.Use();
  3632. }
  3633. public override void OnMove(AxisEventData eventData)
  3634. {
  3635. // Prevent UI navigation while text is being edited.
  3636. if (!m_AllowInput)
  3637. base.OnMove(eventData);
  3638. }
  3639. //public virtual void OnLostFocus(BaseEventData eventData)
  3640. //{
  3641. // if (!IsActive() || !IsInteractable())
  3642. // return;
  3643. //}
  3644. private void EnforceContentType()
  3645. {
  3646. switch (contentType)
  3647. {
  3648. case ContentType.Standard:
  3649. {
  3650. // Don't enforce line type for this content type.
  3651. m_InputType = InputType.Standard;
  3652. m_KeyboardType = TouchScreenKeyboardType.Default;
  3653. m_CharacterValidation = CharacterValidation.None;
  3654. break;
  3655. }
  3656. case ContentType.Autocorrected:
  3657. {
  3658. // Don't enforce line type for this content type.
  3659. m_InputType = InputType.AutoCorrect;
  3660. m_KeyboardType = TouchScreenKeyboardType.Default;
  3661. m_CharacterValidation = CharacterValidation.None;
  3662. break;
  3663. }
  3664. case ContentType.IntegerNumber:
  3665. {
  3666. m_LineType = LineType.SingleLine;
  3667. m_InputType = InputType.Standard;
  3668. m_KeyboardType = TouchScreenKeyboardType.NumberPad;
  3669. m_CharacterValidation = CharacterValidation.Integer;
  3670. break;
  3671. }
  3672. case ContentType.DecimalNumber:
  3673. {
  3674. m_LineType = LineType.SingleLine;
  3675. m_InputType = InputType.Standard;
  3676. m_KeyboardType = TouchScreenKeyboardType.NumbersAndPunctuation;
  3677. m_CharacterValidation = CharacterValidation.Decimal;
  3678. break;
  3679. }
  3680. case ContentType.Alphanumeric:
  3681. {
  3682. m_LineType = LineType.SingleLine;
  3683. m_InputType = InputType.Standard;
  3684. m_KeyboardType = TouchScreenKeyboardType.ASCIICapable;
  3685. m_CharacterValidation = CharacterValidation.Alphanumeric;
  3686. break;
  3687. }
  3688. case ContentType.Name:
  3689. {
  3690. m_LineType = LineType.SingleLine;
  3691. m_InputType = InputType.Standard;
  3692. m_KeyboardType = TouchScreenKeyboardType.Default;
  3693. m_CharacterValidation = CharacterValidation.Name;
  3694. break;
  3695. }
  3696. case ContentType.EmailAddress:
  3697. {
  3698. m_LineType = LineType.SingleLine;
  3699. m_InputType = InputType.Standard;
  3700. m_KeyboardType = TouchScreenKeyboardType.EmailAddress;
  3701. m_CharacterValidation = CharacterValidation.EmailAddress;
  3702. break;
  3703. }
  3704. case ContentType.Password:
  3705. {
  3706. m_LineType = LineType.SingleLine;
  3707. m_InputType = InputType.Password;
  3708. m_KeyboardType = TouchScreenKeyboardType.Default;
  3709. m_CharacterValidation = CharacterValidation.None;
  3710. break;
  3711. }
  3712. case ContentType.Pin:
  3713. {
  3714. m_LineType = LineType.SingleLine;
  3715. m_InputType = InputType.Password;
  3716. m_KeyboardType = TouchScreenKeyboardType.NumberPad;
  3717. m_CharacterValidation = CharacterValidation.Digit;
  3718. break;
  3719. }
  3720. default:
  3721. {
  3722. // Includes Custom type. Nothing should be enforced.
  3723. break;
  3724. }
  3725. }
  3726. SetTextComponentWrapMode();
  3727. }
  3728. void SetTextComponentWrapMode()
  3729. {
  3730. if (m_TextComponent == null)
  3731. return;
  3732. if (multiLine)
  3733. m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
  3734. else
  3735. m_TextComponent.textWrappingMode = TextWrappingModes.PreserveWhitespaceNoWrap;
  3736. }
  3737. // Control Rich Text option on the text component.
  3738. void SetTextComponentRichTextMode()
  3739. {
  3740. if (m_TextComponent == null)
  3741. return;
  3742. m_TextComponent.richText = m_RichText;
  3743. }
  3744. void SetToCustomIfContentTypeIsNot(params ContentType[] allowedContentTypes)
  3745. {
  3746. if (contentType == ContentType.Custom)
  3747. return;
  3748. for (int i = 0; i < allowedContentTypes.Length; i++)
  3749. if (contentType == allowedContentTypes[i])
  3750. return;
  3751. contentType = ContentType.Custom;
  3752. }
  3753. void SetToCustom()
  3754. {
  3755. if (contentType == ContentType.Custom)
  3756. return;
  3757. contentType = ContentType.Custom;
  3758. }
  3759. void SetToCustom(CharacterValidation characterValidation)
  3760. {
  3761. if (contentType == ContentType.Custom)
  3762. {
  3763. characterValidation = CharacterValidation.CustomValidator;
  3764. return;
  3765. }
  3766. contentType = ContentType.Custom;
  3767. characterValidation = CharacterValidation.CustomValidator;
  3768. }
  3769. protected override void DoStateTransition(SelectionState state, bool instant)
  3770. {
  3771. if (m_HasDoneFocusTransition)
  3772. state = SelectionState.Selected;
  3773. else if (state == SelectionState.Pressed)
  3774. m_HasDoneFocusTransition = true;
  3775. base.DoStateTransition(state, instant);
  3776. }
  3777. /// <summary>
  3778. /// See ILayoutElement.CalculateLayoutInputHorizontal.
  3779. /// </summary>
  3780. public virtual void CalculateLayoutInputHorizontal()
  3781. { }
  3782. /// <summary>
  3783. /// See ILayoutElement.CalculateLayoutInputVertical.
  3784. /// </summary>
  3785. public virtual void CalculateLayoutInputVertical()
  3786. { }
  3787. /// <summary>
  3788. /// See ILayoutElement.minWidth.
  3789. /// </summary>
  3790. public virtual float minWidth { get { return 0; } }
  3791. /// <summary>
  3792. /// Get the displayed with of all input characters.
  3793. /// </summary>
  3794. public virtual float preferredWidth
  3795. {
  3796. get
  3797. {
  3798. if (textComponent == null)
  3799. return 0;
  3800. float horizontalPadding = 0;
  3801. if (m_LayoutGroup != null)
  3802. horizontalPadding = m_LayoutGroup.padding.horizontal;
  3803. if (m_TextViewport != null)
  3804. horizontalPadding += m_TextViewport.offsetMin.x - m_TextViewport.offsetMax.x;
  3805. return m_TextComponent.preferredWidth + horizontalPadding; // Should add some extra padding for caret
  3806. }
  3807. }
  3808. /// <summary>
  3809. /// See ILayoutElement.flexibleWidth.
  3810. /// </summary>
  3811. public virtual float flexibleWidth { get { return -1; } }
  3812. /// <summary>
  3813. /// See ILayoutElement.minHeight.
  3814. /// </summary>
  3815. public virtual float minHeight { get { return 0; } }
  3816. /// <summary>
  3817. /// Get the height of all the text if constrained to the height of the RectTransform.
  3818. /// </summary>
  3819. public virtual float preferredHeight
  3820. {
  3821. get
  3822. {
  3823. if (textComponent == null)
  3824. return 0;
  3825. float verticalPadding = 0;
  3826. if (m_LayoutGroup != null)
  3827. verticalPadding = m_LayoutGroup.padding.vertical;
  3828. if (m_TextViewport != null)
  3829. verticalPadding += m_TextViewport.offsetMin.y - m_TextViewport.offsetMax.y;
  3830. return m_TextComponent.preferredHeight + verticalPadding;
  3831. }
  3832. }
  3833. /// <summary>
  3834. /// See ILayoutElement.flexibleHeight.
  3835. /// </summary>
  3836. public virtual float flexibleHeight { get { return -1; } }
  3837. /// <summary>
  3838. /// See ILayoutElement.layoutPriority.
  3839. /// </summary>
  3840. public virtual int layoutPriority { get { return 1; } }
  3841. /// <summary>
  3842. /// Function to conveniently set the point size of both Placeholder and Input Field text object.
  3843. /// </summary>
  3844. /// <param name="pointSize"></param>
  3845. public void SetGlobalPointSize(float pointSize)
  3846. {
  3847. TMP_Text placeholderTextComponent = m_Placeholder as TMP_Text;
  3848. if (placeholderTextComponent != null)
  3849. placeholderTextComponent.fontSize = pointSize;
  3850. textComponent.fontSize = pointSize;
  3851. }
  3852. /// <summary>
  3853. /// Function to conveniently set the Font Asset of both Placeholder and Input Field text object.
  3854. /// </summary>
  3855. /// <param name="fontAsset"></param>
  3856. public void SetGlobalFontAsset(TMP_FontAsset fontAsset)
  3857. {
  3858. TMP_Text placeholderTextComponent = m_Placeholder as TMP_Text;
  3859. if (placeholderTextComponent != null)
  3860. placeholderTextComponent.font = fontAsset;
  3861. textComponent.font = fontAsset;
  3862. }
  3863. }
  3864. static class SetPropertyUtility
  3865. {
  3866. public static bool SetColor(ref Color currentValue, Color newValue)
  3867. {
  3868. if (currentValue.r == newValue.r && currentValue.g == newValue.g && currentValue.b == newValue.b && currentValue.a == newValue.a)
  3869. return false;
  3870. currentValue = newValue;
  3871. return true;
  3872. }
  3873. public static bool SetEquatableStruct<T>(ref T currentValue, T newValue) where T : IEquatable<T>
  3874. {
  3875. if (currentValue.Equals(newValue))
  3876. return false;
  3877. currentValue = newValue;
  3878. return true;
  3879. }
  3880. public static bool SetStruct<T>(ref T currentValue, T newValue) where T : struct
  3881. {
  3882. if (currentValue.Equals(newValue))
  3883. return false;
  3884. currentValue = newValue;
  3885. return true;
  3886. }
  3887. public static bool SetClass<T>(ref T currentValue, T newValue) where T : class
  3888. {
  3889. if ((currentValue == null && newValue == null) || (currentValue != null && currentValue.Equals(newValue)))
  3890. return false;
  3891. currentValue = newValue;
  3892. return true;
  3893. }
  3894. }
  3895. }