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 166KB

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