12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629 |
- #include "display_server_x11.h"
- #ifdef X11_ENABLED
- #include "x11/detect_prime_x11.h"
- #include "x11/key_mapping_x11.h"
- #include "core/config/project_settings.h"
- #include "core/math/math_funcs.h"
- #include "core/string/print_string.h"
- #include "core/string/ustring.h"
- #include "drivers/png/png_driver_common.h"
- #include "main/main.h"
- #if defined(VULKAN_ENABLED)
- #include "servers/rendering/renderer_rd/renderer_compositor_rd.h"
- #endif
- #if defined(GLES3_ENABLED)
- #include "drivers/gles3/rasterizer_gles3.h"
- #endif
- #include <dlfcn.h>
- #include <limits.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <unistd.h>
- #undef CursorShape
- #include <X11/XKBlib.h>
- #define WM_NormalState 1L
- #define WM_IconicState 3L
- #define _NET_WM_STATE_REMOVE 0L
- #define _NET_WM_STATE_ADD 1L
- #define XINPUT_CLIENT_VERSION_MAJOR 2
- #define XINPUT_CLIENT_VERSION_MINOR 2
- #define VALUATOR_ABSX 0
- #define VALUATOR_ABSY 1
- #define VALUATOR_PRESSURE 2
- #define VALUATOR_TILTX 3
- #define VALUATOR_TILTY 4
- #ifdef DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED
- #define DEBUG_LOG_X11(...) printf(__VA_ARGS__)
- #else
- #define DEBUG_LOG_X11(...)
- #endif
- static const double abs_resolution_mult = 10000.0;
- static const double abs_resolution_range_mult = 10.0;
- struct Hints {
- unsigned long flags = 0;
- unsigned long functions = 0;
- unsigned long decorations = 0;
- long inputMode = 0;
- unsigned long status = 0;
- };
- static String get_atom_name(Display *p_disp, Atom p_atom) {
- char *name = XGetAtomName(p_disp, p_atom);
- ERR_FAIL_NULL_V_MSG(name, String(), "Atom is invalid.");
- String ret;
- ret.parse_utf8(name);
- XFree(name);
- return ret;
- }
- bool DisplayServerX11::has_feature(Feature p_feature) const {
- switch (p_feature) {
- #ifndef DISABLE_DEPRECATED
- case FEATURE_GLOBAL_MENU: {
- return (native_menu && native_menu->has_feature(NativeMenu::FEATURE_GLOBAL_MENU));
- } break;
- #endif
- case FEATURE_SUBWINDOWS:
- #ifdef TOUCH_ENABLED
- case FEATURE_TOUCHSCREEN:
- #endif
- case FEATURE_MOUSE:
- case FEATURE_MOUSE_WARP:
- case FEATURE_CLIPBOARD:
- case FEATURE_CURSOR_SHAPE:
- case FEATURE_CUSTOM_CURSOR_SHAPE:
- case FEATURE_IME:
- case FEATURE_WINDOW_TRANSPARENCY:
-
- case FEATURE_ICON:
- #ifdef DBUS_ENABLED
- case FEATURE_NATIVE_DIALOG_FILE:
- case FEATURE_NATIVE_DIALOG_FILE_EXTRA:
- #endif
-
-
-
- case FEATURE_SWAP_BUFFERS:
- #ifdef DBUS_ENABLED
- case FEATURE_KEEP_SCREEN_ON:
- #endif
- case FEATURE_CLIPBOARD_PRIMARY:
- case FEATURE_TEXT_TO_SPEECH:
- return true;
- case FEATURE_SCREEN_CAPTURE:
- return !xwayland;
- default: {
- }
- }
- return false;
- }
- String DisplayServerX11::get_name() const {
- return "X11";
- }
- void DisplayServerX11::_update_real_mouse_position(const WindowData &wd) {
- Window root_return, child_return;
- int root_x, root_y, win_x, win_y;
- unsigned int mask_return;
- Bool xquerypointer_result = XQueryPointer(x11_display, wd.x11_window, &root_return, &child_return, &root_x, &root_y,
- &win_x, &win_y, &mask_return);
- if (xquerypointer_result) {
- if (win_x > 0 && win_y > 0 && win_x <= wd.size.width && win_y <= wd.size.height) {
- last_mouse_pos.x = win_x;
- last_mouse_pos.y = win_y;
- last_mouse_pos_valid = true;
- Input::get_singleton()->set_mouse_position(last_mouse_pos);
- }
- }
- }
- bool DisplayServerX11::_refresh_device_info() {
- int event_base, error_base;
- print_verbose("XInput: Refreshing devices.");
- if (!XQueryExtension(x11_display, "XInputExtension", &xi.opcode, &event_base, &error_base)) {
- print_verbose("XInput extension not available. Please upgrade your distribution.");
- return false;
- }
- int xi_major_query = XINPUT_CLIENT_VERSION_MAJOR;
- int xi_minor_query = XINPUT_CLIENT_VERSION_MINOR;
- if (XIQueryVersion(x11_display, &xi_major_query, &xi_minor_query) != Success) {
- print_verbose(vformat("XInput 2 not available (server supports %d.%d).", xi_major_query, xi_minor_query));
- xi.opcode = 0;
- return false;
- }
- if (xi_major_query < XINPUT_CLIENT_VERSION_MAJOR || (xi_major_query == XINPUT_CLIENT_VERSION_MAJOR && xi_minor_query < XINPUT_CLIENT_VERSION_MINOR)) {
- print_verbose(vformat("XInput %d.%d not available (server supports %d.%d). Touch input unavailable.",
- XINPUT_CLIENT_VERSION_MAJOR, XINPUT_CLIENT_VERSION_MINOR, xi_major_query, xi_minor_query));
- }
- xi.absolute_devices.clear();
- xi.touch_devices.clear();
- xi.pen_inverted_devices.clear();
- xi.last_relative_time = 0;
- int dev_count;
- XIDeviceInfo *info = XIQueryDevice(x11_display, XIAllDevices, &dev_count);
- for (int i = 0; i < dev_count; i++) {
- XIDeviceInfo *dev = &info[i];
- if (!dev->enabled) {
- continue;
- }
- if (!(dev->use == XISlavePointer || dev->use == XIFloatingSlave)) {
- continue;
- }
- bool direct_touch = false;
- bool absolute_mode = false;
- int resolution_x = 0;
- int resolution_y = 0;
- double abs_x_min = 0;
- double abs_x_max = 0;
- double abs_y_min = 0;
- double abs_y_max = 0;
- double pressure_min = 0;
- double pressure_max = 0;
- double tilt_x_min = 0;
- double tilt_x_max = 0;
- double tilt_y_min = 0;
- double tilt_y_max = 0;
- for (int j = 0; j < dev->num_classes; j++) {
- #ifdef TOUCH_ENABLED
- if (dev->classes[j]->type == XITouchClass && ((XITouchClassInfo *)dev->classes[j])->mode == XIDirectTouch) {
- direct_touch = true;
- }
- #endif
- if (dev->classes[j]->type == XIValuatorClass) {
- XIValuatorClassInfo *class_info = (XIValuatorClassInfo *)dev->classes[j];
- if (class_info->number == VALUATOR_ABSX && class_info->mode == XIModeAbsolute) {
- resolution_x = class_info->resolution;
- abs_x_min = class_info->min;
- abs_x_max = class_info->max;
- absolute_mode = true;
- } else if (class_info->number == VALUATOR_ABSY && class_info->mode == XIModeAbsolute) {
- resolution_y = class_info->resolution;
- abs_y_min = class_info->min;
- abs_y_max = class_info->max;
- absolute_mode = true;
- } else if (class_info->number == VALUATOR_PRESSURE && class_info->mode == XIModeAbsolute) {
- pressure_min = class_info->min;
- pressure_max = class_info->max;
- } else if (class_info->number == VALUATOR_TILTX && class_info->mode == XIModeAbsolute) {
- tilt_x_min = class_info->min;
- tilt_x_max = class_info->max;
- } else if (class_info->number == VALUATOR_TILTY && class_info->mode == XIModeAbsolute) {
- tilt_y_min = class_info->min;
- tilt_y_max = class_info->max;
- }
- }
- }
- if (direct_touch) {
- xi.touch_devices.push_back(dev->deviceid);
- print_verbose("XInput: Using touch device: " + String(dev->name));
- }
- if (absolute_mode) {
-
- if (resolution_x <= 0) {
- resolution_x = (abs_x_max - abs_x_min) * abs_resolution_range_mult;
- }
- if (resolution_y <= 0) {
- resolution_y = (abs_y_max - abs_y_min) * abs_resolution_range_mult;
- }
- xi.absolute_devices[dev->deviceid] = Vector2(abs_resolution_mult / resolution_x, abs_resolution_mult / resolution_y);
- print_verbose("XInput: Absolute pointing device: " + String(dev->name));
- }
- xi.pressure = 0;
- xi.pen_pressure_range[dev->deviceid] = Vector2(pressure_min, pressure_max);
- xi.pen_tilt_x_range[dev->deviceid] = Vector2(tilt_x_min, tilt_x_max);
- xi.pen_tilt_y_range[dev->deviceid] = Vector2(tilt_y_min, tilt_y_max);
- xi.pen_inverted_devices[dev->deviceid] = String(dev->name).findn("eraser") > 0;
- }
- XIFreeDeviceInfo(info);
- #ifdef TOUCH_ENABLED
- if (!xi.touch_devices.size()) {
- print_verbose("XInput: No touch devices found.");
- }
- #endif
- return true;
- }
- void DisplayServerX11::_flush_mouse_motion() {
-
- MutexLock mutex_lock(events_mutex);
- for (uint32_t event_index = 0; event_index < polled_events.size(); ++event_index) {
- XEvent &event = polled_events[event_index];
- if (XGetEventData(x11_display, &event.xcookie) && event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) {
- XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data;
- if (event_data->evtype == XI_RawMotion) {
- XFreeEventData(x11_display, &event.xcookie);
- polled_events.remove_at(event_index--);
- continue;
- }
- XFreeEventData(x11_display, &event.xcookie);
- break;
- }
- }
- xi.relative_motion.x = 0;
- xi.relative_motion.y = 0;
- }
- #ifdef SPEECHD_ENABLED
- bool DisplayServerX11::tts_is_speaking() const {
- ERR_FAIL_NULL_V_MSG(tts, false, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
- return tts->is_speaking();
- }
- bool DisplayServerX11::tts_is_paused() const {
- ERR_FAIL_NULL_V_MSG(tts, false, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
- return tts->is_paused();
- }
- TypedArray<Dictionary> DisplayServerX11::tts_get_voices() const {
- ERR_FAIL_NULL_V_MSG(tts, TypedArray<Dictionary>(), "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
- return tts->get_voices();
- }
- void DisplayServerX11::tts_speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
- ERR_FAIL_NULL_MSG(tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
- tts->speak(p_text, p_voice, p_volume, p_pitch, p_rate, p_utterance_id, p_interrupt);
- }
- void DisplayServerX11::tts_pause() {
- ERR_FAIL_NULL_MSG(tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
- tts->pause();
- }
- void DisplayServerX11::tts_resume() {
- ERR_FAIL_NULL_MSG(tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
- tts->resume();
- }
- void DisplayServerX11::tts_stop() {
- ERR_FAIL_NULL_MSG(tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
- tts->stop();
- }
- #endif
- #ifdef DBUS_ENABLED
- bool DisplayServerX11::is_dark_mode_supported() const {
- return portal_desktop->is_supported();
- }
- bool DisplayServerX11::is_dark_mode() const {
- switch (portal_desktop->get_appearance_color_scheme()) {
- case 1:
-
- return true;
- case 2:
-
- return false;
- default:
-
- return false;
- }
- }
- void DisplayServerX11::set_system_theme_change_callback(const Callable &p_callable) {
- portal_desktop->set_system_theme_change_callback(p_callable);
- }
- Error DisplayServerX11::file_dialog_show(const String &p_title, const String &p_current_directory, const String &p_filename, bool p_show_hidden, FileDialogMode p_mode, const Vector<String> &p_filters, const Callable &p_callback) {
- WindowID window_id = last_focused_window;
- if (!windows.has(window_id)) {
- window_id = MAIN_WINDOW_ID;
- }
- String xid = vformat("x11:%x", (uint64_t)windows[window_id].x11_window);
- return portal_desktop->file_dialog_show(last_focused_window, xid, p_title, p_current_directory, String(), p_filename, p_mode, p_filters, TypedArray<Dictionary>(), p_callback, false);
- }
- Error DisplayServerX11::file_dialog_with_options_show(const String &p_title, const String &p_current_directory, const String &p_root, const String &p_filename, bool p_show_hidden, FileDialogMode p_mode, const Vector<String> &p_filters, const TypedArray<Dictionary> &p_options, const Callable &p_callback) {
- WindowID window_id = last_focused_window;
- if (!windows.has(window_id)) {
- window_id = MAIN_WINDOW_ID;
- }
- String xid = vformat("x11:%x", (uint64_t)windows[window_id].x11_window);
- return portal_desktop->file_dialog_show(last_focused_window, xid, p_title, p_current_directory, p_root, p_filename, p_mode, p_filters, p_options, p_callback, true);
- }
- #endif
- void DisplayServerX11::beep() const {
- XBell(x11_display, 0);
- }
- void DisplayServerX11::mouse_set_mode(MouseMode p_mode) {
- _THREAD_SAFE_METHOD_
- if (p_mode == mouse_mode) {
- return;
- }
- if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
- XUngrabPointer(x11_display, CurrentTime);
- }
-
- bool show_cursor = (p_mode == MOUSE_MODE_VISIBLE || p_mode == MOUSE_MODE_CONFINED);
- bool previously_shown = (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED);
- if (show_cursor && !previously_shown) {
- WindowID window_id = get_window_at_screen_position(mouse_get_position());
- if (window_id != INVALID_WINDOW_ID && window_mouseover_id != window_id) {
- if (window_mouseover_id != INVALID_WINDOW_ID) {
- _send_window_event(windows[window_mouseover_id], WINDOW_EVENT_MOUSE_EXIT);
- }
- window_mouseover_id = window_id;
- _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
- }
- }
- for (const KeyValue<WindowID, WindowData> &E : windows) {
- if (show_cursor) {
- XDefineCursor(x11_display, E.value.x11_window, cursors[current_cursor]);
- } else {
- XDefineCursor(x11_display, E.value.x11_window, null_cursor);
- }
- }
- mouse_mode = p_mode;
- if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
-
- _flush_mouse_motion();
- WindowID window_id = _get_focused_window_or_popup();
- if (!windows.has(window_id)) {
- window_id = MAIN_WINDOW_ID;
- }
- WindowData &window = windows[window_id];
- if (XGrabPointer(
- x11_display, window.x11_window, True,
- ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
- GrabModeAsync, GrabModeAsync, window.x11_window, None, CurrentTime) != GrabSuccess) {
- ERR_PRINT("NO GRAB");
- }
- if (mouse_mode == MOUSE_MODE_CAPTURED) {
- center.x = window.size.width / 2;
- center.y = window.size.height / 2;
- XWarpPointer(x11_display, None, window.x11_window,
- 0, 0, 0, 0, (int)center.x, (int)center.y);
- Input::get_singleton()->set_mouse_position(center);
- }
- } else {
- do_mouse_warp = false;
- }
- XFlush(x11_display);
- }
- DisplayServerX11::MouseMode DisplayServerX11::mouse_get_mode() const {
- return mouse_mode;
- }
- void DisplayServerX11::warp_mouse(const Point2i &p_position) {
- _THREAD_SAFE_METHOD_
- if (mouse_mode == MOUSE_MODE_CAPTURED) {
- last_mouse_pos = p_position;
- } else {
- WindowID window_id = _get_focused_window_or_popup();
- if (!windows.has(window_id)) {
- window_id = MAIN_WINDOW_ID;
- }
- XWarpPointer(x11_display, None, windows[window_id].x11_window,
- 0, 0, 0, 0, (int)p_position.x, (int)p_position.y);
- }
- }
- Point2i DisplayServerX11::mouse_get_position() const {
- int number_of_screens = XScreenCount(x11_display);
- for (int i = 0; i < number_of_screens; i++) {
- Window root, child;
- int root_x, root_y, win_x, win_y;
- unsigned int mask;
- if (XQueryPointer(x11_display, XRootWindow(x11_display, i), &root, &child, &root_x, &root_y, &win_x, &win_y, &mask)) {
- XWindowAttributes root_attrs;
- XGetWindowAttributes(x11_display, root, &root_attrs);
- return Vector2i(root_attrs.x + root_x, root_attrs.y + root_y);
- }
- }
- return Vector2i();
- }
- BitField<MouseButtonMask> DisplayServerX11::mouse_get_button_state() const {
- int number_of_screens = XScreenCount(x11_display);
- for (int i = 0; i < number_of_screens; i++) {
- Window root, child;
- int root_x, root_y, win_x, win_y;
- unsigned int mask;
- if (XQueryPointer(x11_display, XRootWindow(x11_display, i), &root, &child, &root_x, &root_y, &win_x, &win_y, &mask)) {
- BitField<MouseButtonMask> last_button_state = 0;
- if (mask & Button1Mask) {
- last_button_state.set_flag(MouseButtonMask::LEFT);
- }
- if (mask & Button2Mask) {
- last_button_state.set_flag(MouseButtonMask::MIDDLE);
- }
- if (mask & Button3Mask) {
- last_button_state.set_flag(MouseButtonMask::RIGHT);
- }
- if (mask & Button4Mask) {
- last_button_state.set_flag(MouseButtonMask::MB_XBUTTON1);
- }
- if (mask & Button5Mask) {
- last_button_state.set_flag(MouseButtonMask::MB_XBUTTON2);
- }
- return last_button_state;
- }
- }
- return 0;
- }
- void DisplayServerX11::clipboard_set(const String &p_text) {
- _THREAD_SAFE_METHOD_
- {
-
- MutexLock mutex_lock(events_mutex);
- internal_clipboard = p_text;
- }
- XSetSelectionOwner(x11_display, XA_PRIMARY, windows[MAIN_WINDOW_ID].x11_window, CurrentTime);
- XSetSelectionOwner(x11_display, XInternAtom(x11_display, "CLIPBOARD", 0), windows[MAIN_WINDOW_ID].x11_window, CurrentTime);
- }
- void DisplayServerX11::clipboard_set_primary(const String &p_text) {
- _THREAD_SAFE_METHOD_
- if (!p_text.is_empty()) {
- {
-
- MutexLock mutex_lock(events_mutex);
- internal_clipboard_primary = p_text;
- }
- XSetSelectionOwner(x11_display, XA_PRIMARY, windows[MAIN_WINDOW_ID].x11_window, CurrentTime);
- XSetSelectionOwner(x11_display, XInternAtom(x11_display, "PRIMARY", 0), windows[MAIN_WINDOW_ID].x11_window, CurrentTime);
- }
- }
- Bool DisplayServerX11::_predicate_clipboard_selection(Display *display, XEvent *event, XPointer arg) {
- if (event->type == SelectionNotify && event->xselection.requestor == *(Window *)arg) {
- return True;
- } else {
- return False;
- }
- }
- Bool DisplayServerX11::_predicate_clipboard_incr(Display *display, XEvent *event, XPointer arg) {
- if (event->type == PropertyNotify && event->xproperty.state == PropertyNewValue && event->xproperty.atom == *(Atom *)arg) {
- return True;
- } else {
- return False;
- }
- }
- String DisplayServerX11::_clipboard_get_impl(Atom p_source, Window x11_window, Atom target) const {
- String ret;
- Window selection_owner = XGetSelectionOwner(x11_display, p_source);
- if (selection_owner == x11_window) {
- static const char *target_type = "PRIMARY";
- if (p_source != None && get_atom_name(x11_display, p_source) == target_type) {
- return internal_clipboard_primary;
- } else {
- return internal_clipboard;
- }
- }
- if (selection_owner != None) {
-
- MutexLock mutex_lock(events_mutex);
- Atom selection = XA_PRIMARY;
- XConvertSelection(x11_display, p_source, target, selection,
- x11_window, CurrentTime);
- XFlush(x11_display);
-
- XEvent event;
- XIfEvent(x11_display, &event, _predicate_clipboard_selection, (XPointer)&x11_window);
-
- Atom type;
- int format, result;
- unsigned long len, bytes_left, dummy;
- unsigned char *data;
- XGetWindowProperty(x11_display, x11_window,
- selection,
- 0, 0,
- 0,
- AnyPropertyType,
- &type,
- &format,
- &len, &bytes_left,
- &data);
- if (data) {
- XFree(data);
- }
- if (type == XInternAtom(x11_display, "INCR", 0)) {
-
- DEBUG_LOG_X11("INCR selection started.\n");
- LocalVector<uint8_t> incr_data;
- uint32_t data_size = 0;
- bool success = false;
-
- XDeleteProperty(x11_display, x11_window, type);
-
- bool done = false;
- while (!done) {
- if (!_wait_for_events()) {
-
- break;
- }
-
- XEvent ev;
- while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_incr, (XPointer)&selection)) {
- result = XGetWindowProperty(x11_display, x11_window,
- selection,
- 0, LONG_MAX,
- True,
- AnyPropertyType,
- &type,
- &format,
- &len, &bytes_left,
- &data);
- DEBUG_LOG_X11("PropertyNotify: len=%lu, format=%i\n", len, format);
- if (result == Success) {
- if (data && (len > 0)) {
- uint32_t prev_size = incr_data.size();
- if (prev_size == 0) {
-
- unsigned long initial_size = *(unsigned long *)data;
- incr_data.resize(initial_size);
- } else {
-
- incr_data.resize(MAX(data_size + len, prev_size));
- memcpy(incr_data.ptr() + data_size, data, len);
- data_size += len;
- }
- } else {
-
- done = true;
- success = true;
- }
- } else {
- print_verbose("Failed to get selection data chunk.");
- done = true;
- }
- if (data) {
- XFree(data);
- }
- if (done) {
- break;
- }
- }
- }
- if (success && (data_size > 0)) {
- ret.parse_utf8((const char *)incr_data.ptr(), data_size);
- }
- } else if (bytes_left > 0) {
-
- result = XGetWindowProperty(x11_display, x11_window,
- selection, 0, bytes_left, 0,
- AnyPropertyType, &type, &format,
- &len, &dummy, &data);
- if (result == Success) {
- ret.parse_utf8((const char *)data);
- } else {
- print_verbose("Failed to get selection data.");
- }
- if (data) {
- XFree(data);
- }
- }
- }
- return ret;
- }
- Atom DisplayServerX11::_clipboard_get_image_target(Atom p_source, Window x11_window) const {
- Atom target = XInternAtom(x11_display, "TARGETS", 0);
- Atom png = XInternAtom(x11_display, "image/png", 0);
- Atom *valid_targets = nullptr;
- unsigned long atom_count = 0;
- Window selection_owner = XGetSelectionOwner(x11_display, p_source);
- if (selection_owner != None && selection_owner != x11_window) {
-
- MutexLock mutex_lock(events_mutex);
- Atom selection = XA_PRIMARY;
- XConvertSelection(x11_display, p_source, target, selection, x11_window, CurrentTime);
- XFlush(x11_display);
-
- XEvent event;
- XIfEvent(x11_display, &event, _predicate_clipboard_selection, (XPointer)&x11_window);
-
- Atom type;
- int format, result;
- unsigned long len, bytes_left, dummy;
- XGetWindowProperty(x11_display, x11_window,
- selection,
- 0, 0,
- 0,
- XA_ATOM,
- &type,
- &format,
- &len, &bytes_left,
- (unsigned char **)&valid_targets);
- if (valid_targets) {
- XFree(valid_targets);
- valid_targets = nullptr;
- }
- if (type == XA_ATOM && bytes_left > 0) {
-
- result = XGetWindowProperty(x11_display, x11_window,
- selection, 0, bytes_left / 4, 0,
- XA_ATOM, &type, &format,
- &len, &dummy, (unsigned char **)&valid_targets);
- if (result == Success) {
- atom_count = len;
- } else {
- print_verbose("Failed to get selection data.");
- return None;
- }
- } else {
- return None;
- }
- } else {
- return None;
- }
- for (unsigned long i = 0; i < atom_count; i++) {
- Atom atom = valid_targets[i];
- if (atom == png) {
- XFree(valid_targets);
- return png;
- }
- }
- XFree(valid_targets);
- return None;
- }
- String DisplayServerX11::_clipboard_get(Atom p_source, Window x11_window) const {
- String ret;
- Atom utf8_atom = XInternAtom(x11_display, "UTF8_STRING", True);
- if (utf8_atom != None) {
- ret = _clipboard_get_impl(p_source, x11_window, utf8_atom);
- }
- if (ret.is_empty()) {
- ret = _clipboard_get_impl(p_source, x11_window, XA_STRING);
- }
- return ret;
- }
- String DisplayServerX11::clipboard_get() const {
- _THREAD_SAFE_METHOD_
- String ret;
- ret = _clipboard_get(XInternAtom(x11_display, "CLIPBOARD", 0), windows[MAIN_WINDOW_ID].x11_window);
- if (ret.is_empty()) {
- ret = _clipboard_get(XA_PRIMARY, windows[MAIN_WINDOW_ID].x11_window);
- }
- return ret;
- }
- String DisplayServerX11::clipboard_get_primary() const {
- _THREAD_SAFE_METHOD_
- String ret;
- ret = _clipboard_get(XInternAtom(x11_display, "PRIMARY", 0), windows[MAIN_WINDOW_ID].x11_window);
- if (ret.is_empty()) {
- ret = _clipboard_get(XA_PRIMARY, windows[MAIN_WINDOW_ID].x11_window);
- }
- return ret;
- }
- Ref<Image> DisplayServerX11::clipboard_get_image() const {
- _THREAD_SAFE_METHOD_
- Atom clipboard = XInternAtom(x11_display, "CLIPBOARD", 0);
- Window x11_window = windows[MAIN_WINDOW_ID].x11_window;
- Ref<Image> ret;
- Atom target = _clipboard_get_image_target(clipboard, x11_window);
- if (target == None) {
- return ret;
- }
- Window selection_owner = XGetSelectionOwner(x11_display, clipboard);
- if (selection_owner != None && selection_owner != x11_window) {
-
- MutexLock mutex_lock(events_mutex);
-
-
- Atom transfer_prop = XA_PRIMARY;
- XConvertSelection(x11_display,
- clipboard,
- target,
- transfer_prop,
- x11_window, CurrentTime);
- XFlush(x11_display);
-
- XEvent event;
- XIfEvent(x11_display, &event, _predicate_clipboard_selection, (XPointer)&x11_window);
-
- Atom type;
- int format, result;
- unsigned long len, bytes_left, dummy;
- unsigned char *data;
- XGetWindowProperty(x11_display, x11_window,
- transfer_prop,
- 0, 1,
- 0,
- AnyPropertyType,
- &type,
- &format,
- &len, &bytes_left,
- &data);
- if (type == XInternAtom(x11_display, "INCR", 0)) {
- ERR_FAIL_COND_V_MSG(len != 1, ret, "Incremental transfer initial value was not length.");
-
- DEBUG_LOG_X11("INCR selection started.\n");
- LocalVector<uint8_t> incr_data;
- uint32_t data_size = 0;
- bool success = false;
-
- incr_data.resize(*(unsigned long *)data);
- XFree(data);
- data = nullptr;
-
- XDeleteProperty(x11_display, x11_window, transfer_prop);
-
- bool done = false;
- while (!done) {
- if (!_wait_for_events()) {
-
- break;
- }
-
- XEvent ev;
- while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_incr, (XPointer)&transfer_prop)) {
- result = XGetWindowProperty(x11_display, x11_window,
- transfer_prop,
- 0, LONG_MAX,
- True,
- AnyPropertyType,
- &type,
- &format,
- &len, &bytes_left,
- &data);
- DEBUG_LOG_X11("PropertyNotify: len=%lu, format=%i\n", len, format);
- if (result == Success) {
- if (data && (len > 0)) {
- uint32_t prev_size = incr_data.size();
-
- incr_data.resize(MAX(data_size + len, prev_size));
- memcpy(incr_data.ptr() + data_size, data, len);
- data_size += len;
- } else if (!(format == 0 && len == 0)) {
-
-
- done = true;
- success = true;
- }
- } else {
- print_verbose("Failed to get selection data chunk.");
- done = true;
- }
- if (data) {
- XFree(data);
- data = nullptr;
- }
- if (done) {
- break;
- }
- }
- }
- if (success && (data_size > 0)) {
- ret.instantiate();
- PNGDriverCommon::png_to_image(incr_data.ptr(), incr_data.size(), false, ret);
- }
- } else if (bytes_left > 0) {
- if (data) {
- XFree(data);
- data = nullptr;
- }
-
- result = XGetWindowProperty(x11_display, x11_window,
- transfer_prop, 0, bytes_left + 4, 0,
- AnyPropertyType, &type, &format,
- &len, &dummy, &data);
- if (result == Success) {
- ret.instantiate();
- PNGDriverCommon::png_to_image((uint8_t *)data, bytes_left, false, ret);
- } else {
- print_verbose("Failed to get selection data.");
- }
- if (data) {
- XFree(data);
- }
- }
- }
- return ret;
- }
- bool DisplayServerX11::clipboard_has_image() const {
- Atom target = _clipboard_get_image_target(
- XInternAtom(x11_display, "CLIPBOARD", 0),
- windows[MAIN_WINDOW_ID].x11_window);
- return target != None;
- }
- Bool DisplayServerX11::_predicate_clipboard_save_targets(Display *display, XEvent *event, XPointer arg) {
- if (event->xany.window == *(Window *)arg) {
- return (event->type == SelectionRequest) ||
- (event->type == SelectionNotify);
- } else {
- return False;
- }
- }
- void DisplayServerX11::_clipboard_transfer_ownership(Atom p_source, Window x11_window) const {
- _THREAD_SAFE_METHOD_
- Window selection_owner = XGetSelectionOwner(x11_display, p_source);
- if (selection_owner != x11_window) {
- return;
- }
-
- MutexLock mutex_lock(events_mutex);
- Atom clipboard_manager = XInternAtom(x11_display, "CLIPBOARD_MANAGER", False);
- Atom save_targets = XInternAtom(x11_display, "SAVE_TARGETS", False);
- XConvertSelection(x11_display, clipboard_manager, save_targets, None,
- x11_window, CurrentTime);
-
- while (true) {
- if (!_wait_for_events()) {
-
- break;
- }
-
- XEvent ev;
- while (XCheckIfEvent(x11_display, &ev, _predicate_clipboard_save_targets, (XPointer)&x11_window)) {
- switch (ev.type) {
- case SelectionRequest:
- _handle_selection_request_event(&(ev.xselectionrequest));
- break;
- case SelectionNotify: {
- if (ev.xselection.target == save_targets) {
-
- return;
- }
- break;
- }
- }
- }
- }
- }
- int DisplayServerX11::get_screen_count() const {
- _THREAD_SAFE_METHOD_
- int count = 0;
-
- int event_base, error_base;
- if (xinerama_ext_ok && XineramaQueryExtension(x11_display, &event_base, &error_base)) {
- XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
- XFree(xsi);
- }
- if (count == 0) {
- count = XScreenCount(x11_display);
- }
- return count;
- }
- int DisplayServerX11::get_primary_screen() const {
- int event_base, error_base;
- if (xinerama_ext_ok && XineramaQueryExtension(x11_display, &event_base, &error_base)) {
- return 0;
- } else {
- return XDefaultScreen(x11_display);
- }
- }
- int DisplayServerX11::get_keyboard_focus_screen() const {
- int count = get_screen_count();
- if (count < 2) {
-
- return 0;
- }
- Window focus = 0;
- int revert_to = 0;
- XGetInputFocus(x11_display, &focus, &revert_to);
- if (focus) {
- Window focus_child = 0;
- int x = 0, y = 0;
- XTranslateCoordinates(x11_display, focus, DefaultRootWindow(x11_display), 0, 0, &x, &y, &focus_child);
- XWindowAttributes xwa;
- XGetWindowAttributes(x11_display, focus, &xwa);
- Rect2i window_rect = Rect2i(x, y, xwa.width, xwa.height);
-
- int screen_index = 0;
- int max_area = 0;
- for (int i = 0; i < count; i++) {
- Rect2i screen_rect = _screen_get_rect(i);
- Rect2i intersection = screen_rect.intersection(window_rect);
- int area = intersection.get_area();
- if (area > max_area) {
- max_area = area;
- screen_index = i;
- }
- }
- return screen_index;
- }
- return get_primary_screen();
- }
- Rect2i DisplayServerX11::_screen_get_rect(int p_screen) const {
- Rect2i rect(0, 0, 0, 0);
- p_screen = _get_screen_index(p_screen);
- ERR_FAIL_COND_V(p_screen < 0, rect);
-
- bool found = false;
- int event_base, error_base;
- if (xinerama_ext_ok && XineramaQueryExtension(x11_display, &event_base, &error_base)) {
- int count;
- XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
- if (xsi) {
- if (count > 0) {
-
- if (p_screen < count) {
- rect.position.x = xsi[p_screen].x_org;
- rect.position.y = xsi[p_screen].y_org;
- rect.size.width = xsi[p_screen].width;
- rect.size.height = xsi[p_screen].height;
- found = true;
- } else {
- ERR_PRINT(vformat("Invalid screen index: %d (count: %d).", p_screen, count));
- }
- }
- XFree(xsi);
- }
- }
- if (!found) {
- int count = XScreenCount(x11_display);
- if (p_screen < count) {
- Window root = XRootWindow(x11_display, p_screen);
- XWindowAttributes xwa;
- XGetWindowAttributes(x11_display, root, &xwa);
- rect.position.x = xwa.x;
- rect.position.y = xwa.y;
- rect.size.width = xwa.width;
- rect.size.height = xwa.height;
- } else {
- ERR_PRINT(vformat("Invalid screen index: %d (count: %d).", p_screen, count));
- }
- }
- return rect;
- }
- Point2i DisplayServerX11::screen_get_position(int p_screen) const {
- _THREAD_SAFE_METHOD_
- return _screen_get_rect(p_screen).position;
- }
- Size2i DisplayServerX11::screen_get_size(int p_screen) const {
- _THREAD_SAFE_METHOD_
- return _screen_get_rect(p_screen).size;
- }
- int default_window_error_handler(Display *display, XErrorEvent *error) {
- static char message[1024];
- XGetErrorText(display, error->error_code, message, sizeof(message));
- ERR_PRINT(vformat("Unhandled XServer error: %s"
- "\n Major opcode of failed request: %d"
- "\n Serial number of failed request: %d"
- "\n Current serial number in output stream: %d",
- String::utf8(message), (uint64_t)error->request_code, (uint64_t)error->minor_code, (uint64_t)error->serial));
- return 0;
- }
- bool g_bad_window = false;
- int bad_window_error_handler(Display *display, XErrorEvent *error) {
- if (error->error_code == BadWindow) {
- g_bad_window = true;
- } else {
- return default_window_error_handler(display, error);
- }
- return 0;
- }
- Rect2i DisplayServerX11::screen_get_usable_rect(int p_screen) const {
- _THREAD_SAFE_METHOD_
- p_screen = _get_screen_index(p_screen);
- int screen_count = get_screen_count();
-
- ERR_FAIL_INDEX_V(p_screen, screen_count, Rect2i(0, 0, 0, 0));
- bool is_multiscreen = screen_count > 1;
-
- Rect2i rect = _screen_get_rect(p_screen);
-
-
- int x11_screen_count = ScreenCount(x11_display);
- Window x11_window = RootWindow(x11_display, p_screen < x11_screen_count ? p_screen : 0);
- Atom type;
- int format = 0;
- unsigned long remaining = 0;
-
- unsigned int desktop_index = 0;
- Atom desktop_prop = XInternAtom(x11_display, "_NET_CURRENT_DESKTOP", True);
- if (desktop_prop != None) {
- unsigned long desktop_len = 0;
- unsigned char *desktop_data = nullptr;
- if (XGetWindowProperty(x11_display, x11_window, desktop_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &desktop_len, &remaining, &desktop_data) == Success) {
- if ((format == 32) && (desktop_len > 0) && desktop_data) {
- desktop_index = (unsigned int)desktop_data[0];
- }
- if (desktop_data) {
- XFree(desktop_data);
- }
- }
- }
- bool use_simple_method = true;
-
- if (is_multiscreen) {
-
- Atom gtk_workareas_prop = XInternAtom(x11_display, "_GTK_WORKAREAS", False);
- if (gtk_workareas_prop != None) {
- char gtk_workarea_prop_name[32];
- snprintf(gtk_workarea_prop_name, 32, "_GTK_WORKAREAS_D%d", desktop_index);
- Atom gtk_workarea_prop = XInternAtom(x11_display, gtk_workarea_prop_name, True);
- if (gtk_workarea_prop != None) {
- unsigned long workarea_len = 0;
- unsigned char *workarea_data = nullptr;
- if (XGetWindowProperty(x11_display, x11_window, gtk_workarea_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &workarea_len, &remaining, &workarea_data) == Success) {
- if ((format == 32) && (workarea_len % 4 == 0) && workarea_data) {
- long *rect_data = (long *)workarea_data;
- for (uint32_t data_offset = 0; data_offset < workarea_len; data_offset += 4) {
- Rect2i workarea_rect;
- workarea_rect.position.x = rect_data[data_offset];
- workarea_rect.position.y = rect_data[data_offset + 1];
- workarea_rect.size.x = rect_data[data_offset + 2];
- workarea_rect.size.y = rect_data[data_offset + 3];
-
-
- if (rect.grow(-1).intersects(workarea_rect)) {
- rect = rect.intersection(workarea_rect);
- XFree(workarea_data);
- return rect;
- }
- }
- }
- }
- if (workarea_data) {
- XFree(workarea_data);
- }
- }
- }
-
- Atom client_list_prop = XInternAtom(x11_display, "_NET_CLIENT_LIST", True);
- if (client_list_prop != None) {
- unsigned long clients_len = 0;
- unsigned char *clients_data = nullptr;
- if (XGetWindowProperty(x11_display, x11_window, client_list_prop, 0, LONG_MAX, False, XA_WINDOW, &type, &format, &clients_len, &remaining, &clients_data) == Success) {
- if ((format == 32) && (clients_len > 0) && clients_data) {
- Window *windows_data = (Window *)clients_data;
- Rect2i desktop_rect;
- bool desktop_valid = false;
-
- {
- Atom desktop_geometry_prop = XInternAtom(x11_display, "_NET_DESKTOP_GEOMETRY", True);
- if (desktop_geometry_prop != None) {
- unsigned long geom_len = 0;
- unsigned char *geom_data = nullptr;
- if (XGetWindowProperty(x11_display, x11_window, desktop_geometry_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &geom_len, &remaining, &geom_data) == Success) {
- if ((format == 32) && (geom_len >= 2) && geom_data) {
- desktop_valid = true;
- long *size_data = (long *)geom_data;
- desktop_rect.size.x = size_data[0];
- desktop_rect.size.y = size_data[1];
- }
- }
- if (geom_data) {
- XFree(geom_data);
- }
- }
- }
-
- if (desktop_valid) {
- Atom desktop_viewport_prop = XInternAtom(x11_display, "_NET_DESKTOP_VIEWPORT", True);
- if (desktop_viewport_prop != None) {
- unsigned long viewport_len = 0;
- unsigned char *viewport_data = nullptr;
- if (XGetWindowProperty(x11_display, x11_window, desktop_viewport_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &viewport_len, &remaining, &viewport_data) == Success) {
- if ((format == 32) && (viewport_len >= 2) && viewport_data) {
- desktop_valid = true;
- long *pos_data = (long *)viewport_data;
- desktop_rect.position.x = pos_data[0];
- desktop_rect.position.y = pos_data[1];
- }
- }
- if (viewport_data) {
- XFree(viewport_data);
- }
- }
- }
- if (desktop_valid) {
- use_simple_method = false;
-
-
- int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&bad_window_error_handler);
- for (unsigned long win_index = 0; win_index < clients_len; ++win_index) {
- g_bad_window = false;
-
- bool strut_found = false;
- unsigned long strut_len = 0;
- unsigned char *strut_data = nullptr;
- Atom strut_partial_prop = XInternAtom(x11_display, "_NET_WM_STRUT_PARTIAL", True);
- if (strut_partial_prop != None) {
- if (XGetWindowProperty(x11_display, windows_data[win_index], strut_partial_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &strut_len, &remaining, &strut_data) == Success) {
- strut_found = true;
- }
- }
-
- if (!g_bad_window && !strut_found) {
- Atom strut_prop = XInternAtom(x11_display, "_NET_WM_STRUT", True);
- if (strut_prop != None) {
- if (XGetWindowProperty(x11_display, windows_data[win_index], strut_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &strut_len, &remaining, &strut_data) == Success) {
- strut_found = true;
- }
- }
- }
- if (!g_bad_window && strut_found && (format == 32) && (strut_len >= 4) && strut_data) {
- long *struts = (long *)strut_data;
- long left = struts[0];
- long right = struts[1];
- long top = struts[2];
- long bottom = struts[3];
- long left_start_y, left_end_y, right_start_y, right_end_y;
- long top_start_x, top_end_x, bottom_start_x, bottom_end_x;
- if (strut_len >= 12) {
- left_start_y = struts[4];
- left_end_y = struts[5];
- right_start_y = struts[6];
- right_end_y = struts[7];
- top_start_x = struts[8];
- top_end_x = struts[9];
- bottom_start_x = struts[10];
- bottom_end_x = struts[11];
- } else {
- left_start_y = 0;
- left_end_y = desktop_rect.size.y;
- right_start_y = 0;
- right_end_y = desktop_rect.size.y;
- top_start_x = 0;
- top_end_x = desktop_rect.size.x;
- bottom_start_x = 0;
- bottom_end_x = desktop_rect.size.x;
- }
- const Point2i &pos = desktop_rect.position;
- const Size2i &size = desktop_rect.size;
- Rect2i left_rect(pos.x, pos.y + left_start_y, left, left_end_y - left_start_y);
- if (left_rect.size.x > 0) {
- Rect2i intersection = rect.intersection(left_rect);
- if (intersection.has_area() && intersection.size.x < rect.size.x) {
- rect.position.x = left_rect.size.x;
- rect.size.x = rect.size.x - intersection.size.x;
- }
- }
- Rect2i right_rect(pos.x + size.x - right, pos.y + right_start_y, right, right_end_y - right_start_y);
- if (right_rect.size.x > 0) {
- Rect2i intersection = rect.intersection(right_rect);
- if (intersection.has_area() && right_rect.size.x < rect.size.x) {
- rect.size.x = intersection.position.x - rect.position.x;
- }
- }
- Rect2i top_rect(pos.x + top_start_x, pos.y, top_end_x - top_start_x, top);
- if (top_rect.size.y > 0) {
- Rect2i intersection = rect.intersection(top_rect);
- if (intersection.has_area() && intersection.size.y < rect.size.y) {
- rect.position.y = top_rect.size.y;
- rect.size.y = rect.size.y - intersection.size.y;
- }
- }
- Rect2i bottom_rect(pos.x + bottom_start_x, pos.y + size.y - bottom, bottom_end_x - bottom_start_x, bottom);
- if (bottom_rect.size.y > 0) {
- Rect2i intersection = rect.intersection(bottom_rect);
- if (intersection.has_area() && right_rect.size.y < rect.size.y) {
- rect.size.y = intersection.position.y - rect.position.y;
- }
- }
- }
- if (strut_data) {
- XFree(strut_data);
- }
- }
-
- XSetErrorHandler(oldHandler);
- }
- }
- }
- if (clients_data) {
- XFree(clients_data);
- }
- }
- }
-
- if (use_simple_method) {
-
- Atom workarea_prop = XInternAtom(x11_display, "_NET_WORKAREA", True);
- if (workarea_prop != None) {
- unsigned long workarea_len = 0;
- unsigned char *workarea_data = nullptr;
- if (XGetWindowProperty(x11_display, x11_window, workarea_prop, 0, LONG_MAX, False, XA_CARDINAL, &type, &format, &workarea_len, &remaining, &workarea_data) == Success) {
- if ((format == 32) && (workarea_len >= ((desktop_index + 1) * 4)) && workarea_data) {
- long *rect_data = (long *)workarea_data;
- int data_offset = desktop_index * 4;
- Rect2i workarea_rect;
- workarea_rect.position.x = rect_data[data_offset];
- workarea_rect.position.y = rect_data[data_offset + 1];
- workarea_rect.size.x = rect_data[data_offset + 2];
- workarea_rect.size.y = rect_data[data_offset + 3];
-
- if (!is_multiscreen) {
- rect = workarea_rect;
- } else if (rect.intersects(workarea_rect)) {
- rect = rect.intersection(workarea_rect);
- }
- }
- }
- if (workarea_data) {
- XFree(workarea_data);
- }
- }
- }
- return rect;
- }
- int DisplayServerX11::screen_get_dpi(int p_screen) const {
- _THREAD_SAFE_METHOD_
- p_screen = _get_screen_index(p_screen);
- ERR_FAIL_INDEX_V(p_screen, get_screen_count(), 0);
-
- Size2i sc = screen_get_size(p_screen);
- if (xrandr_ext_ok) {
- int count = 0;
- if (xrr_get_monitors) {
- xrr_monitor_info *monitors = xrr_get_monitors(x11_display, windows[MAIN_WINDOW_ID].x11_window, true, &count);
- if (p_screen < count) {
- double xdpi = sc.width / (double)monitors[p_screen].mwidth * 25.4;
- double ydpi = sc.height / (double)monitors[p_screen].mheight * 25.4;
- xrr_free_monitors(monitors);
- return (xdpi + ydpi) / 2;
- }
- xrr_free_monitors(monitors);
- } else if (p_screen == 0) {
- XRRScreenSize *sizes = XRRSizes(x11_display, 0, &count);
- if (sizes) {
- double xdpi = sc.width / (double)sizes[0].mwidth * 25.4;
- double ydpi = sc.height / (double)sizes[0].mheight * 25.4;
- return (xdpi + ydpi) / 2;
- }
- }
- }
- int width_mm = DisplayWidthMM(x11_display, p_screen);
- int height_mm = DisplayHeightMM(x11_display, p_screen);
- double xdpi = (width_mm ? sc.width / (double)width_mm * 25.4 : 0);
- double ydpi = (height_mm ? sc.height / (double)height_mm * 25.4 : 0);
- if (xdpi || ydpi) {
- return (xdpi + ydpi) / (xdpi && ydpi ? 2 : 1);
- }
-
- return 96;
- }
- int get_image_errorhandler(Display *dpy, XErrorEvent *ev) {
- return 0;
- }
- Color DisplayServerX11::screen_get_pixel(const Point2i &p_position) const {
- Point2i pos = p_position;
- if (xwayland) {
- return Color();
- }
- int (*old_handler)(Display *, XErrorEvent *) = XSetErrorHandler(&get_image_errorhandler);
- Color color;
- int number_of_screens = XScreenCount(x11_display);
- for (int i = 0; i < number_of_screens; i++) {
- Window root = XRootWindow(x11_display, i);
- XWindowAttributes root_attrs;
- XGetWindowAttributes(x11_display, root, &root_attrs);
- if ((pos.x >= root_attrs.x) && (pos.x <= root_attrs.x + root_attrs.width) && (pos.y >= root_attrs.y) && (pos.y <= root_attrs.y + root_attrs.height)) {
- XImage *image = XGetImage(x11_display, root, pos.x, pos.y, 1, 1, AllPlanes, XYPixmap);
- if (image) {
- XColor c;
- c.pixel = XGetPixel(image, 0, 0);
- XDestroyImage(image);
- XQueryColor(x11_display, XDefaultColormap(x11_display, i), &c);
- color = Color(float(c.red) / 65535.0, float(c.green) / 65535.0, float(c.blue) / 65535.0, 1.0);
- break;
- }
- }
- }
- XSetErrorHandler(old_handler);
- return color;
- }
- Ref<Image> DisplayServerX11::screen_get_image(int p_screen) const {
- ERR_FAIL_INDEX_V(p_screen, get_screen_count(), Ref<Image>());
- switch (p_screen) {
- case SCREEN_PRIMARY: {
- p_screen = get_primary_screen();
- } break;
- case SCREEN_OF_MAIN_WINDOW: {
- p_screen = window_get_current_screen(MAIN_WINDOW_ID);
- } break;
- default:
- break;
- }
- ERR_FAIL_COND_V(p_screen < 0, Ref<Image>());
- if (xwayland) {
- return Ref<Image>();
- }
- int (*old_handler)(Display *, XErrorEvent *) = XSetErrorHandler(&get_image_errorhandler);
- XImage *image = nullptr;
- bool found = false;
- int event_base, error_base;
- if (xinerama_ext_ok && XineramaQueryExtension(x11_display, &event_base, &error_base)) {
- int xin_count;
- XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &xin_count);
- if (xsi) {
- if (xin_count > 0) {
- if (p_screen < xin_count) {
- int x_count = XScreenCount(x11_display);
- for (int i = 0; i < x_count; i++) {
- Window root = XRootWindow(x11_display, i);
- XWindowAttributes root_attrs;
- XGetWindowAttributes(x11_display, root, &root_attrs);
- if ((xsi[p_screen].x_org >= root_attrs.x) && (xsi[p_screen].x_org <= root_attrs.x + root_attrs.width) && (xsi[p_screen].y_org >= root_attrs.y) && (xsi[p_screen].y_org <= root_attrs.y + root_attrs.height)) {
- found = true;
- image = XGetImage(x11_display, root, xsi[p_screen].x_org, xsi[p_screen].y_org, xsi[p_screen].width, xsi[p_screen].height, AllPlanes, ZPixmap);
- break;
- }
- }
- } else {
- ERR_PRINT(vformat("Invalid screen index: %d (count: %d).", p_screen, xin_count));
- }
- }
- XFree(xsi);
- }
- }
- if (!found) {
- int x_count = XScreenCount(x11_display);
- if (p_screen < x_count) {
- Window root = XRootWindow(x11_display, p_screen);
- XWindowAttributes root_attrs;
- XGetWindowAttributes(x11_display, root, &root_attrs);
- image = XGetImage(x11_display, root, root_attrs.x, root_attrs.y, root_attrs.width, root_attrs.height, AllPlanes, ZPixmap);
- } else {
- ERR_PRINT(vformat("Invalid screen index: %d (count: %d).", p_screen, x_count));
- }
- }
- XSetErrorHandler(old_handler);
- Ref<Image> img;
- if (image) {
- int width = image->width;
- int height = image->height;
- Vector<uint8_t> img_data;
- img_data.resize(height * width * 4);
- uint8_t *sr = (uint8_t *)image->data;
- uint8_t *wr = (uint8_t *)img_data.ptrw();
- if (image->bits_per_pixel == 24 && image->red_mask == 0xff0000 && image->green_mask == 0x00ff00 && image->blue_mask == 0x0000ff) {
- for (int y = 0; y < height; y++) {
- for (int x = 0; x < width; x++) {
- wr[(y * width + x) * 4 + 0] = sr[(y * width + x) * 3 + 2];
- wr[(y * width + x) * 4 + 1] = sr[(y * width + x) * 3 + 1];
- wr[(y * width + x) * 4 + 2] = sr[(y * width + x) * 3 + 0];
- wr[(y * width + x) * 4 + 3] = 255;
- }
- }
- } else if (image->bits_per_pixel == 24 && image->red_mask == 0x0000ff && image->green_mask == 0x00ff00 && image->blue_mask == 0xff0000) {
- for (int y = 0; y < height; y++) {
- for (int x = 0; x < width; x++) {
- wr[(y * width + x) * 4 + 0] = sr[(y * width + x) * 3 + 2];
- wr[(y * width + x) * 4 + 1] = sr[(y * width + x) * 3 + 1];
- wr[(y * width + x) * 4 + 2] = sr[(y * width + x) * 3 + 0];
- wr[(y * width + x) * 4 + 3] = 255;
- }
- }
- } else if (image->bits_per_pixel == 32 && image->red_mask == 0xff0000 && image->green_mask == 0x00ff00 && image->blue_mask == 0x0000ff) {
- for (int y = 0; y < height; y++) {
- for (int x = 0; x < width; x++) {
- wr[(y * width + x) * 4 + 0] = sr[(y * width + x) * 4 + 2];
- wr[(y * width + x) * 4 + 1] = sr[(y * width + x) * 4 + 1];
- wr[(y * width + x) * 4 + 2] = sr[(y * width + x) * 4 + 0];
- wr[(y * width + x) * 4 + 3] = 255;
- }
- }
- } else {
- String msg = vformat("XImage with RGB mask %x %x %x and depth %d is not supported.", (uint64_t)image->red_mask, (uint64_t)image->green_mask, (uint64_t)image->blue_mask, (int64_t)image->bits_per_pixel);
- XDestroyImage(image);
- ERR_FAIL_V_MSG(Ref<Image>(), msg);
- }
- img = Image::create_from_data(width, height, false, Image::FORMAT_RGBA8, img_data);
- XDestroyImage(image);
- }
- return img;
- }
- float DisplayServerX11::screen_get_refresh_rate(int p_screen) const {
- _THREAD_SAFE_METHOD_
- p_screen = _get_screen_index(p_screen);
- ERR_FAIL_INDEX_V(p_screen, get_screen_count(), SCREEN_REFRESH_RATE_FALLBACK);
-
- if (xrandr_ext_ok) {
- XRRScreenResources *screen_info = XRRGetScreenResourcesCurrent(x11_display, windows[MAIN_WINDOW_ID].x11_window);
- if (screen_info) {
- RRMode current_mode = 0;
- xrr_monitor_info *monitors = nullptr;
- if (xrr_get_monitors) {
- int count = 0;
- monitors = xrr_get_monitors(x11_display, windows[MAIN_WINDOW_ID].x11_window, true, &count);
- ERR_FAIL_INDEX_V(p_screen, count, SCREEN_REFRESH_RATE_FALLBACK);
- } else {
- ERR_PRINT("An error occurred while trying to get the screen refresh rate.");
- return SCREEN_REFRESH_RATE_FALLBACK;
- }
- bool found_active_mode = false;
- for (int crtc = 0; crtc < screen_info->ncrtc; crtc++) {
- XRRCrtcInfo *monitor_info = XRRGetCrtcInfo(x11_display, screen_info, screen_info->crtcs[crtc]);
- if (monitor_info->x != monitors[p_screen].x || monitor_info->y != monitors[p_screen].y) {
- continue;
- }
- if (monitor_info->mode != None) {
- current_mode = monitor_info->mode;
- found_active_mode = true;
- break;
- }
- }
- if (found_active_mode) {
- for (int mode = 0; mode < screen_info->nmode; mode++) {
- XRRModeInfo m_info = screen_info->modes[mode];
- if (m_info.id == current_mode) {
-
- return Math::snapped((float)m_info.dotClock / ((float)m_info.hTotal * (float)m_info.vTotal), 0.01);
- }
- }
- }
- ERR_PRINT("An error occurred while trying to get the screen refresh rate.");
- return SCREEN_REFRESH_RATE_FALLBACK;
- } else {
- ERR_PRINT("An error occurred while trying to get the screen refresh rate.");
- return SCREEN_REFRESH_RATE_FALLBACK;
- }
- }
- ERR_PRINT("An error occurred while trying to get the screen refresh rate.");
- return SCREEN_REFRESH_RATE_FALLBACK;
- }
- #ifdef DBUS_ENABLED
- void DisplayServerX11::screen_set_keep_on(bool p_enable) {
- if (screen_is_kept_on() == p_enable) {
- return;
- }
- if (p_enable) {
- screensaver->inhibit();
- } else {
- screensaver->uninhibit();
- }
- keep_screen_on = p_enable;
- }
- bool DisplayServerX11::screen_is_kept_on() const {
- return keep_screen_on;
- }
- #endif
- Vector<DisplayServer::WindowID> DisplayServerX11::get_window_list() const {
- _THREAD_SAFE_METHOD_
- Vector<int> ret;
- for (const KeyValue<WindowID, WindowData> &E : windows) {
- ret.push_back(E.key);
- }
- return ret;
- }
- DisplayServer::WindowID DisplayServerX11::create_sub_window(WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Rect2i &p_rect, bool p_exclusive, WindowID p_transient_parent) {
- _THREAD_SAFE_METHOD_
- WindowID id = _create_window(p_mode, p_vsync_mode, p_flags, p_rect);
- for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
- if (p_flags & (1 << i)) {
- window_set_flag(WindowFlags(i), true, id);
- }
- }
- #ifdef RD_ENABLED
- if (rendering_device) {
- rendering_device->screen_create(id);
- }
- #endif
- if (p_transient_parent != INVALID_WINDOW_ID) {
- window_set_transient(id, p_transient_parent);
- }
- return id;
- }
- void DisplayServerX11::show_window(WindowID p_id) {
- _THREAD_SAFE_METHOD_
- const WindowData &wd = windows[p_id];
- popup_open(p_id);
- DEBUG_LOG_X11("show_window: %lu (%u) \n", wd.x11_window, p_id);
- XMapWindow(x11_display, wd.x11_window);
- XSync(x11_display, False);
- _validate_mode_on_map(p_id);
- }
- void DisplayServerX11::delete_sub_window(WindowID p_id) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_id));
- ERR_FAIL_COND_MSG(p_id == MAIN_WINDOW_ID, "Main window can't be deleted");
- popup_close(p_id);
- WindowData &wd = windows[p_id];
- DEBUG_LOG_X11("delete_sub_window: %lu (%u) \n", wd.x11_window, p_id);
- if (window_mouseover_id == p_id) {
- window_mouseover_id = INVALID_WINDOW_ID;
- _send_window_event(windows[p_id], WINDOW_EVENT_MOUSE_EXIT);
- }
- while (wd.transient_children.size()) {
- window_set_transient(*wd.transient_children.begin(), INVALID_WINDOW_ID);
- }
- if (wd.transient_parent != INVALID_WINDOW_ID) {
- window_set_transient(p_id, INVALID_WINDOW_ID);
- }
- #if defined(RD_ENABLED)
- if (rendering_device) {
- rendering_device->screen_free(p_id);
- }
- if (rendering_context) {
- rendering_context->window_destroy(p_id);
- }
- #endif
- #ifdef GLES3_ENABLED
- if (gl_manager) {
- gl_manager->window_destroy(p_id);
- }
- if (gl_manager_egl) {
- gl_manager_egl->window_destroy(p_id);
- }
- #endif
- if (wd.xic) {
- XDestroyIC(wd.xic);
- wd.xic = nullptr;
- }
- XDestroyWindow(x11_display, wd.x11_xim_window);
- #ifdef XKB_ENABLED
- if (xkb_loaded_v05p) {
- if (wd.xkb_state) {
- xkb_compose_state_unref(wd.xkb_state);
- wd.xkb_state = nullptr;
- }
- }
- #endif
- XUnmapWindow(x11_display, wd.x11_window);
- XDestroyWindow(x11_display, wd.x11_window);
- window_set_rect_changed_callback(Callable(), p_id);
- window_set_window_event_callback(Callable(), p_id);
- window_set_input_event_callback(Callable(), p_id);
- window_set_input_text_callback(Callable(), p_id);
- window_set_drop_files_callback(Callable(), p_id);
- windows.erase(p_id);
- }
- int64_t DisplayServerX11::window_get_native_handle(HandleType p_handle_type, WindowID p_window) const {
- ERR_FAIL_COND_V(!windows.has(p_window), 0);
- switch (p_handle_type) {
- case DISPLAY_HANDLE: {
- return (int64_t)x11_display;
- }
- case WINDOW_HANDLE: {
- return (int64_t)windows[p_window].x11_window;
- }
- case WINDOW_VIEW: {
- return 0;
- }
- #ifdef GLES3_ENABLED
- case OPENGL_CONTEXT: {
- if (gl_manager) {
- return (int64_t)gl_manager->get_glx_context(p_window);
- }
- if (gl_manager_egl) {
- return (int64_t)gl_manager_egl->get_context(p_window);
- }
- return 0;
- }
- case EGL_DISPLAY: {
- if (gl_manager_egl) {
- return (int64_t)gl_manager_egl->get_display(p_window);
- }
- return 0;
- }
- case EGL_CONFIG: {
- if (gl_manager_egl) {
- return (int64_t)gl_manager_egl->get_config(p_window);
- }
- return 0;
- }
- #endif
- default: {
- return 0;
- }
- }
- }
- void DisplayServerX11::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- wd.instance_id = p_instance;
- }
- ObjectID DisplayServerX11::window_get_attached_instance_id(WindowID p_window) const {
- ERR_FAIL_COND_V(!windows.has(p_window), ObjectID());
- const WindowData &wd = windows[p_window];
- return wd.instance_id;
- }
- DisplayServerX11::WindowID DisplayServerX11::get_window_at_screen_position(const Point2i &p_position) const {
- WindowID found_window = INVALID_WINDOW_ID;
- WindowID parent_window = INVALID_WINDOW_ID;
- unsigned int focus_order = 0;
- for (const KeyValue<WindowID, WindowData> &E : windows) {
- const WindowData &wd = E.value;
-
- if (wd.focus_order == 0) {
- continue;
- }
-
- WindowID window_id = E.key;
- Rect2i win_rect = Rect2i(window_get_position(window_id), window_get_size(window_id));
- if (win_rect.has_point(p_position)) {
-
- if ((parent_window != wd.transient_parent) || (wd.focus_order > focus_order)) {
- found_window = window_id;
- parent_window = wd.transient_parent;
- focus_order = wd.focus_order;
- }
- }
- }
- return found_window;
- }
- void DisplayServerX11::window_set_title(const String &p_title, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- XStoreName(x11_display, wd.x11_window, p_title.utf8().get_data());
- Atom _net_wm_name = XInternAtom(x11_display, "_NET_WM_NAME", false);
- Atom utf8_string = XInternAtom(x11_display, "UTF8_STRING", false);
- if (_net_wm_name != None && utf8_string != None) {
- XChangeProperty(x11_display, wd.x11_window, _net_wm_name, utf8_string, 8, PropModeReplace, (unsigned char *)p_title.utf8().get_data(), p_title.utf8().length());
- }
- }
- void DisplayServerX11::window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- windows[p_window].mpath = p_region;
- _update_window_mouse_passthrough(p_window);
- }
- void DisplayServerX11::_update_window_mouse_passthrough(WindowID p_window) {
- ERR_FAIL_COND(!windows.has(p_window));
- ERR_FAIL_COND(!xshaped_ext_ok);
- const Vector<Vector2> region_path = windows[p_window].mpath;
- int event_base, error_base;
- const Bool ext_okay = XShapeQueryExtension(x11_display, &event_base, &error_base);
- if (ext_okay) {
- if (windows[p_window].mpass) {
- Region region = XCreateRegion();
- XShapeCombineRegion(x11_display, windows[p_window].x11_window, ShapeInput, 0, 0, region, ShapeSet);
- XDestroyRegion(region);
- } else if (region_path.size() == 0) {
- XShapeCombineMask(x11_display, windows[p_window].x11_window, ShapeInput, 0, 0, None, ShapeSet);
- } else {
- XPoint *points = (XPoint *)memalloc(sizeof(XPoint) * region_path.size());
- for (int i = 0; i < region_path.size(); i++) {
- points[i].x = region_path[i].x;
- points[i].y = region_path[i].y;
- }
- Region region = XPolygonRegion(points, region_path.size(), EvenOddRule);
- memfree(points);
- XShapeCombineRegion(x11_display, windows[p_window].x11_window, ShapeInput, 0, 0, region, ShapeSet);
- XDestroyRegion(region);
- }
- }
- }
- void DisplayServerX11::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- wd.rect_changed_callback = p_callable;
- }
- void DisplayServerX11::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- wd.event_callback = p_callable;
- }
- void DisplayServerX11::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- wd.input_event_callback = p_callable;
- }
- void DisplayServerX11::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- wd.input_text_callback = p_callable;
- }
- void DisplayServerX11::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- wd.drop_files_callback = p_callable;
- }
- int DisplayServerX11::window_get_current_screen(WindowID p_window) const {
- _THREAD_SAFE_METHOD_
- int count = get_screen_count();
- if (count < 2) {
-
- return 0;
- }
- ERR_FAIL_COND_V(!windows.has(p_window), 0);
- const WindowData &wd = windows[p_window];
- const Rect2i window_rect(wd.position, wd.size);
-
- int screen_index = 0;
- int max_area = 0;
- for (int i = 0; i < count; i++) {
- Rect2i screen_rect = _screen_get_rect(i);
- Rect2i intersection = screen_rect.intersection(window_rect);
- int area = intersection.get_area();
- if (area > max_area) {
- max_area = area;
- screen_index = i;
- }
- }
- return screen_index;
- }
- void DisplayServerX11::gl_window_make_current(DisplayServer::WindowID p_window_id) {
- #if defined(GLES3_ENABLED)
- if (gl_manager) {
- gl_manager->window_make_current(p_window_id);
- }
- if (gl_manager_egl) {
- gl_manager_egl->window_make_current(p_window_id);
- }
- #endif
- }
- void DisplayServerX11::window_set_current_screen(int p_screen, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- p_screen = _get_screen_index(p_screen);
- ERR_FAIL_INDEX(p_screen, get_screen_count());
- if (window_get_current_screen(p_window) == p_screen) {
- return;
- }
- if (window_get_mode(p_window) == WINDOW_MODE_FULLSCREEN || window_get_mode(p_window) == WINDOW_MODE_MAXIMIZED) {
- Point2i position = screen_get_position(p_screen);
- Size2i size = screen_get_size(p_screen);
- XMoveResizeWindow(x11_display, wd.x11_window, position.x, position.y, size.x, size.y);
- } else {
- Rect2i srect = screen_get_usable_rect(p_screen);
- Point2i wpos = window_get_position(p_window) - screen_get_position(window_get_current_screen(p_window));
- Size2i wsize = window_get_size(p_window);
- wpos += srect.position;
- if (srect != Rect2i()) {
- wpos = wpos.clamp(srect.position, srect.position + srect.size - wsize / 3);
- }
- window_set_position(wpos, p_window);
- }
- }
- void DisplayServerX11::window_set_transient(WindowID p_window, WindowID p_parent) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(p_window == p_parent);
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd_window = windows[p_window];
- WindowID prev_parent = wd_window.transient_parent;
- ERR_FAIL_COND(prev_parent == p_parent);
- DEBUG_LOG_X11("window_set_transient: %lu (%u), prev_parent=%u, parent=%u\n", wd_window.x11_window, p_window, prev_parent, p_parent);
- ERR_FAIL_COND_MSG(wd_window.on_top, "Windows with the 'on top' can't become transient.");
- if (p_parent == INVALID_WINDOW_ID) {
-
- ERR_FAIL_COND(prev_parent == INVALID_WINDOW_ID);
- ERR_FAIL_COND(!windows.has(prev_parent));
- WindowData &wd_parent = windows[prev_parent];
- wd_window.transient_parent = INVALID_WINDOW_ID;
- wd_parent.transient_children.erase(p_window);
- XSetTransientForHint(x11_display, wd_window.x11_window, None);
- XWindowAttributes xwa;
- XSync(x11_display, False);
- XGetWindowAttributes(x11_display, wd_parent.x11_window, &xwa);
-
-
-
- if (!wd_window.no_focus && !wd_window.is_popup && wd_window.focused) {
- if ((xwa.map_state == IsViewable) && !wd_parent.no_focus && !wd_window.is_popup && _window_focus_check()) {
- _set_input_focus(wd_parent.x11_window, RevertToPointerRoot);
- }
- }
- } else {
- ERR_FAIL_COND(!windows.has(p_parent));
- ERR_FAIL_COND_MSG(prev_parent != INVALID_WINDOW_ID, "Window already has a transient parent");
- WindowData &wd_parent = windows[p_parent];
- wd_window.transient_parent = p_parent;
- wd_parent.transient_children.insert(p_window);
- XSetTransientForHint(x11_display, wd_window.x11_window, wd_parent.x11_window);
- }
- }
- void DisplayServerX11::_update_size_hints(WindowID p_window) {
- WindowData &wd = windows[p_window];
- WindowMode window_mode = window_get_mode(p_window);
- XSizeHints *xsh = XAllocSizeHints();
-
- xsh->flags |= PPosition | PSize;
- xsh->x = wd.position.x;
- xsh->y = wd.position.y;
- xsh->width = wd.size.width;
- xsh->height = wd.size.height;
- if (window_mode == WINDOW_MODE_FULLSCREEN || window_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
-
- } else if (window_get_flag(WINDOW_FLAG_RESIZE_DISABLED, p_window)) {
-
- xsh->flags |= PMinSize | PMaxSize;
- xsh->min_width = wd.size.x;
- xsh->max_width = wd.size.x;
- xsh->min_height = wd.size.y;
- xsh->max_height = wd.size.y;
- } else {
-
- if (wd.min_size != Size2i()) {
- xsh->flags |= PMinSize;
- xsh->min_width = wd.min_size.x;
- xsh->min_height = wd.min_size.y;
- }
- if (wd.max_size != Size2i()) {
- xsh->flags |= PMaxSize;
- xsh->max_width = wd.max_size.x;
- xsh->max_height = wd.max_size.y;
- }
- }
- XSetWMNormalHints(x11_display, wd.x11_window, xsh);
- XFree(xsh);
- }
- Point2i DisplayServerX11::window_get_position(WindowID p_window) const {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND_V(!windows.has(p_window), Point2i());
- const WindowData &wd = windows[p_window];
- return wd.position;
- }
- Point2i DisplayServerX11::window_get_position_with_decorations(WindowID p_window) const {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
- const WindowData &wd = windows[p_window];
- if (wd.fullscreen) {
- return wd.position;
- }
- XWindowAttributes xwa;
- XSync(x11_display, False);
- XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
- int x = wd.position.x;
- int y = wd.position.y;
- Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True);
- if (prop != None) {
- Atom type;
- int format;
- unsigned long len;
- unsigned long remaining;
- unsigned char *data = nullptr;
- if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
- if (format == 32 && len == 4 && data) {
- long *extents = (long *)data;
- x -= extents[0];
- y -= extents[2];
- }
- XFree(data);
- }
- }
- return Size2i(x, y);
- }
- void DisplayServerX11::window_set_position(const Point2i &p_position, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- int x = 0;
- int y = 0;
- if (!window_get_flag(WINDOW_FLAG_BORDERLESS, p_window)) {
-
- XSync(x11_display, False);
- Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True);
- if (prop != None) {
- Atom type;
- int format;
- unsigned long len;
- unsigned long remaining;
- unsigned char *data = nullptr;
- if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
- if (format == 32 && len == 4 && data) {
- long *extents = (long *)data;
- x = extents[0];
- y = extents[2];
- }
- XFree(data);
- }
- }
- }
- XMoveWindow(x11_display, wd.x11_window, p_position.x - x, p_position.y - y);
- _update_real_mouse_position(wd);
- }
- void DisplayServerX11::window_set_max_size(const Size2i p_size, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- if ((p_size != Size2i()) && ((p_size.x < wd.min_size.x) || (p_size.y < wd.min_size.y))) {
- ERR_PRINT("Maximum window size can't be smaller than minimum window size!");
- return;
- }
- wd.max_size = p_size;
- _update_size_hints(p_window);
- XFlush(x11_display);
- }
- Size2i DisplayServerX11::window_get_max_size(WindowID p_window) const {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
- const WindowData &wd = windows[p_window];
- return wd.max_size;
- }
- void DisplayServerX11::window_set_min_size(const Size2i p_size, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- if ((p_size != Size2i()) && (wd.max_size != Size2i()) && ((p_size.x > wd.max_size.x) || (p_size.y > wd.max_size.y))) {
- ERR_PRINT("Minimum window size can't be larger than maximum window size!");
- return;
- }
- wd.min_size = p_size;
- _update_size_hints(p_window);
- XFlush(x11_display);
- }
- Size2i DisplayServerX11::window_get_min_size(WindowID p_window) const {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
- const WindowData &wd = windows[p_window];
- return wd.min_size;
- }
- void DisplayServerX11::window_set_size(const Size2i p_size, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- Size2i size = p_size;
- size = size.maxi(1);
- WindowData &wd = windows[p_window];
- if (wd.size.width == size.width && wd.size.height == size.height) {
- return;
- }
- XWindowAttributes xwa;
- XSync(x11_display, False);
- XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
- int old_w = xwa.width;
- int old_h = xwa.height;
-
- wd.size = size;
-
- _update_size_hints(p_window);
-
- XResizeWindow(x11_display, wd.x11_window, size.x, size.y);
- for (int timeout = 0; timeout < 50; ++timeout) {
- XSync(x11_display, False);
- XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
- if (old_w != xwa.width || old_h != xwa.height) {
- break;
- }
- OS::get_singleton()->delay_usec(10'000);
- }
-
- #if defined(RD_ENABLED)
- if (rendering_context) {
- rendering_context->window_set_size(p_window, xwa.width, xwa.height);
- }
- #endif
- #if defined(GLES3_ENABLED)
- if (gl_manager) {
- gl_manager->window_resize(p_window, xwa.width, xwa.height);
- }
- if (gl_manager_egl) {
- gl_manager_egl->window_resize(p_window, xwa.width, xwa.height);
- }
- #endif
- }
- Size2i DisplayServerX11::window_get_size(WindowID p_window) const {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
- const WindowData &wd = windows[p_window];
- return wd.size;
- }
- Size2i DisplayServerX11::window_get_size_with_decorations(WindowID p_window) const {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
- const WindowData &wd = windows[p_window];
- if (wd.fullscreen) {
- return wd.size;
- }
- XWindowAttributes xwa;
- XSync(x11_display, False);
- XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
- int w = xwa.width;
- int h = xwa.height;
- Atom prop = XInternAtom(x11_display, "_NET_FRAME_EXTENTS", True);
- if (prop != None) {
- Atom type;
- int format;
- unsigned long len;
- unsigned long remaining;
- unsigned char *data = nullptr;
- if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, 4, False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
- if (format == 32 && len == 4 && data) {
- long *extents = (long *)data;
- w += extents[0] + extents[1];
- h += extents[2] + extents[3];
- }
- XFree(data);
- }
- }
- return Size2i(w, h);
- }
- bool DisplayServerX11::_window_maximize_check(WindowID p_window, const char *p_atom_name) const {
- ERR_FAIL_COND_V(!windows.has(p_window), false);
- const WindowData &wd = windows[p_window];
- Atom property = XInternAtom(x11_display, p_atom_name, False);
- Atom type;
- int format;
- unsigned long len;
- unsigned long remaining;
- unsigned char *data = nullptr;
- bool retval = false;
- if (property == None) {
- return false;
- }
- int result = XGetWindowProperty(
- x11_display,
- wd.x11_window,
- property,
- 0,
- 1024,
- False,
- XA_ATOM,
- &type,
- &format,
- &len,
- &remaining,
- &data);
- if (result == Success && data) {
- Atom *atoms = (Atom *)data;
- Atom wm_act_max_horz;
- Atom wm_act_max_vert;
- if (strcmp(p_atom_name, "_NET_WM_STATE") == 0) {
- wm_act_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
- wm_act_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
- } else {
- wm_act_max_horz = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_HORZ", False);
- wm_act_max_vert = XInternAtom(x11_display, "_NET_WM_ACTION_MAXIMIZE_VERT", False);
- }
- bool found_wm_act_max_horz = false;
- bool found_wm_act_max_vert = false;
- for (uint64_t i = 0; i < len; i++) {
- if (atoms[i] == wm_act_max_horz) {
- found_wm_act_max_horz = true;
- }
- if (atoms[i] == wm_act_max_vert) {
- found_wm_act_max_vert = true;
- }
- if (found_wm_act_max_horz || found_wm_act_max_vert) {
- retval = true;
- break;
- }
- }
- XFree(data);
- }
- return retval;
- }
- bool DisplayServerX11::_window_minimize_check(WindowID p_window) const {
- const WindowData &wd = windows[p_window];
-
- Atom property = XInternAtom(x11_display, "_NET_WM_STATE", True);
- Atom hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", True);
- if (property == None || hidden == None) {
- return false;
- }
- Atom type;
- int format;
- unsigned long len;
- unsigned long remaining;
- Atom *atoms = nullptr;
- int result = XGetWindowProperty(
- x11_display,
- wd.x11_window,
- property,
- 0,
- 32,
- False,
- XA_ATOM,
- &type,
- &format,
- &len,
- &remaining,
- (unsigned char **)&atoms);
- if (result == Success && atoms) {
- for (unsigned int i = 0; i < len; i++) {
- if (atoms[i] == hidden) {
- XFree(atoms);
- return true;
- }
- }
- XFree(atoms);
- }
- return false;
- }
- bool DisplayServerX11::_window_fullscreen_check(WindowID p_window) const {
- ERR_FAIL_COND_V(!windows.has(p_window), false);
- const WindowData &wd = windows[p_window];
-
- Atom property = XInternAtom(x11_display, "_NET_WM_STATE", False);
- Atom type;
- int format;
- unsigned long len;
- unsigned long remaining;
- unsigned char *data = nullptr;
- bool retval = false;
- if (property == None) {
- return retval;
- }
- int result = XGetWindowProperty(
- x11_display,
- wd.x11_window,
- property,
- 0,
- 1024,
- False,
- XA_ATOM,
- &type,
- &format,
- &len,
- &remaining,
- &data);
- if (result == Success) {
- Atom *atoms = (Atom *)data;
- Atom wm_fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False);
- for (uint64_t i = 0; i < len; i++) {
- if (atoms[i] == wm_fullscreen) {
- retval = true;
- break;
- }
- }
- XFree(data);
- }
- return retval;
- }
- void DisplayServerX11::_validate_mode_on_map(WindowID p_window) {
-
- const WindowData &wd = windows[p_window];
- if (wd.fullscreen && !_window_fullscreen_check(p_window)) {
- _set_wm_fullscreen(p_window, true, wd.exclusive_fullscreen);
- } else if (wd.maximized && !_window_maximize_check(p_window, "_NET_WM_STATE")) {
- _set_wm_maximized(p_window, true);
- } else if (wd.minimized && !_window_minimize_check(p_window)) {
- _set_wm_minimized(p_window, true);
- }
- if (wd.on_top) {
- Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
- Atom wm_above = XInternAtom(x11_display, "_NET_WM_STATE_ABOVE", False);
- XClientMessageEvent xev;
- memset(&xev, 0, sizeof(xev));
- xev.type = ClientMessage;
- xev.window = wd.x11_window;
- xev.message_type = wm_state;
- xev.format = 32;
- xev.data.l[0] = _NET_WM_STATE_ADD;
- xev.data.l[1] = wm_above;
- xev.data.l[3] = 1;
- XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&xev);
- }
- }
- bool DisplayServerX11::window_is_maximize_allowed(WindowID p_window) const {
- _THREAD_SAFE_METHOD_
- return _window_maximize_check(p_window, "_NET_WM_ALLOWED_ACTIONS");
- }
- void DisplayServerX11::_set_wm_maximized(WindowID p_window, bool p_enabled) {
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
-
- XEvent xev;
- Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
- Atom wm_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
- Atom wm_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
- memset(&xev, 0, sizeof(xev));
- xev.type = ClientMessage;
- xev.xclient.window = wd.x11_window;
- xev.xclient.message_type = wm_state;
- xev.xclient.format = 32;
- xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
- xev.xclient.data.l[1] = wm_max_horz;
- xev.xclient.data.l[2] = wm_max_vert;
- XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
- if (p_enabled && window_is_maximize_allowed(p_window)) {
-
-
-
- for (int attempt = 0; window_get_mode(p_window) != WINDOW_MODE_MAXIMIZED && attempt < 50; attempt++) {
- OS::get_singleton()->delay_usec(10'000);
- }
- }
- wd.maximized = p_enabled;
- }
- void DisplayServerX11::_set_wm_minimized(WindowID p_window, bool p_enabled) {
- WindowData &wd = windows[p_window];
-
- XEvent xev;
- Atom wm_change = XInternAtom(x11_display, "WM_CHANGE_STATE", False);
- memset(&xev, 0, sizeof(xev));
- xev.type = ClientMessage;
- xev.xclient.window = wd.x11_window;
- xev.xclient.message_type = wm_change;
- xev.xclient.format = 32;
- xev.xclient.data.l[0] = p_enabled ? WM_IconicState : WM_NormalState;
- XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
- Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
- Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False);
- memset(&xev, 0, sizeof(xev));
- xev.type = ClientMessage;
- xev.xclient.window = wd.x11_window;
- xev.xclient.message_type = wm_state;
- xev.xclient.format = 32;
- xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
- xev.xclient.data.l[1] = wm_hidden;
- XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
- wd.minimized = p_enabled;
- }
- void DisplayServerX11::_set_wm_fullscreen(WindowID p_window, bool p_enabled, bool p_exclusive) {
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- if (p_enabled && !window_get_flag(WINDOW_FLAG_BORDERLESS, p_window)) {
-
- Hints hints;
- Atom property;
- hints.flags = 2;
- hints.decorations = 0;
- property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
- if (property != None) {
- XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
- }
- }
- if (p_enabled) {
-
- _update_size_hints(p_window);
- }
-
- XEvent xev;
- Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
- Atom wm_fullscreen = XInternAtom(x11_display, "_NET_WM_STATE_FULLSCREEN", False);
- memset(&xev, 0, sizeof(xev));
- xev.type = ClientMessage;
- xev.xclient.window = wd.x11_window;
- xev.xclient.message_type = wm_state;
- xev.xclient.format = 32;
- xev.xclient.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
- xev.xclient.data.l[1] = wm_fullscreen;
- xev.xclient.data.l[2] = 0;
- XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
-
- Atom bypass_compositor = XInternAtom(x11_display, "_NET_WM_BYPASS_COMPOSITOR", False);
- unsigned long compositing_disable_on = 0;
- if (p_enabled) {
- if (p_exclusive) {
- compositing_disable_on = 1;
- } else {
- compositing_disable_on = 2;
- }
- }
- if (bypass_compositor != None) {
- XChangeProperty(x11_display, wd.x11_window, bypass_compositor, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&compositing_disable_on, 1);
- }
- XFlush(x11_display);
- if (!p_enabled) {
-
- _update_size_hints(p_window);
-
- Hints hints;
- Atom property;
- hints.flags = 2;
- hints.decorations = wd.borderless ? 0 : 1;
- property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
- if (property != None) {
- XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
- }
- }
- }
- void DisplayServerX11::window_set_mode(WindowMode p_mode, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- WindowMode old_mode = window_get_mode(p_window);
- if (old_mode == p_mode) {
- return;
- }
-
- switch (old_mode) {
- case WINDOW_MODE_WINDOWED: {
-
- } break;
- case WINDOW_MODE_MINIMIZED: {
- _set_wm_minimized(p_window, false);
- } break;
- case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
- case WINDOW_MODE_FULLSCREEN: {
-
- wd.fullscreen = false;
- wd.exclusive_fullscreen = false;
- _set_wm_fullscreen(p_window, false, false);
-
- bool on_top = window_get_flag(WINDOW_FLAG_ALWAYS_ON_TOP, p_window);
- window_set_position(wd.last_position_before_fs, p_window);
- if (on_top) {
- _set_wm_maximized(p_window, false);
- }
- } break;
- case WINDOW_MODE_MAXIMIZED: {
- _set_wm_maximized(p_window, false);
- } break;
- }
- switch (p_mode) {
- case WINDOW_MODE_WINDOWED: {
-
- } break;
- case WINDOW_MODE_MINIMIZED: {
- _set_wm_minimized(p_window, true);
- } break;
- case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
- case WINDOW_MODE_FULLSCREEN: {
- wd.last_position_before_fs = wd.position;
- if (window_get_flag(WINDOW_FLAG_ALWAYS_ON_TOP, p_window)) {
- _set_wm_maximized(p_window, true);
- }
- wd.fullscreen = true;
- if (p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
- wd.exclusive_fullscreen = true;
- _set_wm_fullscreen(p_window, true, true);
- } else {
- wd.exclusive_fullscreen = false;
- _set_wm_fullscreen(p_window, true, false);
- }
- } break;
- case WINDOW_MODE_MAXIMIZED: {
- _set_wm_maximized(p_window, true);
- } break;
- }
- }
- DisplayServer::WindowMode DisplayServerX11::window_get_mode(WindowID p_window) const {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND_V(!windows.has(p_window), WINDOW_MODE_WINDOWED);
- const WindowData &wd = windows[p_window];
- if (wd.fullscreen) {
- if (wd.exclusive_fullscreen) {
- return WINDOW_MODE_EXCLUSIVE_FULLSCREEN;
- } else {
- return WINDOW_MODE_FULLSCREEN;
- }
- }
-
-
- if (_window_maximize_check(p_window, "_NET_WM_STATE")) {
- return WINDOW_MODE_MAXIMIZED;
- }
- {
- if (_window_minimize_check(p_window)) {
- return WINDOW_MODE_MINIMIZED;
- }
- }
-
- return WINDOW_MODE_WINDOWED;
- }
- void DisplayServerX11::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- switch (p_flag) {
- case WINDOW_FLAG_RESIZE_DISABLED: {
- wd.resize_disabled = p_enabled;
- _update_size_hints(p_window);
- XFlush(x11_display);
- } break;
- case WINDOW_FLAG_BORDERLESS: {
- Hints hints;
- Atom property;
- hints.flags = 2;
- hints.decorations = p_enabled ? 0 : 1;
- property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
- if (property != None) {
- XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
- }
-
- window_set_size(window_get_size(p_window), p_window);
- wd.borderless = p_enabled;
- _update_window_mouse_passthrough(p_window);
- } break;
- case WINDOW_FLAG_ALWAYS_ON_TOP: {
- ERR_FAIL_COND_MSG(wd.transient_parent != INVALID_WINDOW_ID, "Can't make a window transient if the 'on top' flag is active.");
- if (p_enabled && wd.fullscreen) {
- _set_wm_maximized(p_window, true);
- }
- Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
- Atom wm_above = XInternAtom(x11_display, "_NET_WM_STATE_ABOVE", False);
- XClientMessageEvent xev;
- memset(&xev, 0, sizeof(xev));
- xev.type = ClientMessage;
- xev.window = wd.x11_window;
- xev.message_type = wm_state;
- xev.format = 32;
- xev.data.l[0] = p_enabled ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
- xev.data.l[1] = wm_above;
- xev.data.l[3] = 1;
- XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&xev);
- if (!p_enabled && !wd.fullscreen) {
- _set_wm_maximized(p_window, false);
- }
- wd.on_top = p_enabled;
- } break;
- case WINDOW_FLAG_TRANSPARENT: {
- wd.layered_window = p_enabled;
- } break;
- case WINDOW_FLAG_NO_FOCUS: {
- wd.no_focus = p_enabled;
- } break;
- case WINDOW_FLAG_MOUSE_PASSTHROUGH: {
- wd.mpass = p_enabled;
- _update_window_mouse_passthrough(p_window);
- } break;
- case WINDOW_FLAG_POPUP: {
- XWindowAttributes xwa;
- XSync(x11_display, False);
- XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
- ERR_FAIL_COND_MSG(p_window == MAIN_WINDOW_ID, "Main window can't be popup.");
- ERR_FAIL_COND_MSG((xwa.map_state == IsViewable) && (wd.is_popup != p_enabled), "Popup flag can't changed while window is opened.");
- wd.is_popup = p_enabled;
- } break;
- default: {
- }
- }
- }
- bool DisplayServerX11::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND_V(!windows.has(p_window), false);
- const WindowData &wd = windows[p_window];
- switch (p_flag) {
- case WINDOW_FLAG_RESIZE_DISABLED: {
- return wd.resize_disabled;
- } break;
- case WINDOW_FLAG_BORDERLESS: {
- bool borderless = wd.borderless;
- Atom prop = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
- if (prop != None) {
- Atom type;
- int format;
- unsigned long len;
- unsigned long remaining;
- unsigned char *data = nullptr;
- if (XGetWindowProperty(x11_display, wd.x11_window, prop, 0, sizeof(Hints), False, AnyPropertyType, &type, &format, &len, &remaining, &data) == Success) {
- if (data && (format == 32) && (len >= 5)) {
- borderless = !(reinterpret_cast<Hints *>(data)->decorations);
- }
- if (data) {
- XFree(data);
- }
- }
- }
- return borderless;
- } break;
- case WINDOW_FLAG_ALWAYS_ON_TOP: {
- return wd.on_top;
- } break;
- case WINDOW_FLAG_TRANSPARENT: {
- return wd.layered_window;
- } break;
- case WINDOW_FLAG_NO_FOCUS: {
- return wd.no_focus;
- } break;
- case WINDOW_FLAG_MOUSE_PASSTHROUGH: {
- return wd.mpass;
- } break;
- case WINDOW_FLAG_POPUP: {
- return wd.is_popup;
- } break;
- default: {
- }
- }
- return false;
- }
- void DisplayServerX11::window_request_attention(WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- const WindowData &wd = windows[p_window];
-
-
-
-
- XEvent xev;
- Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
- Atom wm_attention = XInternAtom(x11_display, "_NET_WM_STATE_DEMANDS_ATTENTION", False);
- memset(&xev, 0, sizeof(xev));
- xev.type = ClientMessage;
- xev.xclient.window = wd.x11_window;
- xev.xclient.message_type = wm_state;
- xev.xclient.format = 32;
- xev.xclient.data.l[0] = _NET_WM_STATE_ADD;
- xev.xclient.data.l[1] = wm_attention;
- XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
- XFlush(x11_display);
- }
- void DisplayServerX11::window_move_to_foreground(WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- const WindowData &wd = windows[p_window];
- XEvent xev;
- Atom net_active_window = XInternAtom(x11_display, "_NET_ACTIVE_WINDOW", False);
- memset(&xev, 0, sizeof(xev));
- xev.type = ClientMessage;
- xev.xclient.window = wd.x11_window;
- xev.xclient.message_type = net_active_window;
- xev.xclient.format = 32;
- xev.xclient.data.l[0] = 1;
- xev.xclient.data.l[1] = CurrentTime;
- XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
- XFlush(x11_display);
- }
- DisplayServerX11::WindowID DisplayServerX11::get_focused_window() const {
- return last_focused_window;
- }
- bool DisplayServerX11::window_is_focused(WindowID p_window) const {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND_V(!windows.has(p_window), false);
- const WindowData &wd = windows[p_window];
- return wd.focused;
- }
- bool DisplayServerX11::window_can_draw(WindowID p_window) const {
-
- return window_get_mode(p_window) != WINDOW_MODE_MINIMIZED;
- }
- bool DisplayServerX11::can_any_window_draw() const {
- _THREAD_SAFE_METHOD_
- for (const KeyValue<WindowID, WindowData> &E : windows) {
- if (window_get_mode(E.key) != WINDOW_MODE_MINIMIZED) {
- return true;
- }
- }
- return false;
- }
- void DisplayServerX11::window_set_ime_active(const bool p_active, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- if (!wd.xic) {
- return;
- }
- if (!wd.focused) {
- wd.ime_active = false;
- im_text = String();
- im_selection = Vector2i();
- return;
- }
-
-
- if (p_active) {
- MutexLock mutex_lock(events_mutex);
- wd.ime_active = true;
- XMapWindow(x11_display, wd.x11_xim_window);
- XWindowAttributes xwa;
- XSync(x11_display, False);
- XGetWindowAttributes(x11_display, wd.x11_xim_window, &xwa);
- if (xwa.map_state == IsViewable && _window_focus_check()) {
- _set_input_focus(wd.x11_xim_window, RevertToParent);
- }
- XSetICFocus(wd.xic);
- } else {
- MutexLock mutex_lock(events_mutex);
- XUnsetICFocus(wd.xic);
- XUnmapWindow(x11_display, wd.x11_xim_window);
- wd.ime_active = false;
- im_text = String();
- im_selection = Vector2i();
- }
- }
- void DisplayServerX11::window_set_ime_position(const Point2i &p_pos, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- if (!wd.xic) {
- return;
- }
- if (!wd.focused) {
- return;
- }
- if (wd.ime_active) {
- XWindowAttributes xwa;
- XSync(x11_display, False);
- XGetWindowAttributes(x11_display, wd.x11_xim_window, &xwa);
- if (xwa.map_state == IsViewable) {
- XMoveWindow(x11_display, wd.x11_xim_window, p_pos.x, p_pos.y);
- }
- }
- }
- Point2i DisplayServerX11::ime_get_selection() const {
- return im_selection;
- }
- String DisplayServerX11::ime_get_text() const {
- return im_text;
- }
- void DisplayServerX11::cursor_set_shape(CursorShape p_shape) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
- if (p_shape == current_cursor) {
- return;
- }
- if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
- if (cursors[p_shape] != None) {
- for (const KeyValue<WindowID, WindowData> &E : windows) {
- XDefineCursor(x11_display, E.value.x11_window, cursors[p_shape]);
- }
- } else if (cursors[CURSOR_ARROW] != None) {
- for (const KeyValue<WindowID, WindowData> &E : windows) {
- XDefineCursor(x11_display, E.value.x11_window, cursors[CURSOR_ARROW]);
- }
- }
- }
- current_cursor = p_shape;
- }
- DisplayServerX11::CursorShape DisplayServerX11::cursor_get_shape() const {
- return current_cursor;
- }
- void DisplayServerX11::cursor_set_custom_image(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
- if (p_cursor.is_valid()) {
- HashMap<CursorShape, Vector<Variant>>::Iterator cursor_c = cursors_cache.find(p_shape);
- if (cursor_c) {
- if (cursor_c->value[0] == p_cursor && cursor_c->value[1] == p_hotspot) {
- cursor_set_shape(p_shape);
- return;
- }
- cursors_cache.erase(p_shape);
- }
- Ref<Image> image = _get_cursor_image_from_resource(p_cursor, p_hotspot);
- ERR_FAIL_COND(image.is_null());
- Vector2i texture_size = image->get_size();
-
- XcursorImage *cursor_image = XcursorImageCreate(texture_size.width, texture_size.height);
- XcursorUInt image_size = texture_size.width * texture_size.height;
- XcursorDim size = sizeof(XcursorPixel) * image_size;
- cursor_image->version = 1;
- cursor_image->size = size;
- cursor_image->xhot = p_hotspot.x;
- cursor_image->yhot = p_hotspot.y;
-
- cursor_image->pixels = (XcursorPixel *)memalloc(size);
- for (XcursorPixel index = 0; index < image_size; index++) {
- int row_index = floor(index / texture_size.width);
- int column_index = index % int(texture_size.width);
- *(cursor_image->pixels + index) = image->get_pixel(column_index, row_index).to_argb32();
- }
- ERR_FAIL_NULL(cursor_image->pixels);
-
- cursors[p_shape] = XcursorImageLoadCursor(x11_display, cursor_image);
- Vector<Variant> params;
- params.push_back(p_cursor);
- params.push_back(p_hotspot);
- cursors_cache.insert(p_shape, params);
- if (p_shape == current_cursor) {
- if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
- for (const KeyValue<WindowID, WindowData> &E : windows) {
- XDefineCursor(x11_display, E.value.x11_window, cursors[p_shape]);
- }
- }
- }
- memfree(cursor_image->pixels);
- XcursorImageDestroy(cursor_image);
- } else {
-
- if (cursor_img[p_shape]) {
- cursors[p_shape] = XcursorImageLoadCursor(x11_display, cursor_img[p_shape]);
- }
- cursors_cache.erase(p_shape);
- CursorShape c = current_cursor;
- current_cursor = CURSOR_MAX;
- cursor_set_shape(c);
- }
- }
- int DisplayServerX11::keyboard_get_layout_count() const {
- int _group_count = 0;
- XkbDescRec *kbd = XkbAllocKeyboard();
- if (kbd) {
- kbd->dpy = x11_display;
- XkbGetControls(x11_display, XkbAllControlsMask, kbd);
- XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
- const Atom *groups = kbd->names->groups;
- if (kbd->ctrls != nullptr) {
- _group_count = kbd->ctrls->num_groups;
- } else {
- while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
- _group_count++;
- }
- }
- XkbFreeKeyboard(kbd, 0, true);
- }
- return _group_count;
- }
- int DisplayServerX11::keyboard_get_current_layout() const {
- XkbStateRec state;
- XkbGetState(x11_display, XkbUseCoreKbd, &state);
- return state.group;
- }
- void DisplayServerX11::keyboard_set_current_layout(int p_index) {
- ERR_FAIL_INDEX(p_index, keyboard_get_layout_count());
- XkbLockGroup(x11_display, XkbUseCoreKbd, p_index);
- }
- String DisplayServerX11::keyboard_get_layout_language(int p_index) const {
- String ret;
- XkbDescRec *kbd = XkbAllocKeyboard();
- if (kbd) {
- kbd->dpy = x11_display;
- XkbGetControls(x11_display, XkbAllControlsMask, kbd);
- XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
- XkbGetNames(x11_display, XkbGroupNamesMask, kbd);
- int _group_count = 0;
- const Atom *groups = kbd->names->groups;
- if (kbd->ctrls != nullptr) {
- _group_count = kbd->ctrls->num_groups;
- } else {
- while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
- _group_count++;
- }
- }
- Atom names = kbd->names->symbols;
- if (names != None) {
- Vector<String> info = get_atom_name(x11_display, names).split("+");
- if (p_index >= 0 && p_index < _group_count) {
- if (p_index + 1 < info.size()) {
- ret = info[p_index + 1];
- } else {
- ret = "en";
- }
- } else {
- ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ").");
- }
- }
- XkbFreeKeyboard(kbd, 0, true);
- }
- return ret.substr(0, 2);
- }
- String DisplayServerX11::keyboard_get_layout_name(int p_index) const {
- String ret;
- XkbDescRec *kbd = XkbAllocKeyboard();
- if (kbd) {
- kbd->dpy = x11_display;
- XkbGetControls(x11_display, XkbAllControlsMask, kbd);
- XkbGetNames(x11_display, XkbSymbolsNameMask, kbd);
- XkbGetNames(x11_display, XkbGroupNamesMask, kbd);
- int _group_count = 0;
- const Atom *groups = kbd->names->groups;
- if (kbd->ctrls != nullptr) {
- _group_count = kbd->ctrls->num_groups;
- } else {
- while (_group_count < XkbNumKbdGroups && groups[_group_count] != None) {
- _group_count++;
- }
- }
- if (p_index >= 0 && p_index < _group_count) {
- ret = get_atom_name(x11_display, groups[p_index]);
- } else {
- ERR_PRINT("Index " + itos(p_index) + "is out of bounds (" + itos(_group_count) + ").");
- }
- XkbFreeKeyboard(kbd, 0, true);
- }
- return ret;
- }
- Key DisplayServerX11::keyboard_get_keycode_from_physical(Key p_keycode) const {
- Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
- Key keycode_no_mod = p_keycode & KeyModifierMask::CODE_MASK;
- unsigned int xkeycode = KeyMappingX11::get_xlibcode(keycode_no_mod);
- KeySym xkeysym = XkbKeycodeToKeysym(x11_display, xkeycode, keyboard_get_current_layout(), 0);
- if (is_ascii_lower_case(xkeysym)) {
- xkeysym -= ('a' - 'A');
- }
- Key key = KeyMappingX11::get_keycode(xkeysym);
-
-
- if (key == Key::NONE) {
- return p_keycode;
- }
- return (Key)(key | modifiers);
- }
- Key DisplayServerX11::keyboard_get_label_from_physical(Key p_keycode) const {
- Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
- Key keycode_no_mod = p_keycode & KeyModifierMask::CODE_MASK;
- unsigned int xkeycode = KeyMappingX11::get_xlibcode(keycode_no_mod);
- KeySym xkeysym = XkbKeycodeToKeysym(x11_display, xkeycode, keyboard_get_current_layout(), 0);
- if (is_ascii_lower_case(xkeysym)) {
- xkeysym -= ('a' - 'A');
- }
- Key key = KeyMappingX11::get_keycode(xkeysym);
- #ifdef XKB_ENABLED
- if (xkb_loaded_v08p) {
- String keysym = String::chr(xkb_keysym_to_utf32(xkb_keysym_to_upper(xkeysym)));
- key = fix_key_label(keysym[0], KeyMappingX11::get_keycode(xkeysym));
- }
- #endif
-
-
- if (key == Key::NONE) {
- return p_keycode;
- }
- return (Key)(key | modifiers);
- }
- DisplayServerX11::Property DisplayServerX11::_read_property(Display *p_display, Window p_window, Atom p_property) {
- Atom actual_type = None;
- int actual_format = 0;
- unsigned long nitems = 0;
- unsigned long bytes_after = 0;
- unsigned char *ret = nullptr;
-
- if (p_property != None) {
- int read_bytes = 1024;
- do {
- if (ret != nullptr) {
- XFree(ret);
- }
- XGetWindowProperty(p_display, p_window, p_property, 0, read_bytes, False, AnyPropertyType,
- &actual_type, &actual_format, &nitems, &bytes_after,
- &ret);
- read_bytes *= 2;
- } while (bytes_after != 0);
- }
- Property p = { ret, actual_format, (int)nitems, actual_type };
- return p;
- }
- static Atom pick_target_from_list(Display *p_display, const Atom *p_list, int p_count) {
- static const char *target_type = "text/uri-list";
- for (int i = 0; i < p_count; i++) {
- Atom atom = p_list[i];
- if (atom != None && get_atom_name(p_display, atom) == target_type) {
- return atom;
- }
- }
- return None;
- }
- static Atom pick_target_from_atoms(Display *p_disp, Atom p_t1, Atom p_t2, Atom p_t3) {
- static const char *target_type = "text/uri-list";
- if (p_t1 != None && get_atom_name(p_disp, p_t1) == target_type) {
- return p_t1;
- }
- if (p_t2 != None && get_atom_name(p_disp, p_t2) == target_type) {
- return p_t2;
- }
- if (p_t3 != None && get_atom_name(p_disp, p_t3) == target_type) {
- return p_t3;
- }
- return None;
- }
- void DisplayServerX11::_get_key_modifier_state(unsigned int p_x11_state, Ref<InputEventWithModifiers> state) {
- state->set_shift_pressed((p_x11_state & ShiftMask));
- state->set_ctrl_pressed((p_x11_state & ControlMask));
- state->set_alt_pressed((p_x11_state & Mod1Mask ));
- state->set_meta_pressed((p_x11_state & Mod4Mask));
- }
- void DisplayServerX11::_handle_key_event(WindowID p_window, XKeyEvent *p_event, LocalVector<XEvent> &p_events, uint32_t &p_event_index, bool p_echo) {
- WindowData &wd = windows[p_window];
-
- XKeyEvent *xkeyevent = p_event;
- if (wd.ime_in_progress) {
- return;
- }
- if (wd.ime_suppress_next_keyup) {
- wd.ime_suppress_next_keyup = false;
- if (xkeyevent->type != KeyPress) {
- return;
- }
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- KeySym keysym_keycode = 0;
- KeySym keysym_unicode = 0;
-
- char str[256] = {};
- XKeyEvent xkeyevent_no_mod = *xkeyevent;
- xkeyevent_no_mod.state &= ~ShiftMask;
- xkeyevent_no_mod.state &= ~ControlMask;
- XLookupString(xkeyevent, str, 255, &keysym_unicode, nullptr);
- XLookupString(&xkeyevent_no_mod, nullptr, 0, &keysym_keycode, nullptr);
- String keysym;
- #ifdef XKB_ENABLED
- if (xkb_loaded_v08p) {
- KeySym keysym_unicode_nm = 0;
- XLookupString(&xkeyevent_no_mod, nullptr, 0, &keysym_unicode_nm, nullptr);
- keysym = String::chr(xkb_keysym_to_utf32(xkb_keysym_to_upper(keysym_unicode_nm)));
- }
- #endif
-
- if (!xmbstring) {
-
- xmbstring = (char *)memalloc(sizeof(char) * 8);
- xmblen = 8;
- }
- if (xkeyevent->type == KeyPress && wd.xic) {
- Status status;
- #ifdef X_HAVE_UTF8_STRING
- int utf8len = 8;
- char *utf8string = (char *)memalloc(sizeof(char) * utf8len);
- int utf8bytes = Xutf8LookupString(wd.xic, xkeyevent, utf8string,
- utf8len - 1, &keysym_unicode, &status);
- if (status == XBufferOverflow) {
- utf8len = utf8bytes + 1;
- utf8string = (char *)memrealloc(utf8string, utf8len);
- utf8bytes = Xutf8LookupString(wd.xic, xkeyevent, utf8string,
- utf8len - 1, &keysym_unicode, &status);
- }
- utf8string[utf8bytes] = '\0';
- if (status == XLookupChars) {
- bool keypress = xkeyevent->type == KeyPress;
- Key keycode = KeyMappingX11::get_keycode(keysym_keycode);
- Key physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode);
- if (keycode >= Key::A + 32 && keycode <= Key::Z + 32) {
- keycode -= 'a' - 'A';
- }
- String tmp;
- tmp.parse_utf8(utf8string, utf8bytes);
- for (int i = 0; i < tmp.length(); i++) {
- Ref<InputEventKey> k;
- k.instantiate();
- if (physical_keycode == Key::NONE && keycode == Key::NONE && tmp[i] == 0) {
- continue;
- }
- if (keycode == Key::NONE) {
- keycode = (Key)physical_keycode;
- }
- _get_key_modifier_state(xkeyevent->state, k);
- k->set_window_id(p_window);
- k->set_pressed(keypress);
- k->set_keycode(keycode);
- k->set_physical_keycode(physical_keycode);
- if (!keysym.is_empty()) {
- k->set_key_label(fix_key_label(keysym[0], keycode));
- } else {
- k->set_key_label(keycode);
- }
- if (keypress) {
- k->set_unicode(fix_unicode(tmp[i]));
- }
- k->set_echo(false);
- if (k->get_keycode() == Key::BACKTAB) {
-
- k->set_keycode(Key::TAB);
- k->set_physical_keycode(Key::TAB);
- k->set_shift_pressed(true);
- }
- Input::get_singleton()->parse_input_event(k);
- }
- memfree(utf8string);
- return;
- }
- memfree(utf8string);
- #else
- do {
- int mnbytes = XmbLookupString(xic, xkeyevent, xmbstring, xmblen - 1, &keysym_unicode, &status);
- xmbstring[mnbytes] = '\0';
- if (status == XBufferOverflow) {
- xmblen = mnbytes + 1;
- xmbstring = (char *)memrealloc(xmbstring, xmblen);
- }
- } while (status == XBufferOverflow);
- #endif
- #ifdef XKB_ENABLED
- } else if (xkeyevent->type == KeyPress && wd.xkb_state && xkb_loaded_v05p) {
- xkb_compose_feed_result res = xkb_compose_state_feed(wd.xkb_state, keysym_unicode);
- if (res == XKB_COMPOSE_FEED_ACCEPTED) {
- if (xkb_compose_state_get_status(wd.xkb_state) == XKB_COMPOSE_COMPOSED) {
- bool keypress = xkeyevent->type == KeyPress;
- Key keycode = KeyMappingX11::get_keycode(keysym_keycode);
- Key physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode);
- KeyLocation key_location = KeyMappingX11::get_location(xkeyevent->keycode);
- if (keycode >= Key::A + 32 && keycode <= Key::Z + 32) {
- keycode -= 'a' - 'A';
- }
- char str_xkb[256] = {};
- int str_xkb_size = xkb_compose_state_get_utf8(wd.xkb_state, str_xkb, 255);
- String tmp;
- tmp.parse_utf8(str_xkb, str_xkb_size);
- for (int i = 0; i < tmp.length(); i++) {
- Ref<InputEventKey> k;
- k.instantiate();
- if (physical_keycode == Key::NONE && keycode == Key::NONE && tmp[i] == 0) {
- continue;
- }
- if (keycode == Key::NONE) {
- keycode = (Key)physical_keycode;
- }
- _get_key_modifier_state(xkeyevent->state, k);
- k->set_window_id(p_window);
- k->set_pressed(keypress);
- k->set_keycode(keycode);
- k->set_physical_keycode(physical_keycode);
- if (!keysym.is_empty()) {
- k->set_key_label(fix_key_label(keysym[0], keycode));
- } else {
- k->set_key_label(keycode);
- }
- if (keypress) {
- k->set_unicode(fix_unicode(tmp[i]));
- }
- k->set_location(key_location);
- k->set_echo(false);
- if (k->get_keycode() == Key::BACKTAB) {
-
- k->set_keycode(Key::TAB);
- k->set_physical_keycode(Key::TAB);
- k->set_shift_pressed(true);
- }
- Input::get_singleton()->parse_input_event(k);
- }
- return;
- }
- }
- #endif
- }
-
-
-
- Key keycode = KeyMappingX11::get_keycode(keysym_keycode);
- Key physical_keycode = KeyMappingX11::get_scancode(xkeyevent->keycode);
- KeyLocation key_location = KeyMappingX11::get_location(xkeyevent->keycode);
-
-
-
-
- char32_t unicode = keysym_unicode > 0 ? KeyMappingX11::get_unicode_from_keysym(keysym_unicode) : 0;
-
-
-
-
-
-
-
- bool keypress = xkeyevent->type == KeyPress;
- if (physical_keycode == Key::NONE && keycode == Key::NONE && unicode == 0) {
- return;
- }
- if (keycode == Key::NONE) {
- keycode = (Key)physical_keycode;
- }
-
-
-
-
-
- Ref<InputEventKey> k;
- k.instantiate();
- k->set_window_id(p_window);
- _get_key_modifier_state(xkeyevent->state, k);
-
-
-
-
-
- if (xkeyevent->type != KeyPress) {
- p_echo = false;
-
-
- if (p_event_index + 1 < p_events.size()) {
- XEvent &peek_event = p_events[p_event_index + 1];
-
-
-
-
-
- #define ABSDIFF(x, y) (((x) < (y)) ? ((y) - (x)) : ((x) - (y)))
- ::Time threshold = ABSDIFF(peek_event.xkey.time, xkeyevent->time);
- #undef ABSDIFF
- if (peek_event.type == KeyPress && threshold < 5) {
- KeySym rk;
- XLookupString((XKeyEvent *)&peek_event, str, 256, &rk, nullptr);
- if (rk == keysym_keycode) {
-
- ++p_event_index;
- _handle_key_event(p_window, (XKeyEvent *)&peek_event, p_events, p_event_index, true);
- return;
- }
- }
-
- }
-
- }
-
- k->set_pressed(keypress);
- if (keycode >= Key::A + 32 && keycode <= Key::Z + 32) {
- keycode -= int('a' - 'A');
- }
- k->set_keycode(keycode);
- k->set_physical_keycode((Key)physical_keycode);
- if (!keysym.is_empty()) {
- k->set_key_label(fix_key_label(keysym[0], keycode));
- } else {
- k->set_key_label(keycode);
- }
- if (keypress) {
- k->set_unicode(fix_unicode(unicode));
- }
- k->set_location(key_location);
- k->set_echo(p_echo);
- if (k->get_keycode() == Key::BACKTAB) {
-
- k->set_keycode(Key::TAB);
- k->set_physical_keycode(Key::TAB);
- k->set_shift_pressed(true);
- }
-
-
- if (!k->is_pressed()) {
- if (k->get_keycode() == Key::SHIFT) {
- k->set_shift_pressed(false);
- } else if (k->get_keycode() == Key::CTRL) {
- k->set_ctrl_pressed(false);
- } else if (k->get_keycode() == Key::ALT) {
- k->set_alt_pressed(false);
- } else if (k->get_keycode() == Key::META) {
- k->set_meta_pressed(false);
- }
- }
- bool last_is_pressed = Input::get_singleton()->is_key_pressed(k->get_keycode());
- if (k->is_pressed()) {
- if (last_is_pressed) {
- k->set_echo(true);
- }
- }
- Input::get_singleton()->parse_input_event(k);
- }
- Atom DisplayServerX11::_process_selection_request_target(Atom p_target, Window p_requestor, Atom p_property, Atom p_selection) const {
- if (p_target == XInternAtom(x11_display, "TARGETS", 0)) {
-
- Atom data[9];
- data[0] = XInternAtom(x11_display, "TARGETS", 0);
- data[1] = XInternAtom(x11_display, "SAVE_TARGETS", 0);
- data[2] = XInternAtom(x11_display, "MULTIPLE", 0);
- data[3] = XInternAtom(x11_display, "UTF8_STRING", 0);
- data[4] = XInternAtom(x11_display, "COMPOUND_TEXT", 0);
- data[5] = XInternAtom(x11_display, "TEXT", 0);
- data[6] = XA_STRING;
- data[7] = XInternAtom(x11_display, "text/plain;charset=utf-8", 0);
- data[8] = XInternAtom(x11_display, "text/plain", 0);
- XChangeProperty(x11_display,
- p_requestor,
- p_property,
- XA_ATOM,
- 32,
- PropModeReplace,
- (unsigned char *)&data,
- sizeof(data) / sizeof(data[0]));
- return p_property;
- } else if (p_target == XInternAtom(x11_display, "SAVE_TARGETS", 0)) {
-
- XChangeProperty(x11_display,
- p_requestor,
- p_property,
- XInternAtom(x11_display, "NULL", False),
- 32,
- PropModeReplace,
- nullptr,
- 0);
- return p_property;
- } else if (p_target == XInternAtom(x11_display, "UTF8_STRING", 0) ||
- p_target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) ||
- p_target == XInternAtom(x11_display, "TEXT", 0) ||
- p_target == XA_STRING ||
- p_target == XInternAtom(x11_display, "text/plain;charset=utf-8", 0) ||
- p_target == XInternAtom(x11_display, "text/plain", 0)) {
-
-
- CharString clip;
- static const char *target_type = "PRIMARY";
- if (p_selection != None && get_atom_name(x11_display, p_selection) == target_type) {
- clip = internal_clipboard_primary.utf8();
- } else {
- clip = internal_clipboard.utf8();
- }
- XChangeProperty(x11_display,
- p_requestor,
- p_property,
- p_target,
- 8,
- PropModeReplace,
- (unsigned char *)clip.get_data(),
- clip.length());
- return p_property;
- } else {
- char *target_name = XGetAtomName(x11_display, p_target);
- print_verbose(vformat("Target '%s' not supported.", target_name));
- if (target_name) {
- XFree(target_name);
- }
- return None;
- }
- }
- void DisplayServerX11::_handle_selection_request_event(XSelectionRequestEvent *p_event) const {
- XEvent respond;
- if (p_event->target == XInternAtom(x11_display, "MULTIPLE", 0)) {
-
- Atom atom_pair = XInternAtom(x11_display, "ATOM_PAIR", False);
- respond.xselection.property = None;
- Atom type;
- int format;
- unsigned long len;
- unsigned long remaining;
- unsigned char *data = nullptr;
- if (XGetWindowProperty(x11_display, p_event->requestor, p_event->property, 0, LONG_MAX, False, atom_pair, &type, &format, &len, &remaining, &data) == Success) {
- if ((len >= 2) && data) {
- Atom *targets = (Atom *)data;
- for (uint64_t i = 0; i < len; i += 2) {
- Atom target = targets[i];
- Atom &property = targets[i + 1];
- property = _process_selection_request_target(target, p_event->requestor, property, p_event->selection);
- }
- XChangeProperty(x11_display,
- p_event->requestor,
- p_event->property,
- atom_pair,
- 32,
- PropModeReplace,
- (unsigned char *)targets,
- len);
- respond.xselection.property = p_event->property;
- }
- XFree(data);
- }
- } else {
-
- respond.xselection.property = _process_selection_request_target(p_event->target, p_event->requestor, p_event->property, p_event->selection);
- }
- respond.xselection.type = SelectionNotify;
- respond.xselection.display = p_event->display;
- respond.xselection.requestor = p_event->requestor;
- respond.xselection.selection = p_event->selection;
- respond.xselection.target = p_event->target;
- respond.xselection.time = p_event->time;
- XSendEvent(x11_display, p_event->requestor, True, NoEventMask, &respond);
- XFlush(x11_display);
- }
- int DisplayServerX11::_xim_preedit_start_callback(::XIM xim, ::XPointer client_data,
- ::XPointer call_data) {
- DisplayServerX11 *ds = reinterpret_cast<DisplayServerX11 *>(client_data);
- WindowID window_id = ds->_get_focused_window_or_popup();
- WindowData &wd = ds->windows[window_id];
- if (wd.ime_active) {
- wd.ime_in_progress = true;
- }
- return -1;
- }
- void DisplayServerX11::_xim_preedit_done_callback(::XIM xim, ::XPointer client_data,
- ::XPointer call_data) {
- DisplayServerX11 *ds = reinterpret_cast<DisplayServerX11 *>(client_data);
- WindowID window_id = ds->_get_focused_window_or_popup();
- WindowData &wd = ds->windows[window_id];
- if (wd.ime_active) {
- wd.ime_in_progress = false;
- wd.ime_suppress_next_keyup = true;
- }
- }
- void DisplayServerX11::_xim_preedit_draw_callback(::XIM xim, ::XPointer client_data,
- ::XIMPreeditDrawCallbackStruct *call_data) {
- DisplayServerX11 *ds = reinterpret_cast<DisplayServerX11 *>(client_data);
- WindowID window_id = ds->_get_focused_window_or_popup();
- WindowData &wd = ds->windows[window_id];
- XIMText *xim_text = call_data->text;
- if (wd.ime_active) {
- if (xim_text != nullptr) {
- String changed_text;
- if (xim_text->encoding_is_wchar) {
- changed_text = String(xim_text->string.wide_char);
- } else {
- changed_text.parse_utf8(xim_text->string.multi_byte);
- }
- if (call_data->chg_length < 0) {
- ds->im_text = ds->im_text.substr(0, call_data->chg_first) + changed_text;
- } else {
- ds->im_text = ds->im_text.substr(0, call_data->chg_first) + changed_text + ds->im_text.substr(call_data->chg_length);
- }
-
- int start = 0, count = 0;
- for (int i = 0; i < xim_text->length; i++) {
- if (xim_text->feedback[i] & XIMReverse) {
- if (count == 0) {
- start = i;
- count = 1;
- } else {
- count++;
- }
- }
- }
- if (count > 0) {
- ds->im_selection = Point2i(start + call_data->chg_first, count);
- } else {
- ds->im_selection = Point2i(call_data->caret, 0);
- }
- } else {
- ds->im_text = String();
- ds->im_selection = Point2i();
- }
- callable_mp((Object *)OS_Unix::get_singleton()->get_main_loop(), &Object::notification).call_deferred(MainLoop::NOTIFICATION_OS_IME_UPDATE, false);
- }
- }
- void DisplayServerX11::_xim_preedit_caret_callback(::XIM xim, ::XPointer client_data,
- ::XIMPreeditCaretCallbackStruct *call_data) {
- }
- void DisplayServerX11::_xim_destroy_callback(::XIM im, ::XPointer client_data,
- ::XPointer call_data) {
- WARN_PRINT("Input method stopped");
- DisplayServerX11 *ds = reinterpret_cast<DisplayServerX11 *>(client_data);
- ds->xim = nullptr;
- for (KeyValue<WindowID, WindowData> &E : ds->windows) {
- E.value.xic = nullptr;
- }
- }
- void DisplayServerX11::_window_changed(XEvent *event) {
- WindowID window_id = MAIN_WINDOW_ID;
-
- for (const KeyValue<WindowID, WindowData> &E : windows) {
- if (event->xany.window == E.value.x11_window) {
- window_id = E.key;
- break;
- }
- }
- Rect2i new_rect;
- WindowData &wd = windows[window_id];
- if (wd.x11_window != event->xany.window) {
- return;
- }
-
- wd.fullscreen = _window_fullscreen_check(window_id);
- wd.maximized = _window_maximize_check(window_id, "_NET_WM_STATE") && !wd.fullscreen;
- wd.minimized = _window_minimize_check(window_id) && !wd.fullscreen && !wd.maximized;
-
- Window root, parent, *children;
- unsigned int nchildren;
- if (XQueryTree(x11_display, wd.x11_window, &root, &parent, &children, &nchildren) && wd.parent != parent) {
- wd.parent = parent;
- window_set_position(wd.position, window_id);
- }
- XFree(children);
- {
-
- int x = 0, y = 0;
- Window child;
- XTranslateCoordinates(x11_display, wd.x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child);
- new_rect.position.x = x;
- new_rect.position.y = y;
- new_rect.size.width = event->xconfigure.width;
- new_rect.size.height = event->xconfigure.height;
- }
- if (new_rect == Rect2i(wd.position, wd.size)) {
- return;
- }
- wd.position = new_rect.position;
- wd.size = new_rect.size;
- #if defined(RD_ENABLED)
- if (rendering_context) {
- rendering_context->window_set_size(window_id, wd.size.width, wd.size.height);
- }
- #endif
- #if defined(GLES3_ENABLED)
- if (gl_manager) {
- gl_manager->window_resize(window_id, wd.size.width, wd.size.height);
- }
- if (gl_manager_egl) {
- gl_manager_egl->window_resize(window_id, wd.size.width, wd.size.height);
- }
- #endif
- if (wd.rect_changed_callback.is_valid()) {
- wd.rect_changed_callback.call(new_rect);
- }
- }
- DisplayServer::WindowID DisplayServerX11::_get_focused_window_or_popup() const {
- const List<WindowID>::Element *E = popup_list.back();
- if (E) {
- return E->get();
- }
- return last_focused_window;
- }
- void DisplayServerX11::_dispatch_input_events(const Ref<InputEvent> &p_event) {
- static_cast<DisplayServerX11 *>(get_singleton())->_dispatch_input_event(p_event);
- }
- void DisplayServerX11::_dispatch_input_event(const Ref<InputEvent> &p_event) {
- {
- List<WindowID>::Element *E = popup_list.back();
- if (E && Object::cast_to<InputEventKey>(*p_event)) {
-
- if (windows.has(E->get())) {
- Callable callable = windows[E->get()].input_event_callback;
- if (callable.is_valid()) {
- callable.call(p_event);
- }
- }
- return;
- }
- }
- Ref<InputEventFromWindow> event_from_window = p_event;
- if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) {
-
- if (windows.has(event_from_window->get_window_id())) {
- Callable callable = windows[event_from_window->get_window_id()].input_event_callback;
- if (callable.is_valid()) {
- callable.call(p_event);
- }
- }
- } else {
-
- for (KeyValue<WindowID, WindowData> &E : windows) {
- Callable callable = E.value.input_event_callback;
- if (callable.is_valid()) {
- callable.call(p_event);
- }
- }
- }
- }
- void DisplayServerX11::_send_window_event(const WindowData &wd, WindowEvent p_event) {
- if (wd.event_callback.is_valid()) {
- Variant event = int(p_event);
- wd.event_callback.call(event);
- }
- }
- void DisplayServerX11::_set_input_focus(Window p_window, int p_revert_to) {
- Window focused_window;
- int focus_ret_state;
- XGetInputFocus(x11_display, &focused_window, &focus_ret_state);
-
-
- if (p_window != focused_window) {
- XSetInputFocus(x11_display, p_window, p_revert_to, CurrentTime);
- }
- }
- void DisplayServerX11::_poll_events_thread(void *ud) {
- DisplayServerX11 *display_server = static_cast<DisplayServerX11 *>(ud);
- display_server->_poll_events();
- }
- Bool DisplayServerX11::_predicate_all_events(Display *display, XEvent *event, XPointer arg) {
-
- return True;
- }
- bool DisplayServerX11::_wait_for_events() const {
- int x11_fd = ConnectionNumber(x11_display);
- fd_set in_fds;
- XFlush(x11_display);
- FD_ZERO(&in_fds);
- FD_SET(x11_fd, &in_fds);
- struct timeval tv;
- tv.tv_usec = 0;
- tv.tv_sec = 1;
-
- int num_ready_fds = select(x11_fd + 1, &in_fds, nullptr, nullptr, &tv);
- if (num_ready_fds > 0) {
-
- return true;
- } else {
-
- if (num_ready_fds < 0) {
- ERR_PRINT("_wait_for_events: select error: " + itos(errno));
- }
- return false;
- }
- }
- void DisplayServerX11::_poll_events() {
- while (!events_thread_done.is_set()) {
- _wait_for_events();
-
- {
- MutexLock mutex_lock(events_mutex);
- _check_pending_events(polled_events);
- }
- }
- }
- void DisplayServerX11::_check_pending_events(LocalVector<XEvent> &r_events) {
-
- XFlush(x11_display);
-
- XEvent ev = {};
- while (XCheckIfEvent(x11_display, &ev, _predicate_all_events, nullptr)) {
-
- if (XFilterEvent(&ev, None)) {
-
-
- continue;
- }
-
-
-
- if (ev.type == SelectionRequest) {
- _handle_selection_request_event(&(ev.xselectionrequest));
- continue;
- }
- r_events.push_back(ev);
- }
- }
- DisplayServer::WindowID DisplayServerX11::window_get_active_popup() const {
- const List<WindowID>::Element *E = popup_list.back();
- if (E) {
- return E->get();
- } else {
- return INVALID_WINDOW_ID;
- }
- }
- void DisplayServerX11::window_set_popup_safe_rect(WindowID p_window, const Rect2i &p_rect) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
- wd.parent_safe_rect = p_rect;
- }
- Rect2i DisplayServerX11::window_get_popup_safe_rect(WindowID p_window) const {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND_V(!windows.has(p_window), Rect2i());
- const WindowData &wd = windows[p_window];
- return wd.parent_safe_rect;
- }
- void DisplayServerX11::popup_open(WindowID p_window) {
- _THREAD_SAFE_METHOD_
- bool has_popup_ancestor = false;
- WindowID transient_root = p_window;
- while (true) {
- WindowID parent = windows[transient_root].transient_parent;
- if (parent == INVALID_WINDOW_ID) {
- break;
- } else {
- transient_root = parent;
- if (windows[parent].is_popup) {
- has_popup_ancestor = true;
- break;
- }
- }
- }
-
- bool ignores_input = window_get_flag(WINDOW_FLAG_NO_FOCUS, p_window) && window_get_flag(WINDOW_FLAG_MOUSE_PASSTHROUGH, p_window);
- WindowData &wd = windows[p_window];
- if (wd.is_popup || (has_popup_ancestor && !ignores_input)) {
-
- List<WindowID>::Element *C = nullptr;
- List<WindowID>::Element *E = popup_list.back();
- while (E) {
- if (wd.transient_parent != E->get() || wd.transient_parent == INVALID_WINDOW_ID) {
- C = E;
- E = E->prev();
- } else {
- break;
- }
- }
- if (C) {
- _send_window_event(windows[C->get()], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST);
- }
- time_since_popup = OS::get_singleton()->get_ticks_msec();
- popup_list.push_back(p_window);
- }
- }
- void DisplayServerX11::popup_close(WindowID p_window) {
- _THREAD_SAFE_METHOD_
- List<WindowID>::Element *E = popup_list.find(p_window);
- while (E) {
- List<WindowID>::Element *F = E->next();
- WindowID win_id = E->get();
- popup_list.erase(E);
- if (win_id != p_window) {
-
- _send_window_event(windows[win_id], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST);
- }
- E = F;
- }
- }
- bool DisplayServerX11::mouse_process_popups() {
- _THREAD_SAFE_METHOD_
- if (popup_list.is_empty()) {
- return false;
- }
- uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_popup;
- if (delta < 250) {
- return false;
- }
- int number_of_screens = XScreenCount(x11_display);
- bool closed = false;
- for (int i = 0; i < number_of_screens; i++) {
- Window root, child;
- int root_x, root_y, win_x, win_y;
- unsigned int mask;
- if (XQueryPointer(x11_display, XRootWindow(x11_display, i), &root, &child, &root_x, &root_y, &win_x, &win_y, &mask)) {
- XWindowAttributes root_attrs;
- XGetWindowAttributes(x11_display, root, &root_attrs);
- Vector2i pos = Vector2i(root_attrs.x + root_x, root_attrs.y + root_y);
- if (mask != last_mouse_monitor_mask) {
- if (((mask & Button1Mask) || (mask & Button2Mask) || (mask & Button3Mask) || (mask & Button4Mask) || (mask & Button5Mask))) {
- List<WindowID>::Element *C = nullptr;
- List<WindowID>::Element *E = popup_list.back();
-
- while (E) {
-
- Rect2i win_rect = Rect2i(window_get_position_with_decorations(E->get()), window_get_size_with_decorations(E->get()));
-
- Rect2i safe_rect = window_get_popup_safe_rect(E->get());
- if (win_rect.has_point(pos)) {
- break;
- } else if (safe_rect != Rect2i() && safe_rect.has_point(pos)) {
- break;
- } else {
- C = E;
- E = E->prev();
- }
- }
- if (C) {
- _send_window_event(windows[C->get()], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST);
- closed = true;
- }
- }
- }
- last_mouse_monitor_mask = mask;
- }
- }
- return closed;
- }
- bool DisplayServerX11::_window_focus_check() {
- Window focused_window;
- int focus_ret_state;
- XGetInputFocus(x11_display, &focused_window, &focus_ret_state);
- bool has_focus = false;
- for (const KeyValue<int, DisplayServerX11::WindowData> &wid : windows) {
- if (wid.value.x11_window == focused_window || (wid.value.xic && wid.value.ime_active && wid.value.x11_xim_window == focused_window)) {
- has_focus = true;
- break;
- }
- }
- return has_focus;
- }
- void DisplayServerX11::process_events() {
- ERR_FAIL_COND(!Thread::is_main_thread());
- _THREAD_SAFE_LOCK_
- #ifdef DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED
- static int frame = 0;
- ++frame;
- #endif
- bool ignore_events = mouse_process_popups();
- if (app_focused) {
-
- bool focus_found = false;
- for (const KeyValue<WindowID, WindowData> &E : windows) {
- if (E.value.focused) {
- focus_found = true;
- break;
- }
- }
- if (!focus_found) {
- uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_no_focus;
- if (delta > 250) {
-
- if (OS::get_singleton()->get_main_loop()) {
- DEBUG_LOG_X11("All focus lost, triggering NOTIFICATION_APPLICATION_FOCUS_OUT\n");
- OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT);
- }
- app_focused = false;
- }
- } else {
- time_since_no_focus = OS::get_singleton()->get_ticks_msec();
- }
- }
- do_mouse_warp = false;
-
- bool mouse_mode_grab = mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN;
- xi.pressure = 0;
- xi.tilt = Vector2();
- xi.pressure_supported = false;
- LocalVector<XEvent> events;
- {
-
- MutexLock mutex_lock(events_mutex);
- events = polled_events;
- polled_events.clear();
-
- _check_pending_events(events);
- }
- for (uint32_t event_index = 0; event_index < events.size(); ++event_index) {
- XEvent &event = events[event_index];
- bool ime_window_event = false;
- WindowID window_id = MAIN_WINDOW_ID;
-
- for (const KeyValue<WindowID, WindowData> &E : windows) {
- if (event.xany.window == E.value.x11_window) {
- window_id = E.key;
- break;
- }
- if (event.xany.window == E.value.x11_xim_window) {
- window_id = E.key;
- ime_window_event = true;
- break;
- }
- }
- if (XGetEventData(x11_display, &event.xcookie)) {
- if (event.xcookie.type == GenericEvent && event.xcookie.extension == xi.opcode) {
- XIDeviceEvent *event_data = (XIDeviceEvent *)event.xcookie.data;
- switch (event_data->evtype) {
- case XI_HierarchyChanged:
- case XI_DeviceChanged: {
- _refresh_device_info();
- } break;
- case XI_RawMotion: {
- if (ime_window_event || ignore_events) {
- break;
- }
- XIRawEvent *raw_event = (XIRawEvent *)event_data;
- int device_id = raw_event->sourceid;
-
-
-
- if (raw_event->valuators.mask_len <= 0) {
- break;
- }
- const double *values = raw_event->raw_values;
- double rel_x = 0.0;
- double rel_y = 0.0;
- if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSX)) {
- rel_x = *values;
- values++;
- }
- if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_ABSY)) {
- rel_y = *values;
- values++;
- }
- if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_PRESSURE)) {
- HashMap<int, Vector2>::Iterator pen_pressure = xi.pen_pressure_range.find(device_id);
- if (pen_pressure) {
- Vector2 pen_pressure_range = pen_pressure->value;
- if (pen_pressure_range != Vector2()) {
- xi.pressure_supported = true;
- xi.pressure = (*values - pen_pressure_range[0]) /
- (pen_pressure_range[1] - pen_pressure_range[0]);
- }
- }
- values++;
- }
- if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTX)) {
- HashMap<int, Vector2>::Iterator pen_tilt_x = xi.pen_tilt_x_range.find(device_id);
- if (pen_tilt_x) {
- Vector2 pen_tilt_x_range = pen_tilt_x->value;
- if (pen_tilt_x_range[0] != 0 && *values < 0) {
- xi.tilt.x = *values / -pen_tilt_x_range[0];
- } else if (pen_tilt_x_range[1] != 0) {
- xi.tilt.x = *values / pen_tilt_x_range[1];
- }
- }
- values++;
- }
- if (XIMaskIsSet(raw_event->valuators.mask, VALUATOR_TILTY)) {
- HashMap<int, Vector2>::Iterator pen_tilt_y = xi.pen_tilt_y_range.find(device_id);
- if (pen_tilt_y) {
- Vector2 pen_tilt_y_range = pen_tilt_y->value;
- if (pen_tilt_y_range[0] != 0 && *values < 0) {
- xi.tilt.y = *values / -pen_tilt_y_range[0];
- } else if (pen_tilt_y_range[1] != 0) {
- xi.tilt.y = *values / pen_tilt_y_range[1];
- }
- }
- values++;
- }
- HashMap<int, bool>::Iterator pen_inverted = xi.pen_inverted_devices.find(device_id);
- if (pen_inverted) {
- xi.pen_inverted = pen_inverted->value;
- }
-
-
- if (raw_event->time == xi.last_relative_time && rel_x == xi.relative_motion.x && rel_y == xi.relative_motion.y) {
- break;
- }
- xi.old_raw_pos.x = xi.raw_pos.x;
- xi.old_raw_pos.y = xi.raw_pos.y;
- xi.raw_pos.x = rel_x;
- xi.raw_pos.y = rel_y;
- HashMap<int, Vector2>::Iterator abs_info = xi.absolute_devices.find(device_id);
- if (abs_info) {
-
- Vector2 mult = abs_info->value;
- xi.relative_motion.x += (xi.raw_pos.x - xi.old_raw_pos.x) * mult.x;
- xi.relative_motion.y += (xi.raw_pos.y - xi.old_raw_pos.y) * mult.y;
- } else {
-
- xi.relative_motion.x = xi.raw_pos.x;
- xi.relative_motion.y = xi.raw_pos.y;
- }
- xi.last_relative_time = raw_event->time;
- } break;
- #ifdef TOUCH_ENABLED
- case XI_TouchBegin:
- case XI_TouchEnd: {
- if (ime_window_event || ignore_events) {
- break;
- }
- bool is_begin = event_data->evtype == XI_TouchBegin;
- int index = event_data->detail;
- Vector2 pos = Vector2(event_data->event_x, event_data->event_y);
- Ref<InputEventScreenTouch> st;
- st.instantiate();
- st->set_window_id(window_id);
- st->set_index(index);
- st->set_position(pos);
- st->set_pressed(is_begin);
- if (is_begin) {
- if (xi.state.has(index)) {
- break;
- }
- xi.state[index] = pos;
- if (xi.state.size() == 1) {
-
-
- xi.mouse_pos_to_filter = pos;
- }
- Input::get_singleton()->parse_input_event(st);
- } else {
- if (!xi.state.has(index)) {
- break;
- }
- xi.state.erase(index);
- Input::get_singleton()->parse_input_event(st);
- }
- } break;
- case XI_TouchUpdate: {
- if (ime_window_event || ignore_events) {
- break;
- }
- int index = event_data->detail;
- Vector2 pos = Vector2(event_data->event_x, event_data->event_y);
- HashMap<int, Vector2>::Iterator curr_pos_elem = xi.state.find(index);
- if (!curr_pos_elem) {
- break;
- }
- if (curr_pos_elem->value != pos) {
- Ref<InputEventScreenDrag> sd;
- sd.instantiate();
- sd->set_window_id(window_id);
- sd->set_index(index);
- sd->set_position(pos);
- sd->set_relative(pos - curr_pos_elem->value);
- sd->set_relative_screen_position(sd->get_relative());
- Input::get_singleton()->parse_input_event(sd);
- curr_pos_elem->value = pos;
- }
- } break;
- #endif
- }
- }
- }
- XFreeEventData(x11_display, &event.xcookie);
- switch (event.type) {
- case MapNotify: {
- DEBUG_LOG_X11("[%u] MapNotify window=%lu (%u) \n", frame, event.xmap.window, window_id);
- if (ime_window_event) {
- break;
- }
- const WindowData &wd = windows[window_id];
- XWindowAttributes xwa;
- XSync(x11_display, False);
- XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
-
-
-
- if ((xwa.map_state == IsViewable) && !wd.no_focus && !wd.is_popup && _window_focus_check()) {
- _set_input_focus(wd.x11_window, RevertToPointerRoot);
- }
-
- _validate_mode_on_map(window_id);
- } break;
- case Expose: {
- DEBUG_LOG_X11("[%u] Expose window=%lu (%u), count='%u' \n", frame, event.xexpose.window, window_id, event.xexpose.count);
- if (ime_window_event) {
- break;
- }
- windows[window_id].fullscreen = _window_fullscreen_check(window_id);
- Main::force_redraw();
- } break;
- case NoExpose: {
- DEBUG_LOG_X11("[%u] NoExpose drawable=%lu (%u) \n", frame, event.xnoexpose.drawable, window_id);
- if (ime_window_event) {
- break;
- }
- windows[window_id].minimized = true;
- } break;
- case VisibilityNotify: {
- DEBUG_LOG_X11("[%u] VisibilityNotify window=%lu (%u), state=%u \n", frame, event.xvisibility.window, window_id, event.xvisibility.state);
- if (ime_window_event) {
- break;
- }
- windows[window_id].minimized = _window_minimize_check(window_id);
- } break;
- case LeaveNotify: {
- DEBUG_LOG_X11("[%u] LeaveNotify window=%lu (%u), mode='%u' \n", frame, event.xcrossing.window, window_id, event.xcrossing.mode);
- if (ime_window_event) {
- break;
- }
- if (!mouse_mode_grab && window_mouseover_id == window_id) {
- window_mouseover_id = INVALID_WINDOW_ID;
- _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_EXIT);
- }
- } break;
- case EnterNotify: {
- DEBUG_LOG_X11("[%u] EnterNotify window=%lu (%u), mode='%u' \n", frame, event.xcrossing.window, window_id, event.xcrossing.mode);
- if (ime_window_event) {
- break;
- }
- if (!mouse_mode_grab && window_mouseover_id != window_id) {
- if (window_mouseover_id != INVALID_WINDOW_ID) {
- _send_window_event(windows[window_mouseover_id], WINDOW_EVENT_MOUSE_EXIT);
- }
- window_mouseover_id = window_id;
- _send_window_event(windows[window_id], WINDOW_EVENT_MOUSE_ENTER);
- }
- } break;
- case FocusIn: {
- DEBUG_LOG_X11("[%u] FocusIn window=%lu (%u), mode='%u' \n", frame, event.xfocus.window, window_id, event.xfocus.mode);
- if (ime_window_event || (event.xfocus.detail == NotifyInferior)) {
- break;
- }
- WindowData &wd = windows[window_id];
- last_focused_window = window_id;
- wd.focused = true;
-
- static unsigned int focus_order = 0;
- wd.focus_order = ++focus_order;
- _send_window_event(wd, WINDOW_EVENT_FOCUS_IN);
- if (mouse_mode_grab) {
-
- for (const KeyValue<WindowID, WindowData> &E : windows) {
- if (mouse_mode == MOUSE_MODE_CONFINED) {
- XUndefineCursor(x11_display, E.value.x11_window);
- } else if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
- XDefineCursor(x11_display, E.value.x11_window, null_cursor);
- }
- XGrabPointer(
- x11_display, E.value.x11_window, True,
- ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
- GrabModeAsync, GrabModeAsync, E.value.x11_window, None, CurrentTime);
- }
- }
- #ifdef TOUCH_ENABLED
-
-
- #endif
- if (!app_focused) {
- if (OS::get_singleton()->get_main_loop()) {
- OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN);
- }
- app_focused = true;
- }
- } break;
- case FocusOut: {
- DEBUG_LOG_X11("[%u] FocusOut window=%lu (%u), mode='%u' \n", frame, event.xfocus.window, window_id, event.xfocus.mode);
- WindowData &wd = windows[window_id];
- if (ime_window_event || (event.xfocus.detail == NotifyInferior)) {
- break;
- }
- if (wd.ime_active) {
- MutexLock mutex_lock(events_mutex);
- XUnsetICFocus(wd.xic);
- XUnmapWindow(x11_display, wd.x11_xim_window);
- wd.ime_active = false;
- im_text = String();
- im_selection = Vector2i();
- OS_Unix::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_IME_UPDATE);
- }
- wd.focused = false;
- Input::get_singleton()->release_pressed_events();
- _send_window_event(wd, WINDOW_EVENT_FOCUS_OUT);
- if (mouse_mode_grab) {
- for (const KeyValue<WindowID, WindowData> &E : windows) {
-
- if (mouse_mode == MOUSE_MODE_CAPTURED) {
-
- XUndefineCursor(x11_display, E.value.x11_window);
- }
- }
- XUngrabPointer(x11_display, CurrentTime);
- }
- #ifdef TOUCH_ENABLED
-
-
-
- for (const KeyValue<int, Vector2> &E : xi.state) {
- Ref<InputEventScreenTouch> st;
- st.instantiate();
- st->set_index(E.key);
- st->set_window_id(window_id);
- st->set_position(E.value);
- Input::get_singleton()->parse_input_event(st);
- }
- xi.state.clear();
- #endif
- } break;
- case ConfigureNotify: {
- DEBUG_LOG_X11("[%u] ConfigureNotify window=%lu (%u), event=%lu, above=%lu, override_redirect=%u \n", frame, event.xconfigure.window, window_id, event.xconfigure.event, event.xconfigure.above, event.xconfigure.override_redirect);
- if (event.xconfigure.window == windows[window_id].x11_xim_window) {
- break;
- }
- _window_changed(&event);
- } break;
- case ButtonPress:
- case ButtonRelease: {
- if (ime_window_event || ignore_events) {
- break;
- }
-
- last_timestamp = event.xbutton.time;
- if (mouse_mode == MOUSE_MODE_CAPTURED) {
- event.xbutton.x = last_mouse_pos.x;
- event.xbutton.y = last_mouse_pos.y;
- }
- Ref<InputEventMouseButton> mb;
- mb.instantiate();
- mb->set_window_id(window_id);
- _get_key_modifier_state(event.xbutton.state, mb);
- mb->set_button_index((MouseButton)event.xbutton.button);
- if (mb->get_button_index() == MouseButton::RIGHT) {
- mb->set_button_index(MouseButton::MIDDLE);
- } else if (mb->get_button_index() == MouseButton::MIDDLE) {
- mb->set_button_index(MouseButton::RIGHT);
- }
- mb->set_position(Vector2(event.xbutton.x, event.xbutton.y));
- mb->set_global_position(mb->get_position());
- mb->set_pressed((event.type == ButtonPress));
- if (mb->is_pressed() && mb->get_button_index() >= MouseButton::WHEEL_UP && mb->get_button_index() <= MouseButton::WHEEL_RIGHT) {
- MouseButtonMask mask = mouse_button_to_mask(mb->get_button_index());
- BitField<MouseButtonMask> scroll_mask = mouse_get_button_state();
- scroll_mask.set_flag(mask);
- mb->set_button_mask(scroll_mask);
- } else {
- mb->set_button_mask(mouse_get_button_state());
- }
- const WindowData &wd = windows[window_id];
- if (event.type == ButtonPress) {
- DEBUG_LOG_X11("[%u] ButtonPress window=%lu (%u), button_index=%u \n", frame, event.xbutton.window, window_id, mb->get_button_index());
-
-
-
- if (!wd.no_focus && !wd.is_popup) {
- _set_input_focus(wd.x11_window, RevertToPointerRoot);
- }
- uint64_t diff = OS::get_singleton()->get_ticks_usec() / 1000 - last_click_ms;
- if (mb->get_button_index() == last_click_button_index) {
- if (diff < 400 && Vector2(last_click_pos).distance_to(Vector2(event.xbutton.x, event.xbutton.y)) < 5) {
- last_click_ms = 0;
- last_click_pos = Point2i(-100, -100);
- last_click_button_index = MouseButton::NONE;
- mb->set_double_click(true);
- }
- } else if (mb->get_button_index() < MouseButton::WHEEL_UP || mb->get_button_index() > MouseButton::WHEEL_RIGHT) {
- last_click_button_index = mb->get_button_index();
- }
- if (!mb->is_double_click()) {
- last_click_ms += diff;
- last_click_pos = Point2i(event.xbutton.x, event.xbutton.y);
- }
- } else {
- DEBUG_LOG_X11("[%u] ButtonRelease window=%lu (%u), button_index=%u \n", frame, event.xbutton.window, window_id, mb->get_button_index());
- WindowID window_id_other = INVALID_WINDOW_ID;
- Window wd_other_x11_window;
- if (wd.focused) {
-
- WindowID popup_id = _get_focused_window_or_popup();
- if (popup_id != INVALID_WINDOW_ID && popup_id != window_id) {
- window_id_other = popup_id;
- wd_other_x11_window = windows[popup_id].x11_window;
- }
- } else {
-
-
-
-
-
- for (const KeyValue<WindowID, WindowData> &E : windows) {
- if (E.value.focused) {
- if (E.key != window_id) {
- window_id_other = E.key;
- wd_other_x11_window = E.value.x11_window;
- }
- break;
- }
- }
- }
- if (window_id_other != INVALID_WINDOW_ID) {
- int x, y;
- Window child;
- XTranslateCoordinates(x11_display, wd.x11_window, wd_other_x11_window, event.xbutton.x, event.xbutton.y, &x, &y, &child);
- mb->set_window_id(window_id_other);
- mb->set_position(Vector2(x, y));
- mb->set_global_position(mb->get_position());
- }
- }
- Input::get_singleton()->parse_input_event(mb);
- } break;
- case MotionNotify: {
- if (ime_window_event || ignore_events) {
- break;
- }
-
-
-
- WindowID focused_window_id = _get_focused_window_or_popup();
- if (!windows.has(focused_window_id)) {
- focused_window_id = MAIN_WINDOW_ID;
- }
- while (true) {
- if (mouse_mode == MOUSE_MODE_CAPTURED && event.xmotion.x == windows[focused_window_id].size.width / 2 && event.xmotion.y == windows[focused_window_id].size.height / 2) {
-
- center = Vector2(event.xmotion.x, event.xmotion.y);
- break;
- }
- if (event_index + 1 < events.size()) {
- const XEvent &next_event = events[event_index + 1];
- if (next_event.type == MotionNotify) {
- ++event_index;
- event = next_event;
- } else {
- break;
- }
- } else {
- break;
- }
- }
- last_timestamp = event.xmotion.time;
-
-
-
- Point2i pos(event.xmotion.x, event.xmotion.y);
-
- bool filter = false;
-
- if (xi.state.size() && Vector2(pos).distance_squared_to(xi.mouse_pos_to_filter) < 2) {
- filter = true;
- }
-
- xi.mouse_pos_to_filter = Vector2(1e10, 1e10);
- if (filter) {
- break;
- }
- const WindowData &wd = windows[window_id];
- bool focused = wd.focused;
- if (mouse_mode == MOUSE_MODE_CAPTURED) {
- if (xi.relative_motion.x == 0 && xi.relative_motion.y == 0) {
- break;
- }
- Point2i new_center = pos;
- pos = last_mouse_pos + xi.relative_motion;
- center = new_center;
- do_mouse_warp = focused;
- }
- if (!last_mouse_pos_valid) {
- last_mouse_pos = pos;
- last_mouse_pos_valid = true;
- }
-
-
-
-
-
-
- Point2i rel;
-
- if (mouse_mode == MOUSE_MODE_CAPTURED) {
- rel = xi.relative_motion;
- } else {
- rel = pos - last_mouse_pos;
- }
-
- xi.relative_motion.x = 0;
- xi.relative_motion.y = 0;
- if (mouse_mode == MOUSE_MODE_CAPTURED) {
- pos = Point2i(windows[focused_window_id].size.width / 2, windows[focused_window_id].size.height / 2);
- }
- BitField<MouseButtonMask> last_button_state = 0;
- if (event.xmotion.state & Button1Mask) {
- last_button_state.set_flag(MouseButtonMask::LEFT);
- }
- if (event.xmotion.state & Button2Mask) {
- last_button_state.set_flag(MouseButtonMask::MIDDLE);
- }
- if (event.xmotion.state & Button3Mask) {
- last_button_state.set_flag(MouseButtonMask::RIGHT);
- }
- if (event.xmotion.state & Button4Mask) {
- last_button_state.set_flag(MouseButtonMask::MB_XBUTTON1);
- }
- if (event.xmotion.state & Button5Mask) {
- last_button_state.set_flag(MouseButtonMask::MB_XBUTTON2);
- }
- Ref<InputEventMouseMotion> mm;
- mm.instantiate();
- mm->set_window_id(window_id);
- if (xi.pressure_supported) {
- mm->set_pressure(xi.pressure);
- } else {
- mm->set_pressure(bool(last_button_state.has_flag(MouseButtonMask::LEFT)) ? 1.0f : 0.0f);
- }
- mm->set_tilt(xi.tilt);
- mm->set_pen_inverted(xi.pen_inverted);
- _get_key_modifier_state(event.xmotion.state, mm);
- mm->set_button_mask(last_button_state);
- mm->set_position(pos);
- mm->set_global_position(pos);
- mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
- mm->set_screen_velocity(mm->get_velocity());
- mm->set_relative(rel);
- mm->set_relative_screen_position(rel);
- last_mouse_pos = pos;
-
-
-
-
- if (focused) {
- Input::get_singleton()->parse_input_event(mm);
- } else {
-
-
-
-
-
- for (const KeyValue<WindowID, WindowData> &E : windows) {
- const WindowData &wd_other = E.value;
- if (wd_other.focused) {
- int x, y;
- Window child;
- XTranslateCoordinates(x11_display, wd.x11_window, wd_other.x11_window, event.xmotion.x, event.xmotion.y, &x, &y, &child);
- Point2i pos_focused(x, y);
- mm->set_window_id(E.key);
- mm->set_position(pos_focused);
- mm->set_global_position(pos_focused);
- mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
- Input::get_singleton()->parse_input_event(mm);
- break;
- }
- }
- }
- } break;
- case KeyPress:
- case KeyRelease: {
- if (ignore_events) {
- break;
- }
- #ifdef DISPLAY_SERVER_X11_DEBUG_LOGS_ENABLED
- if (event.type == KeyPress) {
- DEBUG_LOG_X11("[%u] KeyPress window=%lu (%u), keycode=%u, time=%lu \n", frame, event.xkey.window, window_id, event.xkey.keycode, event.xkey.time);
- } else {
- DEBUG_LOG_X11("[%u] KeyRelease window=%lu (%u), keycode=%u, time=%lu \n", frame, event.xkey.window, window_id, event.xkey.keycode, event.xkey.time);
- }
- #endif
- last_timestamp = event.xkey.time;
-
-
- _handle_key_event(window_id, &event.xkey, events, event_index);
- } break;
- case SelectionNotify:
- if (ime_window_event) {
- break;
- }
- if (event.xselection.target == requested) {
- Property p = _read_property(x11_display, windows[window_id].x11_window, XInternAtom(x11_display, "PRIMARY", 0));
- Vector<String> files = String((char *)p.data).split("\r\n", false);
- XFree(p.data);
- for (int i = 0; i < files.size(); i++) {
- files.write[i] = files[i].replace("file://", "").uri_decode();
- }
- if (windows[window_id].drop_files_callback.is_valid()) {
- Variant v_files = files;
- const Variant *v_args[1] = { &v_files };
- Variant ret;
- Callable::CallError ce;
- windows[window_id].drop_files_callback.callp((const Variant **)&v_args, 1, ret, ce);
- if (ce.error != Callable::CallError::CALL_OK) {
- ERR_PRINT(vformat("Failed to execute drop files callback: %s.", Variant::get_callable_error_text(windows[window_id].drop_files_callback, v_args, 1, ce)));
- }
- }
-
- XClientMessageEvent m;
- memset(&m, 0, sizeof(m));
- m.type = ClientMessage;
- m.display = x11_display;
- m.window = xdnd_source_window;
- m.message_type = xdnd_finished;
- m.format = 32;
- m.data.l[0] = windows[window_id].x11_window;
- m.data.l[1] = 1;
- m.data.l[2] = xdnd_action_copy;
- XSendEvent(x11_display, xdnd_source_window, False, NoEventMask, (XEvent *)&m);
- }
- break;
- case ClientMessage:
- if (ime_window_event) {
- break;
- }
- if ((unsigned int)event.xclient.data.l[0] == (unsigned int)wm_delete) {
- _send_window_event(windows[window_id], WINDOW_EVENT_CLOSE_REQUEST);
- }
- else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_enter) {
-
- xdnd_version = (event.xclient.data.l[1] >> 24);
- Window source = event.xclient.data.l[0];
- bool more_than_3 = event.xclient.data.l[1] & 1;
- if (more_than_3) {
- Property p = _read_property(x11_display, source, XInternAtom(x11_display, "XdndTypeList", False));
- requested = pick_target_from_list(x11_display, (Atom *)p.data, p.nitems);
- XFree(p.data);
- } else {
- requested = pick_target_from_atoms(x11_display, event.xclient.data.l[2], event.xclient.data.l[3], event.xclient.data.l[4]);
- }
- } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_position) {
-
-
- XClientMessageEvent m;
- memset(&m, 0, sizeof(m));
- m.type = ClientMessage;
- m.display = event.xclient.display;
- m.window = event.xclient.data.l[0];
- m.message_type = xdnd_status;
- m.format = 32;
- m.data.l[0] = windows[window_id].x11_window;
- m.data.l[1] = (requested != None);
- m.data.l[2] = 0;
- m.data.l[3] = 0;
- m.data.l[4] = xdnd_action_copy;
- XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m);
- XFlush(x11_display);
- } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_drop) {
- if (requested != None) {
- xdnd_source_window = event.xclient.data.l[0];
- if (xdnd_version >= 1) {
- XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), windows[window_id].x11_window, event.xclient.data.l[2]);
- } else {
- XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), windows[window_id].x11_window, CurrentTime);
- }
- } else {
-
- XClientMessageEvent m;
- memset(&m, 0, sizeof(m));
- m.type = ClientMessage;
- m.display = event.xclient.display;
- m.window = event.xclient.data.l[0];
- m.message_type = xdnd_finished;
- m.format = 32;
- m.data.l[0] = windows[window_id].x11_window;
- m.data.l[1] = 0;
- m.data.l[2] = None;
- XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m);
- }
- }
- break;
- default:
- break;
- }
- }
- XFlush(x11_display);
- if (do_mouse_warp) {
- XWarpPointer(x11_display, None, windows[MAIN_WINDOW_ID].x11_window,
- 0, 0, 0, 0, (int)windows[MAIN_WINDOW_ID].size.width / 2, (int)windows[MAIN_WINDOW_ID].size.height / 2);
-
- }
- #ifdef DBUS_ENABLED
- if (portal_desktop) {
- portal_desktop->process_file_dialog_callbacks();
- }
- #endif
- _THREAD_SAFE_UNLOCK_
- Input::get_singleton()->flush_buffered_events();
- }
- void DisplayServerX11::release_rendering_thread() {
- #if defined(GLES3_ENABLED)
- if (gl_manager) {
- gl_manager->release_current();
- }
- if (gl_manager_egl) {
- gl_manager_egl->release_current();
- }
- #endif
- }
- void DisplayServerX11::swap_buffers() {
- #if defined(GLES3_ENABLED)
- if (gl_manager) {
- gl_manager->swap_buffers();
- }
- if (gl_manager_egl) {
- gl_manager_egl->swap_buffers();
- }
- #endif
- }
- void DisplayServerX11::_update_context(WindowData &wd) {
- XClassHint *classHint = XAllocClassHint();
- if (classHint) {
- CharString name_str;
- switch (context) {
- case CONTEXT_EDITOR:
- name_str = "Godot_Editor";
- break;
- case CONTEXT_PROJECTMAN:
- name_str = "Godot_ProjectList";
- break;
- case CONTEXT_ENGINE:
- name_str = "Godot_Engine";
- break;
- }
- CharString class_str;
- if (context == CONTEXT_ENGINE) {
- String config_name = GLOBAL_GET("application/config/name");
- if (config_name.length() == 0) {
- class_str = "Godot_Engine";
- } else {
- class_str = config_name.utf8();
- }
- } else {
- class_str = "Godot";
- }
- classHint->res_class = class_str.ptrw();
- classHint->res_name = name_str.ptrw();
- XSetClassHint(x11_display, wd.x11_window, classHint);
- XFree(classHint);
- }
- }
- void DisplayServerX11::set_context(Context p_context) {
- _THREAD_SAFE_METHOD_
- context = p_context;
- for (KeyValue<WindowID, WindowData> &E : windows) {
- _update_context(E.value);
- }
- }
- bool DisplayServerX11::is_window_transparency_available() const {
- CharString net_wm_cm_name = vformat("_NET_WM_CM_S%d", XDefaultScreen(x11_display)).ascii();
- Atom net_wm_cm = XInternAtom(x11_display, net_wm_cm_name.get_data(), False);
- if (net_wm_cm == None) {
- return false;
- }
- if (XGetSelectionOwner(x11_display, net_wm_cm) == None) {
- return false;
- }
- #if defined(RD_ENABLED)
- if (rendering_device && !rendering_device->is_composite_alpha_supported()) {
- return false;
- }
- #endif
- return OS::get_singleton()->is_layered_allowed();
- }
- void DisplayServerX11::set_native_icon(const String &p_filename) {
- WARN_PRINT("Native icon not supported by this display server.");
- }
- bool g_set_icon_error = false;
- int set_icon_errorhandler(Display *dpy, XErrorEvent *ev) {
- g_set_icon_error = true;
- return 0;
- }
- void DisplayServerX11::set_icon(const Ref<Image> &p_icon) {
- _THREAD_SAFE_METHOD_
- WindowData &wd = windows[MAIN_WINDOW_ID];
- int (*oldHandler)(Display *, XErrorEvent *) = XSetErrorHandler(&set_icon_errorhandler);
- Atom net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False);
- if (p_icon.is_valid()) {
- ERR_FAIL_COND(p_icon->get_width() <= 0 || p_icon->get_height() <= 0);
- Ref<Image> img = p_icon->duplicate();
- img->convert(Image::FORMAT_RGBA8);
- while (true) {
- int w = img->get_width();
- int h = img->get_height();
- if (g_set_icon_error) {
- g_set_icon_error = false;
- WARN_PRINT(vformat("Icon too large (%dx%d), attempting to downscale icon.", w, h));
- int new_width, new_height;
- if (w > h) {
- new_width = w / 2;
- new_height = h * new_width / w;
- } else {
- new_height = h / 2;
- new_width = w * new_height / h;
- }
- w = new_width;
- h = new_height;
- if (!w || !h) {
- WARN_PRINT("Unable to set icon.");
- break;
- }
- img->resize(w, h, Image::INTERPOLATE_CUBIC);
- }
-
- Vector<long> pd;
- pd.resize(2 + w * h);
- pd.write[0] = w;
- pd.write[1] = h;
- const uint8_t *r = img->get_data().ptr();
- long *wr = &pd.write[2];
- uint8_t const *pr = r;
- for (int i = 0; i < w * h; i++) {
- long v = 0;
-
- v |= pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2];
- *wr++ = v;
- pr += 4;
- }
- if (net_wm_icon != None) {
- XChangeProperty(x11_display, wd.x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pd.ptr(), pd.size());
- }
- if (!g_set_icon_error) {
- break;
- }
- }
- } else {
- XDeleteProperty(x11_display, wd.x11_window, net_wm_icon);
- }
- XFlush(x11_display);
- XSetErrorHandler(oldHandler);
- }
- void DisplayServerX11::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) {
- _THREAD_SAFE_METHOD_
- #if defined(RD_ENABLED)
- if (rendering_context) {
- rendering_context->window_set_vsync_mode(p_window, p_vsync_mode);
- }
- #endif
- #if defined(GLES3_ENABLED)
- if (gl_manager) {
- gl_manager->set_use_vsync(p_vsync_mode != DisplayServer::VSYNC_DISABLED);
- }
- if (gl_manager_egl) {
- gl_manager_egl->set_use_vsync(p_vsync_mode != DisplayServer::VSYNC_DISABLED);
- }
- #endif
- }
- DisplayServer::VSyncMode DisplayServerX11::window_get_vsync_mode(WindowID p_window) const {
- _THREAD_SAFE_METHOD_
- #if defined(RD_ENABLED)
- if (rendering_context) {
- return rendering_context->window_get_vsync_mode(p_window);
- }
- #endif
- #if defined(GLES3_ENABLED)
- if (gl_manager) {
- return gl_manager->is_using_vsync() ? DisplayServer::VSYNC_ENABLED : DisplayServer::VSYNC_DISABLED;
- }
- if (gl_manager_egl) {
- return gl_manager_egl->is_using_vsync() ? DisplayServer::VSYNC_ENABLED : DisplayServer::VSYNC_DISABLED;
- }
- #endif
- return DisplayServer::VSYNC_ENABLED;
- }
- Vector<String> DisplayServerX11::get_rendering_drivers_func() {
- Vector<String> drivers;
- #ifdef VULKAN_ENABLED
- drivers.push_back("vulkan");
- #endif
- #ifdef GLES3_ENABLED
- drivers.push_back("opengl3");
- drivers.push_back("opengl3_es");
- #endif
- return drivers;
- }
- DisplayServer *DisplayServerX11::create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, int p_screen, Context p_context, Error &r_error) {
- DisplayServer *ds = memnew(DisplayServerX11(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_position, p_resolution, p_screen, p_context, r_error));
- return ds;
- }
- DisplayServerX11::WindowID DisplayServerX11::_create_window(WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Rect2i &p_rect) {
-
- XVisualInfo visualInfo;
- bool vi_selected = false;
- #ifdef GLES3_ENABLED
- if (gl_manager) {
- Error err;
- visualInfo = gl_manager->get_vi(x11_display, err);
- ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't acquire visual info from display.");
- vi_selected = true;
- }
- if (gl_manager_egl) {
- XVisualInfo visual_info_template;
- int visual_id = gl_manager_egl->display_get_native_visual_id(x11_display);
- ERR_FAIL_COND_V_MSG(visual_id < 0, INVALID_WINDOW_ID, "Unable to get a visual id.");
- visual_info_template.visualid = (VisualID)visual_id;
- int number_of_visuals = 0;
- XVisualInfo *vi_list = XGetVisualInfo(x11_display, VisualIDMask, &visual_info_template, &number_of_visuals);
- ERR_FAIL_COND_V(number_of_visuals <= 0, INVALID_WINDOW_ID);
- visualInfo = vi_list[0];
- XFree(vi_list);
- }
- #endif
- if (!vi_selected) {
- long visualMask = VisualScreenMask;
- int numberOfVisuals;
- XVisualInfo vInfoTemplate = {};
- vInfoTemplate.screen = DefaultScreen(x11_display);
- XVisualInfo *vi_list = XGetVisualInfo(x11_display, visualMask, &vInfoTemplate, &numberOfVisuals);
- ERR_FAIL_NULL_V(vi_list, INVALID_WINDOW_ID);
- visualInfo = vi_list[0];
- if (OS::get_singleton()->is_layered_allowed()) {
- for (int i = 0; i < numberOfVisuals; i++) {
- XRenderPictFormat *pict_format = XRenderFindVisualFormat(x11_display, vi_list[i].visual);
- if (!pict_format) {
- continue;
- }
- visualInfo = vi_list[i];
- if (pict_format->direct.alphaMask > 0) {
- break;
- }
- }
- }
- XFree(vi_list);
- }
- Colormap colormap = XCreateColormap(x11_display, RootWindow(x11_display, visualInfo.screen), visualInfo.visual, AllocNone);
- XSetWindowAttributes windowAttributes = {};
- windowAttributes.colormap = colormap;
- windowAttributes.background_pixel = 0xFFFFFFFF;
- windowAttributes.border_pixel = 0;
- windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
- unsigned long valuemask = CWBorderPixel | CWColormap | CWEventMask;
- if (OS::get_singleton()->is_layered_allowed()) {
- windowAttributes.background_pixmap = None;
- windowAttributes.background_pixel = 0;
- windowAttributes.border_pixmap = None;
- valuemask |= CWBackPixel;
- }
- WindowID id = window_id_counter++;
- WindowData &wd = windows[id];
- if (p_flags & WINDOW_FLAG_NO_FOCUS_BIT) {
- wd.no_focus = true;
- }
- if (p_flags & WINDOW_FLAG_POPUP_BIT) {
- wd.is_popup = true;
- }
-
-
-
-
-
- if (wd.no_focus) {
- windowAttributes.override_redirect = True;
- windowAttributes.save_under = True;
- valuemask |= CWOverrideRedirect | CWSaveUnder;
- }
- int rq_screen = get_screen_from_rect(p_rect);
- if (rq_screen < 0) {
- rq_screen = get_primary_screen();
- }
- Rect2i win_rect = p_rect;
- if (p_mode == WINDOW_MODE_FULLSCREEN || p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
- Rect2i screen_rect = Rect2i(screen_get_position(rq_screen), screen_get_size(rq_screen));
- win_rect = screen_rect;
- } else {
- Rect2i srect = screen_get_usable_rect(rq_screen);
- Point2i wpos = p_rect.position;
- wpos = wpos.clamp(srect.position, srect.position + srect.size - p_rect.size / 3);
- win_rect.position = wpos;
- }
-
-
- wd.position = win_rect.position;
- wd.size = win_rect.size;
- {
- wd.x11_window = XCreateWindow(x11_display, RootWindow(x11_display, visualInfo.screen), win_rect.position.x, win_rect.position.y, win_rect.size.width > 0 ? win_rect.size.width : 1, win_rect.size.height > 0 ? win_rect.size.height : 1, 0, visualInfo.depth, InputOutput, visualInfo.visual, valuemask, &windowAttributes);
- wd.parent = RootWindow(x11_display, visualInfo.screen);
- XSetWindowAttributes window_attributes_ime = {};
- window_attributes_ime.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
- wd.x11_xim_window = XCreateWindow(x11_display, wd.x11_window, 0, 0, 1, 1, 0, CopyFromParent, InputOnly, CopyFromParent, CWEventMask, &window_attributes_ime);
- #ifdef XKB_ENABLED
- if (dead_tbl && xkb_loaded_v05p) {
- wd.xkb_state = xkb_compose_state_new(dead_tbl, XKB_COMPOSE_STATE_NO_FLAGS);
- }
- #endif
-
-
- if (!wd.no_focus && !wd.is_popup) {
- XSelectInput(x11_display, wd.x11_window, StructureNotifyMask);
- }
-
-
- {
- const long pid = OS::get_singleton()->get_process_id();
- Atom net_wm_pid = XInternAtom(x11_display, "_NET_WM_PID", False);
- if (net_wm_pid != None) {
- XChangeProperty(x11_display, wd.x11_window, net_wm_pid, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1);
- }
- }
- long im_event_mask = 0;
- {
- XIEventMask all_event_mask;
- XSetWindowAttributes new_attr;
- new_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask |
- ButtonReleaseMask | EnterWindowMask |
- LeaveWindowMask | PointerMotionMask |
- Button1MotionMask |
- Button2MotionMask | Button3MotionMask |
- Button4MotionMask | Button5MotionMask |
- ButtonMotionMask | KeymapStateMask |
- ExposureMask | VisibilityChangeMask |
- StructureNotifyMask |
- SubstructureNotifyMask | SubstructureRedirectMask |
- FocusChangeMask | PropertyChangeMask |
- ColormapChangeMask | OwnerGrabButtonMask |
- im_event_mask;
- XChangeWindowAttributes(x11_display, wd.x11_window, CWEventMask, &new_attr);
- static unsigned char all_mask_data[XIMaskLen(XI_LASTEVENT)] = {};
- all_event_mask.deviceid = XIAllDevices;
- all_event_mask.mask_len = sizeof(all_mask_data);
- all_event_mask.mask = all_mask_data;
- XISetMask(all_event_mask.mask, XI_HierarchyChanged);
- #ifdef TOUCH_ENABLED
- if (xi.touch_devices.size()) {
- XISetMask(all_event_mask.mask, XI_TouchBegin);
- XISetMask(all_event_mask.mask, XI_TouchUpdate);
- XISetMask(all_event_mask.mask, XI_TouchEnd);
- XISetMask(all_event_mask.mask, XI_TouchOwnership);
- }
- #endif
- XISelectEvents(x11_display, wd.x11_window, &all_event_mask, 1);
- }
-
- XStoreName(x11_display, wd.x11_window, "Godot");
- XSetWMProtocols(x11_display, wd.x11_window, &wm_delete, 1);
- if (xdnd_aware != None) {
- XChangeProperty(x11_display, wd.x11_window, xdnd_aware, XA_ATOM, 32, PropModeReplace, (unsigned char *)&xdnd_version, 1);
- }
- if (xim && xim_style) {
-
-
- MutexLock mutex_lock(events_mutex);
-
- if ((xim_style & XIMPreeditPosition) != 0) {
- xim_style &= ~XIMPreeditPosition;
- xim_style |= XIMPreeditCallbacks;
- }
- if ((xim_style & XIMPreeditCallbacks) != 0) {
- ::XIMCallback preedit_start_callback;
- preedit_start_callback.client_data = (::XPointer)(this);
- preedit_start_callback.callback = (::XIMProc)(void *)(_xim_preedit_start_callback);
- ::XIMCallback preedit_done_callback;
- preedit_done_callback.client_data = (::XPointer)(this);
- preedit_done_callback.callback = (::XIMProc)(_xim_preedit_done_callback);
- ::XIMCallback preedit_draw_callback;
- preedit_draw_callback.client_data = (::XPointer)(this);
- preedit_draw_callback.callback = (::XIMProc)(_xim_preedit_draw_callback);
- ::XIMCallback preedit_caret_callback;
- preedit_caret_callback.client_data = (::XPointer)(this);
- preedit_caret_callback.callback = (::XIMProc)(_xim_preedit_caret_callback);
- ::XVaNestedList preedit_attributes = XVaCreateNestedList(0,
- XNPreeditStartCallback, &preedit_start_callback,
- XNPreeditDoneCallback, &preedit_done_callback,
- XNPreeditDrawCallback, &preedit_draw_callback,
- XNPreeditCaretCallback, &preedit_caret_callback,
- (char *)nullptr);
- wd.xic = XCreateIC(xim,
- XNInputStyle, xim_style,
- XNClientWindow, wd.x11_xim_window,
- XNFocusWindow, wd.x11_xim_window,
- XNPreeditAttributes, preedit_attributes,
- (char *)nullptr);
- XFree(preedit_attributes);
- } else {
- wd.xic = XCreateIC(xim,
- XNInputStyle, xim_style,
- XNClientWindow, wd.x11_xim_window,
- XNFocusWindow, wd.x11_xim_window,
- (char *)nullptr);
- }
- if (XGetICValues(wd.xic, XNFilterEvents, &im_event_mask, nullptr) != nullptr) {
- WARN_PRINT("XGetICValues couldn't obtain XNFilterEvents value");
- XDestroyIC(wd.xic);
- wd.xic = nullptr;
- }
- if (wd.xic) {
- XUnsetICFocus(wd.xic);
- } else {
- WARN_PRINT("XCreateIC couldn't create wd.xic");
- }
- } else {
- wd.xic = nullptr;
- WARN_PRINT("XCreateIC couldn't create wd.xic");
- }
- _update_context(wd);
- if (p_flags & WINDOW_FLAG_BORDERLESS_BIT) {
- Hints hints;
- Atom property;
- hints.flags = 2;
- hints.decorations = 0;
- property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
- if (property != None) {
- XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
- }
- }
- if (wd.is_popup || wd.no_focus) {
-
- Atom type_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE_UTILITY", False);
- Atom wt_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE", False);
- if (wt_atom != None && type_atom != None) {
- XChangeProperty(x11_display, wd.x11_window, wt_atom, XA_ATOM, 32, PropModeReplace, (unsigned char *)&type_atom, 1);
- }
- } else {
- Atom type_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE_NORMAL", False);
- Atom wt_atom = XInternAtom(x11_display, "_NET_WM_WINDOW_TYPE", False);
- if (wt_atom != None && type_atom != None) {
- XChangeProperty(x11_display, wd.x11_window, wt_atom, XA_ATOM, 32, PropModeReplace, (unsigned char *)&type_atom, 1);
- }
- }
- _update_size_hints(id);
- #if defined(RD_ENABLED)
- if (rendering_context) {
- union {
- #ifdef VULKAN_ENABLED
- RenderingContextDriverVulkanX11::WindowPlatformData vulkan;
- #endif
- } wpd;
- #ifdef VULKAN_ENABLED
- if (rendering_driver == "vulkan") {
- wpd.vulkan.window = wd.x11_window;
- wpd.vulkan.display = x11_display;
- }
- #endif
- Error err = rendering_context->window_create(id, &wpd);
- ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, vformat("Can't create a %s window", rendering_driver));
- rendering_context->window_set_size(id, win_rect.size.width, win_rect.size.height);
- rendering_context->window_set_vsync_mode(id, p_vsync_mode);
- }
- #endif
- #ifdef GLES3_ENABLED
- if (gl_manager) {
- Error err = gl_manager->window_create(id, wd.x11_window, x11_display, win_rect.size.width, win_rect.size.height);
- ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create an OpenGL window");
- }
- if (gl_manager_egl) {
- Error err = gl_manager_egl->window_create(id, x11_display, &wd.x11_window, win_rect.size.width, win_rect.size.height);
- ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Failed to create an OpenGLES window.");
- }
- window_set_vsync_mode(p_vsync_mode, id);
- #endif
-
- XFlush(x11_display);
- XSync(x11_display, False);
-
- }
- window_set_mode(p_mode, id);
-
- {
- XWindowAttributes xwa;
- XSync(x11_display, False);
- XGetWindowAttributes(x11_display, wd.x11_window, &xwa);
- wd.position.x = xwa.x;
- wd.position.y = xwa.y;
- wd.size.width = xwa.width;
- wd.size.height = xwa.height;
- }
-
- if (cursors[current_cursor] != None) {
- XDefineCursor(x11_display, wd.x11_window, cursors[current_cursor]);
- }
- return id;
- }
- static bool _is_xim_style_supported(const ::XIMStyle &p_style) {
- const ::XIMStyle supported_preedit = XIMPreeditCallbacks | XIMPreeditPosition | XIMPreeditNothing | XIMPreeditNone;
- const ::XIMStyle supported_status = XIMStatusNothing | XIMStatusNone;
-
- if ((p_style & supported_preedit) == 0) {
- return false;
- }
-
- if ((p_style & supported_status) == 0) {
- return false;
- }
- return true;
- }
- static ::XIMStyle _get_best_xim_style(const ::XIMStyle &p_style_a, const ::XIMStyle &p_style_b) {
- if (p_style_a == 0) {
- return p_style_b;
- }
- if (p_style_b == 0) {
- return p_style_a;
- }
- const ::XIMStyle preedit = XIMPreeditArea | XIMPreeditCallbacks | XIMPreeditPosition | XIMPreeditNothing | XIMPreeditNone;
- const ::XIMStyle status = XIMStatusArea | XIMStatusCallbacks | XIMStatusNothing | XIMStatusNone;
- ::XIMStyle a = p_style_a & preedit;
- ::XIMStyle b = p_style_b & preedit;
- if (a != b) {
-
- if ((a | b) & XIMPreeditCallbacks) {
- return a == XIMPreeditCallbacks ? p_style_a : p_style_b;
- } else if ((a | b) & XIMPreeditPosition) {
- return a == XIMPreeditPosition ? p_style_a : p_style_b;
- } else if ((a | b) & XIMPreeditArea) {
- return a == XIMPreeditArea ? p_style_a : p_style_b;
- } else if ((a | b) & XIMPreeditNothing) {
- return a == XIMPreeditNothing ? p_style_a : p_style_b;
- }
- } else {
-
- a = p_style_a & status;
- b = p_style_b & status;
- if ((a | b) & XIMStatusCallbacks) {
- return a == XIMStatusCallbacks ? p_style_a : p_style_b;
- } else if ((a | b) & XIMStatusArea) {
- return a == XIMStatusArea ? p_style_a : p_style_b;
- } else if ((a | b) & XIMStatusNothing) {
- return a == XIMStatusNothing ? p_style_a : p_style_b;
- }
- }
- return p_style_a;
- }
- DisplayServerX11::DisplayServerX11(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, int p_screen, Context p_context, Error &r_error) {
- KeyMappingX11::initialize();
- xwayland = OS::get_singleton()->get_environment("XDG_SESSION_TYPE").to_lower() == "wayland";
- native_menu = memnew(NativeMenu);
- context = p_context;
- #ifdef SOWRAP_ENABLED
- #ifdef DEBUG_ENABLED
- int dylibloader_verbose = 1;
- #else
- int dylibloader_verbose = 0;
- #endif
- if (initialize_xlib(dylibloader_verbose) != 0) {
- r_error = ERR_UNAVAILABLE;
- ERR_FAIL_MSG("Can't load Xlib dynamically.");
- }
- if (initialize_xcursor(dylibloader_verbose) != 0) {
- r_error = ERR_UNAVAILABLE;
- ERR_FAIL_MSG("Can't load XCursor dynamically.");
- }
- #ifdef XKB_ENABLED
- bool xkb_loaded = (initialize_xkbcommon(dylibloader_verbose) == 0);
- xkb_loaded_v05p = xkb_loaded;
- if (!xkb_context_new || !xkb_compose_table_new_from_locale || !xkb_compose_table_unref || !xkb_context_unref || !xkb_compose_state_feed || !xkb_compose_state_unref || !xkb_compose_state_new || !xkb_compose_state_get_status || !xkb_compose_state_get_utf8) {
- xkb_loaded_v05p = false;
- print_verbose("Detected XKBcommon library version older than 0.5, dead key composition and Unicode key labels disabled.");
- }
- xkb_loaded_v08p = xkb_loaded;
- if (!xkb_keysym_to_utf32 || !xkb_keysym_to_upper) {
- xkb_loaded_v08p = false;
- print_verbose("Detected XKBcommon library version older than 0.8, Unicode key labels disabled.");
- }
- #endif
- if (initialize_xext(dylibloader_verbose) != 0) {
- r_error = ERR_UNAVAILABLE;
- ERR_FAIL_MSG("Can't load Xext dynamically.");
- }
- if (initialize_xinerama(dylibloader_verbose) != 0) {
- xinerama_ext_ok = false;
- }
- if (initialize_xrandr(dylibloader_verbose) != 0) {
- xrandr_ext_ok = false;
- }
- if (initialize_xrender(dylibloader_verbose) != 0) {
- r_error = ERR_UNAVAILABLE;
- ERR_FAIL_MSG("Can't load Xrender dynamically.");
- }
- if (initialize_xinput2(dylibloader_verbose) != 0) {
- r_error = ERR_UNAVAILABLE;
- ERR_FAIL_MSG("Can't load Xinput2 dynamically.");
- }
- #else
- #ifdef XKB_ENABLED
- bool xkb_loaded = true;
- xkb_loaded_v05p = true;
- xkb_loaded_v08p = true;
- #endif
- #endif
- #ifdef XKB_ENABLED
- if (xkb_loaded) {
- xkb_ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
- if (xkb_ctx) {
- const char *locale = getenv("LC_ALL");
- if (!locale || !*locale) {
- locale = getenv("LC_CTYPE");
- }
- if (!locale || !*locale) {
- locale = getenv("LANG");
- }
- if (!locale || !*locale) {
- locale = "C";
- }
- dead_tbl = xkb_compose_table_new_from_locale(xkb_ctx, locale, XKB_COMPOSE_COMPILE_NO_FLAGS);
- }
- }
- #endif
- Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events);
- r_error = OK;
- #ifdef SOWRAP_ENABLED
- {
- if (!XcursorImageCreate || !XcursorImageLoadCursor || !XcursorImageDestroy || !XcursorGetDefaultSize || !XcursorGetTheme || !XcursorLibraryLoadImage) {
-
- ERR_PRINT("Unsupported Xcursor library version.");
- r_error = ERR_UNAVAILABLE;
- return;
- }
- }
- #endif
- for (int i = 0; i < CURSOR_MAX; i++) {
- cursors[i] = None;
- cursor_img[i] = nullptr;
- }
- XInitThreads();
-
- x11_display = XOpenDisplay(nullptr);
- if (!x11_display) {
- ERR_PRINT("X11 Display is not available");
- r_error = ERR_UNAVAILABLE;
- return;
- }
- if (xshaped_ext_ok) {
- int version_major = 0;
- int version_minor = 0;
- int rc = XShapeQueryVersion(x11_display, &version_major, &version_minor);
- print_verbose(vformat("Xshape %d.%d detected.", version_major, version_minor));
- if (rc != 1 || version_major < 1) {
- xshaped_ext_ok = false;
- print_verbose("Unsupported Xshape library version.");
- }
- }
- if (xinerama_ext_ok) {
- int version_major = 0;
- int version_minor = 0;
- int rc = XineramaQueryVersion(x11_display, &version_major, &version_minor);
- print_verbose(vformat("Xinerama %d.%d detected.", version_major, version_minor));
- if (rc != 1 || version_major < 1) {
- xinerama_ext_ok = false;
- print_verbose("Unsupported Xinerama library version.");
- }
- }
- if (xrandr_ext_ok) {
- int version_major = 0;
- int version_minor = 0;
- int rc = XRRQueryVersion(x11_display, &version_major, &version_minor);
- print_verbose(vformat("Xrandr %d.%d detected.", version_major, version_minor));
- if (rc != 1 || (version_major == 1 && version_minor < 3) || (version_major < 1)) {
- xrandr_ext_ok = false;
- print_verbose("Unsupported Xrandr library version.");
- }
- }
- {
- int version_major = 0;
- int version_minor = 0;
- int rc = XRenderQueryVersion(x11_display, &version_major, &version_minor);
- print_verbose(vformat("Xrender %d.%d detected.", version_major, version_minor));
- if (rc != 1 || (version_major == 0 && version_minor < 11)) {
- ERR_PRINT("Unsupported Xrender library version.");
- r_error = ERR_UNAVAILABLE;
- XCloseDisplay(x11_display);
- return;
- }
- }
- {
- int version_major = 2;
- int version_minor = 2;
- int rc = XIQueryVersion(x11_display, &version_major, &version_minor);
- print_verbose(vformat("Xinput %d.%d detected.", version_major, version_minor));
- if (rc != Success || (version_major < 2)) {
- ERR_PRINT("Unsupported Xinput2 library version.");
- r_error = ERR_UNAVAILABLE;
- XCloseDisplay(x11_display);
- return;
- }
- }
- char *modifiers = nullptr;
- Bool xkb_dar = False;
- XAutoRepeatOn(x11_display);
- xkb_dar = XkbSetDetectableAutoRepeat(x11_display, True, nullptr);
-
- if (xkb_dar == True) {
- #ifdef X_HAVE_UTF8_STRING
-
-
- modifiers = XSetLocaleModifiers("");
- #endif
- }
- if (modifiers == nullptr) {
- if (OS::get_singleton()->is_stdout_verbose()) {
- WARN_PRINT("IME is disabled");
- }
- XSetLocaleModifiers("@im=none");
- WARN_PRINT("Error setting locale modifiers");
- }
- const char *err;
- int xrandr_major = 0;
- int xrandr_minor = 0;
- int event_base, error_base;
- xrandr_ext_ok = XRRQueryExtension(x11_display, &event_base, &error_base);
- xrandr_handle = dlopen("libXrandr.so.2", RTLD_LAZY);
- if (!xrandr_handle) {
- err = dlerror();
-
-
- xrandr_handle = dlopen("libXrandr.so.3", RTLD_LAZY);
- if (!xrandr_handle) {
- fprintf(stderr, "could not load libXrandr.so.2, Error: %s\n", err);
- }
- }
- if (xrandr_handle) {
- XRRQueryVersion(x11_display, &xrandr_major, &xrandr_minor);
- if (((xrandr_major << 8) | xrandr_minor) >= 0x0105) {
- xrr_get_monitors = (xrr_get_monitors_t)dlsym(xrandr_handle, "XRRGetMonitors");
- if (!xrr_get_monitors) {
- err = dlerror();
- fprintf(stderr, "could not find symbol XRRGetMonitors\nError: %s\n", err);
- } else {
- xrr_free_monitors = (xrr_free_monitors_t)dlsym(xrandr_handle, "XRRFreeMonitors");
- if (!xrr_free_monitors) {
- err = dlerror();
- fprintf(stderr, "could not find XRRFreeMonitors\nError: %s\n", err);
- xrr_get_monitors = nullptr;
- }
- }
- }
- }
- if (!_refresh_device_info()) {
- OS::get_singleton()->alert("Your system does not support XInput 2.\n"
- "Please upgrade your distribution.",
- "Unable to initialize XInput");
- r_error = ERR_UNAVAILABLE;
- return;
- }
- xim = XOpenIM(x11_display, nullptr, nullptr, nullptr);
- if (xim == nullptr) {
- WARN_PRINT("XOpenIM failed");
- xim_style = 0L;
- } else {
- ::XIMCallback im_destroy_callback;
- im_destroy_callback.client_data = (::XPointer)(this);
- im_destroy_callback.callback = (::XIMProc)(_xim_destroy_callback);
- if (XSetIMValues(xim, XNDestroyCallback, &im_destroy_callback,
- nullptr) != nullptr) {
- WARN_PRINT("Error setting XIM destroy callback");
- }
- ::XIMStyles *xim_styles = nullptr;
- xim_style = 0L;
- char *imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, nullptr);
- if (imvalret != nullptr || xim_styles == nullptr) {
- fprintf(stderr, "Input method doesn't support any styles\n");
- }
- if (xim_styles) {
- xim_style = 0L;
- for (int i = 0; i < xim_styles->count_styles; i++) {
- const ::XIMStyle &style = xim_styles->supported_styles[i];
- if (!_is_xim_style_supported(style)) {
- continue;
- }
- xim_style = _get_best_xim_style(xim_style, style);
- }
- XFree(xim_styles);
- }
- XFree(imvalret);
- }
-
- wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true);
-
- xdnd_aware = XInternAtom(x11_display, "XdndAware", False);
- xdnd_enter = XInternAtom(x11_display, "XdndEnter", False);
- xdnd_position = XInternAtom(x11_display, "XdndPosition", False);
- xdnd_status = XInternAtom(x11_display, "XdndStatus", False);
- xdnd_action_copy = XInternAtom(x11_display, "XdndActionCopy", False);
- xdnd_drop = XInternAtom(x11_display, "XdndDrop", False);
- xdnd_finished = XInternAtom(x11_display, "XdndFinished", False);
- xdnd_selection = XInternAtom(x11_display, "XdndSelection", False);
- #ifdef SPEECHD_ENABLED
-
- bool tts_enabled = GLOBAL_GET("audio/general/text_to_speech");
- if (tts_enabled) {
- tts = memnew(TTS_Linux);
- }
- #endif
-
-
- rendering_driver = p_rendering_driver;
- bool driver_found = false;
- String executable_name = OS::get_singleton()->get_executable_path().get_file();
-
- #if defined(RD_ENABLED)
- #if defined(VULKAN_ENABLED)
- if (rendering_driver == "vulkan") {
- rendering_context = memnew(RenderingContextDriverVulkanX11);
- }
- #endif
- if (rendering_context) {
- if (rendering_context->initialize() != OK) {
- memdelete(rendering_context);
- rendering_context = nullptr;
- #if defined(GLES3_ENABLED)
- bool fallback_to_opengl3 = GLOBAL_GET("rendering/rendering_device/fallback_to_opengl3");
- if (fallback_to_opengl3 && rendering_driver != "opengl3") {
- WARN_PRINT("Your video card drivers seem not to support the required Vulkan version, switching to OpenGL 3.");
- rendering_driver = "opengl3";
- OS::get_singleton()->set_current_rendering_method("gl_compatibility");
- OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
- } else
- #endif
- {
- r_error = ERR_CANT_CREATE;
- if (p_rendering_driver == "vulkan") {
- OS::get_singleton()->alert(
- vformat("Your video card drivers seem not to support the required Vulkan version.\n\n"
- "If possible, consider updating your video card drivers or using the OpenGL 3 driver.\n\n"
- "You can enable the OpenGL 3 driver by starting the engine from the\n"
- "command line with the command:\n\n \"%s\" --rendering-driver opengl3\n\n"
- "If you recently updated your video card drivers, try rebooting.",
- executable_name),
- "Unable to initialize Vulkan video driver");
- }
- ERR_FAIL_MSG(vformat("Could not initialize %s", rendering_driver));
- }
- }
- driver_found = true;
- }
- #endif
- #if defined(GLES3_ENABLED)
- if (rendering_driver == "opengl3" || rendering_driver == "opengl3_es") {
- if (getenv("DRI_PRIME") == nullptr) {
- int use_prime = -1;
- if (getenv("PRIMUS_DISPLAY") ||
- getenv("PRIMUS_libGLd") ||
- getenv("PRIMUS_libGLa") ||
- getenv("PRIMUS_libGL") ||
- getenv("PRIMUS_LOAD_GLOBAL") ||
- getenv("BUMBLEBEE_SOCKET")) {
- print_verbose("Optirun/primusrun detected. Skipping GPU detection");
- use_prime = 0;
- }
-
-
-
- if (use_prime == -1 && getenv("LD_LIBRARY_PATH") && !getenv("STEAM_RUNTIME_LIBRARY_PATH")) {
- String ld_library_path(getenv("LD_LIBRARY_PATH"));
- Vector<String> libraries = ld_library_path.split(":");
- for (int i = 0; i < libraries.size(); ++i) {
- if (FileAccess::exists(libraries[i] + "/libGL.so.1") ||
- FileAccess::exists(libraries[i] + "/libGL.so")) {
- print_verbose("Custom libGL override detected. Skipping GPU detection");
- use_prime = 0;
- }
- }
- }
- if (use_prime == -1) {
- print_verbose("Detecting GPUs, set DRI_PRIME in the environment to override GPU detection logic.");
- use_prime = detect_prime();
- }
- if (use_prime) {
- print_line("Found discrete GPU, setting DRI_PRIME=1 to use it.");
- print_line("Note: Set DRI_PRIME=0 in the environment to disable Godot from using the discrete GPU.");
- setenv("DRI_PRIME", "1", 1);
- }
- }
- }
- if (rendering_driver == "opengl3") {
- gl_manager = memnew(GLManager_X11(p_resolution, GLManager_X11::GLES_3_0_COMPATIBLE));
- if (gl_manager->initialize(x11_display) != OK || gl_manager->open_display(x11_display) != OK) {
- memdelete(gl_manager);
- gl_manager = nullptr;
- bool fallback = GLOBAL_GET("rendering/gl_compatibility/fallback_to_gles");
- if (fallback) {
- WARN_PRINT("Your video card drivers seem not to support the required OpenGL version, switching to OpenGLES.");
- rendering_driver = "opengl3_es";
- OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
- } else {
- r_error = ERR_UNAVAILABLE;
- OS::get_singleton()->alert(
- vformat("Your video card drivers seem not to support the required OpenGL 3.3 version.\n\n"
- "If possible, consider updating your video card drivers or using the Vulkan driver.\n\n"
- "You can enable the Vulkan driver by starting the engine from the\n"
- "command line with the command:\n\n \"%s\" --rendering-driver vulkan\n\n"
- "If you recently updated your video card drivers, try rebooting.",
- executable_name),
- "Unable to initialize OpenGL video driver");
- ERR_FAIL_MSG("Could not initialize OpenGL.");
- }
- } else {
- driver_found = true;
- RasterizerGLES3::make_current(true);
- }
- }
- if (rendering_driver == "opengl3_es") {
- gl_manager_egl = memnew(GLManagerEGL_X11);
- if (gl_manager_egl->initialize() != OK || gl_manager_egl->open_display(x11_display) != OK) {
- memdelete(gl_manager_egl);
- gl_manager_egl = nullptr;
- r_error = ERR_UNAVAILABLE;
- OS::get_singleton()->alert(
- "Your video card drivers seem not to support the required OpenGL ES 3.0 version.\n\n"
- "If possible, consider updating your video card drivers.\n\n"
- "If you recently updated your video card drivers, try rebooting.",
- "Unable to initialize OpenGL ES video driver");
- ERR_FAIL_MSG("Could not initialize OpenGL ES.");
- }
- driver_found = true;
- RasterizerGLES3::make_current(false);
- }
- #endif
- if (!driver_found) {
- r_error = ERR_UNAVAILABLE;
- ERR_FAIL_MSG("Video driver not found.");
- }
- Point2i window_position;
- if (p_position != nullptr) {
- window_position = *p_position;
- } else {
- if (p_screen == SCREEN_OF_MAIN_WINDOW) {
- p_screen = SCREEN_PRIMARY;
- }
- Rect2i scr_rect = screen_get_usable_rect(p_screen);
- window_position = scr_rect.position + (scr_rect.size - p_resolution) / 2;
- }
- WindowID main_window = _create_window(p_mode, p_vsync_mode, p_flags, Rect2i(window_position, p_resolution));
- if (main_window == INVALID_WINDOW_ID) {
- r_error = ERR_CANT_CREATE;
- return;
- }
- for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
- if (p_flags & (1 << i)) {
- window_set_flag(WindowFlags(i), true, main_window);
- }
- }
- show_window(main_window);
- #if defined(RD_ENABLED)
- if (rendering_context) {
- rendering_device = memnew(RenderingDevice);
- if (rendering_device->initialize(rendering_context, MAIN_WINDOW_ID) != OK) {
- memdelete(rendering_device);
- rendering_device = nullptr;
- memdelete(rendering_context);
- rendering_context = nullptr;
- r_error = ERR_UNAVAILABLE;
- return;
- }
- rendering_device->screen_create(MAIN_WINDOW_ID);
- RendererCompositorRD::make_current();
- }
- #endif
- {
-
- XIEventMask all_master_event_mask;
- static unsigned char all_master_mask_data[XIMaskLen(XI_LASTEVENT)] = {};
- all_master_event_mask.deviceid = XIAllMasterDevices;
- all_master_event_mask.mask_len = sizeof(all_master_mask_data);
- all_master_event_mask.mask = all_master_mask_data;
- XISetMask(all_master_event_mask.mask, XI_DeviceChanged);
- XISetMask(all_master_event_mask.mask, XI_RawMotion);
- XISelectEvents(x11_display, DefaultRootWindow(x11_display), &all_master_event_mask, 1);
- }
- cursor_size = XcursorGetDefaultSize(x11_display);
- cursor_theme = XcursorGetTheme(x11_display);
- if (!cursor_theme) {
- print_verbose("XcursorGetTheme could not get cursor theme");
- cursor_theme = "default";
- }
- for (int i = 0; i < CURSOR_MAX; i++) {
- static const char *cursor_file[] = {
- "left_ptr",
- "xterm",
- "hand2",
- "cross",
- "watch",
- "left_ptr_watch",
- "fleur",
- "dnd-move",
- "crossed_circle",
- "v_double_arrow",
- "h_double_arrow",
- "size_bdiag",
- "size_fdiag",
- "move",
- "row_resize",
- "col_resize",
- "question_arrow"
- };
- cursor_img[i] = XcursorLibraryLoadImage(cursor_file[i], cursor_theme, cursor_size);
- if (!cursor_img[i]) {
- const char *fallback = nullptr;
- switch (i) {
- case CURSOR_POINTING_HAND:
- fallback = "pointer";
- break;
- case CURSOR_CROSS:
- fallback = "crosshair";
- break;
- case CURSOR_WAIT:
- fallback = "wait";
- break;
- case CURSOR_BUSY:
- fallback = "progress";
- break;
- case CURSOR_DRAG:
- fallback = "grabbing";
- break;
- case CURSOR_CAN_DROP:
- fallback = "hand1";
- break;
- case CURSOR_FORBIDDEN:
- fallback = "forbidden";
- break;
- case CURSOR_VSIZE:
- fallback = "ns-resize";
- break;
- case CURSOR_HSIZE:
- fallback = "ew-resize";
- break;
- case CURSOR_BDIAGSIZE:
- fallback = "fd_double_arrow";
- break;
- case CURSOR_FDIAGSIZE:
- fallback = "bd_double_arrow";
- break;
- case CURSOR_MOVE:
- cursor_img[i] = cursor_img[CURSOR_DRAG];
- break;
- case CURSOR_VSPLIT:
- fallback = "sb_v_double_arrow";
- break;
- case CURSOR_HSPLIT:
- fallback = "sb_h_double_arrow";
- break;
- case CURSOR_HELP:
- fallback = "help";
- break;
- }
- if (fallback != nullptr) {
- cursor_img[i] = XcursorLibraryLoadImage(fallback, cursor_theme, cursor_size);
- }
- }
- if (cursor_img[i]) {
- cursors[i] = XcursorImageLoadCursor(x11_display, cursor_img[i]);
- } else {
- print_verbose("Failed loading custom cursor: " + String(cursor_file[i]));
- }
- }
- {
-
-
- Pixmap cursormask = XCreatePixmap(x11_display,
- RootWindow(x11_display, DefaultScreen(x11_display)), 1, 1, 1);
-
- XGCValues xgc;
- xgc.function = GXclear;
- GC gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc);
- XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1);
-
- XColor col = {};
- Cursor cursor = XCreatePixmapCursor(x11_display,
- cursormask,
- cursormask,
- &col, &col, 0, 0);
- XFreePixmap(x11_display, cursormask);
- XFreeGC(x11_display, gc);
- if (cursor == None) {
- ERR_PRINT("FAILED CREATING CURSOR");
- }
- null_cursor = cursor;
- }
- cursor_set_shape(CURSOR_BUSY);
-
-
-
- XEvent config_event;
- while (XCheckTypedEvent(x11_display, ConfigureNotify, &config_event)) {
- _window_changed(&config_event);
- }
- events_thread.start(_poll_events_thread, this);
- _update_real_mouse_position(windows[MAIN_WINDOW_ID]);
- #ifdef DBUS_ENABLED
- screensaver = memnew(FreeDesktopScreenSaver);
- screen_set_keep_on(GLOBAL_GET("display/window/energy_saving/keep_screen_on"));
- portal_desktop = memnew(FreeDesktopPortalDesktop);
- #endif
- XSetErrorHandler(&default_window_error_handler);
- r_error = OK;
- }
- DisplayServerX11::~DisplayServerX11() {
-
- Window x11_main_window = windows[MAIN_WINDOW_ID].x11_window;
- _clipboard_transfer_ownership(XA_PRIMARY, x11_main_window);
- _clipboard_transfer_ownership(XInternAtom(x11_display, "CLIPBOARD", 0), x11_main_window);
- events_thread_done.set();
- events_thread.wait_to_finish();
- if (native_menu) {
- memdelete(native_menu);
- native_menu = nullptr;
- }
-
- for (KeyValue<WindowID, WindowData> &E : windows) {
- #if defined(RD_ENABLED)
- if (rendering_device) {
- rendering_device->screen_free(E.key);
- }
- if (rendering_context) {
- rendering_context->window_destroy(E.key);
- }
- #endif
- #ifdef GLES3_ENABLED
- if (gl_manager) {
- gl_manager->window_destroy(E.key);
- }
- if (gl_manager_egl) {
- gl_manager_egl->window_destroy(E.key);
- }
- #endif
- WindowData &wd = E.value;
- if (wd.xic) {
- XDestroyIC(wd.xic);
- wd.xic = nullptr;
- }
- XDestroyWindow(x11_display, wd.x11_xim_window);
- #ifdef XKB_ENABLED
- if (xkb_loaded_v05p) {
- if (wd.xkb_state) {
- xkb_compose_state_unref(wd.xkb_state);
- wd.xkb_state = nullptr;
- }
- }
- #endif
- XUnmapWindow(x11_display, wd.x11_window);
- XDestroyWindow(x11_display, wd.x11_window);
- }
- #ifdef XKB_ENABLED
- if (xkb_loaded_v05p) {
- if (dead_tbl) {
- xkb_compose_table_unref(dead_tbl);
- }
- if (xkb_ctx) {
- xkb_context_unref(xkb_ctx);
- }
- }
- #endif
-
- #if defined(RD_ENABLED)
- if (rendering_device) {
- memdelete(rendering_device);
- rendering_device = nullptr;
- }
- if (rendering_context) {
- memdelete(rendering_context);
- rendering_context = nullptr;
- }
- #endif
- #ifdef GLES3_ENABLED
- if (gl_manager) {
- memdelete(gl_manager);
- gl_manager = nullptr;
- }
- if (gl_manager_egl) {
- memdelete(gl_manager_egl);
- gl_manager_egl = nullptr;
- }
- #endif
- if (xrandr_handle) {
- dlclose(xrandr_handle);
- }
- for (int i = 0; i < CURSOR_MAX; i++) {
- if (cursors[i] != None) {
- XFreeCursor(x11_display, cursors[i]);
- }
- if (cursor_img[i] != nullptr) {
- XcursorImageDestroy(cursor_img[i]);
- }
- }
- if (xim) {
- XCloseIM(xim);
- }
- XCloseDisplay(x11_display);
- if (xmbstring) {
- memfree(xmbstring);
- }
- #ifdef SPEECHD_ENABLED
- if (tts) {
- memdelete(tts);
- }
- #endif
- #ifdef DBUS_ENABLED
- memdelete(screensaver);
- memdelete(portal_desktop);
- #endif
- }
- void DisplayServerX11::register_x11_driver() {
- register_create_function("x11", create_func, get_rendering_drivers_func);
- }
- #endif
|