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

TMP_InputField.cs 167KB

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