TMP_InputField.cs 153 KB

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