text_server_adv.cpp 292 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222
  1. /**************************************************************************/
  2. /* text_server_adv.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "text_server_adv.h"
  31. #ifdef GDEXTENSION
  32. // Headers for building as GDExtension plug-in.
  33. #include <godot_cpp/classes/file_access.hpp>
  34. #include <godot_cpp/classes/os.hpp>
  35. #include <godot_cpp/classes/project_settings.hpp>
  36. #include <godot_cpp/classes/rendering_server.hpp>
  37. #include <godot_cpp/classes/translation_server.hpp>
  38. #include <godot_cpp/core/error_macros.hpp>
  39. using namespace godot;
  40. #define GLOBAL_GET(m_var) ProjectSettings::get_singleton()->get_setting_with_override(m_var)
  41. #elif defined(GODOT_MODULE)
  42. // Headers for building as built-in module.
  43. #include "core/config/project_settings.h"
  44. #include "core/error/error_macros.h"
  45. #include "core/object/worker_thread_pool.h"
  46. #include "core/string/translation_server.h"
  47. #include "scene/resources/image_texture.h"
  48. #include "modules/modules_enabled.gen.h" // For freetype, msdfgen, svg.
  49. #endif
  50. // Built-in ICU data.
  51. #ifdef ICU_STATIC_DATA
  52. #include <icudata.gen.h>
  53. #endif
  54. // Thirdparty headers.
  55. #ifdef MODULE_MSDFGEN_ENABLED
  56. #include <core/EdgeHolder.h>
  57. #include <core/ShapeDistanceFinder.h>
  58. #include <core/contour-combiners.h>
  59. #include <core/edge-selectors.h>
  60. #include <msdfgen.h>
  61. #endif
  62. #ifdef MODULE_SVG_ENABLED
  63. #ifdef MODULE_FREETYPE_ENABLED
  64. #include "thorvg_svg_in_ot.h"
  65. #endif
  66. #endif
  67. /*************************************************************************/
  68. /* bmp_font_t HarfBuzz Bitmap font interface */
  69. /*************************************************************************/
  70. hb_font_funcs_t *TextServerAdvanced::funcs = nullptr;
  71. TextServerAdvanced::bmp_font_t *TextServerAdvanced::_bmp_font_create(TextServerAdvanced::FontForSizeAdvanced *p_face, bool p_unref) {
  72. bmp_font_t *bm_font = memnew(bmp_font_t);
  73. if (!bm_font) {
  74. return nullptr;
  75. }
  76. bm_font->face = p_face;
  77. bm_font->unref = p_unref;
  78. return bm_font;
  79. }
  80. void TextServerAdvanced::_bmp_font_destroy(void *p_data) {
  81. bmp_font_t *bm_font = static_cast<bmp_font_t *>(p_data);
  82. memdelete(bm_font);
  83. }
  84. hb_bool_t TextServerAdvanced::_bmp_get_nominal_glyph(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_unicode, hb_codepoint_t *r_glyph, void *p_user_data) {
  85. const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data);
  86. if (!bm_font->face) {
  87. return false;
  88. }
  89. if (!bm_font->face->glyph_map.has(p_unicode)) {
  90. if (bm_font->face->glyph_map.has(0xf000u + p_unicode)) {
  91. *r_glyph = 0xf000u + p_unicode;
  92. return true;
  93. } else {
  94. return false;
  95. }
  96. }
  97. *r_glyph = p_unicode;
  98. return true;
  99. }
  100. hb_position_t TextServerAdvanced::_bmp_get_glyph_h_advance(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_glyph, void *p_user_data) {
  101. const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data);
  102. if (!bm_font->face) {
  103. return 0;
  104. }
  105. HashMap<int32_t, FontGlyph>::Iterator E = bm_font->face->glyph_map.find(p_glyph);
  106. if (!E) {
  107. return 0;
  108. }
  109. return E->value.advance.x * 64;
  110. }
  111. hb_position_t TextServerAdvanced::_bmp_get_glyph_v_advance(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_glyph, void *p_user_data) {
  112. const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data);
  113. if (!bm_font->face) {
  114. return 0;
  115. }
  116. HashMap<int32_t, FontGlyph>::Iterator E = bm_font->face->glyph_map.find(p_glyph);
  117. if (!E) {
  118. return 0;
  119. }
  120. return -E->value.advance.y * 64;
  121. }
  122. hb_position_t TextServerAdvanced::_bmp_get_glyph_h_kerning(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_left_glyph, hb_codepoint_t p_right_glyph, void *p_user_data) {
  123. const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data);
  124. if (!bm_font->face) {
  125. return 0;
  126. }
  127. if (!bm_font->face->kerning_map.has(Vector2i(p_left_glyph, p_right_glyph))) {
  128. return 0;
  129. }
  130. return bm_font->face->kerning_map[Vector2i(p_left_glyph, p_right_glyph)].x * 64;
  131. }
  132. hb_bool_t TextServerAdvanced::_bmp_get_glyph_v_origin(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_glyph, hb_position_t *r_x, hb_position_t *r_y, void *p_user_data) {
  133. const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data);
  134. if (!bm_font->face) {
  135. return false;
  136. }
  137. HashMap<int32_t, FontGlyph>::Iterator E = bm_font->face->glyph_map.find(p_glyph);
  138. if (!E) {
  139. return false;
  140. }
  141. *r_x = E->value.advance.x * 32;
  142. *r_y = -bm_font->face->ascent * 64;
  143. return true;
  144. }
  145. hb_bool_t TextServerAdvanced::_bmp_get_glyph_extents(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_glyph, hb_glyph_extents_t *r_extents, void *p_user_data) {
  146. const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data);
  147. if (!bm_font->face) {
  148. return false;
  149. }
  150. HashMap<int32_t, FontGlyph>::Iterator E = bm_font->face->glyph_map.find(p_glyph);
  151. if (!E) {
  152. return false;
  153. }
  154. r_extents->x_bearing = 0;
  155. r_extents->y_bearing = 0;
  156. r_extents->width = E->value.rect.size.x * 64;
  157. r_extents->height = E->value.rect.size.y * 64;
  158. return true;
  159. }
  160. hb_bool_t TextServerAdvanced::_bmp_get_font_h_extents(hb_font_t *p_font, void *p_font_data, hb_font_extents_t *r_metrics, void *p_user_data) {
  161. const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data);
  162. if (!bm_font->face) {
  163. return false;
  164. }
  165. r_metrics->ascender = bm_font->face->ascent;
  166. r_metrics->descender = bm_font->face->descent;
  167. r_metrics->line_gap = 0;
  168. return true;
  169. }
  170. void TextServerAdvanced::_bmp_create_font_funcs() {
  171. if (funcs == nullptr) {
  172. funcs = hb_font_funcs_create();
  173. hb_font_funcs_set_font_h_extents_func(funcs, _bmp_get_font_h_extents, nullptr, nullptr);
  174. hb_font_funcs_set_nominal_glyph_func(funcs, _bmp_get_nominal_glyph, nullptr, nullptr);
  175. hb_font_funcs_set_glyph_h_advance_func(funcs, _bmp_get_glyph_h_advance, nullptr, nullptr);
  176. hb_font_funcs_set_glyph_v_advance_func(funcs, _bmp_get_glyph_v_advance, nullptr, nullptr);
  177. hb_font_funcs_set_glyph_v_origin_func(funcs, _bmp_get_glyph_v_origin, nullptr, nullptr);
  178. hb_font_funcs_set_glyph_h_kerning_func(funcs, _bmp_get_glyph_h_kerning, nullptr, nullptr);
  179. hb_font_funcs_set_glyph_extents_func(funcs, _bmp_get_glyph_extents, nullptr, nullptr);
  180. hb_font_funcs_make_immutable(funcs);
  181. }
  182. }
  183. void TextServerAdvanced::_bmp_free_font_funcs() {
  184. if (funcs != nullptr) {
  185. hb_font_funcs_destroy(funcs);
  186. funcs = nullptr;
  187. }
  188. }
  189. void TextServerAdvanced::_bmp_font_set_funcs(hb_font_t *p_font, TextServerAdvanced::FontForSizeAdvanced *p_face, bool p_unref) {
  190. hb_font_set_funcs(p_font, funcs, _bmp_font_create(p_face, p_unref), _bmp_font_destroy);
  191. }
  192. hb_font_t *TextServerAdvanced::_bmp_font_create(TextServerAdvanced::FontForSizeAdvanced *p_face, hb_destroy_func_t p_destroy) {
  193. hb_font_t *font;
  194. hb_face_t *face = hb_face_create(nullptr, 0);
  195. font = hb_font_create(face);
  196. hb_face_destroy(face);
  197. _bmp_font_set_funcs(font, p_face, false);
  198. return font;
  199. }
  200. /*************************************************************************/
  201. /* Character properties. */
  202. /*************************************************************************/
  203. _FORCE_INLINE_ bool is_ain(char32_t p_chr) {
  204. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_AIN;
  205. }
  206. _FORCE_INLINE_ bool is_alef(char32_t p_chr) {
  207. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_ALEF;
  208. }
  209. _FORCE_INLINE_ bool is_beh(char32_t p_chr) {
  210. int32_t prop = u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP);
  211. return (prop == U_JG_BEH) || (prop == U_JG_NOON) || (prop == U_JG_AFRICAN_NOON) || (prop == U_JG_NYA) || (prop == U_JG_YEH) || (prop == U_JG_FARSI_YEH);
  212. }
  213. _FORCE_INLINE_ bool is_dal(char32_t p_chr) {
  214. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_DAL;
  215. }
  216. _FORCE_INLINE_ bool is_feh(char32_t p_chr) {
  217. return (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_FEH) || (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_AFRICAN_FEH);
  218. }
  219. _FORCE_INLINE_ bool is_gaf(char32_t p_chr) {
  220. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_GAF;
  221. }
  222. _FORCE_INLINE_ bool is_heh(char32_t p_chr) {
  223. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_HEH;
  224. }
  225. _FORCE_INLINE_ bool is_kaf(char32_t p_chr) {
  226. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_KAF;
  227. }
  228. _FORCE_INLINE_ bool is_lam(char32_t p_chr) {
  229. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_LAM;
  230. }
  231. _FORCE_INLINE_ bool is_qaf(char32_t p_chr) {
  232. return (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_QAF) || (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_AFRICAN_QAF);
  233. }
  234. _FORCE_INLINE_ bool is_reh(char32_t p_chr) {
  235. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_REH;
  236. }
  237. _FORCE_INLINE_ bool is_seen_sad(char32_t p_chr) {
  238. return (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_SAD) || (u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_SEEN);
  239. }
  240. _FORCE_INLINE_ bool is_tah(char32_t p_chr) {
  241. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_TAH;
  242. }
  243. _FORCE_INLINE_ bool is_teh_marbuta(char32_t p_chr) {
  244. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_TEH_MARBUTA;
  245. }
  246. _FORCE_INLINE_ bool is_yeh(char32_t p_chr) {
  247. int32_t prop = u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP);
  248. return (prop == U_JG_YEH) || (prop == U_JG_FARSI_YEH) || (prop == U_JG_YEH_BARREE) || (prop == U_JG_BURUSHASKI_YEH_BARREE) || (prop == U_JG_YEH_WITH_TAIL);
  249. }
  250. _FORCE_INLINE_ bool is_waw(char32_t p_chr) {
  251. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_GROUP) == U_JG_WAW;
  252. }
  253. _FORCE_INLINE_ bool is_transparent(char32_t p_chr) {
  254. return u_getIntPropertyValue(p_chr, UCHAR_JOINING_TYPE) == U_JT_TRANSPARENT;
  255. }
  256. _FORCE_INLINE_ bool is_ligature(char32_t p_chr, char32_t p_nchr) {
  257. return (is_lam(p_chr) && is_alef(p_nchr));
  258. }
  259. _FORCE_INLINE_ bool is_connected_to_prev(char32_t p_chr, char32_t p_pchr) {
  260. int32_t prop = u_getIntPropertyValue(p_pchr, UCHAR_JOINING_TYPE);
  261. return (prop != U_JT_RIGHT_JOINING) && (prop != U_JT_NON_JOINING) ? !is_ligature(p_pchr, p_chr) : false;
  262. }
  263. /*************************************************************************/
  264. bool TextServerAdvanced::icu_data_loaded = false;
  265. PackedByteArray TextServerAdvanced::icu_data;
  266. bool TextServerAdvanced::_has_feature(Feature p_feature) const {
  267. switch (p_feature) {
  268. case FEATURE_SIMPLE_LAYOUT:
  269. case FEATURE_BIDI_LAYOUT:
  270. case FEATURE_VERTICAL_LAYOUT:
  271. case FEATURE_SHAPING:
  272. case FEATURE_KASHIDA_JUSTIFICATION:
  273. case FEATURE_BREAK_ITERATORS:
  274. case FEATURE_FONT_BITMAP:
  275. #ifdef MODULE_FREETYPE_ENABLED
  276. case FEATURE_FONT_DYNAMIC:
  277. #endif
  278. #ifdef MODULE_MSDFGEN_ENABLED
  279. case FEATURE_FONT_MSDF:
  280. #endif
  281. case FEATURE_FONT_VARIABLE:
  282. case FEATURE_CONTEXT_SENSITIVE_CASE_CONVERSION:
  283. case FEATURE_USE_SUPPORT_DATA:
  284. case FEATURE_UNICODE_IDENTIFIERS:
  285. case FEATURE_UNICODE_SECURITY:
  286. return true;
  287. default: {
  288. }
  289. }
  290. return false;
  291. }
  292. String TextServerAdvanced::_get_name() const {
  293. #ifdef GDEXTENSION
  294. return "ICU / HarfBuzz / Graphite (GDExtension)";
  295. #elif defined(GODOT_MODULE)
  296. return "ICU / HarfBuzz / Graphite (Built-in)";
  297. #endif
  298. }
  299. int64_t TextServerAdvanced::_get_features() const {
  300. int64_t interface_features = FEATURE_SIMPLE_LAYOUT | FEATURE_BIDI_LAYOUT | FEATURE_VERTICAL_LAYOUT | FEATURE_SHAPING | FEATURE_KASHIDA_JUSTIFICATION | FEATURE_BREAK_ITERATORS | FEATURE_FONT_BITMAP | FEATURE_FONT_VARIABLE | FEATURE_CONTEXT_SENSITIVE_CASE_CONVERSION | FEATURE_USE_SUPPORT_DATA;
  301. #ifdef MODULE_FREETYPE_ENABLED
  302. interface_features |= FEATURE_FONT_DYNAMIC;
  303. #endif
  304. #ifdef MODULE_MSDFGEN_ENABLED
  305. interface_features |= FEATURE_FONT_MSDF;
  306. #endif
  307. return interface_features;
  308. }
  309. void TextServerAdvanced::_free_rid(const RID &p_rid) {
  310. _THREAD_SAFE_METHOD_
  311. if (font_owner.owns(p_rid)) {
  312. MutexLock ftlock(ft_mutex);
  313. FontAdvanced *fd = font_owner.get_or_null(p_rid);
  314. for (const KeyValue<Vector2i, FontForSizeAdvanced *> &ffsd : fd->cache) {
  315. OversamplingLevel *ol = oversampling_levels.getptr(ffsd.value->viewport_oversampling);
  316. if (ol != nullptr) {
  317. ol->fonts.erase(ffsd.value);
  318. }
  319. }
  320. {
  321. MutexLock lock(fd->mutex);
  322. font_owner.free(p_rid);
  323. }
  324. memdelete(fd);
  325. } else if (font_var_owner.owns(p_rid)) {
  326. MutexLock ftlock(ft_mutex);
  327. FontAdvancedLinkedVariation *fdv = font_var_owner.get_or_null(p_rid);
  328. {
  329. font_var_owner.free(p_rid);
  330. }
  331. memdelete(fdv);
  332. } else if (shaped_owner.owns(p_rid)) {
  333. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_rid);
  334. {
  335. MutexLock lock(sd->mutex);
  336. shaped_owner.free(p_rid);
  337. }
  338. memdelete(sd);
  339. }
  340. }
  341. bool TextServerAdvanced::_has(const RID &p_rid) {
  342. _THREAD_SAFE_METHOD_
  343. return font_owner.owns(p_rid) || font_var_owner.owns(p_rid) || shaped_owner.owns(p_rid);
  344. }
  345. bool TextServerAdvanced::_load_support_data(const String &p_filename) {
  346. _THREAD_SAFE_METHOD_
  347. #if defined(ICU_STATIC_DATA) || !defined(HAVE_ICU_BUILTIN)
  348. if (!icu_data_loaded) {
  349. UErrorCode err = U_ZERO_ERROR;
  350. u_init(&err); // Do not check for errors, since we only load part of the data.
  351. icu_data_loaded = true;
  352. }
  353. #else
  354. if (!icu_data_loaded) {
  355. UErrorCode err = U_ZERO_ERROR;
  356. String filename = (p_filename.is_empty()) ? String("res://icudt_godot.dat") : p_filename;
  357. if (FileAccess::exists(filename)) {
  358. Ref<FileAccess> f = FileAccess::open(filename, FileAccess::READ);
  359. if (f.is_null()) {
  360. return false;
  361. }
  362. uint64_t len = f->get_length();
  363. icu_data = f->get_buffer(len);
  364. udata_setCommonData(icu_data.ptr(), &err);
  365. if (U_FAILURE(err)) {
  366. ERR_FAIL_V_MSG(false, u_errorName(err));
  367. }
  368. err = U_ZERO_ERROR;
  369. icu_data_loaded = true;
  370. }
  371. u_init(&err);
  372. if (U_FAILURE(err)) {
  373. ERR_FAIL_V_MSG(false, u_errorName(err));
  374. }
  375. }
  376. #endif
  377. return true;
  378. }
  379. String TextServerAdvanced::_get_support_data_filename() const {
  380. return String("icudt_godot.dat");
  381. }
  382. String TextServerAdvanced::_get_support_data_info() const {
  383. return String("ICU break iteration data (\"icudt_godot.dat\").");
  384. }
  385. bool TextServerAdvanced::_save_support_data(const String &p_filename) const {
  386. _THREAD_SAFE_METHOD_
  387. #ifdef ICU_STATIC_DATA
  388. // Store data to the res file if it's available.
  389. Ref<FileAccess> f = FileAccess::open(p_filename, FileAccess::WRITE);
  390. if (f.is_null()) {
  391. return false;
  392. }
  393. PackedByteArray icu_data_static;
  394. icu_data_static.resize(U_ICUDATA_SIZE);
  395. memcpy(icu_data_static.ptrw(), U_ICUDATA_ENTRY_POINT, U_ICUDATA_SIZE);
  396. f->store_buffer(icu_data_static);
  397. return true;
  398. #else
  399. return false;
  400. #endif
  401. }
  402. PackedByteArray TextServerAdvanced::_get_support_data() const {
  403. _THREAD_SAFE_METHOD_
  404. #ifdef ICU_STATIC_DATA
  405. PackedByteArray icu_data_static;
  406. icu_data_static.resize(U_ICUDATA_SIZE);
  407. memcpy(icu_data_static.ptrw(), U_ICUDATA_ENTRY_POINT, U_ICUDATA_SIZE);
  408. return icu_data_static;
  409. #else
  410. return icu_data;
  411. #endif
  412. }
  413. bool TextServerAdvanced::_is_locale_right_to_left(const String &p_locale) const {
  414. String l = p_locale.get_slicec('_', 0);
  415. if ((l == "ar") || (l == "dv") || (l == "he") || (l == "fa") || (l == "ff") || (l == "ku") || (l == "ur")) {
  416. return true;
  417. } else {
  418. return false;
  419. }
  420. }
  421. _FORCE_INLINE_ void TextServerAdvanced::_insert_feature(const StringName &p_name, int32_t p_tag, Variant::Type p_vtype, bool p_hidden) {
  422. FeatureInfo fi;
  423. fi.name = p_name;
  424. fi.vtype = p_vtype;
  425. fi.hidden = p_hidden;
  426. feature_sets.insert(p_name, p_tag);
  427. feature_sets_inv.insert(p_tag, fi);
  428. }
  429. void TextServerAdvanced::_insert_feature_sets() {
  430. // Registered OpenType feature tags.
  431. // Name, Tag, Data Type, Hidden
  432. _insert_feature("access_all_alternates", HB_TAG('a', 'a', 'l', 't'), Variant::Type::INT, false);
  433. _insert_feature("above_base_forms", HB_TAG('a', 'b', 'v', 'f'), Variant::Type::INT, true);
  434. _insert_feature("above_base_mark_positioning", HB_TAG('a', 'b', 'v', 'm'), Variant::Type::INT, true);
  435. _insert_feature("above_base_substitutions", HB_TAG('a', 'b', 'v', 's'), Variant::Type::INT, true);
  436. _insert_feature("alternative_fractions", HB_TAG('a', 'f', 'r', 'c'), Variant::Type::INT, false);
  437. _insert_feature("akhands", HB_TAG('a', 'k', 'h', 'n'), Variant::Type::INT, true);
  438. _insert_feature("below_base_forms", HB_TAG('b', 'l', 'w', 'f'), Variant::Type::INT, true);
  439. _insert_feature("below_base_mark_positioning", HB_TAG('b', 'l', 'w', 'm'), Variant::Type::INT, true);
  440. _insert_feature("below_base_substitutions", HB_TAG('b', 'l', 'w', 's'), Variant::Type::INT, true);
  441. _insert_feature("contextual_alternates", HB_TAG('c', 'a', 'l', 't'), Variant::Type::BOOL, false);
  442. _insert_feature("case_sensitive_forms", HB_TAG('c', 'a', 's', 'e'), Variant::Type::BOOL, false);
  443. _insert_feature("glyph_composition", HB_TAG('c', 'c', 'm', 'p'), Variant::Type::INT, true);
  444. _insert_feature("conjunct_form_after_ro", HB_TAG('c', 'f', 'a', 'r'), Variant::Type::INT, true);
  445. _insert_feature("contextual_half_width_spacing", HB_TAG('c', 'h', 'w', 's'), Variant::Type::INT, true);
  446. _insert_feature("conjunct_forms", HB_TAG('c', 'j', 'c', 't'), Variant::Type::INT, true);
  447. _insert_feature("contextual_ligatures", HB_TAG('c', 'l', 'i', 'g'), Variant::Type::BOOL, false);
  448. _insert_feature("centered_cjk_punctuation", HB_TAG('c', 'p', 'c', 't'), Variant::Type::BOOL, false);
  449. _insert_feature("capital_spacing", HB_TAG('c', 'p', 's', 'p'), Variant::Type::BOOL, false);
  450. _insert_feature("contextual_swash", HB_TAG('c', 's', 'w', 'h'), Variant::Type::INT, false);
  451. _insert_feature("cursive_positioning", HB_TAG('c', 'u', 'r', 's'), Variant::Type::INT, true);
  452. _insert_feature("character_variant_01", HB_TAG('c', 'v', '0', '1'), Variant::Type::BOOL, false);
  453. _insert_feature("character_variant_02", HB_TAG('c', 'v', '0', '2'), Variant::Type::BOOL, false);
  454. _insert_feature("character_variant_03", HB_TAG('c', 'v', '0', '3'), Variant::Type::BOOL, false);
  455. _insert_feature("character_variant_04", HB_TAG('c', 'v', '0', '4'), Variant::Type::BOOL, false);
  456. _insert_feature("character_variant_05", HB_TAG('c', 'v', '0', '5'), Variant::Type::BOOL, false);
  457. _insert_feature("character_variant_06", HB_TAG('c', 'v', '0', '6'), Variant::Type::BOOL, false);
  458. _insert_feature("character_variant_07", HB_TAG('c', 'v', '0', '7'), Variant::Type::BOOL, false);
  459. _insert_feature("character_variant_08", HB_TAG('c', 'v', '0', '8'), Variant::Type::BOOL, false);
  460. _insert_feature("character_variant_09", HB_TAG('c', 'v', '0', '9'), Variant::Type::BOOL, false);
  461. _insert_feature("character_variant_10", HB_TAG('c', 'v', '1', '0'), Variant::Type::BOOL, false);
  462. _insert_feature("character_variant_11", HB_TAG('c', 'v', '1', '1'), Variant::Type::BOOL, false);
  463. _insert_feature("character_variant_12", HB_TAG('c', 'v', '1', '2'), Variant::Type::BOOL, false);
  464. _insert_feature("character_variant_13", HB_TAG('c', 'v', '1', '3'), Variant::Type::BOOL, false);
  465. _insert_feature("character_variant_14", HB_TAG('c', 'v', '1', '4'), Variant::Type::BOOL, false);
  466. _insert_feature("character_variant_15", HB_TAG('c', 'v', '1', '5'), Variant::Type::BOOL, false);
  467. _insert_feature("character_variant_16", HB_TAG('c', 'v', '1', '6'), Variant::Type::BOOL, false);
  468. _insert_feature("character_variant_17", HB_TAG('c', 'v', '1', '7'), Variant::Type::BOOL, false);
  469. _insert_feature("character_variant_18", HB_TAG('c', 'v', '1', '8'), Variant::Type::BOOL, false);
  470. _insert_feature("character_variant_19", HB_TAG('c', 'v', '1', '9'), Variant::Type::BOOL, false);
  471. _insert_feature("character_variant_20", HB_TAG('c', 'v', '2', '0'), Variant::Type::BOOL, false);
  472. _insert_feature("character_variant_21", HB_TAG('c', 'v', '2', '1'), Variant::Type::BOOL, false);
  473. _insert_feature("character_variant_22", HB_TAG('c', 'v', '2', '2'), Variant::Type::BOOL, false);
  474. _insert_feature("character_variant_23", HB_TAG('c', 'v', '2', '3'), Variant::Type::BOOL, false);
  475. _insert_feature("character_variant_24", HB_TAG('c', 'v', '2', '4'), Variant::Type::BOOL, false);
  476. _insert_feature("character_variant_25", HB_TAG('c', 'v', '2', '5'), Variant::Type::BOOL, false);
  477. _insert_feature("character_variant_26", HB_TAG('c', 'v', '2', '6'), Variant::Type::BOOL, false);
  478. _insert_feature("character_variant_27", HB_TAG('c', 'v', '2', '7'), Variant::Type::BOOL, false);
  479. _insert_feature("character_variant_28", HB_TAG('c', 'v', '2', '8'), Variant::Type::BOOL, false);
  480. _insert_feature("character_variant_29", HB_TAG('c', 'v', '2', '9'), Variant::Type::BOOL, false);
  481. _insert_feature("character_variant_30", HB_TAG('c', 'v', '3', '0'), Variant::Type::BOOL, false);
  482. _insert_feature("character_variant_31", HB_TAG('c', 'v', '3', '1'), Variant::Type::BOOL, false);
  483. _insert_feature("character_variant_32", HB_TAG('c', 'v', '3', '2'), Variant::Type::BOOL, false);
  484. _insert_feature("character_variant_33", HB_TAG('c', 'v', '3', '3'), Variant::Type::BOOL, false);
  485. _insert_feature("character_variant_34", HB_TAG('c', 'v', '3', '4'), Variant::Type::BOOL, false);
  486. _insert_feature("character_variant_35", HB_TAG('c', 'v', '3', '5'), Variant::Type::BOOL, false);
  487. _insert_feature("character_variant_36", HB_TAG('c', 'v', '3', '6'), Variant::Type::BOOL, false);
  488. _insert_feature("character_variant_37", HB_TAG('c', 'v', '3', '7'), Variant::Type::BOOL, false);
  489. _insert_feature("character_variant_38", HB_TAG('c', 'v', '3', '8'), Variant::Type::BOOL, false);
  490. _insert_feature("character_variant_39", HB_TAG('c', 'v', '3', '9'), Variant::Type::BOOL, false);
  491. _insert_feature("character_variant_40", HB_TAG('c', 'v', '4', '0'), Variant::Type::BOOL, false);
  492. _insert_feature("character_variant_41", HB_TAG('c', 'v', '4', '1'), Variant::Type::BOOL, false);
  493. _insert_feature("character_variant_42", HB_TAG('c', 'v', '4', '2'), Variant::Type::BOOL, false);
  494. _insert_feature("character_variant_43", HB_TAG('c', 'v', '4', '3'), Variant::Type::BOOL, false);
  495. _insert_feature("character_variant_44", HB_TAG('c', 'v', '4', '4'), Variant::Type::BOOL, false);
  496. _insert_feature("character_variant_45", HB_TAG('c', 'v', '4', '5'), Variant::Type::BOOL, false);
  497. _insert_feature("character_variant_46", HB_TAG('c', 'v', '4', '6'), Variant::Type::BOOL, false);
  498. _insert_feature("character_variant_47", HB_TAG('c', 'v', '4', '7'), Variant::Type::BOOL, false);
  499. _insert_feature("character_variant_48", HB_TAG('c', 'v', '4', '8'), Variant::Type::BOOL, false);
  500. _insert_feature("character_variant_49", HB_TAG('c', 'v', '4', '9'), Variant::Type::BOOL, false);
  501. _insert_feature("character_variant_50", HB_TAG('c', 'v', '5', '0'), Variant::Type::BOOL, false);
  502. _insert_feature("character_variant_51", HB_TAG('c', 'v', '5', '1'), Variant::Type::BOOL, false);
  503. _insert_feature("character_variant_52", HB_TAG('c', 'v', '5', '2'), Variant::Type::BOOL, false);
  504. _insert_feature("character_variant_53", HB_TAG('c', 'v', '5', '3'), Variant::Type::BOOL, false);
  505. _insert_feature("character_variant_54", HB_TAG('c', 'v', '5', '4'), Variant::Type::BOOL, false);
  506. _insert_feature("character_variant_55", HB_TAG('c', 'v', '5', '5'), Variant::Type::BOOL, false);
  507. _insert_feature("character_variant_56", HB_TAG('c', 'v', '5', '6'), Variant::Type::BOOL, false);
  508. _insert_feature("character_variant_57", HB_TAG('c', 'v', '5', '7'), Variant::Type::BOOL, false);
  509. _insert_feature("character_variant_58", HB_TAG('c', 'v', '5', '8'), Variant::Type::BOOL, false);
  510. _insert_feature("character_variant_59", HB_TAG('c', 'v', '5', '9'), Variant::Type::BOOL, false);
  511. _insert_feature("character_variant_60", HB_TAG('c', 'v', '6', '0'), Variant::Type::BOOL, false);
  512. _insert_feature("character_variant_61", HB_TAG('c', 'v', '6', '1'), Variant::Type::BOOL, false);
  513. _insert_feature("character_variant_62", HB_TAG('c', 'v', '6', '2'), Variant::Type::BOOL, false);
  514. _insert_feature("character_variant_63", HB_TAG('c', 'v', '6', '3'), Variant::Type::BOOL, false);
  515. _insert_feature("character_variant_64", HB_TAG('c', 'v', '6', '4'), Variant::Type::BOOL, false);
  516. _insert_feature("character_variant_65", HB_TAG('c', 'v', '6', '5'), Variant::Type::BOOL, false);
  517. _insert_feature("character_variant_66", HB_TAG('c', 'v', '6', '6'), Variant::Type::BOOL, false);
  518. _insert_feature("character_variant_67", HB_TAG('c', 'v', '6', '7'), Variant::Type::BOOL, false);
  519. _insert_feature("character_variant_68", HB_TAG('c', 'v', '6', '8'), Variant::Type::BOOL, false);
  520. _insert_feature("character_variant_69", HB_TAG('c', 'v', '6', '9'), Variant::Type::BOOL, false);
  521. _insert_feature("character_variant_70", HB_TAG('c', 'v', '7', '0'), Variant::Type::BOOL, false);
  522. _insert_feature("character_variant_71", HB_TAG('c', 'v', '7', '1'), Variant::Type::BOOL, false);
  523. _insert_feature("character_variant_72", HB_TAG('c', 'v', '7', '2'), Variant::Type::BOOL, false);
  524. _insert_feature("character_variant_73", HB_TAG('c', 'v', '7', '3'), Variant::Type::BOOL, false);
  525. _insert_feature("character_variant_74", HB_TAG('c', 'v', '7', '4'), Variant::Type::BOOL, false);
  526. _insert_feature("character_variant_75", HB_TAG('c', 'v', '7', '5'), Variant::Type::BOOL, false);
  527. _insert_feature("character_variant_76", HB_TAG('c', 'v', '7', '6'), Variant::Type::BOOL, false);
  528. _insert_feature("character_variant_77", HB_TAG('c', 'v', '7', '7'), Variant::Type::BOOL, false);
  529. _insert_feature("character_variant_78", HB_TAG('c', 'v', '7', '8'), Variant::Type::BOOL, false);
  530. _insert_feature("character_variant_79", HB_TAG('c', 'v', '7', '9'), Variant::Type::BOOL, false);
  531. _insert_feature("character_variant_80", HB_TAG('c', 'v', '8', '0'), Variant::Type::BOOL, false);
  532. _insert_feature("character_variant_81", HB_TAG('c', 'v', '8', '1'), Variant::Type::BOOL, false);
  533. _insert_feature("character_variant_82", HB_TAG('c', 'v', '8', '2'), Variant::Type::BOOL, false);
  534. _insert_feature("character_variant_83", HB_TAG('c', 'v', '8', '3'), Variant::Type::BOOL, false);
  535. _insert_feature("character_variant_84", HB_TAG('c', 'v', '8', '4'), Variant::Type::BOOL, false);
  536. _insert_feature("character_variant_85", HB_TAG('c', 'v', '8', '5'), Variant::Type::BOOL, false);
  537. _insert_feature("character_variant_86", HB_TAG('c', 'v', '8', '6'), Variant::Type::BOOL, false);
  538. _insert_feature("character_variant_87", HB_TAG('c', 'v', '8', '7'), Variant::Type::BOOL, false);
  539. _insert_feature("character_variant_88", HB_TAG('c', 'v', '8', '8'), Variant::Type::BOOL, false);
  540. _insert_feature("character_variant_89", HB_TAG('c', 'v', '8', '9'), Variant::Type::BOOL, false);
  541. _insert_feature("character_variant_90", HB_TAG('c', 'v', '9', '0'), Variant::Type::BOOL, false);
  542. _insert_feature("character_variant_91", HB_TAG('c', 'v', '9', '1'), Variant::Type::BOOL, false);
  543. _insert_feature("character_variant_92", HB_TAG('c', 'v', '9', '2'), Variant::Type::BOOL, false);
  544. _insert_feature("character_variant_93", HB_TAG('c', 'v', '9', '3'), Variant::Type::BOOL, false);
  545. _insert_feature("character_variant_94", HB_TAG('c', 'v', '9', '4'), Variant::Type::BOOL, false);
  546. _insert_feature("character_variant_95", HB_TAG('c', 'v', '9', '5'), Variant::Type::BOOL, false);
  547. _insert_feature("character_variant_96", HB_TAG('c', 'v', '9', '6'), Variant::Type::BOOL, false);
  548. _insert_feature("character_variant_97", HB_TAG('c', 'v', '9', '7'), Variant::Type::BOOL, false);
  549. _insert_feature("character_variant_98", HB_TAG('c', 'v', '9', '8'), Variant::Type::BOOL, false);
  550. _insert_feature("character_variant_99", HB_TAG('c', 'v', '9', '9'), Variant::Type::BOOL, false);
  551. _insert_feature("petite_capitals_from_capitals", HB_TAG('c', '2', 'p', 'c'), Variant::Type::BOOL, false);
  552. _insert_feature("small_capitals_from_capitals", HB_TAG('c', '2', 's', 'c'), Variant::Type::BOOL, false);
  553. _insert_feature("distances", HB_TAG('d', 'i', 's', 't'), Variant::Type::INT, true);
  554. _insert_feature("discretionary_ligatures", HB_TAG('d', 'l', 'i', 'g'), Variant::Type::BOOL, false);
  555. _insert_feature("denominators", HB_TAG('d', 'n', 'o', 'm'), Variant::Type::BOOL, false);
  556. _insert_feature("dotless_forms", HB_TAG('d', 't', 'l', 's'), Variant::Type::INT, true);
  557. _insert_feature("expert_forms", HB_TAG('e', 'x', 'p', 't'), Variant::Type::BOOL, true);
  558. _insert_feature("final_glyph_on_line_alternates", HB_TAG('f', 'a', 'l', 't'), Variant::Type::INT, false);
  559. _insert_feature("terminal_forms_2", HB_TAG('f', 'i', 'n', '2'), Variant::Type::INT, true);
  560. _insert_feature("terminal_forms_3", HB_TAG('f', 'i', 'n', '3'), Variant::Type::INT, true);
  561. _insert_feature("terminal_forms", HB_TAG('f', 'i', 'n', 'a'), Variant::Type::INT, true);
  562. _insert_feature("flattened_accent_forms", HB_TAG('f', 'l', 'a', 'c'), Variant::Type::INT, true);
  563. _insert_feature("fractions", HB_TAG('f', 'r', 'a', 'c'), Variant::Type::BOOL, false);
  564. _insert_feature("full_widths", HB_TAG('f', 'w', 'i', 'd'), Variant::Type::BOOL, false);
  565. _insert_feature("half_forms", HB_TAG('h', 'a', 'l', 'f'), Variant::Type::INT, true);
  566. _insert_feature("halant_forms", HB_TAG('h', 'a', 'l', 'n'), Variant::Type::INT, true);
  567. _insert_feature("alternate_half_widths", HB_TAG('h', 'a', 'l', 't'), Variant::Type::BOOL, false);
  568. _insert_feature("historical_forms", HB_TAG('h', 'i', 's', 't'), Variant::Type::INT, false);
  569. _insert_feature("horizontal_kana_alternates", HB_TAG('h', 'k', 'n', 'a'), Variant::Type::BOOL, false);
  570. _insert_feature("historical_ligatures", HB_TAG('h', 'l', 'i', 'g'), Variant::Type::BOOL, false);
  571. _insert_feature("hangul", HB_TAG('h', 'n', 'g', 'l'), Variant::Type::INT, false);
  572. _insert_feature("hojo_kanji_forms", HB_TAG('h', 'o', 'j', 'o'), Variant::Type::INT, false);
  573. _insert_feature("half_widths", HB_TAG('h', 'w', 'i', 'd'), Variant::Type::BOOL, false);
  574. _insert_feature("initial_forms", HB_TAG('i', 'n', 'i', 't'), Variant::Type::INT, true);
  575. _insert_feature("isolated_forms", HB_TAG('i', 's', 'o', 'l'), Variant::Type::INT, true);
  576. _insert_feature("italics", HB_TAG('i', 't', 'a', 'l'), Variant::Type::INT, false);
  577. _insert_feature("justification_alternates", HB_TAG('j', 'a', 'l', 't'), Variant::Type::INT, false);
  578. _insert_feature("jis78_forms", HB_TAG('j', 'p', '7', '8'), Variant::Type::INT, false);
  579. _insert_feature("jis83_forms", HB_TAG('j', 'p', '8', '3'), Variant::Type::INT, false);
  580. _insert_feature("jis90_forms", HB_TAG('j', 'p', '9', '0'), Variant::Type::INT, false);
  581. _insert_feature("jis2004_forms", HB_TAG('j', 'p', '0', '4'), Variant::Type::INT, false);
  582. _insert_feature("kerning", HB_TAG('k', 'e', 'r', 'n'), Variant::Type::BOOL, false);
  583. _insert_feature("left_bounds", HB_TAG('l', 'f', 'b', 'd'), Variant::Type::INT, false);
  584. _insert_feature("standard_ligatures", HB_TAG('l', 'i', 'g', 'a'), Variant::Type::BOOL, false);
  585. _insert_feature("leading_jamo_forms", HB_TAG('l', 'j', 'm', 'o'), Variant::Type::INT, true);
  586. _insert_feature("lining_figures", HB_TAG('l', 'n', 'u', 'm'), Variant::Type::INT, false);
  587. _insert_feature("localized_forms", HB_TAG('l', 'o', 'c', 'l'), Variant::Type::INT, true);
  588. _insert_feature("left_to_right_alternates", HB_TAG('l', 't', 'r', 'a'), Variant::Type::INT, true);
  589. _insert_feature("left_to_right_mirrored_forms", HB_TAG('l', 't', 'r', 'm'), Variant::Type::INT, true);
  590. _insert_feature("mark_positioning", HB_TAG('m', 'a', 'r', 'k'), Variant::Type::INT, true);
  591. _insert_feature("medial_forms_2", HB_TAG('m', 'e', 'd', '2'), Variant::Type::INT, true);
  592. _insert_feature("medial_forms", HB_TAG('m', 'e', 'd', 'i'), Variant::Type::INT, true);
  593. _insert_feature("mathematical_greek", HB_TAG('m', 'g', 'r', 'k'), Variant::Type::BOOL, false);
  594. _insert_feature("mark_to_mark_positioning", HB_TAG('m', 'k', 'm', 'k'), Variant::Type::INT, true);
  595. _insert_feature("mark_positioning_via_substitution", HB_TAG('m', 's', 'e', 't'), Variant::Type::INT, true);
  596. _insert_feature("alternate_annotation_forms", HB_TAG('n', 'a', 'l', 't'), Variant::Type::INT, false);
  597. _insert_feature("nlc_kanji_forms", HB_TAG('n', 'l', 'c', 'k'), Variant::Type::INT, false);
  598. _insert_feature("nukta_forms", HB_TAG('n', 'u', 'k', 't'), Variant::Type::INT, true);
  599. _insert_feature("numerators", HB_TAG('n', 'u', 'm', 'r'), Variant::Type::BOOL, false);
  600. _insert_feature("oldstyle_figures", HB_TAG('o', 'n', 'u', 'm'), Variant::Type::INT, false);
  601. _insert_feature("optical_bounds", HB_TAG('o', 'p', 'b', 'd'), Variant::Type::INT, true);
  602. _insert_feature("ordinals", HB_TAG('o', 'r', 'd', 'n'), Variant::Type::BOOL, false);
  603. _insert_feature("ornaments", HB_TAG('o', 'r', 'n', 'm'), Variant::Type::INT, false);
  604. _insert_feature("proportional_alternate_widths", HB_TAG('p', 'a', 'l', 't'), Variant::Type::BOOL, false);
  605. _insert_feature("petite_capitals", HB_TAG('p', 'c', 'a', 'p'), Variant::Type::BOOL, false);
  606. _insert_feature("proportional_kana", HB_TAG('p', 'k', 'n', 'a'), Variant::Type::BOOL, false);
  607. _insert_feature("proportional_figures", HB_TAG('p', 'n', 'u', 'm'), Variant::Type::BOOL, false);
  608. _insert_feature("pre_base_forms", HB_TAG('p', 'r', 'e', 'f'), Variant::Type::INT, true);
  609. _insert_feature("pre_base_substitutions", HB_TAG('p', 'r', 'e', 's'), Variant::Type::INT, true);
  610. _insert_feature("post_base_forms", HB_TAG('p', 's', 't', 'f'), Variant::Type::INT, true);
  611. _insert_feature("post_base_substitutions", HB_TAG('p', 's', 't', 's'), Variant::Type::INT, true);
  612. _insert_feature("proportional_widths", HB_TAG('p', 'w', 'i', 'd'), Variant::Type::BOOL, false);
  613. _insert_feature("quarter_widths", HB_TAG('q', 'w', 'i', 'd'), Variant::Type::BOOL, false);
  614. _insert_feature("randomize", HB_TAG('r', 'a', 'n', 'd'), Variant::Type::INT, false);
  615. _insert_feature("required_contextual_alternates", HB_TAG('r', 'c', 'l', 't'), Variant::Type::BOOL, true);
  616. _insert_feature("rakar_forms", HB_TAG('r', 'k', 'r', 'f'), Variant::Type::INT, true);
  617. _insert_feature("required_ligatures", HB_TAG('r', 'l', 'i', 'g'), Variant::Type::BOOL, true);
  618. _insert_feature("reph_forms", HB_TAG('r', 'p', 'h', 'f'), Variant::Type::INT, true);
  619. _insert_feature("right_bounds", HB_TAG('r', 't', 'b', 'd'), Variant::Type::INT, false);
  620. _insert_feature("right_to_left_alternates", HB_TAG('r', 't', 'l', 'a'), Variant::Type::INT, true);
  621. _insert_feature("right_to_left_mirrored_forms", HB_TAG('r', 't', 'l', 'm'), Variant::Type::INT, true);
  622. _insert_feature("ruby_notation_forms", HB_TAG('r', 'u', 'b', 'y'), Variant::Type::INT, false);
  623. _insert_feature("required_variation_alternates", HB_TAG('r', 'v', 'r', 'n'), Variant::Type::INT, true);
  624. _insert_feature("stylistic_alternates", HB_TAG('s', 'a', 'l', 't'), Variant::Type::INT, false);
  625. _insert_feature("scientific_inferiors", HB_TAG('s', 'i', 'n', 'f'), Variant::Type::BOOL, false);
  626. _insert_feature("optical_size", HB_TAG('s', 'i', 'z', 'e'), Variant::Type::INT, false);
  627. _insert_feature("small_capitals", HB_TAG('s', 'm', 'c', 'p'), Variant::Type::BOOL, false);
  628. _insert_feature("simplified_forms", HB_TAG('s', 'm', 'p', 'l'), Variant::Type::INT, false);
  629. _insert_feature("stylistic_set_01", HB_TAG('s', 's', '0', '1'), Variant::Type::BOOL, false);
  630. _insert_feature("stylistic_set_02", HB_TAG('s', 's', '0', '2'), Variant::Type::BOOL, false);
  631. _insert_feature("stylistic_set_03", HB_TAG('s', 's', '0', '3'), Variant::Type::BOOL, false);
  632. _insert_feature("stylistic_set_04", HB_TAG('s', 's', '0', '4'), Variant::Type::BOOL, false);
  633. _insert_feature("stylistic_set_05", HB_TAG('s', 's', '0', '5'), Variant::Type::BOOL, false);
  634. _insert_feature("stylistic_set_06", HB_TAG('s', 's', '0', '6'), Variant::Type::BOOL, false);
  635. _insert_feature("stylistic_set_07", HB_TAG('s', 's', '0', '7'), Variant::Type::BOOL, false);
  636. _insert_feature("stylistic_set_08", HB_TAG('s', 's', '0', '8'), Variant::Type::BOOL, false);
  637. _insert_feature("stylistic_set_09", HB_TAG('s', 's', '0', '9'), Variant::Type::BOOL, false);
  638. _insert_feature("stylistic_set_10", HB_TAG('s', 's', '1', '0'), Variant::Type::BOOL, false);
  639. _insert_feature("stylistic_set_11", HB_TAG('s', 's', '1', '1'), Variant::Type::BOOL, false);
  640. _insert_feature("stylistic_set_12", HB_TAG('s', 's', '1', '2'), Variant::Type::BOOL, false);
  641. _insert_feature("stylistic_set_13", HB_TAG('s', 's', '1', '3'), Variant::Type::BOOL, false);
  642. _insert_feature("stylistic_set_14", HB_TAG('s', 's', '1', '4'), Variant::Type::BOOL, false);
  643. _insert_feature("stylistic_set_15", HB_TAG('s', 's', '1', '5'), Variant::Type::BOOL, false);
  644. _insert_feature("stylistic_set_16", HB_TAG('s', 's', '1', '6'), Variant::Type::BOOL, false);
  645. _insert_feature("stylistic_set_17", HB_TAG('s', 's', '1', '7'), Variant::Type::BOOL, false);
  646. _insert_feature("stylistic_set_18", HB_TAG('s', 's', '1', '8'), Variant::Type::BOOL, false);
  647. _insert_feature("stylistic_set_19", HB_TAG('s', 's', '1', '9'), Variant::Type::BOOL, false);
  648. _insert_feature("stylistic_set_20", HB_TAG('s', 's', '2', '0'), Variant::Type::BOOL, false);
  649. _insert_feature("math_script_style_alternates", HB_TAG('s', 's', 't', 'y'), Variant::Type::INT, true);
  650. _insert_feature("stretching_glyph_decomposition", HB_TAG('s', 't', 'c', 'h'), Variant::Type::INT, true);
  651. _insert_feature("subscript", HB_TAG('s', 'u', 'b', 's'), Variant::Type::BOOL, false);
  652. _insert_feature("superscript", HB_TAG('s', 'u', 'p', 's'), Variant::Type::BOOL, false);
  653. _insert_feature("swash", HB_TAG('s', 'w', 's', 'h'), Variant::Type::INT, false);
  654. _insert_feature("titling", HB_TAG('t', 'i', 't', 'l'), Variant::Type::BOOL, false);
  655. _insert_feature("trailing_jamo_forms", HB_TAG('t', 'j', 'm', 'o'), Variant::Type::INT, true);
  656. _insert_feature("traditional_name_forms", HB_TAG('t', 'n', 'a', 'm'), Variant::Type::INT, false);
  657. _insert_feature("tabular_figures", HB_TAG('t', 'n', 'u', 'm'), Variant::Type::BOOL, false);
  658. _insert_feature("traditional_forms", HB_TAG('t', 'r', 'a', 'd'), Variant::Type::INT, false);
  659. _insert_feature("third_widths", HB_TAG('t', 'w', 'i', 'd'), Variant::Type::BOOL, false);
  660. _insert_feature("unicase", HB_TAG('u', 'n', 'i', 'c'), Variant::Type::BOOL, false);
  661. _insert_feature("alternate_vertical_metrics", HB_TAG('v', 'a', 'l', 't'), Variant::Type::INT, false);
  662. _insert_feature("vattu_variants", HB_TAG('v', 'a', 't', 'u'), Variant::Type::INT, true);
  663. _insert_feature("vertical_contextual_half_width_spacing", HB_TAG('v', 'c', 'h', 'w'), Variant::Type::BOOL, false);
  664. _insert_feature("vertical_alternates", HB_TAG('v', 'e', 'r', 't'), Variant::Type::INT, false);
  665. _insert_feature("alternate_vertical_half_metrics", HB_TAG('v', 'h', 'a', 'l'), Variant::Type::BOOL, false);
  666. _insert_feature("vowel_jamo_forms", HB_TAG('v', 'j', 'm', 'o'), Variant::Type::INT, true);
  667. _insert_feature("vertical_kana_alternates", HB_TAG('v', 'k', 'n', 'a'), Variant::Type::INT, false);
  668. _insert_feature("vertical_kerning", HB_TAG('v', 'k', 'r', 'n'), Variant::Type::BOOL, false);
  669. _insert_feature("proportional_alternate_vertical_metrics", HB_TAG('v', 'p', 'a', 'l'), Variant::Type::BOOL, false);
  670. _insert_feature("vertical_alternates_and_rotation", HB_TAG('v', 'r', 't', '2'), Variant::Type::INT, false);
  671. _insert_feature("vertical_alternates_for_rotation", HB_TAG('v', 'r', 't', 'r'), Variant::Type::INT, false);
  672. _insert_feature("slashed_zero", HB_TAG('z', 'e', 'r', 'o'), Variant::Type::BOOL, false);
  673. // Registered OpenType variation tag.
  674. _insert_feature("italic", HB_TAG('i', 't', 'a', 'l'), Variant::Type::INT, false);
  675. _insert_feature("optical_size", HB_TAG('o', 'p', 's', 'z'), Variant::Type::INT, false);
  676. _insert_feature("slant", HB_TAG('s', 'l', 'n', 't'), Variant::Type::INT, false);
  677. _insert_feature("width", HB_TAG('w', 'd', 't', 'h'), Variant::Type::INT, false);
  678. _insert_feature("weight", HB_TAG('w', 'g', 'h', 't'), Variant::Type::INT, false);
  679. }
  680. int64_t TextServerAdvanced::_name_to_tag(const String &p_name) const {
  681. if (feature_sets.has(p_name)) {
  682. return feature_sets[p_name];
  683. }
  684. // No readable name, use tag string.
  685. return hb_tag_from_string(p_name.replace("custom_", "").ascii().get_data(), -1);
  686. }
  687. Variant::Type TextServerAdvanced::_get_tag_type(int64_t p_tag) const {
  688. if (feature_sets_inv.has(p_tag)) {
  689. return feature_sets_inv[p_tag].vtype;
  690. }
  691. return Variant::Type::INT;
  692. }
  693. bool TextServerAdvanced::_get_tag_hidden(int64_t p_tag) const {
  694. if (feature_sets_inv.has(p_tag)) {
  695. return feature_sets_inv[p_tag].hidden;
  696. }
  697. return false;
  698. }
  699. String TextServerAdvanced::_tag_to_name(int64_t p_tag) const {
  700. if (feature_sets_inv.has(p_tag)) {
  701. return feature_sets_inv[p_tag].name;
  702. }
  703. // No readable name, use tag string.
  704. char name[5];
  705. memset(name, 0, 5);
  706. hb_tag_to_string(p_tag, name);
  707. return String("custom_") + String(name);
  708. }
  709. /*************************************************************************/
  710. /* Font Glyph Rendering */
  711. /*************************************************************************/
  712. _FORCE_INLINE_ TextServerAdvanced::FontTexturePosition TextServerAdvanced::find_texture_pos_for_glyph(FontForSizeAdvanced *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height, bool p_msdf) const {
  713. FontTexturePosition ret;
  714. int mw = p_width;
  715. int mh = p_height;
  716. ShelfPackTexture *ct = p_data->textures.ptrw();
  717. for (int32_t i = 0; i < p_data->textures.size(); i++) {
  718. if (ct[i].image.is_null()) {
  719. continue;
  720. }
  721. if (p_image_format != ct[i].image->get_format()) {
  722. continue;
  723. }
  724. if (mw > ct[i].texture_w || mh > ct[i].texture_h) { // Too big for this texture.
  725. continue;
  726. }
  727. ret = ct[i].pack_rect(i, mh, mw);
  728. if (ret.index != -1) {
  729. break;
  730. }
  731. }
  732. if (ret.index == -1) {
  733. // Could not find texture to fit, create one.
  734. int texsize = MAX(p_data->size.x * 0.125, 256);
  735. texsize = next_power_of_2((uint32_t)texsize);
  736. if (p_msdf) {
  737. texsize = MIN(texsize, 2048);
  738. } else {
  739. texsize = MIN(texsize, 1024);
  740. }
  741. if (mw > texsize) { // Special case, adapt to it?
  742. texsize = next_power_of_2((uint32_t)mw);
  743. }
  744. if (mh > texsize) { // Special case, adapt to it?
  745. texsize = next_power_of_2((uint32_t)mh);
  746. }
  747. ShelfPackTexture tex = ShelfPackTexture(texsize, texsize);
  748. tex.image = Image::create_empty(texsize, texsize, false, p_image_format);
  749. {
  750. // Zero texture.
  751. uint8_t *w = tex.image->ptrw();
  752. ERR_FAIL_COND_V(texsize * texsize * p_color_size > tex.image->get_data_size(), ret);
  753. // Initialize the texture to all-white pixels to prevent artifacts when the
  754. // font is displayed at a non-default scale with filtering enabled.
  755. if (p_color_size == 2) {
  756. for (int i = 0; i < texsize * texsize * p_color_size; i += 2) { // FORMAT_LA8, BW font.
  757. w[i + 0] = 255;
  758. w[i + 1] = 0;
  759. }
  760. } else if (p_color_size == 4) {
  761. for (int i = 0; i < texsize * texsize * p_color_size; i += 4) { // FORMAT_RGBA8, Color font, Multichannel(+True) SDF.
  762. w[i + 0] = 255;
  763. w[i + 1] = 255;
  764. w[i + 2] = 255;
  765. w[i + 3] = 0;
  766. }
  767. } else {
  768. ERR_FAIL_V(ret);
  769. }
  770. }
  771. p_data->textures.push_back(tex);
  772. int32_t idx = p_data->textures.size() - 1;
  773. ret = p_data->textures.write[idx].pack_rect(idx, mh, mw);
  774. }
  775. return ret;
  776. }
  777. #ifdef MODULE_MSDFGEN_ENABLED
  778. struct MSContext {
  779. msdfgen::Point2 position;
  780. msdfgen::Shape *shape = nullptr;
  781. msdfgen::Contour *contour = nullptr;
  782. };
  783. class DistancePixelConversion {
  784. double invRange;
  785. public:
  786. _FORCE_INLINE_ explicit DistancePixelConversion(double range) :
  787. invRange(1 / range) {}
  788. _FORCE_INLINE_ void operator()(float *pixels, const msdfgen::MultiAndTrueDistance &distance) const {
  789. pixels[0] = float(invRange * distance.r + .5);
  790. pixels[1] = float(invRange * distance.g + .5);
  791. pixels[2] = float(invRange * distance.b + .5);
  792. pixels[3] = float(invRange * distance.a + .5);
  793. }
  794. };
  795. struct MSDFThreadData {
  796. msdfgen::Bitmap<float, 4> *output;
  797. msdfgen::Shape *shape;
  798. msdfgen::Projection *projection;
  799. DistancePixelConversion *distancePixelConversion;
  800. };
  801. static msdfgen::Point2 ft_point2(const FT_Vector &vector) {
  802. return msdfgen::Point2(vector.x / 60.0f, vector.y / 60.0f);
  803. }
  804. static int ft_move_to(const FT_Vector *to, void *user) {
  805. MSContext *context = static_cast<MSContext *>(user);
  806. if (!(context->contour && context->contour->edges.empty())) {
  807. context->contour = &context->shape->addContour();
  808. }
  809. context->position = ft_point2(*to);
  810. return 0;
  811. }
  812. static int ft_line_to(const FT_Vector *to, void *user) {
  813. MSContext *context = static_cast<MSContext *>(user);
  814. msdfgen::Point2 endpoint = ft_point2(*to);
  815. if (endpoint != context->position) {
  816. context->contour->addEdge(new msdfgen::LinearSegment(context->position, endpoint));
  817. context->position = endpoint;
  818. }
  819. return 0;
  820. }
  821. static int ft_conic_to(const FT_Vector *control, const FT_Vector *to, void *user) {
  822. MSContext *context = static_cast<MSContext *>(user);
  823. context->contour->addEdge(new msdfgen::QuadraticSegment(context->position, ft_point2(*control), ft_point2(*to)));
  824. context->position = ft_point2(*to);
  825. return 0;
  826. }
  827. static int ft_cubic_to(const FT_Vector *control1, const FT_Vector *control2, const FT_Vector *to, void *user) {
  828. MSContext *context = static_cast<MSContext *>(user);
  829. context->contour->addEdge(new msdfgen::CubicSegment(context->position, ft_point2(*control1), ft_point2(*control2), ft_point2(*to)));
  830. context->position = ft_point2(*to);
  831. return 0;
  832. }
  833. void TextServerAdvanced::_generateMTSDF_threaded(void *p_td, uint32_t p_y) {
  834. MSDFThreadData *td = static_cast<MSDFThreadData *>(p_td);
  835. msdfgen::ShapeDistanceFinder<msdfgen::OverlappingContourCombiner<msdfgen::MultiAndTrueDistanceSelector>> distanceFinder(*td->shape);
  836. int row = td->shape->inverseYAxis ? td->output->height() - p_y - 1 : p_y;
  837. for (int col = 0; col < td->output->width(); ++col) {
  838. int x = (p_y % 2) ? td->output->width() - col - 1 : col;
  839. msdfgen::Point2 p = td->projection->unproject(msdfgen::Point2(x + .5, p_y + .5));
  840. msdfgen::MultiAndTrueDistance distance = distanceFinder.distance(p);
  841. td->distancePixelConversion->operator()(td->output->operator()(x, row), distance);
  842. }
  843. }
  844. _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_msdf(FontAdvanced *p_font_data, FontForSizeAdvanced *p_data, int p_pixel_range, int p_rect_margin, FT_Outline *p_outline, const Vector2 &p_advance) const {
  845. msdfgen::Shape shape;
  846. shape.contours.clear();
  847. shape.inverseYAxis = false;
  848. MSContext context = {};
  849. context.shape = &shape;
  850. FT_Outline_Funcs ft_functions;
  851. ft_functions.move_to = &ft_move_to;
  852. ft_functions.line_to = &ft_line_to;
  853. ft_functions.conic_to = &ft_conic_to;
  854. ft_functions.cubic_to = &ft_cubic_to;
  855. ft_functions.shift = 0;
  856. ft_functions.delta = 0;
  857. int error = FT_Outline_Decompose(p_outline, &ft_functions, &context);
  858. ERR_FAIL_COND_V_MSG(error, FontGlyph(), "FreeType: Outline decomposition error: '" + String(FT_Error_String(error)) + "'.");
  859. if (!shape.contours.empty() && shape.contours.back().edges.empty()) {
  860. shape.contours.pop_back();
  861. }
  862. if (FT_Outline_Get_Orientation(p_outline) == 1) {
  863. for (int i = 0; i < (int)shape.contours.size(); ++i) {
  864. shape.contours[i].reverse();
  865. }
  866. }
  867. shape.inverseYAxis = true;
  868. shape.normalize();
  869. msdfgen::Shape::Bounds bounds = shape.getBounds(p_pixel_range);
  870. FontGlyph chr;
  871. chr.found = true;
  872. chr.advance = p_advance;
  873. if (shape.validate() && shape.contours.size() > 0) {
  874. int w = (bounds.r - bounds.l);
  875. int h = (bounds.t - bounds.b);
  876. if (w == 0 || h == 0) {
  877. chr.texture_idx = -1;
  878. chr.uv_rect = Rect2();
  879. chr.rect = Rect2();
  880. return chr;
  881. }
  882. int mw = w + p_rect_margin * 4;
  883. int mh = h + p_rect_margin * 4;
  884. ERR_FAIL_COND_V(mw > 4096, FontGlyph());
  885. ERR_FAIL_COND_V(mh > 4096, FontGlyph());
  886. FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, 4, Image::FORMAT_RGBA8, mw, mh, true);
  887. ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph());
  888. ShelfPackTexture &tex = p_data->textures.write[tex_pos.index];
  889. edgeColoringSimple(shape, 3.0); // Max. angle.
  890. msdfgen::Bitmap<float, 4> image(w, h); // Texture size.
  891. DistancePixelConversion distancePixelConversion(p_pixel_range);
  892. msdfgen::Projection projection(msdfgen::Vector2(1.0, 1.0), msdfgen::Vector2(-bounds.l, -bounds.b));
  893. msdfgen::MSDFGeneratorConfig config(true, msdfgen::ErrorCorrectionConfig());
  894. MSDFThreadData td;
  895. td.output = &image;
  896. td.shape = &shape;
  897. td.projection = &projection;
  898. td.distancePixelConversion = &distancePixelConversion;
  899. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_native_group_task(&TextServerAdvanced::_generateMTSDF_threaded, &td, h, -1, true, String("FontServerRasterizeMSDF"));
  900. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  901. msdfgen::msdfErrorCorrection(image, shape, projection, p_pixel_range, config);
  902. {
  903. uint8_t *wr = tex.image->ptrw();
  904. for (int i = 0; i < h; i++) {
  905. for (int j = 0; j < w; j++) {
  906. int ofs = ((i + tex_pos.y + p_rect_margin * 2) * tex.texture_w + j + tex_pos.x + p_rect_margin * 2) * 4;
  907. ERR_FAIL_COND_V(ofs >= tex.image->get_data_size(), FontGlyph());
  908. wr[ofs + 0] = (uint8_t)(CLAMP(image(j, i)[0] * 256.f, 0.f, 255.f));
  909. wr[ofs + 1] = (uint8_t)(CLAMP(image(j, i)[1] * 256.f, 0.f, 255.f));
  910. wr[ofs + 2] = (uint8_t)(CLAMP(image(j, i)[2] * 256.f, 0.f, 255.f));
  911. wr[ofs + 3] = (uint8_t)(CLAMP(image(j, i)[3] * 256.f, 0.f, 255.f));
  912. }
  913. }
  914. }
  915. tex.dirty = true;
  916. chr.texture_idx = tex_pos.index;
  917. chr.uv_rect = Rect2(tex_pos.x + p_rect_margin, tex_pos.y + p_rect_margin, w + p_rect_margin * 2, h + p_rect_margin * 2);
  918. chr.rect.position = Vector2(bounds.l - p_rect_margin, -bounds.t - p_rect_margin);
  919. chr.rect.size = chr.uv_rect.size;
  920. }
  921. return chr;
  922. }
  923. #endif
  924. #ifdef MODULE_FREETYPE_ENABLED
  925. _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_bitmap(FontForSizeAdvanced *p_data, int p_rect_margin, FT_Bitmap p_bitmap, int p_yofs, int p_xofs, const Vector2 &p_advance, bool p_bgra) const {
  926. FontGlyph chr;
  927. chr.advance = p_advance * p_data->scale;
  928. chr.found = true;
  929. int w = p_bitmap.width;
  930. int h = p_bitmap.rows;
  931. if (w == 0 || h == 0) {
  932. chr.texture_idx = -1;
  933. chr.uv_rect = Rect2();
  934. chr.rect = Rect2();
  935. return chr;
  936. }
  937. int color_size = 2;
  938. switch (p_bitmap.pixel_mode) {
  939. case FT_PIXEL_MODE_MONO:
  940. case FT_PIXEL_MODE_GRAY: {
  941. color_size = 2;
  942. } break;
  943. case FT_PIXEL_MODE_BGRA: {
  944. color_size = 4;
  945. } break;
  946. case FT_PIXEL_MODE_LCD: {
  947. color_size = 4;
  948. w /= 3;
  949. } break;
  950. case FT_PIXEL_MODE_LCD_V: {
  951. color_size = 4;
  952. h /= 3;
  953. } break;
  954. }
  955. int mw = w + p_rect_margin * 4;
  956. int mh = h + p_rect_margin * 4;
  957. ERR_FAIL_COND_V(mw > 4096, FontGlyph());
  958. ERR_FAIL_COND_V(mh > 4096, FontGlyph());
  959. Image::Format require_format = color_size == 4 ? Image::FORMAT_RGBA8 : Image::FORMAT_LA8;
  960. FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, color_size, require_format, mw, mh, false);
  961. ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph());
  962. // Fit character in char texture.
  963. ShelfPackTexture &tex = p_data->textures.write[tex_pos.index];
  964. {
  965. uint8_t *wr = tex.image->ptrw();
  966. for (int i = 0; i < h; i++) {
  967. for (int j = 0; j < w; j++) {
  968. int ofs = ((i + tex_pos.y + p_rect_margin * 2) * tex.texture_w + j + tex_pos.x + p_rect_margin * 2) * color_size;
  969. ERR_FAIL_COND_V(ofs >= tex.image->get_data_size(), FontGlyph());
  970. switch (p_bitmap.pixel_mode) {
  971. case FT_PIXEL_MODE_MONO: {
  972. int byte = i * p_bitmap.pitch + (j >> 3);
  973. int bit = 1 << (7 - (j % 8));
  974. wr[ofs + 0] = 255; // grayscale as 1
  975. wr[ofs + 1] = (p_bitmap.buffer[byte] & bit) ? 255 : 0;
  976. } break;
  977. case FT_PIXEL_MODE_GRAY:
  978. wr[ofs + 0] = 255; // grayscale as 1
  979. wr[ofs + 1] = p_bitmap.buffer[i * p_bitmap.pitch + j];
  980. break;
  981. case FT_PIXEL_MODE_BGRA: {
  982. int ofs_color = i * p_bitmap.pitch + (j << 2);
  983. wr[ofs + 2] = p_bitmap.buffer[ofs_color + 0];
  984. wr[ofs + 1] = p_bitmap.buffer[ofs_color + 1];
  985. wr[ofs + 0] = p_bitmap.buffer[ofs_color + 2];
  986. wr[ofs + 3] = p_bitmap.buffer[ofs_color + 3];
  987. } break;
  988. case FT_PIXEL_MODE_LCD: {
  989. int ofs_color = i * p_bitmap.pitch + (j * 3);
  990. if (p_bgra) {
  991. wr[ofs + 0] = p_bitmap.buffer[ofs_color + 2];
  992. wr[ofs + 1] = p_bitmap.buffer[ofs_color + 1];
  993. wr[ofs + 2] = p_bitmap.buffer[ofs_color + 0];
  994. wr[ofs + 3] = 255;
  995. } else {
  996. wr[ofs + 0] = p_bitmap.buffer[ofs_color + 0];
  997. wr[ofs + 1] = p_bitmap.buffer[ofs_color + 1];
  998. wr[ofs + 2] = p_bitmap.buffer[ofs_color + 2];
  999. wr[ofs + 3] = 255;
  1000. }
  1001. } break;
  1002. case FT_PIXEL_MODE_LCD_V: {
  1003. int ofs_color = i * p_bitmap.pitch * 3 + j;
  1004. if (p_bgra) {
  1005. wr[ofs + 0] = p_bitmap.buffer[ofs_color + p_bitmap.pitch * 2];
  1006. wr[ofs + 1] = p_bitmap.buffer[ofs_color + p_bitmap.pitch];
  1007. wr[ofs + 2] = p_bitmap.buffer[ofs_color + 0];
  1008. wr[ofs + 3] = 255;
  1009. } else {
  1010. wr[ofs + 0] = p_bitmap.buffer[ofs_color + 0];
  1011. wr[ofs + 1] = p_bitmap.buffer[ofs_color + p_bitmap.pitch];
  1012. wr[ofs + 2] = p_bitmap.buffer[ofs_color + p_bitmap.pitch * 2];
  1013. wr[ofs + 3] = 255;
  1014. }
  1015. } break;
  1016. default:
  1017. ERR_FAIL_V_MSG(FontGlyph(), "Font uses unsupported pixel format: " + String::num_int64(p_bitmap.pixel_mode) + ".");
  1018. break;
  1019. }
  1020. }
  1021. }
  1022. }
  1023. tex.dirty = true;
  1024. chr.texture_idx = tex_pos.index;
  1025. chr.uv_rect = Rect2(tex_pos.x + p_rect_margin, tex_pos.y + p_rect_margin, w + p_rect_margin * 2, h + p_rect_margin * 2);
  1026. chr.rect.position = Vector2(p_xofs - p_rect_margin, -p_yofs - p_rect_margin) * p_data->scale;
  1027. chr.rect.size = chr.uv_rect.size * p_data->scale;
  1028. return chr;
  1029. }
  1030. #endif
  1031. /*************************************************************************/
  1032. /* Font Cache */
  1033. /*************************************************************************/
  1034. bool TextServerAdvanced::_ensure_glyph(FontAdvanced *p_font_data, const Vector2i &p_size, int32_t p_glyph, FontGlyph &r_glyph, uint32_t p_oversampling) const {
  1035. FontForSizeAdvanced *fd = nullptr;
  1036. ERR_FAIL_COND_V(!_ensure_cache_for_size(p_font_data, p_size, fd, false, p_oversampling), false);
  1037. int32_t glyph_index = p_glyph & 0xffffff; // Remove subpixel shifts.
  1038. HashMap<int32_t, FontGlyph>::Iterator E = fd->glyph_map.find(p_glyph);
  1039. if (E) {
  1040. r_glyph = E->value;
  1041. return E->value.found;
  1042. }
  1043. if (glyph_index == 0) { // Non graphical or invalid glyph, do not render.
  1044. E = fd->glyph_map.insert(p_glyph, FontGlyph());
  1045. r_glyph = E->value;
  1046. return true;
  1047. }
  1048. #ifdef MODULE_FREETYPE_ENABLED
  1049. FontGlyph gl;
  1050. if (fd->face) {
  1051. FT_Int32 flags = FT_LOAD_DEFAULT;
  1052. bool outline = p_size.y > 0;
  1053. switch (p_font_data->hinting) {
  1054. case TextServer::HINTING_NONE:
  1055. flags |= FT_LOAD_NO_HINTING;
  1056. break;
  1057. case TextServer::HINTING_LIGHT:
  1058. flags |= FT_LOAD_TARGET_LIGHT;
  1059. break;
  1060. default:
  1061. flags |= FT_LOAD_TARGET_NORMAL;
  1062. break;
  1063. }
  1064. if (p_font_data->force_autohinter) {
  1065. flags |= FT_LOAD_FORCE_AUTOHINT;
  1066. }
  1067. if (outline || (p_font_data->disable_embedded_bitmaps && !FT_HAS_COLOR(fd->face))) {
  1068. flags |= FT_LOAD_NO_BITMAP;
  1069. } else if (FT_HAS_COLOR(fd->face)) {
  1070. flags |= FT_LOAD_COLOR;
  1071. }
  1072. FT_Fixed v, h;
  1073. FT_Get_Advance(fd->face, glyph_index, flags, &h);
  1074. FT_Get_Advance(fd->face, glyph_index, flags | FT_LOAD_VERTICAL_LAYOUT, &v);
  1075. int error = FT_Load_Glyph(fd->face, glyph_index, flags);
  1076. if (error) {
  1077. E = fd->glyph_map.insert(p_glyph, FontGlyph());
  1078. r_glyph = E->value;
  1079. return false;
  1080. }
  1081. if (!p_font_data->msdf) {
  1082. if ((p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && p_size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE * 64)) {
  1083. FT_Pos xshift = (int)((p_glyph >> 27) & 3) << 4;
  1084. FT_Outline_Translate(&fd->face->glyph->outline, xshift, 0);
  1085. } else if ((p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (p_font_data->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && p_size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE * 64)) {
  1086. FT_Pos xshift = (int)((p_glyph >> 27) & 3) << 5;
  1087. FT_Outline_Translate(&fd->face->glyph->outline, xshift, 0);
  1088. }
  1089. }
  1090. if (p_font_data->embolden != 0.f) {
  1091. FT_Pos strength = p_font_data->embolden * p_size.x / 16; // 26.6 fractional units (1 / 64).
  1092. FT_Outline_Embolden(&fd->face->glyph->outline, strength);
  1093. }
  1094. if (p_font_data->transform != Transform2D()) {
  1095. FT_Matrix mat = { FT_Fixed(p_font_data->transform[0][0] * 65536), FT_Fixed(p_font_data->transform[0][1] * 65536), FT_Fixed(p_font_data->transform[1][0] * 65536), FT_Fixed(p_font_data->transform[1][1] * 65536) }; // 16.16 fractional units (1 / 65536).
  1096. FT_Outline_Transform(&fd->face->glyph->outline, &mat);
  1097. }
  1098. FT_Render_Mode aa_mode = FT_RENDER_MODE_NORMAL;
  1099. bool bgra = false;
  1100. switch (p_font_data->antialiasing) {
  1101. case FONT_ANTIALIASING_NONE: {
  1102. aa_mode = FT_RENDER_MODE_MONO;
  1103. } break;
  1104. case FONT_ANTIALIASING_GRAY: {
  1105. aa_mode = FT_RENDER_MODE_NORMAL;
  1106. } break;
  1107. case FONT_ANTIALIASING_LCD: {
  1108. int aa_layout = (int)((p_glyph >> 24) & 7);
  1109. switch (aa_layout) {
  1110. case FONT_LCD_SUBPIXEL_LAYOUT_HRGB: {
  1111. aa_mode = FT_RENDER_MODE_LCD;
  1112. bgra = false;
  1113. } break;
  1114. case FONT_LCD_SUBPIXEL_LAYOUT_HBGR: {
  1115. aa_mode = FT_RENDER_MODE_LCD;
  1116. bgra = true;
  1117. } break;
  1118. case FONT_LCD_SUBPIXEL_LAYOUT_VRGB: {
  1119. aa_mode = FT_RENDER_MODE_LCD_V;
  1120. bgra = false;
  1121. } break;
  1122. case FONT_LCD_SUBPIXEL_LAYOUT_VBGR: {
  1123. aa_mode = FT_RENDER_MODE_LCD_V;
  1124. bgra = true;
  1125. } break;
  1126. default: {
  1127. aa_mode = FT_RENDER_MODE_NORMAL;
  1128. } break;
  1129. }
  1130. } break;
  1131. }
  1132. FT_GlyphSlot slot = fd->face->glyph;
  1133. bool from_svg = (slot->format == FT_GLYPH_FORMAT_SVG); // Need to check before FT_Render_Glyph as it will change format to bitmap.
  1134. if (!outline) {
  1135. if (!p_font_data->msdf) {
  1136. error = FT_Render_Glyph(slot, aa_mode);
  1137. }
  1138. if (!error) {
  1139. if (p_font_data->msdf) {
  1140. #ifdef MODULE_MSDFGEN_ENABLED
  1141. gl = rasterize_msdf(p_font_data, fd, p_font_data->msdf_range, rect_range, &slot->outline, Vector2((h + (1 << 9)) >> 10, (v + (1 << 9)) >> 10) / 64.0);
  1142. #else
  1143. fd->glyph_map[p_glyph] = FontGlyph();
  1144. ERR_FAIL_V_MSG(false, "Compiled without MSDFGEN support!");
  1145. #endif
  1146. } else {
  1147. gl = rasterize_bitmap(fd, rect_range, slot->bitmap, slot->bitmap_top, slot->bitmap_left, Vector2((h + (1 << 9)) >> 10, (v + (1 << 9)) >> 10) / 64.0, bgra);
  1148. }
  1149. }
  1150. } else {
  1151. FT_Stroker stroker;
  1152. if (FT_Stroker_New(ft_library, &stroker) != 0) {
  1153. fd->glyph_map[p_glyph] = FontGlyph();
  1154. ERR_FAIL_V_MSG(false, "FreeType: Failed to load glyph stroker.");
  1155. }
  1156. FT_Stroker_Set(stroker, (int)(fd->size.y * 16.0), FT_STROKER_LINECAP_BUTT, FT_STROKER_LINEJOIN_ROUND, 0);
  1157. FT_Glyph glyph;
  1158. FT_BitmapGlyph glyph_bitmap;
  1159. if (FT_Get_Glyph(fd->face->glyph, &glyph) != 0) {
  1160. goto cleanup_stroker;
  1161. }
  1162. if (FT_Glyph_Stroke(&glyph, stroker, 1) != 0) {
  1163. goto cleanup_glyph;
  1164. }
  1165. if (FT_Glyph_To_Bitmap(&glyph, aa_mode, nullptr, 1) != 0) {
  1166. goto cleanup_glyph;
  1167. }
  1168. glyph_bitmap = (FT_BitmapGlyph)glyph;
  1169. gl = rasterize_bitmap(fd, rect_range, glyph_bitmap->bitmap, glyph_bitmap->top, glyph_bitmap->left, Vector2(), bgra);
  1170. cleanup_glyph:
  1171. FT_Done_Glyph(glyph);
  1172. cleanup_stroker:
  1173. FT_Stroker_Done(stroker);
  1174. }
  1175. gl.from_svg = from_svg;
  1176. E = fd->glyph_map.insert(p_glyph, gl);
  1177. r_glyph = E->value;
  1178. return gl.found;
  1179. }
  1180. #endif
  1181. E = fd->glyph_map.insert(p_glyph, FontGlyph());
  1182. r_glyph = E->value;
  1183. return false;
  1184. }
  1185. bool TextServerAdvanced::_ensure_cache_for_size(FontAdvanced *p_font_data, const Vector2i &p_size, FontForSizeAdvanced *&r_cache_for_size, bool p_silent, uint32_t p_oversampling) const {
  1186. ERR_FAIL_COND_V(p_size.x <= 0, false);
  1187. HashMap<Vector2i, FontForSizeAdvanced *>::Iterator E = p_font_data->cache.find(p_size);
  1188. if (E) {
  1189. r_cache_for_size = E->value;
  1190. // Size used directly, remove from oversampling list.
  1191. if (p_oversampling == 0 && E->value->viewport_oversampling != 0) {
  1192. OversamplingLevel *ol = oversampling_levels.getptr(E->value->viewport_oversampling);
  1193. if (ol) {
  1194. ol->fonts.erase(E->value);
  1195. }
  1196. }
  1197. return true;
  1198. }
  1199. FontForSizeAdvanced *fd = memnew(FontForSizeAdvanced);
  1200. fd->size = p_size;
  1201. if (p_font_data->data_ptr && (p_font_data->data_size > 0)) {
  1202. // Init dynamic font.
  1203. #ifdef MODULE_FREETYPE_ENABLED
  1204. int error = 0;
  1205. {
  1206. MutexLock ftlock(ft_mutex);
  1207. if (!ft_library) {
  1208. error = FT_Init_FreeType(&ft_library);
  1209. if (error != 0) {
  1210. memdelete(fd);
  1211. if (p_silent) {
  1212. return false;
  1213. } else {
  1214. ERR_FAIL_V_MSG(false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'.");
  1215. }
  1216. }
  1217. #ifdef MODULE_SVG_ENABLED
  1218. FT_Property_Set(ft_library, "ot-svg", "svg-hooks", get_tvg_svg_in_ot_hooks());
  1219. #endif
  1220. }
  1221. memset(&fd->stream, 0, sizeof(FT_StreamRec));
  1222. fd->stream.base = (unsigned char *)p_font_data->data_ptr;
  1223. fd->stream.size = p_font_data->data_size;
  1224. fd->stream.pos = 0;
  1225. FT_Open_Args fargs;
  1226. memset(&fargs, 0, sizeof(FT_Open_Args));
  1227. fargs.memory_base = (unsigned char *)p_font_data->data_ptr;
  1228. fargs.memory_size = p_font_data->data_size;
  1229. fargs.flags = FT_OPEN_MEMORY;
  1230. fargs.stream = &fd->stream;
  1231. error = FT_Open_Face(ft_library, &fargs, p_font_data->face_index, &fd->face);
  1232. if (error) {
  1233. if (fd->face) {
  1234. FT_Done_Face(fd->face);
  1235. fd->face = nullptr;
  1236. }
  1237. memdelete(fd);
  1238. if (p_silent) {
  1239. return false;
  1240. } else {
  1241. ERR_FAIL_V_MSG(false, "FreeType: Error loading font: '" + String(FT_Error_String(error)) + "' (face_index=" + String::num_int64(p_font_data->face_index) + ").");
  1242. }
  1243. }
  1244. }
  1245. double sz = double(fd->size.x) / 64.0;
  1246. if (p_font_data->msdf) {
  1247. sz = p_font_data->msdf_source_size;
  1248. }
  1249. if (FT_HAS_COLOR(fd->face) && fd->face->num_fixed_sizes > 0) {
  1250. int best_match = 0;
  1251. int diff = Math::abs(sz - ((int64_t)fd->face->available_sizes[0].width));
  1252. fd->scale = sz / fd->face->available_sizes[0].width;
  1253. for (int i = 1; i < fd->face->num_fixed_sizes; i++) {
  1254. int ndiff = Math::abs(sz - ((int64_t)fd->face->available_sizes[i].width));
  1255. if (ndiff < diff) {
  1256. best_match = i;
  1257. diff = ndiff;
  1258. fd->scale = sz / fd->face->available_sizes[i].width;
  1259. }
  1260. }
  1261. FT_Select_Size(fd->face, best_match);
  1262. } else {
  1263. FT_Size_RequestRec req;
  1264. req.type = FT_SIZE_REQUEST_TYPE_NOMINAL;
  1265. req.width = sz * 64.0;
  1266. req.height = sz * 64.0;
  1267. req.horiResolution = 0;
  1268. req.vertResolution = 0;
  1269. FT_Request_Size(fd->face, &req);
  1270. if (fd->face->size->metrics.y_ppem != 0) {
  1271. fd->scale = sz / (double)fd->face->size->metrics.y_ppem;
  1272. }
  1273. }
  1274. fd->hb_handle = hb_ft_font_create(fd->face, nullptr);
  1275. fd->ascent = (fd->face->size->metrics.ascender / 64.0) * fd->scale;
  1276. fd->descent = (-fd->face->size->metrics.descender / 64.0) * fd->scale;
  1277. fd->underline_position = (-FT_MulFix(fd->face->underline_position, fd->face->size->metrics.y_scale) / 64.0) * fd->scale;
  1278. fd->underline_thickness = (FT_MulFix(fd->face->underline_thickness, fd->face->size->metrics.y_scale) / 64.0) * fd->scale;
  1279. #if HB_VERSION_ATLEAST(3, 3, 0)
  1280. hb_font_set_synthetic_slant(fd->hb_handle, p_font_data->transform[0][1]);
  1281. #else
  1282. #ifndef _MSC_VER
  1283. #warning Building with HarfBuzz < 3.3.0, synthetic slant offset correction disabled.
  1284. #endif
  1285. #endif
  1286. if (!p_font_data->face_init) {
  1287. // When a font does not provide a `family_name`, FreeType tries to synthesize one based on other names.
  1288. // FreeType automatically converts non-ASCII characters to "?" in the synthesized name.
  1289. // To avoid that behavior, use the format-specific name directly if available.
  1290. hb_face_t *hb_face = hb_font_get_face(fd->hb_handle);
  1291. unsigned int num_entries = 0;
  1292. const hb_ot_name_entry_t *names = hb_ot_name_list_names(hb_face, &num_entries);
  1293. const hb_language_t english = hb_language_from_string("en", -1);
  1294. for (unsigned int i = 0; i < num_entries; i++) {
  1295. if (names[i].name_id != HB_OT_NAME_ID_FONT_FAMILY) {
  1296. continue;
  1297. }
  1298. if (!p_font_data->font_name.is_empty() && names[i].language != english) {
  1299. continue;
  1300. }
  1301. unsigned int text_size = hb_ot_name_get_utf32(hb_face, names[i].name_id, names[i].language, nullptr, nullptr) + 1;
  1302. p_font_data->font_name.resize_uninitialized(text_size);
  1303. hb_ot_name_get_utf32(hb_face, names[i].name_id, names[i].language, &text_size, (uint32_t *)p_font_data->font_name.ptrw());
  1304. }
  1305. if (p_font_data->font_name.is_empty() && fd->face->family_name != nullptr) {
  1306. p_font_data->font_name = String::utf8((const char *)fd->face->family_name);
  1307. }
  1308. if (fd->face->style_name != nullptr) {
  1309. p_font_data->style_name = String::utf8((const char *)fd->face->style_name);
  1310. }
  1311. p_font_data->weight = _font_get_weight_by_name(p_font_data->style_name.to_lower());
  1312. p_font_data->stretch = _font_get_stretch_by_name(p_font_data->style_name.to_lower());
  1313. p_font_data->style_flags = 0;
  1314. if ((fd->face->style_flags & FT_STYLE_FLAG_BOLD) || p_font_data->weight >= 700) {
  1315. p_font_data->style_flags.set_flag(FONT_BOLD);
  1316. }
  1317. if ((fd->face->style_flags & FT_STYLE_FLAG_ITALIC) || _is_ital_style(p_font_data->style_name.to_lower())) {
  1318. p_font_data->style_flags.set_flag(FONT_ITALIC);
  1319. }
  1320. if (fd->face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) {
  1321. p_font_data->style_flags.set_flag(FONT_FIXED_WIDTH);
  1322. }
  1323. // Get supported scripts from OpenType font data.
  1324. p_font_data->supported_scripts.clear();
  1325. unsigned int count = hb_ot_layout_table_get_script_tags(hb_face, HB_OT_TAG_GSUB, 0, nullptr, nullptr);
  1326. if (count != 0) {
  1327. hb_tag_t *script_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t));
  1328. hb_ot_layout_table_get_script_tags(hb_face, HB_OT_TAG_GSUB, 0, &count, script_tags);
  1329. for (unsigned int i = 0; i < count; i++) {
  1330. p_font_data->supported_scripts.insert(script_tags[i]);
  1331. }
  1332. memfree(script_tags);
  1333. }
  1334. count = hb_ot_layout_table_get_script_tags(hb_face, HB_OT_TAG_GPOS, 0, nullptr, nullptr);
  1335. if (count != 0) {
  1336. hb_tag_t *script_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t));
  1337. hb_ot_layout_table_get_script_tags(hb_face, HB_OT_TAG_GPOS, 0, &count, script_tags);
  1338. for (unsigned int i = 0; i < count; i++) {
  1339. p_font_data->supported_scripts.insert(script_tags[i]);
  1340. }
  1341. memfree(script_tags);
  1342. }
  1343. // Get supported scripts from OS2 table.
  1344. TT_OS2 *os2 = (TT_OS2 *)FT_Get_Sfnt_Table(fd->face, FT_SFNT_OS2);
  1345. if (os2) {
  1346. if ((os2->ulUnicodeRange1 & 1L << 4) || (os2->ulUnicodeRange1 & 1L << 5) || (os2->ulUnicodeRange1 & 1L << 6) || (os2->ulUnicodeRange1 & 1L << 31) || (os2->ulUnicodeRange2 & 1L << 0) || (os2->ulUnicodeRange2 & 1L << 1) || (os2->ulUnicodeRange2 & 1L << 2) || (os2->ulUnicodeRange2 & 1L << 3) || (os2->ulUnicodeRange2 & 1L << 4) || (os2->ulUnicodeRange2 & 1L << 5) || (os2->ulUnicodeRange2 & 1L << 6) || (os2->ulUnicodeRange2 & 1L << 7) || (os2->ulUnicodeRange2 & 1L << 8) || (os2->ulUnicodeRange2 & 1L << 9) || (os2->ulUnicodeRange2 & 1L << 10) || (os2->ulUnicodeRange2 & 1L << 11) || (os2->ulUnicodeRange2 & 1L << 12) || (os2->ulUnicodeRange2 & 1L << 13) || (os2->ulUnicodeRange2 & 1L << 14) || (os2->ulUnicodeRange2 & 1L << 15) || (os2->ulUnicodeRange2 & 1L << 30) || (os2->ulUnicodeRange3 & 1L << 0) || (os2->ulUnicodeRange3 & 1L << 1) || (os2->ulUnicodeRange3 & 1L << 2) || (os2->ulUnicodeRange3 & 1L << 4) || (os2->ulUnicodeRange3 & 1L << 5) || (os2->ulUnicodeRange3 & 1L << 18) || (os2->ulUnicodeRange3 & 1L << 24) || (os2->ulUnicodeRange3 & 1L << 25) || (os2->ulUnicodeRange3 & 1L << 26) || (os2->ulUnicodeRange3 & 1L << 27) || (os2->ulUnicodeRange3 & 1L << 28) || (os2->ulUnicodeRange4 & 1L << 3) || (os2->ulUnicodeRange4 & 1L << 6) || (os2->ulUnicodeRange4 & 1L << 15) || (os2->ulUnicodeRange4 & 1L << 23) || (os2->ulUnicodeRange4 & 1L << 24) || (os2->ulUnicodeRange4 & 1L << 26)) {
  1347. p_font_data->supported_scripts.insert(HB_SCRIPT_COMMON);
  1348. }
  1349. if ((os2->ulUnicodeRange1 & 1L << 0) || (os2->ulUnicodeRange1 & 1L << 1) || (os2->ulUnicodeRange1 & 1L << 2) || (os2->ulUnicodeRange1 & 1L << 3) || (os2->ulUnicodeRange1 & 1L << 29)) {
  1350. p_font_data->supported_scripts.insert(HB_SCRIPT_LATIN);
  1351. }
  1352. if ((os2->ulUnicodeRange1 & 1L << 7) || (os2->ulUnicodeRange1 & 1L << 30)) {
  1353. p_font_data->supported_scripts.insert(HB_SCRIPT_GREEK);
  1354. }
  1355. if (os2->ulUnicodeRange1 & 1L << 8) {
  1356. p_font_data->supported_scripts.insert(HB_SCRIPT_COPTIC);
  1357. }
  1358. if (os2->ulUnicodeRange1 & 1L << 9) {
  1359. p_font_data->supported_scripts.insert(HB_SCRIPT_CYRILLIC);
  1360. }
  1361. if (os2->ulUnicodeRange1 & 1L << 10) {
  1362. p_font_data->supported_scripts.insert(HB_SCRIPT_ARMENIAN);
  1363. }
  1364. if (os2->ulUnicodeRange1 & 1L << 11) {
  1365. p_font_data->supported_scripts.insert(HB_SCRIPT_HEBREW);
  1366. }
  1367. if (os2->ulUnicodeRange1 & 1L << 12) {
  1368. p_font_data->supported_scripts.insert(HB_SCRIPT_VAI);
  1369. }
  1370. if ((os2->ulUnicodeRange1 & 1L << 13) || (os2->ulUnicodeRange2 & 1L << 31) || (os2->ulUnicodeRange3 & 1L << 3)) {
  1371. p_font_data->supported_scripts.insert(HB_SCRIPT_ARABIC);
  1372. }
  1373. if (os2->ulUnicodeRange1 & 1L << 14) {
  1374. p_font_data->supported_scripts.insert(HB_SCRIPT_NKO);
  1375. }
  1376. if (os2->ulUnicodeRange1 & 1L << 15) {
  1377. p_font_data->supported_scripts.insert(HB_SCRIPT_DEVANAGARI);
  1378. }
  1379. if (os2->ulUnicodeRange1 & 1L << 16) {
  1380. p_font_data->supported_scripts.insert(HB_SCRIPT_BENGALI);
  1381. }
  1382. if (os2->ulUnicodeRange1 & 1L << 17) {
  1383. p_font_data->supported_scripts.insert(HB_SCRIPT_GURMUKHI);
  1384. }
  1385. if (os2->ulUnicodeRange1 & 1L << 18) {
  1386. p_font_data->supported_scripts.insert(HB_SCRIPT_GUJARATI);
  1387. }
  1388. if (os2->ulUnicodeRange1 & 1L << 19) {
  1389. p_font_data->supported_scripts.insert(HB_SCRIPT_ORIYA);
  1390. }
  1391. if (os2->ulUnicodeRange1 & 1L << 20) {
  1392. p_font_data->supported_scripts.insert(HB_SCRIPT_TAMIL);
  1393. }
  1394. if (os2->ulUnicodeRange1 & 1L << 21) {
  1395. p_font_data->supported_scripts.insert(HB_SCRIPT_TELUGU);
  1396. }
  1397. if (os2->ulUnicodeRange1 & 1L << 22) {
  1398. p_font_data->supported_scripts.insert(HB_SCRIPT_KANNADA);
  1399. }
  1400. if (os2->ulUnicodeRange1 & 1L << 23) {
  1401. p_font_data->supported_scripts.insert(HB_SCRIPT_MALAYALAM);
  1402. }
  1403. if (os2->ulUnicodeRange1 & 1L << 24) {
  1404. p_font_data->supported_scripts.insert(HB_SCRIPT_THAI);
  1405. }
  1406. if (os2->ulUnicodeRange1 & 1L << 25) {
  1407. p_font_data->supported_scripts.insert(HB_SCRIPT_LAO);
  1408. }
  1409. if (os2->ulUnicodeRange1 & 1L << 26) {
  1410. p_font_data->supported_scripts.insert(HB_SCRIPT_GEORGIAN);
  1411. }
  1412. if (os2->ulUnicodeRange1 & 1L << 27) {
  1413. p_font_data->supported_scripts.insert(HB_SCRIPT_BALINESE);
  1414. }
  1415. if ((os2->ulUnicodeRange1 & 1L << 28) || (os2->ulUnicodeRange2 & 1L << 20) || (os2->ulUnicodeRange2 & 1L << 24)) {
  1416. p_font_data->supported_scripts.insert(HB_SCRIPT_HANGUL);
  1417. }
  1418. if ((os2->ulUnicodeRange2 & 1L << 21) || (os2->ulUnicodeRange2 & 1L << 22) || (os2->ulUnicodeRange2 & 1L << 23) || (os2->ulUnicodeRange2 & 1L << 26) || (os2->ulUnicodeRange2 & 1L << 27) || (os2->ulUnicodeRange2 & 1L << 29)) {
  1419. p_font_data->supported_scripts.insert(HB_SCRIPT_HAN);
  1420. }
  1421. if (os2->ulUnicodeRange2 & 1L << 17) {
  1422. p_font_data->supported_scripts.insert(HB_SCRIPT_HIRAGANA);
  1423. }
  1424. if (os2->ulUnicodeRange2 & 1L << 18) {
  1425. p_font_data->supported_scripts.insert(HB_SCRIPT_KATAKANA);
  1426. }
  1427. if (os2->ulUnicodeRange2 & 1L << 19) {
  1428. p_font_data->supported_scripts.insert(HB_SCRIPT_BOPOMOFO);
  1429. }
  1430. if (os2->ulUnicodeRange3 & 1L << 6) {
  1431. p_font_data->supported_scripts.insert(HB_SCRIPT_TIBETAN);
  1432. }
  1433. if (os2->ulUnicodeRange3 & 1L << 7) {
  1434. p_font_data->supported_scripts.insert(HB_SCRIPT_SYRIAC);
  1435. }
  1436. if (os2->ulUnicodeRange3 & 1L << 8) {
  1437. p_font_data->supported_scripts.insert(HB_SCRIPT_THAANA);
  1438. }
  1439. if (os2->ulUnicodeRange3 & 1L << 9) {
  1440. p_font_data->supported_scripts.insert(HB_SCRIPT_SINHALA);
  1441. }
  1442. if (os2->ulUnicodeRange3 & 1L << 10) {
  1443. p_font_data->supported_scripts.insert(HB_SCRIPT_MYANMAR);
  1444. }
  1445. if (os2->ulUnicodeRange3 & 1L << 11) {
  1446. p_font_data->supported_scripts.insert(HB_SCRIPT_ETHIOPIC);
  1447. }
  1448. if (os2->ulUnicodeRange3 & 1L << 12) {
  1449. p_font_data->supported_scripts.insert(HB_SCRIPT_CHEROKEE);
  1450. }
  1451. if (os2->ulUnicodeRange3 & 1L << 13) {
  1452. p_font_data->supported_scripts.insert(HB_SCRIPT_CANADIAN_SYLLABICS);
  1453. }
  1454. if (os2->ulUnicodeRange3 & 1L << 14) {
  1455. p_font_data->supported_scripts.insert(HB_SCRIPT_OGHAM);
  1456. }
  1457. if (os2->ulUnicodeRange3 & 1L << 15) {
  1458. p_font_data->supported_scripts.insert(HB_SCRIPT_RUNIC);
  1459. }
  1460. if (os2->ulUnicodeRange3 & 1L << 16) {
  1461. p_font_data->supported_scripts.insert(HB_SCRIPT_KHMER);
  1462. }
  1463. if (os2->ulUnicodeRange3 & 1L << 17) {
  1464. p_font_data->supported_scripts.insert(HB_SCRIPT_MONGOLIAN);
  1465. }
  1466. if (os2->ulUnicodeRange3 & 1L << 19) {
  1467. p_font_data->supported_scripts.insert(HB_SCRIPT_YI);
  1468. }
  1469. if (os2->ulUnicodeRange3 & 1L << 20) {
  1470. p_font_data->supported_scripts.insert(HB_SCRIPT_HANUNOO);
  1471. p_font_data->supported_scripts.insert(HB_SCRIPT_TAGBANWA);
  1472. p_font_data->supported_scripts.insert(HB_SCRIPT_BUHID);
  1473. p_font_data->supported_scripts.insert(HB_SCRIPT_TAGALOG);
  1474. }
  1475. if (os2->ulUnicodeRange3 & 1L << 21) {
  1476. p_font_data->supported_scripts.insert(HB_SCRIPT_OLD_ITALIC);
  1477. }
  1478. if (os2->ulUnicodeRange3 & 1L << 22) {
  1479. p_font_data->supported_scripts.insert(HB_SCRIPT_GOTHIC);
  1480. }
  1481. if (os2->ulUnicodeRange3 & 1L << 23) {
  1482. p_font_data->supported_scripts.insert(HB_SCRIPT_DESERET);
  1483. }
  1484. if (os2->ulUnicodeRange3 & 1L << 29) {
  1485. p_font_data->supported_scripts.insert(HB_SCRIPT_LIMBU);
  1486. }
  1487. if (os2->ulUnicodeRange3 & 1L << 30) {
  1488. p_font_data->supported_scripts.insert(HB_SCRIPT_TAI_LE);
  1489. }
  1490. if (os2->ulUnicodeRange3 & 1L << 31) {
  1491. p_font_data->supported_scripts.insert(HB_SCRIPT_NEW_TAI_LUE);
  1492. }
  1493. if (os2->ulUnicodeRange4 & 1L << 0) {
  1494. p_font_data->supported_scripts.insert(HB_SCRIPT_BUGINESE);
  1495. }
  1496. if (os2->ulUnicodeRange4 & 1L << 1) {
  1497. p_font_data->supported_scripts.insert(HB_SCRIPT_GLAGOLITIC);
  1498. }
  1499. if (os2->ulUnicodeRange4 & 1L << 2) {
  1500. p_font_data->supported_scripts.insert(HB_SCRIPT_TIFINAGH);
  1501. }
  1502. if (os2->ulUnicodeRange4 & 1L << 4) {
  1503. p_font_data->supported_scripts.insert(HB_SCRIPT_SYLOTI_NAGRI);
  1504. }
  1505. if (os2->ulUnicodeRange4 & 1L << 5) {
  1506. p_font_data->supported_scripts.insert(HB_SCRIPT_LINEAR_B);
  1507. }
  1508. if (os2->ulUnicodeRange4 & 1L << 7) {
  1509. p_font_data->supported_scripts.insert(HB_SCRIPT_UGARITIC);
  1510. }
  1511. if (os2->ulUnicodeRange4 & 1L << 8) {
  1512. p_font_data->supported_scripts.insert(HB_SCRIPT_OLD_PERSIAN);
  1513. }
  1514. if (os2->ulUnicodeRange4 & 1L << 9) {
  1515. p_font_data->supported_scripts.insert(HB_SCRIPT_SHAVIAN);
  1516. }
  1517. if (os2->ulUnicodeRange4 & 1L << 10) {
  1518. p_font_data->supported_scripts.insert(HB_SCRIPT_OSMANYA);
  1519. }
  1520. if (os2->ulUnicodeRange4 & 1L << 11) {
  1521. p_font_data->supported_scripts.insert(HB_SCRIPT_CYPRIOT);
  1522. }
  1523. if (os2->ulUnicodeRange4 & 1L << 12) {
  1524. p_font_data->supported_scripts.insert(HB_SCRIPT_KHAROSHTHI);
  1525. }
  1526. if (os2->ulUnicodeRange4 & 1L << 13) {
  1527. p_font_data->supported_scripts.insert(HB_SCRIPT_TAI_VIET);
  1528. }
  1529. if (os2->ulUnicodeRange4 & 1L << 14) {
  1530. p_font_data->supported_scripts.insert(HB_SCRIPT_CUNEIFORM);
  1531. }
  1532. if (os2->ulUnicodeRange4 & 1L << 16) {
  1533. p_font_data->supported_scripts.insert(HB_SCRIPT_SUNDANESE);
  1534. }
  1535. if (os2->ulUnicodeRange4 & 1L << 17) {
  1536. p_font_data->supported_scripts.insert(HB_SCRIPT_LEPCHA);
  1537. }
  1538. if (os2->ulUnicodeRange4 & 1L << 18) {
  1539. p_font_data->supported_scripts.insert(HB_SCRIPT_OL_CHIKI);
  1540. }
  1541. if (os2->ulUnicodeRange4 & 1L << 19) {
  1542. p_font_data->supported_scripts.insert(HB_SCRIPT_SAURASHTRA);
  1543. }
  1544. if (os2->ulUnicodeRange4 & 1L << 20) {
  1545. p_font_data->supported_scripts.insert(HB_SCRIPT_KAYAH_LI);
  1546. }
  1547. if (os2->ulUnicodeRange4 & 1L << 21) {
  1548. p_font_data->supported_scripts.insert(HB_SCRIPT_REJANG);
  1549. }
  1550. if (os2->ulUnicodeRange4 & 1L << 22) {
  1551. p_font_data->supported_scripts.insert(HB_SCRIPT_CHAM);
  1552. }
  1553. if (os2->ulUnicodeRange4 & 1L << 25) {
  1554. p_font_data->supported_scripts.insert(HB_SCRIPT_ANATOLIAN_HIEROGLYPHS);
  1555. }
  1556. }
  1557. // Validate script sample strings.
  1558. {
  1559. LocalVector<uint32_t> failed_scripts;
  1560. Vector<UChar> sample_buf;
  1561. sample_buf.resize(255);
  1562. for (const uint32_t &scr_tag : p_font_data->supported_scripts) {
  1563. if ((hb_script_t)scr_tag == HB_SCRIPT_COMMON) {
  1564. continue;
  1565. }
  1566. UErrorCode icu_err = U_ZERO_ERROR;
  1567. int32_t len = uscript_getSampleString(hb_icu_script_from_script((hb_script_t)scr_tag), sample_buf.ptrw(), 255, &icu_err);
  1568. if (U_SUCCESS(icu_err) && len > 0) {
  1569. String sample = String::utf16(sample_buf.ptr(), len);
  1570. for (int ch = 0; ch < sample.length(); ch++) {
  1571. if (FT_Get_Char_Index(fd->face, sample[ch]) == 0) {
  1572. failed_scripts.push_back(scr_tag);
  1573. break;
  1574. }
  1575. }
  1576. }
  1577. }
  1578. for (const uint32_t &scr_tag : failed_scripts) {
  1579. p_font_data->supported_scripts.erase(scr_tag);
  1580. }
  1581. }
  1582. // Read OpenType feature tags.
  1583. p_font_data->supported_features.clear();
  1584. count = hb_ot_layout_table_get_feature_tags(hb_face, HB_OT_TAG_GSUB, 0, nullptr, nullptr);
  1585. if (count != 0) {
  1586. hb_tag_t *feature_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t));
  1587. hb_ot_layout_table_get_feature_tags(hb_face, HB_OT_TAG_GSUB, 0, &count, feature_tags);
  1588. for (unsigned int i = 0; i < count; i++) {
  1589. Dictionary ftr;
  1590. #if HB_VERSION_ATLEAST(2, 1, 0)
  1591. hb_ot_name_id_t lbl_id;
  1592. if (hb_ot_layout_feature_get_name_ids(hb_face, HB_OT_TAG_GSUB, i, &lbl_id, nullptr, nullptr, nullptr, nullptr)) {
  1593. PackedInt32Array lbl;
  1594. unsigned int text_size = hb_ot_name_get_utf32(hb_face, lbl_id, hb_language_from_string(TranslationServer::get_singleton()->get_tool_locale().ascii().get_data(), -1), nullptr, nullptr) + 1;
  1595. lbl.resize(text_size);
  1596. memset((uint32_t *)lbl.ptrw(), 0, sizeof(uint32_t) * text_size);
  1597. hb_ot_name_get_utf32(hb_face, lbl_id, hb_language_from_string(TranslationServer::get_singleton()->get_tool_locale().ascii().get_data(), -1), &text_size, (uint32_t *)lbl.ptrw());
  1598. ftr["label"] = String((const char32_t *)lbl.ptr());
  1599. }
  1600. #else
  1601. #ifndef _MSC_VER
  1602. #warning Building with HarfBuzz < 2.1.0, readable OpenType feature names disabled.
  1603. #endif
  1604. #endif
  1605. ftr["type"] = _get_tag_type(feature_tags[i]);
  1606. ftr["hidden"] = _get_tag_hidden(feature_tags[i]);
  1607. p_font_data->supported_features[feature_tags[i]] = ftr;
  1608. }
  1609. memfree(feature_tags);
  1610. }
  1611. count = hb_ot_layout_table_get_feature_tags(hb_face, HB_OT_TAG_GPOS, 0, nullptr, nullptr);
  1612. if (count != 0) {
  1613. hb_tag_t *feature_tags = (hb_tag_t *)memalloc(count * sizeof(hb_tag_t));
  1614. hb_ot_layout_table_get_feature_tags(hb_face, HB_OT_TAG_GPOS, 0, &count, feature_tags);
  1615. for (unsigned int i = 0; i < count; i++) {
  1616. Dictionary ftr;
  1617. #if HB_VERSION_ATLEAST(2, 1, 0)
  1618. hb_ot_name_id_t lbl_id;
  1619. if (hb_ot_layout_feature_get_name_ids(hb_face, HB_OT_TAG_GPOS, i, &lbl_id, nullptr, nullptr, nullptr, nullptr)) {
  1620. PackedInt32Array lbl;
  1621. unsigned int text_size = hb_ot_name_get_utf32(hb_face, lbl_id, hb_language_from_string(TranslationServer::get_singleton()->get_tool_locale().ascii().get_data(), -1), nullptr, nullptr) + 1;
  1622. lbl.resize(text_size);
  1623. memset((uint32_t *)lbl.ptrw(), 0, sizeof(uint32_t) * text_size);
  1624. hb_ot_name_get_utf32(hb_face, lbl_id, hb_language_from_string(TranslationServer::get_singleton()->get_tool_locale().ascii().get_data(), -1), &text_size, (uint32_t *)lbl.ptrw());
  1625. ftr["label"] = String((const char32_t *)lbl.ptr());
  1626. }
  1627. #else
  1628. #ifndef _MSC_VER
  1629. #warning Building with HarfBuzz < 2.1.0, readable OpenType feature names disabled.
  1630. #endif
  1631. #endif
  1632. ftr["type"] = _get_tag_type(feature_tags[i]);
  1633. ftr["hidden"] = _get_tag_hidden(feature_tags[i]);
  1634. p_font_data->supported_features[feature_tags[i]] = ftr;
  1635. }
  1636. memfree(feature_tags);
  1637. }
  1638. // Read OpenType variations.
  1639. p_font_data->supported_varaitions.clear();
  1640. if (fd->face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
  1641. FT_MM_Var *amaster;
  1642. FT_Get_MM_Var(fd->face, &amaster);
  1643. for (FT_UInt i = 0; i < amaster->num_axis; i++) {
  1644. p_font_data->supported_varaitions[(int32_t)amaster->axis[i].tag] = Vector3i(amaster->axis[i].minimum / 65536, amaster->axis[i].maximum / 65536, amaster->axis[i].def / 65536);
  1645. }
  1646. FT_Done_MM_Var(ft_library, amaster);
  1647. }
  1648. p_font_data->face_init = true;
  1649. }
  1650. #if defined(MACOS_ENABLED) || defined(IOS_ENABLED)
  1651. if (p_font_data->font_name == ".Apple Color Emoji UI" || p_font_data->font_name == "Apple Color Emoji") {
  1652. // The baseline offset is missing from the Apple Color Emoji UI font data, so add it manually.
  1653. // This issue doesn't occur with other system emoji fonts.
  1654. if (!FT_Load_Glyph(fd->face, FT_Get_Char_Index(fd->face, 0x1F92E), FT_LOAD_DEFAULT | FT_LOAD_COLOR)) {
  1655. if (fd->face->glyph->metrics.horiBearingY == fd->face->glyph->metrics.height) {
  1656. p_font_data->baseline_offset = 0.15;
  1657. }
  1658. }
  1659. }
  1660. #endif
  1661. // Write variations.
  1662. if (fd->face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) {
  1663. FT_MM_Var *amaster;
  1664. FT_Get_MM_Var(fd->face, &amaster);
  1665. Vector<hb_variation_t> hb_vars;
  1666. Vector<FT_Fixed> coords;
  1667. coords.resize(amaster->num_axis);
  1668. FT_Get_Var_Design_Coordinates(fd->face, coords.size(), coords.ptrw());
  1669. for (FT_UInt i = 0; i < amaster->num_axis; i++) {
  1670. hb_variation_t var;
  1671. // Reset to default.
  1672. var.tag = amaster->axis[i].tag;
  1673. var.value = (double)amaster->axis[i].def / 65536.0;
  1674. coords.write[i] = amaster->axis[i].def;
  1675. if (p_font_data->variation_coordinates.has(var.tag)) {
  1676. var.value = p_font_data->variation_coordinates[var.tag];
  1677. coords.write[i] = CLAMP(var.value * 65536.0, amaster->axis[i].minimum, amaster->axis[i].maximum);
  1678. }
  1679. if (p_font_data->variation_coordinates.has(_tag_to_name(var.tag))) {
  1680. var.value = p_font_data->variation_coordinates[_tag_to_name(var.tag)];
  1681. coords.write[i] = CLAMP(var.value * 65536.0, amaster->axis[i].minimum, amaster->axis[i].maximum);
  1682. }
  1683. hb_vars.push_back(var);
  1684. }
  1685. FT_Set_Var_Design_Coordinates(fd->face, coords.size(), coords.ptrw());
  1686. hb_font_set_variations(fd->hb_handle, hb_vars.is_empty() ? nullptr : &hb_vars[0], hb_vars.size());
  1687. FT_Done_MM_Var(ft_library, amaster);
  1688. }
  1689. #else
  1690. memdelete(fd);
  1691. if (p_silent) {
  1692. return false;
  1693. } else {
  1694. ERR_FAIL_V_MSG(false, "FreeType: Can't load dynamic font, engine is compiled without FreeType support!");
  1695. }
  1696. #endif
  1697. } else {
  1698. // Init bitmap font.
  1699. fd->hb_handle = _bmp_font_create(fd, nullptr);
  1700. }
  1701. fd->owner = p_font_data;
  1702. p_font_data->cache.insert(p_size, fd);
  1703. r_cache_for_size = fd;
  1704. if (p_oversampling != 0) {
  1705. OversamplingLevel *ol = oversampling_levels.getptr(p_oversampling);
  1706. if (ol) {
  1707. fd->viewport_oversampling = p_oversampling;
  1708. ol->fonts.insert(fd);
  1709. }
  1710. }
  1711. return true;
  1712. }
  1713. void TextServerAdvanced::_reference_oversampling_level(double p_oversampling) {
  1714. uint32_t oversampling = CLAMP(p_oversampling, 0.1, 100.0) * 64;
  1715. if (oversampling == 64) {
  1716. return;
  1717. }
  1718. OversamplingLevel *ol = oversampling_levels.getptr(oversampling);
  1719. if (ol) {
  1720. ol->refcount++;
  1721. } else {
  1722. OversamplingLevel new_ol;
  1723. oversampling_levels.insert(oversampling, new_ol);
  1724. }
  1725. }
  1726. void TextServerAdvanced::_unreference_oversampling_level(double p_oversampling) {
  1727. uint32_t oversampling = CLAMP(p_oversampling, 0.1, 100.0) * 64;
  1728. if (oversampling == 64) {
  1729. return;
  1730. }
  1731. OversamplingLevel *ol = oversampling_levels.getptr(oversampling);
  1732. if (ol) {
  1733. ol->refcount--;
  1734. if (ol->refcount == 0) {
  1735. for (FontForSizeAdvanced *fd : ol->fonts) {
  1736. fd->owner->cache.erase(fd->size);
  1737. memdelete(fd);
  1738. }
  1739. ol->fonts.clear();
  1740. oversampling_levels.erase(oversampling);
  1741. }
  1742. }
  1743. }
  1744. _FORCE_INLINE_ bool TextServerAdvanced::_font_validate(const RID &p_font_rid) const {
  1745. FontAdvanced *fd = _get_font_data(p_font_rid);
  1746. ERR_FAIL_NULL_V(fd, false);
  1747. MutexLock lock(fd->mutex);
  1748. Vector2i size = _get_size(fd, 16);
  1749. FontForSizeAdvanced *ffsd = nullptr;
  1750. return _ensure_cache_for_size(fd, size, ffsd, true);
  1751. }
  1752. _FORCE_INLINE_ void TextServerAdvanced::_font_clear_cache(FontAdvanced *p_font_data) {
  1753. MutexLock ftlock(ft_mutex);
  1754. for (const KeyValue<Vector2i, FontForSizeAdvanced *> &E : p_font_data->cache) {
  1755. if (E.value->viewport_oversampling != 0) {
  1756. OversamplingLevel *ol = oversampling_levels.getptr(E.value->viewport_oversampling);
  1757. if (ol) {
  1758. ol->fonts.erase(E.value);
  1759. }
  1760. }
  1761. memdelete(E.value);
  1762. }
  1763. p_font_data->cache.clear();
  1764. p_font_data->face_init = false;
  1765. p_font_data->supported_features.clear();
  1766. p_font_data->supported_varaitions.clear();
  1767. p_font_data->supported_scripts.clear();
  1768. }
  1769. hb_font_t *TextServerAdvanced::_font_get_hb_handle(const RID &p_font_rid, int64_t p_size) const {
  1770. FontAdvanced *fd = _get_font_data(p_font_rid);
  1771. ERR_FAIL_NULL_V(fd, nullptr);
  1772. MutexLock lock(fd->mutex);
  1773. Vector2i size = _get_size(fd, p_size);
  1774. FontForSizeAdvanced *ffsd = nullptr;
  1775. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), nullptr);
  1776. return ffsd->hb_handle;
  1777. }
  1778. RID TextServerAdvanced::_create_font() {
  1779. _THREAD_SAFE_METHOD_
  1780. FontAdvanced *fd = memnew(FontAdvanced);
  1781. return font_owner.make_rid(fd);
  1782. }
  1783. RID TextServerAdvanced::_create_font_linked_variation(const RID &p_font_rid) {
  1784. _THREAD_SAFE_METHOD_
  1785. RID rid = p_font_rid;
  1786. FontAdvancedLinkedVariation *fdv = font_var_owner.get_or_null(rid);
  1787. if (unlikely(fdv)) {
  1788. rid = fdv->base_font;
  1789. }
  1790. ERR_FAIL_COND_V(!font_owner.owns(rid), RID());
  1791. FontAdvancedLinkedVariation *new_fdv = memnew(FontAdvancedLinkedVariation);
  1792. new_fdv->base_font = rid;
  1793. return font_var_owner.make_rid(new_fdv);
  1794. }
  1795. void TextServerAdvanced::_font_set_data(const RID &p_font_rid, const PackedByteArray &p_data) {
  1796. FontAdvanced *fd = _get_font_data(p_font_rid);
  1797. ERR_FAIL_NULL(fd);
  1798. MutexLock lock(fd->mutex);
  1799. _font_clear_cache(fd);
  1800. fd->data = p_data;
  1801. fd->data_ptr = fd->data.ptr();
  1802. fd->data_size = fd->data.size();
  1803. }
  1804. void TextServerAdvanced::_font_set_data_ptr(const RID &p_font_rid, const uint8_t *p_data_ptr, int64_t p_data_size) {
  1805. FontAdvanced *fd = _get_font_data(p_font_rid);
  1806. ERR_FAIL_NULL(fd);
  1807. MutexLock lock(fd->mutex);
  1808. _font_clear_cache(fd);
  1809. fd->data.resize(0);
  1810. fd->data_ptr = p_data_ptr;
  1811. fd->data_size = p_data_size;
  1812. }
  1813. void TextServerAdvanced::_font_set_face_index(const RID &p_font_rid, int64_t p_face_index) {
  1814. ERR_FAIL_COND(p_face_index < 0);
  1815. ERR_FAIL_COND(p_face_index >= 0x7FFF);
  1816. FontAdvanced *fd = _get_font_data(p_font_rid);
  1817. ERR_FAIL_NULL(fd);
  1818. MutexLock lock(fd->mutex);
  1819. if (fd->face_index != p_face_index) {
  1820. fd->face_index = p_face_index;
  1821. _font_clear_cache(fd);
  1822. }
  1823. }
  1824. int64_t TextServerAdvanced::_font_get_face_index(const RID &p_font_rid) const {
  1825. FontAdvanced *fd = _get_font_data(p_font_rid);
  1826. ERR_FAIL_NULL_V(fd, 0);
  1827. MutexLock lock(fd->mutex);
  1828. return fd->face_index;
  1829. }
  1830. int64_t TextServerAdvanced::_font_get_face_count(const RID &p_font_rid) const {
  1831. FontAdvanced *fd = _get_font_data(p_font_rid);
  1832. ERR_FAIL_NULL_V(fd, 0);
  1833. MutexLock lock(fd->mutex);
  1834. int face_count = 0;
  1835. if (fd->data_ptr && (fd->data_size > 0)) {
  1836. // Init dynamic font.
  1837. #ifdef MODULE_FREETYPE_ENABLED
  1838. int error = 0;
  1839. if (!ft_library) {
  1840. error = FT_Init_FreeType(&ft_library);
  1841. ERR_FAIL_COND_V_MSG(error != 0, false, "FreeType: Error initializing library: '" + String(FT_Error_String(error)) + "'.");
  1842. #ifdef MODULE_SVG_ENABLED
  1843. FT_Property_Set(ft_library, "ot-svg", "svg-hooks", get_tvg_svg_in_ot_hooks());
  1844. #endif
  1845. }
  1846. FT_StreamRec stream;
  1847. memset(&stream, 0, sizeof(FT_StreamRec));
  1848. stream.base = (unsigned char *)fd->data_ptr;
  1849. stream.size = fd->data_size;
  1850. stream.pos = 0;
  1851. FT_Open_Args fargs;
  1852. memset(&fargs, 0, sizeof(FT_Open_Args));
  1853. fargs.memory_base = (unsigned char *)fd->data_ptr;
  1854. fargs.memory_size = fd->data_size;
  1855. fargs.flags = FT_OPEN_MEMORY;
  1856. fargs.stream = &stream;
  1857. MutexLock ftlock(ft_mutex);
  1858. FT_Face tmp_face = nullptr;
  1859. error = FT_Open_Face(ft_library, &fargs, -1, &tmp_face);
  1860. if (error == 0) {
  1861. face_count = tmp_face->num_faces;
  1862. FT_Done_Face(tmp_face);
  1863. }
  1864. #endif
  1865. }
  1866. return face_count;
  1867. }
  1868. void TextServerAdvanced::_font_set_style(const RID &p_font_rid, BitField<FontStyle> p_style) {
  1869. FontAdvanced *fd = _get_font_data(p_font_rid);
  1870. ERR_FAIL_NULL(fd);
  1871. MutexLock lock(fd->mutex);
  1872. Vector2i size = _get_size(fd, 16);
  1873. FontForSizeAdvanced *ffsd = nullptr;
  1874. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  1875. fd->style_flags = p_style;
  1876. }
  1877. BitField<TextServer::FontStyle> TextServerAdvanced::_font_get_style(const RID &p_font_rid) const {
  1878. FontAdvanced *fd = _get_font_data(p_font_rid);
  1879. ERR_FAIL_NULL_V(fd, 0);
  1880. MutexLock lock(fd->mutex);
  1881. Vector2i size = _get_size(fd, 16);
  1882. FontForSizeAdvanced *ffsd = nullptr;
  1883. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), 0);
  1884. return fd->style_flags;
  1885. }
  1886. void TextServerAdvanced::_font_set_style_name(const RID &p_font_rid, const String &p_name) {
  1887. FontAdvanced *fd = _get_font_data(p_font_rid);
  1888. ERR_FAIL_NULL(fd);
  1889. MutexLock lock(fd->mutex);
  1890. Vector2i size = _get_size(fd, 16);
  1891. FontForSizeAdvanced *ffsd = nullptr;
  1892. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  1893. fd->style_name = p_name;
  1894. }
  1895. String TextServerAdvanced::_font_get_style_name(const RID &p_font_rid) const {
  1896. FontAdvanced *fd = _get_font_data(p_font_rid);
  1897. ERR_FAIL_NULL_V(fd, String());
  1898. MutexLock lock(fd->mutex);
  1899. Vector2i size = _get_size(fd, 16);
  1900. FontForSizeAdvanced *ffsd = nullptr;
  1901. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), String());
  1902. return fd->style_name;
  1903. }
  1904. void TextServerAdvanced::_font_set_weight(const RID &p_font_rid, int64_t p_weight) {
  1905. FontAdvanced *fd = _get_font_data(p_font_rid);
  1906. ERR_FAIL_NULL(fd);
  1907. MutexLock lock(fd->mutex);
  1908. Vector2i size = _get_size(fd, 16);
  1909. FontForSizeAdvanced *ffsd = nullptr;
  1910. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  1911. fd->weight = CLAMP(p_weight, 100, 999);
  1912. }
  1913. int64_t TextServerAdvanced::_font_get_weight(const RID &p_font_rid) const {
  1914. FontAdvanced *fd = _get_font_data(p_font_rid);
  1915. ERR_FAIL_NULL_V(fd, 400);
  1916. MutexLock lock(fd->mutex);
  1917. Vector2i size = _get_size(fd, 16);
  1918. FontForSizeAdvanced *ffsd = nullptr;
  1919. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), 400);
  1920. return fd->weight;
  1921. }
  1922. void TextServerAdvanced::_font_set_stretch(const RID &p_font_rid, int64_t p_stretch) {
  1923. FontAdvanced *fd = _get_font_data(p_font_rid);
  1924. ERR_FAIL_NULL(fd);
  1925. MutexLock lock(fd->mutex);
  1926. Vector2i size = _get_size(fd, 16);
  1927. FontForSizeAdvanced *ffsd = nullptr;
  1928. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  1929. fd->stretch = CLAMP(p_stretch, 50, 200);
  1930. }
  1931. int64_t TextServerAdvanced::_font_get_stretch(const RID &p_font_rid) const {
  1932. FontAdvanced *fd = _get_font_data(p_font_rid);
  1933. ERR_FAIL_NULL_V(fd, 100);
  1934. MutexLock lock(fd->mutex);
  1935. Vector2i size = _get_size(fd, 16);
  1936. FontForSizeAdvanced *ffsd = nullptr;
  1937. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), 100);
  1938. return fd->stretch;
  1939. }
  1940. void TextServerAdvanced::_font_set_name(const RID &p_font_rid, const String &p_name) {
  1941. FontAdvanced *fd = _get_font_data(p_font_rid);
  1942. ERR_FAIL_NULL(fd);
  1943. MutexLock lock(fd->mutex);
  1944. Vector2i size = _get_size(fd, 16);
  1945. FontForSizeAdvanced *ffsd = nullptr;
  1946. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  1947. fd->font_name = p_name;
  1948. }
  1949. String TextServerAdvanced::_font_get_name(const RID &p_font_rid) const {
  1950. FontAdvanced *fd = _get_font_data(p_font_rid);
  1951. ERR_FAIL_NULL_V(fd, String());
  1952. MutexLock lock(fd->mutex);
  1953. Vector2i size = _get_size(fd, 16);
  1954. FontForSizeAdvanced *ffsd = nullptr;
  1955. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), String());
  1956. return fd->font_name;
  1957. }
  1958. Dictionary TextServerAdvanced::_font_get_ot_name_strings(const RID &p_font_rid) const {
  1959. FontAdvanced *fd = _get_font_data(p_font_rid);
  1960. ERR_FAIL_NULL_V(fd, Dictionary());
  1961. MutexLock lock(fd->mutex);
  1962. Vector2i size = _get_size(fd, 16);
  1963. FontForSizeAdvanced *ffsd = nullptr;
  1964. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), Dictionary());
  1965. hb_face_t *hb_face = hb_font_get_face(ffsd->hb_handle);
  1966. unsigned int num_entries = 0;
  1967. const hb_ot_name_entry_t *names = hb_ot_name_list_names(hb_face, &num_entries);
  1968. HashMap<String, Dictionary> names_for_lang;
  1969. for (unsigned int i = 0; i < num_entries; i++) {
  1970. String name;
  1971. switch (names[i].name_id) {
  1972. case HB_OT_NAME_ID_COPYRIGHT: {
  1973. name = "copyright";
  1974. } break;
  1975. case HB_OT_NAME_ID_FONT_FAMILY: {
  1976. name = "family_name";
  1977. } break;
  1978. case HB_OT_NAME_ID_FONT_SUBFAMILY: {
  1979. name = "subfamily_name";
  1980. } break;
  1981. case HB_OT_NAME_ID_UNIQUE_ID: {
  1982. name = "unique_identifier";
  1983. } break;
  1984. case HB_OT_NAME_ID_FULL_NAME: {
  1985. name = "full_name";
  1986. } break;
  1987. case HB_OT_NAME_ID_VERSION_STRING: {
  1988. name = "version";
  1989. } break;
  1990. case HB_OT_NAME_ID_POSTSCRIPT_NAME: {
  1991. name = "postscript_name";
  1992. } break;
  1993. case HB_OT_NAME_ID_TRADEMARK: {
  1994. name = "trademark";
  1995. } break;
  1996. case HB_OT_NAME_ID_MANUFACTURER: {
  1997. name = "manufacturer";
  1998. } break;
  1999. case HB_OT_NAME_ID_DESIGNER: {
  2000. name = "designer";
  2001. } break;
  2002. case HB_OT_NAME_ID_DESCRIPTION: {
  2003. name = "description";
  2004. } break;
  2005. case HB_OT_NAME_ID_VENDOR_URL: {
  2006. name = "vendor_url";
  2007. } break;
  2008. case HB_OT_NAME_ID_DESIGNER_URL: {
  2009. name = "designer_url";
  2010. } break;
  2011. case HB_OT_NAME_ID_LICENSE: {
  2012. name = "license";
  2013. } break;
  2014. case HB_OT_NAME_ID_LICENSE_URL: {
  2015. name = "license_url";
  2016. } break;
  2017. case HB_OT_NAME_ID_TYPOGRAPHIC_FAMILY: {
  2018. name = "typographic_family_name";
  2019. } break;
  2020. case HB_OT_NAME_ID_TYPOGRAPHIC_SUBFAMILY: {
  2021. name = "typographic_subfamily_name";
  2022. } break;
  2023. case HB_OT_NAME_ID_MAC_FULL_NAME: {
  2024. name = "full_name_macos";
  2025. } break;
  2026. case HB_OT_NAME_ID_SAMPLE_TEXT: {
  2027. name = "sample_text";
  2028. } break;
  2029. case HB_OT_NAME_ID_CID_FINDFONT_NAME: {
  2030. name = "cid_findfont_name";
  2031. } break;
  2032. case HB_OT_NAME_ID_WWS_FAMILY: {
  2033. name = "weight_width_slope_family_name";
  2034. } break;
  2035. case HB_OT_NAME_ID_WWS_SUBFAMILY: {
  2036. name = "weight_width_slope_subfamily_name";
  2037. } break;
  2038. case HB_OT_NAME_ID_LIGHT_BACKGROUND: {
  2039. name = "light_background_palette";
  2040. } break;
  2041. case HB_OT_NAME_ID_DARK_BACKGROUND: {
  2042. name = "dark_background_palette";
  2043. } break;
  2044. case HB_OT_NAME_ID_VARIATIONS_PS_PREFIX: {
  2045. name = "postscript_name_prefix";
  2046. } break;
  2047. default: {
  2048. name = vformat("unknown_%d", names[i].name_id);
  2049. } break;
  2050. }
  2051. String text;
  2052. unsigned int text_size = hb_ot_name_get_utf32(hb_face, names[i].name_id, names[i].language, nullptr, nullptr) + 1;
  2053. text.resize_uninitialized(text_size);
  2054. hb_ot_name_get_utf32(hb_face, names[i].name_id, names[i].language, &text_size, (uint32_t *)text.ptrw());
  2055. if (!text.is_empty()) {
  2056. Dictionary &id_string = names_for_lang[String(hb_language_to_string(names[i].language))];
  2057. id_string[name] = text;
  2058. }
  2059. }
  2060. Dictionary out;
  2061. for (const KeyValue<String, Dictionary> &E : names_for_lang) {
  2062. out[E.key] = E.value;
  2063. }
  2064. return out;
  2065. }
  2066. void TextServerAdvanced::_font_set_antialiasing(const RID &p_font_rid, TextServer::FontAntialiasing p_antialiasing) {
  2067. FontAdvanced *fd = _get_font_data(p_font_rid);
  2068. ERR_FAIL_NULL(fd);
  2069. MutexLock lock(fd->mutex);
  2070. if (fd->antialiasing != p_antialiasing) {
  2071. _font_clear_cache(fd);
  2072. fd->antialiasing = p_antialiasing;
  2073. }
  2074. }
  2075. TextServer::FontAntialiasing TextServerAdvanced::_font_get_antialiasing(const RID &p_font_rid) const {
  2076. FontAdvanced *fd = _get_font_data(p_font_rid);
  2077. ERR_FAIL_NULL_V(fd, TextServer::FONT_ANTIALIASING_NONE);
  2078. MutexLock lock(fd->mutex);
  2079. return fd->antialiasing;
  2080. }
  2081. void TextServerAdvanced::_font_set_disable_embedded_bitmaps(const RID &p_font_rid, bool p_disable_embedded_bitmaps) {
  2082. FontAdvanced *fd = _get_font_data(p_font_rid);
  2083. ERR_FAIL_NULL(fd);
  2084. MutexLock lock(fd->mutex);
  2085. if (fd->disable_embedded_bitmaps != p_disable_embedded_bitmaps) {
  2086. _font_clear_cache(fd);
  2087. fd->disable_embedded_bitmaps = p_disable_embedded_bitmaps;
  2088. }
  2089. }
  2090. bool TextServerAdvanced::_font_get_disable_embedded_bitmaps(const RID &p_font_rid) const {
  2091. FontAdvanced *fd = _get_font_data(p_font_rid);
  2092. ERR_FAIL_NULL_V(fd, false);
  2093. MutexLock lock(fd->mutex);
  2094. return fd->disable_embedded_bitmaps;
  2095. }
  2096. void TextServerAdvanced::_font_set_generate_mipmaps(const RID &p_font_rid, bool p_generate_mipmaps) {
  2097. FontAdvanced *fd = _get_font_data(p_font_rid);
  2098. ERR_FAIL_NULL(fd);
  2099. MutexLock lock(fd->mutex);
  2100. if (fd->mipmaps != p_generate_mipmaps) {
  2101. for (KeyValue<Vector2i, FontForSizeAdvanced *> &E : fd->cache) {
  2102. for (int i = 0; i < E.value->textures.size(); i++) {
  2103. E.value->textures.write[i].dirty = true;
  2104. E.value->textures.write[i].texture = Ref<ImageTexture>();
  2105. }
  2106. }
  2107. fd->mipmaps = p_generate_mipmaps;
  2108. }
  2109. }
  2110. bool TextServerAdvanced::_font_get_generate_mipmaps(const RID &p_font_rid) const {
  2111. FontAdvanced *fd = _get_font_data(p_font_rid);
  2112. ERR_FAIL_NULL_V(fd, false);
  2113. MutexLock lock(fd->mutex);
  2114. return fd->mipmaps;
  2115. }
  2116. void TextServerAdvanced::_font_set_multichannel_signed_distance_field(const RID &p_font_rid, bool p_msdf) {
  2117. FontAdvanced *fd = _get_font_data(p_font_rid);
  2118. ERR_FAIL_NULL(fd);
  2119. MutexLock lock(fd->mutex);
  2120. if (fd->msdf != p_msdf) {
  2121. _font_clear_cache(fd);
  2122. fd->msdf = p_msdf;
  2123. }
  2124. }
  2125. bool TextServerAdvanced::_font_is_multichannel_signed_distance_field(const RID &p_font_rid) const {
  2126. FontAdvanced *fd = _get_font_data(p_font_rid);
  2127. ERR_FAIL_NULL_V(fd, false);
  2128. MutexLock lock(fd->mutex);
  2129. return fd->msdf;
  2130. }
  2131. void TextServerAdvanced::_font_set_msdf_pixel_range(const RID &p_font_rid, int64_t p_msdf_pixel_range) {
  2132. FontAdvanced *fd = _get_font_data(p_font_rid);
  2133. ERR_FAIL_NULL(fd);
  2134. MutexLock lock(fd->mutex);
  2135. if (fd->msdf_range != p_msdf_pixel_range) {
  2136. _font_clear_cache(fd);
  2137. fd->msdf_range = p_msdf_pixel_range;
  2138. }
  2139. }
  2140. int64_t TextServerAdvanced::_font_get_msdf_pixel_range(const RID &p_font_rid) const {
  2141. FontAdvanced *fd = _get_font_data(p_font_rid);
  2142. ERR_FAIL_NULL_V(fd, false);
  2143. MutexLock lock(fd->mutex);
  2144. return fd->msdf_range;
  2145. }
  2146. void TextServerAdvanced::_font_set_msdf_size(const RID &p_font_rid, int64_t p_msdf_size) {
  2147. FontAdvanced *fd = _get_font_data(p_font_rid);
  2148. ERR_FAIL_NULL(fd);
  2149. MutexLock lock(fd->mutex);
  2150. if (fd->msdf_source_size != p_msdf_size) {
  2151. _font_clear_cache(fd);
  2152. fd->msdf_source_size = p_msdf_size;
  2153. }
  2154. }
  2155. int64_t TextServerAdvanced::_font_get_msdf_size(const RID &p_font_rid) const {
  2156. FontAdvanced *fd = _get_font_data(p_font_rid);
  2157. ERR_FAIL_NULL_V(fd, 0);
  2158. MutexLock lock(fd->mutex);
  2159. return fd->msdf_source_size;
  2160. }
  2161. void TextServerAdvanced::_font_set_fixed_size(const RID &p_font_rid, int64_t p_fixed_size) {
  2162. FontAdvanced *fd = _get_font_data(p_font_rid);
  2163. ERR_FAIL_NULL(fd);
  2164. MutexLock lock(fd->mutex);
  2165. fd->fixed_size = p_fixed_size;
  2166. }
  2167. int64_t TextServerAdvanced::_font_get_fixed_size(const RID &p_font_rid) const {
  2168. FontAdvanced *fd = _get_font_data(p_font_rid);
  2169. ERR_FAIL_NULL_V(fd, 0);
  2170. MutexLock lock(fd->mutex);
  2171. return fd->fixed_size;
  2172. }
  2173. void TextServerAdvanced::_font_set_fixed_size_scale_mode(const RID &p_font_rid, TextServer::FixedSizeScaleMode p_fixed_size_scale_mode) {
  2174. FontAdvanced *fd = _get_font_data(p_font_rid);
  2175. ERR_FAIL_NULL(fd);
  2176. MutexLock lock(fd->mutex);
  2177. fd->fixed_size_scale_mode = p_fixed_size_scale_mode;
  2178. }
  2179. TextServer::FixedSizeScaleMode TextServerAdvanced::_font_get_fixed_size_scale_mode(const RID &p_font_rid) const {
  2180. FontAdvanced *fd = _get_font_data(p_font_rid);
  2181. ERR_FAIL_NULL_V(fd, FIXED_SIZE_SCALE_DISABLE);
  2182. MutexLock lock(fd->mutex);
  2183. return fd->fixed_size_scale_mode;
  2184. }
  2185. void TextServerAdvanced::_font_set_allow_system_fallback(const RID &p_font_rid, bool p_allow_system_fallback) {
  2186. FontAdvanced *fd = _get_font_data(p_font_rid);
  2187. ERR_FAIL_NULL(fd);
  2188. MutexLock lock(fd->mutex);
  2189. fd->allow_system_fallback = p_allow_system_fallback;
  2190. }
  2191. bool TextServerAdvanced::_font_is_allow_system_fallback(const RID &p_font_rid) const {
  2192. FontAdvanced *fd = _get_font_data(p_font_rid);
  2193. ERR_FAIL_NULL_V(fd, false);
  2194. MutexLock lock(fd->mutex);
  2195. return fd->allow_system_fallback;
  2196. }
  2197. void TextServerAdvanced::_font_set_force_autohinter(const RID &p_font_rid, bool p_force_autohinter) {
  2198. FontAdvanced *fd = _get_font_data(p_font_rid);
  2199. ERR_FAIL_NULL(fd);
  2200. MutexLock lock(fd->mutex);
  2201. if (fd->force_autohinter != p_force_autohinter) {
  2202. _font_clear_cache(fd);
  2203. fd->force_autohinter = p_force_autohinter;
  2204. }
  2205. }
  2206. bool TextServerAdvanced::_font_is_force_autohinter(const RID &p_font_rid) const {
  2207. FontAdvanced *fd = _get_font_data(p_font_rid);
  2208. ERR_FAIL_NULL_V(fd, false);
  2209. MutexLock lock(fd->mutex);
  2210. return fd->force_autohinter;
  2211. }
  2212. void TextServerAdvanced::_font_set_modulate_color_glyphs(const RID &p_font_rid, bool p_modulate) {
  2213. FontAdvanced *fd = _get_font_data(p_font_rid);
  2214. ERR_FAIL_NULL(fd);
  2215. MutexLock lock(fd->mutex);
  2216. if (fd->modulate_color_glyphs != p_modulate) {
  2217. fd->modulate_color_glyphs = p_modulate;
  2218. }
  2219. }
  2220. bool TextServerAdvanced::_font_is_modulate_color_glyphs(const RID &p_font_rid) const {
  2221. FontAdvanced *fd = _get_font_data(p_font_rid);
  2222. ERR_FAIL_NULL_V(fd, false);
  2223. MutexLock lock(fd->mutex);
  2224. return fd->modulate_color_glyphs;
  2225. }
  2226. void TextServerAdvanced::_font_set_hinting(const RID &p_font_rid, TextServer::Hinting p_hinting) {
  2227. FontAdvanced *fd = _get_font_data(p_font_rid);
  2228. ERR_FAIL_NULL(fd);
  2229. MutexLock lock(fd->mutex);
  2230. if (fd->hinting != p_hinting) {
  2231. _font_clear_cache(fd);
  2232. fd->hinting = p_hinting;
  2233. }
  2234. }
  2235. TextServer::Hinting TextServerAdvanced::_font_get_hinting(const RID &p_font_rid) const {
  2236. FontAdvanced *fd = _get_font_data(p_font_rid);
  2237. ERR_FAIL_NULL_V(fd, HINTING_NONE);
  2238. MutexLock lock(fd->mutex);
  2239. return fd->hinting;
  2240. }
  2241. void TextServerAdvanced::_font_set_subpixel_positioning(const RID &p_font_rid, TextServer::SubpixelPositioning p_subpixel) {
  2242. FontAdvanced *fd = _get_font_data(p_font_rid);
  2243. ERR_FAIL_NULL(fd);
  2244. MutexLock lock(fd->mutex);
  2245. fd->subpixel_positioning = p_subpixel;
  2246. }
  2247. TextServer::SubpixelPositioning TextServerAdvanced::_font_get_subpixel_positioning(const RID &p_font_rid) const {
  2248. FontAdvanced *fd = _get_font_data(p_font_rid);
  2249. ERR_FAIL_NULL_V(fd, SUBPIXEL_POSITIONING_DISABLED);
  2250. MutexLock lock(fd->mutex);
  2251. return fd->subpixel_positioning;
  2252. }
  2253. void TextServerAdvanced::_font_set_keep_rounding_remainders(const RID &p_font_rid, bool p_keep_rounding_remainders) {
  2254. FontAdvanced *fd = _get_font_data(p_font_rid);
  2255. ERR_FAIL_NULL(fd);
  2256. MutexLock lock(fd->mutex);
  2257. fd->keep_rounding_remainders = p_keep_rounding_remainders;
  2258. }
  2259. bool TextServerAdvanced::_font_get_keep_rounding_remainders(const RID &p_font_rid) const {
  2260. FontAdvanced *fd = _get_font_data(p_font_rid);
  2261. ERR_FAIL_NULL_V(fd, false);
  2262. MutexLock lock(fd->mutex);
  2263. return fd->keep_rounding_remainders;
  2264. }
  2265. void TextServerAdvanced::_font_set_embolden(const RID &p_font_rid, double p_strength) {
  2266. FontAdvanced *fd = _get_font_data(p_font_rid);
  2267. ERR_FAIL_NULL(fd);
  2268. MutexLock lock(fd->mutex);
  2269. if (fd->embolden != p_strength) {
  2270. _font_clear_cache(fd);
  2271. fd->embolden = p_strength;
  2272. }
  2273. }
  2274. double TextServerAdvanced::_font_get_embolden(const RID &p_font_rid) const {
  2275. FontAdvanced *fd = _get_font_data(p_font_rid);
  2276. ERR_FAIL_NULL_V(fd, 0.0);
  2277. MutexLock lock(fd->mutex);
  2278. return fd->embolden;
  2279. }
  2280. void TextServerAdvanced::_font_set_spacing(const RID &p_font_rid, SpacingType p_spacing, int64_t p_value) {
  2281. ERR_FAIL_INDEX((int)p_spacing, 4);
  2282. FontAdvancedLinkedVariation *fdv = font_var_owner.get_or_null(p_font_rid);
  2283. if (fdv) {
  2284. if (fdv->extra_spacing[p_spacing] != p_value) {
  2285. fdv->extra_spacing[p_spacing] = p_value;
  2286. }
  2287. } else {
  2288. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2289. ERR_FAIL_NULL(fd);
  2290. MutexLock lock(fd->mutex);
  2291. if (fd->extra_spacing[p_spacing] != p_value) {
  2292. fd->extra_spacing[p_spacing] = p_value;
  2293. }
  2294. }
  2295. }
  2296. int64_t TextServerAdvanced::_font_get_spacing(const RID &p_font_rid, SpacingType p_spacing) const {
  2297. ERR_FAIL_INDEX_V((int)p_spacing, 4, 0);
  2298. FontAdvancedLinkedVariation *fdv = font_var_owner.get_or_null(p_font_rid);
  2299. if (fdv) {
  2300. return fdv->extra_spacing[p_spacing];
  2301. } else {
  2302. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2303. ERR_FAIL_NULL_V(fd, 0);
  2304. MutexLock lock(fd->mutex);
  2305. return fd->extra_spacing[p_spacing];
  2306. }
  2307. }
  2308. void TextServerAdvanced::_font_set_baseline_offset(const RID &p_font_rid, double p_baseline_offset) {
  2309. FontAdvancedLinkedVariation *fdv = font_var_owner.get_or_null(p_font_rid);
  2310. if (fdv) {
  2311. if (fdv->baseline_offset != p_baseline_offset) {
  2312. fdv->baseline_offset = p_baseline_offset;
  2313. }
  2314. } else {
  2315. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2316. ERR_FAIL_NULL(fd);
  2317. MutexLock lock(fd->mutex);
  2318. if (fd->baseline_offset != p_baseline_offset) {
  2319. _font_clear_cache(fd);
  2320. fd->baseline_offset = p_baseline_offset;
  2321. }
  2322. }
  2323. }
  2324. double TextServerAdvanced::_font_get_baseline_offset(const RID &p_font_rid) const {
  2325. FontAdvancedLinkedVariation *fdv = font_var_owner.get_or_null(p_font_rid);
  2326. if (fdv) {
  2327. return fdv->baseline_offset;
  2328. } else {
  2329. FontAdvanced *fd = font_owner.get_or_null(p_font_rid);
  2330. ERR_FAIL_NULL_V(fd, 0.0);
  2331. MutexLock lock(fd->mutex);
  2332. return fd->baseline_offset;
  2333. }
  2334. }
  2335. void TextServerAdvanced::_font_set_transform(const RID &p_font_rid, const Transform2D &p_transform) {
  2336. FontAdvanced *fd = _get_font_data(p_font_rid);
  2337. ERR_FAIL_NULL(fd);
  2338. MutexLock lock(fd->mutex);
  2339. if (fd->transform != p_transform) {
  2340. _font_clear_cache(fd);
  2341. fd->transform = p_transform;
  2342. }
  2343. }
  2344. Transform2D TextServerAdvanced::_font_get_transform(const RID &p_font_rid) const {
  2345. FontAdvanced *fd = _get_font_data(p_font_rid);
  2346. ERR_FAIL_NULL_V(fd, Transform2D());
  2347. MutexLock lock(fd->mutex);
  2348. return fd->transform;
  2349. }
  2350. void TextServerAdvanced::_font_set_variation_coordinates(const RID &p_font_rid, const Dictionary &p_variation_coordinates) {
  2351. FontAdvanced *fd = _get_font_data(p_font_rid);
  2352. ERR_FAIL_NULL(fd);
  2353. MutexLock lock(fd->mutex);
  2354. if (!fd->variation_coordinates.recursive_equal(p_variation_coordinates, 1)) {
  2355. _font_clear_cache(fd);
  2356. fd->variation_coordinates = p_variation_coordinates.duplicate();
  2357. }
  2358. }
  2359. double TextServerAdvanced::_font_get_oversampling(const RID &p_font_rid) const {
  2360. FontAdvanced *fd = _get_font_data(p_font_rid);
  2361. ERR_FAIL_NULL_V(fd, -1.0);
  2362. MutexLock lock(fd->mutex);
  2363. return fd->oversampling_override;
  2364. }
  2365. void TextServerAdvanced::_font_set_oversampling(const RID &p_font_rid, double p_oversampling) {
  2366. FontAdvanced *fd = _get_font_data(p_font_rid);
  2367. ERR_FAIL_NULL(fd);
  2368. MutexLock lock(fd->mutex);
  2369. if (fd->oversampling_override != p_oversampling) {
  2370. _font_clear_cache(fd);
  2371. fd->oversampling_override = p_oversampling;
  2372. }
  2373. }
  2374. Dictionary TextServerAdvanced::_font_get_variation_coordinates(const RID &p_font_rid) const {
  2375. FontAdvanced *fd = _get_font_data(p_font_rid);
  2376. ERR_FAIL_NULL_V(fd, Dictionary());
  2377. MutexLock lock(fd->mutex);
  2378. return fd->variation_coordinates;
  2379. }
  2380. TypedArray<Vector2i> TextServerAdvanced::_font_get_size_cache_list(const RID &p_font_rid) const {
  2381. FontAdvanced *fd = _get_font_data(p_font_rid);
  2382. ERR_FAIL_NULL_V(fd, TypedArray<Vector2i>());
  2383. MutexLock lock(fd->mutex);
  2384. TypedArray<Vector2i> ret;
  2385. for (const KeyValue<Vector2i, FontForSizeAdvanced *> &E : fd->cache) {
  2386. if ((E.key.x % 64 == 0) && (E.value->viewport_oversampling == 0)) {
  2387. ret.push_back(Vector2i(E.key.x / 64, E.key.y));
  2388. }
  2389. }
  2390. return ret;
  2391. }
  2392. TypedArray<Dictionary> TextServerAdvanced::_font_get_size_cache_info(const RID &p_font_rid) const {
  2393. FontAdvanced *fd = _get_font_data(p_font_rid);
  2394. ERR_FAIL_NULL_V(fd, TypedArray<Dictionary>());
  2395. MutexLock lock(fd->mutex);
  2396. TypedArray<Dictionary> ret;
  2397. for (const KeyValue<Vector2i, FontForSizeAdvanced *> &E : fd->cache) {
  2398. Dictionary size_info;
  2399. size_info["size_px"] = Vector2i(E.key.x / 64, E.key.y);
  2400. if (E.value->viewport_oversampling) {
  2401. size_info["viewport_oversampling"] = double(E.value->viewport_oversampling) / 64.0;
  2402. }
  2403. size_info["glyphs"] = E.value->glyph_map.size();
  2404. size_info["textures"] = E.value->textures.size();
  2405. uint64_t sz = 0;
  2406. for (const ShelfPackTexture &tx : E.value->textures) {
  2407. sz += tx.image->get_data_size() * 2;
  2408. }
  2409. size_info["textures_size"] = sz;
  2410. ret.push_back(size_info);
  2411. }
  2412. return ret;
  2413. }
  2414. void TextServerAdvanced::_font_clear_size_cache(const RID &p_font_rid) {
  2415. FontAdvanced *fd = _get_font_data(p_font_rid);
  2416. ERR_FAIL_NULL(fd);
  2417. MutexLock lock(fd->mutex);
  2418. MutexLock ftlock(ft_mutex);
  2419. for (const KeyValue<Vector2i, FontForSizeAdvanced *> &E : fd->cache) {
  2420. if (E.value->viewport_oversampling != 0) {
  2421. OversamplingLevel *ol = oversampling_levels.getptr(E.value->viewport_oversampling);
  2422. if (ol) {
  2423. ol->fonts.erase(E.value);
  2424. }
  2425. }
  2426. memdelete(E.value);
  2427. }
  2428. fd->cache.clear();
  2429. }
  2430. void TextServerAdvanced::_font_remove_size_cache(const RID &p_font_rid, const Vector2i &p_size) {
  2431. FontAdvanced *fd = _get_font_data(p_font_rid);
  2432. ERR_FAIL_NULL(fd);
  2433. MutexLock lock(fd->mutex);
  2434. MutexLock ftlock(ft_mutex);
  2435. Vector2i size = Vector2i(p_size.x * 64, p_size.y);
  2436. if (fd->cache.has(size)) {
  2437. if (fd->cache[size]->viewport_oversampling != 0) {
  2438. OversamplingLevel *ol = oversampling_levels.getptr(fd->cache[size]->viewport_oversampling);
  2439. if (ol) {
  2440. ol->fonts.erase(fd->cache[size]);
  2441. }
  2442. }
  2443. memdelete(fd->cache[size]);
  2444. fd->cache.erase(size);
  2445. }
  2446. }
  2447. void TextServerAdvanced::_font_set_ascent(const RID &p_font_rid, int64_t p_size, double p_ascent) {
  2448. FontAdvanced *fd = _get_font_data(p_font_rid);
  2449. ERR_FAIL_NULL(fd);
  2450. MutexLock lock(fd->mutex);
  2451. Vector2i size = _get_size(fd, p_size);
  2452. FontForSizeAdvanced *ffsd = nullptr;
  2453. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2454. ffsd->ascent = p_ascent;
  2455. }
  2456. double TextServerAdvanced::_font_get_ascent(const RID &p_font_rid, int64_t p_size) const {
  2457. FontAdvanced *fd = _get_font_data(p_font_rid);
  2458. ERR_FAIL_NULL_V(fd, 0.0);
  2459. MutexLock lock(fd->mutex);
  2460. Vector2i size = _get_size(fd, p_size);
  2461. FontForSizeAdvanced *ffsd = nullptr;
  2462. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), 0.0);
  2463. if (fd->msdf) {
  2464. return ffsd->ascent * (double)p_size / (double)fd->msdf_source_size;
  2465. } else if (fd->fixed_size > 0 && fd->fixed_size_scale_mode != FIXED_SIZE_SCALE_DISABLE && size.x != p_size * 64) {
  2466. if (fd->fixed_size_scale_mode == FIXED_SIZE_SCALE_ENABLED) {
  2467. return ffsd->ascent * (double)p_size / (double)fd->fixed_size;
  2468. } else {
  2469. return ffsd->ascent * Math::round((double)p_size / (double)fd->fixed_size);
  2470. }
  2471. } else {
  2472. return ffsd->ascent;
  2473. }
  2474. }
  2475. void TextServerAdvanced::_font_set_descent(const RID &p_font_rid, int64_t p_size, double p_descent) {
  2476. FontAdvanced *fd = _get_font_data(p_font_rid);
  2477. ERR_FAIL_NULL(fd);
  2478. Vector2i size = _get_size(fd, p_size);
  2479. FontForSizeAdvanced *ffsd = nullptr;
  2480. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2481. ffsd->descent = p_descent;
  2482. }
  2483. double TextServerAdvanced::_font_get_descent(const RID &p_font_rid, int64_t p_size) const {
  2484. FontAdvanced *fd = _get_font_data(p_font_rid);
  2485. ERR_FAIL_NULL_V(fd, 0.0);
  2486. MutexLock lock(fd->mutex);
  2487. Vector2i size = _get_size(fd, p_size);
  2488. FontForSizeAdvanced *ffsd = nullptr;
  2489. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), 0.0);
  2490. if (fd->msdf) {
  2491. return ffsd->descent * (double)p_size / (double)fd->msdf_source_size;
  2492. } else if (fd->fixed_size > 0 && fd->fixed_size_scale_mode != FIXED_SIZE_SCALE_DISABLE && size.x != p_size * 64) {
  2493. if (fd->fixed_size_scale_mode == FIXED_SIZE_SCALE_ENABLED) {
  2494. return ffsd->descent * (double)p_size / (double)fd->fixed_size;
  2495. } else {
  2496. return ffsd->descent * Math::round((double)p_size / (double)fd->fixed_size);
  2497. }
  2498. } else {
  2499. return ffsd->descent;
  2500. }
  2501. }
  2502. void TextServerAdvanced::_font_set_underline_position(const RID &p_font_rid, int64_t p_size, double p_underline_position) {
  2503. FontAdvanced *fd = _get_font_data(p_font_rid);
  2504. ERR_FAIL_NULL(fd);
  2505. MutexLock lock(fd->mutex);
  2506. Vector2i size = _get_size(fd, p_size);
  2507. FontForSizeAdvanced *ffsd = nullptr;
  2508. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2509. ffsd->underline_position = p_underline_position;
  2510. }
  2511. double TextServerAdvanced::_font_get_underline_position(const RID &p_font_rid, int64_t p_size) const {
  2512. FontAdvanced *fd = _get_font_data(p_font_rid);
  2513. ERR_FAIL_NULL_V(fd, 0.0);
  2514. MutexLock lock(fd->mutex);
  2515. Vector2i size = _get_size(fd, p_size);
  2516. FontForSizeAdvanced *ffsd = nullptr;
  2517. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), 0.0);
  2518. if (fd->msdf) {
  2519. return ffsd->underline_position * (double)p_size / (double)fd->msdf_source_size;
  2520. } else if (fd->fixed_size > 0 && fd->fixed_size_scale_mode != FIXED_SIZE_SCALE_DISABLE && size.x != p_size * 64) {
  2521. if (fd->fixed_size_scale_mode == FIXED_SIZE_SCALE_ENABLED) {
  2522. return ffsd->underline_position * (double)p_size / (double)fd->fixed_size;
  2523. } else {
  2524. return ffsd->underline_position * Math::round((double)p_size / (double)fd->fixed_size);
  2525. }
  2526. } else {
  2527. return ffsd->underline_position;
  2528. }
  2529. }
  2530. void TextServerAdvanced::_font_set_underline_thickness(const RID &p_font_rid, int64_t p_size, double p_underline_thickness) {
  2531. FontAdvanced *fd = _get_font_data(p_font_rid);
  2532. ERR_FAIL_NULL(fd);
  2533. MutexLock lock(fd->mutex);
  2534. Vector2i size = _get_size(fd, p_size);
  2535. FontForSizeAdvanced *ffsd = nullptr;
  2536. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2537. ffsd->underline_thickness = p_underline_thickness;
  2538. }
  2539. double TextServerAdvanced::_font_get_underline_thickness(const RID &p_font_rid, int64_t p_size) const {
  2540. FontAdvanced *fd = _get_font_data(p_font_rid);
  2541. ERR_FAIL_NULL_V(fd, 0.0);
  2542. MutexLock lock(fd->mutex);
  2543. Vector2i size = _get_size(fd, p_size);
  2544. FontForSizeAdvanced *ffsd = nullptr;
  2545. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), 0.0);
  2546. if (fd->msdf) {
  2547. return ffsd->underline_thickness * (double)p_size / (double)fd->msdf_source_size;
  2548. } else if (fd->fixed_size > 0 && fd->fixed_size_scale_mode != FIXED_SIZE_SCALE_DISABLE && size.x != p_size * 64) {
  2549. if (fd->fixed_size_scale_mode == FIXED_SIZE_SCALE_ENABLED) {
  2550. return ffsd->underline_thickness * (double)p_size / (double)fd->fixed_size;
  2551. } else {
  2552. return ffsd->underline_thickness * Math::round((double)p_size / (double)fd->fixed_size);
  2553. }
  2554. } else {
  2555. return ffsd->underline_thickness;
  2556. }
  2557. }
  2558. void TextServerAdvanced::_font_set_scale(const RID &p_font_rid, int64_t p_size, double p_scale) {
  2559. FontAdvanced *fd = _get_font_data(p_font_rid);
  2560. ERR_FAIL_NULL(fd);
  2561. MutexLock lock(fd->mutex);
  2562. Vector2i size = _get_size(fd, p_size);
  2563. FontForSizeAdvanced *ffsd = nullptr;
  2564. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2565. #ifdef MODULE_FREETYPE_ENABLED
  2566. if (ffsd->face) {
  2567. return; // Do not override scale for dynamic fonts, it's calculated automatically.
  2568. }
  2569. #endif
  2570. ffsd->scale = p_scale;
  2571. }
  2572. double TextServerAdvanced::_font_get_scale(const RID &p_font_rid, int64_t p_size) const {
  2573. FontAdvanced *fd = _get_font_data(p_font_rid);
  2574. ERR_FAIL_NULL_V(fd, 0.0);
  2575. MutexLock lock(fd->mutex);
  2576. Vector2i size = _get_size(fd, p_size);
  2577. FontForSizeAdvanced *ffsd = nullptr;
  2578. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), 0.0);
  2579. if (fd->msdf) {
  2580. return ffsd->scale * (double)p_size / (double)fd->msdf_source_size;
  2581. } else if (fd->fixed_size > 0 && fd->fixed_size_scale_mode != FIXED_SIZE_SCALE_DISABLE && size.x != p_size * 64) {
  2582. if (fd->fixed_size_scale_mode == FIXED_SIZE_SCALE_ENABLED) {
  2583. return ffsd->scale * (double)p_size / (double)fd->fixed_size;
  2584. } else {
  2585. return ffsd->scale * Math::round((double)p_size / (double)fd->fixed_size);
  2586. }
  2587. } else {
  2588. return ffsd->scale;
  2589. }
  2590. }
  2591. int64_t TextServerAdvanced::_font_get_texture_count(const RID &p_font_rid, const Vector2i &p_size) const {
  2592. FontAdvanced *fd = _get_font_data(p_font_rid);
  2593. ERR_FAIL_NULL_V(fd, 0);
  2594. MutexLock lock(fd->mutex);
  2595. Vector2i size = _get_size_outline(fd, p_size);
  2596. FontForSizeAdvanced *ffsd = nullptr;
  2597. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), 0);
  2598. return ffsd->textures.size();
  2599. }
  2600. void TextServerAdvanced::_font_clear_textures(const RID &p_font_rid, const Vector2i &p_size) {
  2601. FontAdvanced *fd = _get_font_data(p_font_rid);
  2602. ERR_FAIL_NULL(fd);
  2603. MutexLock lock(fd->mutex);
  2604. Vector2i size = _get_size_outline(fd, p_size);
  2605. FontForSizeAdvanced *ffsd = nullptr;
  2606. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2607. ffsd->textures.clear();
  2608. }
  2609. void TextServerAdvanced::_font_remove_texture(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) {
  2610. FontAdvanced *fd = _get_font_data(p_font_rid);
  2611. ERR_FAIL_NULL(fd);
  2612. MutexLock lock(fd->mutex);
  2613. Vector2i size = _get_size_outline(fd, p_size);
  2614. FontForSizeAdvanced *ffsd = nullptr;
  2615. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2616. ERR_FAIL_INDEX(p_texture_index, ffsd->textures.size());
  2617. ffsd->textures.remove_at(p_texture_index);
  2618. }
  2619. void TextServerAdvanced::_font_set_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const Ref<Image> &p_image) {
  2620. FontAdvanced *fd = _get_font_data(p_font_rid);
  2621. ERR_FAIL_NULL(fd);
  2622. ERR_FAIL_COND(p_image.is_null());
  2623. MutexLock lock(fd->mutex);
  2624. Vector2i size = _get_size_outline(fd, p_size);
  2625. FontForSizeAdvanced *ffsd = nullptr;
  2626. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2627. ERR_FAIL_COND(p_texture_index < 0);
  2628. if (p_texture_index >= ffsd->textures.size()) {
  2629. ffsd->textures.resize(p_texture_index + 1);
  2630. }
  2631. ShelfPackTexture &tex = ffsd->textures.write[p_texture_index];
  2632. tex.image = p_image;
  2633. tex.texture_w = p_image->get_width();
  2634. tex.texture_h = p_image->get_height();
  2635. Ref<Image> img = p_image;
  2636. if (fd->mipmaps && !img->has_mipmaps()) {
  2637. img = p_image->duplicate();
  2638. img->generate_mipmaps();
  2639. }
  2640. tex.texture = ImageTexture::create_from_image(img);
  2641. tex.dirty = false;
  2642. }
  2643. Ref<Image> TextServerAdvanced::_font_get_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const {
  2644. FontAdvanced *fd = _get_font_data(p_font_rid);
  2645. ERR_FAIL_NULL_V(fd, Ref<Image>());
  2646. MutexLock lock(fd->mutex);
  2647. Vector2i size = _get_size_outline(fd, p_size);
  2648. FontForSizeAdvanced *ffsd = nullptr;
  2649. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), Ref<Image>());
  2650. ERR_FAIL_INDEX_V(p_texture_index, ffsd->textures.size(), Ref<Image>());
  2651. const ShelfPackTexture &tex = ffsd->textures[p_texture_index];
  2652. return tex.image;
  2653. }
  2654. void TextServerAdvanced::_font_set_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index, const PackedInt32Array &p_offsets) {
  2655. ERR_FAIL_COND(p_offsets.size() % 4 != 0);
  2656. FontAdvanced *fd = _get_font_data(p_font_rid);
  2657. ERR_FAIL_NULL(fd);
  2658. MutexLock lock(fd->mutex);
  2659. Vector2i size = _get_size_outline(fd, p_size);
  2660. FontForSizeAdvanced *ffsd = nullptr;
  2661. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2662. ERR_FAIL_COND(p_texture_index < 0);
  2663. if (p_texture_index >= ffsd->textures.size()) {
  2664. ffsd->textures.resize(p_texture_index + 1);
  2665. }
  2666. ShelfPackTexture &tex = ffsd->textures.write[p_texture_index];
  2667. tex.shelves.clear();
  2668. for (int32_t i = 0; i < p_offsets.size(); i += 4) {
  2669. tex.shelves.push_back(Shelf(p_offsets[i], p_offsets[i + 1], p_offsets[i + 2], p_offsets[i + 3]));
  2670. }
  2671. }
  2672. PackedInt32Array TextServerAdvanced::_font_get_texture_offsets(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const {
  2673. FontAdvanced *fd = _get_font_data(p_font_rid);
  2674. ERR_FAIL_NULL_V(fd, PackedInt32Array());
  2675. MutexLock lock(fd->mutex);
  2676. Vector2i size = _get_size_outline(fd, p_size);
  2677. FontForSizeAdvanced *ffsd = nullptr;
  2678. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), PackedInt32Array());
  2679. ERR_FAIL_INDEX_V(p_texture_index, ffsd->textures.size(), PackedInt32Array());
  2680. const ShelfPackTexture &tex = ffsd->textures[p_texture_index];
  2681. PackedInt32Array ret;
  2682. ret.resize(tex.shelves.size() * 4);
  2683. int32_t *wr = ret.ptrw();
  2684. int32_t i = 0;
  2685. for (const Shelf &E : tex.shelves) {
  2686. wr[i * 4] = E.x;
  2687. wr[i * 4 + 1] = E.y;
  2688. wr[i * 4 + 2] = E.w;
  2689. wr[i * 4 + 3] = E.h;
  2690. i++;
  2691. }
  2692. return ret;
  2693. }
  2694. PackedInt32Array TextServerAdvanced::_font_get_glyph_list(const RID &p_font_rid, const Vector2i &p_size) const {
  2695. FontAdvanced *fd = _get_font_data(p_font_rid);
  2696. ERR_FAIL_NULL_V(fd, PackedInt32Array());
  2697. MutexLock lock(fd->mutex);
  2698. Vector2i size = _get_size_outline(fd, p_size);
  2699. FontForSizeAdvanced *ffsd = nullptr;
  2700. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), PackedInt32Array());
  2701. PackedInt32Array ret;
  2702. const HashMap<int32_t, FontGlyph> &gl = ffsd->glyph_map;
  2703. for (const KeyValue<int32_t, FontGlyph> &E : gl) {
  2704. ret.push_back(E.key);
  2705. }
  2706. return ret;
  2707. }
  2708. void TextServerAdvanced::_font_clear_glyphs(const RID &p_font_rid, const Vector2i &p_size) {
  2709. FontAdvanced *fd = _get_font_data(p_font_rid);
  2710. ERR_FAIL_NULL(fd);
  2711. MutexLock lock(fd->mutex);
  2712. Vector2i size = _get_size_outline(fd, p_size);
  2713. FontForSizeAdvanced *ffsd = nullptr;
  2714. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2715. ffsd->glyph_map.clear();
  2716. }
  2717. void TextServerAdvanced::_font_remove_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) {
  2718. FontAdvanced *fd = _get_font_data(p_font_rid);
  2719. ERR_FAIL_NULL(fd);
  2720. MutexLock lock(fd->mutex);
  2721. Vector2i size = _get_size_outline(fd, p_size);
  2722. FontForSizeAdvanced *ffsd = nullptr;
  2723. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2724. ffsd->glyph_map.erase(p_glyph);
  2725. }
  2726. double TextServerAdvanced::_get_extra_advance(RID p_font_rid, int p_font_size) const {
  2727. const FontAdvanced *fd = _get_font_data(p_font_rid);
  2728. ERR_FAIL_NULL_V(fd, 0.0);
  2729. MutexLock lock(fd->mutex);
  2730. Vector2i size = _get_size(fd, p_font_size);
  2731. if (fd->embolden != 0.0) {
  2732. return fd->embolden * double(size.x) / 4096.0;
  2733. } else {
  2734. return 0.0;
  2735. }
  2736. }
  2737. Vector2 TextServerAdvanced::_font_get_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph) const {
  2738. FontAdvanced *fd = _get_font_data(p_font_rid);
  2739. ERR_FAIL_NULL_V(fd, Vector2());
  2740. MutexLock lock(fd->mutex);
  2741. Vector2i size = _get_size(fd, p_size);
  2742. FontForSizeAdvanced *ffsd = nullptr;
  2743. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), Vector2());
  2744. int mod = 0;
  2745. if (fd->antialiasing == FONT_ANTIALIASING_LCD) {
  2746. TextServer::FontLCDSubpixelLayout layout = lcd_subpixel_layout.get();
  2747. if (layout != FONT_LCD_SUBPIXEL_LAYOUT_NONE) {
  2748. mod = (layout << 24);
  2749. }
  2750. }
  2751. FontGlyph fgl;
  2752. if (!_ensure_glyph(fd, size, p_glyph | mod, fgl)) {
  2753. return Vector2(); // Invalid or non graphicl glyph, do not display errors.
  2754. }
  2755. Vector2 ea;
  2756. if (fd->embolden != 0.0) {
  2757. ea.x = fd->embolden * double(size.x) / 4096.0;
  2758. }
  2759. double scale = _font_get_scale(p_font_rid, p_size);
  2760. if (fd->msdf) {
  2761. return (fgl.advance + ea) * (double)p_size / (double)fd->msdf_source_size;
  2762. } else if (fd->fixed_size > 0 && fd->fixed_size_scale_mode != FIXED_SIZE_SCALE_DISABLE && size.x != p_size * 64) {
  2763. if (fd->fixed_size_scale_mode == FIXED_SIZE_SCALE_ENABLED) {
  2764. return (fgl.advance + ea) * (double)p_size / (double)fd->fixed_size;
  2765. } else {
  2766. return (fgl.advance + ea) * Math::round((double)p_size / (double)fd->fixed_size);
  2767. }
  2768. } else if ((scale == 1.0) && ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_DISABLED) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x > SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE * 64))) {
  2769. return (fgl.advance + ea).round();
  2770. } else {
  2771. return fgl.advance + ea;
  2772. }
  2773. }
  2774. void TextServerAdvanced::_font_set_glyph_advance(const RID &p_font_rid, int64_t p_size, int64_t p_glyph, const Vector2 &p_advance) {
  2775. FontAdvanced *fd = _get_font_data(p_font_rid);
  2776. ERR_FAIL_NULL(fd);
  2777. MutexLock lock(fd->mutex);
  2778. Vector2i size = _get_size(fd, p_size);
  2779. FontForSizeAdvanced *ffsd = nullptr;
  2780. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2781. FontGlyph &fgl = ffsd->glyph_map[p_glyph];
  2782. fgl.advance = p_advance;
  2783. fgl.found = true;
  2784. }
  2785. Vector2 TextServerAdvanced::_font_get_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const {
  2786. FontAdvanced *fd = _get_font_data(p_font_rid);
  2787. ERR_FAIL_NULL_V(fd, Vector2());
  2788. MutexLock lock(fd->mutex);
  2789. Vector2i size = _get_size_outline(fd, p_size);
  2790. FontForSizeAdvanced *ffsd = nullptr;
  2791. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), Vector2());
  2792. int mod = 0;
  2793. if (fd->antialiasing == FONT_ANTIALIASING_LCD) {
  2794. TextServer::FontLCDSubpixelLayout layout = lcd_subpixel_layout.get();
  2795. if (layout != FONT_LCD_SUBPIXEL_LAYOUT_NONE) {
  2796. mod = (layout << 24);
  2797. }
  2798. }
  2799. FontGlyph fgl;
  2800. if (!_ensure_glyph(fd, size, p_glyph | mod, fgl)) {
  2801. return Vector2(); // Invalid or non graphicl glyph, do not display errors.
  2802. }
  2803. if (fd->msdf) {
  2804. return fgl.rect.position * (double)p_size.x / (double)fd->msdf_source_size;
  2805. } else if (fd->fixed_size > 0 && fd->fixed_size_scale_mode != FIXED_SIZE_SCALE_DISABLE && size.x != p_size.x * 64) {
  2806. if (fd->fixed_size_scale_mode == FIXED_SIZE_SCALE_ENABLED) {
  2807. return fgl.rect.position * (double)p_size.x / (double)fd->fixed_size;
  2808. } else {
  2809. return fgl.rect.position * Math::round((double)p_size.x / (double)fd->fixed_size);
  2810. }
  2811. } else {
  2812. return fgl.rect.position;
  2813. }
  2814. }
  2815. void TextServerAdvanced::_font_set_glyph_offset(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_offset) {
  2816. FontAdvanced *fd = _get_font_data(p_font_rid);
  2817. ERR_FAIL_NULL(fd);
  2818. MutexLock lock(fd->mutex);
  2819. Vector2i size = _get_size_outline(fd, p_size);
  2820. FontForSizeAdvanced *ffsd = nullptr;
  2821. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2822. FontGlyph &fgl = ffsd->glyph_map[p_glyph];
  2823. fgl.rect.position = p_offset;
  2824. fgl.found = true;
  2825. }
  2826. Vector2 TextServerAdvanced::_font_get_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const {
  2827. FontAdvanced *fd = _get_font_data(p_font_rid);
  2828. ERR_FAIL_NULL_V(fd, Vector2());
  2829. MutexLock lock(fd->mutex);
  2830. Vector2i size = _get_size_outline(fd, p_size);
  2831. FontForSizeAdvanced *ffsd = nullptr;
  2832. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), Vector2());
  2833. int mod = 0;
  2834. if (fd->antialiasing == FONT_ANTIALIASING_LCD) {
  2835. TextServer::FontLCDSubpixelLayout layout = lcd_subpixel_layout.get();
  2836. if (layout != FONT_LCD_SUBPIXEL_LAYOUT_NONE) {
  2837. mod = (layout << 24);
  2838. }
  2839. }
  2840. FontGlyph fgl;
  2841. if (!_ensure_glyph(fd, size, p_glyph | mod, fgl)) {
  2842. return Vector2(); // Invalid or non graphicl glyph, do not display errors.
  2843. }
  2844. if (fd->msdf) {
  2845. return fgl.rect.size * (double)p_size.x / (double)fd->msdf_source_size;
  2846. } else if (fd->fixed_size > 0 && fd->fixed_size_scale_mode != FIXED_SIZE_SCALE_DISABLE && size.x != p_size.x * 64) {
  2847. if (fd->fixed_size_scale_mode == FIXED_SIZE_SCALE_ENABLED) {
  2848. return fgl.rect.size * (double)p_size.x / (double)fd->fixed_size;
  2849. } else {
  2850. return fgl.rect.size * Math::round((double)p_size.x / (double)fd->fixed_size);
  2851. }
  2852. } else {
  2853. return fgl.rect.size;
  2854. }
  2855. }
  2856. void TextServerAdvanced::_font_set_glyph_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Vector2 &p_gl_size) {
  2857. FontAdvanced *fd = _get_font_data(p_font_rid);
  2858. ERR_FAIL_NULL(fd);
  2859. MutexLock lock(fd->mutex);
  2860. Vector2i size = _get_size_outline(fd, p_size);
  2861. FontForSizeAdvanced *ffsd = nullptr;
  2862. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2863. FontGlyph &fgl = ffsd->glyph_map[p_glyph];
  2864. fgl.rect.size = p_gl_size;
  2865. fgl.found = true;
  2866. }
  2867. Rect2 TextServerAdvanced::_font_get_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const {
  2868. FontAdvanced *fd = _get_font_data(p_font_rid);
  2869. ERR_FAIL_NULL_V(fd, Rect2());
  2870. MutexLock lock(fd->mutex);
  2871. Vector2i size = _get_size_outline(fd, p_size);
  2872. FontForSizeAdvanced *ffsd = nullptr;
  2873. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), Rect2());
  2874. int mod = 0;
  2875. if (fd->antialiasing == FONT_ANTIALIASING_LCD) {
  2876. TextServer::FontLCDSubpixelLayout layout = lcd_subpixel_layout.get();
  2877. if (layout != FONT_LCD_SUBPIXEL_LAYOUT_NONE) {
  2878. mod = (layout << 24);
  2879. }
  2880. }
  2881. FontGlyph fgl;
  2882. if (!_ensure_glyph(fd, size, p_glyph | mod, fgl)) {
  2883. return Rect2(); // Invalid or non graphicl glyph, do not display errors.
  2884. }
  2885. return fgl.uv_rect;
  2886. }
  2887. void TextServerAdvanced::_font_set_glyph_uv_rect(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, const Rect2 &p_uv_rect) {
  2888. FontAdvanced *fd = _get_font_data(p_font_rid);
  2889. ERR_FAIL_NULL(fd);
  2890. MutexLock lock(fd->mutex);
  2891. Vector2i size = _get_size_outline(fd, p_size);
  2892. FontForSizeAdvanced *ffsd = nullptr;
  2893. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2894. FontGlyph &fgl = ffsd->glyph_map[p_glyph];
  2895. fgl.uv_rect = p_uv_rect;
  2896. fgl.found = true;
  2897. }
  2898. int64_t TextServerAdvanced::_font_get_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const {
  2899. FontAdvanced *fd = _get_font_data(p_font_rid);
  2900. ERR_FAIL_NULL_V(fd, -1);
  2901. MutexLock lock(fd->mutex);
  2902. Vector2i size = _get_size_outline(fd, p_size);
  2903. FontForSizeAdvanced *ffsd = nullptr;
  2904. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), -1);
  2905. int mod = 0;
  2906. if (fd->antialiasing == FONT_ANTIALIASING_LCD) {
  2907. TextServer::FontLCDSubpixelLayout layout = lcd_subpixel_layout.get();
  2908. if (layout != FONT_LCD_SUBPIXEL_LAYOUT_NONE) {
  2909. mod = (layout << 24);
  2910. }
  2911. }
  2912. FontGlyph fgl;
  2913. if (!_ensure_glyph(fd, size, p_glyph | mod, fgl)) {
  2914. return -1; // Invalid or non graphicl glyph, do not display errors.
  2915. }
  2916. return fgl.texture_idx;
  2917. }
  2918. void TextServerAdvanced::_font_set_glyph_texture_idx(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph, int64_t p_texture_idx) {
  2919. FontAdvanced *fd = _get_font_data(p_font_rid);
  2920. ERR_FAIL_NULL(fd);
  2921. MutexLock lock(fd->mutex);
  2922. Vector2i size = _get_size_outline(fd, p_size);
  2923. FontForSizeAdvanced *ffsd = nullptr;
  2924. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  2925. FontGlyph &fgl = ffsd->glyph_map[p_glyph];
  2926. fgl.texture_idx = p_texture_idx;
  2927. fgl.found = true;
  2928. }
  2929. RID TextServerAdvanced::_font_get_glyph_texture_rid(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const {
  2930. FontAdvanced *fd = _get_font_data(p_font_rid);
  2931. ERR_FAIL_NULL_V(fd, RID());
  2932. MutexLock lock(fd->mutex);
  2933. Vector2i size = _get_size_outline(fd, p_size);
  2934. FontForSizeAdvanced *ffsd = nullptr;
  2935. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), RID());
  2936. int mod = 0;
  2937. if (fd->antialiasing == FONT_ANTIALIASING_LCD) {
  2938. TextServer::FontLCDSubpixelLayout layout = lcd_subpixel_layout.get();
  2939. if (layout != FONT_LCD_SUBPIXEL_LAYOUT_NONE) {
  2940. mod = (layout << 24);
  2941. }
  2942. }
  2943. FontGlyph fgl;
  2944. if (!_ensure_glyph(fd, size, p_glyph | mod, fgl)) {
  2945. return RID(); // Invalid or non graphicl glyph, do not display errors.
  2946. }
  2947. ERR_FAIL_COND_V(fgl.texture_idx < -1 || fgl.texture_idx >= ffsd->textures.size(), RID());
  2948. if (RenderingServer::get_singleton() != nullptr) {
  2949. if (fgl.texture_idx != -1) {
  2950. if (ffsd->textures[fgl.texture_idx].dirty) {
  2951. ShelfPackTexture &tex = ffsd->textures.write[fgl.texture_idx];
  2952. Ref<Image> img = tex.image;
  2953. if (fgl.from_svg) {
  2954. // Same as the "fix alpha border" process option when importing SVGs
  2955. img->fix_alpha_edges();
  2956. }
  2957. if (fd->mipmaps && !img->has_mipmaps()) {
  2958. img = tex.image->duplicate();
  2959. img->generate_mipmaps();
  2960. }
  2961. if (tex.texture.is_null()) {
  2962. tex.texture = ImageTexture::create_from_image(img);
  2963. } else {
  2964. tex.texture->update(img);
  2965. }
  2966. tex.dirty = false;
  2967. }
  2968. return ffsd->textures[fgl.texture_idx].texture->get_rid();
  2969. }
  2970. }
  2971. return RID();
  2972. }
  2973. Size2 TextServerAdvanced::_font_get_glyph_texture_size(const RID &p_font_rid, const Vector2i &p_size, int64_t p_glyph) const {
  2974. FontAdvanced *fd = _get_font_data(p_font_rid);
  2975. ERR_FAIL_NULL_V(fd, Size2());
  2976. MutexLock lock(fd->mutex);
  2977. Vector2i size = _get_size_outline(fd, p_size);
  2978. FontForSizeAdvanced *ffsd = nullptr;
  2979. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), Size2());
  2980. int mod = 0;
  2981. if (fd->antialiasing == FONT_ANTIALIASING_LCD) {
  2982. TextServer::FontLCDSubpixelLayout layout = lcd_subpixel_layout.get();
  2983. if (layout != FONT_LCD_SUBPIXEL_LAYOUT_NONE) {
  2984. mod = (layout << 24);
  2985. }
  2986. }
  2987. FontGlyph fgl;
  2988. if (!_ensure_glyph(fd, size, p_glyph | mod, fgl)) {
  2989. return Size2(); // Invalid or non graphicl glyph, do not display errors.
  2990. }
  2991. ERR_FAIL_COND_V(fgl.texture_idx < -1 || fgl.texture_idx >= ffsd->textures.size(), Size2());
  2992. if (RenderingServer::get_singleton() != nullptr) {
  2993. if (fgl.texture_idx != -1) {
  2994. if (ffsd->textures[fgl.texture_idx].dirty) {
  2995. ShelfPackTexture &tex = ffsd->textures.write[fgl.texture_idx];
  2996. Ref<Image> img = tex.image;
  2997. if (fgl.from_svg) {
  2998. // Same as the "fix alpha border" process option when importing SVGs
  2999. img->fix_alpha_edges();
  3000. }
  3001. if (fd->mipmaps && !img->has_mipmaps()) {
  3002. img = tex.image->duplicate();
  3003. img->generate_mipmaps();
  3004. }
  3005. if (tex.texture.is_null()) {
  3006. tex.texture = ImageTexture::create_from_image(img);
  3007. } else {
  3008. tex.texture->update(img);
  3009. }
  3010. tex.dirty = false;
  3011. }
  3012. return ffsd->textures[fgl.texture_idx].texture->get_size();
  3013. }
  3014. }
  3015. return Size2();
  3016. }
  3017. Dictionary TextServerAdvanced::_font_get_glyph_contours(const RID &p_font_rid, int64_t p_size, int64_t p_index) const {
  3018. FontAdvanced *fd = _get_font_data(p_font_rid);
  3019. ERR_FAIL_NULL_V(fd, Dictionary());
  3020. MutexLock lock(fd->mutex);
  3021. Vector2i size = _get_size(fd, p_size);
  3022. FontForSizeAdvanced *ffsd = nullptr;
  3023. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), Dictionary());
  3024. #ifdef MODULE_FREETYPE_ENABLED
  3025. PackedVector3Array points;
  3026. PackedInt32Array contours;
  3027. int32_t index = p_index & 0xffffff; // Remove subpixel shifts.
  3028. int error = FT_Load_Glyph(ffsd->face, index, FT_LOAD_NO_BITMAP | (fd->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0));
  3029. ERR_FAIL_COND_V(error, Dictionary());
  3030. if (fd->embolden != 0.f) {
  3031. FT_Pos strength = fd->embolden * size.x / 16; // 26.6 fractional units (1 / 64).
  3032. FT_Outline_Embolden(&ffsd->face->glyph->outline, strength);
  3033. }
  3034. if (fd->transform != Transform2D()) {
  3035. FT_Matrix mat = { FT_Fixed(fd->transform[0][0] * 65536), FT_Fixed(fd->transform[0][1] * 65536), FT_Fixed(fd->transform[1][0] * 65536), FT_Fixed(fd->transform[1][1] * 65536) }; // 16.16 fractional units (1 / 65536).
  3036. FT_Outline_Transform(&ffsd->face->glyph->outline, &mat);
  3037. }
  3038. double scale = (1.0 / 64.0) * ffsd->scale;
  3039. if (fd->msdf) {
  3040. scale = scale * (double)p_size / (double)fd->msdf_source_size;
  3041. } else if (fd->fixed_size > 0 && fd->fixed_size_scale_mode != FIXED_SIZE_SCALE_DISABLE && size.x != p_size * 64) {
  3042. if (fd->fixed_size_scale_mode == FIXED_SIZE_SCALE_ENABLED) {
  3043. scale = scale * (double)p_size / (double)fd->fixed_size;
  3044. } else {
  3045. scale = scale * Math::round((double)p_size / (double)fd->fixed_size);
  3046. }
  3047. }
  3048. for (short i = 0; i < ffsd->face->glyph->outline.n_points; i++) {
  3049. points.push_back(Vector3(ffsd->face->glyph->outline.points[i].x * scale, -ffsd->face->glyph->outline.points[i].y * scale, FT_CURVE_TAG(ffsd->face->glyph->outline.tags[i])));
  3050. }
  3051. for (short i = 0; i < ffsd->face->glyph->outline.n_contours; i++) {
  3052. contours.push_back(ffsd->face->glyph->outline.contours[i]);
  3053. }
  3054. bool orientation = (FT_Outline_Get_Orientation(&ffsd->face->glyph->outline) == FT_ORIENTATION_FILL_RIGHT);
  3055. Dictionary out;
  3056. out["points"] = points;
  3057. out["contours"] = contours;
  3058. out["orientation"] = orientation;
  3059. return out;
  3060. #else
  3061. return Dictionary();
  3062. #endif
  3063. }
  3064. TypedArray<Vector2i> TextServerAdvanced::_font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const {
  3065. FontAdvanced *fd = _get_font_data(p_font_rid);
  3066. ERR_FAIL_NULL_V(fd, TypedArray<Vector2i>());
  3067. MutexLock lock(fd->mutex);
  3068. Vector2i size = _get_size(fd, p_size);
  3069. FontForSizeAdvanced *ffsd = nullptr;
  3070. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), TypedArray<Vector2i>());
  3071. TypedArray<Vector2i> ret;
  3072. for (const KeyValue<Vector2i, Vector2> &E : fd->cache[size]->kerning_map) {
  3073. ret.push_back(E.key);
  3074. }
  3075. return ret;
  3076. }
  3077. void TextServerAdvanced::_font_clear_kerning_map(const RID &p_font_rid, int64_t p_size) {
  3078. FontAdvanced *fd = _get_font_data(p_font_rid);
  3079. ERR_FAIL_NULL(fd);
  3080. MutexLock lock(fd->mutex);
  3081. Vector2i size = _get_size(fd, p_size);
  3082. FontForSizeAdvanced *ffsd = nullptr;
  3083. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  3084. ffsd->kerning_map.clear();
  3085. }
  3086. void TextServerAdvanced::_font_remove_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) {
  3087. FontAdvanced *fd = _get_font_data(p_font_rid);
  3088. ERR_FAIL_NULL(fd);
  3089. MutexLock lock(fd->mutex);
  3090. Vector2i size = _get_size(fd, p_size);
  3091. FontForSizeAdvanced *ffsd = nullptr;
  3092. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  3093. ffsd->kerning_map.erase(p_glyph_pair);
  3094. }
  3095. void TextServerAdvanced::_font_set_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair, const Vector2 &p_kerning) {
  3096. FontAdvanced *fd = _get_font_data(p_font_rid);
  3097. ERR_FAIL_NULL(fd);
  3098. MutexLock lock(fd->mutex);
  3099. Vector2i size = _get_size(fd, p_size);
  3100. FontForSizeAdvanced *ffsd = nullptr;
  3101. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  3102. ffsd->kerning_map[p_glyph_pair] = p_kerning;
  3103. }
  3104. Vector2 TextServerAdvanced::_font_get_kerning(const RID &p_font_rid, int64_t p_size, const Vector2i &p_glyph_pair) const {
  3105. FontAdvanced *fd = _get_font_data(p_font_rid);
  3106. ERR_FAIL_NULL_V(fd, Vector2());
  3107. MutexLock lock(fd->mutex);
  3108. Vector2i size = _get_size(fd, p_size);
  3109. FontForSizeAdvanced *ffsd = nullptr;
  3110. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), Vector2());
  3111. const HashMap<Vector2i, Vector2> &kern = ffsd->kerning_map;
  3112. if (kern.has(p_glyph_pair)) {
  3113. if (fd->msdf) {
  3114. return kern[p_glyph_pair] * (double)p_size / (double)fd->msdf_source_size;
  3115. } else if (fd->fixed_size > 0 && fd->fixed_size_scale_mode != FIXED_SIZE_SCALE_DISABLE && size.x != p_size * 64) {
  3116. if (fd->fixed_size_scale_mode == FIXED_SIZE_SCALE_ENABLED) {
  3117. return kern[p_glyph_pair] * (double)p_size / (double)fd->fixed_size;
  3118. } else {
  3119. return kern[p_glyph_pair] * Math::round((double)p_size / (double)fd->fixed_size);
  3120. }
  3121. } else {
  3122. return kern[p_glyph_pair];
  3123. }
  3124. } else {
  3125. #ifdef MODULE_FREETYPE_ENABLED
  3126. if (ffsd->face) {
  3127. FT_Vector delta;
  3128. FT_Get_Kerning(ffsd->face, p_glyph_pair.x, p_glyph_pair.y, FT_KERNING_DEFAULT, &delta);
  3129. if (fd->msdf) {
  3130. return Vector2(delta.x, delta.y) * (double)p_size / (double)fd->msdf_source_size;
  3131. } else if (fd->fixed_size > 0 && fd->fixed_size_scale_mode != FIXED_SIZE_SCALE_DISABLE && size.x != p_size * 64) {
  3132. if (fd->fixed_size_scale_mode == FIXED_SIZE_SCALE_ENABLED) {
  3133. return Vector2(delta.x, delta.y) * (double)p_size / (double)fd->fixed_size;
  3134. } else {
  3135. return Vector2(delta.x, delta.y) * Math::round((double)p_size / (double)fd->fixed_size);
  3136. }
  3137. } else {
  3138. return Vector2(delta.x, delta.y);
  3139. }
  3140. }
  3141. #endif
  3142. }
  3143. return Vector2();
  3144. }
  3145. int64_t TextServerAdvanced::_font_get_glyph_index(const RID &p_font_rid, int64_t p_size, int64_t p_char, int64_t p_variation_selector) const {
  3146. FontAdvanced *fd = _get_font_data(p_font_rid);
  3147. ERR_FAIL_NULL_V(fd, 0);
  3148. ERR_FAIL_COND_V_MSG((p_char >= 0xd800 && p_char <= 0xdfff) || (p_char > 0x10ffff), 0, "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_char, 16) + ".");
  3149. ERR_FAIL_COND_V_MSG((p_variation_selector >= 0xd800 && p_variation_selector <= 0xdfff) || (p_variation_selector > 0x10ffff), 0, "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_variation_selector, 16) + ".");
  3150. MutexLock lock(fd->mutex);
  3151. Vector2i size = _get_size(fd, p_size);
  3152. FontForSizeAdvanced *ffsd = nullptr;
  3153. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), 0);
  3154. #ifdef MODULE_FREETYPE_ENABLED
  3155. if (ffsd->face) {
  3156. if (p_variation_selector) {
  3157. return FT_Face_GetCharVariantIndex(ffsd->face, p_char, p_variation_selector);
  3158. } else {
  3159. return FT_Get_Char_Index(ffsd->face, p_char);
  3160. }
  3161. } else {
  3162. return (int64_t)p_char;
  3163. }
  3164. #else
  3165. return (int64_t)p_char;
  3166. #endif
  3167. }
  3168. int64_t TextServerAdvanced::_font_get_char_from_glyph_index(const RID &p_font_rid, int64_t p_size, int64_t p_glyph_index) const {
  3169. FontAdvanced *fd = _get_font_data(p_font_rid);
  3170. ERR_FAIL_NULL_V(fd, 0);
  3171. MutexLock lock(fd->mutex);
  3172. Vector2i size = _get_size(fd, p_size);
  3173. FontForSizeAdvanced *ffsd = nullptr;
  3174. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), 0);
  3175. #ifdef MODULE_FREETYPE_ENABLED
  3176. if (ffsd->inv_glyph_map.is_empty()) {
  3177. FT_Face face = ffsd->face;
  3178. FT_UInt gindex;
  3179. FT_ULong charcode = FT_Get_First_Char(face, &gindex);
  3180. while (gindex != 0) {
  3181. if (charcode != 0) {
  3182. ffsd->inv_glyph_map[gindex] = charcode;
  3183. }
  3184. charcode = FT_Get_Next_Char(face, charcode, &gindex);
  3185. }
  3186. }
  3187. if (ffsd->inv_glyph_map.has(p_glyph_index)) {
  3188. return ffsd->inv_glyph_map[p_glyph_index];
  3189. } else {
  3190. return 0;
  3191. }
  3192. #else
  3193. return p_glyph_index;
  3194. #endif
  3195. }
  3196. bool TextServerAdvanced::_font_has_char(const RID &p_font_rid, int64_t p_char) const {
  3197. FontAdvanced *fd = _get_font_data(p_font_rid);
  3198. ERR_FAIL_COND_V_MSG((p_char >= 0xd800 && p_char <= 0xdfff) || (p_char > 0x10ffff), false, "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_char, 16) + ".");
  3199. if (!fd) {
  3200. return false;
  3201. }
  3202. MutexLock lock(fd->mutex);
  3203. FontForSizeAdvanced *ffsd = nullptr;
  3204. if (fd->cache.is_empty()) {
  3205. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, fd->msdf ? Vector2i(fd->msdf_source_size * 64, 0) : Vector2i(16 * 64, 0), ffsd), false);
  3206. } else {
  3207. ffsd = fd->cache.begin()->value;
  3208. }
  3209. #ifdef MODULE_FREETYPE_ENABLED
  3210. if (ffsd->face) {
  3211. return FT_Get_Char_Index(ffsd->face, p_char) != 0;
  3212. }
  3213. #endif
  3214. return ffsd->glyph_map.has((int32_t)p_char);
  3215. }
  3216. String TextServerAdvanced::_font_get_supported_chars(const RID &p_font_rid) const {
  3217. FontAdvanced *fd = _get_font_data(p_font_rid);
  3218. ERR_FAIL_NULL_V(fd, String());
  3219. MutexLock lock(fd->mutex);
  3220. FontForSizeAdvanced *ffsd = nullptr;
  3221. if (fd->cache.is_empty()) {
  3222. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, fd->msdf ? Vector2i(fd->msdf_source_size * 64, 0) : Vector2i(16 * 64, 0), ffsd), String());
  3223. } else {
  3224. ffsd = fd->cache.begin()->value;
  3225. }
  3226. String chars;
  3227. #ifdef MODULE_FREETYPE_ENABLED
  3228. if (ffsd->face) {
  3229. FT_UInt gindex;
  3230. FT_ULong charcode = FT_Get_First_Char(ffsd->face, &gindex);
  3231. while (gindex != 0) {
  3232. if (charcode != 0) {
  3233. chars = chars + String::chr(charcode);
  3234. }
  3235. charcode = FT_Get_Next_Char(ffsd->face, charcode, &gindex);
  3236. }
  3237. return chars;
  3238. }
  3239. #endif
  3240. const HashMap<int32_t, FontGlyph> &gl = ffsd->glyph_map;
  3241. for (const KeyValue<int32_t, FontGlyph> &E : gl) {
  3242. chars = chars + String::chr(E.key);
  3243. }
  3244. return chars;
  3245. }
  3246. PackedInt32Array TextServerAdvanced::_font_get_supported_glyphs(const RID &p_font_rid) const {
  3247. FontAdvanced *fd = _get_font_data(p_font_rid);
  3248. ERR_FAIL_NULL_V(fd, PackedInt32Array());
  3249. MutexLock lock(fd->mutex);
  3250. FontForSizeAdvanced *at_size = nullptr;
  3251. if (fd->cache.is_empty()) {
  3252. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, fd->msdf ? Vector2i(fd->msdf_source_size * 64, 0) : Vector2i(16 * 64, 0), at_size), PackedInt32Array());
  3253. } else {
  3254. at_size = fd->cache.begin()->value;
  3255. }
  3256. PackedInt32Array glyphs;
  3257. #ifdef MODULE_FREETYPE_ENABLED
  3258. if (at_size && at_size->face) {
  3259. FT_UInt gindex;
  3260. FT_ULong charcode = FT_Get_First_Char(at_size->face, &gindex);
  3261. while (gindex != 0) {
  3262. glyphs.push_back(gindex);
  3263. charcode = FT_Get_Next_Char(at_size->face, charcode, &gindex);
  3264. }
  3265. return glyphs;
  3266. }
  3267. #endif
  3268. if (at_size) {
  3269. const HashMap<int32_t, FontGlyph> &gl = at_size->glyph_map;
  3270. for (const KeyValue<int32_t, FontGlyph> &E : gl) {
  3271. glyphs.push_back(E.key);
  3272. }
  3273. }
  3274. return glyphs;
  3275. }
  3276. void TextServerAdvanced::_font_render_range(const RID &p_font_rid, const Vector2i &p_size, int64_t p_start, int64_t p_end) {
  3277. FontAdvanced *fd = _get_font_data(p_font_rid);
  3278. ERR_FAIL_NULL(fd);
  3279. ERR_FAIL_COND_MSG((p_start >= 0xd800 && p_start <= 0xdfff) || (p_start > 0x10ffff), "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_start, 16) + ".");
  3280. ERR_FAIL_COND_MSG((p_end >= 0xd800 && p_end <= 0xdfff) || (p_end > 0x10ffff), "Unicode parsing error: Invalid unicode codepoint " + String::num_int64(p_end, 16) + ".");
  3281. MutexLock lock(fd->mutex);
  3282. Vector2i size = _get_size_outline(fd, p_size);
  3283. FontForSizeAdvanced *ffsd = nullptr;
  3284. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  3285. for (int64_t i = p_start; i <= p_end; i++) {
  3286. #ifdef MODULE_FREETYPE_ENABLED
  3287. int32_t idx = FT_Get_Char_Index(ffsd->face, i);
  3288. if (ffsd->face) {
  3289. FontGlyph fgl;
  3290. if (fd->msdf) {
  3291. _ensure_glyph(fd, size, (int32_t)idx, fgl);
  3292. } else {
  3293. for (int aa = 0; aa < ((fd->antialiasing == FONT_ANTIALIASING_LCD) ? FONT_LCD_SUBPIXEL_LAYOUT_MAX : 1); aa++) {
  3294. if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE * 64)) {
  3295. _ensure_glyph(fd, size, (int32_t)idx | (0 << 27) | (aa << 24), fgl);
  3296. _ensure_glyph(fd, size, (int32_t)idx | (1 << 27) | (aa << 24), fgl);
  3297. _ensure_glyph(fd, size, (int32_t)idx | (2 << 27) | (aa << 24), fgl);
  3298. _ensure_glyph(fd, size, (int32_t)idx | (3 << 27) | (aa << 24), fgl);
  3299. } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE * 64)) {
  3300. _ensure_glyph(fd, size, (int32_t)idx | (1 << 27) | (aa << 24), fgl);
  3301. _ensure_glyph(fd, size, (int32_t)idx | (0 << 27) | (aa << 24), fgl);
  3302. } else {
  3303. _ensure_glyph(fd, size, (int32_t)idx | (aa << 24), fgl);
  3304. }
  3305. }
  3306. }
  3307. }
  3308. #endif
  3309. }
  3310. }
  3311. void TextServerAdvanced::_font_render_glyph(const RID &p_font_rid, const Vector2i &p_size, int64_t p_index) {
  3312. FontAdvanced *fd = _get_font_data(p_font_rid);
  3313. ERR_FAIL_NULL(fd);
  3314. MutexLock lock(fd->mutex);
  3315. Vector2i size = _get_size_outline(fd, p_size);
  3316. FontForSizeAdvanced *ffsd = nullptr;
  3317. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  3318. #ifdef MODULE_FREETYPE_ENABLED
  3319. int32_t idx = p_index & 0xffffff; // Remove subpixel shifts.
  3320. if (ffsd->face) {
  3321. FontGlyph fgl;
  3322. if (fd->msdf) {
  3323. _ensure_glyph(fd, size, (int32_t)idx, fgl);
  3324. } else {
  3325. for (int aa = 0; aa < ((fd->antialiasing == FONT_ANTIALIASING_LCD) ? FONT_LCD_SUBPIXEL_LAYOUT_MAX : 1); aa++) {
  3326. if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE * 64)) {
  3327. _ensure_glyph(fd, size, (int32_t)idx | (0 << 27) | (aa << 24), fgl);
  3328. _ensure_glyph(fd, size, (int32_t)idx | (1 << 27) | (aa << 24), fgl);
  3329. _ensure_glyph(fd, size, (int32_t)idx | (2 << 27) | (aa << 24), fgl);
  3330. _ensure_glyph(fd, size, (int32_t)idx | (3 << 27) | (aa << 24), fgl);
  3331. } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE * 64)) {
  3332. _ensure_glyph(fd, size, (int32_t)idx | (1 << 27) | (aa << 24), fgl);
  3333. _ensure_glyph(fd, size, (int32_t)idx | (0 << 27) | (aa << 24), fgl);
  3334. } else {
  3335. _ensure_glyph(fd, size, (int32_t)idx | (aa << 24), fgl);
  3336. }
  3337. }
  3338. }
  3339. }
  3340. #endif
  3341. }
  3342. void TextServerAdvanced::_font_draw_glyph(const RID &p_font_rid, const RID &p_canvas, int64_t p_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color, float p_oversampling) const {
  3343. if (p_index == 0) {
  3344. return; // Non visual character, skip.
  3345. }
  3346. FontAdvanced *fd = _get_font_data(p_font_rid);
  3347. ERR_FAIL_NULL(fd);
  3348. MutexLock lock(fd->mutex);
  3349. // Oversampling.
  3350. bool viewport_oversampling = false;
  3351. float oversampling_factor = p_oversampling;
  3352. if (p_oversampling <= 0.0) {
  3353. if (fd->oversampling_override > 0.0) {
  3354. oversampling_factor = fd->oversampling_override;
  3355. } else if (vp_oversampling > 0.0) {
  3356. oversampling_factor = vp_oversampling;
  3357. viewport_oversampling = true;
  3358. } else {
  3359. oversampling_factor = 1.0;
  3360. }
  3361. }
  3362. bool skip_oversampling = fd->msdf || fd->fixed_size > 0;
  3363. if (skip_oversampling) {
  3364. oversampling_factor = 1.0;
  3365. } else {
  3366. uint64_t oversampling_level = CLAMP(oversampling_factor, 0.1, 100.0) * 64;
  3367. oversampling_factor = double(oversampling_level) / 64.0;
  3368. }
  3369. Vector2i size;
  3370. if (skip_oversampling) {
  3371. size = _get_size(fd, p_size);
  3372. } else {
  3373. size = Vector2i(p_size * 64 * oversampling_factor, 0);
  3374. }
  3375. FontForSizeAdvanced *ffsd = nullptr;
  3376. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd, false, viewport_oversampling ? 64 * oversampling_factor : 0));
  3377. int32_t index = p_index & 0xffffff; // Remove subpixel shifts.
  3378. bool lcd_aa = false;
  3379. #ifdef MODULE_FREETYPE_ENABLED
  3380. if (!fd->msdf && ffsd->face) {
  3381. // LCD layout, bits 24, 25, 26
  3382. if (fd->antialiasing == FONT_ANTIALIASING_LCD) {
  3383. TextServer::FontLCDSubpixelLayout layout = lcd_subpixel_layout.get();
  3384. if (layout != FONT_LCD_SUBPIXEL_LAYOUT_NONE) {
  3385. lcd_aa = true;
  3386. index = index | (layout << 24);
  3387. }
  3388. }
  3389. // Subpixel X-shift, bits 27, 28
  3390. if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE * 64)) {
  3391. int xshift = (int)(Math::floor(4 * (p_pos.x + 0.125)) - 4 * Math::floor(p_pos.x + 0.125));
  3392. index = index | (xshift << 27);
  3393. } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE * 64)) {
  3394. int xshift = (int)(Math::floor(2 * (p_pos.x + 0.25)) - 2 * Math::floor(p_pos.x + 0.25));
  3395. index = index | (xshift << 27);
  3396. }
  3397. }
  3398. #endif
  3399. FontGlyph fgl;
  3400. if (!_ensure_glyph(fd, size, index, fgl, viewport_oversampling ? 64 * oversampling_factor : 0)) {
  3401. return; // Invalid or non-graphical glyph, do not display errors, nothing to draw.
  3402. }
  3403. if (fgl.found) {
  3404. ERR_FAIL_COND(fgl.texture_idx < -1 || fgl.texture_idx >= ffsd->textures.size());
  3405. if (fgl.texture_idx != -1) {
  3406. Color modulate = p_color;
  3407. #ifdef MODULE_FREETYPE_ENABLED
  3408. if (!fd->modulate_color_glyphs && ffsd->face && ffsd->textures[fgl.texture_idx].image.is_valid() && (ffsd->textures[fgl.texture_idx].image->get_format() == Image::FORMAT_RGBA8) && !lcd_aa && !fd->msdf) {
  3409. modulate.r = modulate.g = modulate.b = 1.0;
  3410. }
  3411. #endif
  3412. if (RenderingServer::get_singleton() != nullptr) {
  3413. if (ffsd->textures[fgl.texture_idx].dirty) {
  3414. ShelfPackTexture &tex = ffsd->textures.write[fgl.texture_idx];
  3415. Ref<Image> img = tex.image;
  3416. if (fgl.from_svg) {
  3417. // Same as the "fix alpha border" process option when importing SVGs
  3418. img->fix_alpha_edges();
  3419. }
  3420. if (fd->mipmaps && !img->has_mipmaps()) {
  3421. img = tex.image->duplicate();
  3422. img->generate_mipmaps();
  3423. }
  3424. if (tex.texture.is_null()) {
  3425. tex.texture = ImageTexture::create_from_image(img);
  3426. } else {
  3427. tex.texture->update(img);
  3428. }
  3429. tex.dirty = false;
  3430. }
  3431. RID texture = ffsd->textures[fgl.texture_idx].texture->get_rid();
  3432. if (fd->msdf) {
  3433. Point2 cpos = p_pos;
  3434. cpos += fgl.rect.position * (double)p_size / (double)fd->msdf_source_size;
  3435. Size2 csize = fgl.rect.size * (double)p_size / (double)fd->msdf_source_size;
  3436. RenderingServer::get_singleton()->canvas_item_add_msdf_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, fgl.uv_rect, modulate, 0, fd->msdf_range, (double)p_size / (double)fd->msdf_source_size);
  3437. } else {
  3438. Point2 cpos = p_pos;
  3439. double scale = _font_get_scale(p_font_rid, p_size) / oversampling_factor;
  3440. if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE * 64)) {
  3441. cpos.x = cpos.x + 0.125;
  3442. } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE * 64)) {
  3443. cpos.x = cpos.x + 0.25;
  3444. }
  3445. if (scale == 1.0) {
  3446. cpos.y = Math::floor(cpos.y);
  3447. cpos.x = Math::floor(cpos.x);
  3448. }
  3449. Vector2 gpos = fgl.rect.position;
  3450. Size2 csize = fgl.rect.size;
  3451. if (fd->fixed_size > 0 && fd->fixed_size_scale_mode != FIXED_SIZE_SCALE_DISABLE) {
  3452. if (size.x != p_size * 64) {
  3453. if (fd->fixed_size_scale_mode == FIXED_SIZE_SCALE_ENABLED) {
  3454. double gl_scale = (double)p_size / (double)fd->fixed_size;
  3455. gpos *= gl_scale;
  3456. csize *= gl_scale;
  3457. } else {
  3458. double gl_scale = Math::round((double)p_size / (double)fd->fixed_size);
  3459. gpos *= gl_scale;
  3460. csize *= gl_scale;
  3461. }
  3462. }
  3463. } else {
  3464. gpos /= oversampling_factor;
  3465. csize /= oversampling_factor;
  3466. }
  3467. cpos += gpos;
  3468. if (lcd_aa) {
  3469. RenderingServer::get_singleton()->canvas_item_add_lcd_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, fgl.uv_rect, modulate);
  3470. } else {
  3471. RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, fgl.uv_rect, modulate, false, false);
  3472. }
  3473. }
  3474. }
  3475. }
  3476. }
  3477. }
  3478. void TextServerAdvanced::_font_draw_glyph_outline(const RID &p_font_rid, const RID &p_canvas, int64_t p_size, int64_t p_outline_size, const Vector2 &p_pos, int64_t p_index, const Color &p_color, float p_oversampling) const {
  3479. if (p_index == 0) {
  3480. return; // Non visual character, skip.
  3481. }
  3482. FontAdvanced *fd = _get_font_data(p_font_rid);
  3483. ERR_FAIL_NULL(fd);
  3484. MutexLock lock(fd->mutex);
  3485. // Oversampling.
  3486. bool viewport_oversampling = false;
  3487. float oversampling_factor = p_oversampling;
  3488. if (p_oversampling <= 0.0) {
  3489. if (fd->oversampling_override > 0.0) {
  3490. oversampling_factor = fd->oversampling_override;
  3491. } else if (vp_oversampling > 0.0) {
  3492. oversampling_factor = vp_oversampling;
  3493. viewport_oversampling = true;
  3494. } else {
  3495. oversampling_factor = 1.0;
  3496. }
  3497. }
  3498. bool skip_oversampling = fd->msdf || fd->fixed_size > 0;
  3499. if (skip_oversampling) {
  3500. oversampling_factor = 1.0;
  3501. } else {
  3502. uint64_t oversampling_level = CLAMP(oversampling_factor, 0.1, 100.0) * 64;
  3503. oversampling_factor = double(oversampling_level) / 64.0;
  3504. }
  3505. Vector2i size;
  3506. if (skip_oversampling) {
  3507. size = _get_size_outline(fd, Vector2i(p_size, p_outline_size));
  3508. } else {
  3509. size = Vector2i(p_size * 64 * oversampling_factor, p_outline_size * oversampling_factor);
  3510. }
  3511. FontForSizeAdvanced *ffsd = nullptr;
  3512. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd, false, viewport_oversampling ? 64 * oversampling_factor : 0));
  3513. int32_t index = p_index & 0xffffff; // Remove subpixel shifts.
  3514. bool lcd_aa = false;
  3515. #ifdef MODULE_FREETYPE_ENABLED
  3516. if (!fd->msdf && ffsd->face) {
  3517. // LCD layout, bits 24, 25, 26
  3518. if (fd->antialiasing == FONT_ANTIALIASING_LCD) {
  3519. TextServer::FontLCDSubpixelLayout layout = lcd_subpixel_layout.get();
  3520. if (layout != FONT_LCD_SUBPIXEL_LAYOUT_NONE) {
  3521. lcd_aa = true;
  3522. index = index | (layout << 24);
  3523. }
  3524. }
  3525. // Subpixel X-shift, bits 27, 28
  3526. if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE * 64)) {
  3527. int xshift = (int)(Math::floor(4 * (p_pos.x + 0.125)) - 4 * Math::floor(p_pos.x + 0.125));
  3528. index = index | (xshift << 27);
  3529. } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE * 64)) {
  3530. int xshift = (int)(Math::floor(2 * (p_pos.x + 0.25)) - 2 * Math::floor(p_pos.x + 0.25));
  3531. index = index | (xshift << 27);
  3532. }
  3533. }
  3534. #endif
  3535. FontGlyph fgl;
  3536. if (!_ensure_glyph(fd, size, index, fgl, viewport_oversampling ? 64 * oversampling_factor : 0)) {
  3537. return; // Invalid or non-graphical glyph, do not display errors, nothing to draw.
  3538. }
  3539. if (fgl.found) {
  3540. ERR_FAIL_COND(fgl.texture_idx < -1 || fgl.texture_idx >= ffsd->textures.size());
  3541. if (fgl.texture_idx != -1) {
  3542. Color modulate = p_color;
  3543. #ifdef MODULE_FREETYPE_ENABLED
  3544. if (ffsd->face && fd->cache[size]->textures[fgl.texture_idx].image.is_valid() && (ffsd->textures[fgl.texture_idx].image->get_format() == Image::FORMAT_RGBA8) && !lcd_aa && !fd->msdf) {
  3545. modulate.r = modulate.g = modulate.b = 1.0;
  3546. }
  3547. #endif
  3548. if (RenderingServer::get_singleton() != nullptr) {
  3549. if (ffsd->textures[fgl.texture_idx].dirty) {
  3550. ShelfPackTexture &tex = ffsd->textures.write[fgl.texture_idx];
  3551. Ref<Image> img = tex.image;
  3552. if (fd->mipmaps && !img->has_mipmaps()) {
  3553. img = tex.image->duplicate();
  3554. img->generate_mipmaps();
  3555. }
  3556. if (tex.texture.is_null()) {
  3557. tex.texture = ImageTexture::create_from_image(img);
  3558. } else {
  3559. tex.texture->update(img);
  3560. }
  3561. tex.dirty = false;
  3562. }
  3563. RID texture = ffsd->textures[fgl.texture_idx].texture->get_rid();
  3564. if (fd->msdf) {
  3565. Point2 cpos = p_pos;
  3566. cpos += fgl.rect.position * (double)p_size / (double)fd->msdf_source_size;
  3567. Size2 csize = fgl.rect.size * (double)p_size / (double)fd->msdf_source_size;
  3568. RenderingServer::get_singleton()->canvas_item_add_msdf_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, fgl.uv_rect, modulate, p_outline_size, fd->msdf_range, (double)p_size / (double)fd->msdf_source_size);
  3569. } else {
  3570. Point2 cpos = p_pos;
  3571. double scale = _font_get_scale(p_font_rid, p_size) / oversampling_factor;
  3572. if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_QUARTER) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_QUARTER_MAX_SIZE * 64)) {
  3573. cpos.x = cpos.x + 0.125;
  3574. } else if ((fd->subpixel_positioning == SUBPIXEL_POSITIONING_ONE_HALF) || (fd->subpixel_positioning == SUBPIXEL_POSITIONING_AUTO && size.x <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE * 64)) {
  3575. cpos.x = cpos.x + 0.25;
  3576. }
  3577. if (scale == 1.0) {
  3578. cpos.y = Math::floor(cpos.y);
  3579. cpos.x = Math::floor(cpos.x);
  3580. }
  3581. Vector2 gpos = fgl.rect.position;
  3582. Size2 csize = fgl.rect.size;
  3583. if (fd->fixed_size > 0 && fd->fixed_size_scale_mode != FIXED_SIZE_SCALE_DISABLE) {
  3584. if (size.x != p_size * 64) {
  3585. if (fd->fixed_size_scale_mode == FIXED_SIZE_SCALE_ENABLED) {
  3586. double gl_scale = (double)p_size / (double)fd->fixed_size;
  3587. gpos *= gl_scale;
  3588. csize *= gl_scale;
  3589. } else {
  3590. double gl_scale = Math::round((double)p_size / (double)fd->fixed_size);
  3591. gpos *= gl_scale;
  3592. csize *= gl_scale;
  3593. }
  3594. }
  3595. } else {
  3596. gpos /= oversampling_factor;
  3597. csize /= oversampling_factor;
  3598. }
  3599. cpos += gpos;
  3600. if (lcd_aa) {
  3601. RenderingServer::get_singleton()->canvas_item_add_lcd_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, fgl.uv_rect, modulate);
  3602. } else {
  3603. RenderingServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas, Rect2(cpos, csize), texture, fgl.uv_rect, modulate, false, false);
  3604. }
  3605. }
  3606. }
  3607. }
  3608. }
  3609. }
  3610. bool TextServerAdvanced::_font_is_language_supported(const RID &p_font_rid, const String &p_language) const {
  3611. FontAdvanced *fd = _get_font_data(p_font_rid);
  3612. ERR_FAIL_NULL_V(fd, false);
  3613. MutexLock lock(fd->mutex);
  3614. if (fd->language_support_overrides.has(p_language)) {
  3615. return fd->language_support_overrides[p_language];
  3616. } else {
  3617. return true;
  3618. }
  3619. }
  3620. void TextServerAdvanced::_font_set_language_support_override(const RID &p_font_rid, const String &p_language, bool p_supported) {
  3621. FontAdvanced *fd = _get_font_data(p_font_rid);
  3622. ERR_FAIL_NULL(fd);
  3623. MutexLock lock(fd->mutex);
  3624. fd->language_support_overrides[p_language] = p_supported;
  3625. }
  3626. bool TextServerAdvanced::_font_get_language_support_override(const RID &p_font_rid, const String &p_language) {
  3627. FontAdvanced *fd = _get_font_data(p_font_rid);
  3628. ERR_FAIL_NULL_V(fd, false);
  3629. MutexLock lock(fd->mutex);
  3630. return fd->language_support_overrides[p_language];
  3631. }
  3632. void TextServerAdvanced::_font_remove_language_support_override(const RID &p_font_rid, const String &p_language) {
  3633. FontAdvanced *fd = _get_font_data(p_font_rid);
  3634. ERR_FAIL_NULL(fd);
  3635. MutexLock lock(fd->mutex);
  3636. fd->language_support_overrides.erase(p_language);
  3637. }
  3638. PackedStringArray TextServerAdvanced::_font_get_language_support_overrides(const RID &p_font_rid) {
  3639. FontAdvanced *fd = _get_font_data(p_font_rid);
  3640. ERR_FAIL_NULL_V(fd, PackedStringArray());
  3641. MutexLock lock(fd->mutex);
  3642. PackedStringArray out;
  3643. for (const KeyValue<String, bool> &E : fd->language_support_overrides) {
  3644. out.push_back(E.key);
  3645. }
  3646. return out;
  3647. }
  3648. bool TextServerAdvanced::_font_is_script_supported(const RID &p_font_rid, const String &p_script) const {
  3649. FontAdvanced *fd = _get_font_data(p_font_rid);
  3650. ERR_FAIL_NULL_V(fd, false);
  3651. MutexLock lock(fd->mutex);
  3652. if (fd->script_support_overrides.has(p_script)) {
  3653. return fd->script_support_overrides[p_script];
  3654. } else {
  3655. Vector2i size = _get_size(fd, 16);
  3656. FontForSizeAdvanced *ffsd = nullptr;
  3657. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), false);
  3658. return fd->supported_scripts.has(hb_tag_from_string(p_script.ascii().get_data(), -1));
  3659. }
  3660. }
  3661. void TextServerAdvanced::_font_set_script_support_override(const RID &p_font_rid, const String &p_script, bool p_supported) {
  3662. FontAdvanced *fd = _get_font_data(p_font_rid);
  3663. ERR_FAIL_NULL(fd);
  3664. MutexLock lock(fd->mutex);
  3665. fd->script_support_overrides[p_script] = p_supported;
  3666. }
  3667. bool TextServerAdvanced::_font_get_script_support_override(const RID &p_font_rid, const String &p_script) {
  3668. FontAdvanced *fd = _get_font_data(p_font_rid);
  3669. ERR_FAIL_NULL_V(fd, false);
  3670. MutexLock lock(fd->mutex);
  3671. return fd->script_support_overrides[p_script];
  3672. }
  3673. void TextServerAdvanced::_font_remove_script_support_override(const RID &p_font_rid, const String &p_script) {
  3674. FontAdvanced *fd = _get_font_data(p_font_rid);
  3675. ERR_FAIL_NULL(fd);
  3676. MutexLock lock(fd->mutex);
  3677. fd->script_support_overrides.erase(p_script);
  3678. }
  3679. PackedStringArray TextServerAdvanced::_font_get_script_support_overrides(const RID &p_font_rid) {
  3680. FontAdvanced *fd = _get_font_data(p_font_rid);
  3681. ERR_FAIL_NULL_V(fd, PackedStringArray());
  3682. MutexLock lock(fd->mutex);
  3683. PackedStringArray out;
  3684. for (const KeyValue<String, bool> &E : fd->script_support_overrides) {
  3685. out.push_back(E.key);
  3686. }
  3687. return out;
  3688. }
  3689. void TextServerAdvanced::_font_set_opentype_feature_overrides(const RID &p_font_rid, const Dictionary &p_overrides) {
  3690. FontAdvanced *fd = _get_font_data(p_font_rid);
  3691. ERR_FAIL_NULL(fd);
  3692. MutexLock lock(fd->mutex);
  3693. Vector2i size = _get_size(fd, 16);
  3694. FontForSizeAdvanced *ffsd = nullptr;
  3695. ERR_FAIL_COND(!_ensure_cache_for_size(fd, size, ffsd));
  3696. fd->feature_overrides = p_overrides;
  3697. }
  3698. Dictionary TextServerAdvanced::_font_get_opentype_feature_overrides(const RID &p_font_rid) const {
  3699. FontAdvanced *fd = _get_font_data(p_font_rid);
  3700. ERR_FAIL_NULL_V(fd, Dictionary());
  3701. MutexLock lock(fd->mutex);
  3702. return fd->feature_overrides;
  3703. }
  3704. Dictionary TextServerAdvanced::_font_supported_feature_list(const RID &p_font_rid) const {
  3705. FontAdvanced *fd = _get_font_data(p_font_rid);
  3706. ERR_FAIL_NULL_V(fd, Dictionary());
  3707. MutexLock lock(fd->mutex);
  3708. Vector2i size = _get_size(fd, 16);
  3709. FontForSizeAdvanced *ffsd = nullptr;
  3710. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), Dictionary());
  3711. return fd->supported_features;
  3712. }
  3713. Dictionary TextServerAdvanced::_font_supported_variation_list(const RID &p_font_rid) const {
  3714. FontAdvanced *fd = _get_font_data(p_font_rid);
  3715. ERR_FAIL_NULL_V(fd, Dictionary());
  3716. MutexLock lock(fd->mutex);
  3717. Vector2i size = _get_size(fd, 16);
  3718. FontForSizeAdvanced *ffsd = nullptr;
  3719. ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size, ffsd), Dictionary());
  3720. return fd->supported_varaitions;
  3721. }
  3722. /*************************************************************************/
  3723. /* Shaped text buffer interface */
  3724. /*************************************************************************/
  3725. int64_t TextServerAdvanced::_convert_pos(const String &p_utf32, const Char16String &p_utf16, int64_t p_pos) const {
  3726. int64_t limit = p_pos;
  3727. if (p_utf32.length() != p_utf16.length()) {
  3728. const UChar *data = p_utf16.get_data();
  3729. for (int i = 0; i < p_pos; i++) {
  3730. if (U16_IS_LEAD(data[i])) {
  3731. limit--;
  3732. }
  3733. }
  3734. }
  3735. return limit;
  3736. }
  3737. int64_t TextServerAdvanced::_convert_pos(const ShapedTextDataAdvanced *p_sd, int64_t p_pos) const {
  3738. int64_t limit = p_pos;
  3739. if (p_sd->text.length() != p_sd->utf16.length()) {
  3740. const UChar *data = p_sd->utf16.get_data();
  3741. for (int i = 0; i < p_pos; i++) {
  3742. if (U16_IS_LEAD(data[i])) {
  3743. limit--;
  3744. }
  3745. }
  3746. }
  3747. return limit;
  3748. }
  3749. int64_t TextServerAdvanced::_convert_pos_inv(const ShapedTextDataAdvanced *p_sd, int64_t p_pos) const {
  3750. int64_t limit = p_pos;
  3751. if (p_sd->text.length() != p_sd->utf16.length()) {
  3752. for (int i = 0; i < p_pos; i++) {
  3753. if (p_sd->text[i] > 0xffff) {
  3754. limit++;
  3755. }
  3756. }
  3757. }
  3758. return limit;
  3759. }
  3760. void TextServerAdvanced::invalidate(TextServerAdvanced::ShapedTextDataAdvanced *p_shaped, bool p_text) {
  3761. p_shaped->valid.clear();
  3762. p_shaped->sort_valid = false;
  3763. p_shaped->line_breaks_valid = false;
  3764. p_shaped->justification_ops_valid = false;
  3765. p_shaped->text_trimmed = false;
  3766. p_shaped->ascent = 0.0;
  3767. p_shaped->descent = 0.0;
  3768. p_shaped->width = 0.0;
  3769. p_shaped->upos = 0.0;
  3770. p_shaped->uthk = 0.0;
  3771. p_shaped->glyphs.clear();
  3772. p_shaped->glyphs_logical.clear();
  3773. p_shaped->runs.clear();
  3774. p_shaped->runs_dirty = true;
  3775. p_shaped->overrun_trim_data = TrimData();
  3776. p_shaped->utf16 = Char16String();
  3777. for (int i = 0; i < p_shaped->bidi_iter.size(); i++) {
  3778. ubidi_close(p_shaped->bidi_iter[i]);
  3779. }
  3780. p_shaped->bidi_iter.clear();
  3781. if (p_text) {
  3782. if (p_shaped->script_iter != nullptr) {
  3783. memdelete(p_shaped->script_iter);
  3784. p_shaped->script_iter = nullptr;
  3785. }
  3786. p_shaped->break_ops_valid = false;
  3787. p_shaped->chars_valid = false;
  3788. p_shaped->js_ops_valid = false;
  3789. }
  3790. }
  3791. void TextServerAdvanced::full_copy(ShapedTextDataAdvanced *p_shaped) {
  3792. ShapedTextDataAdvanced *parent = shaped_owner.get_or_null(p_shaped->parent);
  3793. for (const KeyValue<Variant, ShapedTextDataAdvanced::EmbeddedObject> &E : parent->objects) {
  3794. if (E.value.start >= p_shaped->start && E.value.start < p_shaped->end) {
  3795. p_shaped->objects[E.key] = E.value;
  3796. }
  3797. }
  3798. for (int i = p_shaped->first_span; i <= p_shaped->last_span; i++) {
  3799. ShapedTextDataAdvanced::Span span = parent->spans[i];
  3800. span.start = MAX(p_shaped->start, span.start);
  3801. span.end = MIN(p_shaped->end, span.end);
  3802. p_shaped->spans.push_back(span);
  3803. }
  3804. p_shaped->first_span = 0;
  3805. p_shaped->last_span = 0;
  3806. p_shaped->parent = RID();
  3807. }
  3808. RID TextServerAdvanced::_create_shaped_text(TextServer::Direction p_direction, TextServer::Orientation p_orientation) {
  3809. _THREAD_SAFE_METHOD_
  3810. ERR_FAIL_COND_V_MSG(p_direction == DIRECTION_INHERITED, RID(), "Invalid text direction.");
  3811. ShapedTextDataAdvanced *sd = memnew(ShapedTextDataAdvanced);
  3812. sd->hb_buffer = hb_buffer_create();
  3813. sd->direction = p_direction;
  3814. sd->orientation = p_orientation;
  3815. return shaped_owner.make_rid(sd);
  3816. }
  3817. void TextServerAdvanced::_shaped_text_clear(const RID &p_shaped) {
  3818. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3819. ERR_FAIL_NULL(sd);
  3820. MutexLock lock(sd->mutex);
  3821. sd->parent = RID();
  3822. sd->start = 0;
  3823. sd->end = 0;
  3824. sd->text = String();
  3825. sd->spans.clear();
  3826. sd->first_span = 0;
  3827. sd->last_span = 0;
  3828. sd->objects.clear();
  3829. sd->bidi_override.clear();
  3830. invalidate(sd, true);
  3831. }
  3832. void TextServerAdvanced::_shaped_text_set_direction(const RID &p_shaped, TextServer::Direction p_direction) {
  3833. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3834. ERR_FAIL_COND_MSG(p_direction == DIRECTION_INHERITED, "Invalid text direction.");
  3835. ERR_FAIL_NULL(sd);
  3836. MutexLock lock(sd->mutex);
  3837. if (sd->direction != p_direction) {
  3838. if (sd->parent != RID()) {
  3839. full_copy(sd);
  3840. }
  3841. sd->direction = p_direction;
  3842. invalidate(sd, false);
  3843. }
  3844. }
  3845. TextServer::Direction TextServerAdvanced::_shaped_text_get_direction(const RID &p_shaped) const {
  3846. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3847. ERR_FAIL_NULL_V(sd, TextServer::DIRECTION_LTR);
  3848. MutexLock lock(sd->mutex);
  3849. return sd->direction;
  3850. }
  3851. TextServer::Direction TextServerAdvanced::_shaped_text_get_inferred_direction(const RID &p_shaped) const {
  3852. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3853. ERR_FAIL_NULL_V(sd, TextServer::DIRECTION_LTR);
  3854. MutexLock lock(sd->mutex);
  3855. return sd->para_direction;
  3856. }
  3857. void TextServerAdvanced::_shaped_text_set_custom_punctuation(const RID &p_shaped, const String &p_punct) {
  3858. _THREAD_SAFE_METHOD_
  3859. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3860. ERR_FAIL_NULL(sd);
  3861. if (sd->custom_punct != p_punct) {
  3862. if (sd->parent != RID()) {
  3863. full_copy(sd);
  3864. }
  3865. sd->custom_punct = p_punct;
  3866. invalidate(sd, false);
  3867. }
  3868. }
  3869. String TextServerAdvanced::_shaped_text_get_custom_punctuation(const RID &p_shaped) const {
  3870. _THREAD_SAFE_METHOD_
  3871. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3872. ERR_FAIL_NULL_V(sd, String());
  3873. return sd->custom_punct;
  3874. }
  3875. void TextServerAdvanced::_shaped_text_set_custom_ellipsis(const RID &p_shaped, int64_t p_char) {
  3876. _THREAD_SAFE_METHOD_
  3877. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3878. ERR_FAIL_NULL(sd);
  3879. sd->el_char = p_char;
  3880. }
  3881. int64_t TextServerAdvanced::_shaped_text_get_custom_ellipsis(const RID &p_shaped) const {
  3882. _THREAD_SAFE_METHOD_
  3883. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3884. ERR_FAIL_NULL_V(sd, 0);
  3885. return sd->el_char;
  3886. }
  3887. void TextServerAdvanced::_shaped_text_set_bidi_override(const RID &p_shaped, const Array &p_override) {
  3888. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3889. ERR_FAIL_NULL(sd);
  3890. MutexLock lock(sd->mutex);
  3891. if (sd->parent != RID()) {
  3892. full_copy(sd);
  3893. }
  3894. sd->bidi_override.clear();
  3895. for (int i = 0; i < p_override.size(); i++) {
  3896. if (p_override[i].get_type() == Variant::VECTOR3I) {
  3897. const Vector3i &r = p_override[i];
  3898. sd->bidi_override.push_back(r);
  3899. } else if (p_override[i].get_type() == Variant::VECTOR2I) {
  3900. const Vector2i &r = p_override[i];
  3901. sd->bidi_override.push_back(Vector3i(r.x, r.y, DIRECTION_INHERITED));
  3902. }
  3903. }
  3904. invalidate(sd, false);
  3905. }
  3906. void TextServerAdvanced::_shaped_text_set_orientation(const RID &p_shaped, TextServer::Orientation p_orientation) {
  3907. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3908. ERR_FAIL_NULL(sd);
  3909. MutexLock lock(sd->mutex);
  3910. if (sd->orientation != p_orientation) {
  3911. if (sd->parent != RID()) {
  3912. full_copy(sd);
  3913. }
  3914. sd->orientation = p_orientation;
  3915. invalidate(sd, false);
  3916. }
  3917. }
  3918. void TextServerAdvanced::_shaped_text_set_preserve_invalid(const RID &p_shaped, bool p_enabled) {
  3919. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3920. ERR_FAIL_NULL(sd);
  3921. MutexLock lock(sd->mutex);
  3922. ERR_FAIL_COND(sd->parent != RID());
  3923. if (sd->preserve_invalid != p_enabled) {
  3924. sd->preserve_invalid = p_enabled;
  3925. invalidate(sd, false);
  3926. }
  3927. }
  3928. bool TextServerAdvanced::_shaped_text_get_preserve_invalid(const RID &p_shaped) const {
  3929. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3930. ERR_FAIL_NULL_V(sd, false);
  3931. MutexLock lock(sd->mutex);
  3932. return sd->preserve_invalid;
  3933. }
  3934. void TextServerAdvanced::_shaped_text_set_preserve_control(const RID &p_shaped, bool p_enabled) {
  3935. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3936. ERR_FAIL_NULL(sd);
  3937. MutexLock lock(sd->mutex);
  3938. if (sd->preserve_control != p_enabled) {
  3939. if (sd->parent != RID()) {
  3940. full_copy(sd);
  3941. }
  3942. sd->preserve_control = p_enabled;
  3943. invalidate(sd, false);
  3944. }
  3945. }
  3946. bool TextServerAdvanced::_shaped_text_get_preserve_control(const RID &p_shaped) const {
  3947. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3948. ERR_FAIL_NULL_V(sd, false);
  3949. MutexLock lock(sd->mutex);
  3950. return sd->preserve_control;
  3951. }
  3952. void TextServerAdvanced::_shaped_text_set_spacing(const RID &p_shaped, SpacingType p_spacing, int64_t p_value) {
  3953. ERR_FAIL_INDEX((int)p_spacing, 4);
  3954. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3955. ERR_FAIL_NULL(sd);
  3956. MutexLock lock(sd->mutex);
  3957. if (sd->extra_spacing[p_spacing] != p_value) {
  3958. if (sd->parent != RID()) {
  3959. full_copy(sd);
  3960. }
  3961. sd->extra_spacing[p_spacing] = p_value;
  3962. invalidate(sd, false);
  3963. }
  3964. }
  3965. int64_t TextServerAdvanced::_shaped_text_get_spacing(const RID &p_shaped, SpacingType p_spacing) const {
  3966. ERR_FAIL_INDEX_V((int)p_spacing, 4, 0);
  3967. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3968. ERR_FAIL_NULL_V(sd, 0);
  3969. MutexLock lock(sd->mutex);
  3970. return sd->extra_spacing[p_spacing];
  3971. }
  3972. TextServer::Orientation TextServerAdvanced::_shaped_text_get_orientation(const RID &p_shaped) const {
  3973. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3974. ERR_FAIL_NULL_V(sd, TextServer::ORIENTATION_HORIZONTAL);
  3975. MutexLock lock(sd->mutex);
  3976. return sd->orientation;
  3977. }
  3978. int64_t TextServerAdvanced::_shaped_get_span_count(const RID &p_shaped) const {
  3979. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3980. ERR_FAIL_NULL_V(sd, 0);
  3981. if (sd->parent != RID()) {
  3982. return sd->last_span - sd->first_span + 1;
  3983. } else {
  3984. return sd->spans.size();
  3985. }
  3986. }
  3987. Variant TextServerAdvanced::_shaped_get_span_meta(const RID &p_shaped, int64_t p_index) const {
  3988. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  3989. ERR_FAIL_NULL_V(sd, Variant());
  3990. if (sd->parent != RID()) {
  3991. ShapedTextDataAdvanced *parent_sd = shaped_owner.get_or_null(sd->parent);
  3992. ERR_FAIL_COND_V(!parent_sd->valid.is_set(), Variant());
  3993. ERR_FAIL_INDEX_V(p_index + sd->first_span, parent_sd->spans.size(), Variant());
  3994. return parent_sd->spans[p_index + sd->first_span].meta;
  3995. } else {
  3996. ERR_FAIL_INDEX_V(p_index, sd->spans.size(), Variant());
  3997. return sd->spans[p_index].meta;
  3998. }
  3999. }
  4000. Variant TextServerAdvanced::_shaped_get_span_embedded_object(const RID &p_shaped, int64_t p_index) const {
  4001. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4002. ERR_FAIL_NULL_V(sd, Variant());
  4003. if (sd->parent != RID()) {
  4004. ShapedTextDataAdvanced *parent_sd = shaped_owner.get_or_null(sd->parent);
  4005. ERR_FAIL_COND_V(!parent_sd->valid.is_set(), Variant());
  4006. ERR_FAIL_INDEX_V(p_index + sd->first_span, parent_sd->spans.size(), Variant());
  4007. return parent_sd->spans[p_index + sd->first_span].embedded_key;
  4008. } else {
  4009. ERR_FAIL_INDEX_V(p_index, sd->spans.size(), Variant());
  4010. return sd->spans[p_index].embedded_key;
  4011. }
  4012. }
  4013. String TextServerAdvanced::_shaped_get_span_text(const RID &p_shaped, int64_t p_index) const {
  4014. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4015. ERR_FAIL_NULL_V(sd, String());
  4016. ShapedTextDataAdvanced *span_sd = sd;
  4017. if (sd->parent.is_valid()) {
  4018. span_sd = shaped_owner.get_or_null(sd->parent);
  4019. ERR_FAIL_NULL_V(span_sd, String());
  4020. }
  4021. ERR_FAIL_INDEX_V(p_index, span_sd->spans.size(), String());
  4022. return span_sd->text.substr(span_sd->spans[p_index].start, span_sd->spans[p_index].end - span_sd->spans[p_index].start);
  4023. }
  4024. Variant TextServerAdvanced::_shaped_get_span_object(const RID &p_shaped, int64_t p_index) const {
  4025. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4026. ERR_FAIL_NULL_V(sd, Variant());
  4027. ShapedTextDataAdvanced *span_sd = sd;
  4028. if (sd->parent.is_valid()) {
  4029. span_sd = shaped_owner.get_or_null(sd->parent);
  4030. ERR_FAIL_NULL_V(span_sd, Variant());
  4031. }
  4032. ERR_FAIL_INDEX_V(p_index, span_sd->spans.size(), Variant());
  4033. return span_sd->spans[p_index].embedded_key;
  4034. }
  4035. void TextServerAdvanced::_generate_runs(ShapedTextDataAdvanced *p_sd) const {
  4036. ERR_FAIL_NULL(p_sd);
  4037. p_sd->runs.clear();
  4038. ShapedTextDataAdvanced *span_sd = p_sd;
  4039. if (p_sd->parent.is_valid()) {
  4040. span_sd = shaped_owner.get_or_null(p_sd->parent);
  4041. ERR_FAIL_NULL(span_sd);
  4042. }
  4043. int sd_size = p_sd->glyphs.size();
  4044. const Glyph *sd_gl = p_sd->glyphs.ptr();
  4045. int span_count = span_sd->spans.size();
  4046. int span = -1;
  4047. int span_start = -1;
  4048. int span_end = -1;
  4049. TextRun run;
  4050. for (int i = 0; i < sd_size; i += sd_gl[i].count) {
  4051. const Glyph &gl = sd_gl[i];
  4052. if (gl.start < 0 || gl.end < 0) {
  4053. continue;
  4054. }
  4055. if (gl.start < span_start || gl.start >= span_end) {
  4056. span = -1;
  4057. span_start = -1;
  4058. span_end = -1;
  4059. for (int j = 0; j < span_count; j++) {
  4060. if (gl.start >= span_sd->spans[j].start && gl.end <= span_sd->spans[j].end) {
  4061. span = j;
  4062. span_start = span_sd->spans[j].start;
  4063. span_end = span_sd->spans[j].end;
  4064. break;
  4065. }
  4066. }
  4067. }
  4068. if (run.font_rid != gl.font_rid || run.font_size != gl.font_size || run.span_index != span || run.rtl != bool(gl.flags & GRAPHEME_IS_RTL)) {
  4069. if (run.span_index >= 0) {
  4070. p_sd->runs.push_back(run);
  4071. }
  4072. run.range = Vector2i(gl.start, gl.end);
  4073. run.font_rid = gl.font_rid;
  4074. run.font_size = gl.font_size;
  4075. run.rtl = bool(gl.flags & GRAPHEME_IS_RTL);
  4076. run.span_index = span;
  4077. }
  4078. run.range.x = MIN(run.range.x, gl.start);
  4079. run.range.y = MAX(run.range.y, gl.end);
  4080. }
  4081. if (run.span_index >= 0) {
  4082. p_sd->runs.push_back(run);
  4083. }
  4084. p_sd->runs_dirty = false;
  4085. }
  4086. int64_t TextServerAdvanced::_shaped_get_run_count(const RID &p_shaped) const {
  4087. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4088. ERR_FAIL_NULL_V(sd, 0);
  4089. MutexLock lock(sd->mutex);
  4090. if (!sd->valid.is_set()) {
  4091. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  4092. }
  4093. if (sd->runs_dirty) {
  4094. _generate_runs(sd);
  4095. }
  4096. return sd->runs.size();
  4097. }
  4098. String TextServerAdvanced::_shaped_get_run_text(const RID &p_shaped, int64_t p_index) const {
  4099. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4100. ERR_FAIL_NULL_V(sd, String());
  4101. MutexLock lock(sd->mutex);
  4102. if (!sd->valid.is_set()) {
  4103. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  4104. }
  4105. if (sd->runs_dirty) {
  4106. _generate_runs(sd);
  4107. }
  4108. ERR_FAIL_INDEX_V(p_index, sd->runs.size(), String());
  4109. return sd->text.substr(sd->runs[p_index].range.x - sd->start, sd->runs[p_index].range.y - sd->runs[p_index].range.x);
  4110. }
  4111. Vector2i TextServerAdvanced::_shaped_get_run_range(const RID &p_shaped, int64_t p_index) const {
  4112. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4113. ERR_FAIL_NULL_V(sd, Vector2i());
  4114. MutexLock lock(sd->mutex);
  4115. if (!sd->valid.is_set()) {
  4116. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  4117. }
  4118. if (sd->runs_dirty) {
  4119. _generate_runs(sd);
  4120. }
  4121. ERR_FAIL_INDEX_V(p_index, sd->runs.size(), Vector2i());
  4122. return sd->runs[p_index].range;
  4123. }
  4124. RID TextServerAdvanced::_shaped_get_run_font_rid(const RID &p_shaped, int64_t p_index) const {
  4125. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4126. ERR_FAIL_NULL_V(sd, RID());
  4127. MutexLock lock(sd->mutex);
  4128. if (!sd->valid.is_set()) {
  4129. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  4130. }
  4131. if (sd->runs_dirty) {
  4132. _generate_runs(sd);
  4133. }
  4134. ERR_FAIL_INDEX_V(p_index, sd->runs.size(), RID());
  4135. return sd->runs[p_index].font_rid;
  4136. }
  4137. int TextServerAdvanced::_shaped_get_run_font_size(const RID &p_shaped, int64_t p_index) const {
  4138. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4139. ERR_FAIL_NULL_V(sd, 0);
  4140. MutexLock lock(sd->mutex);
  4141. if (!sd->valid.is_set()) {
  4142. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  4143. }
  4144. if (sd->runs_dirty) {
  4145. _generate_runs(sd);
  4146. }
  4147. ERR_FAIL_INDEX_V(p_index, sd->runs.size(), 0);
  4148. return sd->runs[p_index].font_size;
  4149. }
  4150. String TextServerAdvanced::_shaped_get_run_language(const RID &p_shaped, int64_t p_index) const {
  4151. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4152. ERR_FAIL_NULL_V(sd, String());
  4153. MutexLock lock(sd->mutex);
  4154. if (!sd->valid.is_set()) {
  4155. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  4156. }
  4157. if (sd->runs_dirty) {
  4158. _generate_runs(sd);
  4159. }
  4160. ERR_FAIL_INDEX_V(p_index, sd->runs.size(), String());
  4161. int span_idx = sd->runs[p_index].span_index;
  4162. ShapedTextDataAdvanced *span_sd = sd;
  4163. if (sd->parent.is_valid()) {
  4164. span_sd = shaped_owner.get_or_null(sd->parent);
  4165. ERR_FAIL_NULL_V(span_sd, String());
  4166. }
  4167. ERR_FAIL_INDEX_V(span_idx, span_sd->spans.size(), String());
  4168. return span_sd->spans[span_idx].language;
  4169. }
  4170. TextServer::Direction TextServerAdvanced::_shaped_get_run_direction(const RID &p_shaped, int64_t p_index) const {
  4171. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4172. ERR_FAIL_NULL_V(sd, TextServer::DIRECTION_LTR);
  4173. MutexLock lock(sd->mutex);
  4174. if (!sd->valid.is_set()) {
  4175. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  4176. }
  4177. if (sd->runs_dirty) {
  4178. _generate_runs(sd);
  4179. }
  4180. ERR_FAIL_INDEX_V(p_index, sd->runs.size(), TextServer::DIRECTION_LTR);
  4181. return sd->runs[p_index].rtl ? TextServer::DIRECTION_RTL : TextServer::DIRECTION_LTR;
  4182. }
  4183. Variant TextServerAdvanced::_shaped_get_run_object(const RID &p_shaped, int64_t p_index) const {
  4184. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4185. ERR_FAIL_NULL_V(sd, Variant());
  4186. MutexLock lock(sd->mutex);
  4187. if (!sd->valid.is_set()) {
  4188. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  4189. }
  4190. if (sd->runs_dirty) {
  4191. _generate_runs(sd);
  4192. }
  4193. ERR_FAIL_INDEX_V(p_index, sd->runs.size(), Variant());
  4194. int span_idx = sd->runs[p_index].span_index;
  4195. ShapedTextDataAdvanced *span_sd = sd;
  4196. if (sd->parent.is_valid()) {
  4197. span_sd = shaped_owner.get_or_null(sd->parent);
  4198. ERR_FAIL_NULL_V(span_sd, Variant());
  4199. }
  4200. ERR_FAIL_INDEX_V(span_idx, span_sd->spans.size(), Variant());
  4201. return span_sd->spans[span_idx].embedded_key;
  4202. }
  4203. void TextServerAdvanced::_shaped_set_span_update_font(const RID &p_shaped, int64_t p_index, const TypedArray<RID> &p_fonts, int64_t p_size, const Dictionary &p_opentype_features) {
  4204. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4205. ERR_FAIL_NULL(sd);
  4206. if (sd->parent != RID()) {
  4207. full_copy(sd);
  4208. }
  4209. ERR_FAIL_INDEX(p_index, sd->spans.size());
  4210. ShapedTextDataAdvanced::Span &span = sd->spans.ptrw()[p_index];
  4211. span.fonts = p_fonts;
  4212. span.font_size = p_size;
  4213. span.features = p_opentype_features;
  4214. invalidate(sd, false);
  4215. }
  4216. bool TextServerAdvanced::_shaped_text_add_string(const RID &p_shaped, const String &p_text, const TypedArray<RID> &p_fonts, int64_t p_size, const Dictionary &p_opentype_features, const String &p_language, const Variant &p_meta) {
  4217. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4218. ERR_FAIL_NULL_V(sd, false);
  4219. ERR_FAIL_COND_V(p_size <= 0, false);
  4220. MutexLock lock(sd->mutex);
  4221. for (int i = 0; i < p_fonts.size(); i++) {
  4222. ERR_FAIL_NULL_V(_get_font_data(p_fonts[i]), false);
  4223. }
  4224. if (p_text.is_empty()) {
  4225. return true;
  4226. }
  4227. if (sd->parent != RID()) {
  4228. full_copy(sd);
  4229. }
  4230. ShapedTextDataAdvanced::Span span;
  4231. span.start = sd->text.length();
  4232. span.end = span.start + p_text.length();
  4233. span.fonts = p_fonts; // Do not pre-sort, spans will be divided to subruns later.
  4234. span.font_size = p_size;
  4235. span.language = p_language;
  4236. span.features = p_opentype_features;
  4237. span.meta = p_meta;
  4238. sd->spans.push_back(span);
  4239. sd->text = sd->text + p_text;
  4240. sd->end += p_text.length();
  4241. invalidate(sd, true);
  4242. return true;
  4243. }
  4244. bool TextServerAdvanced::_shaped_text_add_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align, int64_t p_length, double p_baseline) {
  4245. _THREAD_SAFE_METHOD_
  4246. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4247. ERR_FAIL_NULL_V(sd, false);
  4248. ERR_FAIL_COND_V(p_key == Variant(), false);
  4249. ERR_FAIL_COND_V(sd->objects.has(p_key), false);
  4250. if (sd->parent != RID()) {
  4251. full_copy(sd);
  4252. }
  4253. ShapedTextDataAdvanced::Span span;
  4254. span.start = sd->start + sd->text.length();
  4255. span.end = span.start + p_length;
  4256. span.embedded_key = p_key;
  4257. ShapedTextDataAdvanced::EmbeddedObject obj;
  4258. obj.inline_align = p_inline_align;
  4259. obj.rect.size = p_size;
  4260. obj.start = span.start;
  4261. obj.end = span.end;
  4262. obj.baseline = p_baseline;
  4263. sd->spans.push_back(span);
  4264. sd->text = sd->text + String::chr(0xfffc).repeat(p_length);
  4265. sd->end += p_length;
  4266. sd->objects[p_key] = obj;
  4267. invalidate(sd, true);
  4268. return true;
  4269. }
  4270. String TextServerAdvanced::_shaped_get_text(const RID &p_shaped) const {
  4271. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4272. ERR_FAIL_NULL_V(sd, String());
  4273. return sd->text;
  4274. }
  4275. bool TextServerAdvanced::_shaped_text_resize_object(const RID &p_shaped, const Variant &p_key, const Size2 &p_size, InlineAlignment p_inline_align, double p_baseline) {
  4276. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4277. ERR_FAIL_NULL_V(sd, false);
  4278. MutexLock lock(sd->mutex);
  4279. ERR_FAIL_COND_V(!sd->objects.has(p_key), false);
  4280. sd->objects[p_key].rect.size = p_size;
  4281. sd->objects[p_key].inline_align = p_inline_align;
  4282. sd->objects[p_key].baseline = p_baseline;
  4283. if (sd->valid.is_set()) {
  4284. // Recalc string metrics.
  4285. sd->ascent = 0;
  4286. sd->descent = 0;
  4287. sd->width = 0;
  4288. sd->upos = 0;
  4289. sd->uthk = 0;
  4290. Vector<ShapedTextDataAdvanced::Span> &spans = sd->spans;
  4291. if (sd->parent != RID()) {
  4292. ShapedTextDataAdvanced *parent_sd = shaped_owner.get_or_null(sd->parent);
  4293. ERR_FAIL_COND_V(!parent_sd->valid.is_set(), false);
  4294. spans = parent_sd->spans;
  4295. }
  4296. int sd_size = sd->glyphs.size();
  4297. int span_size = spans.size();
  4298. const char32_t *ch = sd->text.ptr();
  4299. for (int i = 0; i < sd_size; i++) {
  4300. Glyph gl = sd->glyphs[i];
  4301. Variant key;
  4302. if ((gl.flags & GRAPHEME_IS_EMBEDDED_OBJECT) == GRAPHEME_IS_EMBEDDED_OBJECT && gl.span_index + sd->first_span >= 0 && gl.span_index + sd->first_span < span_size) {
  4303. key = spans[gl.span_index + sd->first_span].embedded_key;
  4304. }
  4305. if (key != Variant()) {
  4306. if (sd->orientation == ORIENTATION_HORIZONTAL) {
  4307. sd->objects[key].rect.position.x = sd->width;
  4308. sd->width += sd->objects[key].rect.size.x;
  4309. sd->glyphs[i].advance = sd->objects[key].rect.size.x;
  4310. } else {
  4311. sd->objects[key].rect.position.y = sd->width;
  4312. sd->width += sd->objects[key].rect.size.y;
  4313. sd->glyphs[i].advance = sd->objects[key].rect.size.y;
  4314. }
  4315. } else {
  4316. if (gl.font_rid.is_valid()) {
  4317. if (sd->orientation == ORIENTATION_HORIZONTAL) {
  4318. sd->ascent = MAX(sd->ascent, MAX(_font_get_ascent(gl.font_rid, gl.font_size) + _font_get_spacing(gl.font_rid, SPACING_TOP), -gl.y_off));
  4319. sd->descent = MAX(sd->descent, MAX(_font_get_descent(gl.font_rid, gl.font_size) + _font_get_spacing(gl.font_rid, SPACING_BOTTOM), gl.y_off));
  4320. } else {
  4321. sd->ascent = MAX(sd->ascent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5));
  4322. sd->descent = MAX(sd->descent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5));
  4323. }
  4324. sd->upos = MAX(sd->upos, _font_get_underline_position(gl.font_rid, gl.font_size));
  4325. sd->uthk = MAX(sd->uthk, _font_get_underline_thickness(gl.font_rid, gl.font_size));
  4326. } else if (sd->preserve_invalid || (sd->preserve_control && is_control(ch[gl.start - sd->start]))) {
  4327. // Glyph not found, replace with hex code box.
  4328. if (sd->orientation == ORIENTATION_HORIZONTAL) {
  4329. sd->ascent = MAX(sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.85);
  4330. sd->descent = MAX(sd->descent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.15);
  4331. } else {
  4332. sd->ascent = MAX(sd->ascent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5));
  4333. sd->descent = MAX(sd->descent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5));
  4334. }
  4335. }
  4336. sd->width += gl.advance * gl.repeat;
  4337. }
  4338. }
  4339. sd->sort_valid = false;
  4340. sd->glyphs_logical.clear();
  4341. _realign(sd);
  4342. }
  4343. return true;
  4344. }
  4345. void TextServerAdvanced::_realign(ShapedTextDataAdvanced *p_sd) const {
  4346. // Align embedded objects to baseline.
  4347. double full_ascent = p_sd->ascent;
  4348. double full_descent = p_sd->descent;
  4349. for (KeyValue<Variant, ShapedTextDataAdvanced::EmbeddedObject> &E : p_sd->objects) {
  4350. if ((E.value.start >= p_sd->start) && (E.value.start < p_sd->end)) {
  4351. if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  4352. switch (E.value.inline_align & INLINE_ALIGNMENT_TEXT_MASK) {
  4353. case INLINE_ALIGNMENT_TO_TOP: {
  4354. E.value.rect.position.y = -p_sd->ascent;
  4355. } break;
  4356. case INLINE_ALIGNMENT_TO_CENTER: {
  4357. E.value.rect.position.y = (-p_sd->ascent + p_sd->descent) / 2;
  4358. } break;
  4359. case INLINE_ALIGNMENT_TO_BASELINE: {
  4360. E.value.rect.position.y = 0;
  4361. } break;
  4362. case INLINE_ALIGNMENT_TO_BOTTOM: {
  4363. E.value.rect.position.y = p_sd->descent;
  4364. } break;
  4365. }
  4366. switch (E.value.inline_align & INLINE_ALIGNMENT_IMAGE_MASK) {
  4367. case INLINE_ALIGNMENT_BOTTOM_TO: {
  4368. E.value.rect.position.y -= E.value.rect.size.y;
  4369. } break;
  4370. case INLINE_ALIGNMENT_CENTER_TO: {
  4371. E.value.rect.position.y -= E.value.rect.size.y / 2;
  4372. } break;
  4373. case INLINE_ALIGNMENT_BASELINE_TO: {
  4374. E.value.rect.position.y -= E.value.baseline;
  4375. } break;
  4376. case INLINE_ALIGNMENT_TOP_TO: {
  4377. // NOP
  4378. } break;
  4379. }
  4380. full_ascent = MAX(full_ascent, -E.value.rect.position.y);
  4381. full_descent = MAX(full_descent, E.value.rect.position.y + E.value.rect.size.y);
  4382. } else {
  4383. switch (E.value.inline_align & INLINE_ALIGNMENT_TEXT_MASK) {
  4384. case INLINE_ALIGNMENT_TO_TOP: {
  4385. E.value.rect.position.x = -p_sd->ascent;
  4386. } break;
  4387. case INLINE_ALIGNMENT_TO_CENTER: {
  4388. E.value.rect.position.x = (-p_sd->ascent + p_sd->descent) / 2;
  4389. } break;
  4390. case INLINE_ALIGNMENT_TO_BASELINE: {
  4391. E.value.rect.position.x = 0;
  4392. } break;
  4393. case INLINE_ALIGNMENT_TO_BOTTOM: {
  4394. E.value.rect.position.x = p_sd->descent;
  4395. } break;
  4396. }
  4397. switch (E.value.inline_align & INLINE_ALIGNMENT_IMAGE_MASK) {
  4398. case INLINE_ALIGNMENT_BOTTOM_TO: {
  4399. E.value.rect.position.x -= E.value.rect.size.x;
  4400. } break;
  4401. case INLINE_ALIGNMENT_CENTER_TO: {
  4402. E.value.rect.position.x -= E.value.rect.size.x / 2;
  4403. } break;
  4404. case INLINE_ALIGNMENT_BASELINE_TO: {
  4405. E.value.rect.position.x -= E.value.baseline;
  4406. } break;
  4407. case INLINE_ALIGNMENT_TOP_TO: {
  4408. // NOP
  4409. } break;
  4410. }
  4411. full_ascent = MAX(full_ascent, -E.value.rect.position.x);
  4412. full_descent = MAX(full_descent, E.value.rect.position.x + E.value.rect.size.x);
  4413. }
  4414. }
  4415. }
  4416. p_sd->ascent = full_ascent;
  4417. p_sd->descent = full_descent;
  4418. }
  4419. RID TextServerAdvanced::_shaped_text_substr(const RID &p_shaped, int64_t p_start, int64_t p_length) const {
  4420. _THREAD_SAFE_METHOD_
  4421. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4422. ERR_FAIL_NULL_V(sd, RID());
  4423. MutexLock lock(sd->mutex);
  4424. if (sd->parent != RID()) {
  4425. return _shaped_text_substr(sd->parent, p_start, p_length);
  4426. }
  4427. if (!sd->valid.is_set()) {
  4428. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  4429. }
  4430. ERR_FAIL_COND_V(p_start < 0 || p_length < 0, RID());
  4431. ERR_FAIL_COND_V(sd->start > p_start || sd->end < p_start, RID());
  4432. ERR_FAIL_COND_V(sd->end < p_start + p_length, RID());
  4433. ShapedTextDataAdvanced *new_sd = memnew(ShapedTextDataAdvanced);
  4434. new_sd->parent = p_shaped;
  4435. new_sd->start = p_start;
  4436. new_sd->end = p_start + p_length;
  4437. new_sd->orientation = sd->orientation;
  4438. new_sd->direction = sd->direction;
  4439. new_sd->custom_punct = sd->custom_punct;
  4440. new_sd->para_direction = sd->para_direction;
  4441. new_sd->base_para_direction = sd->base_para_direction;
  4442. for (int i = 0; i < TextServer::SPACING_MAX; i++) {
  4443. new_sd->extra_spacing[i] = sd->extra_spacing[i];
  4444. }
  4445. if (!_shape_substr(new_sd, sd, p_start, p_length)) {
  4446. memdelete(new_sd);
  4447. return RID();
  4448. }
  4449. return shaped_owner.make_rid(new_sd);
  4450. }
  4451. bool TextServerAdvanced::_shape_substr(ShapedTextDataAdvanced *p_new_sd, const ShapedTextDataAdvanced *p_sd, int64_t p_start, int64_t p_length) const {
  4452. if (p_new_sd->valid.is_set()) {
  4453. return true;
  4454. }
  4455. p_new_sd->hb_buffer = hb_buffer_create();
  4456. p_new_sd->line_breaks_valid = p_sd->line_breaks_valid;
  4457. p_new_sd->justification_ops_valid = p_sd->justification_ops_valid;
  4458. p_new_sd->sort_valid = false;
  4459. p_new_sd->upos = p_sd->upos;
  4460. p_new_sd->uthk = p_sd->uthk;
  4461. p_new_sd->runs.clear();
  4462. p_new_sd->runs_dirty = true;
  4463. if (p_length > 0) {
  4464. p_new_sd->text = p_sd->text.substr(p_start - p_sd->start, p_length);
  4465. p_new_sd->utf16 = p_new_sd->text.utf16();
  4466. p_new_sd->script_iter = memnew(ScriptIterator(p_new_sd->text, 0, p_new_sd->text.length()));
  4467. int span_size = p_sd->spans.size();
  4468. p_new_sd->first_span = 0;
  4469. p_new_sd->last_span = span_size - 1;
  4470. for (int i = 0; i < span_size; i++) {
  4471. const ShapedTextDataAdvanced::Span &span = p_sd->spans[i];
  4472. if (span.end <= p_start) {
  4473. p_new_sd->first_span = i + 1;
  4474. } else if (span.start >= p_start + p_length) {
  4475. p_new_sd->last_span = i - 1;
  4476. break;
  4477. }
  4478. }
  4479. Vector<Vector3i> bidi_ranges;
  4480. if (p_sd->bidi_override.is_empty()) {
  4481. bidi_ranges.push_back(Vector3i(p_sd->start, p_sd->end, DIRECTION_INHERITED));
  4482. } else {
  4483. bidi_ranges = p_sd->bidi_override;
  4484. }
  4485. int sd_size = p_sd->glyphs.size();
  4486. const Glyph *sd_glyphs = p_sd->glyphs.ptr();
  4487. const char32_t *ch = p_sd->text.ptr();
  4488. for (int ov = 0; ov < bidi_ranges.size(); ov++) {
  4489. UErrorCode err = U_ZERO_ERROR;
  4490. if (bidi_ranges[ov].x >= p_start + p_length || bidi_ranges[ov].y <= p_start) {
  4491. continue;
  4492. }
  4493. int ov_start = _convert_pos_inv(p_sd, bidi_ranges[ov].x);
  4494. int start = MAX(0, _convert_pos_inv(p_sd, p_start) - ov_start);
  4495. int end = MIN(_convert_pos_inv(p_sd, p_start + p_length), _convert_pos_inv(p_sd, bidi_ranges[ov].y)) - ov_start;
  4496. ERR_FAIL_COND_V_MSG((start < 0 || end - start > p_new_sd->utf16.length()), false, "Invalid BiDi override range.");
  4497. // Create temporary line bidi & shape.
  4498. UBiDi *bidi_iter = nullptr;
  4499. if (p_sd->bidi_iter[ov]) {
  4500. bidi_iter = ubidi_openSized(end - start, 0, &err);
  4501. if (U_SUCCESS(err)) {
  4502. ubidi_setLine(p_sd->bidi_iter[ov], start, end, bidi_iter, &err);
  4503. if (U_FAILURE(err)) {
  4504. // Line BiDi failed (string contains incompatible control characters), try full paragraph BiDi instead.
  4505. err = U_ZERO_ERROR;
  4506. const UChar *data = p_sd->utf16.get_data();
  4507. switch (static_cast<TextServer::Direction>(bidi_ranges[ov].z)) {
  4508. case DIRECTION_LTR: {
  4509. ubidi_setPara(bidi_iter, data + start, end - start, UBIDI_LTR, nullptr, &err);
  4510. } break;
  4511. case DIRECTION_RTL: {
  4512. ubidi_setPara(bidi_iter, data + start, end - start, UBIDI_RTL, nullptr, &err);
  4513. } break;
  4514. case DIRECTION_INHERITED: {
  4515. ubidi_setPara(bidi_iter, data + start, end - start, p_sd->base_para_direction, nullptr, &err);
  4516. } break;
  4517. case DIRECTION_AUTO: {
  4518. UBiDiDirection direction = ubidi_getBaseDirection(data + start, end - start);
  4519. if (direction != UBIDI_NEUTRAL) {
  4520. ubidi_setPara(bidi_iter, data + start, end - start, direction, nullptr, &err);
  4521. } else {
  4522. ubidi_setPara(bidi_iter, data + start, end - start, p_sd->base_para_direction, nullptr, &err);
  4523. }
  4524. } break;
  4525. }
  4526. if (U_FAILURE(err)) {
  4527. ubidi_close(bidi_iter);
  4528. bidi_iter = nullptr;
  4529. ERR_PRINT(vformat("BiDi reordering for the line failed: %s", u_errorName(err)));
  4530. }
  4531. }
  4532. } else {
  4533. bidi_iter = nullptr;
  4534. ERR_PRINT(vformat("BiDi iterator allocation for the line failed: %s", u_errorName(err)));
  4535. }
  4536. }
  4537. p_new_sd->bidi_iter.push_back(bidi_iter);
  4538. err = U_ZERO_ERROR;
  4539. int bidi_run_count = 1;
  4540. if (bidi_iter) {
  4541. bidi_run_count = ubidi_countRuns(bidi_iter, &err);
  4542. if (U_FAILURE(err)) {
  4543. ERR_PRINT(u_errorName(err));
  4544. }
  4545. }
  4546. for (int i = 0; i < bidi_run_count; i++) {
  4547. int32_t _bidi_run_start = 0;
  4548. int32_t _bidi_run_length = end - start;
  4549. if (bidi_iter) {
  4550. ubidi_getVisualRun(bidi_iter, i, &_bidi_run_start, &_bidi_run_length);
  4551. }
  4552. int32_t bidi_run_start = _convert_pos(p_sd, ov_start + start + _bidi_run_start);
  4553. int32_t bidi_run_end = _convert_pos(p_sd, ov_start + start + _bidi_run_start + _bidi_run_length);
  4554. for (int j = 0; j < sd_size; j++) {
  4555. int col_key_off = (sd_glyphs[j].start == sd_glyphs[j].end) ? 1 : 0;
  4556. if ((sd_glyphs[j].start >= bidi_run_start) && (sd_glyphs[j].end <= bidi_run_end - col_key_off)) {
  4557. // Copy glyphs.
  4558. Glyph gl = sd_glyphs[j];
  4559. if (gl.span_index >= 0) {
  4560. gl.span_index -= p_new_sd->first_span;
  4561. }
  4562. if (gl.end == p_start + p_length && ((gl.flags & GRAPHEME_IS_SOFT_HYPHEN) == GRAPHEME_IS_SOFT_HYPHEN)) {
  4563. uint32_t index = font_get_glyph_index(gl.font_rid, gl.font_size, 0x00ad, 0);
  4564. if (index == 0) { // Try other fonts in the span.
  4565. const ShapedTextDataAdvanced::Span &span = p_sd->spans[gl.span_index + p_new_sd->first_span];
  4566. for (int k = 0; k < span.fonts.size(); k++) {
  4567. if (span.fonts[k] != gl.font_rid) {
  4568. index = font_get_glyph_index(span.fonts[k], gl.font_size, 0x00ad, 0);
  4569. if (index != 0) {
  4570. gl.font_rid = span.fonts[k];
  4571. break;
  4572. }
  4573. }
  4574. }
  4575. }
  4576. if (index == 0 && gl.font_rid.is_valid() && OS::get_singleton()->has_feature("system_fonts") && _font_is_allow_system_fallback(gl.font_rid)) { // Try system font fallback.
  4577. const char32_t u32str[] = { 0x00ad, 0 };
  4578. RID rid = const_cast<TextServerAdvanced *>(this)->_find_sys_font_for_text(gl.font_rid, String(), String(), u32str);
  4579. if (rid.is_valid()) {
  4580. index = font_get_glyph_index(rid, gl.font_size, 0x00ad, 0);
  4581. if (index != 0) {
  4582. gl.font_rid = rid;
  4583. }
  4584. }
  4585. }
  4586. float w = font_get_glyph_advance(gl.font_rid, gl.font_size, index)[(p_new_sd->orientation == ORIENTATION_HORIZONTAL) ? 0 : 1];
  4587. gl.index = index;
  4588. gl.advance = w;
  4589. }
  4590. if ((gl.flags & GRAPHEME_IS_EMBEDDED_OBJECT) == GRAPHEME_IS_EMBEDDED_OBJECT && gl.span_index + p_new_sd->first_span >= 0 && gl.span_index + p_new_sd->first_span < span_size) {
  4591. Variant key = p_sd->spans[gl.span_index + p_new_sd->first_span].embedded_key;
  4592. if (key != Variant()) {
  4593. ShapedTextDataAdvanced::EmbeddedObject obj = p_sd->objects[key];
  4594. if (p_new_sd->orientation == ORIENTATION_HORIZONTAL) {
  4595. obj.rect.position.x = p_new_sd->width;
  4596. p_new_sd->width += obj.rect.size.x;
  4597. } else {
  4598. obj.rect.position.y = p_new_sd->width;
  4599. p_new_sd->width += obj.rect.size.y;
  4600. }
  4601. p_new_sd->objects[key] = obj;
  4602. }
  4603. } else {
  4604. if (gl.font_rid.is_valid()) {
  4605. if (p_new_sd->orientation == ORIENTATION_HORIZONTAL) {
  4606. p_new_sd->ascent = MAX(p_new_sd->ascent, MAX(_font_get_ascent(gl.font_rid, gl.font_size) + _font_get_spacing(gl.font_rid, SPACING_TOP), -gl.y_off));
  4607. p_new_sd->descent = MAX(p_new_sd->descent, MAX(_font_get_descent(gl.font_rid, gl.font_size) + _font_get_spacing(gl.font_rid, SPACING_BOTTOM), gl.y_off));
  4608. } else {
  4609. p_new_sd->ascent = MAX(p_new_sd->ascent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5));
  4610. p_new_sd->descent = MAX(p_new_sd->descent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5));
  4611. }
  4612. } else if (p_new_sd->preserve_invalid || (p_new_sd->preserve_control && is_control(ch[gl.start - p_sd->start]))) {
  4613. // Glyph not found, replace with hex code box.
  4614. if (p_new_sd->orientation == ORIENTATION_HORIZONTAL) {
  4615. p_new_sd->ascent = MAX(p_new_sd->ascent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.85);
  4616. p_new_sd->descent = MAX(p_new_sd->descent, get_hex_code_box_size(gl.font_size, gl.index).y * 0.15);
  4617. } else {
  4618. p_new_sd->ascent = MAX(p_new_sd->ascent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5));
  4619. p_new_sd->descent = MAX(p_new_sd->descent, Math::round(get_hex_code_box_size(gl.font_size, gl.index).x * 0.5));
  4620. }
  4621. }
  4622. p_new_sd->width += gl.advance * gl.repeat;
  4623. }
  4624. p_new_sd->glyphs.push_back(gl);
  4625. }
  4626. }
  4627. }
  4628. }
  4629. _realign(p_new_sd);
  4630. }
  4631. p_new_sd->valid.set();
  4632. return true;
  4633. }
  4634. RID TextServerAdvanced::_shaped_text_get_parent(const RID &p_shaped) const {
  4635. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4636. ERR_FAIL_NULL_V(sd, RID());
  4637. MutexLock lock(sd->mutex);
  4638. return sd->parent;
  4639. }
  4640. double TextServerAdvanced::_shaped_text_fit_to_width(const RID &p_shaped, double p_width, BitField<TextServer::JustificationFlag> p_jst_flags) {
  4641. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4642. ERR_FAIL_NULL_V(sd, 0.0);
  4643. MutexLock lock(sd->mutex);
  4644. if (!sd->valid.is_set()) {
  4645. _shaped_text_shape(p_shaped);
  4646. }
  4647. if (!sd->justification_ops_valid) {
  4648. _shaped_text_update_justification_ops(p_shaped);
  4649. }
  4650. sd->fit_width_minimum_reached = false;
  4651. int start_pos = 0;
  4652. int end_pos = sd->glyphs.size() - 1;
  4653. if (p_jst_flags.has_flag(JUSTIFICATION_AFTER_LAST_TAB)) {
  4654. int start, end, delta;
  4655. if (sd->para_direction == DIRECTION_LTR) {
  4656. start = sd->glyphs.size() - 1;
  4657. end = -1;
  4658. delta = -1;
  4659. } else {
  4660. start = 0;
  4661. end = sd->glyphs.size();
  4662. delta = +1;
  4663. }
  4664. for (int i = start; i != end; i += delta) {
  4665. if ((sd->glyphs[i].flags & GRAPHEME_IS_TAB) == GRAPHEME_IS_TAB) {
  4666. if (sd->para_direction == DIRECTION_LTR) {
  4667. start_pos = i;
  4668. break;
  4669. } else {
  4670. end_pos = i;
  4671. break;
  4672. }
  4673. }
  4674. }
  4675. }
  4676. double justification_width;
  4677. if (p_jst_flags.has_flag(JUSTIFICATION_CONSTRAIN_ELLIPSIS)) {
  4678. if (sd->overrun_trim_data.trim_pos >= 0) {
  4679. if (sd->para_direction == DIRECTION_RTL) {
  4680. start_pos = sd->overrun_trim_data.trim_pos;
  4681. } else {
  4682. end_pos = sd->overrun_trim_data.trim_pos;
  4683. }
  4684. justification_width = sd->width_trimmed;
  4685. } else {
  4686. return Math::ceil(sd->width);
  4687. }
  4688. } else {
  4689. justification_width = sd->width;
  4690. }
  4691. if (p_jst_flags.has_flag(JUSTIFICATION_TRIM_EDGE_SPACES)) {
  4692. // Trim spaces.
  4693. while ((start_pos < end_pos) && ((sd->glyphs[start_pos].flags & GRAPHEME_IS_SOFT_HYPHEN) != GRAPHEME_IS_SOFT_HYPHEN) && ((sd->glyphs[start_pos].flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) {
  4694. justification_width -= sd->glyphs[start_pos].advance * sd->glyphs[start_pos].repeat;
  4695. sd->glyphs[start_pos].advance = 0;
  4696. start_pos += sd->glyphs[start_pos].count;
  4697. }
  4698. while ((start_pos < end_pos) && ((sd->glyphs[end_pos].flags & GRAPHEME_IS_SOFT_HYPHEN) != GRAPHEME_IS_SOFT_HYPHEN) && ((sd->glyphs[end_pos].flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) {
  4699. justification_width -= sd->glyphs[end_pos].advance * sd->glyphs[end_pos].repeat;
  4700. sd->glyphs[end_pos].advance = 0;
  4701. end_pos -= sd->glyphs[end_pos].count;
  4702. }
  4703. } else {
  4704. // Skip breaks, but do not reset size.
  4705. while ((start_pos < end_pos) && ((sd->glyphs[start_pos].flags & GRAPHEME_IS_SOFT_HYPHEN) != GRAPHEME_IS_SOFT_HYPHEN) && ((sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) {
  4706. start_pos += sd->glyphs[start_pos].count;
  4707. }
  4708. while ((start_pos < end_pos) && ((sd->glyphs[end_pos].flags & GRAPHEME_IS_SOFT_HYPHEN) != GRAPHEME_IS_SOFT_HYPHEN) && ((sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) {
  4709. end_pos -= sd->glyphs[end_pos].count;
  4710. }
  4711. }
  4712. int space_count = 0;
  4713. int elongation_count = 0;
  4714. for (int i = start_pos; i <= end_pos; i++) {
  4715. const Glyph &gl = sd->glyphs[i];
  4716. if (gl.count > 0) {
  4717. if ((gl.flags & GRAPHEME_IS_ELONGATION) == GRAPHEME_IS_ELONGATION) {
  4718. if ((i > 0) && ((sd->glyphs[i - 1].flags & GRAPHEME_IS_ELONGATION) != GRAPHEME_IS_ELONGATION)) {
  4719. // Expand once per elongation sequence.
  4720. elongation_count++;
  4721. }
  4722. }
  4723. if ((gl.flags & GRAPHEME_IS_SOFT_HYPHEN) != GRAPHEME_IS_SOFT_HYPHEN && (gl.flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE && (gl.flags & GRAPHEME_IS_PUNCTUATION) != GRAPHEME_IS_PUNCTUATION) {
  4724. space_count++;
  4725. }
  4726. }
  4727. }
  4728. if ((elongation_count > 0) && p_jst_flags.has_flag(JUSTIFICATION_KASHIDA)) {
  4729. double delta_width_per_kashida = (p_width - justification_width) / elongation_count;
  4730. for (int i = start_pos; i <= end_pos; i++) {
  4731. Glyph &gl = sd->glyphs[i];
  4732. if (gl.count > 0) {
  4733. if (((gl.flags & GRAPHEME_IS_ELONGATION) == GRAPHEME_IS_ELONGATION) && (gl.advance > 0)) {
  4734. if ((i > 0) && ((sd->glyphs[i - 1].flags & GRAPHEME_IS_ELONGATION) != GRAPHEME_IS_ELONGATION)) {
  4735. // Expand once per elongation sequence.
  4736. int count = delta_width_per_kashida / gl.advance;
  4737. int prev_count = gl.repeat;
  4738. if ((gl.flags & GRAPHEME_IS_VIRTUAL) == GRAPHEME_IS_VIRTUAL) {
  4739. gl.repeat = CLAMP(count, 0, 255);
  4740. } else {
  4741. gl.repeat = CLAMP(count + 1, 1, 255);
  4742. }
  4743. justification_width += (gl.repeat - prev_count) * gl.advance;
  4744. }
  4745. }
  4746. }
  4747. }
  4748. }
  4749. if ((space_count > 0) && p_jst_flags.has_flag(JUSTIFICATION_WORD_BOUND)) {
  4750. double delta_width_per_space = (p_width - justification_width) / space_count;
  4751. double adv_remain = 0;
  4752. for (int i = start_pos; i <= end_pos; i++) {
  4753. Glyph &gl = sd->glyphs[i];
  4754. if (gl.count > 0) {
  4755. if ((gl.flags & GRAPHEME_IS_SOFT_HYPHEN) != GRAPHEME_IS_SOFT_HYPHEN && (gl.flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE && (gl.flags & GRAPHEME_IS_PUNCTUATION) != GRAPHEME_IS_PUNCTUATION) {
  4756. double old_adv = gl.advance;
  4757. double new_advance;
  4758. if ((gl.flags & GRAPHEME_IS_VIRTUAL) == GRAPHEME_IS_VIRTUAL) {
  4759. new_advance = MAX(gl.advance + delta_width_per_space, 0.0);
  4760. } else {
  4761. new_advance = MAX(gl.advance + delta_width_per_space, 0.1 * gl.font_size);
  4762. }
  4763. gl.advance = new_advance;
  4764. adv_remain += (new_advance - gl.advance);
  4765. if (adv_remain >= 1.0) {
  4766. gl.advance++;
  4767. adv_remain -= 1.0;
  4768. } else if (adv_remain <= -1.0) {
  4769. gl.advance = MAX(gl.advance - 1, 0);
  4770. adv_remain -= 1.0;
  4771. }
  4772. justification_width += (gl.advance - old_adv);
  4773. }
  4774. }
  4775. }
  4776. }
  4777. if (Math::floor(p_width) < Math::floor(justification_width)) {
  4778. sd->fit_width_minimum_reached = true;
  4779. }
  4780. if (!p_jst_flags.has_flag(JUSTIFICATION_CONSTRAIN_ELLIPSIS)) {
  4781. sd->width = justification_width;
  4782. }
  4783. return Math::ceil(justification_width);
  4784. }
  4785. double TextServerAdvanced::_shaped_text_tab_align(const RID &p_shaped, const PackedFloat32Array &p_tab_stops) {
  4786. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  4787. ERR_FAIL_NULL_V(sd, 0.0);
  4788. MutexLock lock(sd->mutex);
  4789. if (!sd->valid.is_set()) {
  4790. _shaped_text_shape(p_shaped);
  4791. }
  4792. if (!sd->line_breaks_valid) {
  4793. _shaped_text_update_breaks(p_shaped);
  4794. }
  4795. for (int i = 0; i < p_tab_stops.size(); i++) {
  4796. if (p_tab_stops[i] <= 0) {
  4797. return 0.0;
  4798. }
  4799. }
  4800. int tab_index = 0;
  4801. double off = 0.0;
  4802. int start, end, delta;
  4803. if (sd->para_direction == DIRECTION_LTR) {
  4804. start = 0;
  4805. end = sd->glyphs.size();
  4806. delta = +1;
  4807. } else {
  4808. start = sd->glyphs.size() - 1;
  4809. end = -1;
  4810. delta = -1;
  4811. }
  4812. Glyph *gl = sd->glyphs.ptr();
  4813. for (int i = start; i != end; i += delta) {
  4814. if ((gl[i].flags & GRAPHEME_IS_TAB) == GRAPHEME_IS_TAB) {
  4815. double tab_off = 0.0;
  4816. while (tab_off <= off) {
  4817. tab_off += p_tab_stops[tab_index];
  4818. tab_index++;
  4819. if (tab_index >= p_tab_stops.size()) {
  4820. tab_index = 0;
  4821. }
  4822. }
  4823. double old_adv = gl[i].advance;
  4824. gl[i].advance = tab_off - off;
  4825. sd->width += gl[i].advance - old_adv;
  4826. off = 0;
  4827. continue;
  4828. }
  4829. off += gl[i].advance * gl[i].repeat;
  4830. }
  4831. return 0.0;
  4832. }
  4833. RID TextServerAdvanced::_find_sys_font_for_text(const RID &p_fdef, const String &p_script_code, const String &p_language, const String &p_text) {
  4834. RID f;
  4835. // Try system fallback.
  4836. String font_name = _font_get_name(p_fdef);
  4837. BitField<FontStyle> font_style = _font_get_style(p_fdef);
  4838. int font_weight = _font_get_weight(p_fdef);
  4839. int font_stretch = _font_get_stretch(p_fdef);
  4840. Dictionary dvar = _font_get_variation_coordinates(p_fdef);
  4841. static int64_t wgth_tag = _name_to_tag("weight");
  4842. static int64_t wdth_tag = _name_to_tag("width");
  4843. static int64_t ital_tag = _name_to_tag("italic");
  4844. if (dvar.has(wgth_tag)) {
  4845. font_weight = dvar[wgth_tag].operator int();
  4846. }
  4847. if (dvar.has(wdth_tag)) {
  4848. font_stretch = dvar[wdth_tag].operator int();
  4849. }
  4850. if (dvar.has(ital_tag) && dvar[ital_tag].operator int() == 1) {
  4851. font_style.set_flag(TextServer::FONT_ITALIC);
  4852. }
  4853. String locale = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  4854. PackedStringArray fallback_font_name = OS::get_singleton()->get_system_font_path_for_text(font_name, p_text, locale, p_script_code, font_weight, font_stretch, font_style & TextServer::FONT_ITALIC);
  4855. #ifdef GDEXTENSION
  4856. for (int fb = 0; fb < fallback_font_name.size(); fb++) {
  4857. const String &E = fallback_font_name[fb];
  4858. #elif defined(GODOT_MODULE)
  4859. for (const String &E : fallback_font_name) {
  4860. #endif
  4861. SystemFontKey key = SystemFontKey(E, font_style & TextServer::FONT_ITALIC, font_weight, font_stretch, p_fdef, this);
  4862. if (system_fonts.has(key)) {
  4863. const SystemFontCache &sysf_cache = system_fonts[key];
  4864. int best_score = 0;
  4865. int best_match = -1;
  4866. for (int face_idx = 0; face_idx < sysf_cache.var.size(); face_idx++) {
  4867. const SystemFontCacheRec &F = sysf_cache.var[face_idx];
  4868. if (unlikely(!_font_has_char(F.rid, p_text[0]))) {
  4869. continue;
  4870. }
  4871. BitField<FontStyle> style = _font_get_style(F.rid);
  4872. int weight = _font_get_weight(F.rid);
  4873. int stretch = _font_get_stretch(F.rid);
  4874. int score = (20 - Math::abs(weight - font_weight) / 50);
  4875. score += (20 - Math::abs(stretch - font_stretch) / 10);
  4876. if (bool(style & TextServer::FONT_ITALIC) == bool(font_style & TextServer::FONT_ITALIC)) {
  4877. score += 30;
  4878. }
  4879. if (score >= best_score) {
  4880. best_score = score;
  4881. best_match = face_idx;
  4882. }
  4883. if (best_score == 70) {
  4884. break;
  4885. }
  4886. }
  4887. if (best_match != -1) {
  4888. f = sysf_cache.var[best_match].rid;
  4889. }
  4890. }
  4891. if (!f.is_valid()) {
  4892. if (system_fonts.has(key)) {
  4893. const SystemFontCache &sysf_cache = system_fonts[key];
  4894. if (sysf_cache.max_var == sysf_cache.var.size()) {
  4895. // All subfonts already tested, skip.
  4896. continue;
  4897. }
  4898. }
  4899. if (!system_font_data.has(E)) {
  4900. system_font_data[E] = FileAccess::get_file_as_bytes(E);
  4901. }
  4902. const PackedByteArray &font_data = system_font_data[E];
  4903. SystemFontCacheRec sysf;
  4904. sysf.rid = _create_font();
  4905. _font_set_data_ptr(sysf.rid, font_data.ptr(), font_data.size());
  4906. if (!_font_validate(sysf.rid)) {
  4907. _free_rid(sysf.rid);
  4908. continue;
  4909. }
  4910. Dictionary var = dvar;
  4911. // Select matching style from collection.
  4912. int best_score = 0;
  4913. int best_match = -1;
  4914. for (int face_idx = 0; face_idx < _font_get_face_count(sysf.rid); face_idx++) {
  4915. _font_set_face_index(sysf.rid, face_idx);
  4916. if (unlikely(!_font_has_char(sysf.rid, p_text[0]))) {
  4917. continue;
  4918. }
  4919. BitField<FontStyle> style = _font_get_style(sysf.rid);
  4920. int weight = _font_get_weight(sysf.rid);
  4921. int stretch = _font_get_stretch(sysf.rid);
  4922. int score = (20 - Math::abs(weight - font_weight) / 50);
  4923. score += (20 - Math::abs(stretch - font_stretch) / 10);
  4924. if (bool(style & TextServer::FONT_ITALIC) == bool(font_style & TextServer::FONT_ITALIC)) {
  4925. score += 30;
  4926. }
  4927. if (score >= best_score) {
  4928. best_score = score;
  4929. best_match = face_idx;
  4930. }
  4931. if (best_score == 70) {
  4932. break;
  4933. }
  4934. }
  4935. if (best_match == -1) {
  4936. _free_rid(sysf.rid);
  4937. continue;
  4938. } else {
  4939. _font_set_face_index(sysf.rid, best_match);
  4940. }
  4941. sysf.index = best_match;
  4942. // If it's a variable font, apply weight, stretch and italic coordinates to match requested style.
  4943. if (best_score != 70) {
  4944. Dictionary ftr = _font_supported_variation_list(sysf.rid);
  4945. if (ftr.has(wdth_tag)) {
  4946. var[wdth_tag] = font_stretch;
  4947. _font_set_stretch(sysf.rid, font_stretch);
  4948. }
  4949. if (ftr.has(wgth_tag)) {
  4950. var[wgth_tag] = font_weight;
  4951. _font_set_weight(sysf.rid, font_weight);
  4952. }
  4953. if ((font_style & TextServer::FONT_ITALIC) && ftr.has(ital_tag)) {
  4954. var[ital_tag] = 1;
  4955. _font_set_style(sysf.rid, _font_get_style(sysf.rid) | TextServer::FONT_ITALIC);
  4956. }
  4957. }
  4958. _font_set_antialiasing(sysf.rid, key.antialiasing);
  4959. _font_set_disable_embedded_bitmaps(sysf.rid, key.disable_embedded_bitmaps);
  4960. _font_set_generate_mipmaps(sysf.rid, key.mipmaps);
  4961. _font_set_multichannel_signed_distance_field(sysf.rid, key.msdf);
  4962. _font_set_msdf_pixel_range(sysf.rid, key.msdf_range);
  4963. _font_set_msdf_size(sysf.rid, key.msdf_source_size);
  4964. _font_set_fixed_size(sysf.rid, key.fixed_size);
  4965. _font_set_force_autohinter(sysf.rid, key.force_autohinter);
  4966. _font_set_hinting(sysf.rid, key.hinting);
  4967. _font_set_subpixel_positioning(sysf.rid, key.subpixel_positioning);
  4968. _font_set_keep_rounding_remainders(sysf.rid, key.keep_rounding_remainders);
  4969. _font_set_variation_coordinates(sysf.rid, var);
  4970. _font_set_embolden(sysf.rid, key.embolden);
  4971. _font_set_transform(sysf.rid, key.transform);
  4972. _font_set_spacing(sysf.rid, SPACING_TOP, key.extra_spacing[SPACING_TOP]);
  4973. _font_set_spacing(sysf.rid, SPACING_BOTTOM, key.extra_spacing[SPACING_BOTTOM]);
  4974. _font_set_spacing(sysf.rid, SPACING_SPACE, key.extra_spacing[SPACING_SPACE]);
  4975. _font_set_spacing(sysf.rid, SPACING_GLYPH, key.extra_spacing[SPACING_GLYPH]);
  4976. if (system_fonts.has(key)) {
  4977. system_fonts[key].var.push_back(sysf);
  4978. } else {
  4979. SystemFontCache &sysf_cache = system_fonts[key];
  4980. sysf_cache.max_var = _font_get_face_count(sysf.rid);
  4981. sysf_cache.var.push_back(sysf);
  4982. }
  4983. f = sysf.rid;
  4984. }
  4985. break;
  4986. }
  4987. return f;
  4988. }
  4989. void TextServerAdvanced::_shaped_text_overrun_trim_to_width(const RID &p_shaped_line, double p_width, BitField<TextServer::TextOverrunFlag> p_trim_flags) {
  4990. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped_line);
  4991. ERR_FAIL_NULL_MSG(sd, "ShapedTextDataAdvanced invalid.");
  4992. MutexLock lock(sd->mutex);
  4993. if (!sd->valid.is_set()) {
  4994. _shaped_text_shape(p_shaped_line);
  4995. }
  4996. if (!sd->line_breaks_valid) {
  4997. _shaped_text_update_breaks(p_shaped_line);
  4998. }
  4999. sd->text_trimmed = false;
  5000. sd->overrun_trim_data.ellipsis_glyph_buf.clear();
  5001. bool add_ellipsis = p_trim_flags.has_flag(OVERRUN_ADD_ELLIPSIS);
  5002. bool cut_per_word = p_trim_flags.has_flag(OVERRUN_TRIM_WORD_ONLY);
  5003. bool enforce_ellipsis = p_trim_flags.has_flag(OVERRUN_ENFORCE_ELLIPSIS);
  5004. bool justification_aware = p_trim_flags.has_flag(OVERRUN_JUSTIFICATION_AWARE);
  5005. Glyph *sd_glyphs = sd->glyphs.ptr();
  5006. if ((p_trim_flags & OVERRUN_TRIM) == OVERRUN_NO_TRIM || sd_glyphs == nullptr || p_width <= 0 || !(sd->width > p_width || enforce_ellipsis)) {
  5007. sd->overrun_trim_data.trim_pos = -1;
  5008. sd->overrun_trim_data.ellipsis_pos = -1;
  5009. return;
  5010. }
  5011. if (justification_aware && !sd->fit_width_minimum_reached) {
  5012. return;
  5013. }
  5014. Vector<ShapedTextDataAdvanced::Span> &spans = sd->spans;
  5015. if (sd->parent != RID()) {
  5016. ShapedTextDataAdvanced *parent_sd = shaped_owner.get_or_null(sd->parent);
  5017. ERR_FAIL_COND(!parent_sd->valid.is_set());
  5018. spans = parent_sd->spans;
  5019. }
  5020. int span_size = spans.size();
  5021. if (span_size == 0) {
  5022. return;
  5023. }
  5024. int sd_size = sd->glyphs.size();
  5025. int last_gl_font_size = sd_glyphs[sd_size - 1].font_size;
  5026. bool found_el_char = false;
  5027. // Find usable fonts, if fonts from the last glyph do not have required chars.
  5028. RID dot_gl_font_rid = sd_glyphs[sd_size - 1].font_rid;
  5029. if (add_ellipsis || enforce_ellipsis) {
  5030. if (!_font_has_char(dot_gl_font_rid, sd->el_char)) {
  5031. const Array &fonts = spans[span_size - 1].fonts;
  5032. for (int i = 0; i < fonts.size(); i++) {
  5033. if (_font_has_char(fonts[i], sd->el_char)) {
  5034. dot_gl_font_rid = fonts[i];
  5035. found_el_char = true;
  5036. break;
  5037. }
  5038. }
  5039. if (!found_el_char && OS::get_singleton()->has_feature("system_fonts") && fonts.size() > 0 && _font_is_allow_system_fallback(fonts[0])) {
  5040. const char32_t u32str[] = { sd->el_char, 0 };
  5041. RID rid = _find_sys_font_for_text(fonts[0], String(), spans[span_size - 1].language, u32str);
  5042. if (rid.is_valid()) {
  5043. dot_gl_font_rid = rid;
  5044. found_el_char = true;
  5045. }
  5046. }
  5047. } else {
  5048. found_el_char = true;
  5049. }
  5050. if (!found_el_char) {
  5051. bool found_dot_char = false;
  5052. dot_gl_font_rid = sd_glyphs[sd_size - 1].font_rid;
  5053. if (!_font_has_char(dot_gl_font_rid, '.')) {
  5054. const Array &fonts = spans[span_size - 1].fonts;
  5055. for (int i = 0; i < fonts.size(); i++) {
  5056. if (_font_has_char(fonts[i], '.')) {
  5057. dot_gl_font_rid = fonts[i];
  5058. found_dot_char = true;
  5059. break;
  5060. }
  5061. }
  5062. if (!found_dot_char && OS::get_singleton()->has_feature("system_fonts") && fonts.size() > 0 && _font_is_allow_system_fallback(fonts[0])) {
  5063. RID rid = _find_sys_font_for_text(fonts[0], String(), spans[span_size - 1].language, ".");
  5064. if (rid.is_valid()) {
  5065. dot_gl_font_rid = rid;
  5066. }
  5067. }
  5068. }
  5069. }
  5070. }
  5071. RID whitespace_gl_font_rid = sd_glyphs[sd_size - 1].font_rid;
  5072. if (!_font_has_char(whitespace_gl_font_rid, ' ')) {
  5073. const Array &fonts = spans[span_size - 1].fonts;
  5074. for (int i = 0; i < fonts.size(); i++) {
  5075. if (_font_has_char(fonts[i], ' ')) {
  5076. whitespace_gl_font_rid = fonts[i];
  5077. break;
  5078. }
  5079. }
  5080. }
  5081. int32_t dot_gl_idx = ((add_ellipsis || enforce_ellipsis) && dot_gl_font_rid.is_valid()) ? _font_get_glyph_index(dot_gl_font_rid, last_gl_font_size, (found_el_char ? sd->el_char : '.'), 0) : -1;
  5082. Vector2 dot_adv = ((add_ellipsis || enforce_ellipsis) && dot_gl_font_rid.is_valid()) ? _font_get_glyph_advance(dot_gl_font_rid, last_gl_font_size, dot_gl_idx) : Vector2();
  5083. int32_t whitespace_gl_idx = whitespace_gl_font_rid.is_valid() ? _font_get_glyph_index(whitespace_gl_font_rid, last_gl_font_size, ' ', 0) : -1;
  5084. Vector2 whitespace_adv = whitespace_gl_font_rid.is_valid() ? _font_get_glyph_advance(whitespace_gl_font_rid, last_gl_font_size, whitespace_gl_idx) : Vector2();
  5085. int ellipsis_width = 0;
  5086. if (add_ellipsis && whitespace_gl_font_rid.is_valid()) {
  5087. ellipsis_width = (found_el_char ? 1 : 3) * dot_adv.x + sd->extra_spacing[SPACING_GLYPH] + _font_get_spacing(dot_gl_font_rid, SPACING_GLYPH) + (cut_per_word ? whitespace_adv.x : 0);
  5088. }
  5089. int ell_min_characters = 6;
  5090. double width = sd->width;
  5091. double width_without_el = width;
  5092. bool is_rtl = sd->para_direction == DIRECTION_RTL;
  5093. int trim_pos = (is_rtl) ? sd_size : 0;
  5094. int ellipsis_pos = (enforce_ellipsis) ? 0 : -1;
  5095. int last_valid_cut = -1;
  5096. int last_valid_cut_witout_el = -1;
  5097. int glyphs_from = (is_rtl) ? 0 : sd_size - 1;
  5098. int glyphs_to = (is_rtl) ? sd_size - 1 : -1;
  5099. int glyphs_delta = (is_rtl) ? +1 : -1;
  5100. if (enforce_ellipsis && (width + ellipsis_width <= p_width)) {
  5101. trim_pos = -1;
  5102. ellipsis_pos = (is_rtl) ? 0 : sd_size;
  5103. } else {
  5104. for (int i = glyphs_from; i != glyphs_to; i += glyphs_delta) {
  5105. if (!is_rtl) {
  5106. width -= sd_glyphs[i].advance * sd_glyphs[i].repeat;
  5107. }
  5108. if (sd_glyphs[i].count > 0) {
  5109. bool above_min_char_threshold = ((is_rtl) ? sd_size - 1 - i : i) >= ell_min_characters;
  5110. if (!above_min_char_threshold && last_valid_cut_witout_el != -1) {
  5111. trim_pos = last_valid_cut_witout_el;
  5112. ellipsis_pos = -1;
  5113. width = width_without_el;
  5114. break;
  5115. }
  5116. if (!enforce_ellipsis && width <= p_width && last_valid_cut_witout_el == -1) {
  5117. if (cut_per_word && above_min_char_threshold) {
  5118. if ((sd_glyphs[i].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT) {
  5119. last_valid_cut_witout_el = i;
  5120. width_without_el = width;
  5121. }
  5122. } else {
  5123. last_valid_cut_witout_el = i;
  5124. width_without_el = width;
  5125. }
  5126. }
  5127. if (width + (((above_min_char_threshold && add_ellipsis) || enforce_ellipsis) ? ellipsis_width : 0) <= p_width) {
  5128. if (cut_per_word && above_min_char_threshold) {
  5129. if ((sd_glyphs[i].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT) {
  5130. last_valid_cut = i;
  5131. }
  5132. } else {
  5133. last_valid_cut = i;
  5134. }
  5135. if (last_valid_cut != -1) {
  5136. trim_pos = last_valid_cut;
  5137. if (add_ellipsis && (above_min_char_threshold || enforce_ellipsis) && width - ellipsis_width <= p_width) {
  5138. ellipsis_pos = trim_pos;
  5139. }
  5140. break;
  5141. }
  5142. }
  5143. }
  5144. if (is_rtl) {
  5145. width -= sd_glyphs[i].advance * sd_glyphs[i].repeat;
  5146. }
  5147. }
  5148. }
  5149. sd->overrun_trim_data.trim_pos = trim_pos;
  5150. sd->overrun_trim_data.ellipsis_pos = ellipsis_pos;
  5151. if (trim_pos == 0 && enforce_ellipsis && add_ellipsis) {
  5152. sd->overrun_trim_data.ellipsis_pos = 0;
  5153. }
  5154. if ((trim_pos >= 0 && sd->width > p_width) || enforce_ellipsis) {
  5155. if (add_ellipsis && (ellipsis_pos > 0 || enforce_ellipsis)) {
  5156. // Insert an additional space when cutting word bound for aesthetics.
  5157. if (cut_per_word && (ellipsis_pos > 0)) {
  5158. Glyph gl;
  5159. gl.count = 1;
  5160. gl.advance = whitespace_adv.x;
  5161. gl.index = whitespace_gl_idx;
  5162. gl.font_rid = whitespace_gl_font_rid;
  5163. gl.font_size = last_gl_font_size;
  5164. gl.flags = GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT | GRAPHEME_IS_VIRTUAL | (is_rtl ? GRAPHEME_IS_RTL : 0);
  5165. sd->overrun_trim_data.ellipsis_glyph_buf.append(gl);
  5166. }
  5167. // Add ellipsis dots.
  5168. if (dot_gl_idx != 0) {
  5169. Glyph gl;
  5170. gl.count = 1;
  5171. gl.repeat = (found_el_char ? 1 : 3);
  5172. gl.advance = dot_adv.x;
  5173. gl.index = dot_gl_idx;
  5174. gl.font_rid = dot_gl_font_rid;
  5175. gl.font_size = last_gl_font_size;
  5176. gl.flags = GRAPHEME_IS_PUNCTUATION | GRAPHEME_IS_VIRTUAL | (is_rtl ? GRAPHEME_IS_RTL : 0);
  5177. sd->overrun_trim_data.ellipsis_glyph_buf.append(gl);
  5178. }
  5179. }
  5180. sd->text_trimmed = true;
  5181. sd->width_trimmed = width + ((ellipsis_pos != -1) ? ellipsis_width : 0);
  5182. }
  5183. }
  5184. int64_t TextServerAdvanced::_shaped_text_get_trim_pos(const RID &p_shaped) const {
  5185. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  5186. ERR_FAIL_NULL_V_MSG(sd, -1, "ShapedTextDataAdvanced invalid.");
  5187. MutexLock lock(sd->mutex);
  5188. return sd->overrun_trim_data.trim_pos;
  5189. }
  5190. int64_t TextServerAdvanced::_shaped_text_get_ellipsis_pos(const RID &p_shaped) const {
  5191. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  5192. ERR_FAIL_NULL_V_MSG(sd, -1, "ShapedTextDataAdvanced invalid.");
  5193. MutexLock lock(sd->mutex);
  5194. return sd->overrun_trim_data.ellipsis_pos;
  5195. }
  5196. const Glyph *TextServerAdvanced::_shaped_text_get_ellipsis_glyphs(const RID &p_shaped) const {
  5197. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  5198. ERR_FAIL_NULL_V_MSG(sd, nullptr, "ShapedTextDataAdvanced invalid.");
  5199. MutexLock lock(sd->mutex);
  5200. return sd->overrun_trim_data.ellipsis_glyph_buf.ptr();
  5201. }
  5202. int64_t TextServerAdvanced::_shaped_text_get_ellipsis_glyph_count(const RID &p_shaped) const {
  5203. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  5204. ERR_FAIL_NULL_V_MSG(sd, 0, "ShapedTextDataAdvanced invalid.");
  5205. MutexLock lock(sd->mutex);
  5206. return sd->overrun_trim_data.ellipsis_glyph_buf.size();
  5207. }
  5208. void TextServerAdvanced::_update_chars(ShapedTextDataAdvanced *p_sd) const {
  5209. if (!p_sd->chars_valid) {
  5210. p_sd->chars.clear();
  5211. const UChar *data = p_sd->utf16.get_data();
  5212. UErrorCode err = U_ZERO_ERROR;
  5213. int prev = -1;
  5214. int i = 0;
  5215. Vector<ShapedTextDataAdvanced::Span> &spans = p_sd->spans;
  5216. if (p_sd->parent != RID()) {
  5217. ShapedTextDataAdvanced *parent_sd = shaped_owner.get_or_null(p_sd->parent);
  5218. ERR_FAIL_COND(!parent_sd->valid.is_set());
  5219. spans = parent_sd->spans;
  5220. }
  5221. int span_size = spans.size();
  5222. while (i < span_size) {
  5223. if (spans[i].start > p_sd->end) {
  5224. break;
  5225. }
  5226. if (spans[i].end < p_sd->start) {
  5227. i++;
  5228. continue;
  5229. }
  5230. int r_start = MAX(0, spans[i].start - p_sd->start);
  5231. String language = spans[i].language;
  5232. while (i + 1 < span_size && language == spans[i + 1].language) {
  5233. i++;
  5234. }
  5235. int r_end = MIN(spans[i].end - p_sd->start, p_sd->text.length());
  5236. UBreakIterator *bi = ubrk_open(UBRK_CHARACTER, (language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale().ascii().get_data() : language.ascii().get_data(), data + _convert_pos_inv(p_sd, r_start), _convert_pos_inv(p_sd, r_end - r_start), &err);
  5237. if (U_SUCCESS(err)) {
  5238. while (ubrk_next(bi) != UBRK_DONE) {
  5239. int pos = _convert_pos(p_sd, ubrk_current(bi)) + r_start + p_sd->start;
  5240. if (prev != pos) {
  5241. p_sd->chars.push_back(pos);
  5242. }
  5243. prev = pos;
  5244. }
  5245. ubrk_close(bi);
  5246. } else {
  5247. for (int j = r_start; j < r_end; j++) {
  5248. if (prev != j) {
  5249. p_sd->chars.push_back(j + 1 + p_sd->start);
  5250. }
  5251. prev = j;
  5252. }
  5253. }
  5254. i++;
  5255. }
  5256. p_sd->chars_valid = true;
  5257. }
  5258. }
  5259. PackedInt32Array TextServerAdvanced::_shaped_text_get_character_breaks(const RID &p_shaped) const {
  5260. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  5261. ERR_FAIL_NULL_V(sd, PackedInt32Array());
  5262. MutexLock lock(sd->mutex);
  5263. if (!sd->valid.is_set()) {
  5264. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  5265. }
  5266. _update_chars(sd);
  5267. return sd->chars;
  5268. }
  5269. bool TextServerAdvanced::_shaped_text_update_breaks(const RID &p_shaped) {
  5270. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  5271. ERR_FAIL_NULL_V(sd, false);
  5272. MutexLock lock(sd->mutex);
  5273. if (!sd->valid.is_set()) {
  5274. _shaped_text_shape(p_shaped);
  5275. }
  5276. if (sd->line_breaks_valid) {
  5277. return true; // Nothing to do.
  5278. }
  5279. const UChar *data = sd->utf16.get_data();
  5280. if (!sd->break_ops_valid) {
  5281. sd->breaks.clear();
  5282. sd->break_inserts = 0;
  5283. UErrorCode err = U_ZERO_ERROR;
  5284. int i = 0;
  5285. int span_size = sd->spans.size();
  5286. while (i < span_size) {
  5287. String language = sd->spans[i].language;
  5288. int r_start = sd->spans[i].start;
  5289. if (r_start == sd->spans[i].end) {
  5290. i++;
  5291. continue;
  5292. }
  5293. while (i + 1 < span_size && (language == sd->spans[i + 1].language || sd->spans[i + 1].start == sd->spans[i + 1].end)) {
  5294. i++;
  5295. }
  5296. int r_end = sd->spans[i].end;
  5297. UBreakIterator *bi = _create_line_break_iterator_for_locale(language, &err);
  5298. if (!U_FAILURE(err) && bi) {
  5299. ubrk_setText(bi, data + _convert_pos_inv(sd, r_start), _convert_pos_inv(sd, r_end - r_start), &err);
  5300. }
  5301. if (U_FAILURE(err) || !bi) {
  5302. // No data loaded - use fallback.
  5303. for (int j = r_start; j < r_end; j++) {
  5304. char32_t c = sd->text[j - sd->start];
  5305. char32_t c_next = (j < r_end) ? sd->text[j - sd->start + 1] : 0x0000;
  5306. if (is_whitespace(c)) {
  5307. sd->breaks[j + 1] = false;
  5308. }
  5309. if (is_linebreak(c)) {
  5310. if (c != 0x000D || c_next != 0x000A) { // Skip first hard break in CR-LF pair.
  5311. sd->breaks[j + 1] = true;
  5312. }
  5313. }
  5314. }
  5315. } else {
  5316. while (ubrk_next(bi) != UBRK_DONE) {
  5317. int pos = _convert_pos(sd, ubrk_current(bi)) + r_start;
  5318. if ((ubrk_getRuleStatus(bi) >= UBRK_LINE_HARD) && (ubrk_getRuleStatus(bi) < UBRK_LINE_HARD_LIMIT)) {
  5319. sd->breaks[pos] = true;
  5320. } else if ((ubrk_getRuleStatus(bi) >= UBRK_LINE_SOFT) && (ubrk_getRuleStatus(bi) < UBRK_LINE_SOFT_LIMIT)) {
  5321. sd->breaks[pos] = false;
  5322. }
  5323. int pos_p = pos - 1 - sd->start;
  5324. char32_t c = sd->text[pos_p];
  5325. if (pos - sd->start != sd->end && !is_whitespace(c) && (c != 0xfffc)) {
  5326. sd->break_inserts++;
  5327. }
  5328. }
  5329. ubrk_close(bi);
  5330. }
  5331. i++;
  5332. }
  5333. sd->break_ops_valid = true;
  5334. }
  5335. LocalVector<Glyph> glyphs_new;
  5336. bool rewrite = false;
  5337. int sd_shift = 0;
  5338. int sd_size = sd->glyphs.size();
  5339. Glyph *sd_glyphs = sd->glyphs.ptr();
  5340. Glyph *sd_glyphs_new = nullptr;
  5341. if (sd->break_inserts > 0) {
  5342. glyphs_new.resize(sd->glyphs.size() + sd->break_inserts);
  5343. sd_glyphs_new = glyphs_new.ptr();
  5344. rewrite = true;
  5345. } else {
  5346. sd_glyphs_new = sd_glyphs;
  5347. }
  5348. sd->sort_valid = false;
  5349. sd->glyphs_logical.clear();
  5350. const char32_t *ch = sd->text.ptr();
  5351. int c_punct_size = sd->custom_punct.length();
  5352. const char32_t *c_punct = sd->custom_punct.ptr();
  5353. for (int i = 0; i < sd_size; i++) {
  5354. if (rewrite) {
  5355. for (int j = 0; j < sd_glyphs[i].count; j++) {
  5356. sd_glyphs_new[sd_shift + i + j] = sd_glyphs[i + j];
  5357. }
  5358. }
  5359. if (sd_glyphs[i].count > 0) {
  5360. char32_t c = ch[sd_glyphs[i].start - sd->start];
  5361. if (c == 0xfffc) {
  5362. i += (sd_glyphs[i].count - 1);
  5363. continue;
  5364. }
  5365. if (c == 0x0009 || c == 0x000b) {
  5366. sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_TAB;
  5367. }
  5368. if (c == 0x00ad) {
  5369. sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_SOFT_HYPHEN;
  5370. }
  5371. if (is_whitespace(c)) {
  5372. sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_SPACE;
  5373. }
  5374. if (c_punct_size == 0) {
  5375. if (u_ispunct(c) && c != 0x005f) {
  5376. sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_PUNCTUATION;
  5377. }
  5378. } else {
  5379. for (int j = 0; j < c_punct_size; j++) {
  5380. if (c_punct[j] == c) {
  5381. sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_PUNCTUATION;
  5382. break;
  5383. }
  5384. }
  5385. }
  5386. if (is_underscore(c)) {
  5387. sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_UNDERSCORE;
  5388. }
  5389. if (sd->breaks.has(sd_glyphs[i].end)) {
  5390. if (sd->breaks[sd_glyphs[i].end] && (is_linebreak(c))) {
  5391. sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_BREAK_HARD;
  5392. } else if (is_whitespace(c) || c == 0x00ad) {
  5393. sd_glyphs_new[sd_shift + i].flags |= GRAPHEME_IS_BREAK_SOFT;
  5394. } else {
  5395. int count = sd_glyphs[i].count;
  5396. // Do not add extra space at the end of the line.
  5397. if (sd_glyphs[i].end == sd->end) {
  5398. i += (sd_glyphs[i].count - 1);
  5399. continue;
  5400. }
  5401. // Do not add extra space after existing space.
  5402. if (sd_glyphs[i].flags & GRAPHEME_IS_RTL) {
  5403. if ((i + count < sd_size - 1) && ((sd_glyphs[i + count].flags & (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT)) == (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT))) {
  5404. i += (sd_glyphs[i].count - 1);
  5405. continue;
  5406. }
  5407. } else {
  5408. if ((sd_glyphs[i].flags & (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT)) == (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT)) {
  5409. i += (sd_glyphs[i].count - 1);
  5410. continue;
  5411. }
  5412. }
  5413. // Do not add extra space for color picker object.
  5414. if (((sd_glyphs[i].flags & GRAPHEME_IS_EMBEDDED_OBJECT) == GRAPHEME_IS_EMBEDDED_OBJECT && sd_glyphs[i].start == sd_glyphs[i].end) || (uint32_t(i + 1) < sd->glyphs.size() && (sd_glyphs[i + 1].flags & GRAPHEME_IS_EMBEDDED_OBJECT) == GRAPHEME_IS_EMBEDDED_OBJECT && sd_glyphs[i + 1].start == sd_glyphs[i + 1].end)) {
  5415. i += (sd_glyphs[i].count - 1);
  5416. continue;
  5417. }
  5418. Glyph gl;
  5419. gl.span_index = sd_glyphs[i].span_index;
  5420. gl.start = sd_glyphs[i].start;
  5421. gl.end = sd_glyphs[i].end;
  5422. gl.count = 1;
  5423. gl.font_rid = sd_glyphs[i].font_rid;
  5424. gl.font_size = sd_glyphs[i].font_size;
  5425. gl.flags = GRAPHEME_IS_BREAK_SOFT | GRAPHEME_IS_VIRTUAL | GRAPHEME_IS_SPACE;
  5426. // Mark virtual space after punctuation as punctuation to avoid justification at this point.
  5427. if (c_punct_size == 0) {
  5428. if (u_ispunct(c) && c != 0x005f) {
  5429. gl.flags |= GRAPHEME_IS_PUNCTUATION;
  5430. }
  5431. } else {
  5432. for (int j = 0; j < c_punct_size; j++) {
  5433. if (c_punct[j] == c) {
  5434. gl.flags |= GRAPHEME_IS_PUNCTUATION;
  5435. break;
  5436. }
  5437. }
  5438. }
  5439. if (sd_glyphs[i].flags & GRAPHEME_IS_RTL) {
  5440. gl.flags |= GRAPHEME_IS_RTL;
  5441. for (int j = sd_glyphs[i].count - 1; j >= 0; j--) {
  5442. sd_glyphs_new[sd_shift + i + j + 1] = sd_glyphs_new[sd_shift + i + j];
  5443. }
  5444. sd_glyphs_new[sd_shift + i] = gl;
  5445. } else {
  5446. sd_glyphs_new[sd_shift + i + count] = gl;
  5447. }
  5448. sd_shift++;
  5449. ERR_FAIL_COND_V_MSG(sd_shift > sd->break_inserts, false, "Invalid break insert count!");
  5450. }
  5451. }
  5452. i += (sd_glyphs[i].count - 1);
  5453. }
  5454. }
  5455. if (sd_shift < sd->break_inserts) {
  5456. // Note: should not happen with a normal text, but might be a case with special fonts that substitute a long string (with breaks opportunities in it) with a single glyph (like Font Awesome).
  5457. glyphs_new.resize(sd->glyphs.size() + sd_shift);
  5458. }
  5459. if (sd->break_inserts > 0) {
  5460. sd->glyphs = std::move(glyphs_new);
  5461. }
  5462. sd->line_breaks_valid = true;
  5463. return sd->line_breaks_valid;
  5464. }
  5465. _FORCE_INLINE_ int64_t _generate_kashida_justification_opportunities(const String &p_data, int64_t p_start, int64_t p_end) {
  5466. int64_t kashida_pos = -1;
  5467. int8_t priority = 100;
  5468. int64_t i = p_start;
  5469. char32_t pc = 0;
  5470. while ((p_end > p_start) && is_transparent(p_data[p_end - 1])) {
  5471. p_end--;
  5472. }
  5473. while (i < p_end) {
  5474. uint32_t c = p_data[i];
  5475. if (c == 0x0640) {
  5476. kashida_pos = i;
  5477. priority = 0;
  5478. }
  5479. if (priority >= 1 && i < p_end - 1) {
  5480. if (is_seen_sad(c) && (p_data[i + 1] != 0x200c)) {
  5481. kashida_pos = i;
  5482. priority = 1;
  5483. }
  5484. }
  5485. if (priority >= 2 && i > p_start) {
  5486. if (is_teh_marbuta(c) || is_dal(c) || (is_heh(c) && i == p_end - 1)) {
  5487. if (is_connected_to_prev(c, pc)) {
  5488. kashida_pos = i - 1;
  5489. priority = 2;
  5490. }
  5491. }
  5492. }
  5493. if (priority >= 3 && i > p_start) {
  5494. if (is_alef(c) || ((is_lam(c) || is_tah(c) || is_kaf(c) || is_gaf(c)) && i == p_end - 1)) {
  5495. if (is_connected_to_prev(c, pc)) {
  5496. kashida_pos = i - 1;
  5497. priority = 3;
  5498. }
  5499. }
  5500. }
  5501. if (priority >= 4 && i > p_start && i < p_end - 1) {
  5502. if (is_beh(c)) {
  5503. if (is_reh(p_data[i + 1]) || is_yeh(p_data[i + 1])) {
  5504. if (is_connected_to_prev(c, pc)) {
  5505. kashida_pos = i - 1;
  5506. priority = 4;
  5507. }
  5508. }
  5509. }
  5510. }
  5511. if (priority >= 5 && i > p_start) {
  5512. if (is_waw(c) || ((is_ain(c) || is_qaf(c) || is_feh(c)) && i == p_end - 1)) {
  5513. if (is_connected_to_prev(c, pc)) {
  5514. kashida_pos = i - 1;
  5515. priority = 5;
  5516. }
  5517. }
  5518. }
  5519. if (priority >= 6 && i > p_start) {
  5520. if (is_reh(c)) {
  5521. if (is_connected_to_prev(c, pc)) {
  5522. kashida_pos = i - 1;
  5523. priority = 6;
  5524. }
  5525. }
  5526. }
  5527. if (!is_transparent(c)) {
  5528. pc = c;
  5529. }
  5530. i++;
  5531. }
  5532. return kashida_pos;
  5533. }
  5534. bool TextServerAdvanced::_shaped_text_update_justification_ops(const RID &p_shaped) {
  5535. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  5536. ERR_FAIL_NULL_V(sd, false);
  5537. MutexLock lock(sd->mutex);
  5538. if (!sd->valid.is_set()) {
  5539. _shaped_text_shape(p_shaped);
  5540. }
  5541. if (!sd->line_breaks_valid) {
  5542. _shaped_text_update_breaks(p_shaped);
  5543. }
  5544. if (sd->justification_ops_valid) {
  5545. return true; // Nothing to do.
  5546. }
  5547. const UChar *data = sd->utf16.get_data();
  5548. int data_size = sd->utf16.length();
  5549. if (!sd->js_ops_valid) {
  5550. sd->jstops.clear();
  5551. // Use ICU word iterator and custom kashida detection.
  5552. UErrorCode err = U_ZERO_ERROR;
  5553. UBreakIterator *bi = ubrk_open(UBRK_WORD, "", data, data_size, &err);
  5554. if (U_FAILURE(err)) {
  5555. // No data - use fallback.
  5556. int limit = 0;
  5557. for (int i = 0; i < sd->text.length(); i++) {
  5558. if (is_whitespace(sd->text[i])) {
  5559. int ks = _generate_kashida_justification_opportunities(sd->text, limit, i) + sd->start;
  5560. if (ks != -1) {
  5561. sd->jstops[ks] = true;
  5562. }
  5563. limit = i + 1;
  5564. }
  5565. }
  5566. int ks = _generate_kashida_justification_opportunities(sd->text, limit, sd->text.length()) + sd->start;
  5567. if (ks != -1) {
  5568. sd->jstops[ks] = true;
  5569. }
  5570. } else {
  5571. int limit = 0;
  5572. while (ubrk_next(bi) != UBRK_DONE) {
  5573. if (ubrk_getRuleStatus(bi) != UBRK_WORD_NONE) {
  5574. int i = _convert_pos(sd, ubrk_current(bi));
  5575. sd->jstops[i + sd->start] = false;
  5576. int ks = _generate_kashida_justification_opportunities(sd->text, limit, i);
  5577. if (ks != -1) {
  5578. sd->jstops[ks + sd->start] = true;
  5579. }
  5580. limit = i;
  5581. }
  5582. }
  5583. ubrk_close(bi);
  5584. }
  5585. sd->js_ops_valid = true;
  5586. }
  5587. sd->sort_valid = false;
  5588. sd->glyphs_logical.clear();
  5589. Glyph *sd_glyphs = sd->glyphs.ptr();
  5590. int sd_size = sd->glyphs.size();
  5591. if (!sd->jstops.is_empty()) {
  5592. for (int i = 0; i < sd_size; i++) {
  5593. if (sd_glyphs[i].count > 0) {
  5594. char32_t c = sd->text[sd_glyphs[i].start - sd->start];
  5595. if (c == 0x0640 && sd_glyphs[i].start == sd_glyphs[i].end - 1) {
  5596. sd_glyphs[i].flags |= GRAPHEME_IS_ELONGATION;
  5597. }
  5598. if (sd->jstops.has(sd_glyphs[i].start)) {
  5599. if (c == 0xfffc || c == 0x00ad) {
  5600. continue;
  5601. }
  5602. if (sd->jstops[sd_glyphs[i].start]) {
  5603. if (c != 0x0640) {
  5604. if (sd_glyphs[i].font_rid != RID()) {
  5605. Glyph gl = _shape_single_glyph(sd, 0x0640, HB_SCRIPT_ARABIC, HB_DIRECTION_RTL, sd->glyphs[i].font_rid, sd->glyphs[i].font_size);
  5606. if ((sd_glyphs[i].flags & GRAPHEME_IS_VALID) == GRAPHEME_IS_VALID) {
  5607. #if HB_VERSION_ATLEAST(5, 1, 0)
  5608. if ((i > 0) && ((sd_glyphs[i - 1].flags & GRAPHEME_IS_SAFE_TO_INSERT_TATWEEL) != GRAPHEME_IS_SAFE_TO_INSERT_TATWEEL)) {
  5609. continue;
  5610. }
  5611. #endif
  5612. gl.start = sd_glyphs[i].start;
  5613. gl.end = sd_glyphs[i].end;
  5614. gl.repeat = 0;
  5615. gl.count = 1;
  5616. if (sd->orientation == ORIENTATION_HORIZONTAL) {
  5617. gl.y_off = sd_glyphs[i].y_off;
  5618. } else {
  5619. gl.x_off = sd_glyphs[i].x_off;
  5620. }
  5621. gl.flags |= GRAPHEME_IS_ELONGATION | GRAPHEME_IS_VIRTUAL;
  5622. sd->glyphs.insert(i, gl);
  5623. i++;
  5624. // Update write pointer and size.
  5625. sd_size = sd->glyphs.size();
  5626. sd_glyphs = sd->glyphs.ptr();
  5627. continue;
  5628. }
  5629. }
  5630. }
  5631. } else if ((sd_glyphs[i].flags & GRAPHEME_IS_SPACE) != GRAPHEME_IS_SPACE && (sd_glyphs[i].flags & GRAPHEME_IS_PUNCTUATION) != GRAPHEME_IS_PUNCTUATION) {
  5632. int count = sd_glyphs[i].count;
  5633. // Do not add extra spaces at the end of the line.
  5634. if (sd_glyphs[i].end == sd->end) {
  5635. continue;
  5636. }
  5637. // Do not add extra space after existing space.
  5638. if (sd_glyphs[i].flags & GRAPHEME_IS_RTL) {
  5639. if ((i + count < sd_size - 1) && ((sd_glyphs[i + count].flags & (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT)) == (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT))) {
  5640. continue;
  5641. }
  5642. } else {
  5643. if ((i > 0) && ((sd_glyphs[i - 1].flags & (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT)) == (GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT))) {
  5644. continue;
  5645. }
  5646. }
  5647. // Inject virtual space for alignment.
  5648. Glyph gl;
  5649. gl.span_index = sd_glyphs[i].span_index;
  5650. gl.start = sd_glyphs[i].start;
  5651. gl.end = sd_glyphs[i].end;
  5652. gl.count = 1;
  5653. gl.font_rid = sd_glyphs[i].font_rid;
  5654. gl.font_size = sd_glyphs[i].font_size;
  5655. gl.flags = GRAPHEME_IS_SPACE | GRAPHEME_IS_VIRTUAL;
  5656. if (sd_glyphs[i].flags & GRAPHEME_IS_RTL) {
  5657. gl.flags |= GRAPHEME_IS_RTL;
  5658. sd->glyphs.insert(i, gl); // Insert before.
  5659. } else {
  5660. sd->glyphs.insert(i + count, gl); // Insert after.
  5661. }
  5662. i += count;
  5663. // Update write pointer and size.
  5664. sd_size = sd->glyphs.size();
  5665. sd_glyphs = sd->glyphs.ptr();
  5666. continue;
  5667. }
  5668. }
  5669. }
  5670. }
  5671. }
  5672. sd->justification_ops_valid = true;
  5673. return sd->justification_ops_valid;
  5674. }
  5675. Glyph TextServerAdvanced::_shape_single_glyph(ShapedTextDataAdvanced *p_sd, char32_t p_char, hb_script_t p_script, hb_direction_t p_direction, const RID &p_font, int64_t p_font_size) {
  5676. hb_font_t *hb_font = _font_get_hb_handle(p_font, p_font_size);
  5677. double scale = _font_get_scale(p_font, p_font_size);
  5678. bool subpos = (scale != 1.0) || (_font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_ONE_HALF) || (_font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_ONE_QUARTER) || (_font_get_subpixel_positioning(p_font) == SUBPIXEL_POSITIONING_AUTO && p_font_size <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE);
  5679. ERR_FAIL_NULL_V(hb_font, Glyph());
  5680. hb_buffer_clear_contents(p_sd->hb_buffer);
  5681. hb_buffer_set_direction(p_sd->hb_buffer, p_direction);
  5682. hb_buffer_set_flags(p_sd->hb_buffer, (hb_buffer_flags_t)(HB_BUFFER_FLAG_DEFAULT));
  5683. hb_buffer_set_script(p_sd->hb_buffer, p_script);
  5684. hb_buffer_add_utf32(p_sd->hb_buffer, (const uint32_t *)&p_char, 1, 0, 1);
  5685. hb_shape(hb_font, p_sd->hb_buffer, nullptr, 0);
  5686. unsigned int glyph_count = 0;
  5687. hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(p_sd->hb_buffer, &glyph_count);
  5688. hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(p_sd->hb_buffer, &glyph_count);
  5689. // Process glyphs.
  5690. Glyph gl;
  5691. if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
  5692. gl.flags |= TextServer::GRAPHEME_IS_RTL;
  5693. }
  5694. gl.font_rid = p_font;
  5695. gl.font_size = p_font_size;
  5696. if (glyph_count > 0) {
  5697. if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  5698. if (subpos) {
  5699. gl.advance = (double)glyph_pos[0].x_advance / (64.0 / scale) + _get_extra_advance(p_font, p_font_size);
  5700. } else {
  5701. gl.advance = Math::round((double)glyph_pos[0].x_advance / (64.0 / scale) + _get_extra_advance(p_font, p_font_size));
  5702. }
  5703. } else {
  5704. gl.advance = -Math::round((double)glyph_pos[0].y_advance / (64.0 / scale));
  5705. }
  5706. gl.count = 1;
  5707. gl.index = glyph_info[0].codepoint;
  5708. if (subpos) {
  5709. gl.x_off = (double)glyph_pos[0].x_offset / (64.0 / scale);
  5710. } else {
  5711. gl.x_off = Math::round((double)glyph_pos[0].x_offset / (64.0 / scale));
  5712. }
  5713. gl.y_off = -Math::round((double)glyph_pos[0].y_offset / (64.0 / scale));
  5714. if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  5715. gl.y_off += _font_get_baseline_offset(gl.font_rid) * (double)(_font_get_ascent(gl.font_rid, gl.font_size) + _font_get_descent(gl.font_rid, gl.font_size));
  5716. } else {
  5717. gl.x_off += _font_get_baseline_offset(gl.font_rid) * (double)(_font_get_ascent(gl.font_rid, gl.font_size) + _font_get_descent(gl.font_rid, gl.font_size));
  5718. }
  5719. if ((glyph_info[0].codepoint != 0) || !u_isgraph(p_char)) {
  5720. gl.flags |= GRAPHEME_IS_VALID;
  5721. }
  5722. }
  5723. return gl;
  5724. }
  5725. _FORCE_INLINE_ void TextServerAdvanced::_add_features(const Dictionary &p_source, Vector<hb_feature_t> &r_ftrs) {
  5726. for (const KeyValue<Variant, Variant> &key_value : p_source) {
  5727. int32_t value = key_value.value;
  5728. if (value >= 0) {
  5729. hb_feature_t feature;
  5730. if (key_value.key.is_string()) {
  5731. feature.tag = _name_to_tag(key_value.key);
  5732. } else {
  5733. feature.tag = key_value.key;
  5734. }
  5735. feature.value = value;
  5736. feature.start = 0;
  5737. feature.end = -1;
  5738. r_ftrs.push_back(feature);
  5739. }
  5740. }
  5741. }
  5742. UBreakIterator *TextServerAdvanced::_create_line_break_iterator_for_locale(const String &p_language, UErrorCode *r_err) const {
  5743. // Creating UBreakIterator (ubrk_open) is surprisingly costly.
  5744. // However, cloning (ubrk_clone) is cheaper, so we keep around blueprints to accelerate creating new ones.
  5745. String language = p_language.is_empty() ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  5746. if (!language.contains("@")) {
  5747. if (lb_strictness == LB_LOOSE) {
  5748. language += "@lb=loose";
  5749. } else if (lb_strictness == LB_NORMAL) {
  5750. language += "@lb=normal";
  5751. } else if (lb_strictness == LB_STRICT) {
  5752. language += "@lb=strict";
  5753. }
  5754. }
  5755. _THREAD_SAFE_METHOD_
  5756. const HashMap<String, UBreakIterator *>::Iterator key_value = line_break_iterators_per_language.find(language);
  5757. if (key_value) {
  5758. return ubrk_clone(key_value->value, r_err);
  5759. }
  5760. UBreakIterator *bi = ubrk_open(UBRK_LINE, language.ascii().get_data(), nullptr, 0, r_err);
  5761. if (U_FAILURE(*r_err) || !bi) {
  5762. return nullptr;
  5763. }
  5764. line_break_iterators_per_language.insert(language, bi);
  5765. return ubrk_clone(bi, r_err);
  5766. }
  5767. void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int64_t p_start, int64_t p_end, hb_script_t p_script, hb_direction_t p_direction, TypedArray<RID> p_fonts, int64_t p_span, int64_t p_fb_index, int64_t p_prev_start, int64_t p_prev_end, RID p_prev_font) {
  5768. RID f;
  5769. int fs = p_sd->spans[p_span].font_size;
  5770. if (p_fb_index >= 0 && p_fb_index < p_fonts.size()) {
  5771. // Try font from list.
  5772. f = p_fonts[p_fb_index];
  5773. } else if (OS::get_singleton()->has_feature("system_fonts") && p_fonts.size() > 0 && ((p_fb_index == p_fonts.size()) || (p_fb_index > p_fonts.size() && p_start != p_prev_start))) {
  5774. // Try system fallback.
  5775. RID fdef = p_fonts[0];
  5776. if (_font_is_allow_system_fallback(fdef)) {
  5777. _update_chars(p_sd);
  5778. int64_t next = p_end;
  5779. for (const int32_t &E : p_sd->chars) {
  5780. if (E > p_start) {
  5781. next = E;
  5782. break;
  5783. }
  5784. }
  5785. char scr_buffer[5] = { 0, 0, 0, 0, 0 };
  5786. hb_tag_to_string(hb_script_to_iso15924_tag(p_script), scr_buffer);
  5787. String script_code = String(scr_buffer);
  5788. String text = p_sd->text.substr(p_start, next - p_start);
  5789. f = _find_sys_font_for_text(fdef, script_code, p_sd->spans[p_span].language, text);
  5790. }
  5791. }
  5792. if (!f.is_valid()) {
  5793. // Shaping failed, try looking up raw characters or use fallback hex code boxes.
  5794. int fb_from = (p_direction != HB_DIRECTION_RTL) ? p_start : p_end - 1;
  5795. int fb_to = (p_direction != HB_DIRECTION_RTL) ? p_end : p_start - 1;
  5796. int fb_delta = (p_direction != HB_DIRECTION_RTL) ? +1 : -1;
  5797. for (int i = fb_from; i != fb_to; i += fb_delta) {
  5798. if (p_sd->preserve_invalid || (p_sd->preserve_control && is_control(p_sd->text[i]))) {
  5799. Glyph gl;
  5800. gl.span_index = p_span;
  5801. gl.start = i + p_sd->start;
  5802. gl.end = i + 1 + p_sd->start;
  5803. gl.count = 1;
  5804. gl.font_size = fs;
  5805. if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
  5806. gl.flags |= TextServer::GRAPHEME_IS_RTL;
  5807. }
  5808. bool found = false;
  5809. for (int j = 0; j <= p_fonts.size(); j++) {
  5810. RID f_rid;
  5811. if (j == p_fonts.size()) {
  5812. f_rid = p_prev_font;
  5813. } else {
  5814. f_rid = p_fonts[j];
  5815. }
  5816. if (f_rid.is_valid() && _font_has_char(f_rid, p_sd->text[i])) {
  5817. gl.font_rid = f_rid;
  5818. gl.index = _font_get_glyph_index(gl.font_rid, fs, p_sd->text[i], 0);
  5819. if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  5820. gl.advance = _font_get_glyph_advance(gl.font_rid, fs, gl.index).x;
  5821. gl.x_off = 0;
  5822. gl.y_off = _font_get_baseline_offset(gl.font_rid) * (double)(_font_get_ascent(gl.font_rid, gl.font_size) + _font_get_descent(gl.font_rid, gl.font_size));
  5823. p_sd->ascent = MAX(p_sd->ascent, _font_get_ascent(gl.font_rid, gl.font_size) + _font_get_spacing(gl.font_rid, SPACING_TOP));
  5824. p_sd->descent = MAX(p_sd->descent, _font_get_descent(gl.font_rid, gl.font_size) + _font_get_spacing(gl.font_rid, SPACING_BOTTOM));
  5825. } else {
  5826. gl.advance = _font_get_glyph_advance(gl.font_rid, fs, gl.index).y;
  5827. gl.x_off = -Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5) + _font_get_baseline_offset(gl.font_rid) * (double)(_font_get_ascent(gl.font_rid, gl.font_size) + _font_get_descent(gl.font_rid, gl.font_size));
  5828. gl.y_off = _font_get_ascent(gl.font_rid, gl.font_size);
  5829. p_sd->ascent = MAX(p_sd->ascent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5));
  5830. p_sd->descent = MAX(p_sd->descent, Math::round(_font_get_glyph_advance(gl.font_rid, gl.font_size, gl.index).x * 0.5));
  5831. }
  5832. double scale = _font_get_scale(gl.font_rid, fs);
  5833. bool subpos = (scale != 1.0) || (_font_get_subpixel_positioning(gl.font_rid) == SUBPIXEL_POSITIONING_ONE_HALF) || (_font_get_subpixel_positioning(gl.font_rid) == SUBPIXEL_POSITIONING_ONE_QUARTER) || (_font_get_subpixel_positioning(gl.font_rid) == SUBPIXEL_POSITIONING_AUTO && fs <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE);
  5834. if (!subpos) {
  5835. gl.advance = Math::round(gl.advance);
  5836. gl.x_off = Math::round(gl.x_off);
  5837. }
  5838. found = true;
  5839. break;
  5840. }
  5841. }
  5842. if (!found) {
  5843. gl.font_rid = RID();
  5844. gl.index = p_sd->text[i];
  5845. if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  5846. gl.advance = get_hex_code_box_size(fs, gl.index).x;
  5847. p_sd->ascent = MAX(p_sd->ascent, get_hex_code_box_size(fs, gl.index).y * 0.85);
  5848. p_sd->descent = MAX(p_sd->descent, get_hex_code_box_size(fs, gl.index).y * 0.15);
  5849. } else {
  5850. gl.advance = get_hex_code_box_size(fs, gl.index).y;
  5851. gl.y_off = get_hex_code_box_size(fs, gl.index).y;
  5852. gl.x_off = -Math::round(get_hex_code_box_size(fs, gl.index).x * 0.5);
  5853. p_sd->ascent = MAX(p_sd->ascent, Math::round(get_hex_code_box_size(fs, gl.index).x * 0.5));
  5854. p_sd->descent = MAX(p_sd->descent, Math::round(get_hex_code_box_size(fs, gl.index).x * 0.5));
  5855. }
  5856. }
  5857. p_sd->width += gl.advance;
  5858. p_sd->glyphs.push_back(gl);
  5859. }
  5860. }
  5861. return;
  5862. }
  5863. FontAdvanced *fd = _get_font_data(f);
  5864. ERR_FAIL_NULL(fd);
  5865. MutexLock lock(fd->mutex);
  5866. Vector2i fss = _get_size(fd, fs);
  5867. hb_font_t *hb_font = _font_get_hb_handle(f, fs);
  5868. double scale = _font_get_scale(f, fs);
  5869. double sp_sp = p_sd->extra_spacing[SPACING_SPACE] + _font_get_spacing(f, SPACING_SPACE);
  5870. double sp_gl = p_sd->extra_spacing[SPACING_GLYPH] + _font_get_spacing(f, SPACING_GLYPH);
  5871. bool last_run = (p_sd->end == p_end);
  5872. double ea = _get_extra_advance(f, fs);
  5873. bool subpos = (scale != 1.0) || (_font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_ONE_HALF) || (_font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_ONE_QUARTER) || (_font_get_subpixel_positioning(f) == SUBPIXEL_POSITIONING_AUTO && fs <= SUBPIXEL_POSITIONING_ONE_HALF_MAX_SIZE);
  5874. ERR_FAIL_NULL(hb_font);
  5875. hb_buffer_clear_contents(p_sd->hb_buffer);
  5876. hb_buffer_set_direction(p_sd->hb_buffer, p_direction);
  5877. int flags = (p_start == 0 ? HB_BUFFER_FLAG_BOT : 0) | (p_end == p_sd->text.length() ? HB_BUFFER_FLAG_EOT : 0);
  5878. if (p_sd->preserve_control) {
  5879. flags |= HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES;
  5880. } else {
  5881. flags |= HB_BUFFER_FLAG_DEFAULT;
  5882. }
  5883. #if HB_VERSION_ATLEAST(5, 1, 0)
  5884. flags |= HB_BUFFER_FLAG_PRODUCE_SAFE_TO_INSERT_TATWEEL;
  5885. #endif
  5886. hb_buffer_set_flags(p_sd->hb_buffer, (hb_buffer_flags_t)flags);
  5887. hb_buffer_set_script(p_sd->hb_buffer, p_script);
  5888. if (p_sd->spans[p_span].language.is_empty()) {
  5889. hb_language_t lang = hb_language_from_string(TranslationServer::get_singleton()->get_tool_locale().ascii().get_data(), -1);
  5890. hb_buffer_set_language(p_sd->hb_buffer, lang);
  5891. } else {
  5892. hb_language_t lang = hb_language_from_string(p_sd->spans[p_span].language.ascii().get_data(), -1);
  5893. hb_buffer_set_language(p_sd->hb_buffer, lang);
  5894. }
  5895. hb_buffer_add_utf32(p_sd->hb_buffer, (const uint32_t *)p_sd->text.ptr(), p_sd->text.length(), p_start, p_end - p_start);
  5896. Vector<hb_feature_t> ftrs;
  5897. _add_features(_font_get_opentype_feature_overrides(f), ftrs);
  5898. _add_features(p_sd->spans[p_span].features, ftrs);
  5899. hb_shape(hb_font, p_sd->hb_buffer, ftrs.is_empty() ? nullptr : &ftrs[0], ftrs.size());
  5900. unsigned int glyph_count = 0;
  5901. hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(p_sd->hb_buffer, &glyph_count);
  5902. hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(p_sd->hb_buffer, &glyph_count);
  5903. int mod = 0;
  5904. if (fd->antialiasing == FONT_ANTIALIASING_LCD) {
  5905. TextServer::FontLCDSubpixelLayout layout = lcd_subpixel_layout.get();
  5906. if (layout != FONT_LCD_SUBPIXEL_LAYOUT_NONE) {
  5907. mod = (layout << 24);
  5908. }
  5909. }
  5910. // Process glyphs.
  5911. if (glyph_count > 0) {
  5912. Glyph *w = (Glyph *)memalloc(glyph_count * sizeof(Glyph));
  5913. int end = (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) ? p_end : 0;
  5914. uint32_t last_cluster_id = UINT32_MAX;
  5915. unsigned int last_cluster_index = 0;
  5916. bool last_cluster_valid = true;
  5917. double adv_rem = 0.0;
  5918. for (unsigned int i = 0; i < glyph_count; i++) {
  5919. if ((i > 0) && (last_cluster_id != glyph_info[i].cluster)) {
  5920. if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
  5921. end = w[last_cluster_index].start;
  5922. } else {
  5923. for (unsigned int j = last_cluster_index; j < i; j++) {
  5924. w[j].end = glyph_info[i].cluster;
  5925. }
  5926. }
  5927. if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
  5928. w[last_cluster_index].flags |= GRAPHEME_IS_RTL;
  5929. }
  5930. if (last_cluster_valid) {
  5931. w[last_cluster_index].flags |= GRAPHEME_IS_VALID;
  5932. }
  5933. w[last_cluster_index].count = i - last_cluster_index;
  5934. last_cluster_index = i;
  5935. last_cluster_valid = true;
  5936. }
  5937. last_cluster_id = glyph_info[i].cluster;
  5938. Glyph &gl = w[i];
  5939. gl = Glyph();
  5940. gl.span_index = p_span;
  5941. gl.start = glyph_info[i].cluster;
  5942. gl.end = end;
  5943. gl.count = 0;
  5944. gl.font_rid = f;
  5945. gl.font_size = fs;
  5946. if (glyph_info[i].mask & HB_GLYPH_FLAG_UNSAFE_TO_BREAK) {
  5947. gl.flags |= GRAPHEME_IS_CONNECTED;
  5948. }
  5949. #if HB_VERSION_ATLEAST(5, 1, 0)
  5950. if (glyph_info[i].mask & HB_GLYPH_FLAG_SAFE_TO_INSERT_TATWEEL) {
  5951. gl.flags |= GRAPHEME_IS_SAFE_TO_INSERT_TATWEEL;
  5952. }
  5953. #endif
  5954. gl.index = glyph_info[i].codepoint;
  5955. if ((p_sd->text[glyph_info[i].cluster] == 0x0009) || u_isblank(p_sd->text[glyph_info[i].cluster]) || is_linebreak(p_sd->text[glyph_info[i].cluster])) {
  5956. adv_rem = 0.0; // Reset on blank.
  5957. }
  5958. if (gl.index != 0) {
  5959. FontGlyph fgl;
  5960. _ensure_glyph(fd, fss, gl.index | mod, fgl);
  5961. if (subpos) {
  5962. gl.x_off = (double)glyph_pos[i].x_offset / (64.0 / scale);
  5963. } else if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  5964. gl.x_off = Math::round(adv_rem + ((double)glyph_pos[i].x_offset / (64.0 / scale)));
  5965. } else {
  5966. gl.x_off = Math::round((double)glyph_pos[i].x_offset / (64.0 / scale));
  5967. }
  5968. if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  5969. gl.y_off = -Math::round((double)glyph_pos[i].y_offset / (64.0 / scale));
  5970. } else {
  5971. gl.y_off = -Math::round(adv_rem + ((double)glyph_pos[i].y_offset / (64.0 / scale)));
  5972. }
  5973. if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  5974. if (subpos) {
  5975. gl.advance = (double)glyph_pos[i].x_advance / (64.0 / scale) + ea;
  5976. } else {
  5977. double full_adv = adv_rem + ((double)glyph_pos[i].x_advance / (64.0 / scale) + ea);
  5978. gl.advance = Math::round(full_adv);
  5979. if (fd->keep_rounding_remainders) {
  5980. adv_rem = full_adv - gl.advance;
  5981. }
  5982. }
  5983. } else {
  5984. double full_adv = adv_rem + ((double)glyph_pos[i].y_advance / (64.0 / scale));
  5985. gl.advance = -Math::round(full_adv);
  5986. if (fd->keep_rounding_remainders) {
  5987. adv_rem = full_adv + gl.advance;
  5988. }
  5989. }
  5990. if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  5991. gl.y_off += _font_get_baseline_offset(gl.font_rid) * (double)(_font_get_ascent(gl.font_rid, gl.font_size) + _font_get_descent(gl.font_rid, gl.font_size));
  5992. } else {
  5993. gl.x_off += _font_get_baseline_offset(gl.font_rid) * (double)(_font_get_ascent(gl.font_rid, gl.font_size) + _font_get_descent(gl.font_rid, gl.font_size));
  5994. }
  5995. }
  5996. if (!last_run || i < glyph_count - 1) {
  5997. // Do not add extra spacing to the last glyph of the string.
  5998. if (sp_sp && is_whitespace(p_sd->text[glyph_info[i].cluster])) {
  5999. gl.advance += sp_sp;
  6000. } else {
  6001. gl.advance += sp_gl;
  6002. }
  6003. }
  6004. if (p_sd->preserve_control) {
  6005. last_cluster_valid = last_cluster_valid && ((glyph_info[i].codepoint != 0) || (p_sd->text[glyph_info[i].cluster] == 0x0009) || (u_isblank(p_sd->text[glyph_info[i].cluster]) && (gl.advance != 0)) || (!u_isblank(p_sd->text[glyph_info[i].cluster]) && is_linebreak(p_sd->text[glyph_info[i].cluster])));
  6006. } else {
  6007. last_cluster_valid = last_cluster_valid && ((glyph_info[i].codepoint != 0) || (p_sd->text[glyph_info[i].cluster] == 0x0009) || (u_isblank(p_sd->text[glyph_info[i].cluster]) && (gl.advance != 0)) || (!u_isblank(p_sd->text[glyph_info[i].cluster]) && !u_isgraph(p_sd->text[glyph_info[i].cluster])));
  6008. }
  6009. }
  6010. if (p_direction == HB_DIRECTION_LTR || p_direction == HB_DIRECTION_TTB) {
  6011. for (unsigned int j = last_cluster_index; j < glyph_count; j++) {
  6012. w[j].end = p_end;
  6013. }
  6014. }
  6015. w[last_cluster_index].count = glyph_count - last_cluster_index;
  6016. if (p_direction == HB_DIRECTION_RTL || p_direction == HB_DIRECTION_BTT) {
  6017. w[last_cluster_index].flags |= GRAPHEME_IS_RTL;
  6018. }
  6019. if (last_cluster_valid) {
  6020. w[last_cluster_index].flags |= GRAPHEME_IS_VALID;
  6021. }
  6022. // Fallback.
  6023. int failed_subrun_start = p_end + 1;
  6024. int failed_subrun_end = p_start;
  6025. for (unsigned int i = 0; i < glyph_count; i++) {
  6026. if ((w[i].flags & GRAPHEME_IS_VALID) == GRAPHEME_IS_VALID) {
  6027. if (failed_subrun_start != p_end + 1) {
  6028. _shape_run(p_sd, failed_subrun_start, failed_subrun_end, p_script, p_direction, p_fonts, p_span, p_fb_index + 1, p_start, p_end, (p_fb_index >= p_fonts.size()) ? f : RID());
  6029. failed_subrun_start = p_end + 1;
  6030. failed_subrun_end = p_start;
  6031. }
  6032. for (int j = 0; j < w[i].count; j++) {
  6033. if (p_sd->orientation == ORIENTATION_HORIZONTAL) {
  6034. p_sd->ascent = MAX(p_sd->ascent, -w[i + j].y_off);
  6035. p_sd->descent = MAX(p_sd->descent, w[i + j].y_off);
  6036. } else {
  6037. double gla = Math::round(_font_get_glyph_advance(f, fs, w[i + j].index).x * 0.5);
  6038. p_sd->ascent = MAX(p_sd->ascent, gla);
  6039. p_sd->descent = MAX(p_sd->descent, gla);
  6040. }
  6041. p_sd->width += w[i + j].advance;
  6042. w[i + j].start += p_sd->start;
  6043. w[i + j].end += p_sd->start;
  6044. p_sd->glyphs.push_back(w[i + j]);
  6045. }
  6046. } else {
  6047. if (failed_subrun_start >= w[i].start) {
  6048. failed_subrun_start = w[i].start;
  6049. }
  6050. if (failed_subrun_end <= w[i].end) {
  6051. failed_subrun_end = w[i].end;
  6052. }
  6053. }
  6054. i += w[i].count - 1;
  6055. }
  6056. memfree(w);
  6057. if (failed_subrun_start != p_end + 1) {
  6058. _shape_run(p_sd, failed_subrun_start, failed_subrun_end, p_script, p_direction, p_fonts, p_span, p_fb_index + 1, p_start, p_end, (p_fb_index >= p_fonts.size()) ? f : RID());
  6059. }
  6060. p_sd->ascent = MAX(p_sd->ascent, _font_get_ascent(f, fs) + _font_get_spacing(f, SPACING_TOP));
  6061. p_sd->descent = MAX(p_sd->descent, _font_get_descent(f, fs) + _font_get_spacing(f, SPACING_BOTTOM));
  6062. p_sd->upos = MAX(p_sd->upos, _font_get_underline_position(f, fs));
  6063. p_sd->uthk = MAX(p_sd->uthk, _font_get_underline_thickness(f, fs));
  6064. } else if (p_start != p_end) {
  6065. if (p_fb_index >= p_fonts.size()) {
  6066. Glyph gl;
  6067. gl.start = p_start;
  6068. gl.end = p_end;
  6069. gl.span_index = p_span;
  6070. gl.font_rid = f;
  6071. gl.font_size = fs;
  6072. gl.flags = GRAPHEME_IS_VALID;
  6073. p_sd->glyphs.push_back(gl);
  6074. p_sd->ascent = MAX(p_sd->ascent, _font_get_ascent(f, fs) + _font_get_spacing(f, SPACING_TOP));
  6075. p_sd->descent = MAX(p_sd->descent, _font_get_descent(f, fs) + _font_get_spacing(f, SPACING_BOTTOM));
  6076. p_sd->upos = MAX(p_sd->upos, _font_get_underline_position(f, fs));
  6077. p_sd->uthk = MAX(p_sd->uthk, _font_get_underline_thickness(f, fs));
  6078. } else {
  6079. _shape_run(p_sd, p_start, p_end, p_script, p_direction, p_fonts, p_span, p_fb_index + 1, p_start, p_end, f);
  6080. }
  6081. }
  6082. }
  6083. bool TextServerAdvanced::_shaped_text_shape(const RID &p_shaped) {
  6084. _THREAD_SAFE_METHOD_
  6085. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6086. ERR_FAIL_NULL_V(sd, false);
  6087. MutexLock lock(sd->mutex);
  6088. if (sd->valid.is_set()) {
  6089. return true;
  6090. }
  6091. invalidate(sd, false);
  6092. if (sd->parent != RID()) {
  6093. _shaped_text_shape(sd->parent);
  6094. ShapedTextDataAdvanced *parent_sd = shaped_owner.get_or_null(sd->parent);
  6095. ERR_FAIL_COND_V(!parent_sd->valid.is_set(), false);
  6096. ERR_FAIL_COND_V(!_shape_substr(sd, parent_sd, sd->start, sd->end - sd->start), false);
  6097. return true;
  6098. }
  6099. if (sd->text.length() == 0) {
  6100. sd->valid.set();
  6101. return true;
  6102. }
  6103. sd->utf16 = sd->text.utf16();
  6104. const UChar *data = sd->utf16.get_data();
  6105. // Create script iterator.
  6106. if (sd->script_iter == nullptr) {
  6107. sd->script_iter = memnew(ScriptIterator(sd->text, 0, sd->text.length()));
  6108. }
  6109. sd->base_para_direction = UBIDI_DEFAULT_LTR;
  6110. switch (sd->direction) {
  6111. case DIRECTION_LTR: {
  6112. sd->para_direction = DIRECTION_LTR;
  6113. sd->base_para_direction = UBIDI_LTR;
  6114. } break;
  6115. case DIRECTION_RTL: {
  6116. sd->para_direction = DIRECTION_RTL;
  6117. sd->base_para_direction = UBIDI_RTL;
  6118. } break;
  6119. case DIRECTION_INHERITED:
  6120. case DIRECTION_AUTO: {
  6121. UBiDiDirection direction = ubidi_getBaseDirection(data, sd->utf16.length());
  6122. if (direction != UBIDI_NEUTRAL) {
  6123. sd->para_direction = (direction == UBIDI_RTL) ? DIRECTION_RTL : DIRECTION_LTR;
  6124. sd->base_para_direction = direction;
  6125. } else {
  6126. const String &lang = (sd->spans.is_empty() || sd->spans[0].language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : sd->spans[0].language;
  6127. bool lang_rtl = _is_locale_right_to_left(lang);
  6128. sd->para_direction = lang_rtl ? DIRECTION_RTL : DIRECTION_LTR;
  6129. sd->base_para_direction = lang_rtl ? UBIDI_DEFAULT_RTL : UBIDI_DEFAULT_LTR;
  6130. }
  6131. } break;
  6132. }
  6133. Vector<Vector3i> bidi_ranges;
  6134. if (sd->bidi_override.is_empty()) {
  6135. bidi_ranges.push_back(Vector3i(sd->start, sd->end, DIRECTION_INHERITED));
  6136. } else {
  6137. bidi_ranges = sd->bidi_override;
  6138. }
  6139. sd->runs.clear();
  6140. sd->runs_dirty = true;
  6141. for (int ov = 0; ov < bidi_ranges.size(); ov++) {
  6142. // Create BiDi iterator.
  6143. int start = _convert_pos_inv(sd, bidi_ranges[ov].x - sd->start);
  6144. int end = _convert_pos_inv(sd, bidi_ranges[ov].y - sd->start);
  6145. if (start < 0 || end - start > sd->utf16.length()) {
  6146. continue;
  6147. }
  6148. UErrorCode err = U_ZERO_ERROR;
  6149. UBiDi *bidi_iter = ubidi_openSized(end - start, 0, &err);
  6150. if (U_SUCCESS(err)) {
  6151. switch (static_cast<TextServer::Direction>(bidi_ranges[ov].z)) {
  6152. case DIRECTION_LTR: {
  6153. ubidi_setPara(bidi_iter, data + start, end - start, UBIDI_LTR, nullptr, &err);
  6154. } break;
  6155. case DIRECTION_RTL: {
  6156. ubidi_setPara(bidi_iter, data + start, end - start, UBIDI_RTL, nullptr, &err);
  6157. } break;
  6158. case DIRECTION_INHERITED: {
  6159. ubidi_setPara(bidi_iter, data + start, end - start, sd->base_para_direction, nullptr, &err);
  6160. } break;
  6161. case DIRECTION_AUTO: {
  6162. UBiDiDirection direction = ubidi_getBaseDirection(data + start, end - start);
  6163. if (direction != UBIDI_NEUTRAL) {
  6164. ubidi_setPara(bidi_iter, data + start, end - start, direction, nullptr, &err);
  6165. } else {
  6166. ubidi_setPara(bidi_iter, data + start, end - start, sd->base_para_direction, nullptr, &err);
  6167. }
  6168. } break;
  6169. }
  6170. if (U_FAILURE(err)) {
  6171. ubidi_close(bidi_iter);
  6172. bidi_iter = nullptr;
  6173. ERR_PRINT(vformat("BiDi reordering for the paragraph failed: %s", u_errorName(err)));
  6174. }
  6175. } else {
  6176. bidi_iter = nullptr;
  6177. ERR_PRINT(vformat("BiDi iterator allocation for the paragraph failed: %s", u_errorName(err)));
  6178. }
  6179. sd->bidi_iter.push_back(bidi_iter);
  6180. err = U_ZERO_ERROR;
  6181. int bidi_run_count = 1;
  6182. if (bidi_iter) {
  6183. bidi_run_count = ubidi_countRuns(bidi_iter, &err);
  6184. if (U_FAILURE(err)) {
  6185. ERR_PRINT(u_errorName(err));
  6186. }
  6187. }
  6188. for (int i = 0; i < bidi_run_count; i++) {
  6189. int32_t _bidi_run_start = 0;
  6190. int32_t _bidi_run_length = end - start;
  6191. bool is_ltr = false;
  6192. hb_direction_t bidi_run_direction = HB_DIRECTION_INVALID;
  6193. if (bidi_iter) {
  6194. is_ltr = (ubidi_getVisualRun(bidi_iter, i, &_bidi_run_start, &_bidi_run_length) == UBIDI_LTR);
  6195. }
  6196. switch (sd->orientation) {
  6197. case ORIENTATION_HORIZONTAL: {
  6198. if (is_ltr) {
  6199. bidi_run_direction = HB_DIRECTION_LTR;
  6200. } else {
  6201. bidi_run_direction = HB_DIRECTION_RTL;
  6202. }
  6203. } break;
  6204. case ORIENTATION_VERTICAL: {
  6205. if (is_ltr) {
  6206. bidi_run_direction = HB_DIRECTION_TTB;
  6207. } else {
  6208. bidi_run_direction = HB_DIRECTION_BTT;
  6209. }
  6210. }
  6211. }
  6212. int32_t bidi_run_start = _convert_pos(sd, start + _bidi_run_start);
  6213. int32_t bidi_run_end = _convert_pos(sd, start + _bidi_run_start + _bidi_run_length);
  6214. // Shape runs.
  6215. int scr_from = (is_ltr) ? 0 : sd->script_iter->script_ranges.size() - 1;
  6216. int scr_to = (is_ltr) ? sd->script_iter->script_ranges.size() : -1;
  6217. int scr_delta = (is_ltr) ? +1 : -1;
  6218. for (int j = scr_from; j != scr_to; j += scr_delta) {
  6219. if ((sd->script_iter->script_ranges[j].start < bidi_run_end) && (sd->script_iter->script_ranges[j].end > bidi_run_start)) {
  6220. int32_t script_run_start = MAX(sd->script_iter->script_ranges[j].start, bidi_run_start);
  6221. int32_t script_run_end = MIN(sd->script_iter->script_ranges[j].end, bidi_run_end);
  6222. char scr_buffer[5] = { 0, 0, 0, 0, 0 };
  6223. hb_tag_to_string(hb_script_to_iso15924_tag(sd->script_iter->script_ranges[j].script), scr_buffer);
  6224. String script_code = String(scr_buffer);
  6225. int spn_from = (is_ltr) ? 0 : sd->spans.size() - 1;
  6226. int spn_to = (is_ltr) ? sd->spans.size() : -1;
  6227. int spn_delta = (is_ltr) ? +1 : -1;
  6228. for (int k = spn_from; k != spn_to; k += spn_delta) {
  6229. const ShapedTextDataAdvanced::Span &span = sd->spans[k];
  6230. int col_key_off = (span.start == span.end) ? 1 : 0;
  6231. if (span.start - sd->start >= script_run_end || span.end - sd->start <= script_run_start - col_key_off) {
  6232. continue;
  6233. }
  6234. if (span.embedded_key != Variant()) {
  6235. // Embedded object.
  6236. if (sd->orientation == ORIENTATION_HORIZONTAL) {
  6237. sd->objects[span.embedded_key].rect.position.x = sd->width;
  6238. sd->width += sd->objects[span.embedded_key].rect.size.x;
  6239. } else {
  6240. sd->objects[span.embedded_key].rect.position.y = sd->width;
  6241. sd->width += sd->objects[span.embedded_key].rect.size.y;
  6242. }
  6243. Glyph gl;
  6244. gl.start = span.start;
  6245. gl.end = span.end;
  6246. gl.count = 1;
  6247. gl.span_index = k;
  6248. gl.flags = GRAPHEME_IS_VALID | GRAPHEME_IS_EMBEDDED_OBJECT;
  6249. if (sd->orientation == ORIENTATION_HORIZONTAL) {
  6250. gl.advance = sd->objects[span.embedded_key].rect.size.x;
  6251. } else {
  6252. gl.advance = sd->objects[span.embedded_key].rect.size.y;
  6253. }
  6254. sd->glyphs.push_back(gl);
  6255. } else {
  6256. Array fonts;
  6257. Array fonts_scr_only;
  6258. Array fonts_no_match;
  6259. int font_count = span.fonts.size();
  6260. if (font_count > 0) {
  6261. fonts.push_back(sd->spans[k].fonts[0]);
  6262. }
  6263. for (int l = 1; l < font_count; l++) {
  6264. if (_font_is_script_supported(span.fonts[l], script_code)) {
  6265. if (_font_is_language_supported(span.fonts[l], span.language)) {
  6266. fonts.push_back(sd->spans[k].fonts[l]);
  6267. } else {
  6268. fonts_scr_only.push_back(sd->spans[k].fonts[l]);
  6269. }
  6270. } else {
  6271. fonts_no_match.push_back(sd->spans[k].fonts[l]);
  6272. }
  6273. }
  6274. fonts.append_array(fonts_scr_only);
  6275. fonts.append_array(fonts_no_match);
  6276. _shape_run(sd, MAX(sd->spans[k].start - sd->start, script_run_start), MIN(sd->spans[k].end - sd->start, script_run_end), sd->script_iter->script_ranges[j].script, bidi_run_direction, fonts, k, 0, 0, 0, RID());
  6277. }
  6278. }
  6279. }
  6280. }
  6281. }
  6282. }
  6283. _realign(sd);
  6284. sd->valid.set();
  6285. return sd->valid.is_set();
  6286. }
  6287. bool TextServerAdvanced::_shaped_text_is_ready(const RID &p_shaped) const {
  6288. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6289. ERR_FAIL_NULL_V(sd, false);
  6290. // Atomic read is safe and faster.
  6291. return sd->valid.is_set();
  6292. }
  6293. const Glyph *TextServerAdvanced::_shaped_text_get_glyphs(const RID &p_shaped) const {
  6294. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6295. ERR_FAIL_NULL_V(sd, nullptr);
  6296. MutexLock lock(sd->mutex);
  6297. if (!sd->valid.is_set()) {
  6298. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  6299. }
  6300. return sd->glyphs.ptr();
  6301. }
  6302. int64_t TextServerAdvanced::_shaped_text_get_glyph_count(const RID &p_shaped) const {
  6303. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6304. ERR_FAIL_NULL_V(sd, 0);
  6305. MutexLock lock(sd->mutex);
  6306. if (!sd->valid.is_set()) {
  6307. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  6308. }
  6309. return sd->glyphs.size();
  6310. }
  6311. const Glyph *TextServerAdvanced::_shaped_text_sort_logical(const RID &p_shaped) {
  6312. ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6313. ERR_FAIL_NULL_V(sd, nullptr);
  6314. MutexLock lock(sd->mutex);
  6315. if (!sd->valid.is_set()) {
  6316. _shaped_text_shape(p_shaped);
  6317. }
  6318. if (!sd->sort_valid) {
  6319. sd->glyphs_logical = sd->glyphs;
  6320. sd->glyphs_logical.sort_custom<GlyphCompare>();
  6321. sd->sort_valid = true;
  6322. }
  6323. return sd->glyphs_logical.ptr();
  6324. }
  6325. Vector2i TextServerAdvanced::_shaped_text_get_range(const RID &p_shaped) const {
  6326. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6327. ERR_FAIL_NULL_V(sd, Vector2i());
  6328. MutexLock lock(sd->mutex);
  6329. return Vector2(sd->start, sd->end);
  6330. }
  6331. Array TextServerAdvanced::_shaped_text_get_objects(const RID &p_shaped) const {
  6332. Array ret;
  6333. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6334. ERR_FAIL_NULL_V(sd, ret);
  6335. MutexLock lock(sd->mutex);
  6336. for (const KeyValue<Variant, ShapedTextDataAdvanced::EmbeddedObject> &E : sd->objects) {
  6337. ret.push_back(E.key);
  6338. }
  6339. return ret;
  6340. }
  6341. Rect2 TextServerAdvanced::_shaped_text_get_object_rect(const RID &p_shaped, const Variant &p_key) const {
  6342. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6343. ERR_FAIL_NULL_V(sd, Rect2());
  6344. MutexLock lock(sd->mutex);
  6345. ERR_FAIL_COND_V(!sd->objects.has(p_key), Rect2());
  6346. if (!sd->valid.is_set()) {
  6347. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  6348. }
  6349. return sd->objects[p_key].rect;
  6350. }
  6351. Vector2i TextServerAdvanced::_shaped_text_get_object_range(const RID &p_shaped, const Variant &p_key) const {
  6352. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6353. ERR_FAIL_NULL_V(sd, Vector2i());
  6354. MutexLock lock(sd->mutex);
  6355. ERR_FAIL_COND_V(!sd->objects.has(p_key), Vector2i());
  6356. return Vector2i(sd->objects[p_key].start, sd->objects[p_key].end);
  6357. }
  6358. int64_t TextServerAdvanced::_shaped_text_get_object_glyph(const RID &p_shaped, const Variant &p_key) const {
  6359. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6360. ERR_FAIL_NULL_V(sd, -1);
  6361. MutexLock lock(sd->mutex);
  6362. ERR_FAIL_COND_V(!sd->objects.has(p_key), -1);
  6363. if (!sd->valid.is_set()) {
  6364. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  6365. }
  6366. const ShapedTextDataAdvanced::EmbeddedObject &obj = sd->objects[p_key];
  6367. int sd_size = sd->glyphs.size();
  6368. const Glyph *sd_glyphs = sd->glyphs.ptr();
  6369. for (int i = 0; i < sd_size; i++) {
  6370. if (obj.start == sd_glyphs[i].start) {
  6371. return i;
  6372. }
  6373. }
  6374. return -1;
  6375. }
  6376. Size2 TextServerAdvanced::_shaped_text_get_size(const RID &p_shaped) const {
  6377. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6378. ERR_FAIL_NULL_V(sd, Size2());
  6379. MutexLock lock(sd->mutex);
  6380. if (!sd->valid.is_set()) {
  6381. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  6382. }
  6383. if (sd->orientation == TextServer::ORIENTATION_HORIZONTAL) {
  6384. return Size2((sd->text_trimmed ? sd->width_trimmed : sd->width), sd->ascent + sd->descent + sd->extra_spacing[SPACING_TOP] + sd->extra_spacing[SPACING_BOTTOM]).ceil();
  6385. } else {
  6386. return Size2(sd->ascent + sd->descent + sd->extra_spacing[SPACING_TOP] + sd->extra_spacing[SPACING_BOTTOM], (sd->text_trimmed ? sd->width_trimmed : sd->width)).ceil();
  6387. }
  6388. }
  6389. double TextServerAdvanced::_shaped_text_get_ascent(const RID &p_shaped) const {
  6390. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6391. ERR_FAIL_NULL_V(sd, 0.0);
  6392. MutexLock lock(sd->mutex);
  6393. if (!sd->valid.is_set()) {
  6394. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  6395. }
  6396. return sd->ascent + sd->extra_spacing[SPACING_TOP];
  6397. }
  6398. double TextServerAdvanced::_shaped_text_get_descent(const RID &p_shaped) const {
  6399. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6400. ERR_FAIL_NULL_V(sd, 0.0);
  6401. MutexLock lock(sd->mutex);
  6402. if (!sd->valid.is_set()) {
  6403. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  6404. }
  6405. return sd->descent + sd->extra_spacing[SPACING_BOTTOM];
  6406. }
  6407. double TextServerAdvanced::_shaped_text_get_width(const RID &p_shaped) const {
  6408. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6409. ERR_FAIL_NULL_V(sd, 0.0);
  6410. MutexLock lock(sd->mutex);
  6411. if (!sd->valid.is_set()) {
  6412. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  6413. }
  6414. return Math::ceil(sd->text_trimmed ? sd->width_trimmed : sd->width);
  6415. }
  6416. double TextServerAdvanced::_shaped_text_get_underline_position(const RID &p_shaped) const {
  6417. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6418. ERR_FAIL_NULL_V(sd, 0.0);
  6419. MutexLock lock(sd->mutex);
  6420. if (!sd->valid.is_set()) {
  6421. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  6422. }
  6423. return sd->upos;
  6424. }
  6425. double TextServerAdvanced::_shaped_text_get_underline_thickness(const RID &p_shaped) const {
  6426. const ShapedTextDataAdvanced *sd = shaped_owner.get_or_null(p_shaped);
  6427. ERR_FAIL_NULL_V(sd, 0.0);
  6428. MutexLock lock(sd->mutex);
  6429. if (!sd->valid.is_set()) {
  6430. const_cast<TextServerAdvanced *>(this)->_shaped_text_shape(p_shaped);
  6431. }
  6432. return sd->uthk;
  6433. }
  6434. void TextServerAdvanced::_insert_num_systems_lang() {
  6435. // Eastern Arabic numerals.
  6436. {
  6437. NumSystemData ar;
  6438. ar.lang.insert(StringName("ar")); // Arabic
  6439. ar.lang.insert(StringName("ar_AE"));
  6440. ar.lang.insert(StringName("ar_BH"));
  6441. ar.lang.insert(StringName("ar_DJ"));
  6442. ar.lang.insert(StringName("ar_EG"));
  6443. ar.lang.insert(StringName("ar_ER"));
  6444. ar.lang.insert(StringName("ar_IL"));
  6445. ar.lang.insert(StringName("ar_IQ"));
  6446. ar.lang.insert(StringName("ar_JO"));
  6447. ar.lang.insert(StringName("ar_KM"));
  6448. ar.lang.insert(StringName("ar_KW"));
  6449. ar.lang.insert(StringName("ar_LB"));
  6450. ar.lang.insert(StringName("ar_MR"));
  6451. ar.lang.insert(StringName("ar_OM"));
  6452. ar.lang.insert(StringName("ar_PS"));
  6453. ar.lang.insert(StringName("ar_QA"));
  6454. ar.lang.insert(StringName("ar_SA"));
  6455. ar.lang.insert(StringName("ar_SD"));
  6456. ar.lang.insert(StringName("ar_SO"));
  6457. ar.lang.insert(StringName("ar_SS"));
  6458. ar.lang.insert(StringName("ar_SY"));
  6459. ar.lang.insert(StringName("ar_TD"));
  6460. ar.lang.insert(StringName("ar_YE"));
  6461. ar.lang.insert(StringName("ckb")); // Central Kurdish
  6462. ar.lang.insert(StringName("ckb_IQ"));
  6463. ar.lang.insert(StringName("ckb_IR"));
  6464. ar.lang.insert(StringName("sd")); // Sindhi
  6465. ar.lang.insert(StringName("sd_PK"));
  6466. ar.lang.insert(StringName("sd_Arab"));
  6467. ar.lang.insert(StringName("sd_Arab_PK"));
  6468. ar.digits = U"٠١٢٣٤٥٦٧٨٩٫";
  6469. ar.percent_sign = U"٪";
  6470. ar.exp_l = U"اس";
  6471. ar.exp_u = U"اس";
  6472. num_systems.push_back(ar);
  6473. }
  6474. // Persian and Urdu numerals.
  6475. {
  6476. NumSystemData pr;
  6477. pr.lang.insert(StringName("fa")); // Persian
  6478. pr.lang.insert(StringName("fa_AF"));
  6479. pr.lang.insert(StringName("fa_IR"));
  6480. pr.lang.insert(StringName("ks")); // Kashmiri
  6481. pr.lang.insert(StringName("ks_IN"));
  6482. pr.lang.insert(StringName("ks_Arab"));
  6483. pr.lang.insert(StringName("ks_Arab_IN"));
  6484. pr.lang.insert(StringName("lrc")); // Northern Luri
  6485. pr.lang.insert(StringName("lrc_IQ"));
  6486. pr.lang.insert(StringName("lrc_IR"));
  6487. pr.lang.insert(StringName("mzn")); // Mazanderani
  6488. pr.lang.insert(StringName("mzn_IR"));
  6489. pr.lang.insert(StringName("pa_PK")); // Panjabi
  6490. pr.lang.insert(StringName("pa_Arab"));
  6491. pr.lang.insert(StringName("pa_Arab_PK"));
  6492. pr.lang.insert(StringName("ps")); // Pushto
  6493. pr.lang.insert(StringName("ps_AF"));
  6494. pr.lang.insert(StringName("ps_PK"));
  6495. pr.lang.insert(StringName("ur_IN")); // Urdu
  6496. pr.lang.insert(StringName("uz_AF")); // Uzbek
  6497. pr.lang.insert(StringName("uz_Arab"));
  6498. pr.lang.insert(StringName("uz_Arab_AF"));
  6499. pr.digits = U"۰۱۲۳۴۵۶۷۸۹٫";
  6500. pr.percent_sign = U"٪";
  6501. pr.exp_l = U"اس";
  6502. pr.exp_u = U"اس";
  6503. num_systems.push_back(pr);
  6504. }
  6505. // Bengali numerals.
  6506. {
  6507. NumSystemData bn;
  6508. bn.lang.insert(StringName("as")); // Assamese
  6509. bn.lang.insert(StringName("as_IN"));
  6510. bn.lang.insert(StringName("bn")); // Bengali
  6511. bn.lang.insert(StringName("bn_BD"));
  6512. bn.lang.insert(StringName("bn_IN"));
  6513. bn.lang.insert(StringName("mni")); // Manipuri
  6514. bn.lang.insert(StringName("mni_IN"));
  6515. bn.lang.insert(StringName("mni_Beng"));
  6516. bn.lang.insert(StringName("mni_Beng_IN"));
  6517. bn.digits = U"০১২৩৪৫৬৭৮৯.";
  6518. bn.percent_sign = U"%";
  6519. bn.exp_l = U"e";
  6520. bn.exp_u = U"E";
  6521. num_systems.push_back(bn);
  6522. }
  6523. // Devanagari numerals.
  6524. {
  6525. NumSystemData mr;
  6526. mr.lang.insert(StringName("mr")); // Marathi
  6527. mr.lang.insert(StringName("mr_IN"));
  6528. mr.lang.insert(StringName("ne")); // Nepali
  6529. mr.lang.insert(StringName("ne_IN"));
  6530. mr.lang.insert(StringName("ne_NP"));
  6531. mr.lang.insert(StringName("sa")); // Sanskrit
  6532. mr.lang.insert(StringName("sa_IN"));
  6533. mr.digits = U"०१२३४५६७८९.";
  6534. mr.percent_sign = U"%";
  6535. mr.exp_l = U"e";
  6536. mr.exp_u = U"E";
  6537. num_systems.push_back(mr);
  6538. }
  6539. // Dzongkha numerals.
  6540. {
  6541. NumSystemData dz;
  6542. dz.lang.insert(StringName("dz")); // Dzongkha
  6543. dz.lang.insert(StringName("dz_BT"));
  6544. dz.digits = U"༠༡༢༣༤༥༦༧༨༩.";
  6545. dz.percent_sign = U"%";
  6546. dz.exp_l = U"e";
  6547. dz.exp_u = U"E";
  6548. num_systems.push_back(dz);
  6549. }
  6550. // Santali numerals.
  6551. {
  6552. NumSystemData sat;
  6553. sat.lang.insert(StringName("sat")); // Santali
  6554. sat.lang.insert(StringName("sat_IN"));
  6555. sat.lang.insert(StringName("sat_Olck"));
  6556. sat.lang.insert(StringName("sat_Olck_IN"));
  6557. sat.digits = U"᱐᱑᱒᱓᱔᱕᱖᱗᱘᱙.";
  6558. sat.percent_sign = U"%";
  6559. sat.exp_l = U"e";
  6560. sat.exp_u = U"E";
  6561. num_systems.push_back(sat);
  6562. }
  6563. // Burmese numerals.
  6564. {
  6565. NumSystemData my;
  6566. my.lang.insert(StringName("my")); // Burmese
  6567. my.lang.insert(StringName("my_MM"));
  6568. my.digits = U"၀၁၂၃၄၅၆၇၈၉.";
  6569. my.percent_sign = U"%";
  6570. my.exp_l = U"e";
  6571. my.exp_u = U"E";
  6572. num_systems.push_back(my);
  6573. }
  6574. // Chakma numerals.
  6575. {
  6576. NumSystemData ccp;
  6577. ccp.lang.insert(StringName("ccp")); // Chakma
  6578. ccp.lang.insert(StringName("ccp_BD"));
  6579. ccp.lang.insert(StringName("ccp_IN"));
  6580. ccp.digits = U"𑄶𑄷𑄸𑄹𑄺𑄻𑄼𑄽𑄾𑄿.";
  6581. ccp.percent_sign = U"%";
  6582. ccp.exp_l = U"e";
  6583. ccp.exp_u = U"E";
  6584. num_systems.push_back(ccp);
  6585. }
  6586. // Adlam numerals.
  6587. {
  6588. NumSystemData ff;
  6589. ff.lang.insert(StringName("ff")); // Fulah
  6590. ff.lang.insert(StringName("ff_Adlm_BF"));
  6591. ff.lang.insert(StringName("ff_Adlm_CM"));
  6592. ff.lang.insert(StringName("ff_Adlm_GH"));
  6593. ff.lang.insert(StringName("ff_Adlm_GM"));
  6594. ff.lang.insert(StringName("ff_Adlm_GN"));
  6595. ff.lang.insert(StringName("ff_Adlm_GW"));
  6596. ff.lang.insert(StringName("ff_Adlm_LR"));
  6597. ff.lang.insert(StringName("ff_Adlm_MR"));
  6598. ff.lang.insert(StringName("ff_Adlm_NE"));
  6599. ff.lang.insert(StringName("ff_Adlm_NG"));
  6600. ff.lang.insert(StringName("ff_Adlm_SL"));
  6601. ff.lang.insert(StringName("ff_Adlm_SN"));
  6602. ff.digits = U"𞥐𞥑𞥒𞥓𞥔𞥕𞥖𞥗𞥘𞥙.";
  6603. ff.percent_sign = U"%";
  6604. ff.exp_l = U"𞤉";
  6605. ff.exp_u = U"𞤉";
  6606. num_systems.push_back(ff);
  6607. }
  6608. }
  6609. String TextServerAdvanced::_format_number(const String &p_string, const String &p_language) const {
  6610. const StringName lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  6611. String res = p_string;
  6612. for (int i = 0; i < num_systems.size(); i++) {
  6613. if (num_systems[i].lang.has(lang)) {
  6614. if (num_systems[i].digits.is_empty()) {
  6615. return p_string;
  6616. }
  6617. res = res.replace("e", num_systems[i].exp_l);
  6618. res = res.replace("E", num_systems[i].exp_u);
  6619. char32_t *data = res.ptrw();
  6620. for (int j = 0; j < res.length(); j++) {
  6621. if (data[j] >= 0x30 && data[j] <= 0x39) {
  6622. data[j] = num_systems[i].digits[data[j] - 0x30];
  6623. } else if (data[j] == '.' || data[j] == ',') {
  6624. data[j] = num_systems[i].digits[10];
  6625. }
  6626. }
  6627. break;
  6628. }
  6629. }
  6630. return res;
  6631. }
  6632. String TextServerAdvanced::_parse_number(const String &p_string, const String &p_language) const {
  6633. const StringName lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  6634. String res = p_string;
  6635. for (int i = 0; i < num_systems.size(); i++) {
  6636. if (num_systems[i].lang.has(lang)) {
  6637. if (num_systems[i].digits.is_empty()) {
  6638. return p_string;
  6639. }
  6640. res = res.replace(num_systems[i].exp_l, "e");
  6641. res = res.replace(num_systems[i].exp_u, "E");
  6642. char32_t *data = res.ptrw();
  6643. for (int j = 0; j < res.length(); j++) {
  6644. if (data[j] == num_systems[i].digits[10]) {
  6645. data[j] = '.';
  6646. } else {
  6647. for (int k = 0; k < 10; k++) {
  6648. if (data[j] == num_systems[i].digits[k]) {
  6649. data[j] = 0x30 + k;
  6650. }
  6651. }
  6652. }
  6653. }
  6654. break;
  6655. }
  6656. }
  6657. return res;
  6658. }
  6659. String TextServerAdvanced::_percent_sign(const String &p_language) const {
  6660. const StringName lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  6661. for (int i = 0; i < num_systems.size(); i++) {
  6662. if (num_systems[i].lang.has(lang)) {
  6663. if (num_systems[i].percent_sign.is_empty()) {
  6664. return "%";
  6665. }
  6666. return num_systems[i].percent_sign;
  6667. }
  6668. }
  6669. return "%";
  6670. }
  6671. int64_t TextServerAdvanced::_is_confusable(const String &p_string, const PackedStringArray &p_dict) const {
  6672. #ifndef ICU_STATIC_DATA
  6673. if (!icu_data_loaded) {
  6674. return -1;
  6675. }
  6676. #endif
  6677. UErrorCode status = U_ZERO_ERROR;
  6678. int64_t match_index = -1;
  6679. Char16String utf16 = p_string.utf16();
  6680. Vector<UChar *> skeletons;
  6681. skeletons.resize(p_dict.size());
  6682. if (sc_conf == nullptr) {
  6683. sc_conf = uspoof_open(&status);
  6684. uspoof_setChecks(sc_conf, USPOOF_CONFUSABLE, &status);
  6685. }
  6686. for (int i = 0; i < p_dict.size(); i++) {
  6687. Char16String word = p_dict[i].utf16();
  6688. int32_t len = uspoof_getSkeleton(sc_conf, 0, word.get_data(), -1, nullptr, 0, &status);
  6689. skeletons.write[i] = (UChar *)memalloc(++len * sizeof(UChar));
  6690. status = U_ZERO_ERROR;
  6691. uspoof_getSkeleton(sc_conf, 0, word.get_data(), -1, skeletons.write[i], len, &status);
  6692. }
  6693. int32_t len = uspoof_getSkeleton(sc_conf, 0, utf16.get_data(), -1, nullptr, 0, &status);
  6694. UChar *skel = (UChar *)memalloc(++len * sizeof(UChar));
  6695. status = U_ZERO_ERROR;
  6696. uspoof_getSkeleton(sc_conf, 0, utf16.get_data(), -1, skel, len, &status);
  6697. for (int i = 0; i < skeletons.size(); i++) {
  6698. if (u_strcmp(skel, skeletons[i]) == 0) {
  6699. match_index = i;
  6700. break;
  6701. }
  6702. }
  6703. memfree(skel);
  6704. for (int i = 0; i < skeletons.size(); i++) {
  6705. memfree(skeletons.write[i]);
  6706. }
  6707. ERR_FAIL_COND_V_MSG(U_FAILURE(status), -1, u_errorName(status));
  6708. return match_index;
  6709. }
  6710. bool TextServerAdvanced::_spoof_check(const String &p_string) const {
  6711. #ifndef ICU_STATIC_DATA
  6712. if (!icu_data_loaded) {
  6713. return false;
  6714. }
  6715. #endif
  6716. UErrorCode status = U_ZERO_ERROR;
  6717. Char16String utf16 = p_string.utf16();
  6718. if (allowed == nullptr) {
  6719. allowed = uset_openEmpty();
  6720. uset_addAll(allowed, uspoof_getRecommendedSet(&status));
  6721. uset_addAll(allowed, uspoof_getInclusionSet(&status));
  6722. }
  6723. if (sc_spoof == nullptr) {
  6724. sc_spoof = uspoof_open(&status);
  6725. uspoof_setAllowedChars(sc_spoof, allowed, &status);
  6726. uspoof_setRestrictionLevel(sc_spoof, USPOOF_MODERATELY_RESTRICTIVE);
  6727. }
  6728. int32_t bitmask = uspoof_check(sc_spoof, utf16.get_data(), -1, nullptr, &status);
  6729. ERR_FAIL_COND_V_MSG(U_FAILURE(status), false, u_errorName(status));
  6730. return (bitmask != 0);
  6731. }
  6732. String TextServerAdvanced::_strip_diacritics(const String &p_string) const {
  6733. #ifndef ICU_STATIC_DATA
  6734. if (!icu_data_loaded) {
  6735. return TextServer::strip_diacritics(p_string);
  6736. }
  6737. #endif
  6738. UErrorCode err = U_ZERO_ERROR;
  6739. // Get NFKD normalizer singleton.
  6740. const UNormalizer2 *unorm = unorm2_getNFKDInstance(&err);
  6741. ERR_FAIL_COND_V_MSG(U_FAILURE(err), TextServer::strip_diacritics(p_string), u_errorName(err));
  6742. // Convert to UTF-16.
  6743. Char16String utf16 = p_string.utf16();
  6744. // Normalize.
  6745. Vector<char16_t> normalized;
  6746. err = U_ZERO_ERROR;
  6747. int32_t len = unorm2_normalize(unorm, utf16.get_data(), -1, nullptr, 0, &err);
  6748. ERR_FAIL_COND_V_MSG(err != U_BUFFER_OVERFLOW_ERROR, TextServer::strip_diacritics(p_string), u_errorName(err));
  6749. normalized.resize(len);
  6750. err = U_ZERO_ERROR;
  6751. unorm2_normalize(unorm, utf16.get_data(), -1, normalized.ptrw(), len, &err);
  6752. ERR_FAIL_COND_V_MSG(U_FAILURE(err), TextServer::strip_diacritics(p_string), u_errorName(err));
  6753. // Convert back to UTF-32.
  6754. String normalized_string = String::utf16(normalized.ptr(), len);
  6755. // Strip combining characters.
  6756. String result;
  6757. for (int i = 0; i < normalized_string.length(); i++) {
  6758. if (u_getCombiningClass(normalized_string[i]) == 0) {
  6759. #ifdef GDEXTENSION
  6760. result = result + String::chr(normalized_string[i]);
  6761. #elif defined(GODOT_MODULE)
  6762. result = result + normalized_string[i];
  6763. #endif
  6764. }
  6765. }
  6766. return result;
  6767. }
  6768. String TextServerAdvanced::_string_to_upper(const String &p_string, const String &p_language) const {
  6769. #ifndef ICU_STATIC_DATA
  6770. if (!icu_data_loaded) {
  6771. return p_string.to_upper();
  6772. }
  6773. #endif
  6774. if (p_string.is_empty()) {
  6775. return p_string;
  6776. }
  6777. const String lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  6778. // Convert to UTF-16.
  6779. Char16String utf16 = p_string.utf16();
  6780. Vector<char16_t> upper;
  6781. UErrorCode err = U_ZERO_ERROR;
  6782. int32_t len = u_strToUpper(nullptr, 0, utf16.get_data(), -1, lang.ascii().get_data(), &err);
  6783. ERR_FAIL_COND_V_MSG(err != U_BUFFER_OVERFLOW_ERROR, p_string, u_errorName(err));
  6784. upper.resize(len);
  6785. err = U_ZERO_ERROR;
  6786. u_strToUpper(upper.ptrw(), len, utf16.get_data(), -1, lang.ascii().get_data(), &err);
  6787. ERR_FAIL_COND_V_MSG(U_FAILURE(err), p_string, u_errorName(err));
  6788. // Convert back to UTF-32.
  6789. return String::utf16(upper.ptr(), len);
  6790. }
  6791. String TextServerAdvanced::_string_to_lower(const String &p_string, const String &p_language) const {
  6792. #ifndef ICU_STATIC_DATA
  6793. if (!icu_data_loaded) {
  6794. return p_string.to_lower();
  6795. }
  6796. #endif
  6797. if (p_string.is_empty()) {
  6798. return p_string;
  6799. }
  6800. const String lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  6801. // Convert to UTF-16.
  6802. Char16String utf16 = p_string.utf16();
  6803. Vector<char16_t> lower;
  6804. UErrorCode err = U_ZERO_ERROR;
  6805. int32_t len = u_strToLower(nullptr, 0, utf16.get_data(), -1, lang.ascii().get_data(), &err);
  6806. ERR_FAIL_COND_V_MSG(err != U_BUFFER_OVERFLOW_ERROR, p_string, u_errorName(err));
  6807. lower.resize(len);
  6808. err = U_ZERO_ERROR;
  6809. u_strToLower(lower.ptrw(), len, utf16.get_data(), -1, lang.ascii().get_data(), &err);
  6810. ERR_FAIL_COND_V_MSG(U_FAILURE(err), p_string, u_errorName(err));
  6811. // Convert back to UTF-32.
  6812. return String::utf16(lower.ptr(), len);
  6813. }
  6814. String TextServerAdvanced::_string_to_title(const String &p_string, const String &p_language) const {
  6815. #ifndef ICU_STATIC_DATA
  6816. if (!icu_data_loaded) {
  6817. return p_string.capitalize();
  6818. }
  6819. #endif
  6820. if (p_string.is_empty()) {
  6821. return p_string;
  6822. }
  6823. const String lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  6824. // Convert to UTF-16.
  6825. Char16String utf16 = p_string.utf16();
  6826. Vector<char16_t> upper;
  6827. UErrorCode err = U_ZERO_ERROR;
  6828. int32_t len = u_strToTitle(nullptr, 0, utf16.get_data(), -1, nullptr, lang.ascii().get_data(), &err);
  6829. ERR_FAIL_COND_V_MSG(err != U_BUFFER_OVERFLOW_ERROR, p_string, u_errorName(err));
  6830. upper.resize(len);
  6831. err = U_ZERO_ERROR;
  6832. u_strToTitle(upper.ptrw(), len, utf16.get_data(), -1, nullptr, lang.ascii().get_data(), &err);
  6833. ERR_FAIL_COND_V_MSG(U_FAILURE(err), p_string, u_errorName(err));
  6834. // Convert back to UTF-32.
  6835. return String::utf16(upper.ptr(), len);
  6836. }
  6837. PackedInt32Array TextServerAdvanced::_string_get_word_breaks(const String &p_string, const String &p_language, int64_t p_chars_per_line) const {
  6838. const String lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  6839. // Convert to UTF-16.
  6840. Char16String utf16 = p_string.utf16();
  6841. HashSet<int> breaks;
  6842. UErrorCode err = U_ZERO_ERROR;
  6843. UBreakIterator *bi = ubrk_open(UBRK_WORD, lang.ascii().get_data(), (const UChar *)utf16.get_data(), utf16.length(), &err);
  6844. if (U_SUCCESS(err)) {
  6845. while (ubrk_next(bi) != UBRK_DONE) {
  6846. int pos = _convert_pos(p_string, utf16, ubrk_current(bi));
  6847. if (pos != p_string.length() - 1) {
  6848. breaks.insert(pos);
  6849. }
  6850. }
  6851. ubrk_close(bi);
  6852. }
  6853. PackedInt32Array ret;
  6854. if (p_chars_per_line > 0) {
  6855. int line_start = 0;
  6856. int last_break = -1;
  6857. int line_length = 0;
  6858. for (int i = 0; i < p_string.length(); i++) {
  6859. const char32_t c = p_string[i];
  6860. bool is_lb = is_linebreak(c);
  6861. bool is_ws = is_whitespace(c);
  6862. bool is_p = (u_ispunct(c) && c != 0x005F) || is_underscore(c) || c == '\t' || c == 0xfffc;
  6863. if (is_lb) {
  6864. if (line_length > 0) {
  6865. ret.push_back(line_start);
  6866. ret.push_back(i);
  6867. }
  6868. line_start = i;
  6869. line_length = 0;
  6870. last_break = -1;
  6871. continue;
  6872. } else if (breaks.has(i) || is_ws || is_p) {
  6873. last_break = i;
  6874. }
  6875. if (line_length == p_chars_per_line) {
  6876. if (last_break != -1) {
  6877. int last_break_w_spaces = last_break;
  6878. while (last_break > line_start && is_whitespace(p_string[last_break - 1])) {
  6879. last_break--;
  6880. }
  6881. if (line_start != last_break) {
  6882. ret.push_back(line_start);
  6883. ret.push_back(last_break);
  6884. }
  6885. while (last_break_w_spaces < p_string.length() && is_whitespace(p_string[last_break_w_spaces])) {
  6886. last_break_w_spaces++;
  6887. }
  6888. line_start = last_break_w_spaces;
  6889. if (last_break_w_spaces < i) {
  6890. line_length = i - last_break_w_spaces;
  6891. } else {
  6892. i = last_break_w_spaces;
  6893. line_length = 0;
  6894. }
  6895. } else {
  6896. ret.push_back(line_start);
  6897. ret.push_back(i);
  6898. line_start = i;
  6899. line_length = 0;
  6900. }
  6901. last_break = -1;
  6902. }
  6903. line_length++;
  6904. }
  6905. if (line_length > 0) {
  6906. ret.push_back(line_start);
  6907. ret.push_back(p_string.length());
  6908. }
  6909. } else {
  6910. int word_start = 0; // -1 if no word encountered. Leading spaces are part of a word.
  6911. int word_length = 0;
  6912. for (int i = 0; i < p_string.length(); i++) {
  6913. const char32_t c = p_string[i];
  6914. bool is_lb = is_linebreak(c);
  6915. bool is_ws = is_whitespace(c);
  6916. bool is_p = (u_ispunct(c) && c != 0x005F) || is_underscore(c) || c == '\t' || c == 0xfffc;
  6917. if (word_start == -1) {
  6918. if (!is_lb && !is_ws && !is_p) {
  6919. word_start = i;
  6920. }
  6921. continue;
  6922. }
  6923. if (is_lb) {
  6924. if (word_start != -1 && word_length > 0) {
  6925. ret.push_back(word_start);
  6926. ret.push_back(i);
  6927. }
  6928. word_start = -1;
  6929. word_length = 0;
  6930. } else if (breaks.has(i) || is_ws || is_p) {
  6931. if (word_start != -1 && word_length > 0) {
  6932. ret.push_back(word_start);
  6933. ret.push_back(i);
  6934. }
  6935. if (is_ws || is_p) {
  6936. word_start = -1;
  6937. } else {
  6938. word_start = i;
  6939. }
  6940. word_length = 0;
  6941. }
  6942. word_length++;
  6943. }
  6944. if (word_start != -1 && word_length > 0) {
  6945. ret.push_back(word_start);
  6946. ret.push_back(p_string.length());
  6947. }
  6948. }
  6949. return ret;
  6950. }
  6951. PackedInt32Array TextServerAdvanced::_string_get_character_breaks(const String &p_string, const String &p_language) const {
  6952. const String lang = (p_language.is_empty()) ? TranslationServer::get_singleton()->get_tool_locale() : p_language;
  6953. // Convert to UTF-16.
  6954. Char16String utf16 = p_string.utf16();
  6955. PackedInt32Array ret;
  6956. UErrorCode err = U_ZERO_ERROR;
  6957. UBreakIterator *bi = ubrk_open(UBRK_CHARACTER, lang.ascii().get_data(), (const UChar *)utf16.get_data(), utf16.length(), &err);
  6958. if (U_SUCCESS(err)) {
  6959. while (ubrk_next(bi) != UBRK_DONE) {
  6960. int pos = _convert_pos(p_string, utf16, ubrk_current(bi));
  6961. ret.push_back(pos);
  6962. }
  6963. ubrk_close(bi);
  6964. } else {
  6965. return TextServer::string_get_character_breaks(p_string, p_language);
  6966. }
  6967. return ret;
  6968. }
  6969. bool TextServerAdvanced::_is_valid_identifier(const String &p_string) const {
  6970. #ifndef ICU_STATIC_DATA
  6971. if (!icu_data_loaded) {
  6972. WARN_PRINT_ONCE("ICU data is not loaded, Unicode security and spoofing detection disabled.");
  6973. return TextServer::is_valid_identifier(p_string);
  6974. }
  6975. #endif
  6976. enum UAX31SequenceStatus {
  6977. SEQ_NOT_STARTED,
  6978. SEQ_STARTED,
  6979. SEQ_STARTED_VIR,
  6980. SEQ_NEAR_END,
  6981. };
  6982. const char32_t *str = p_string.ptr();
  6983. int len = p_string.length();
  6984. if (len == 0) {
  6985. return false; // Empty string.
  6986. }
  6987. UErrorCode err = U_ZERO_ERROR;
  6988. Char16String utf16 = p_string.utf16();
  6989. const UNormalizer2 *norm_c = unorm2_getNFCInstance(&err);
  6990. if (U_FAILURE(err)) {
  6991. return false; // Failed to load normalizer.
  6992. }
  6993. bool isnurom = unorm2_isNormalized(norm_c, utf16.get_data(), utf16.length(), &err);
  6994. if (U_FAILURE(err) || !isnurom) {
  6995. return false; // Do not conform to Normalization Form C.
  6996. }
  6997. UAX31SequenceStatus A1_sequence_status = SEQ_NOT_STARTED;
  6998. UScriptCode A1_scr = USCRIPT_INHERITED;
  6999. UAX31SequenceStatus A2_sequence_status = SEQ_NOT_STARTED;
  7000. UScriptCode A2_scr = USCRIPT_INHERITED;
  7001. UAX31SequenceStatus B_sequence_status = SEQ_NOT_STARTED;
  7002. UScriptCode B_scr = USCRIPT_INHERITED;
  7003. for (int i = 0; i < len; i++) {
  7004. err = U_ZERO_ERROR;
  7005. UScriptCode scr = uscript_getScript(str[i], &err);
  7006. if (U_FAILURE(err)) {
  7007. return false; // Invalid script.
  7008. }
  7009. if (uscript_getUsage(scr) != USCRIPT_USAGE_RECOMMENDED) {
  7010. return false; // Not a recommended script.
  7011. }
  7012. uint8_t cat = u_charType(str[i]);
  7013. int32_t jt = u_getIntPropertyValue(str[i], UCHAR_JOINING_TYPE);
  7014. // UAX #31 section 2.3 subsections A1, A2 and B, check ZWNJ and ZWJ usage.
  7015. switch (A1_sequence_status) {
  7016. case SEQ_NEAR_END: {
  7017. if ((A1_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != A1_scr)) {
  7018. return false; // Mixed script.
  7019. }
  7020. if (jt == U_JT_RIGHT_JOINING || jt == U_JT_DUAL_JOINING) {
  7021. A1_sequence_status = SEQ_NOT_STARTED; // Valid end of sequence, reset.
  7022. } else if (jt != U_JT_TRANSPARENT) {
  7023. return false; // Invalid end of sequence.
  7024. }
  7025. } break;
  7026. case SEQ_STARTED: {
  7027. if ((A1_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != A1_scr)) {
  7028. A1_sequence_status = SEQ_NOT_STARTED; // Reset.
  7029. } else {
  7030. if (jt != U_JT_TRANSPARENT) {
  7031. if (str[i] == 0x200C /*ZWNJ*/) {
  7032. A1_sequence_status = SEQ_NEAR_END;
  7033. continue;
  7034. } else {
  7035. A1_sequence_status = SEQ_NOT_STARTED; // Reset.
  7036. }
  7037. }
  7038. }
  7039. } break;
  7040. default:
  7041. break;
  7042. }
  7043. if (A1_sequence_status == SEQ_NOT_STARTED) {
  7044. if (jt == U_JT_LEFT_JOINING || jt == U_JT_DUAL_JOINING) {
  7045. A1_sequence_status = SEQ_STARTED;
  7046. A1_scr = scr;
  7047. }
  7048. };
  7049. switch (A2_sequence_status) {
  7050. case SEQ_NEAR_END: {
  7051. if ((A2_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != A2_scr)) {
  7052. return false; // Mixed script.
  7053. }
  7054. if (cat == U_UPPERCASE_LETTER || cat == U_LOWERCASE_LETTER || cat == U_TITLECASE_LETTER || cat == U_MODIFIER_LETTER || cat == U_OTHER_LETTER) {
  7055. A2_sequence_status = SEQ_NOT_STARTED; // Valid end of sequence, reset.
  7056. } else if (cat != U_MODIFIER_LETTER || u_getCombiningClass(str[i]) == 0) {
  7057. return false; // Invalid end of sequence.
  7058. }
  7059. } break;
  7060. case SEQ_STARTED_VIR: {
  7061. if ((A2_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != A2_scr)) {
  7062. A2_sequence_status = SEQ_NOT_STARTED; // Reset.
  7063. } else {
  7064. if (str[i] == 0x200C /*ZWNJ*/) {
  7065. A2_sequence_status = SEQ_NEAR_END;
  7066. continue;
  7067. } else if (cat != U_MODIFIER_LETTER || u_getCombiningClass(str[i]) == 0) {
  7068. A2_sequence_status = SEQ_NOT_STARTED; // Reset.
  7069. }
  7070. }
  7071. } break;
  7072. case SEQ_STARTED: {
  7073. if ((A2_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != A2_scr)) {
  7074. A2_sequence_status = SEQ_NOT_STARTED; // Reset.
  7075. } else {
  7076. if (u_getCombiningClass(str[i]) == 9 /*Virama Combining Class*/) {
  7077. A2_sequence_status = SEQ_STARTED_VIR;
  7078. } else if (cat != U_MODIFIER_LETTER) {
  7079. A2_sequence_status = SEQ_NOT_STARTED; // Reset.
  7080. }
  7081. }
  7082. } break;
  7083. default:
  7084. break;
  7085. }
  7086. if (A2_sequence_status == SEQ_NOT_STARTED) {
  7087. if (cat == U_UPPERCASE_LETTER || cat == U_LOWERCASE_LETTER || cat == U_TITLECASE_LETTER || cat == U_MODIFIER_LETTER || cat == U_OTHER_LETTER) {
  7088. A2_sequence_status = SEQ_STARTED;
  7089. A2_scr = scr;
  7090. }
  7091. }
  7092. switch (B_sequence_status) {
  7093. case SEQ_NEAR_END: {
  7094. if ((B_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != B_scr)) {
  7095. return false; // Mixed script.
  7096. }
  7097. if (u_getIntPropertyValue(str[i], UCHAR_INDIC_SYLLABIC_CATEGORY) != U_INSC_VOWEL_DEPENDENT) {
  7098. B_sequence_status = SEQ_NOT_STARTED; // Valid end of sequence, reset.
  7099. } else {
  7100. return false; // Invalid end of sequence.
  7101. }
  7102. } break;
  7103. case SEQ_STARTED_VIR: {
  7104. if ((B_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != B_scr)) {
  7105. B_sequence_status = SEQ_NOT_STARTED; // Reset.
  7106. } else {
  7107. if (str[i] == 0x200D /*ZWJ*/) {
  7108. B_sequence_status = SEQ_NEAR_END;
  7109. continue;
  7110. } else if (cat != U_MODIFIER_LETTER || u_getCombiningClass(str[i]) == 0) {
  7111. B_sequence_status = SEQ_NOT_STARTED; // Reset.
  7112. }
  7113. }
  7114. } break;
  7115. case SEQ_STARTED: {
  7116. if ((B_scr > USCRIPT_INHERITED) && (scr > USCRIPT_INHERITED) && (scr != B_scr)) {
  7117. B_sequence_status = SEQ_NOT_STARTED; // Reset.
  7118. } else {
  7119. if (u_getCombiningClass(str[i]) == 9 /*Virama Combining Class*/) {
  7120. B_sequence_status = SEQ_STARTED_VIR;
  7121. } else if (cat != U_MODIFIER_LETTER) {
  7122. B_sequence_status = SEQ_NOT_STARTED; // Reset.
  7123. }
  7124. }
  7125. } break;
  7126. default:
  7127. break;
  7128. }
  7129. if (B_sequence_status == SEQ_NOT_STARTED) {
  7130. if (cat == U_UPPERCASE_LETTER || cat == U_LOWERCASE_LETTER || cat == U_TITLECASE_LETTER || cat == U_MODIFIER_LETTER || cat == U_OTHER_LETTER) {
  7131. B_sequence_status = SEQ_STARTED;
  7132. B_scr = scr;
  7133. }
  7134. }
  7135. if (u_hasBinaryProperty(str[i], UCHAR_PATTERN_SYNTAX) || u_hasBinaryProperty(str[i], UCHAR_PATTERN_WHITE_SPACE) || u_hasBinaryProperty(str[i], UCHAR_NONCHARACTER_CODE_POINT)) {
  7136. return false; // Not a XID_Start or XID_Continue character.
  7137. }
  7138. if (i == 0) {
  7139. if (!(cat == U_LOWERCASE_LETTER || cat == U_UPPERCASE_LETTER || cat == U_TITLECASE_LETTER || cat == U_OTHER_LETTER || cat == U_MODIFIER_LETTER || cat == U_LETTER_NUMBER || str[0] == 0x2118 || str[0] == 0x212E || str[0] == 0x309B || str[0] == 0x309C || str[0] == 0x005F)) {
  7140. return false; // Not a XID_Start character.
  7141. }
  7142. } else {
  7143. if (!(cat == U_LOWERCASE_LETTER || cat == U_UPPERCASE_LETTER || cat == U_TITLECASE_LETTER || cat == U_OTHER_LETTER || cat == U_MODIFIER_LETTER || cat == U_LETTER_NUMBER || cat == U_NON_SPACING_MARK || cat == U_COMBINING_SPACING_MARK || cat == U_DECIMAL_DIGIT_NUMBER || cat == U_CONNECTOR_PUNCTUATION || str[i] == 0x2118 || str[i] == 0x212E || str[i] == 0x309B || str[i] == 0x309C || str[i] == 0x1369 || str[i] == 0x1371 || str[i] == 0x00B7 || str[i] == 0x0387 || str[i] == 0x19DA || str[i] == 0x0E33 || str[i] == 0x0EB3 || str[i] == 0xFF9E || str[i] == 0xFF9F)) {
  7144. return false; // Not a XID_Continue character.
  7145. }
  7146. }
  7147. }
  7148. return true;
  7149. }
  7150. bool TextServerAdvanced::_is_valid_letter(uint64_t p_unicode) const {
  7151. #ifndef ICU_STATIC_DATA
  7152. if (!icu_data_loaded) {
  7153. return TextServer::is_valid_letter(p_unicode);
  7154. }
  7155. #endif
  7156. return u_isalpha(p_unicode);
  7157. }
  7158. void TextServerAdvanced::_update_settings() {
  7159. lcd_subpixel_layout.set((TextServer::FontLCDSubpixelLayout)(int)GLOBAL_GET("gui/theme/lcd_subpixel_layout"));
  7160. lb_strictness = (LineBreakStrictness)(int)GLOBAL_GET("internationalization/locale/line_breaking_strictness");
  7161. }
  7162. TextServerAdvanced::TextServerAdvanced() {
  7163. _insert_num_systems_lang();
  7164. _insert_feature_sets();
  7165. _bmp_create_font_funcs();
  7166. _update_settings();
  7167. ProjectSettings::get_singleton()->connect("settings_changed", callable_mp(this, &TextServerAdvanced::_update_settings));
  7168. }
  7169. void TextServerAdvanced::_font_clear_system_fallback_cache() {
  7170. _THREAD_SAFE_METHOD_
  7171. for (const KeyValue<SystemFontKey, SystemFontCache> &E : system_fonts) {
  7172. const Vector<SystemFontCacheRec> &sysf_cache = E.value.var;
  7173. for (const SystemFontCacheRec &F : sysf_cache) {
  7174. _free_rid(F.rid);
  7175. }
  7176. }
  7177. system_fonts.clear();
  7178. system_font_data.clear();
  7179. }
  7180. void TextServerAdvanced::_cleanup() {
  7181. font_clear_system_fallback_cache();
  7182. }
  7183. TextServerAdvanced::~TextServerAdvanced() {
  7184. _bmp_free_font_funcs();
  7185. #ifdef MODULE_FREETYPE_ENABLED
  7186. if (ft_library != nullptr) {
  7187. FT_Done_FreeType(ft_library);
  7188. }
  7189. #endif
  7190. if (sc_spoof != nullptr) {
  7191. uspoof_close(sc_spoof);
  7192. sc_spoof = nullptr;
  7193. }
  7194. if (sc_conf != nullptr) {
  7195. uspoof_close(sc_conf);
  7196. sc_conf = nullptr;
  7197. }
  7198. if (allowed != nullptr) {
  7199. uset_close(allowed);
  7200. allowed = nullptr;
  7201. }
  7202. for (const KeyValue<String, UBreakIterator *> &bi : line_break_iterators_per_language) {
  7203. ubrk_close(bi.value);
  7204. }
  7205. std::atexit(u_cleanup);
  7206. }