TMP_InputField.cs 161 KB

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